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(audit): suppress empty-to-empty diff noise, extract pure diff module
naveenkashe41b1b95525c
diff --git a/.claude/rules/audit-log-system.md b/.claude/rules/audit-log-system.mdindex 4fa5e4f22c..638d217af4 100644--- a/.claude/rules/audit-log-system.md+++ b/.claude/rules/audit-log-system.md@@ -66,7 +66,7 @@ DB triggers added via `attach_event_trigger(...)` push table changes onto a PGMQ`handlerType = 'AUDIT'`. The queue dispatcher (`packages/jobs/src/inngest/.../queue.ts`) batches AUDITrecords and emits `carbon/event-audit`. `auditFunction` in`packages/jobs/src/inngest/functions/events/audit.ts` (Inngest id `event-handler-audit`) computes diffs-(`computeDiff` / `computeCreateDiff` / `computeNestedDiff`, honoring `skipFields`), resolves FK snapshots+(`computeDiff` / `computeCreateDiff` / `computeNestedDiff` in `events/diff.ts` — pure, unit-tested; honors `skipFields` and suppresses empty↔empty transitions like `null → {}` / `null → ""`), resolves FK snapshots(`applyFkSnapshots`: FK topology from `get_foreign_key_map` cached per process, display columns from`fkDisplayRegistry`, override precedence in `events/fk-snapshots.ts` → `resolveSnapshotSpec`, one batchedlookup per target table), and writes via `client.rpc("insert_audit_log_batch", { p_company_id, p_entries })`.diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex a46dfa6892..5ac877cc9b 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -83941,6 +83941,66 @@ export default {tags: ["(rpc) update_receipt_line_serial_tracking"]}},+ "/rpc/get_foreign_key_map": {+ get: {+ parameters: [+ {+ format: "text[]",+ in: "query",+ name: "p_table_names",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_foreign_key_map"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_table_names: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ }+ },+ required: ["p_table_names"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_foreign_key_map"]+ }+ },"/rpc/get_ar_aging": {post: {parameters: [@@ -84903,6 +84963,63 @@ export default {tags: ["(rpc) resolve_shelf_life_start_for_receipt"]}},+ "/rpc/get_primary_key_columns": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "p_table_name",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_primary_key_columns"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_table_name: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_table_name"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_primary_key_columns"]+ }+ },"/rpc/check_api_key_rate_limit": {post: {parameters: [diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex d1edeacef0..2cb72fa51a 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -67678,7 +67678,7 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -67692,7 +67692,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -68240,14 +68240,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -72202,6 +72202,15 @@ export type Database = {tableName: string}[]}+ get_foreign_key_map: {+ Args: { p_table_names: string[] }+ Returns: {+ columnName: string+ tableName: string+ targetHasCompanyId: boolean+ targetTable: string+ }[]+ }get_inventory_quantities: {Args: { company_id: string; item_id?: string; location_id: string }Returns: {diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex d1edeacef0..2cb72fa51a 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -67678,7 +67678,7 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -67692,7 +67692,7 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -68240,14 +68240,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -72202,6 +72202,15 @@ export type Database = {tableName: string}[]}+ get_foreign_key_map: {+ Args: { p_table_names: string[] }+ Returns: {+ columnName: string+ tableName: string+ targetHasCompanyId: boolean+ targetTable: string+ }[]+ }get_inventory_quantities: {Args: { company_id: string; item_id?: string; location_id: string }Returns: {diff --git a/packages/jobs/src/inngest/functions/events/audit.ts b/packages/jobs/src/inngest/functions/events/audit.tsindex 593951afd4..7a477d662c 100644--- a/packages/jobs/src/inngest/functions/events/audit.ts+++ b/packages/jobs/src/inngest/functions/events/audit.ts@@ -4,7 +4,6 @@ import type {TableConfig} from "@carbon/database/audit.config";import {- auditConfig,getAuditableTableNames,getCreateFields,getEntityConfigsForTable,@@ -20,9 +19,10 @@ import type {CreateAuditLogEntry} from "@carbon/database/audit.types";import { getLogger } from "@carbon/logger";-import { groupBy, tiptapToText } from "@carbon/utils";+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 { parseFkMapRows, resolveSnapshotSpec } from "./fk-snapshots";@@ -48,161 +48,6 @@ const AuditPayloadSchema = z.object({export type AuditPayload = z.infer<typeof AuditPayloadSchema>;-/**- * Whether a diff key should be excluded from the audit log. Matches both- * top-level columns (`"embedding"`) and any nested suffix (`"foo.embedding"`)- * so vector / metadata columns don't leak when they appear inside JSON- * containers or under createField allowlists.- */-function isSkippedAuditKey(key: string): boolean {- const skip = auditConfig.skipFields as readonly string[];- for (let i = 0; i < skip.length; i++) {- const s = skip[i]!;- if (key === s || key.endsWith(`.${s}`)) return true;- }- return false;-}--/**- * Rich-text (Tiptap) JSONB columns like `internalNotes` / `externalNotes`- * store a ProseMirror document. Diffing them structurally produces noise- * (`notes.content: [...]`), so they are treated as atomic values and stored- * as extracted plain text.- */-function isTiptapDoc(value: unknown): boolean {- return (- typeof value === "object" &&- value !== null &&- !Array.isArray(value) &&- (value as { type?: unknown }).type === "doc"- );-}--/**- * Normalize a rich-text column value to plain text. Notes columns default to- * `{}` before the first edit, so an empty object — like a doc with no text —- * reads as "" (empty notes), not as a JSON literal.- */-function richTextToText(value: unknown): string {- if (isTiptapDoc(value)) {- // Malformed doc JSON must degrade to "", not throw — an unhandled throw- // here poisons the event batch and Inngest retries it forever.- try {- return tiptapToText(value as Parameters<typeof tiptapToText>[0]);- } catch {- return "";- }- }- if (typeof value === "string") return value;- return "";-}--/**- * Compute the diff between old and new record values.- */-function computeDiff(- old: Record<string, unknown>,- newRecord: Record<string, unknown>-): AuditDiff | null {- const diff: AuditDiff = {};-- const allKeys = new Set([...Object.keys(old), ...Object.keys(newRecord)]);-- for (const key of allKeys) {- if (isSkippedAuditKey(key)) continue;-- const oldValue = old[key];- const newValue = newRecord[key];-- if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {- if (isTiptapDoc(oldValue) || isTiptapDoc(newValue)) {- const oldText = richTextToText(oldValue);- const newText = richTextToText(newValue);- // Equal text on both sides means an empty↔empty or formatting-only- // change — not worth an audit row. An empty side is omitted so a- // first edit renders as a value being set, not "{} → text".- if (oldText !== newText) {- diff[key] = {- ...(oldText !== "" && { old: oldText }),- ...(newText !== "" && { new: newText })- };- }- } else if (- typeof oldValue === "object" &&- oldValue !== null &&- typeof newValue === "object" &&- newValue !== null &&- !Array.isArray(oldValue) &&- !Array.isArray(newValue)- ) {- const nestedDiff = computeNestedDiff(- oldValue as Record<string, unknown>,- newValue as Record<string, unknown>,- key- );- Object.assign(diff, nestedDiff);- } else {- diff[key] = { old: oldValue, new: newValue };- }- }- }-- return Object.keys(diff).length > 0 ? diff : null;-}--/**- * Build a diff for INSERT events from an allowlist of columns.- * Returns null when no fields are configured or none are present on the record.- * Globally-skipped fields (e.g. `embedding`) are dropped even if listed in- * `createFields` so vector / metadata noise can't leak into CREATE diffs.- */-function computeCreateDiff(- newRecord: Record<string, unknown>,- createFields: readonly string[]-): AuditDiff | null {- if (createFields.length === 0) return null;-- const diff: AuditDiff = {};- for (const field of createFields) {- if (isSkippedAuditKey(field)) continue;- if (field in newRecord) {- const value = newRecord[field];- if (isTiptapDoc(value)) {- const text = richTextToText(value);- if (text !== "") diff[field] = { new: text };- } else {- diff[field] = { new: value };- }- }- }-- return Object.keys(diff).length > 0 ? diff : null;-}--function computeNestedDiff(- old: Record<string, unknown>,- newRecord: Record<string, unknown>,- prefix: string-): AuditDiff {- const diff: AuditDiff = {};-- const allKeys = new Set([...Object.keys(old), ...Object.keys(newRecord)]);-- for (const key of allKeys) {- const fullKey = `${prefix}.${key}`;- if (isSkippedAuditKey(fullKey)) continue;-- const oldValue = old[key];- const newValue = newRecord[key];-- if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {- diff[fullKey] = { old: oldValue, new: newValue };- }- }-- return diff;-}-type AuditRpcClient = {rpc(fn: "insert_audit_log_batch",diff --git a/packages/jobs/src/inngest/functions/events/diff.test.ts b/packages/jobs/src/inngest/functions/events/diff.test.tsnew file mode 100644index 0000000000..0183ce6c6a--- /dev/null+++ b/packages/jobs/src/inngest/functions/events/diff.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it } from "vitest";+import { computeDiff } from "./diff";++// Pins the empty-value guard in computeDiff: a form's first save writes ""+// / {} / [] over DB nulls for every untouched field, and those must not+// produce audit noise ("Custom Fields: null → {}", "Tracking Number:+// null → "). Real transitions in or out of a value must keep logging.++describe("computeDiff — empty↔empty transitions are suppressed", () => {+ it("skips null → {} (customFields on first save)", () => {+ expect(+ computeDiff({ customFields: null }, { customFields: {} })+ ).toBeNull();+ });++ it('skips null → "" (untouched text input on first save)', () => {+ expect(+ computeDiff({ trackingNumber: null }, { trackingNumber: "" })+ ).toBeNull();+ });++ it('skips "" → null and {} → null (the reverse direction)', () => {+ expect(computeDiff({ a: "" }, { a: null })).toBeNull();+ expect(computeDiff({ b: {} }, { b: null })).toBeNull();+ });++ it("skips null → [] (array columns like tags)", () => {+ expect(computeDiff({ tags: null }, { tags: [] })).toBeNull();+ });++ it('skips undefined → "" (column absent from the old record)', () => {+ expect(computeDiff({}, { note: "" })).toBeNull();+ });+});++describe("computeDiff — real transitions still log", () => {+ it("logs empty → value (a value being set)", () => {+ expect(+ computeDiff({ trackingNumber: "" }, { trackingNumber: "1234" })+ ).toEqual({ trackingNumber: { old: "", new: "1234" } });+ expect(+ computeDiff({ paymentTermId: null }, { paymentTermId: "pt_1" })+ ).toEqual({ paymentTermId: { old: null, new: "pt_1" } });+ });++ it("logs value → empty (a value being cleared)", () => {+ expect(+ computeDiff({ trackingNumber: "1234" }, { trackingNumber: "" })+ ).toEqual({ trackingNumber: { old: "1234", new: "" } });+ });++ it("logs value → value", () => {+ expect(computeDiff({ status: "Draft" }, { status: "Released" })).toEqual({+ status: { old: "Draft", new: "Released" }+ });+ });++ it("does not treat falsy scalars as empty (0 and false are real values)", () => {+ expect(computeDiff({ qty: null }, { qty: 0 })).toEqual({+ qty: { old: null, new: 0 }+ });+ expect(computeDiff({ active: null }, { active: false })).toEqual({+ active: { old: null, new: false }+ });+ });++ it("suppresses empty↔empty nested keys but keeps real nested changes", () => {+ // customFields is an object on both sides → nested diff path+ expect(+ computeDiff(+ { customFields: { color: null, size: "L" } },+ { customFields: { color: "", size: "XL" } }+ )+ ).toEqual({ "customFields.size": { old: "L", new: "XL" } });+ });++ it("returns null when nothing changed at all", () => {+ expect(computeDiff({ a: 1 }, { a: 1 })).toBeNull();+ });+});diff --git a/packages/jobs/src/inngest/functions/events/diff.ts b/packages/jobs/src/inngest/functions/events/diff.tsnew file mode 100644index 0000000000..f347ca7ca0--- /dev/null+++ b/packages/jobs/src/inngest/functions/events/diff.ts@@ -0,0 +1,181 @@+import { auditConfig } from "@carbon/database/audit.config";+import type { AuditDiff } from "@carbon/database/audit.types";+import { tiptapToText } from "@carbon/utils";++// Pure diff computation for the audit handler. Kept free of Inngest / auth+// imports (which require env vars at import time) so it can be unit-tested+// directly — same pattern as ./fk-snapshots.ts.++/**+ * Whether a diff key should be excluded from the audit log. Matches both+ * top-level columns (`"embedding"`) and any nested suffix (`"foo.embedding"`)+ * so vector / metadata columns don't leak when they appear inside JSON+ * containers or under createField allowlists.+ */+function isSkippedAuditKey(key: string): boolean {+ const skip = auditConfig.skipFields as readonly string[];+ for (let i = 0; i < skip.length; i++) {+ const s = skip[i]!;+ if (key === s || key.endsWith(`.${s}`)) return true;+ }+ return false;+}++/**+ * Rich-text (Tiptap) JSONB columns like `internalNotes` / `externalNotes`+ * store a ProseMirror document. Diffing them structurally produces noise+ * (`notes.content: [...]`), so they are treated as atomic values and stored+ * as extracted plain text.+ */+function isTiptapDoc(value: unknown): boolean {+ return (+ typeof value === "object" &&+ value !== null &&+ !Array.isArray(value) &&+ (value as { type?: unknown }).type === "doc"+ );+}++/**+ * Normalize a rich-text column value to plain text. Notes columns default to+ * `{}` before the first edit, so an empty object — like a doc with no text —+ * reads as "" (empty notes), not as a JSON literal.+ */+function richTextToText(value: unknown): string {+ if (isTiptapDoc(value)) {+ // Malformed doc JSON must degrade to "", not throw — an unhandled throw+ // here poisons the event batch and Inngest retries it forever.+ try {+ return tiptapToText(value as Parameters<typeof tiptapToText>[0]);+ } catch {+ return "";+ }+ }+ if (typeof value === "string") return value;+ return "";+}++/**+ * Whether a value is "empty" for diff purposes: null/undefined, an empty+ * string, or an empty object/array. Forms submit `""` / `{}` / `[]` for+ * untouched fields whose DB value is null, so an empty↔empty transition+ * (e.g. `null → {}` on customFields, `null → ""` on a cleared text input)+ * describes no real change — without this guard every first save of a form+ * section logs a diff line per empty field.+ */+function isEmptyValue(value: unknown): boolean {+ if (value === null || value === undefined || value === "") return true;+ if (Array.isArray(value)) return value.length === 0;+ if (typeof value === "object") return Object.keys(value).length === 0;+ return false;+}++/**+ * Compute the diff between old and new record values.+ */+export function computeDiff(+ old: Record<string, unknown>,+ newRecord: Record<string, unknown>+): AuditDiff | null {+ const diff: AuditDiff = {};++ const allKeys = new Set([...Object.keys(old), ...Object.keys(newRecord)]);++ for (const key of allKeys) {+ if (isSkippedAuditKey(key)) continue;++ const oldValue = old[key];+ const newValue = newRecord[key];++ if (isEmptyValue(oldValue) && isEmptyValue(newValue)) continue;++ if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {+ if (isTiptapDoc(oldValue) || isTiptapDoc(newValue)) {+ const oldText = richTextToText(oldValue);+ const newText = richTextToText(newValue);+ // Equal text on both sides means an empty↔empty or formatting-only+ // change — not worth an audit row. An empty side is omitted so a+ // first edit renders as a value being set, not "{} → text".+ if (oldText !== newText) {+ diff[key] = {+ ...(oldText !== "" && { old: oldText }),+ ...(newText !== "" && { new: newText })+ };+ }+ } else if (+ typeof oldValue === "object" &&+ oldValue !== null &&+ typeof newValue === "object" &&+ newValue !== null &&+ !Array.isArray(oldValue) &&+ !Array.isArray(newValue)+ ) {+ const nestedDiff = computeNestedDiff(+ oldValue as Record<string, unknown>,+ newValue as Record<string, unknown>,+ key+ );+ Object.assign(diff, nestedDiff);+ } else {+ diff[key] = { old: oldValue, new: newValue };+ }+ }+ }++ return Object.keys(diff).length > 0 ? diff : null;+}++/**+ * Build a diff for INSERT events from an allowlist of columns.+ * Returns null when no fields are configured or none are present on the record.+ * Globally-skipped fields (e.g. `embedding`) are dropped even if listed in+ * `createFields` so vector / metadata noise can't leak into CREATE diffs.+ */+export function computeCreateDiff(+ newRecord: Record<string, unknown>,+ createFields: readonly string[]+): AuditDiff | null {+ if (createFields.length === 0) return null;++ const diff: AuditDiff = {};+ for (const field of createFields) {+ if (isSkippedAuditKey(field)) continue;+ if (field in newRecord) {+ const value = newRecord[field];+ if (isTiptapDoc(value)) {+ const text = richTextToText(value);+ if (text !== "") diff[field] = { new: text };+ } else {+ diff[field] = { new: value };+ }+ }+ }++ return Object.keys(diff).length > 0 ? diff : null;+}++function computeNestedDiff(+ old: Record<string, unknown>,+ newRecord: Record<string, unknown>,+ prefix: string+): AuditDiff {+ const diff: AuditDiff = {};++ const allKeys = new Set([...Object.keys(old), ...Object.keys(newRecord)]);++ for (const key of allKeys) {+ const fullKey = `${prefix}.${key}`;+ if (isSkippedAuditKey(fullKey)) continue;++ const oldValue = old[key];+ const newValue = newRecord[key];++ if (isEmptyValue(oldValue) && isEmptyValue(newValue)) continue;++ if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {+ diff[fullKey] = { old: oldValue, new: newValue };+ }+ }++ return diff;+}