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: cover remaining unserialized jsonb copies + add regression test

Samay Gandhic6728abb1382
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index d7d978e15e..f7b708c82a 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -28,7 +28,7 @@ import {
traverseQuoteMethod,
} from "../lib/methods.ts";
import { getFunctionLogger } from "../lib/logging.ts";
-import { toJson } from "../lib/json.ts";
+import { toJson, toJsonColumns } from "../lib/json.ts";
import { KyselyDatabase } from "../lib/postgres/index.ts";
import { importTypeScript } from "../lib/sandbox.ee.ts";
import { getStorageUnitId } from "../lib/storage-units.ts";
@@ -47,6 +47,16 @@ const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
const logger = getFunctionLogger("get-method");
+// quoteLine's jsonb columns — run through toJsonColumns() in quoteToQuote's per-line copy.
+const QUOTE_LINE_JSON_COLUMNS = [
+ "additionalCharges",
+ "configuration",
+ "customFields",
+ "externalNotes",
+ "internalNotes",
+ "priceTrace",
+] as const satisfies readonly (keyof Database["public"]["Tables"]["quoteLine"]["Row"])[];
+
// Stored configurator rules are user-authored JS that may still return legacy "Inside"/"Outside" operationType values.
const normalizeOperationType = (value: unknown) =>
(value === "Inside"
@@ -1063,7 +1073,7 @@ serve(async (req: Request) => {
processId,
op.operationSupplierProcessId
),
- workInstruction: (!node.data.isRoot || parts.workInstructions) ? op.workInstruction : {},
+ workInstruction: toJson((!node.data.isRoot || parts.workInstructions) ? op.workInstruction : {}),
targetQuantity,
operationQuantity,
companyId,
@@ -1939,7 +1949,7 @@ serve(async (req: Request) => {
op.operationSupplierProcessId
),
tags: op.tags ?? [],
- workInstruction: parts.workInstructions ? op.workInstruction : {},
+ workInstruction: toJson(parts.workInstructions ? op.workInstruction : {}),
targetQuantity,
operationQuantity,
companyId,
@@ -2772,7 +2782,7 @@ serve(async (req: Request) => {
),
operationMinimumCost: op.operationMinimumCost ?? 0,
tags: op.tags ?? [],
- workInstruction: (!node.data.isRoot || parts.workInstructions) ? op.workInstruction : {},
+ workInstruction: toJson((!node.data.isRoot || parts.workInstructions) ? op.workInstruction : {}),
companyId,
createdBy: userId,
customFields: {},
@@ -3336,7 +3346,7 @@ serve(async (req: Request) => {
op.operationSupplierProcessId
),
tags: op.tags ?? [],
- workInstruction: parts.workInstructions ? op.workInstruction : {},
+ workInstruction: toJson(parts.workInstructions ? op.workInstruction : {}),
companyId,
createdBy: userId,
customFields: {},
@@ -3753,7 +3763,7 @@ serve(async (req: Request) => {
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
tags: op.tags ?? [],
- workInstruction: parts.workInstructions ? op.workInstruction : {},
+ workInstruction: toJson(parts.workInstructions ? op.workInstruction : {}),
companyId,
createdBy: userId,
customFields: {},
@@ -4076,7 +4086,7 @@ serve(async (req: Request) => {
operationUnitCost: op.operationUnitCost ?? 0,
operationSupplierProcessId: op.operationSupplierProcessId,
tags: op.tags ?? [],
- workInstruction: parts.workInstructions ? op.workInstruction : {},
+ workInstruction: toJson(parts.workInstructions ? op.workInstruction : {}),
companyId,
createdBy: userId,
customFields: {},
@@ -4705,9 +4715,9 @@ serve(async (req: Request) => {
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
tags: op.tags ?? [],
- workInstruction: parts.workInstructions
- ? op.workInstruction
- : {},
+ workInstruction: toJson(
+ parts.workInstructions ? op.workInstruction : {}
+ ),
targetQuantity: opQuantities.targetQuantity,
// Fractional targets flow through; the scrap allowance is already whole
operationQuantity: opQuantities.totalWithScrap,
@@ -5282,7 +5292,7 @@ serve(async (req: Request) => {
await trx
.updateTable("jobOperation")
.set({
- workInstruction: procedure.data.content,
+ workInstruction: toJson(procedure.data.content),
procedureId: procedureId,
})
.where("id", "=", operationId)
@@ -5500,7 +5510,7 @@ serve(async (req: Request) => {
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
tags: op.tags ?? [],
- workInstruction: parts.workInstructions ? op.workInstruction : {},
+ workInstruction: toJson(parts.workInstructions ? op.workInstruction : {}),
companyId,
createdBy: userId,
customFields: {},
@@ -5819,7 +5829,7 @@ serve(async (req: Request) => {
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
tags: op.tags ?? [],
- workInstruction: parts.workInstructions ? op.workInstruction : {},
+ workInstruction: toJson(parts.workInstructions ? op.workInstruction : {}),
companyId,
createdBy: userId,
customFields: {},
@@ -6357,7 +6367,7 @@ serve(async (req: Request) => {
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
tags: op.tags ?? [],
- workInstruction: parts.workInstructions ? op.workInstruction : {},
+ workInstruction: toJson(parts.workInstructions ? op.workInstruction : {}),
targetQuantity: opQuantities.targetQuantity,
// Fractional targets flow through; the scrap allowance is already whole
operationQuantity: opQuantities.totalWithScrap,
@@ -6724,7 +6734,7 @@ serve(async (req: Request) => {
operationUnitCost: op.operationUnitCost ?? 0,
overheadRate: op.overheadRate,
tags: op.tags ?? [],
- workInstruction: parts.workInstructions ? op.workInstruction : {},
+ workInstruction: toJson(parts.workInstructions ? op.workInstruction : {}),
companyId,
createdBy: userId,
customFields: {},
@@ -7017,12 +7027,7 @@ serve(async (req: Request) => {
.insertInto("quoteLine")
.values({
...line,
- additionalCharges: toJson(line.additionalCharges),
- configuration: toJson(line.configuration),
- customFields: toJson(line.customFields),
- externalNotes: toJson(line.externalNotes),
- internalNotes: toJson(line.internalNotes),
- priceTrace: toJson(line.priceTrace),
+ ...toJsonColumns(line, QUOTE_LINE_JSON_COLUMNS),
quoteId: quote.id,
companyId,
})
@@ -7786,7 +7791,7 @@ async function insertProcedureDataForJobOperation(
await trx
.updateTable("jobOperation")
.set({
- workInstruction: procedure?.data?.content ?? {},
+ workInstruction: toJson(procedure?.data?.content ?? {}),
})
.where("id", "=", operationId)
.execute();
diff --git a/packages/database/supabase/functions/lib/json.test.ts b/packages/database/supabase/functions/lib/json.test.ts
index b1cfb01aec..bdf85347a3 100644
--- a/packages/database/supabase/functions/lib/json.test.ts
+++ b/packages/database/supabase/functions/lib/json.test.ts
@@ -1,5 +1,5 @@
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
-import { toJson } from "./json.ts";
+import { toJson, toJsonColumns } from "./json.ts";
// deno-postgres encodes a string parameter as raw text and an array as a
// Postgres array literal, so a JSON column only round-trips object values.
@@ -41,3 +41,55 @@ Deno.test("toJson: output always parses back to the input", () => {
assertEquals(JSON.parse(toJson(value) as string), value);
}
});
+
+// toJsonColumns is what a document copy (quoteToQuote's per-line copy in
+// get-method/index.ts) runs a source row through before spreading it into a
+// Kysely insert. This pins the exact regression: a quoteLine whose
+// jsonb columns were ever written as a bare string/array (legacy data, or an
+// API path typed `z.any()`) must still copy cleanly instead of failing the
+// whole quote duplication with "invalid input syntax for type json".
+Deno.test("toJsonColumns: serialises only the named columns, leaving the rest of the row untouched", () => {
+ const line = {
+ id: "qtl_1",
+ quoteId: "qt_1",
+ description: "A widget",
+ additionalCharges: ["legacy-array-instead-of-object"],
+ configuration: "legacy-string-instead-of-object",
+ customFields: { color: "red" },
+ externalNotes: "a plain string note",
+ internalNotes: null as unknown,
+ priceTrace: [{ step: "Markup", source: "Rule: x", amount: 12.5 }]
+ };
+
+ const result = toJsonColumns(line, [
+ "additionalCharges",
+ "configuration",
+ "customFields",
+ "externalNotes",
+ "internalNotes",
+ "priceTrace"
+ ] as const);
+
+ // Every named column comes back as valid JSON TEXT, regardless of the
+ // shape it was stored in — an array, a bare string, an object, or null.
+ assertEquals(result.additionalCharges, '["legacy-array-instead-of-object"]');
+ assertEquals(result.configuration, '"legacy-string-instead-of-object"');
+ assertEquals(result.customFields, '{"color":"red"}');
+ assertEquals(result.externalNotes, '"a plain string note"');
+ assertEquals(result.internalNotes, null);
+ assertEquals(
+ JSON.parse(result.priceTrace as string),
+ line.priceTrace
+ );
+
+ // Columns not named in the list are untouched by the call, so spreading
+ // `{ ...line, ...toJsonColumns(line, [...]) }` only overrides what's named.
+ assertEquals("id" in result, false);
+ assertEquals("description" in result, false);
+});
+
+Deno.test("toJsonColumns: an already-clean object column round-trips unchanged in meaning", () => {
+ const line = { customFields: { a: 1, b: [2, 3] } };
+ const result = toJsonColumns(line, ["customFields"] as const);
+ assertEquals(JSON.parse(result.customFields as string), line.customFields);
+});
diff --git a/packages/database/supabase/functions/lib/json.ts b/packages/database/supabase/functions/lib/json.ts
index ff403f9164..ecff1d36e2 100644
--- a/packages/database/supabase/functions/lib/json.ts
+++ b/packages/database/supabase/functions/lib/json.ts
@@ -19,3 +19,26 @@ export function toJson(value: unknown): string | null | undefined {
if (value === null || value === undefined) return value;
return JSON.stringify(value);
}
+
+/**
+ * Runs `toJson` over a fixed list of jsonb columns on a row read back from
+ * Supabase, for re-inserting that row (or a spread of it) through Kysely —
+ * e.g. `{ ...line, ...toJsonColumns(line, QUOTE_LINE_JSON_COLUMNS) }`.
+ *
+ * A document-copy that spreads a source row raw (`{...line, quoteId, companyId}`)
+ * silently regresses to the unserialised bug the day a new jsonb column is
+ * added to that table and the spread picks it up untouched. Naming the
+ * column list here, next to the call site, makes that list something a
+ * future column addition has to be checked against, and something a test can
+ * assert against directly.
+ */
+export function toJsonColumns<T extends Record<string, unknown>, K extends keyof T>(
+ row: T,
+ keys: readonly K[]
+): { [P in K]: string | null | undefined } {
+ const out = {} as { [P in K]: string | null | undefined };
+ for (const key of keys) {
+ out[key] = toJson(row[key]);
+ }
+ return out;
+}