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
Added fk snapshots to audit logs
Gaurav Bhatt049ccba05e87
diff --git a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsxindex 62b5a0d90e..ed1d3c69f8 100644--- a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx+++ b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx@@ -282,32 +282,9 @@ const AuditLogEntryCard = memo(({ entry }: AuditLogEntryCardProps) => {</p>{diffKeys.length > 0 ? (<div className="space-y-1">- {diffKeys.map((key) => {- const change = entry.diff![key];- return (- <div- key={key}- className="flex items-center gap-2 font-mono text-sm py-1"- >- <span className="text-muted-foreground font-medium min-w-[120px]">- {key}:- </span>- {change.old !== undefined && (- <span className="px-2 py-0.5 rounded bg-red-500/10 text-red-500">- {formatValue(change.old)}- </span>- )}- {change.old !== undefined && change.new !== undefined && (- <span className="text-muted-foreground">→</span>- )}- {change.new !== undefined && (- <span className="px-2 py-0.5 rounded bg-green-500/10 text-green-500">- {formatValue(change.new)}- </span>- )}- </div>- );- })}+ {diffKeys.map((key) => (+ <ChangeRow key={key} columnKey={key} change={entry.diff![key]} />+ ))}</div>) : (<p className="text-sm text-muted-foreground italic">@@ -336,3 +313,171 @@ function formatValue(value: unknown): string {return String(value);return JSON.stringify(value);}++// Convert a column name into a Linear-style human label. When a snapshot+// exists, strip the trailing `Id` so a FK column reads as its referenced+// entity (e.g. `triggerProcessId` → `Trigger Process`). Without a+// snapshot, preserve the column name as-is so the raw column is still+// recognizable for forensic queries.+function humanizeColumnKey(key: string, hasSnapshot: boolean): string {+ const normalized = hasSnapshot && key.endsWith("Id") ? key.slice(0, -2) : key;+ return normalized+ .replace(/([A-Z])/g, " $1")+ .replace(/^./, (c) => c.toUpperCase())+ .trim();+}++// Pick the snapshot value for a given snapshot column from old or new sides.+function snapshotValue(+ snapshot: Record<string, unknown> | undefined,+ col: string+): unknown {+ return snapshot && col in snapshot ? snapshot[col] : undefined;+}++// 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.+function ChangePill({+ value,+ display,+ variant+}: {+ value: unknown;+ display?: unknown;+ variant: "old" | "new";+}) {+ const hasDisplay = display !== undefined && display !== null;+ const text = hasDisplay ? formatValue(display) : formatValue(value);+ const className = cn(+ "px-2 py-0.5 rounded",+ !hasDisplay && "font-mono",+ variant === "old"+ ? "bg-red-500/10 text-red-500"+ : "bg-green-500/10 text-green-500"+ );+ const tooltip = hasDisplay && typeof value === "string" ? value : undefined;+ return (+ <span className={className} title={tooltip}>+ {text}+ </span>+ );+}++// One labeled side-by-side row: "label [old] → [new]". Used for both+// the top-level column rows and the indented sub-rows under a multi-field+// snapshot header.+function ChangeLine({+ label,+ oldValue,+ newValue,+ oldDisplay,+ newDisplay,+ indent+}: {+ label: string;+ oldValue: unknown;+ newValue: unknown;+ oldDisplay?: unknown;+ newDisplay?: unknown;+ indent?: boolean;+}) {+ return (+ <div+ className={cn("flex items-center gap-2 text-sm py-1", indent && "pl-4")}+ >+ <span className="text-muted-foreground font-medium min-w-[120px]">+ {label}+ </span>+ {oldValue !== undefined && (+ <ChangePill value={oldValue} display={oldDisplay} variant="old" />+ )}+ {oldValue !== undefined && newValue !== undefined && (+ <span className="text-muted-foreground">→</span>+ )}+ {newValue !== undefined && (+ <ChangePill value={newValue} display={newDisplay} variant="new" />+ )}+ </div>+ );+}++// Renders one row of the diff. Branches on snapshot key count:+// • no snapshot → raw column name + mono pill (numbers, booleans, ids)+// • single-key snap → humanized FK label + Linear pill (name primary,+// id on hover)+// • 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({+ columnKey,+ change+}: {+ columnKey: string;+ change: import("@carbon/database/audit.types").AuditDiffEntry;+}) {+ const oldSnap = change.snapshot?.old;+ const newSnap = change.snapshot?.new;+ const snapKeys = new Set<string>([+ ...Object.keys(oldSnap ?? {}),+ ...Object.keys(newSnap ?? {})+ ]);+ const hasSnapshot = snapKeys.size > 0;+ const label = humanizeColumnKey(columnKey, hasSnapshot);++ // Path 1 — no snapshot. Same as before: one row, raw value pill.+ if (!hasSnapshot) {+ return (+ <ChangeLine label={label} oldValue={change.old} newValue={change.new} />+ );+ }++ // Path 2 — single snapshot column. Inline Linear pill, id on hover.+ if (snapKeys.size === 1) {+ const [col] = Array.from(snapKeys);+ return (+ <ChangeLine+ label={label}+ oldValue={change.old}+ newValue={change.new}+ oldDisplay={snapshotValue(oldSnap, col)}+ newDisplay={snapshotValue(newSnap, col)}+ />+ );+ }++ // Path 3 — multi-column snapshot. The snapshot fields disambiguate, so+ // 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}`;+ })();+ return (+ <div className="py-1">+ <div+ className="text-sm text-muted-foreground font-medium"+ title={idTooltip}+ >+ {label}+ </div>+ <div className="space-y-1 mt-1">+ {Array.from(snapKeys).map((col) => (+ <ChangeLine+ key={col}+ label={humanizeColumnKey(col, false)}+ oldValue={snapshotValue(oldSnap, col)}+ newValue={snapshotValue(newSnap, col)}+ indent+ />+ ))}+ </div>+ </div>+ );+}diff --git a/apps/erp/app/modules/items/ui/ItemRules/ItemRuleAssignments.tsx b/apps/erp/app/modules/items/ui/ItemRules/ItemRuleAssignments.tsxindex 78395c337e..4ae6ff8132 100644--- a/apps/erp/app/modules/items/ui/ItemRules/ItemRuleAssignments.tsx+++ b/apps/erp/app/modules/items/ui/ItemRules/ItemRuleAssignments.tsx@@ -168,14 +168,13 @@ export default function ItemRuleAssignments({<HStack className="gap-2">{availableOptions.length > 0 && (<Combobox- size="sm"value=""options={availableOptions}onChange={handleAssign}placeholder={t`Add from library…`}/>)}- <Button asChild variant="secondary" size="sm">+ <Button asChild><Link to={path.to.newItemRule}><Trans>Add rule</Trans></Link>@@ -315,18 +314,12 @@ function EmptyState({{availableOptions.length > 0 ? (<><Combobox- size="sm"value=""options={availableOptions}onChange={onAssign}placeholder={t`Add from library…`}/>- <Button- asChild- variant="secondary"- size="sm"- leftIcon={<LuPlus />}- >+ <Button asChild variant="secondary" leftIcon={<LuPlus />}><Link to={path.to.newItemRule}><Trans>Create new rule</Trans></Link>@@ -334,17 +327,12 @@ function EmptyState({</>) : (<>- <Button- asChild- variant="secondary"- size="sm"- leftIcon={<LuLibrary />}- >+ <Button asChild variant="secondary" leftIcon={<LuLibrary />}><Link to={path.to.itemRules}><Trans>Browse library</Trans></Link></Button>- <Button asChild size="sm" leftIcon={<LuPlus />}>+ <Button asChild leftIcon={<LuPlus />}><Link to={path.to.newItemRule}><Trans>Create new rule</Trans></Link>diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.tsindex b57bfdabb5..869c9014b9 100644--- a/packages/database/src/audit.config.ts+++ b/packages/database/src/audit.config.ts@@ -47,23 +47,53 @@ export type ColumnOf<T extends TableName> = Extract<* List columns here to surface their initial values. Only meaningful on* tables that log INSERTs (today: root tables).*+ * `snapshotFields` declares FK columns whose target row's display values+ * should be captured into the diff at write time. The audit handler resolves+ * each listed column's id against the target table and stores the picked+ * columns under `snapshot.old` / `snapshot.new` on the diff entry. The+ * snapshot is frozen in the audit row forever — historical accuracy is+ * preserved if the FK target is later renamed or deleted.+ ** Each variant declares `createFields` directly (rather than sharing a base* via intersection) so TS can narrow `T` — and autocomplete column names —* inside object-literal config entries.*/+type SnapshotFields<T extends TableName> = {+ [Col in ColumnOf<T>]?: {+ [Target in TableName]: {+ table: Target;+ displayColumns: readonly ColumnOf<Target>[];+ };+ }[TableName];+};++/**+ * Flattened view of one snapshot declaration, returned by+ * `getSnapshotFields`. Lives at type-level so consumers (the audit handler)+ * can iterate without re-parsing the typed config.+ */+export type SnapshotFieldEntry = {+ column: string;+ table: string;+ displayColumns: readonly string[];+};+type RootTable<T extends TableName> = {role: "root";createFields?: readonly ColumnOf<T>[];+ snapshotFields?: SnapshotFields<T>;};type ExtensionTable<T extends TableName> = {role: "extension";createFields?: readonly ColumnOf<T>[];+ snapshotFields?: SnapshotFields<T>;};type ChildTable<T extends TableName> = {entityIdColumn: ColumnOf<T>;createFields?: readonly ColumnOf<T>[];+ snapshotFields?: SnapshotFields<T>;};/**@@ -84,6 +114,7 @@ type IndirectResolve = {type IndirectTable<T extends TableName> = {resolve: IndirectResolve;createFields?: readonly ColumnOf<T>[];+ snapshotFields?: SnapshotFields<T>;};export type TableConfig<T extends TableName = TableName> =@@ -180,7 +211,10 @@ export const auditConfig = {"triggerProcessId","triggerTiming","calculateFromBom"- ]+ ],+ snapshotFields: {+ triggerProcessId: { table: "process", displayColumns: ["name"] }+ }}}},@@ -507,6 +541,33 @@ export function getCreateFields(config: TableConfig): readonly string[] {return config.createFields ?? [];}+/**+ * FK columns on this table whose target row's display values should be+ * snapshotted into the diff at write time. Each entry maps a column name+ * to its target table and the columns on that table to read as the human+ * display values. A single-column list yields a Linear-style inline pill+ * in the audit drawer; a multi-column list renders as an expanded section.+ */+export function getSnapshotFields(+ config: TableConfig+): readonly SnapshotFieldEntry[] {+ const snapshot = config.snapshotFields;+ if (!snapshot) return [];+ const entries: SnapshotFieldEntry[] = [];+ for (const [column, spec] of Object.entries(snapshot) as [+ string,+ { table: string; displayColumns: readonly string[] } | undefined+ ][]) {+ if (!spec) continue;+ entries.push({+ column,+ table: spec.table,+ displayColumns: spec.displayColumns+ });+ }+ return entries;+}+/** @deprecated Use isAuditableTable instead */export function isAuditableEntity(table: string): boolean {return isAuditableTable(table);diff --git a/packages/database/src/audit.types.ts b/packages/database/src/audit.types.tsindex 45711ab11c..26bd9a079e 100644--- a/packages/database/src/audit.types.ts+++ b/packages/database/src/audit.types.ts@@ -21,10 +21,23 @@ export interface AuditMetadata {* Both `old` and `new` are optional: INSERT entries populated via a table's* `createFields` config only include `new`, and the UI hides the "old" pill* when the key is absent.+ *+ * `snapshot` carries frozen values from the FK target row for columns+ * declared in `snapshotFields`. Captured at write time so the row is+ * self-contained — renaming or deleting the FK target later does not+ * rewrite history. The nested `old` / `new` mirrors the parent's old/new+ * pair, recursively. Each key inside `snapshot.old` / `snapshot.new`+ * corresponds to one column listed in `displayColumns`. The renderer+ * switches presentation based on key count: a single key renders inline;+ * multiple keys render as an expanded section.*/export interface AuditDiffEntry {old?: unknown;new?: unknown;+ snapshot?: {+ old?: Record<string, unknown>;+ new?: Record<string, unknown>;+ };}/**diff --git a/packages/jobs/src/inngest/functions/events/audit.ts b/packages/jobs/src/inngest/functions/events/audit.tsindex d58b6fac99..1f75d90fda 100644--- a/packages/jobs/src/inngest/functions/events/audit.ts+++ b/packages/jobs/src/inngest/functions/events/audit.ts@@ -1,8 +1,10 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";+import type { TableConfig } from "@carbon/database/audit.config";import {auditConfig,getCreateFields,getEntityConfigsForTable,+ getSnapshotFields,isAuditableTable,isChildTable,isExtensionTable,@@ -362,6 +364,11 @@ export const auditFunction = inngest.createFunction(}}+ // Snapshot FK target display values into each diff before insert.+ // Frozen at write time — renames/deletes of the FK target do not+ // rewrite history.+ await applyFkSnapshots(client, companyId, entries);+// Batch insert entries using RPCif (entries.length > 0) {const { data: insertedCount, error } = await (@@ -392,3 +399,132 @@ export const auditFunction = inngest.createFunction(return results;});++/**+ * For every entry whose tableConfig declares `snapshotFields`, look up the+ * FK target's display columns and freeze them onto the diff entry under+ * `snapshot.old` / `snapshot.new`. One batched query per target table —+ * proportional to distinct FK targets, not to entries.+ */+async function applyFkSnapshots(+ client: ReturnType<typeof getCarbonServiceRole>,+ companyId: string,+ entries: CreateAuditLogEntry[]+): Promise<void> {+ type Ref = {+ diffEntry: {+ old?: unknown;+ new?: unknown;+ snapshot?: {+ old?: Record<string, unknown>;+ new?: Record<string, unknown>;+ };+ };+ table: string;+ displayColumns: readonly string[];+ };++ const refs: Ref[] = [];+ const idsByTable = new Map<string, Set<string>>();+ const colsByTable = new Map<string, Set<string>>();++ for (const entry of entries) {+ if (!entry.diff) continue;+ const configs = getEntityConfigsForTable(entry.tableName).filter(+ (c) => c.entityType === entry.entityType+ );+ for (const { tableConfig } of configs) {+ const snapshots = getSnapshotFields(tableConfig as TableConfig);+ for (const snap of snapshots) {+ const change = entry.diff[snap.column];+ if (!change) continue;+ refs.push({+ diffEntry: change,+ table: snap.table,+ displayColumns: snap.displayColumns+ });++ const ids = idsByTable.get(snap.table) ?? new Set<string>();+ if (typeof change.old === "string") ids.add(change.old);+ if (typeof change.new === "string") ids.add(change.new);+ idsByTable.set(snap.table, ids);++ const cols = colsByTable.get(snap.table) ?? new Set<string>();+ for (const c of snap.displayColumns) cols.add(c);+ colsByTable.set(snap.table, cols);+ }+ }+ }++ if (refs.length === 0) return;++ // (table, id) → { col: value, ... } — full snapshot row per id+ const 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(", ");++ try {+ const { data, error } = await (client as any)+ .from(table)+ .select(selectClause)+ .eq("companyId", companyId)+ .in("id", Array.from(ids));++ 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);+ }+ } catch (err) {+ console.error(`FK snapshot lookup failed for table "${table}":`, err);+ }+ }++ // Pick only the columns this ref asked for. Multiple refs can share a+ // target table but request different subsets; per-ref filtering keeps+ // each diff entry's snapshot scoped to what the config declared.+ const pickSnapshot = (+ fullSnapshot: Record<string, unknown> | undefined,+ displayColumns: readonly string[]+ ): Record<string, unknown> | undefined => {+ if (!fullSnapshot) return undefined;+ const picked: Record<string, unknown> = {};+ for (const col of displayColumns) {+ if (col in fullSnapshot) picked[col] = fullSnapshot[col];+ }+ return Object.keys(picked).length > 0 ? picked : undefined;+ };++ for (const ref of refs) {+ const oldVal = ref.diffEntry.old;+ const newVal = ref.diffEntry.new;+ const oldSnap =+ typeof oldVal === "string"+ ? pickSnapshot(+ lookup.get(`${ref.table}::${oldVal}`),+ ref.displayColumns+ )+ : undefined;+ const newSnap =+ typeof newVal === "string"+ ? pickSnapshot(+ lookup.get(`${ref.table}::${newVal}`),+ ref.displayColumns+ )+ : undefined;+ if (oldSnap || newSnap) {+ ref.diffEntry.snapshot = {+ ...(oldSnap && { old: oldSnap }),+ ...(newSnap && { new: newSnap })+ };+ }+ }+}