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(sales): serialise JSON columns copied through Kysely in quote conversions (#1635)

Naveen Kashyap6c139ecb9aa3
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 154117650c..b75f4b4327 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1551,3 +1551,13 @@ full-screen ERP route.
**Rule:** When a migration adds a nullable column and leaves existing rows NULL, every reader added in the same change must define what NULL means and handle it, or the migration must backfill. Keep the throw only where a DB constraint already guarantees the value (source-linked rows). Derive legacy values from the columns that did exist (`appliedAmount` at the applicable exchange rate) and cover the NULL case in the pure-function tests.
**Applies to:** `payment-funding.ts` reducers, any future column added to `invoiceSettlement`, `journalLine`, or other high-volume tables where a backfill is skipped.
+
+## A JSON column copied through Kysely on deno-postgres only survives as an object
+
+**Context:** Quote → sales order conversion (`convert` edge function) reads the quote with supabase-js and re-inserts its `internalNotes` / `externalNotes` into `salesOrder` through Kysely inside the transaction. One quote had `internalNotes` stored as a JSON string scalar rather than a tiptap document, written through an API path whose validator typed `notes` as `z.any()`.
+
+**Problem:** deno-postgres encodes query parameters by JS type, not by column type: an object is `JSON.stringify`ed, but a string is sent as raw text and an array as a Postgres array literal. A JSON string scalar therefore round-trips as unquoted text and Postgres rejects the insert with `invalid input syntax for type json`. The route sanitised the body, so Vercel only showed "Edge Function returned a non-2xx status code"; the real line was only in the Supabase function log. Every retry failed identically, and the same latent fault sat in RFQ → quote, supplier quote → PO, and quote revision copies.
+
+**Rule:** Two layers, both required. (1) Any `json`/`jsonb` value written through Kysely in an edge function goes through `lib/json.ts` `toJson()`, which pre-serialises every non-null shape so the wire value is valid JSON text. (2) A validator for a rich-text column is never `z.any()`; use the shared `optionalTiptapDoc` / `toTiptapDoc` in `shared.models.ts`, which turns text, a JSON-encoded doc, or a doc object into a tiptap document and rejects the rest. Put `.optional()` AFTER the transform or zod infers a required key. When an edge function fails opaquely, read the function's own log (Supabase management API `function_logs`), not the caller's.
+
+**Applies to:** `packages/database/supabase/functions/**` Kysely inserts of `internalNotes`, `externalNotes`, `customFields`, `priceTrace`, `configuration`, `additionalCharges`; every `*.models.ts` field that feeds a rich-text column (the purchasing `notes: z.any()` fields still need this).
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index b3a919d954..7a767c8f32 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1,5 +1,4 @@
import type { Database } from "@carbon/database";
-import { textToTiptap } from "@carbon/utils";
import { parseDate } from "@internationalized/date";
import { z } from "zod";
import { zfd } from "zod-form-data";
@@ -14,7 +13,8 @@ import {
methodType,
operationTypes,
procedureStepType,
- standardFactorType
+ standardFactorType,
+ toTiptapDoc
} from "../shared";
import type {
ItemOrderStatus,
@@ -1368,20 +1368,9 @@ export const assemblyInstructionVersionValidator = z.object({
*/
const optionalTiptapDescription = zfd
.text(z.string().optional())
- .transform((val): any => {
- if (val === undefined || val === "") return undefined;
- let parsed: unknown;
- try {
- parsed = JSON.parse(val);
- } catch {
- parsed = val;
- }
- // Always store a tiptap doc object, never a scalar string (jsonb scalar
- // strings break method copies) and never silently drop content to {}.
- if (typeof parsed === "string") return textToTiptap(parsed);
- if (parsed && typeof parsed === "object") return parsed;
- return textToTiptap(String(val));
- });
+ .transform((val): any =>
+ val === undefined || val === "" ? undefined : toTiptapDoc(val)
+ );
export const assemblyInstructionStepValidator = z
.object({
diff --git a/apps/erp/app/modules/sales/sales.models.test.ts b/apps/erp/app/modules/sales/sales.models.test.ts
new file mode 100644
index 0000000000..0d94a93b6f
--- /dev/null
+++ b/apps/erp/app/modules/sales/sales.models.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it, vi } from "vitest";
+
+// sales.models' module graph transitively loads @carbon/glossary and
+// @carbon/onboarding, both of which build Lingui `msg` descriptors at module
+// load. The macro isn't transformed under plain vitest, so raw `msg` throws.
+// Stub it to a plain string builder; the validator under test is untouched.
+vi.mock("@lingui/core/macro", () => ({
+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>
+ Array.isArray(strings)
+ ? strings.reduce(
+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),
+ ""
+ )
+ : String(strings)
+}));
+
+const { quoteValidator } = await import("./sales.models");
+
+// `quote.internalNotes` is a `json` column that the sales-order conversion
+// copies through Kysely. A bare string stored there (which `notes: z.any()`
+// allowed from the MCP / API tool) made every conversion of that quote fail
+// with `invalid input syntax for type json`. The validator must now turn
+// whatever a caller sends into a tiptap document object.
+
+const base = { customerId: "cust_1", locationId: "loc_1" };
+
+describe("quoteValidator.notes", () => {
+ it("stores plain-text notes as a tiptap document", () => {
+ const parsed = quoteValidator.parse({ ...base, notes: "rush order" });
+ expect(parsed.notes).toEqual({
+ type: "doc",
+ content: [
+ { type: "paragraph", content: [{ type: "text", text: "rush order" }] }
+ ]
+ });
+ });
+
+ it("keeps a tiptap document as sent", () => {
+ const notes = { type: "doc", content: [] };
+ expect(quoteValidator.parse({ ...base, notes }).notes).toEqual(notes);
+ });
+
+ it("leaves notes undefined when not sent", () => {
+ expect(quoteValidator.parse(base).notes).toBeUndefined();
+ });
+
+ it("rejects a non-document scalar instead of storing it", () => {
+ expect(quoteValidator.safeParse({ ...base, notes: 42 }).success).toBe(
+ false
+ );
+ });
+});
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index 9e3abfd636..b8a2aaed8e 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -9,6 +9,7 @@ import {
methodOperationOrders,
methodType,
operationTypes,
+ optionalTiptapDoc,
standardFactorType,
taxExemptionReasons
} from "../shared";
@@ -288,7 +289,7 @@ export const quoteValidator = z.object({
customerReference: zfd.text(z.string().optional()),
locationId: z.string().min(1, { message: "Location is required" }),
status: z.enum(quoteStatusType).optional(),
- notes: z.any().optional(),
+ notes: optionalTiptapDoc,
dueDate: zfd.text(z.string().optional()),
expirationDate: zfd.text(z.string().optional()),
currencyCode: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/shared/shared.models.test.ts b/apps/erp/app/modules/shared/shared.models.test.ts
new file mode 100644
index 0000000000..8caf92d4a5
--- /dev/null
+++ b/apps/erp/app/modules/shared/shared.models.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+import { optionalTiptapDoc, toTiptapDoc } from "./shared.models";
+
+// Rich-text columns are `json` and must hold a tiptap document OBJECT. A JSON
+// string scalar stored there later breaks every Kysely copy of the row
+// (deno-postgres sends a string parameter as raw text). These pin the one
+// coercion every writer goes through.
+
+const doc = {
+ type: "doc",
+ content: [{ type: "paragraph", content: [{ type: "text", text: "hi" }] }]
+};
+
+describe("toTiptapDoc", () => {
+ it("wraps plain text into a document", () => {
+ expect(toTiptapDoc("hi")).toEqual(doc);
+ });
+
+ it("keeps line breaks as paragraphs", () => {
+ expect(toTiptapDoc("a\nb")).toEqual({
+ type: "doc",
+ content: [
+ { type: "paragraph", content: [{ type: "text", text: "a" }] },
+ { type: "paragraph", content: [{ type: "text", text: "b" }] }
+ ]
+ });
+ });
+
+ it("parses a JSON-encoded document (form post)", () => {
+ expect(toTiptapDoc(JSON.stringify(doc))).toEqual(doc);
+ });
+
+ it("passes a document object through untouched (JSON body)", () => {
+ expect(toTiptapDoc(doc)).toBe(doc);
+ });
+
+ it("never returns a string, array, or scalar", () => {
+ for (const value of ['"quoted"', "123", "[1,2]", 7, true, ["x"]]) {
+ const out = toTiptapDoc(value);
+ expect(typeof out).toBe("object");
+ expect(Array.isArray(out)).toBe(false);
+ expect(out.type).toBe("doc");
+ }
+ });
+
+ it("keeps text that merely looks like JSON, characters intact", () => {
+ // `123` parses as a number, `[1,2]` as an array and `"quoted"` as a bare
+ // string — none is a doc, so the ORIGINAL text is stored verbatim; the
+ // parse must not strip the quote characters the user typed.
+ for (const text of ["123", "[1,2]", '"quoted"']) {
+ expect(toTiptapDoc(text)).toEqual({
+ type: "doc",
+ content: [{ type: "paragraph", content: [{ type: "text", text }] }]
+ });
+ }
+ });
+});
+
+describe("optionalTiptapDoc", () => {
+ it("leaves the column untouched when absent or empty", () => {
+ expect(optionalTiptapDoc.parse(undefined)).toBeUndefined();
+ expect(optionalTiptapDoc.parse("")).toBeUndefined();
+ });
+
+ it("accepts a string and stores a document", () => {
+ expect(optionalTiptapDoc.parse("hi")).toEqual(doc);
+ });
+
+ it("accepts a document object", () => {
+ expect(optionalTiptapDoc.parse(doc)).toEqual(doc);
+ });
+
+ it("rejects shapes that could never be a document", () => {
+ expect(optionalTiptapDoc.safeParse(42).success).toBe(false);
+ expect(optionalTiptapDoc.safeParse(["x"]).success).toBe(false);
+ expect(optionalTiptapDoc.safeParse(null).success).toBe(false);
+ });
+});
diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.ts
index 0d07b4095c..b833652370 100644
--- a/apps/erp/app/modules/shared/shared.models.ts
+++ b/apps/erp/app/modules/shared/shared.models.ts
@@ -288,6 +288,58 @@ export const oAuthCallbackSchema = z.object({
state: z.string()
});
+/**
+ * Coerces whatever a caller sent for a rich-text column into a tiptap document
+ * object. Accepts plain text, a JSON-encoded document (a form post), or the
+ * document itself (an MCP / API JSON body).
+ *
+ * Rich-text columns (`internalNotes`, `externalNotes`, step descriptions) are
+ * `json`, and they MUST hold an object. A JSON string scalar stored there is
+ * read back by supabase-js as a JS string; when the row is later copied through
+ * Kysely (quote → sales order, RFQ → quote, quote → revision, method copies)
+ * deno-postgres sends that string as raw text and Postgres rejects it with
+ * `invalid input syntax for type json`. The edge functions now serialise on
+ * their side too (`lib/json.ts`), but the write side must never store the
+ * scalar in the first place. Never drops content to `{}`.
+ *
+ * Returns `any`: the doc is consumed both as a DB Json value and as editor
+ * JSONContent, and a narrower type breaks one of the two call sites.
+ */
+export function toTiptapDoc(value: unknown): any {
+ if (typeof value === "string") {
+ let parsed: unknown = value;
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ // raw text, not JSON
+ }
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ return parsed;
+ }
+ // Anything else the caller typed is literal text — including text that
+ // happens to parse as JSON (`"quoted"`, `123`, `[1,2]`). Wrap the ORIGINAL
+ // value so no characters are lost to the parse.
+ return textToTiptap(value);
+ }
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
+ return textToTiptap(String(value));
+}
+
+/**
+ * Optional rich-text field: absent or empty leaves the column untouched,
+ * anything else is stored as a tiptap document via `toTiptapDoc`. Declared as
+ * `string | object` on the input side so the MCP manifest (which publishes the
+ * INPUT schema) tells a caller both shapes are accepted, instead of the bare
+ * `{}` a `z.any()` produced.
+ */
+export const optionalTiptapDoc = z
+ .union([z.string(), z.record(z.string(), z.unknown())])
+ .transform((value): any => (value === "" ? undefined : toTiptapDoc(value)))
+ // `.optional()` LAST so the inferred key is optional (`notes?:`) — placing it
+ // before the transform makes zod infer a required key and every caller that
+ // omits `notes` stops compiling.
+ .optional();
+
export const operationStepValidator = z
.object({
id: zfd.text(z.string().optional()),
@@ -296,22 +348,7 @@ export const operationStepValidator = z
description: z
.string()
.min(1, { message: "Description is required" })
- // Returns `any`: the tiptap doc is consumed both as a DB Json value and as
- // editor JSONContent, and a narrower type breaks one of the two call sites.
- .transform((val): any => {
- let parsed: unknown;
- try {
- parsed = JSON.parse(val);
- // biome-ignore lint/correctness/noUnusedVariables: raw text is not JSON
- } catch (e) {
- parsed = val;
- }
- // Always store a tiptap doc object, never a scalar string (jsonb scalar
- // strings break method copies) and never silently drop content to {}.
- if (typeof parsed === "string") return textToTiptap(parsed);
- if (parsed && typeof parsed === "object") return parsed;
- return textToTiptap(String(val));
- }),
+ .transform((val): any => toTiptapDoc(val)),
type: z.enum(procedureStepType, {
error: "Type is required"
}),
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 593c946a69..7449644bc6 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1355,7 +1355,7 @@
{"name":"sales_upsertMakeMethodFromQuoteLine","classification":"WRITE","paramCount":4,"schema":"ca78a9869ff2","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertMakeMethodFromQuoteMethod","classification":"WRITE","paramCount":3,"schema":"32b3a0f5efa0","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertNoQuoteReason","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
- {"name":"sales_upsertQuote","classification":"WRITE","paramCount":21,"schema":"3ae0de5535e8","response":"3acbb53b8c04","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
+ {"name":"sales_upsertQuote","classification":"WRITE","paramCount":21,"schema":"c8e476a66d0a","response":"3acbb53b8c04","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertQuoteLine","classification":"WRITE","paramCount":17,"schema":"5fd3eea3d988","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertQuoteLineAdditionalCharges","classification":"WRITE","paramCount":2,"schema":"483aa73b0c32","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
{"name":"sales_upsertQuoteLineMethod","classification":"WRITE","paramCount":5,"schema":"5f94e8a4cbf6","response":"none","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create+update","paginates":false},
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
index 9bedde865b..709411350c 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
@@ -18,6 +18,7 @@ import {
sendSalesOrderEmail
} from "~/modules/shared/shared.server";
import { loader as pdfLoader } from "~/routes/file+/sales-order+/$id[.]pdf";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { path } from "~/utils/path";
const logger = getLogger("erp", "quoteid-convert");
@@ -85,7 +86,13 @@ export async function action(args: ActionFunctionArgs) {
path.to.quoteDetails(quoteId),
await flash(
request,
- error(convert.error, "Failed to convert quote to order")
+ error(
+ convert.error,
+ await getEdgeFunctionErrorMessage(
+ convert.error,
+ "Failed to convert quote to order"
+ )
+ )
)
);
}
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
index e2cb6bc374..daa0df8fe7 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
@@ -12,6 +12,7 @@ import {
selectedLinesValidator
} from "~/modules/purchasing";
import { isApprovalRequired } from "~/modules/shared";
+import { getEdgeFunctionErrorMessage } from "~/utils/error";
import { path } from "~/utils/path";
const logger = getLogger("erp", "id-convert");
@@ -84,7 +85,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
path.to.supplierQuoteDetails(id),
await flash(
request,
- error(convert.error, "Failed to convert quote to order")
+ error(
+ convert.error,
+ await getEdgeFunctionErrorMessage(
+ convert.error,
+ "Failed to convert quote to order"
+ )
+ )
)
);
}
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 9d9a90f2cd..41dd2675a6 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -6,6 +6,7 @@ import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { format } from "https://deno.land/[email protected]/datetime/format.ts";
import { getFunctionLogger } from "../lib/logging.ts";
+import { toJson } from "../lib/json.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
@@ -603,8 +604,8 @@ serve(async (req: Request) => {
quote.data.currencyCode ??
company.data?.baseCurrencyCode ??
"USD",
- externalNotes: quote.data.externalNotes,
- internalNotes: quote.data.internalNotes,
+ externalNotes: toJson(quote.data.externalNotes),
+ internalNotes: toJson(quote.data.internalNotes),
exchangeRate: quote.data.exchangeRate ?? 1,
exchangeRateUpdatedAt:
quote.data.exchangeRateUpdatedAt ?? new Date().toISOString(),
@@ -686,8 +687,8 @@ serve(async (req: Request) => {
locationId: line.locationId ?? quote.data.locationId,
methodType: line.methodType,
storageUnitId: pickMethodDefaultsByLineId.get(line.id!) ?? null,
- internalNotes: line.internalNotes,
- externalNotes: line.externalNotes,
+ internalNotes: toJson(line.internalNotes),
+ externalNotes: toJson(line.externalNotes),
saleQuantity: price.quantity,
status: "Ordered",
unitOfMeasureCode: line.unitOfMeasureCode,
@@ -1177,8 +1178,8 @@ serve(async (req: Request) => {
).add({ days: 30 }).toString(),
salesPersonId: salesRfq.data?.salesPersonId ?? userId,
status: "Draft",
- externalNotes: salesRfq.data?.externalNotes,
- internalNotes: salesRfq.data?.internalNotes,
+ externalNotes: toJson(salesRfq.data?.externalNotes),
+ internalNotes: toJson(salesRfq.data?.internalNotes),
companyId,
createdBy: userId,
currencyCode,
@@ -1240,8 +1241,8 @@ serve(async (req: Request) => {
locationId: salesRfq.data?.locationId,
methodType: line.methodType!,
modelUploadId: line.modelUploadId,
- internalNotes: line.internalNotes,
- externalNotes: line.externalNotes,
+ internalNotes: toJson(line.internalNotes),
+ externalNotes: toJson(line.externalNotes),
quantity: line.quantity,
status: "Not Started",
unitOfMeasureCode: line.unitOfMeasureCode,
@@ -1709,8 +1710,8 @@ serve(async (req: Request) => {
)?.defaultStorageUnitId ?? null,
exchangeRate: quote.data.exchangeRate ?? 1,
conversionFactor: line.conversionFactor,
- internalNotes: line.internalNotes,
- externalNotes: line.externalNotes,
+ internalNotes: toJson(line.internalNotes),
+ externalNotes: toJson(line.externalNotes),
purchaseQuantity: selectedLines![line.id!].quantity,
inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,
purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index e1d22efb56..e8bff8cd6c 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -28,6 +28,7 @@ import {
traverseQuoteMethod,
} from "../lib/methods.ts";
import { getFunctionLogger } from "../lib/logging.ts";
+import { toJson } 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";
@@ -6959,8 +6960,8 @@ serve(async (req: Request) => {
).add({ days: 30 }).toString(),
salesPersonId: sourceQuote.data?.salesPersonId ?? userId,
status: "Draft",
- externalNotes: sourceQuote.data?.externalNotes,
- internalNotes: sourceQuote.data?.internalNotes,
+ externalNotes: toJson(sourceQuote.data?.externalNotes),
+ internalNotes: toJson(sourceQuote.data?.internalNotes),
currencyCode: sourceQuote.data?.currencyCode,
exchangeRate: sourceQuote.data?.exchangeRate,
exchangeRateUpdatedAt: new Date().toISOString(),
diff --git a/packages/database/supabase/functions/lib/json.test.ts b/packages/database/supabase/functions/lib/json.test.ts
new file mode 100644
index 0000000000..b1cfb01aec
--- /dev/null
+++ b/packages/database/supabase/functions/lib/json.test.ts
@@ -0,0 +1,43 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import { toJson } 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.
+// `toJson` must hand the driver valid JSON TEXT for every shape a json/jsonb
+// column can legitimately hold — that is the whole contract.
+
+Deno.test("toJson: object is serialised as JSON text", () => {
+ assertEquals(
+ toJson({ type: "doc", content: [] }),
+ '{"type":"doc","content":[]}'
+ );
+});
+
+Deno.test("toJson: a JSON string scalar is quoted, not sent raw", () => {
+ // Raw `some text` is what deno-postgres would otherwise send; Postgres
+ // rejects it with `invalid input syntax for type json`.
+ assertEquals(toJson("some text"), '"some text"');
+ assertEquals(toJson(""), '""');
+});
+
+Deno.test("toJson: an array is JSON, not a Postgres array literal", () => {
+ assertEquals(toJson(["a", "b"]), '["a","b"]');
+});
+
+Deno.test("toJson: numbers and booleans are JSON scalars", () => {
+ assertEquals(toJson(1.5), "1.5");
+ assertEquals(toJson(false), "false");
+});
+
+Deno.test("toJson: null and undefined pass through untouched", () => {
+ // null must stay NULL (not the JSON text "null"), and undefined must stay
+ // absent so Kysely omits the column and the DEFAULT applies.
+ assertEquals(toJson(null), null);
+ assertEquals(toJson(undefined), undefined);
+});
+
+Deno.test("toJson: output always parses back to the input", () => {
+ for (const value of [{ a: 1 }, "x", ["y"], 0, true]) {
+ assertEquals(JSON.parse(toJson(value) as string), value);
+ }
+});
diff --git a/packages/database/supabase/functions/lib/json.ts b/packages/database/supabase/functions/lib/json.ts
new file mode 100644
index 0000000000..ff403f9164
--- /dev/null
+++ b/packages/database/supabase/functions/lib/json.ts
@@ -0,0 +1,21 @@
+/**
+ * Encodes a value for a `json` / `jsonb` column written through Kysely on the
+ * deno-postgres driver.
+ *
+ * deno-postgres (`query/encode.ts`) serialises query parameters by JS type, not
+ * by column type: an object becomes `JSON.stringify(value)`, but a string is
+ * sent as raw text and an array as a Postgres array literal (`{a,b}`). For a
+ * JSON column that means a stored JSON string scalar (`"some text"`) is read
+ * back by supabase-js as the JS string `some text`, re-sent unquoted, and
+ * rejected with `invalid input syntax for type json`; a JSON array is mangled
+ * the same way. Only object-shaped values survive the round trip.
+ *
+ * Pre-serialising here makes the wire value valid JSON text for every shape,
+ * so a row copied from one document to another (quote → sales order, RFQ →
+ * quote, …) keeps working whatever a previous writer stored. `null` and
+ * `undefined` pass through so the column's NULL / DEFAULT semantics are kept.
+ */
+export function toJson(value: unknown): string | null | undefined {
+ if (value === null || value === undefined) return value;
+ return JSON.stringify(value);
+}