Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(inventory): redesign the traceability graph around lot states (#1327)
Sidc913d811d141
diff --git a/apps/erp/app/modules/inventory/lineage.server.ts b/apps/erp/app/modules/inventory/lineage.server.tsindex cc4ae39287..88ad6d3813 100644--- a/apps/erp/app/modules/inventory/lineage.server.ts+++ b/apps/erp/app/modules/inventory/lineage.server.ts@@ -1,4 +1,5 @@import type { Database } from "@carbon/database";+import { indexByMapped, pluckUnique } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type {Activity,@@ -75,29 +76,31 @@ async function expandActivitySiblings(.in("trackedActivityId", activityIds)]);+ // These rows are the AUTHORITATIVE edge quantities — how much actually flowed+ // through this activity. Always overwrite: the BFS seeds edges from the+ // traversal RPCs, whose `quantity` column is the neighbour ENTITY's current+ // quantity (`te."quantity"`), not the edge's. Left as-is, a lot that was later+ // drawn down paints its post-hoc quantity onto a historical edge (a 6-unit+ // split reading "4" after 2 were consumed).const siblingEntityIds = new Set<string>();for (const row of siblingInputs.data ?? []) {const key = `${row.trackedActivityId}:${row.trackedEntityId}`;- if (!inputs.has(key)) {- inputs.set(key, {- trackedActivityId: row.trackedActivityId,- trackedEntityId: row.trackedEntityId,- quantity: row.quantity- });- }+ inputs.set(key, {+ trackedActivityId: row.trackedActivityId,+ trackedEntityId: row.trackedEntityId,+ quantity: row.quantity+ });if (!entities.has(row.trackedEntityId)) {siblingEntityIds.add(row.trackedEntityId);}}for (const row of siblingOutputs.data ?? []) {const key = `${row.trackedActivityId}:${row.trackedEntityId}`;- if (!outputs.has(key)) {- outputs.set(key, {- trackedActivityId: row.trackedActivityId,- trackedEntityId: row.trackedEntityId,- quantity: row.quantity- });- }+ outputs.set(key, {+ trackedActivityId: row.trackedActivityId,+ trackedEntityId: row.trackedEntityId,+ quantity: row.quantity+ });if (!entities.has(row.trackedEntityId)) {siblingEntityIds.add(row.trackedEntityId);}@@ -461,6 +464,22 @@ export function toGraphData(payload: LineagePayload): GraphData {}))];+ // Historical split survivors are recorded as both input and output of their+ // own Split activity. Drop the output half of that self-loop so the graph+ // doesn't render the survivor as produced by its own split; the input edge+ // stays (it carries the drawn quantity).+ const splitActivityIds = new Set(+ payload.activities.filter((a) => a?.type === "Split").map((a) => a.id)+ );+ const inputPairs = new Set(+ pluckUnique(+ payload.inputs.filter((input) =>+ splitActivityIds.has(input.trackedActivityId)+ ),+ (input) => `${input.trackedActivityId}::${input.trackedEntityId}`+ )+ );+const links = [...payload.inputs.map((input) => ({source: input.trackedEntityId,@@ -468,13 +487,79 @@ export function toGraphData(payload: LineagePayload): GraphData {type: "input" as const,quantity: input.quantity})),- ...payload.outputs.map((output) => ({- source: output.trackedActivityId,- target: output.trackedEntityId,- type: "output" as const,- quantity: output.quantity- }))+ ...payload.outputs+ .filter(+ (output) =>+ !inputPairs.has(+ `${output.trackedActivityId}::${output.trackedEntityId}`+ )+ )+ .map((output) => ({+ source: output.trackedActivityId,+ target: output.trackedEntityId,+ type: "output" as const,+ quantity: output.quantity+ }))];return { nodes, links };}++/**+ * Resolve the storage-unit ids that movement activities carry in their+ * attributes ("From Shelf" / "To Shelf") into names, written back as+ * "From Storage Unit Name" / "To Storage Unit Name".+ *+ * The graph renders a lot as a chain of states; a movement produces two states+ * with the SAME quantity, so the bin is the only thing that distinguishes+ * them. Without this they render identically and a Pick looks like a no-op.+ * Enriching here keeps the ids server-side and needs no extra plumbing — the+ * activities already flow through the payload to the layout worker.+ */+export async function enrichActivityBinNames(+ client: SupabaseClient<Database>,+ payload: LineagePayload+): Promise<LineagePayload> {+ const binIds = new Set<string>();+ for (const activity of payload.activities) {+ const attrs = activity.attributes as Record<string, unknown> | null;+ for (const key of ["From Shelf", "To Shelf"]) {+ const id = attrs?.[key];+ if (typeof id === "string" && id) binIds.add(id);+ }+ }+ if (binIds.size === 0) return payload;++ const storageUnits = await client+ .from("storageUnit")+ .select("id, name")+ .in("id", Array.from(binIds));+ if (storageUnits.error || !storageUnits.data?.length) return payload;++ const nameById = indexByMapped(+ storageUnits.data,+ (row) => row.id,+ (row) => row.name+ );++ return {+ ...payload,+ activities: payload.activities.map((activity) => {+ const attrs = activity.attributes as Record<string, unknown> | null;+ const from = attrs?.["From Shelf"];+ const to = attrs?.["To Shelf"];+ const fromName =+ typeof from === "string" ? nameById.get(from) : undefined;+ const toName = typeof to === "string" ? nameById.get(to) : undefined;+ if (!fromName && !toName) return activity;+ return {+ ...activity,+ attributes: {+ ...(attrs ?? {}),+ ...(fromName ? { "From Storage Unit Name": fromName } : {}),+ ...(toName ? { "To Storage Unit Name": toName } : {})+ }+ };+ })+ };+}diff --git a/apps/erp/app/modules/inventory/types.ts b/apps/erp/app/modules/inventory/types.tsindex f7c4fa7648..a07c3f95b7 100644--- a/apps/erp/app/modules/inventory/types.ts+++ b/apps/erp/app/modules/inventory/types.ts@@ -127,6 +127,8 @@ export interface Activity {sourceDocumentId?: string;sourceDocumentReadableId?: string;attributes: Record<string, any>;+ /** Present when loaded from trackedActivity (select *); orders lot states. */+ createdAt?: string;}export interface ActivityInput {diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsxindex a13aa825fb..98a3d634ae 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryActivity.tsx@@ -27,6 +27,10 @@ export type CollapsedItemLedger = ItemLedger & {export function collapseTransferPairs(rows: ItemLedger[]): CollapsedItemLedger[] {+ // Batch Split rows are internal net-zero bookkeeping — the Transfer/+ // Consumption rows tell the real story, so they never reach the feed.+ rows = rows.filter((row) => row.documentType !== "Batch Split");+const pairKey = (row: ItemLedger) =>[row.documentId, row.itemId, row.trackedEntityId ?? "", row.createdAt].join("|"@@ -63,11 +67,17 @@ export function collapseTransferPairs(}, []);}-const getActivityText = (ledgerRecord: CollapsedItemLedger) => {+const getActivityText = (+ ledgerRecord: CollapsedItemLedger,+ trackingNoun: "batch" | "serial" | null+) => {// Prefer the entity's readable serial/batch number; fall back to the raw// tracked-entity id when it has none (e.g. unnumbered receipt batches).- const trackedEntityLabel =- ledgerRecord.trackedEntity?.readableId || ledgerRecord.trackedEntityId;+ // The tracked-entity clause is omitted entirely when the item isn't+ // serial/batch tracked (trackingNoun null).+ const trackedEntityLabel = trackingNoun+ ? ledgerRecord.trackedEntity?.readableId || ledgerRecord.trackedEntityId+ : null;switch (ledgerRecord.documentType) {case "Purchase Receipt":@@ -76,11 +86,7 @@ const getActivityText = (ledgerRecord: CollapsedItemLedger) => {? ` to ${ledgerRecord.storageUnit.name}`: ""}${- trackedEntityLabel- ? ` from ${- Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"- } ${trackedEntityLabel}`- : ""+ trackedEntityLabel ? ` of ${trackingNoun} ${trackedEntityLabel}` : ""}`;case "Purchase Invoice":return `invoiced ${ledgerRecord.quantity} units${@@ -94,9 +100,7 @@ const getActivityText = (ledgerRecord: CollapsedItemLedger) => {? ` from ${ledgerRecord.storageUnit.name}`: ""}${- trackedEntityLabel- ? ` of ${Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"} ${trackedEntityLabel}`- : ""+ trackedEntityLabel ? ` of ${trackingNoun} ${trackedEntityLabel}` : ""}`;case "Sales Invoice":return `invoiced ${ledgerRecord.quantity} units for sale${@@ -197,8 +201,7 @@ const getActivityText = (ledgerRecord: CollapsedItemLedger) => {: ""}{trackedEntityLabel ? (<>- from {Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"}{" "}- {trackedEntityLabel}{" "}+ of {trackingNoun} {trackedEntityLabel}{" "}</>) : null}{ledgerRecord.documentLineId && ledgerRecord.documentId ? (@@ -241,8 +244,7 @@ const getActivityText = (ledgerRecord: CollapsedItemLedger) => {: ""}{trackedEntityLabel ? (<>- from {Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"}{" "}- {trackedEntityLabel}{" "}+ of {trackingNoun} {trackedEntityLabel}{" "}</>) : null}{ledgerRecord.documentId ? (@@ -293,9 +295,7 @@ const getActivityText = (ledgerRecord: CollapsedItemLedger) => {? ` to ${ledgerRecord.storageUnit?.name}`: ""}${- trackedEntityLabel- ? ` for ${Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"} ${trackedEntityLabel}`- : ""+ trackedEntityLabel ? ` for ${trackingNoun} ${trackedEntityLabel}` : ""}`;case "Negative Adjmt.":return `made a negative adjustment of ${-1 * ledgerRecord.quantity}${@@ -303,9 +303,7 @@ const getActivityText = (ledgerRecord: CollapsedItemLedger) => {? ` to ${ledgerRecord.storageUnit.name}`: ""}${- trackedEntityLabel- ? ` for ${Math.abs(ledgerRecord.quantity) > 1 ? "batch" : "serial"} ${trackedEntityLabel}`- : ""+ trackedEntityLabel ? ` for ${trackingNoun} ${trackedEntityLabel}` : ""}`;default:return "";@@ -329,14 +327,21 @@ const getActivityIcon = (ledgerRecord: ItemLedger) => {type InventoryActivityProps = {item: CollapsedItemLedger;highlightId?: string;+ itemTrackingType?: string | null;};const InventoryActivity = memo(- ({ item, highlightId }: InventoryActivityProps) => {+ ({ item, highlightId, itemTrackingType }: InventoryActivityProps) => {+ const trackingNoun =+ itemTrackingType === "Serial"+ ? ("serial" as const)+ : itemTrackingType === "Batch"+ ? ("batch" as const)+ : null;return (<ActivityemployeeId={item.createdBy}- activityMessage={getActivityText(item)}+ activityMessage={getActivityText(item, trackingNoun)}activityTime={item.createdAt}activityIcon={getActivityIcon(item)}comment={item.comment}diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsxindex e30c85c9ef..d3b6ed9b99 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx@@ -38,14 +38,16 @@ import {useDisclosure,VStack} from "@carbon/react";-import { formatDate } from "@carbon/utils";+import { formatDate, groupBy } from "@carbon/utils";import { getLocalTimeZone, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import { nanoid } from "nanoid";-import { useMemo, useState } from "react";+import { Fragment, useMemo, useState } from "react";import {LuCheck,+ LuChevronDown,+ LuChevronRight,LuEllipsisVertical,LuPencil,LuPrinter,@@ -112,6 +114,44 @@ const InventoryStorageUnits = ({[itemStorageUnitQuantities]);+ // One visual row per (storage unit, lot): fragments of the same batch in the+ // same bin collapse into a group row with the summed quantity, expandable to+ // the underlying tracked entities.+ const storageUnitGroups = useMemo(() => {+ const grouped = groupBy(+ visibleStorageUnitQuantities.map((item, index) => ({ item, index })),+ // Untracked/unnumbered rows get a per-row key so they stay singletons.+ ({ item, index }) =>+ `${item.storageUnitId}::${item.readableId ?? item.trackedEntityId ?? `row-${index}`}`+ );+ return Object.entries(grouped)+ .map(([key, rows]) => ({ key, members: rows.map((r) => r.item) }))+ .sort((a, b) => {+ const unitA = a.members[0].storageUnitName ?? "";+ const unitB = b.members[0].storageUnitName ?? "";+ if (unitA !== unitB) return unitA.localeCompare(unitB);+ return (a.members[0].readableId ?? "").localeCompare(+ b.members[0].readableId ?? ""+ );+ });+ }, [visibleStorageUnitQuantities]);++ const [expandedGroupKeys, setExpandedGroupKeys] = useState<Set<string>>(+ new Set()+ );++ const toggleGroup = (key: string) => {+ setExpandedGroupKeys((prev) => {+ const next = new Set(prev);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ return next;+ });+ };+const showExpirationColumn = useMemo(() =>visibleStorageUnitQuantities.some(@@ -218,6 +258,83 @@ const InventoryStorageUnits = ({setPendingPrintEntityId(null);};+ const renderStorageUnitRow = (+ item: ItemStorageUnitQuantities,+ key: string+ ) => (+ <Tr key={key}>+ <Td>+ {storageUnits.find((s) => s.value === item.storageUnitId)?.label ||+ item.storageUnitName ||+ item.storageUnitId}+ </Td>++ <Td>+ <span>{item.quantity}</span>+ </Td>+ <Td>+ {item.trackedEntityId && (+ <HStack>+ {item.readableId && <span>{item.readableId}</span>}+ <Copy+ icon={<LuQrCode />}+ text={item.trackedEntityId}+ withTextInTooltip+ />+ </HStack>+ )}+ </Td>+ {showExpirationColumn && (+ <Td>+ {item.trackedEntityId &&+ trackedEntityExpirations[item.trackedEntityId] && (+ <span>+ {formatDate(+ trackedEntityExpirations[item.trackedEntityId],+ undefined,+ locale+ )}+ </span>+ )}+ </Td>+ )}+ <Td className="flex flex-shrink-0 justify-end items-center">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label={t`Actions`}+ variant="ghost"+ icon={<LuEllipsisVertical />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-56">+ <DropdownMenuItem+ onClick={() =>+ openAdjustmentModal(+ item.storageUnitId,+ item.trackedEntityId,+ item.readableId,+ item.quantity+ )+ }+ >+ <DropdownMenuIcon icon={<LuPencil />} />+ <Trans>Update Quantity</Trans>+ </DropdownMenuItem>+ {item.trackedEntityId && (+ <DropdownMenuItem+ onClick={() => handlePrintLabel(item.trackedEntityId!)}+ >+ <DropdownMenuIcon icon={<LuPrinter />} />+ <Trans>Print Label</Trans>+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </Td>+ </Tr>+ );+return (<><Card className="w-full">@@ -265,82 +382,87 @@ const InventoryStorageUnits = ({</Tr></Thead><Tbody>- {visibleStorageUnitQuantities.map((item, index) => (- <Tr key={index}>- <Td>- {storageUnits.find((s) => s.value === item.storageUnitId)- ?.label ||- item.storageUnitName ||- item.storageUnitId}- </Td>-- <Td>- <span>{item.quantity}</span>- </Td>- <Td>- {item.trackedEntityId && (- <HStack>- {item.readableId && <span>{item.readableId}</span>}- <Copy- icon={<LuQrCode />}- text={item.trackedEntityId}- withTextInTooltip- />- </HStack>- )}- </Td>- {showExpirationColumn && (- <Td>- {item.trackedEntityId &&- trackedEntityExpirations[item.trackedEntityId] && (+ {storageUnitGroups.map((group) => {+ if (group.members.length === 1) {+ return renderStorageUnitRow(group.members[0], group.key);+ }+ const isExpanded = expandedGroupKeys.has(group.key);+ const first = group.members[0];+ // Batch quantities are decimals — clamp float noise on the sum.+ const summedQuantity =+ Math.round(+ group.members.reduce((sum, m) => sum + m.quantity, 0) * 1e6+ ) / 1e6;+ const expirations = group.members+ .map((m) =>+ m.trackedEntityId+ ? trackedEntityExpirations[m.trackedEntityId]+ : null+ )+ .filter((d): d is string => Boolean(d));+ const earliestExpiration =+ expirations.length > 0+ ? expirations.reduce((min, d) => (d < min ? d : min))+ : null;+ return (+ <Fragment key={group.key}>+ <Tr>+ <Td>+ <HStack className="gap-1">+ <IconButton+ aria-label={isExpanded ? t`Collapse` : t`Expand`}+ variant="ghost"+ icon={+ isExpanded ? (+ <LuChevronDown />+ ) : (+ <LuChevronRight />+ )+ }+ onClick={() => toggleGroup(group.key)}+ /><span>- {formatDate(- trackedEntityExpirations[item.trackedEntityId],- undefined,- locale- )}+ {storageUnits.find(+ (s) => s.value === first.storageUnitId+ )?.label ||+ first.storageUnitName ||+ first.storageUnitId}</span>- )}- </Td>- )}- <Td className="flex flex-shrink-0 justify-end items-center">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label={t`Actions`}- variant="ghost"- icon={<LuEllipsisVertical />}- />- </DropdownMenuTrigger>- <DropdownMenuContent className="w-56">- <DropdownMenuItem- onClick={() =>- openAdjustmentModal(- item.storageUnitId,- item.trackedEntityId,- item.readableId,- item.quantity- )- }- >- <DropdownMenuIcon icon={<LuPencil />} />- <Trans>Update Quantity</Trans>- </DropdownMenuItem>- {item.trackedEntityId && (- <DropdownMenuItem- onClick={() =>- handlePrintLabel(item.trackedEntityId!)- }- >- <DropdownMenuIcon icon={<LuPrinter />} />- <Trans>Print Label</Trans>- </DropdownMenuItem>- )}- </DropdownMenuContent>- </DropdownMenu>- </Td>- </Tr>- ))}+ </HStack>+ </Td>+ <Td>+ <span>{summedQuantity}</span>+ </Td>+ <Td>+ <HStack>+ {first.readableId && <span>{first.readableId}</span>}+ <span className="text-xs text-muted-foreground">+ ×{group.members.length}+ </span>+ </HStack>+ </Td>+ {showExpirationColumn && (+ <Td>+ {earliestExpiration && (+ <span>+ {formatDate(+ earliestExpiration,+ undefined,+ locale+ )}+ </span>+ )}+ </Td>+ )}+ <Td className="flex flex-shrink-0 justify-end items-center" />+ </Tr>+ {isExpanded &&+ group.members.map((item, index) =>+ renderStorageUnitRow(item, `${group.key}:${index}`)+ )}+ </Fragment>+ );+ })}</Tbody></Table></CardContent>diff --git a/apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsx b/apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsxindex 9ec3a016ec..da5a2e53b1 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsx@@ -215,7 +215,11 @@ function buildSteps(// the Source row's date — that's when the receipt / production / split// happened. For receipt-source entities this is the goods-in date.const sourceDate = entity.createdAt ?? null;- const splitFrom = attrs["Split Entity ID"];+ // "Split From Entity ID" points at the parent the entity was drawn from.+ // The legacy "Split Entity ID" key names the CHILD that departed, not the+ // parent — rendering it as "Parent {id}" would be wrong, so legacy-only+ // entities fall through to their real provenance rows below.+ const splitFrom = attrs["Split From Entity ID"];const receiptId = attrs.Receipt;const jobId = attrs.Job;const adjustment = attrs["Inventory Adjustment"] asdiff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsxindex 47620cc6f8..960f5b0d06 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilityGraph.tsx@@ -44,7 +44,8 @@ import {type LineageEdge,type LineageNode,type LineagePayload,- mergePayloads+ mergePayloads,+ stateEntityId} from "./utils";import {useAsyncLayout,@@ -358,19 +359,21 @@ function TraceabilityGraphInner({const onExpandNode = useCallback((id: string, direction: "up" | "down" | "both") => {- const cached = probeCacheRef.current.get(id);+ // Lot-state nodes expand their underlying entity.+ const entityId = stateEntityId(id);+ const cached = probeCacheRef.current.get(entityId);if (cached) {- addExpansion(id, cached);+ addExpansion(entityId, cached);return;}- expand(id, direction, 1);+ expand(entityId, direction, 1);},[expand, addExpansion]);const onCollapseNode = useCallback((id: string) => {- removeExpansion(id);+ removeExpansion(stateEntityId(id));},[removeExpansion]);@@ -426,20 +429,23 @@ function TraceabilityGraphInner({const enrichedNodes = useMemo<Node[]>(() => {const isJobRoot = rootType === "job";return nodes.map((n) => {+ // Entity nodes may be lot-STATE nodes (`<entityId>::sN`); expansion,+ // probing, and containment are all keyed by the underlying entity.+ const entityId = stateEntityId(n.id);const isRoot = !isJobRoot && n.id === rootId;const selected = selectedIdSet.has(n.id);const excluded = excludedIds.has(n.id);const inPath = !excluded && (selectionPath?.nodeIds.has(n.id) ?? false);const dimmed = isolated ? !isolated.nodeIds.has(n.id) : false;- const isExpanded = expansions.has(n.id);+ const isExpanded = expansions.has(entityId);const isEntity = (n.data as any)?.kind === "entity";- const isExpandable = expandable.has(n.id);+ const isExpandable = expandable.has(entityId);const canExpandUp =isEntity && isExpandable && !boundaryByNode.incoming.has(n.id);const canExpandDown =isEntity && isExpandable && !boundaryByNode.outgoing.has(n.id);const containmentStatus = isEntity- ? containmentByEntity.get(n.id)+ ? containmentByEntity.get(entityId): undefined;return {...n,diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsxindex 63b07361a2..e3da5da08e 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/TraceabilitySidebar.tsx@@ -7,6 +7,7 @@ import {TooltipContent,TooltipTrigger} from "@carbon/react";+import { indexBy, pluckUnique } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import { useEffect, useMemo, useRef } from "react";import {@@ -74,57 +75,90 @@ export function TraceabilitySidebar({entity?.sourceDocumentReadableId ?? activity?.sourceDocumentReadableId;const sourceHref = sourceLinkHref(sourceDoc, sourceDocId);- const { producedBy, consumedBy, movedBy, inputs, outputs } = useMemo(() => {- if (!payload) {- return {- producedBy: [] as RelatedActivity[],- consumedBy: [] as RelatedActivity[],- movedBy: [] as RelatedActivity[],- inputs: [] as RelatedEntity[],- outputs: [] as RelatedEntity[]- };- }- const activityById = new Map(payload.activities.map((a) => [a.id, a]));- const entityById = new Map(payload.entities.map((e) => [e.id, e]));+ const { producedBy, consumedBy, movedBy, splits, inputs, outputs } =+ useMemo(() => {+ if (!payload) {+ return {+ producedBy: [] as RelatedActivity[],+ consumedBy: [] as RelatedActivity[],+ movedBy: [] as RelatedActivity[],+ splits: [] as RelatedActivity[],+ inputs: [] as RelatedEntity[],+ outputs: [] as RelatedEntity[]+ };+ }+ const activityById = indexBy(payload.activities, (a) => a.id);+ const entityById = indexBy(payload.entities, (e) => e.id);- const producedBy: RelatedActivity[] = [];- const consumedBy: RelatedActivity[] = [];- const movedBy: RelatedActivity[] = [];- const inputs: RelatedEntity[] = [];- const outputs: RelatedEntity[] = [];+ const producedBy: RelatedActivity[] = [];+ const consumedBy: RelatedActivity[] = [];+ const movedBy: RelatedActivity[] = [];+ const splits: RelatedActivity[] = [];+ const inputs: RelatedEntity[] = [];+ const outputs: RelatedEntity[] = [];- if (entity) {- for (const o of payload.outputs) {- if (o.trackedEntityId !== entity.id) continue;- const a = activityById.get(o.trackedActivityId);- if (a) producedBy.push({ activity: a, quantity: o.quantity });- }- for (const i of payload.inputs) {- if (i.trackedEntityId !== entity.id) continue;- const a = activityById.get(i.trackedActivityId);- if (!a) continue;- // A transfer/pick relocated the lot — it did not consume it.- if (isMovementActivity(a.type)) {- movedBy.push({ activity: a, quantity: i.quantity });- } else {- consumedBy.push({ activity: a, quantity: i.quantity });+ 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.+ const inputActivityIds = new Set(+ pluckUnique(payload.inputs, (i) =>+ i.trackedEntityId === entity.id ? i.trackedActivityId : null+ )+ );+ const selfLoopActivityIds = new Set(+ pluckUnique(payload.outputs, (o) =>+ o.trackedEntityId === entity.id &&+ inputActivityIds.has(o.trackedActivityId)+ ? o.trackedActivityId+ : null+ )+ );++ for (const o of payload.outputs) {+ if (o.trackedEntityId !== entity.id) continue;+ const a = activityById.get(o.trackedActivityId);+ if (!a) continue;+ if (selfLoopActivityIds.has(o.trackedActivityId)) {+ // The output row's quantity is what the entity kept.+ splits.push({ activity: a, quantity: o.quantity });+ } else {+ producedBy.push({ activity: a, quantity: o.quantity });+ }+ }+ for (const i of payload.inputs) {+ if (i.trackedEntityId !== entity.id) continue;+ if (selfLoopActivityIds.has(i.trackedActivityId)) continue;+ const a = activityById.get(i.trackedActivityId);+ if (!a) continue;+ // A Split draws a portion off this lot and leaves the rest on the+ // shelf — the lot is an input but was NOT consumed. (Legacy splits+ // recorded the survivor as input AND output; the self-loop skip above+ // catches those.)+ if (a.type === "Split") {+ splits.push({ activity: a, quantity: i.quantity });+ } else if (isMovementActivity(a.type)) {+ // A transfer/pick relocated the lot — it did not consume it.+ movedBy.push({ activity: a, quantity: i.quantity });+ } else {+ consumedBy.push({ activity: a, quantity: i.quantity });+ }+ }+ } 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 });}}- } 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 });- }- }- return { producedBy, consumedBy, movedBy, inputs, outputs };- }, [payload, entity, activity]);+ return { producedBy, consumedBy, movedBy, splits, inputs, outputs };+ }, [payload, entity, activity]);const stepRecordsFetcher = useFetcher<{ stepRecords: StepRecord[] }>();const lastLoadedActivityIdRef = useRef<string | null>(null);@@ -156,6 +190,32 @@ export function TraceabilitySidebar({);}, [activity, stepRecordsFetcher.data]);+ // Where the lot sits now: destination of the latest movement that took it as+ // an input. Bin names are enriched server-side (enrichActivityBinNames).+ const storageUnit = useMemo(() => {+ if (!entity || !payload) return null;+ // A fully consumed lot was last moved somewhere, but nothing is there now —+ // showing a bin would read as "the stock is in here". Rejected and On Hold+ // lots still physically occupy a bin, so they keep the row.+ if (entity.status === "Consumed" || !(Number(entity.quantity) > 0)) {+ return null;+ }+ const activityById = indexBy(payload.activities, (a) => a.id);+ let latest: { at: string; bin: string } | null = null;+ for (const i of payload.inputs) {+ if (i.trackedEntityId !== entity.id) continue;+ const activity = activityById.get(i.trackedActivityId);+ if (!activity || !isMovementActivity(activity.type)) continue;+ const bin = (activity.attributes as Record<string, unknown> | null)?.[+ "To Storage Unit Name"+ ];+ if (typeof bin !== "string" || !bin) continue;+ const at = (activity.createdAt as string | undefined) ?? "";+ if (!latest || at >= latest.at) latest = { at, bin };+ }+ return latest?.bin ?? null;+ }, [entity, payload]);+const containmentsForEntity = useMemo(() => {if (!entity || !payload?.containments?.length) return [];return payload.containments.filter((c) => c.trackedEntityId === entity.id);@@ -281,7 +341,7 @@ export function TraceabilitySidebar({<PropRow label="Status"><TrackedEntityStatus status={entity?.status} /></PropRow>- <PropRow label="Quantity">+ <PropRow label="Current Quantity"><span className="text-sm font-medium tabular-nums">{entity?.quantity}</span>@@ -293,6 +353,11 @@ export function TraceabilitySidebar({</span></PropRow>)}+ {storageUnit && (+ <PropRow label="Storage Unit">+ <span className="text-sm font-medium">{storageUnit}</span>+ </PropRow>+ )}</>)}{sourceDoc && (@@ -321,6 +386,19 @@ export function TraceabilitySidebar({</ul></Section>)}+ {splits.length > 0 && (+ <Section title="Splits" count={splits.length}>+ <ul className="divide-y divide-border/30">+ {splits.map((item) => (+ <RelatedActivityRow+ key={item.activity.id}+ item={item}+ onSelect={onSelect}+ />+ ))}+ </ul>+ </Section>+ )}{movedBy.length > 0 && (<Section title="Moved by" count={movedBy.length}><ul className="divide-y divide-border/30">diff --git a/apps/erp/app/modules/inventory/ui/Traceability/attributeRenderers.tsx b/apps/erp/app/modules/inventory/ui/Traceability/attributeRenderers.tsxindex 5731b136dc..d854170cad 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/attributeRenderers.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/attributeRenderers.tsx@@ -36,12 +36,17 @@ function InlineLink({const SKIPPED_ATTRIBUTE_KEYS = new Set(["Job Material",+ "Picking List Line","Purchase Order Line","Receipt Line","Sales Order Line","Shipment Line","Inventory Adjustment",- "expiryOverrides"+ "expiryOverrides",+ // Injected by the lineage loader for the graph's edge badges; the stored+ // "From Shelf"/"To Shelf" ids already render as "From/To Storage Unit".+ "From Storage Unit Name",+ "To Storage Unit Name"]);// The edge functions still write "Shelf" keys into trackedActivity/trackedEntity@@ -134,6 +139,10 @@ export function AttributeList({ attrs }: { attrs: Record<string, any> }) {operationId={value}/>);+ case "Picking List":+ return <PickingListAttribute key={key} pickingListId={value} />;+ case "Picking List Line":+ return null;case "Purchase Order":return (<PurchaseOrderAttribute key={key} purchaseOrderId={value} />@@ -221,6 +230,32 @@ function Row({);}+function PickingListAttribute({ pickingListId }: { pickingListId: string }) {+ const [readableId, setReadableId] = useState<string | null>(null);+ const { carbon } = useCarbon();++ const getPickingList = async () => {+ const response = await carbon+ ?.from("pickingList")+ .select("pickingListId")+ .eq("id", pickingListId)+ .single();+ setReadableId(response?.data?.pickingListId ?? null);+ };++ useMount(() => {+ getPickingList();+ });++ return (+ <Row label="Picking List">+ <InlineLink to={path.to.pickingList(pickingListId)}>+ {readableId ?? pickingListId}+ </InlineLink>+ </Row>+ );+}+function StockTransferAttribute({stockTransferId}: {diff --git a/apps/erp/app/modules/inventory/ui/Traceability/edges/QuantityEdge.tsx b/apps/erp/app/modules/inventory/ui/Traceability/edges/QuantityEdge.tsxindex a9b98f5756..074b1e6865 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/edges/QuantityEdge.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/edges/QuantityEdge.tsx@@ -70,7 +70,7 @@ function QuantityEdgeImpl({fill: "none"}}/>- {!dimmed && data?.quantity != null && (+ {!dimmed && (data?.labelText || data?.quantity != null) && (<EdgeLabelRenderer><divstyle={{@@ -81,7 +81,9 @@ function QuantityEdgeImpl({textAlign: "center",zIndex: 1000}}- className={`text-[11px] font-medium tabular-nums leading-none px-2 py-1 rounded-full border-2 ${+ className={`text-[11px] font-medium leading-none px-2 py-1 rounded-full border-2 ${+ data.labelText ? "" : "tabular-nums"+ } ${isReject? "bg-background text-[hsl(0_72%_55%)] border-[hsl(0_72%_55%)]": highlighted@@ -91,7 +93,7 @@ function QuantityEdgeImpl({: "bg-background text-foreground border-border"}`}>- {data.quantity}+ {data.labelText ?? data.quantity}</div></EdgeLabelRenderer>)}diff --git a/apps/erp/app/modules/inventory/ui/Traceability/metadata.ts b/apps/erp/app/modules/inventory/ui/Traceability/metadata.tsindex 5b739bf11a..264a5e12c1 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/metadata.ts+++ b/apps/erp/app/modules/inventory/ui/Traceability/metadata.ts@@ -11,6 +11,7 @@ import {LuPackageX,LuPause,LuRotateCw,+ LuShoppingCart,LuTruck,LuWrench} from "react-icons/lu";@@ -64,6 +65,7 @@ export type ActivityKind =| "Manufacturing"| "Assembly"| "Shipment"+ | "Pick"| "Transfer"| "Rework"| "Inspection"@@ -84,6 +86,8 @@ export const ACTIVITY_KIND_META: Record<ActivityKind, ActivityKindMeta> = {},Assembly: { label: "Assembly", color: "hsl(265 70% 65%)", icon: LuWrench },Shipment: { label: "Shipment", color: "hsl(20 90% 55%)", icon: LuTruck },+ // Same blue as Transfer: both are moves, the icon carries the distinction.+ Pick: { label: "Pick", color: "hsl(200 80% 55%)", icon: LuShoppingCart },Transfer: { label: "Transfer", color: "hsl(200 80% 55%)", icon: LuForklift },Rework: { label: "Rework", color: "hsl(45 95% 55%)", icon: LuRotateCw },Inspection: {@@ -99,9 +103,10 @@ export function activityKindFor(type: string | undefined | null): ActivityKind {const t = type.toLowerCase();if (t.includes("receipt") || t.includes("receive")) return "Receipt";if (t.includes("ship")) return "Shipment";- // A pick is a warehouse→lineside transfer; render it with the Transfer kind- // (the node label still shows the raw "Pick" type).- if (t.includes("transfer") || t.includes("pick")) return "Transfer";+ // Its own kind so picks and transfers don't render identically, but still a+ // movement — see isMovementActivity.+ if (t.includes("pick")) return "Pick";+ if (t.includes("transfer")) return "Transfer";if (t.includes("rework")) return "Rework";if (t.includes("inspect") || t.includes("qc") || t.includes("quality"))return "Inspection";@@ -115,5 +120,6 @@ export function activityKindFor(type: string | undefined | null): ActivityKind {// Such activities record only an input, so they read as a consumption unless// callers distinguish them. Shipments don't qualify: those really do consume.export function isMovementActivity(type: string | null | undefined): boolean {- return activityKindFor(type) === "Transfer";+ const kind = activityKindFor(type);+ return kind === "Transfer" || kind === "Pick";}diff --git a/apps/erp/app/modules/inventory/ui/Traceability/nodes/ActivityNode.tsx b/apps/erp/app/modules/inventory/ui/Traceability/nodes/ActivityNode.tsxindex 80557fac2a..09e68f5fad 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/nodes/ActivityNode.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/nodes/ActivityNode.tsx@@ -3,7 +3,7 @@ import { Handle, type NodeProps, Position, useStore } from "@xyflow/react";import { memo } from "react";import { NODE_RADIUS, NODE_SIZE } from "../constants";import { ACTIVITY_KIND_META, activityKindFor } from "../metadata";-import type { ActivityNodeData } from "../utils";+import { type ActivityNodeData, formatQuantity } from "../utils";type Props = NodeProps & {data: ActivityNodeData & {@@ -76,6 +76,14 @@ function ActivityNodeImpl({ data, selected }: Props) {<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>+ {data.movementQuantity != null && (+ <div+ className="absolute -top-1 -right-1 rounded-full bg-card border border-border text-[9px] tabular-nums px-1 leading-tight pointer-events-none"+ title={`Quantity moved: ${data.movementQuantity}`}+ >+ {formatQuantity(data.movementQuantity)}+ </div>+ )}{showLabel && (<divclassName={cn(diff --git a/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityNode.tsx b/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityNode.tsxindex f8553bd337..a3ac605e62 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityNode.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/nodes/EntityNode.tsx@@ -4,7 +4,7 @@ import { memo } from "react";import { LuChevronDown, LuChevronUp, LuMinus } from "react-icons/lu";import { NODE_RADIUS, NODE_SIZE } from "../constants";import { entityStatusMeta } from "../metadata";-import { type EntityNodeData, entityHeadline } from "../utils";+import { type EntityNodeData, entityHeadline, formatQuantity } from "../utils";type Props = NodeProps & {data: EntityNodeData & {@@ -34,6 +34,26 @@ function EntityNodeImpl({ data, selected, id }: Props) {const size = NODE_SIZE;const iconSize = 18;+ // Lot-state graph: each node is the lot AT A MOMENT — the badge shows the+ // quantity it held then. The last state is where the stock sits today and+ // gets a dashed halo. Collapsed (non-replayable) entities have no state+ // fields and fall back to the live quantity.+ const stateQuantity = data.stateQuantity ?? Number(entity.quantity);+ const isHistorical = data.isCurrentState === false;+ const showCurrentRing =+ data.isCurrentState === true &&+ (data.stateCount ?? 1) > 1 &&+ entity.status !== "Consumed" &&+ entity.status !== "Rejected";+ // A lot's chain repeats one headline per state; show it on the first and+ // current states only. Mid-chain states carry just their bin, which is the+ // thing that actually changed.+ const showHeadline =+ data.stateIndex === undefined ||+ data.stateIndex === 0 ||+ data.isCurrentState === true ||+ selected;+return (<divclassName={cn("relative", data.dimmed && "opacity-15")}@@ -90,11 +110,26 @@ function EntityNodeImpl({ data, selected, id }: Props) {strokeDasharray="3 3"/>)}+ {!isRejected && !containmentStatus && showCurrentRing && (+ <circle+ cx={radius}+ cy={radius}+ r={radius + 3}+ fill="none"+ stroke={meta.color}+ strokeWidth={1.5}+ strokeDasharray="4 3"+ opacity={0.9}+ />+ )}<circlecx={radius}cy={radius}r={radius}fill={meta.color}+ // Historical states read as the lot's past — faded next to the+ // current state that holds today's stock.+ opacity={isHistorical ? 0.55 : 1}stroke={selected || data.isRoot ? "hsl(var(--foreground))" : "transparent"}@@ -105,10 +140,17 @@ function EntityNodeImpl({ data, selected, id }: Props) {<Icon style={{ width: iconSize, height: iconSize }} /></div><div- className="absolute -top-1 -right-1 rounded-full bg-card border border-border text-[9px] tabular-nums px-1 leading-tight pointer-events-none"- title={`Quantity ${entity.quantity}`}+ className={cn(+ "absolute -top-1 -right-1 rounded-full bg-card border border-border text-[9px] tabular-nums px-1 leading-tight pointer-events-none",+ isHistorical && "opacity-70"+ )}+ title={+ isHistorical+ ? `Quantity at this step: ${stateQuantity} (current: ${entity.quantity})`+ : `Current quantity: ${stateQuantity}`+ }>- {formatQuantity(entity.quantity)}+ {formatQuantity(stateQuantity)}</div>{data.isExpanded ? (<NodeExpandToggle@@ -131,7 +173,7 @@ function EntityNodeImpl({ data, selected, id }: Props) {)}</>)}- {showLabel && (+ {showLabel && showHeadline && (<divclassName={cn("absolute left-1/2 -translate-x-1/2 whitespace-nowrap pointer-events-none select-none flex flex-col items-center",@@ -141,26 +183,22 @@ function EntityNodeImpl({ data, selected, id }: Props) {)}style={{ top: size + 4 }}>- <span- className={cn(- "text-[11px] tracking-tight px-1.5 py-px rounded bg-background",- (data.isRoot || selected) && "font-medium"- )}- >- {headline}- </span>+ {showHeadline && (+ <span+ className={cn(+ "text-[11px] tracking-tight px-1.5 py-px rounded bg-background",+ (data.isRoot || selected) && "font-medium"+ )}+ >+ {headline}+ </span>+ )}</div>)}</div>);}-function formatQuantity(q: number): string {- if (q >= 1000) return `${(q / 1000).toFixed(1)}k`;- if (Number.isInteger(q)) return String(q);- return q.toFixed(1);-}-const TOGGLE_META = {collapse: { icon: LuMinus, title: "Collapse", anchor: "top" },up: { icon: LuChevronUp, title: "Expand upstream", anchor: "top" },diff --git a/apps/erp/app/modules/inventory/ui/Traceability/store.ts b/apps/erp/app/modules/inventory/ui/Traceability/store.tsindex 37a1a1a299..7f6773ac17 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/store.ts+++ b/apps/erp/app/modules/inventory/ui/Traceability/store.ts@@ -72,7 +72,10 @@ export const useTraceabilityStore = create<TraceabilityState>()(return { additionalRootIds: next };}),- clearAdditionalRoots: () => set({ additionalRootIds: new Set() }),+ clearAdditionalRoots: () =>+ set((s) =>+ s.additionalRootIds.size === 0 ? {} : { additionalRootIds: new Set() }+ ),addExpansion: (originId, payload) =>set((s) => {@@ -115,7 +118,13 @@ export const useTraceabilityStore = create<TraceabilityState>()(return { excludedIds: next };}),- clearExcluded: () => set({ excludedIds: new Set() }),+ // Keep the same Set when there's nothing to clear. Every plain node click+ // calls this, and a fresh empty Set is a new identity — enough to re-run+ // the async selection pathfinder and repaint the graph for nothing.+ clearExcluded: () =>+ set((s) =>+ s.excludedIds.size === 0 ? {} : { excludedIds: new Set() }+ ),setDirection: (next) => set({ direction: next }),setView: (next) => set({ view: next }),diff --git a/apps/erp/app/modules/inventory/ui/Traceability/utils.ts b/apps/erp/app/modules/inventory/ui/Traceability/utils.tsindex e95adb21ee..97487ec1f2 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/utils.ts+++ b/apps/erp/app/modules/inventory/ui/Traceability/utils.ts@@ -12,12 +12,27 @@ export type EntityNodeData = {kind: "entity";entity: TrackedEntity;dimmed: boolean;+ /**+ * Lot-state fields. The graph renders each entity as a CHAIN of states —+ * quantity at each point in time — so a split reads as a real branch+ * (parent-before → Split → child + parent-after) instead of a pass-through.+ * Absent (undefined) when the entity's history couldn't be replayed and it+ * collapsed to a single current-quantity node.+ */+ stateQuantity?: number;+ stateIndex?: number;+ stateCount?: number;+ /** Last state of the chain — this is where the lot's stock sits today. */+ isCurrentState?: boolean;};export type ActivityNodeData = {kind: "activity";activity: Activity;dimmed: boolean;+ /** Amount moved, for Pick / Transfer. Their edges carry the bins instead, so+ * the quantity lives on the node. */+ movementQuantity?: number;};export type LineageNode = Node<EntityNodeData | ActivityNodeData>;@@ -25,6 +40,9 @@ export type LineageNode = Node<EntityNodeData | ActivityNodeData>;export type LineageEdgeData = {kind: "input" | "output" | "movement";quantity: number;+ /** Rendered instead of the quantity. Movement edges use it for the from/to+ * bin — for a move, where matters more than how much. */+ labelText?: string;dimmed: boolean;weight?: number;isReject?: boolean;@@ -75,84 +93,368 @@ export type LineagePayload = {containments?: IssueContainment[];};+// Delimiter between an entity id and its state index in node ids. Entity ids+// are nanoids (A-Za-z0-9_-), so "::s" can never occur inside one.+const STATE_DELIMITER = "::s";++/** Node id → the tracked entity id it represents (state nodes included). */+export function stateEntityId(nodeId: string): string {+ const i = nodeId.indexOf(STATE_DELIMITER);+ return i === -1 ? nodeId : nodeId.slice(0, i);+}++function stateNodeId(entityId: string, stateIndex: number): string {+ // State 0 keeps the bare entity id so URLs, root highlighting, and search+ // selection keep working without translation.+ return stateIndex === 0+ ? entityId+ : `${entityId}${STATE_DELIMITER}${stateIndex}`;+}++type LotEvent = {+ activityId: string;+ type: string | null;+ movement: boolean;+ createdAt: string;+ inQty: number | null;+ outQty: number | null;+ /** Bin names, enriched server-side onto movement activities. */+ fromBin: string | null;+ toBin: string | null;+};++type LotEventWiring = {+ activityId: string;+ movement: boolean;+ fromBin: string | null;+ toBin: string | null;+ /** State feeding the activity (input side); null for creation events. */+ beforeState: number | null;+ beforeQty: number | null;+ /** State the activity produces for THIS entity; null for terminal events. */+ afterState: number | null;+ afterQty: number | null;+};++type LotTimeline = {+ stateQuantities: number[];+ wiring: LotEventWiring[];+};++const QTY_EPSILON = 1e-6;++/**+ * Replay an entity's visible events backward from its current quantity to+ * recover the quantity at every point in time, then wire each event to+ * before/after states. Returns null when the history can't be reconciled+ * (legacy or partially-recorded data) — the caller collapses that entity to a+ * single current-quantity node instead of guessing.+ *+ * Rules per event shape:+ * - input+output (legacy split self-loop): before = input qty, after = output qty+ * - output only, first event: creation — after = output qty, no before state+ * - output only, later (e.g. merge gain): after = before + output qty+ * - input only, movement: after = before (relocation, quantity carried)+ * - input only, Split/Merge draw: after = before − input qty+ * - input only, otherwise (consume/ship): terminal — the state ends here+ */+function buildLotTimeline(+ entity: TrackedEntity,+ events: LotEvent[]+): LotTimeline | null {+ const current = Number(entity.quantity);+ if (!Number.isFinite(current)) return null;++ const before: (number | null)[] = new Array(events.length).fill(null);+ const after: (number | null)[] = new Array(events.length).fill(null);++ let cur = current;+ for (let i = events.length - 1; i >= 0; i--) {+ const ev = events[i];+ if (ev.inQty !== null && ev.outQty !== null) {+ if (Math.abs(cur - ev.outQty) > QTY_EPSILON) return null;+ after[i] = ev.outQty;+ before[i] = ev.inQty;+ cur = ev.inQty;+ } else if (ev.outQty !== null) {+ if (i === 0) {+ // Creation: the produced quantity must be what flowed forward.+ if (Math.abs(cur - ev.outQty) > QTY_EPSILON) return null;+ after[i] = ev.outQty;+ before[i] = null;+ } else {+ after[i] = cur;+ before[i] = cur - ev.outQty;+ cur = before[i]!;+ }+ } else if (ev.inQty !== null) {+ if (ev.movement) {+ after[i] = cur;+ before[i] = cur;+ } else if (ev.type === "Split" || ev.type === "Merge") {+ after[i] = cur;+ before[i] = cur + ev.inQty;+ cur = before[i]!;+ } else {+ // Terminal consumption/shipment. Must be the last event — anything+ // after a full consume means the history doesn't replay.+ if (i !== events.length - 1) return null;+ after[i] = null;+ before[i] = ev.inQty;+ cur = ev.inQty;+ }+ } else {+ return null;+ }+ if (+ before[i] !== null &&+ (before[i]! < -QTY_EPSILON || !Number.isFinite(before[i]!))+ ) {+ return null;+ }+ }++ const stateQuantities: number[] = [];+ const wiring: LotEventWiring[] = [];+ for (let i = 0; i < events.length; i++) {+ const ev = events[i];+ let beforeState: number | null = null;+ if (before[i] !== null) {+ if (stateQuantities.length === 0) {+ stateQuantities.push(before[i]!);+ } else if (+ Math.abs(stateQuantities[stateQuantities.length - 1] - before[i]!) >+ QTY_EPSILON+ ) {+ return null;+ }+ beforeState = stateQuantities.length - 1;+ }+ let afterState: number | null = null;+ if (after[i] !== null) {+ stateQuantities.push(after[i]!);+ afterState = stateQuantities.length - 1;+ }+ wiring.push({+ activityId: ev.activityId,+ movement: ev.movement,+ fromBin: ev.fromBin,+ toBin: ev.toBin,+ beforeState,+ beforeQty: before[i],+ afterState,+ afterQty: after[i]+ });+ }+ if (stateQuantities.length === 0) return null;+ return { stateQuantities, wiring };+}+export function payloadToFlow(payload: LineagePayload,positions: Map<string, { x: number; y: number }> = new Map()): { nodes: LineageNode[]; edges: LineageEdge[] } {+ const activityById = new Map(payload.activities.map((a) => [a.id, a]));++ // Gather each entity's events from the junction rows.+ const eventsByEntity = new Map<string, Map<string, LotEvent>>();+ const eventFor = (entityId: string, activityId: string): LotEvent => {+ let events = eventsByEntity.get(entityId);+ if (events === undefined) {+ events = new Map();+ eventsByEntity.set(entityId, events);+ }+ let ev = events.get(activityId);+ if (ev === undefined) {+ const activity = activityById.get(activityId);+ const attrs = activity?.attributes as Record<string, unknown> | undefined;+ ev = {+ activityId,+ type: activity?.type ?? null,+ movement: isMovementActivity(activity?.type),+ createdAt: (activity?.createdAt as string | undefined) ?? "",+ inQty: null,+ outQty: null,+ fromBin:+ (attrs?.["From Storage Unit Name"] as string | undefined) ?? null,+ toBin: (attrs?.["To Storage Unit Name"] as string | undefined) ?? null+ };+ events.set(activityId, ev);+ }+ return ev;+ };+ for (const input of payload.inputs) {+ eventFor(input.trackedEntityId, input.trackedActivityId).inQty = Number(+ input.quantity+ );+ }+ for (const output of payload.outputs) {+ eventFor(output.trackedEntityId, output.trackedActivityId).outQty = Number(+ output.quantity+ );+ }++ // Replay every entity; entities whose history doesn't reconcile collapse to+ // a single current-quantity node with the raw recorded edges (legacy data).+ const timelines = new Map<string, LotTimeline>();+ const seenEntityIds = new Set<string>();+ for (const entity of payload.entities) {+ if (!entity?.id || seenEntityIds.has(entity.id)) continue;+ seenEntityIds.add(entity.id);+ const events = Array.from(+ eventsByEntity.get(entity.id)?.values() ?? []+ ).sort(+ (a, b) =>+ a.createdAt.localeCompare(b.createdAt) ||+ // Same-transaction activities share a timestamp; the event that+ // creates the entity (output-only) precedes the ones that draw on it.+ Number(a.outQty === null) - Number(b.outQty === null) ||+ a.activityId.localeCompare(b.activityId)+ );+ if (events.length === 0) continue;+ const timeline = buildLotTimeline(entity, events);+ if (timeline) timelines.set(entity.id, timeline);+ }++ const nodes: LineageNode[] = [];const seenNodeIds = new Set<string>();- const entityNodes: LineageNode[] = payload.entities- .filter((e) => {- if (!e?.id || seenNodeIds.has(e.id)) return false;- seenNodeIds.add(e.id);- return true;- })- .map((entity) => ({- id: entity.id,- type: "entity",- position: positions.get(entity.id) ?? { x: 0, y: 0 },- width: NODE_SIZE,- height: NODE_SIZE,- measured: { width: NODE_SIZE, height: NODE_SIZE },- data: { kind: "entity", entity, dimmed: false }- }));-- const activityNodes: LineageNode[] = payload.activities- .filter((a) => {- if (!a?.id || seenNodeIds.has(a.id)) return false;- seenNodeIds.add(a.id);- return true;- })- .map((activity) => ({+ for (const entity of payload.entities) {+ if (!entity?.id || seenNodeIds.has(entity.id)) continue;+ seenNodeIds.add(entity.id);+ const timeline = timelines.get(entity.id);+ const stateQuantities = timeline?.stateQuantities ?? [+ Number(entity.quantity)+ ];+ for (let k = 0; k < stateQuantities.length; k++) {+ const id = stateNodeId(entity.id, k);+ nodes.push({+ id,+ type: "entity",+ position: positions.get(id) ?? { x: 0, y: 0 },+ width: NODE_SIZE,+ height: NODE_SIZE,+ measured: { width: NODE_SIZE, height: NODE_SIZE },+ data: {+ kind: "entity",+ entity,+ dimmed: false,+ stateQuantity: stateQuantities[k],+ stateIndex: k,+ stateCount: stateQuantities.length,+ isCurrentState: k === stateQuantities.length - 1+ }+ });+ }+ }++ const movementQtyByActivity = new Map<string, number>();+ for (const timeline of timelines.values()) {+ for (const w of timeline.wiring) {+ if (!w.movement) continue;+ const qty = w.beforeQty ?? w.afterQty;+ if (qty !== null) movementQtyByActivity.set(w.activityId, qty);+ }+ }++ for (const activity of payload.activities) {+ if (!activity?.id || seenNodeIds.has(activity.id)) continue;+ seenNodeIds.add(activity.id);+ nodes.push({id: activity.id,type: "activity",position: positions.get(activity.id) ?? { x: 0, y: 0 },width: NODE_SIZE,height: NODE_SIZE,measured: { width: NODE_SIZE, height: NODE_SIZE },- data: { kind: "activity", activity, dimmed: false }- }));+ data: {+ kind: "activity",+ activity,+ dimmed: false,+ movementQuantity: movementQtyByActivity.get(activity.id)+ }+ });+ }const seenEdgeIds = new Set<string>();const edges: LineageEdge[] = [];+ const pushEdge = (+ id: string,+ source: string,+ target: string,+ kind: LineageEdgeData["kind"],+ quantity: number,+ labelText?: string+ ) => {+ if (seenEdgeIds.has(id)) return;+ seenEdgeIds.add(id);+ edges.push({+ id,+ type: "quantity",+ source,+ target,+ data: { kind, quantity, labelText, dimmed: false }+ });+ };+ // 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) {+ for (const w of timeline.wiring) {+ if (w.beforeState !== null && w.beforeQty !== null) {+ pushEdge(+ `in:${w.activityId}:${entityId}@${w.beforeState}`,+ stateNodeId(entityId, w.beforeState),+ w.activityId,+ w.movement ? "movement" : "input",+ w.beforeQty,+ w.movement ? (w.fromBin ?? undefined) : undefined+ );+ }+ if (w.afterState !== null && w.afterQty !== null) {+ pushEdge(+ `out:${w.activityId}:${entityId}@${w.afterState}`,+ w.activityId,+ stateNodeId(entityId, w.afterState),+ w.movement ? "movement" : "output",+ w.afterQty,+ w.movement ? (w.toBin ?? undefined) : undefined+ );+ }+ }+ }++ // Raw edges for collapsed entities (no timeline) — today's rendering.const activityTypeById = new Map(payload.activities.map((a) => [a.id, a.type]));-for (const input of payload.inputs) {- const id = `in:${input.trackedActivityId}:${input.trackedEntityId}`;- if (seenEdgeIds.has(id)) continue;- seenEdgeIds.add(id);- // A move consumes nothing — the entity keeps its id and stays Available.+ if (timelines.has(input.trackedEntityId)) continue;const kind = isMovementActivity(activityTypeById.get(input.trackedActivityId))? "movement": "input";- edges.push({- id,- type: "quantity",- source: input.trackedEntityId,- target: input.trackedActivityId,- data: { kind, quantity: input.quantity, dimmed: false }- });+ pushEdge(+ `in:${input.trackedActivityId}:${input.trackedEntityId}`,+ input.trackedEntityId,+ input.trackedActivityId,+ kind,+ input.quantity+ );}-for (const output of payload.outputs) {- const id = `out:${output.trackedActivityId}:${output.trackedEntityId}`;- if (seenEdgeIds.has(id)) continue;- seenEdgeIds.add(id);- edges.push({- id,- type: "quantity",- source: output.trackedActivityId,- target: output.trackedEntityId,- data: { kind: "output", quantity: output.quantity, dimmed: false }- });+ if (timelines.has(output.trackedEntityId)) continue;+ pushEdge(+ `out:${output.trackedActivityId}:${output.trackedEntityId}`,+ output.trackedActivityId,+ output.trackedEntityId,+ "output",+ output.quantity+ );}- return { nodes: [...entityNodes, ...activityNodes], edges };+ return { nodes, edges };}export function mergePayloads(@@ -363,6 +665,10 @@ export function sourceLinkHref(return `/x/purchase-order/${id}`;case "Sales Order":return `/x/sales-order/${id}`;+ case "Picking List":+ return `/x/picking-list/${id}`;+ case "Stock Transfer":+ return `/x/stock-transfer/${id}`;default:return null;}@@ -387,8 +693,16 @@ export function annotateEdgeWeights(data: {...(e.data as LineageEdgeData),weight,- isReject: rejectIds.has(e.target)+ // rejectIds hold entity ids; edge targets may be state nodes.+ isReject: rejectIds.has(stateEntityId(e.target))}};});}++// Compact quantity for node badges/stubs, where horizontal space is tight.+export function formatQuantity(q: number): string {+ if (q >= 1000) return `${(q / 1000).toFixed(1)}k`;+ if (Number.isInteger(q)) return String(q);+ return q.toFixed(1);+}diff --git a/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts b/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.tsindex 02df8e273a..0070a1244e 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts+++ b/apps/erp/app/modules/inventory/ui/Traceability/worker/hooks.ts@@ -63,14 +63,31 @@ export function useAsyncSelectionPath([additionalRootIds]);+ // Pathfinding reads only topology and which nodes are selected, but `edges`+ // and `selectedIds` are rebuilt whenever ANY node state changes — a drag frame+ // included. Keying on the values instead of the array identities keeps the+ // worker from re-running (and repainting the graph a frame later) for edits it+ // would answer identically.+ const topologyKey = useMemo(+ () => edges.map((e) => `${e.id}>${e.source}>${e.target}`).join("|"),+ [edges]+ );+ const selectedKey = selectedIds.join("|");++ const latest = useRef({ edges, selectedIds });+ latest.current = { edges, selectedIds };++ // biome-ignore lint/correctness/useExhaustiveDependencies: keyed on topologyKey/selectedKey, not the array identities they summarizeuseEffect(() => {- if (selectedIds.length === 0 && additionalArray.length === 0) {+ const { edges: currentEdges, selectedIds: currentSelected } =+ latest.current;+ if (currentSelected.length === 0 && additionalArray.length === 0) {setPath(null);return;}let cancelled = false;manager- .selection(edges, selectedIds, excludedArray, additionalArray)+ .selection(currentEdges, currentSelected, excludedArray, additionalArray).then((r) => {if (cancelled || r === null) return;setPath({@@ -81,7 +98,7 @@ export function useAsyncSelectionPath(return () => {cancelled = true;};- }, [manager, edges, selectedIds, excludedArray, additionalArray]);+ }, [manager, topologyKey, selectedKey, excludedArray, additionalArray]);return path;}diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsxindex 66651d2997..8da12e7e40 100644--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx@@ -8,12 +8,13 @@ import { LuChevronUp } from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";import InfiniteScroll from "~/components/InfiniteScroll";-import type { ItemLedger } from "~/modules/inventory";+import type { CollapsedItemLedger, ItemLedger } from "~/modules/inventory";import {collapseTransferPairs,getItemLedgerActivity,InventoryActivity} from "~/modules/inventory";+import { getItem } from "~/modules/items";import { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";import { path } from "~/utils/path";@@ -77,7 +78,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// The activity page and the "is there anything newer than the anchor?"// existence check both depend only on `anchorEntryNumber`, not on each other —// run them in parallel to save a roundtrip on highlight navigations.- const [itemLedgerRecords, newer] = await Promise.all([+ const [itemLedgerRecords, newer, item] = await Promise.all([getItemLedgerActivity(client, {itemId,companyId,@@ -95,7 +96,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {.eq("locationId", locationId).gt("entryNumber", anchorEntryNumber).limit(1)- : Promise.resolve({ data: [] as { id: string }[] })+ : Promise.resolve({ data: [] as { id: string }[] }),+ getItem(client, itemId)]);if (itemLedgerRecords.error) {throw redirect(@@ -117,7 +119,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locationId,highlightId,hasOlder: itemLedgerRecords.hasMore,- hasNewer+ hasNewer,+ itemTrackingType: item.data?.itemTrackingType ?? null};}@@ -129,7 +132,8 @@ export default function ItemInventoryActivityRoute() {locationId,highlightId,hasOlder: initialHasOlder,- hasNewer: initialHasNewer+ hasNewer: initialHasNewer,+ itemTrackingType} = useLoaderData<typeof loader>();const { carbon } = useCarbon();@@ -142,6 +146,28 @@ export default function ItemInventoryActivityRoute() {() => collapseTransferPairs(itemLedgers),[itemLedgers]);+ // InfiniteScroll only forwards { item, highlightId } — close over the item's+ // tracking type so rows label their tracked entity from the item, not a+ // quantity heuristic.+ const ActivityItem = useMemo(+ () =>+ function ActivityItem({+ item,+ highlightId: rowHighlightId+ }: {+ item: CollapsedItemLedger;+ highlightId?: string;+ }) {+ return (+ <InventoryActivity+ item={item}+ highlightId={rowHighlightId}+ itemTrackingType={itemTrackingType}+ />+ );+ },+ [itemTrackingType]+ );const [hasOlder, setHasOlder] = useState(initialHasOlder);const [hasNewer, setHasNewer] = useState(initialHasNewer);const [isLoadingNewer, setIsLoadingNewer] = useState(false);@@ -228,7 +254,7 @@ export default function ItemInventoryActivityRoute() {)}<InfiniteScroll- component={InventoryActivity}+ component={ActivityItem}items={activityItems}loadMore={loadOlder}hasMore={hasOlder}diff --git a/apps/erp/app/routes/x+/traceability+/graph.tsx b/apps/erp/app/routes/x+/traceability+/graph.tsxindex eb32aeb34f..e3f8c88f47 100644--- a/apps/erp/app/routes/x+/traceability+/graph.tsx+++ b/apps/erp/app/routes/x+/traceability+/graph.tsx@@ -13,6 +13,7 @@ import { Link, redirect, useLoaderData, useNavigation } from "react-router";import { Empty } from "~/components";import type { Activity, TrackedEntity } from "~/modules/inventory";import {+ enrichActivityBinNames,fetchContainmentsForEntities,fetchJobScopedLineage,fetchLineageSubgraph,@@ -21,6 +22,7 @@ import {import { clampDepth } from "~/modules/inventory/ui/Traceability/constants";import { TraceabilityGraph } from "~/modules/inventory/ui/Traceability/TraceabilityGraph";import { TraceabilitySidebar } from "~/modules/inventory/ui/Traceability/TraceabilitySidebar";+import { stateEntityId } from "~/modules/inventory/ui/Traceability/utils";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -79,7 +81,7 @@ export async function loader({ request }: LoaderFunctionArgs) {payload.entities.map((e) => e.id));return {- ...payload,+ ...(await enrichActivityBinNames(client, payload)),containments,rootId: trackedEntityId,rootType: "entity" as const,@@ -95,7 +97,7 @@ export async function loader({ request }: LoaderFunctionArgs) {jobReadableId);return {- ...payload,+ ...(await enrichActivityBinNames(client, payload)),rootId: jobId,rootType: "job" as const,depth@@ -166,13 +168,18 @@ export async function loader({ request }: LoaderFunctionArgs) {);return {- entities: allEntities,- inputs: [...(directInputs?.data || []), ...(additionalInputs?.data || [])],- outputs: [- ...(directOutputs?.data || []),- ...(additionalOutputs?.data || [])- ],- activities: allActivities,+ ...(await enrichActivityBinNames(client, {+ entities: allEntities,+ inputs: [+ ...(directInputs?.data || []),+ ...(additionalInputs?.data || [])+ ],+ outputs: [+ ...(directOutputs?.data || []),+ ...(additionalOutputs?.data || [])+ ],+ activities: allActivities+ })),containments,rootId: trackedActivityId!,rootType: "activity" as const,@@ -359,9 +366,13 @@ function TraceabilityRouteInner() {[setNodes]);+ // 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 === sidebarId) as TrackedEntity | undefined) ??- null;+ (entities.find((e) => e?.id === sidebarEntityId) as+ | TrackedEntity+ | undefined) ?? null;const selectedActivity =(activities.find((a) => a?.id === sidebarId) as Activity | undefined) ??null;diff --git a/packages/utils/src/types.ts b/packages/utils/src/types.tsindex 35f6c4b49f..51c5cc76da 100644--- a/packages/utils/src/types.ts+++ b/packages/utils/src/types.ts@@ -64,6 +64,8 @@ export interface TrackedActivityAttributes {// attributed per-unit even though every unit shares one lot entity.Unit?: number;"Original Quantity"?: number;+ "Picking List"?: string;+ "Picking List Line"?: string;"Production Event"?: string;"Receipt Line"?: string;"Remaining Quantity"?: number;