Skip to content

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

fix(audit): composite-key event pairing, tiptap diffs, FK snapshots

naveenkasha8d5a762687a
diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.ts
index 5dd4d81c04..a9f5284571 100644
--- a/packages/database/src/audit.config.ts
+++ b/packages/database/src/audit.config.ts
@@ -141,7 +141,16 @@ export const auditConfig = {
customer: {
label: "Customer",
tables: {
- customer: { role: "root" },
+ customer: {
+ role: "root",
+ snapshotFields: {
+ customerTypeId: { table: "customerType", displayColumns: ["name"] },
+ customerStatusId: {
+ table: "customerStatus",
+ displayColumns: ["name"]
+ }
+ }
+ },
customerPayment: { role: "extension" }, // PK = customerId
customerShipping: { role: "extension" }, // PK = customerId
customerTax: { role: "extension" }, // PK = customerId
@@ -165,7 +174,12 @@ export const auditConfig = {
supplier: {
label: "Supplier",
tables: {
- supplier: { role: "root" },
+ supplier: {
+ role: "root",
+ snapshotFields: {
+ supplierTypeId: { table: "supplierType", displayColumns: ["name"] }
+ }
+ },
supplierPayment: { role: "extension" }, // PK = supplierId
supplierShipping: { role: "extension" }, // PK = supplierId
supplierTax: { role: "extension" }, // PK = supplierId
@@ -192,7 +206,12 @@ export const auditConfig = {
item: { role: "root" },
itemShelfLife: { role: "root" },
itemCost: { role: "extension" }, // PK = itemId
- itemPlanning: { role: "extension" }, // PK = itemId
+ itemPlanning: {
+ role: "extension", // unique on (itemId, locationId); entityId = itemId
+ snapshotFields: {
+ locationId: { table: "location", displayColumns: ["name"] }
+ }
+ },
itemReplenishment: { role: "extension" }, // PK = itemId
itemUnitSalePrice: { role: "extension" }, // PK = itemId
supplierPart: { entityIdColumn: "itemId" },
@@ -232,10 +251,47 @@ export const auditConfig = {
purchaseOrder: {
label: "Purchase Order",
tables: {
- purchaseOrder: { role: "root" },
+ purchaseOrder: {
+ role: "root",
+ snapshotFields: {
+ supplierId: { table: "supplier", displayColumns: ["name"] },
+ supplierLocationId: {
+ table: "supplierLocation",
+ displayColumns: ["name"]
+ }
+ }
+ },
purchaseOrderLine: { entityIdColumn: "purchaseOrderId" },
- purchaseOrderPayment: { role: "extension" }, // PK = purchaseOrderId
- purchaseOrderDelivery: { role: "extension" } // PK = purchaseOrderId
+ purchaseOrderPayment: {
+ role: "extension", // PK = purchaseOrderId
+ snapshotFields: {
+ paymentTermId: { table: "paymentTerm", displayColumns: ["name"] },
+ invoiceSupplierId: {
+ table: "supplier",
+ displayColumns: ["name"]
+ },
+ invoiceSupplierLocationId: {
+ table: "supplierLocation",
+ displayColumns: ["name"]
+ }
+ }
+ },
+ purchaseOrderDelivery: {
+ role: "extension", // PK = purchaseOrderId
+ snapshotFields: {
+ shippingMethodId: {
+ table: "shippingMethod",
+ displayColumns: ["name"]
+ },
+ shippingTermId: { table: "shippingTerm", displayColumns: ["name"] },
+ locationId: { table: "location", displayColumns: ["name"] },
+ customerId: { table: "customer", displayColumns: ["name"] },
+ customerLocationId: {
+ table: "customerLocation",
+ displayColumns: ["name"]
+ }
+ }
+ }
}
},
diff --git a/packages/database/supabase/migrations/20260717143448_fix-event-update-row-pairing.sql b/packages/database/supabase/migrations/20260717143448_fix-event-update-row-pairing.sql
new file mode 100644
index 0000000000..89c78db9a4
--- /dev/null
+++ b/packages/database/supabase/migrations/20260717143448_fix-event-update-row-pairing.sql
@@ -0,0 +1,211 @@
+-- Fix event-system UPDATE row pairing for tables with composite identity.
+--
+-- dispatch_event_batch() paired old/new transition rows by a SINGLE key column
+-- from get_primary_key_column(). For tables whose row identity is composite —
+-- e.g. "itemPlanning", unique on ("itemId", "locationId") with no PK — a single
+-- statement updating several rows of the same parent cross-joined old×new rows
+-- (every before-row paired with every after-row of the same item) and emitted
+-- spurious audit diffs, including phantom "locationId changed" entries. Bulk
+-- writers that trigger this exist today: the CSV importer updates all of an
+-- item's itemPlanning rows in one statement, as do the demand/production
+-- planning SQL functions.
+--
+-- Fix: pair on EVERY column of the table's primary key (or, when the table has
+-- no PK, its smallest unique index). recordId keeps using the legacy
+-- single-column resolver so audit entity resolution is unchanged.
+
+CREATE OR REPLACE FUNCTION public.get_primary_key_columns(p_table_name TEXT)
+RETURNS TEXT[]
+LANGUAGE plpgsql
+STABLE
+AS $$
+DECLARE
+ pk_columns TEXT[];
+BEGIN
+ -- All columns of the primary key
+ SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i.indisprimary;
+
+ -- No PK: all columns of the smallest unique index
+ IF pk_columns IS NULL THEN
+ SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indexrelid = (
+ SELECT i2.indexrelid
+ FROM pg_index i2
+ WHERE i2.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i2.indisunique
+ ORDER BY i2.indnkeyatts ASC
+ LIMIT 1
+ );
+ END IF;
+
+ -- Last resort: the legacy single-column resolver
+ IF pk_columns IS NULL OR array_length(pk_columns, 1) IS NULL THEN
+ pk_columns := ARRAY[public.get_primary_key_column(p_table_name)];
+ END IF;
+
+ RETURN pk_columns;
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+RETURNS trigger
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path TO 'public', 'pgmq', 'extensions'
+AS $function$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+ pk_column TEXT;
+ pk_join TEXT;
+ query_text TEXT;
+BEGIN
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ current_actor_id := auth.uid()::TEXT;
+ pk_column := public.get_primary_key_column(TG_TABLE_NAME);
+
+ -- Pair UPDATE transition rows on the table's full row identity, not just
+ -- the first key column — single-column pairing cross-joins rows on tables
+ -- with composite identity (see migration header).
+ SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')
+ INTO pk_join
+ FROM unnest(public.get_primary_key_columns(TG_TABLE_NAME)) AS col;
+
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ LOOP
+
+ IF TG_OP = 'INSERT' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', row_to_json(t)::jsonb,
+ ''old'', null,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+
+ ELSIF TG_OP = 'DELETE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', null,
+ ''old'', row_to_json(t)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_old t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', n.%I::TEXT,
+ ''new'', row_to_json(n)::jsonb,
+ ''old'', row_to_json(o)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new n
+ JOIN batched_old o ON %s
+ WHERE n."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
+ ', pk_column, pk_join);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+ END IF;
+
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ END IF;
+
+ END LOOP;
+
+ RETURN NULL;
+END;
+$function$;
diff --git a/packages/jobs/src/inngest/functions/events/audit.ts b/packages/jobs/src/inngest/functions/events/audit.ts
index d3afc2a1d0..d3658c645c 100644
--- a/packages/jobs/src/inngest/functions/events/audit.ts
+++ b/packages/jobs/src/inngest/functions/events/audit.ts
@@ -16,7 +16,7 @@ import type {
CreateAuditLogEntry
} from "@carbon/database/audit.types";
import { getLogger } from "@carbon/logger";
-import { groupBy } from "@carbon/utils";
+import { groupBy, tiptapToText } from "@carbon/utils";
import { z } from "zod";
import { inngest } from "../../client";
@@ -57,6 +57,34 @@ function isSkippedAuditKey(key: string): boolean {
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)) {
+ return tiptapToText(value as Parameters<typeof tiptapToText>[0]);
+ }
+ if (typeof value === "string") return value;
+ return "";
+}
+
/**
* Compute the diff between old and new record values.
*/
@@ -75,7 +103,19 @@ function computeDiff(
const newValue = newRecord[key];
if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
- if (
+ 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" &&
@@ -114,7 +154,13 @@ function computeCreateDiff(
for (const field of createFields) {
if (isSkippedAuditKey(field)) continue;
if (field in newRecord) {
- diff[field] = { new: newRecord[field] };
+ const value = newRecord[field];
+ if (isTiptapDoc(value)) {
+ const text = richTextToText(value);
+ if (text !== "") diff[field] = { new: text };
+ } else {
+ diff[field] = { new: value };
+ }
}
}