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(settings): show display names instead of raw ids in audit log diffs (#1313)
Naveen Kashyap6f4943cf3f53
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 2a654f3860..8e8be1ed56 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -593,3 +593,13 @@ Format: `Context → Problem → Rule → Applies to`**Rule:** Never let an unstable `Intl.NumberFormatOptions` reference reach react-aria. `packages/react/src/Number.tsx`'s `NumberField` now stabilizes it via `useStableFormatOptions` / `areNumberFormatOptionsEqual` (shallow value compare — exact, since the options are all primitives), so call sites are free to pass literals. If you build another react-aria wrapper that forwards `formatOptions`, do the same; do not "fix" this class of bug by only adding/adjusting `formatOptions` at the call site — that is what introduced it here. Also note the same trap for any react-aria prop compared by identity.**Applies to:** `packages/react/src/Number.tsx`; every `formatOptions={{ ... }}` call site in `apps/erp` / `apps/mes` (~144); `packages/form/src/components/{Number,NumberControlled,ArrayNumeric}.tsx`, whose `rest.formatOptions ?? ({ ... })` default also allocates a fresh object each render.++## Audit FK snapshots: constraint-less columns are invisible to schema discovery; junction targets need hops++**Context:** Audit-log diffs resolve FK ids into frozen display names ("Location: Chicago → Dallas") via `get_foreign_key_map` + `fkDisplayRegistry` (`packages/database/src/audit.config.ts`, handler in `packages/jobs/src/inngest/functions/events/{audit,fk-snapshots}.ts`). Found while fixing "audit log shows location id instead of name" (2026-08).++**Problem:** Three distinct shapes made raw ids reach the UI. (1) `get_foreign_key_map` reads `pg_constraint`, so reference columns **without a real FK constraint** are invisible to it — no snapshot no matter what the registry says. This schema has many: `salesOrder.salesPersonId`, `salesInvoice.assignee`, line-level `locationId`s on `purchaseOrderLine`/`salesOrderLine`/`salesInvoiceShipment`, `inventoryCountLine.storageUnitId`, etc. (2) Junction targets (`customerContact`/`supplierContact`, `opportunity`, `fulfillment`…) have no displayable columns of their own — the name lives one hop away (`contact.fullName`), which single-hop resolution can't reach. (3) A target table simply missing from `fkDisplayRegistry` silently degrades to the raw id — no error anywhere.++**Rule:** When adding a reference column to an audited table, either give it a real FK constraint (registry/hops then cover it automatically) or declare a per-column `snapshotFields` override on that table's audit config. For targets whose display value lives on another table, use `fkDisplayHops` (two-stage batched lookup). Resolution precedence is override > hop > registry; hops and registry must stay disjoint, and overrides must not target hop tables — both invariants are enforced by tests in `fk-snapshots.test.ts`. Snapshots are frozen at write time: config changes never backfill existing audit rows.++**Applies to:** `packages/database/src/audit.config.ts` (`fkDisplayRegistry`, `fkDisplayHops`, `snapshotFields`), `packages/jobs/src/inngest/functions/events/fk-snapshots.ts` + `audit.ts`, and any migration adding reference columns to tables listed in `auditConfig.entities`.diff --git a/.claude/rules/audit-log-system.md b/.claude/rules/audit-log-system.mdindex 638d217af4..fb069bac07 100644--- a/.claude/rules/audit-log-system.md+++ b/.claude/rules/audit-log-system.md@@ -53,7 +53,8 @@ Other config knobs:- `retentionDays: 30`- `archivePath: "audit-logs/{companyId}/{year}/{month}.jsonl.gz"` and `archiveBucket: "private"`.- `createFields` (allowlist of columns surfaced on INSERT) is declared per table.-- `fkDisplayRegistry` — display columns per FK *target* table (e.g. `supplier: ["name"]`, `user: ["fullName"]`). FK columns are discovered from the schema at runtime via the `get_foreign_key_map` RPC (reads `pg_constraint`; only FKs referencing the target's `id`; returns `targetHasCompanyId` so non-tenant targets like `user` skip the companyId filter). Any changed FK column whose target is in the registry gets its display values frozen into the diff automatically; targets missing from the registry degrade to showing the raw id. Per-column `snapshotFields` on a table config still exist as overrides and win over the registry.+- `fkDisplayRegistry` — display columns per FK *target* table (e.g. `supplier: ["name"]`, `user: ["fullName"]`, ~64 targets). FK columns are discovered from the schema at runtime via the `get_foreign_key_map` RPC (reads `pg_constraint`; only FKs referencing the target's `id`; returns `targetHasCompanyId` so non-tenant targets like `user` skip the companyId filter). Any changed FK column whose target is in the registry gets its display values frozen into the diff automatically; targets missing from the registry degrade to showing the raw id. Per-column `snapshotFields` on a table config still exist as overrides and win over the registry — they're REQUIRED for columns with no FK constraint in the DB (e.g. `salesOrder.salesPersonId`, several line-level `locationId`s), which `get_foreign_key_map` cannot see. An override target's tenancy is inherited from any schema FK referencing the same table (so a `user` override is correctly unscoped).+- `fkDisplayHops` — junction targets whose display value lives one hop away (`customerContact`/`supplierContact` → `contact.fullName`). The handler resolves these in two batched lookups (junction id → hop column → display row); hops win over the registry for the same target.Types live in `audit.types.ts`: `AuditLogEntry`, `CreateAuditLogEntry`, `AuditDiff`, `AuditDiffEntry`,`AuditMetadata`, `AuditOperation`, `AuditLogFilters`, `AuditLogResponse`, `AuditLogArchive`, `AuditLogConfig`.@@ -100,7 +101,10 @@ than from config.Unknown prefixes render as plain text.- `.../AuditLog/AuditLogSettings.tsx` — enable/disable + archive download list.- `apps/erp/app/components/AuditLog/` — per-entity history `AuditLogDrawer.tsx` + `useAuditLog.tsx` hook,- fetching `api+/audit-log.ts` by `entityType`/`entityId`/`recordId`.+ fetching `api+/audit-log.ts` by `entityType`/`entityId`/`recordId`. `AuditLogDrawer.tsx` also exports+ `ChangeRow`, the snapshot-aware diff-row renderer (FK name from `diff[col].snapshot`, raw id on hover)+ used by BOTH the drawer and the global `AuditLogTable` expanded rows — don't render `change.old/new`+ raw or FKs regress to bare ids.- Actor column: `<EmployeeAvatar employeeId={actorId} />` linked to `path.to.employeeAccount`; null actor → "System".(`actorName` column was removed; the UI resolves names from `actorId`.)diff --git a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsxindex 9c84ea3eca..8b7e866793 100644--- a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx+++ b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx@@ -11,6 +11,9 @@ import {DrawerTitle,HStack,Skeleton,+ Tooltip,+ TooltipContent,+ TooltipTrigger,VStack} from "@carbon/react";import { Trans } from "@lingui/react/macro";@@ -345,6 +348,19 @@ function humanizeColumnKey(key: string, hasSnapshot: boolean): string {.trim();}+// Raw "oldId → newId" transition for a multi-column snapshot header, or+// undefined when neither side is a string id.+function formatIdTransition(+ change: import("@carbon/database/audit.types").AuditDiffEntry+): string | undefined {+ if (typeof change.old !== "string" && typeof change.new !== "string") {+ return undefined;+ }+ const oldId = typeof change.old === "string" ? change.old : "—";+ const newId = typeof change.new === "string" ? change.new : "—";+ return `${oldId} → ${newId}`;+}+// Pick the snapshot value for a given snapshot column from old or new sides.function snapshotValue(snapshot: Record<string, unknown> | undefined,@@ -353,10 +369,31 @@ function snapshotValue(return snapshot && col in snapshot ? snapshot[col] : undefined;}+// Wraps children in a styled tooltip carrying the raw id(s) — the forensic+// anchor behind a resolved display name. Instant-ish (root provider sets a+// 200ms delay), unlike the native `title` attribute which needs a ~1s+// motionless hover.+function IdTooltip({+ id,+ children+}: {+ id: string;+ children: React.ReactElement;+}) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>{children}</TooltipTrigger>+ <TooltipContent>+ <span className="font-mono text-xs">{id}</span>+ </TooltipContent>+ </Tooltip>+ );+}+// Linear-style pill: when a display value is present, show that as primary-// sans-serif text and stash the underlying raw value on the title attribute-// (hover to inspect). When no display value is supplied, fall back to-// mono-rendering the raw value — appropriate for IDs, booleans, numbers.+// sans-serif text with the underlying raw value in a hover tooltip. When no+// display value is supplied, fall back to mono-rendering the raw value —+// appropriate for IDs, booleans, numbers.function ChangePill({value,display,@@ -387,11 +424,9 @@ function ChangePill({: "bg-green-500/10 text-green-500");const tooltip = hasDisplay && typeof value === "string" ? value : undefined;- return (- <span className={className} title={tooltip}>- {text}- </span>- );+ const pill = <span className={className}>{text}</span>;+ if (!tooltip) return pill;+ return <IdTooltip id={tooltip}>{pill}</IdTooltip>;}// One labeled side-by-side row: "label [old] → [new]". Used for both@@ -439,7 +474,7 @@ function ChangeLine({// • multi-key snap → humanized FK header + indented sub-rows per// snapshot column, with the raw id shown last as a// muted forensic anchor-function ChangeRow({+export function ChangeRow({columnKey,change}: {@@ -480,22 +515,15 @@ function ChangeRow({// the raw FK id is demoted to a hover tooltip on the section header —// Linear-style. Power users still see the id transition without crowding// the visual flow.- const idTooltip = ((): string | undefined => {- if (typeof change.old !== "string" && typeof change.new !== "string") {- return undefined;- }- const oldId = typeof change.old === "string" ? change.old : "—";- const newId = typeof change.new === "string" ? change.new : "—";- return `${oldId} → ${newId}`;- })();+ const idTooltip = formatIdTransition(change);+ const header = (+ <div className="text-sm text-muted-foreground font-medium w-fit">+ {label}+ </div>+ );return (<div className="py-1">- <div- className="text-sm text-muted-foreground font-medium"- title={idTooltip}- >- {label}- </div>+ {idTooltip ? <IdTooltip id={idTooltip}>{header}</IdTooltip> : header}<div className="space-y-1 mt-1">{Array.from(snapKeys).map((col) => (<ChangeLinediff --git a/apps/erp/app/components/AuditLog/index.ts b/apps/erp/app/components/AuditLog/index.tsindex da0a512546..ca43d78c80 100644--- a/apps/erp/app/components/AuditLog/index.ts+++ b/apps/erp/app/components/AuditLog/index.ts@@ -1,3 +1,3 @@-export { default as AuditLogDrawer } from "./AuditLogDrawer";+export { ChangeRow, default as AuditLogDrawer } from "./AuditLogDrawer";export { useAuditLog } from "./useAuditLog";export { isEmptyDiffValue } from "./utils";diff --git a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsxindex 9cc6cdd547..a8633f9010 100644--- a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx+++ b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx@@ -6,13 +6,13 @@ import {} from "@carbon/database/audit.config";import type { AuditDiff, AuditLogEntry } from "@carbon/database/audit.types";import { Badge, HStack } from "@carbon/react";-import { Trans, useLingui } from "@lingui/react/macro";+import { useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo } from "react";import { LuFilePen, LuFilePlus, LuFileX } from "react-icons/lu";import { Link } from "react-router";import { EmployeeAvatar, Table } from "~/components";-import { isEmptyDiffValue } from "~/components/AuditLog";+import { ChangeRow } from "~/components/AuditLog";import { useDateFormatter } from "~/hooks";import { path } from "~/utils/path";@@ -42,42 +42,6 @@ const operationConfig: Record<}};-function formatValue(value: unknown): string {- if (value === null) return "null";- if (value === undefined) return "undefined";- if (typeof value === "string") return value;- if (typeof value === "number" || typeof value === "boolean")- return String(value);- return JSON.stringify(value);-}--function DiffValue({- value,- variant-}: {- value: unknown;- variant: "old" | "new";-}) {- if (isEmptyDiffValue(value)) {- return (- <span className="px-2 py-0.5 rounded bg-muted text-muted-foreground italic font-sans">- <Trans>Empty</Trans>- </span>- );- }- return (- <span- className={- variant === "old"- ? "px-2 py-0.5 rounded bg-red-500/10 text-red-500"- : "px-2 py-0.5 rounded bg-green-500/10 text-green-500"- }- >- {formatValue(value)}- </span>- );-}-function getEntityPath(entityId: string): string | null {const prefix = entityId.split("_")[0];if (!prefix || prefix === entityId) return null;@@ -107,30 +71,6 @@ function getEntityPath(entityId: string): string | null {return pathFn ? pathFn(entityId) : null;}-const InlineDiff = memo(- ({- fieldName,- oldValue,- newValue- }: {- fieldName: string;- oldValue: unknown;- newValue: unknown;- }) => (- <div className="flex items-center gap-2 font-mono text-sm py-1">- <span className="text-muted-foreground font-medium min-w-[120px]">- {fieldName}:- </span>- {oldValue !== undefined && <DiffValue value={oldValue} variant="old" />}- {oldValue !== undefined && newValue !== undefined && (- <span className="text-muted-foreground">→</span>- )}- {newValue !== undefined && <DiffValue value={newValue} variant="new" />}- </div>- )-);-InlineDiff.displayName = "InlineDiff";-// Hide globally-skipped columns (and any nested suffix) from the rendered// diff. Defense-in-depth — backend strips skipFields too, but legacy entries// or newly-added skipFields can slip through.@@ -182,11 +122,10 @@ const ExpandedRowContent = memo(({ entry }: { entry: AuditLogEntry }) => {{hasDiff ? (<div className="space-y-1">{visibleEntries.map(([fieldName, change]) => (- <InlineDiff+ <ChangeRowkey={fieldName}- fieldName={fieldName}- oldValue={change.old}- newValue={change.new}+ columnKey={fieldName}+ change={change}/>))}</div>diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.tsindex b04267d6cd..34c1b2f26d 100644--- a/packages/database/src/audit.config.ts+++ b/packages/database/src/audit.config.ts@@ -241,10 +241,32 @@ export const auditConfig = {salesOrder: {label: "Sales Order",tables: {- salesOrder: { role: "root" },- salesOrderLine: { entityIdColumn: "salesOrderId" },+ salesOrder: {+ role: "root",+ snapshotFields: {+ // No FK constraint on this column, so the schema-discovered map+ // can't resolve it — declare the target explicitly.+ salesPersonId: { table: "user", displayColumns: ["fullName"] }+ }+ },+ salesOrderLine: {+ entityIdColumn: "salesOrderId",+ snapshotFields: {+ locationId: { table: "location", displayColumns: ["name"] },+ modelUploadId: { table: "modelUpload", displayColumns: ["name"] }+ }+ },salesOrderPayment: { role: "extension" }, // PK = salesOrderId- salesOrderShipment: { role: "extension" } // PK = salesOrderId+ salesOrderShipment: {+ role: "extension", // PK = salesOrderId+ snapshotFields: {+ supplierId: { table: "supplier", displayColumns: ["name"] },+ supplierLocationId: {+ table: "supplierLocation",+ displayColumns: ["name"]+ }+ }+ }}},@@ -261,7 +283,13 @@ export const auditConfig = {}}},- purchaseOrderLine: { entityIdColumn: "purchaseOrderId" },+ purchaseOrderLine: {+ entityIdColumn: "purchaseOrderId",+ snapshotFields: {+ // No FK constraint on this column — resolve explicitly.+ locationId: { table: "location", displayColumns: ["name"] }+ }+ },purchaseOrderPayment: {role: "extension", // PK = purchaseOrderIdsnapshotFields: {@@ -298,9 +326,26 @@ export const auditConfig = {salesInvoice: {label: "Sales Invoice",tables: {- salesInvoice: { role: "root" },+ salesInvoice: {+ role: "root",+ // No FK constraint on this column — resolve explicitly.+ snapshotFields: {+ assignee: { table: "user", displayColumns: ["fullName"] }+ }+ },salesInvoiceLine: { entityIdColumn: "invoiceId" },- salesInvoiceShipment: { role: "extension" } // PK = salesInvoiceId+ salesInvoiceShipment: {+ role: "extension", // PK = salesInvoiceId+ // These columns have no FK constraints — resolve explicitly.+ snapshotFields: {+ locationId: { table: "location", displayColumns: ["name"] },+ shippingMethodId: {+ table: "shippingMethod",+ displayColumns: ["name"]+ },+ shippingTermId: { table: "shippingTerm", displayColumns: ["name"] }+ }+ }}},@@ -308,7 +353,13 @@ export const auditConfig = {label: "Purchase Invoice",tables: {purchaseInvoice: { role: "root" },- purchaseInvoiceLine: { entityIdColumn: "invoiceId" }+ purchaseInvoiceLine: {+ entityIdColumn: "invoiceId",+ // No FK constraint on this column — resolve explicitly.+ snapshotFields: {+ assetId: { table: "fixedAsset", displayColumns: ["name"] }+ }+ }}},@@ -331,9 +382,25 @@ export const auditConfig = {productionJob: {label: "Job",tables: {- job: { role: "root" },+ job: {+ role: "root",+ // No FK constraints on these columns — resolve explicitly.+ snapshotFields: {+ modelUploadId: { table: "modelUpload", displayColumns: ["name"] },+ quoteLineId: { table: "quoteLine", displayColumns: ["description"] }+ }+ },jobOperation: { entityIdColumn: "jobId" },- jobMaterial: { entityIdColumn: "jobId" },+ jobMaterial: {+ entityIdColumn: "jobId",+ snapshotFields: {+ // No FK constraint on this column — resolve explicitly.+ substitutedFromItemId: {+ table: "item",+ displayColumns: ["readableId"]+ }+ }+ },jobMakeMethod: { entityIdColumn: "jobId" }}},@@ -412,7 +479,18 @@ export const auditConfig = {inventoryCount: { role: "root" },// Line INSERTs (bulk snapshot generation) are auto-skipped for non-root// tables; only UPDATE/DELETE on a counted line are logged.- inventoryCountLine: { entityIdColumn: "inventoryCountId" }+ inventoryCountLine: {+ entityIdColumn: "inventoryCountId",+ // These columns have no FK constraints — resolve explicitly.+ snapshotFields: {+ locationId: { table: "location", displayColumns: ["name"] },+ storageUnitId: { table: "storageUnit", displayColumns: ["name"] },+ trackedEntityId: {+ table: "trackedEntity",+ displayColumns: ["readableId"]+ }+ }+ }}},@@ -603,29 +681,142 @@ export const auditConfig = {export const fkDisplayRegistry: {[T in TableName]?: readonly ColumnOf<T>[];} = {+ ability: ["name"],+ account: ["number", "name"],address: ["addressLine1", "city"],+ assemblyInstruction: ["name"],+ changeOrder: ["changeOrderId"],+ changeOrderRequiredAction: ["name"],+ changeOrderType: ["name"],+ company: ["name"],contact: ["fullName"],+ costCenter: ["name"],customer: ["name"],customerLocation: ["name"],customerStatus: ["name"],customerType: ["name"],department: ["name"],employeeType: ["name"],+ fixedAsset: ["name"],+ fixedAssetClass: ["name"],+ gauge: ["gaugeId"],+ gaugeType: ["name"],+ inspectionDocument: ["fileName"],+ inventoryCount: ["inventoryCountId"],item: ["readableId"],+ itemPostingGroup: ["name"],+ job: ["jobId"],+ jobMaterial: ["description"],+ jobOperation: ["description"],location: ["name"],+ maintenanceDispatch: ["maintenanceDispatchId"],+ maintenanceFailureMode: ["name"],+ maintenanceSchedule: ["name"],+ modelUpload: ["name"],+ nonConformance: ["nonConformanceId"],+ nonConformanceRequiredAction: ["name"],+ nonConformanceType: ["name"],+ nonConformanceWorkflow: ["name"],paymentTerm: ["name"],+ pricingRule: ["name"],+ procedure: ["name"],process: ["name"],+ purchaseInvoice: ["invoiceId"],+ purchaseOrder: ["purchaseOrderId"],+ purchaseOrderLine: ["description"],+ quote: ["quoteId"],+ receipt: ["receiptId"],+ rework: ["reason"],+ salesInvoice: ["invoiceId"],+ salesOrder: ["salesOrderId"],+ salesOrderLine: ["description"],shift: ["name"],+ shipment: ["shipmentId"],shippingMethod: ["name"],shippingTerm: ["name"],+ stockTransfer: ["stockTransferId"],+ storageUnit: ["name"],supplier: ["name"],supplierLocation: ["name"],+ supplierQuote: ["supplierQuoteId"],supplierType: ["name"],+ trackedEntity: ["readableId"],unitOfMeasure: ["name"],user: ["fullName"],+ warehouseTransfer: ["transferId"],workCenter: ["name"]} as const;+/**+ * Junction FK targets whose display value lives one hop away, keyed by the+ * table being pointed at. A column like `invoiceSupplierContactId` references+ * a `supplierContact` link row, which has no displayable columns of its own —+ * the person's name is on `contact`, reachable via the junction's `column`.+ *+ * The audit handler resolves these in two batched lookups: junction rows+ * (id → hop column) then display rows (hop id → displayColumns). A junction+ * table listed here must NOT also appear in `fkDisplayRegistry` — hops take+ * precedence.+ */+export type FkDisplayHop = {+ /** Column on the junction row holding the display row's id. */+ column: string;+ /** Table the display columns are read from. */+ table: string;+ displayColumns: readonly string[];+};++export const fkDisplayHops: {+ [T in TableName]?: {+ [D in TableName]: {+ column: ColumnOf<T>;+ table: D;+ displayColumns: readonly ColumnOf<D>[];+ };+ }[TableName];+} = {+ customerContact: {+ column: "contactId",+ table: "contact",+ displayColumns: ["fullName"]+ },+ customerItemPriceOverride: {+ column: "itemId",+ table: "item",+ displayColumns: ["readableId"]+ },+ fulfillment: {+ column: "jobId",+ table: "job",+ displayColumns: ["jobId"]+ },+ jobMakeMethod: {+ column: "itemId",+ table: "item",+ displayColumns: ["readableId"]+ },+ makeMethod: {+ column: "itemId",+ table: "item",+ displayColumns: ["readableId"]+ },+ opportunity: {+ column: "customerId",+ table: "customer",+ displayColumns: ["name"]+ },+ supplierContact: {+ column: "contactId",+ table: "contact",+ displayColumns: ["fullName"]+ },+ supplierInteraction: {+ column: "supplierId",+ table: "supplier",+ displayColumns: ["name"]+ }+} as const;+// ---------------------------------------------------------------------------// Derived types// ---------------------------------------------------------------------------diff --git a/packages/jobs/src/inngest/functions/events/audit.ts b/packages/jobs/src/inngest/functions/events/audit.tsindex 7a477d662c..9ef9fc6c3f 100644--- a/packages/jobs/src/inngest/functions/events/audit.ts+++ b/packages/jobs/src/inngest/functions/events/audit.ts@@ -23,7 +23,7 @@ import { groupBy } from "@carbon/utils";import { z } from "zod";import { inngest } from "../../client";import { computeCreateDiff, computeDiff } from "./diff";-import type { FkMap, FkMapRow } from "./fk-snapshots";+import type { FkMap, FkMapRow, SnapshotSpec } from "./fk-snapshots";import { parseFkMapRows, resolveSnapshotSpec } from "./fk-snapshots";const log = getLogger("jobs", "audit");@@ -392,6 +392,7 @@ async function applyFkSnapshots(const idsByTable = new Map<string, Set<string>>();const colsByTable = new Map<string, Set<string>>();const companyScopedByTable = new Map<string, boolean>();+ const hopByTable = new Map<string, NonNullable<SnapshotSpec["hop"]>>();const fkMap = await getFkMap(client);for (const entry of entries) {@@ -433,6 +434,7 @@ async function applyFkSnapshots(colsByTable.set(spec.table, cols);companyScopedByTable.set(spec.table, spec.hasCompanyId);+ if (spec.hop) hopByTable.set(spec.table, spec.hop);}}@@ -441,37 +443,106 @@ async function applyFkSnapshots(// (table, id) → { col: value, ... } — full snapshot row per idconst lookup = new Map<string, Record<string, unknown>>();- for (const [table, ids] of idsByTable) {- if (ids.size === 0) continue;- const cols = colsByTable.get(table);- if (!cols || cols.size === 0) continue;- const selectClause = ["id", ...cols].join(", ");-+ const fetchRows = async (+ table: string,+ selectCols: Iterable<string>,+ ids: readonly string[],+ tenantScoped: boolean+ ): Promise<Array<Record<string, unknown>> | null> => {try {let query = (client as any).from(table)- .select(selectClause)- .in("id", Array.from(ids));+ .select(["id", ...selectCols].join(", "))+ .in("id", ids);// Tenant-scope the lookup unless the target table has no companyId// (e.g. "user" — global identity).- if (companyScopedByTable.get(table) !== false) {+ if (tenantScoped) {query = query.eq("companyId", companyId);}const { data, error } = await query;-- if (error || !data) continue;-- for (const row of data as Array<Record<string, unknown>>) {- const rowId = row?.id;- if (typeof rowId !== "string") continue;- const snapshot: Record<string, unknown> = {};- for (const col of cols) snapshot[col] = row[col];- lookup.set(`${table}::${rowId}`, snapshot);+ if (error || !data) {+ // A rejected query (e.g. a tenancy filter on a table without+ // companyId) silently degrades the affected diffs to raw ids —+ // make that visible.+ log.error(`FK snapshot lookup failed for table "${table}"`, {+ error,+ tenantScoped+ });+ return null;}+ return data as Array<Record<string, unknown>>;} catch (err) {log.error(`FK snapshot lookup failed for table "${table}"`, {error: err});+ return null;+ }+ };++ for (const [table, ids] of idsByTable) {+ if (ids.size === 0) continue;+ const cols = colsByTable.get(table);+ if (!cols || cols.size === 0) continue;+ const tenantScoped = companyScopedByTable.get(table) !== false;+ const hop = hopByTable.get(table);++ if (hop) {+ // Junction target: the row the FK points at has no display columns of+ // its own. Stage 1 reads the hop column off the junction rows; stage 2+ // fetches the display columns from the hop table. Keyed in `lookup` by+ // the junction id so the ref loop below works unchanged.+ const junctionRows = await fetchRows(+ table,+ [hop.column],+ Array.from(ids),+ tenantScoped+ );+ if (!junctionRows) continue;++ const displayIds = new Set<string>();+ for (const row of junctionRows) {+ const displayId = row[hop.column];+ if (typeof displayId === "string") displayIds.add(displayId);+ }+ if (displayIds.size === 0) continue;++ const displayRows = await fetchRows(+ hop.table,+ cols,+ Array.from(displayIds),+ hop.hasCompanyId+ );+ if (!displayRows) continue;++ const displayById = new Map<string, Record<string, unknown>>();+ for (const row of displayRows) {+ if (typeof row.id === "string") displayById.set(row.id, row);+ }++ for (const junctionRow of junctionRows) {+ const junctionId = junctionRow.id;+ const displayId = junctionRow[hop.column];+ if (typeof junctionId !== "string" || typeof displayId !== "string") {+ continue;+ }+ const display = displayById.get(displayId);+ if (!display) continue;+ const snapshot: Record<string, unknown> = {};+ for (const col of cols) snapshot[col] = display[col];+ lookup.set(`${table}::${junctionId}`, snapshot);+ }+ continue;+ }++ const data = await fetchRows(table, cols, Array.from(ids), tenantScoped);+ if (!data) continue;++ for (const row of data) {+ const rowId = row?.id;+ if (typeof rowId !== "string") continue;+ const snapshot: Record<string, unknown> = {};+ for (const col of cols) snapshot[col] = row[col];+ lookup.set(`${table}::${rowId}`, snapshot);}}diff --git a/packages/jobs/src/inngest/functions/events/fk-snapshots.test.ts b/packages/jobs/src/inngest/functions/events/fk-snapshots.test.tsindex 6a6e73a371..204251d955 100644--- a/packages/jobs/src/inngest/functions/events/fk-snapshots.test.ts+++ b/packages/jobs/src/inngest/functions/events/fk-snapshots.test.ts@@ -1,5 +1,13 @@-import type { SnapshotFieldEntry } from "@carbon/database/audit.config";-import { fkDisplayRegistry } from "@carbon/database/audit.config";+import type {+ SnapshotFieldEntry,+ TableConfig+} from "@carbon/database/audit.config";+import {+ auditConfig,+ fkDisplayHops,+ fkDisplayRegistry,+ getSnapshotFields+} from "@carbon/database/audit.config";import { describe, expect, it } from "vitest";import type { FkMapRow } from "./fk-snapshots";import { fkMapKey, parseFkMapRows, resolveSnapshotSpec } from "./fk-snapshots";@@ -100,6 +108,56 @@ describe("resolveSnapshotSpec — automatic path (schema FK + registry)", () =>});});+describe("resolveSnapshotSpec — junction hops (fkDisplayHops)", () => {+ it("resolves a contact-junction FK to a two-stage hop spec", () => {+ // invoiceSupplierContactId → supplierContact (a link row with no name);+ // the display value is contact.fullName, one hop away.+ const fkMap = fkMapOf({+ tableName: "purchaseInvoice",+ columnName: "invoiceSupplierContactId",+ targetTable: "supplierContact",+ targetHasCompanyId: true+ });+ expect(+ resolveSnapshotSpec(+ "purchaseInvoice",+ "invoiceSupplierContactId",+ NO_OVERRIDES,+ fkMap+ )+ ).toEqual({+ table: "supplierContact",+ displayColumns: ["fullName"],+ hasCompanyId: true,+ // "contact" has no FK entry in this map, so tenancy defaults to+ // scoped — correct, contact is tenant-scoped.+ hop: { column: "contactId", table: "contact", hasCompanyId: true }+ });+ });++ it("prefers a per-column override over the hop", () => {+ const override: SnapshotFieldEntry = {+ column: "customerContactId",+ table: "customerContact",+ displayColumns: ["id"]+ };+ const fkMap = fkMapOf({+ tableName: "salesOrder",+ columnName: "customerContactId",+ targetTable: "customerContact",+ targetHasCompanyId: true+ });+ const spec = resolveSnapshotSpec(+ "salesOrder",+ "customerContactId",+ new Map([["customerContactId", override]]),+ fkMap+ );+ expect(spec?.hop).toBeUndefined();+ expect(spec?.displayColumns).toEqual(["id"]);+ });+});+describe("resolveSnapshotSpec — overrides (declared snapshotFields)", () => {const override: SnapshotFieldEntry = {column: "supplierId",@@ -134,6 +192,36 @@ describe("resolveSnapshotSpec — overrides (declared snapshotFields)", () => {});});+ it("derives tenancy from other FKs to the same target when the override column has no constraint", () => {+ // salesOrder.salesPersonId has no FK constraint, but "user" appears as+ // the target of other schema FKs (createdBy etc.) — the override must+ // inherit its global (non-tenant) tenancy or the snapshot lookup would+ // filter "user" by a companyId column it doesn't have.+ const userOverride: SnapshotFieldEntry = {+ column: "salesPersonId",+ table: "user",+ displayColumns: ["fullName"]+ };+ const fkMap = fkMapOf({+ tableName: "salesOrder",+ columnName: "createdBy",+ targetTable: "user",+ targetHasCompanyId: false+ });+ expect(+ resolveSnapshotSpec(+ "salesOrder",+ "salesPersonId",+ new Map([["salesPersonId", userOverride]]),+ fkMap+ )+ ).toEqual({+ table: "user",+ displayColumns: ["fullName"],+ hasCompanyId: false+ });+ });+it("defaults to tenant-scoped when the override target disagrees with the schema FK", () => {const fkMap = fkMapOf({tableName: "purchaseOrder",@@ -152,6 +240,38 @@ describe("resolveSnapshotSpec — overrides (declared snapshotFields)", () => {});});+describe("fkDisplayHops / fkDisplayRegistry invariants", () => {+ const hopTables = Object.keys(fkDisplayHops);++ it("no table appears in both the hops and the registry", () => {+ // Resolution checks hops before the registry, so a table in both would+ // leave the registry entry as silently-dead config.+ for (const table of hopTables) {+ expect(+ (fkDisplayRegistry as Record<string, unknown>)[table],+ `"${table}" is in fkDisplayHops AND fkDisplayRegistry — hops win, so the registry entry is dead config; remove one of the two`+ ).toBeUndefined();+ }+ });++ it("no snapshotFields override targets a hop table", () => {+ // Overrides are single-hop: one pointing at a junction would freeze the+ // junction's raw columns, and its column set could collide with the+ // hop's in the same batched lookup. Point overrides at tables whose+ // display columns are reachable in one hop.+ for (const entity of Object.values(auditConfig.entities)) {+ for (const [tableName, tableConfig] of Object.entries(entity.tables)) {+ for (const snap of getSnapshotFields(tableConfig as TableConfig)) {+ expect(+ hopTables,+ `snapshotFields override ${tableName}.${snap.column} targets hop table "${snap.table}"`+ ).not.toContain(snap.table);+ }+ }+ }+ });+});+describe("fkDisplayRegistry", () => {it("covers every target the previously hand-declared snapshotFields used", () => {// The 7 tables the old per-FK allowlist pointed at — the registry mustdiff --git a/packages/jobs/src/inngest/functions/events/fk-snapshots.ts b/packages/jobs/src/inngest/functions/events/fk-snapshots.tsindex 80671e8e93..4b8c9c5380 100644--- a/packages/jobs/src/inngest/functions/events/fk-snapshots.ts+++ b/packages/jobs/src/inngest/functions/events/fk-snapshots.ts@@ -1,5 +1,11 @@-import type { SnapshotFieldEntry } from "@carbon/database/audit.config";-import { fkDisplayRegistry } from "@carbon/database/audit.config";+import type {+ FkDisplayHop,+ SnapshotFieldEntry+} from "@carbon/database/audit.config";+import {+ fkDisplayHops,+ fkDisplayRegistry+} from "@carbon/database/audit.config";/*** FK topology for the audited tables, discovered from the schema via the@@ -40,11 +46,16 @@ export function parseFkMapRows(/*** What to snapshot for one diff column: the FK target table, the display* columns to freeze, and whether the lookup can be tenant-scoped.+ *+ * When `hop` is set, `table` is a junction with no displayable columns of+ * its own: the handler reads `hop.column` off the junction row, then fetches+ * `displayColumns` from `hop.table` (tenant-scoped iff `hop.hasCompanyId`).*/export type SnapshotSpec = {table: string;displayColumns: readonly string[];hasCompanyId: boolean;+ hop?: { column: string; table: string; hasCompanyId: boolean };};/**@@ -54,10 +65,12 @@ export type SnapshotSpec = {* Precedence:* 1. A per-column `snapshotFields` override on the table config — explicit* display columns for this one FK.- * 2. Schema-discovered FK (fkMap) whose target table is in- * `fkDisplayRegistry` — the automatic path covering every FK.+ * 2. Schema-discovered FK (fkMap) whose target is a junction in+ * `fkDisplayHops` — two-stage resolution through the junction.+ * 3. Schema-discovered FK whose target table is in `fkDisplayRegistry` —+ * the automatic path covering every direct FK.*- * Nested diff keys ("notes.content") and non-FK columns miss both and+ * Nested diff keys ("notes.content") and non-FK columns miss all three and* resolve to null — the diff keeps its raw values.*/export function resolveSnapshotSpec(@@ -73,16 +86,36 @@ export function resolveSnapshotSpec(return {table: override.table,displayColumns: override.displayColumns,- // The override's target may differ from the schema FK's target (or the- // fkMap may be unavailable); only trust the fkMap's tenancy flag when- // it describes the same target table. Default to tenant-scoped — the- // behavior overrides always had.+ // The override's column may have no schema FK at all (overrides exist+ // precisely for constraint-less columns), so fall back to the tenancy+ // of ANY schema FK referencing the same target table — a global table+ // like "user" is global no matter which column points at it. Default+ // to tenant-scoped only when the fkMap has no knowledge of the target.hasCompanyId:- fk && fk.targetTable === override.table ? fk.targetHasCompanyId : true+ fk && fk.targetTable === override.table+ ? fk.targetHasCompanyId+ : (targetTenancy(fkMap, override.table) ?? true)};}if (!fk) return null;++ const hop = (fkDisplayHops as Record<string, FkDisplayHop | undefined>)[+ fk.targetTable+ ];+ if (hop) {+ return {+ table: fk.targetTable,+ displayColumns: hop.displayColumns,+ hasCompanyId: fk.targetHasCompanyId,+ hop: {+ column: hop.column,+ table: hop.table,+ hasCompanyId: targetTenancy(fkMap, hop.table) ?? true+ }+ };+ }+const displayColumns = (fkDisplayRegistry as Record<string, readonly string[] | undefined>)[fk.targetTable];@@ -94,3 +127,15 @@ export function resolveSnapshotSpec(hasCompanyId: fk.targetHasCompanyId};}++/**+ * Tenancy of a target table according to any schema FK that references it,+ * regardless of which column does the referencing. Undefined when no FK in+ * the map points at the table.+ */+function targetTenancy(fkMap: FkMap, table: string): boolean | undefined {+ for (const entry of fkMap.values()) {+ if (entry.targetTable === table) return entry.targetHasCompanyId;+ }+ return undefined;+}