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.

feat(backup): cover company-owned tables, unify closure + load pipeline (#953)

Sid6c5fde5c546c
diff --git a/.claude/skills/test/playbooks/backup-restore-roundtrip.md b/.claude/skills/test/playbooks/backup-restore-roundtrip.md
index 690433f837..d8af793e08 100644
--- a/.claude/skills/test/playbooks/backup-restore-roundtrip.md
+++ b/.claude/skills/test/playbooks/backup-restore-roundtrip.md
@@ -1,8 +1,10 @@
# Company Backup / Restore round-trip
-Last tested: 2026-06-25
+Last tested: 2026-06-25 (re-verified after the closure/transform-unification refactor — own export→restore→revert all PASS; restore marker: 362 rows, foreign=false, includeGroup=true)
Route: `/x/settings/backups` (internal-gated — needs an `@carbon.ms` / `@carbon.us.org` user; `[email protected]` qualifies)
+> NOT covered by the own round-trip: the FOREIGN restore (`remap=true`) path — that's where the unified `buildRowTransforms` substrate pass-through + reseed/template logic actually run. And the `20260625163000_add-companyid-to-backup-tables` migration (singletons + audit tables) must be applied before its new coverage shows up.
+
## Prerequisites
- Logged in (see `/login`). Dev server up.
- `networkidle` wait times out on this app (persistent dev connections) — snapshot directly after a short `sleep` instead of `agent-browser wait --load networkidle`.
diff --git a/apps/erp/app/modules/settings/backups-archive.server.ts b/apps/erp/app/modules/settings/backups-archive.server.ts
index 3b1a8a87a2..22c3534f5d 100644
--- a/apps/erp/app/modules/settings/backups-archive.server.ts
+++ b/apps/erp/app/modules/settings/backups-archive.server.ts
@@ -17,12 +17,16 @@ export async function unpackBackupArchive(
client: SupabaseClient<Database>,
companyId: string,
source: Readable
-): Promise<{ name: string; fileErrors: number }> {
+): Promise<{ name: string; assetErrors: number }> {
const ts = new Date().toISOString().replace(/[:.]/g, "-");
const name = `${ts}_uploaded`;
const dir = `exports/${name}`;
let manifestSeen = false;
- let fileErrors = 0;
+ // Split critical (manifest + table) failures from asset failures: a missing
+ // table breaks the load, but assets are best-effort downstream (the restore
+ // only warns on a failed asset copy), so a hiccuped asset must not block it.
+ let criticalErrors = 0;
+ let assetErrors = 0;
const extract = tarExtract();
const gunzip = createGunzip();
@@ -42,11 +46,18 @@ export async function unpackBackupArchive(
next();
return;
}
- if (rel === "manifest.json") manifestSeen = true;
const up = await client.storage
.from(companyId)
.upload(`${dir}/${rel}`, Buffer.concat(chunks), { upsert: true });
- if (up.error) fileErrors++;
+ if (up.error) {
+ if (rel.startsWith("assets/")) assetErrors++;
+ else criticalErrors++;
+ } else if (rel === "manifest.json") {
+ // Only mark the manifest seen once it's actually landed — an
+ // interrupted/failed upload must not pass the completeness check
+ // below and yield a phantom folder a restore would fire against.
+ manifestSeen = true;
+ }
next();
} catch (err) {
next(err as Error);
@@ -61,5 +72,13 @@ export async function unpackBackupArchive(
if (!manifestSeen) {
throw new Error("Archive is missing manifest.json");
}
- return { name, fileErrors };
+ if (criticalErrors > 0) {
+ // A manifest or table file failed to land — the folder is unrestorable.
+ // Surface it rather than return a name a restore would later fail on with
+ // an opaque "manifest not found".
+ throw new Error(
+ `${criticalErrors} critical file(s) failed to upload — the backup is incomplete. Retry the upload.`
+ );
+ }
+ return { name, assetErrors };
}
diff --git a/packages/database/supabase/migrations/20260625163000_add-companyid-to-backup-tables.sql b/packages/database/supabase/migrations/20260625163000_add-companyid-to-backup-tables.sql
new file mode 100644
index 0000000000..0aee2abb28
--- /dev/null
+++ b/packages/database/supabase/migrations/20260625163000_add-companyid-to-backup-tables.sql
@@ -0,0 +1,185 @@
+-- Make "a company's data" an explicit, directly-queryable fact for the company
+-- backup/export: give a denormalized `companyId` to company-owned CHILD tables
+-- that previously derived scope from a parent FK, so the export catalog scopes
+-- them with a direct `companyId = $` predicate instead of an inferred FK path.
+--
+-- Company-SINGLETON config tables (companySettings, terms, AP/AR billing — one
+-- row per company, keyed by `id -> company`) are NOT touched here: the export
+-- catalog scopes them by their `id` directly (it IS the company id), so they need
+-- no redundant `companyId` column. companyPlan is a singleton too but deliberately
+-- excluded (Stripe billing identity, must never travel).
+--
+-- Supersedes PR #946 (`20260625101500_add-companyid-to-child-tables.sql`): this
+-- migration covers the FULL set in one place — the contact/location/line-price
+-- child tables from #946, PLUS the order/invoice status + activity history and
+-- contractor ability links. Close #946 in favor of this. The shared
+-- `set_company_id_from_parent` trigger is defined here, so this applies standalone.
+--
+-- companyId is backfilled from each table's parent and kept populated on INSERT by
+-- a BEFORE-INSERT trigger, so no app insert code changes. All parent FK columns are
+-- NOT NULL with no orphans, so the backfill fills every row.
+
+-- Shared trigger: derive companyId from a parent. TG_ARGV = (parent_table, fk_column).
+-- Reuses the canonical get_company_id_from_foreign_key() helper (same one the RLS
+-- policies on these tables use). AUTHORITATIVE — it ALWAYS overwrites companyId
+-- from the parent, ignoring any caller-supplied value, so a crafted insert
+-- (parentId in my company, companyId of another) can't mis-scope the row across
+-- tenants (the RLS INSERT policy gates on the parent, not on this column). The
+-- restore/import load runs under session_replication_role='replica' (triggers
+-- off) and sets companyId itself; when replica is unavailable the trigger derives
+-- the same value from the already-loaded parent, so this is safe on every path.
+CREATE OR REPLACE FUNCTION set_company_id_from_parent() RETURNS trigger AS $$
+DECLARE
+ v_fkval text := to_jsonb(NEW) ->> TG_ARGV[1];
+BEGIN
+ IF v_fkval IS NOT NULL THEN
+ NEW."companyId" := get_company_id_from_foreign_key(v_fkval, TG_ARGV[0]);
+ END IF;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+-- ─── child tables (derive companyId from parent) ────────────────────────────
+-- ─── customerContact ← customer ─────────────────────────────────────────────
+ALTER TABLE "customerContact" ADD COLUMN "companyId" TEXT;
+UPDATE "customerContact" c SET "companyId" = p."companyId" FROM "customer" p WHERE c."customerId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "customerContact" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('customer', 'customerId');
+ALTER TABLE "customerContact" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "customerContact" ADD CONSTRAINT "customerContact_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "customerContact_companyId_idx" ON "customerContact" ("companyId");
+
+-- ─── customerLocation ← customer ────────────────────────────────────────────
+ALTER TABLE "customerLocation" ADD COLUMN "companyId" TEXT;
+UPDATE "customerLocation" c SET "companyId" = p."companyId" FROM "customer" p WHERE c."customerId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "customerLocation" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('customer', 'customerId');
+ALTER TABLE "customerLocation" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "customerLocation" ADD CONSTRAINT "customerLocation_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "customerLocation_companyId_idx" ON "customerLocation" ("companyId");
+
+-- ─── supplierContact ← supplier ─────────────────────────────────────────────
+ALTER TABLE "supplierContact" ADD COLUMN "companyId" TEXT;
+UPDATE "supplierContact" c SET "companyId" = p."companyId" FROM "supplier" p WHERE c."supplierId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "supplierContact" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('supplier', 'supplierId');
+ALTER TABLE "supplierContact" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "supplierContact" ADD CONSTRAINT "supplierContact_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "supplierContact_companyId_idx" ON "supplierContact" ("companyId");
+
+-- ─── supplierLocation ← supplier ────────────────────────────────────────────
+ALTER TABLE "supplierLocation" ADD COLUMN "companyId" TEXT;
+UPDATE "supplierLocation" c SET "companyId" = p."companyId" FROM "supplier" p WHERE c."supplierId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "supplierLocation" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('supplier', 'supplierId');
+ALTER TABLE "supplierLocation" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "supplierLocation" ADD CONSTRAINT "supplierLocation_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "supplierLocation_companyId_idx" ON "supplierLocation" ("companyId");
+
+-- ─── quoteLinePrice ← quote ─────────────────────────────────────────────────
+ALTER TABLE "quoteLinePrice" ADD COLUMN "companyId" TEXT;
+UPDATE "quoteLinePrice" c SET "companyId" = p."companyId" FROM "quote" p WHERE c."quoteId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "quoteLinePrice" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('quote', 'quoteId');
+ALTER TABLE "quoteLinePrice" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "quoteLinePrice" ADD CONSTRAINT "quoteLinePrice_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "quoteLinePrice_companyId_idx" ON "quoteLinePrice" ("companyId");
+
+-- ─── supplierQuoteLinePrice ← supplierQuote ─────────────────────────────────
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "companyId" TEXT;
+UPDATE "supplierQuoteLinePrice" c SET "companyId" = p."companyId" FROM "supplierQuote" p WHERE c."supplierQuoteId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "supplierQuoteLinePrice" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('supplierQuote', 'supplierQuoteId');
+ALTER TABLE "supplierQuoteLinePrice" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "supplierQuoteLinePrice" ADD CONSTRAINT "supplierQuoteLinePrice_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "supplierQuoteLinePrice_companyId_idx" ON "supplierQuoteLinePrice" ("companyId");
+
+-- ─── purchaseInvoicePriceChange ← purchaseInvoice ───────────────────────────
+ALTER TABLE "purchaseInvoicePriceChange" ADD COLUMN "companyId" TEXT;
+UPDATE "purchaseInvoicePriceChange" c SET "companyId" = p."companyId" FROM "purchaseInvoice" p WHERE c."invoiceId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "purchaseInvoicePriceChange" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('purchaseInvoice', 'invoiceId');
+ALTER TABLE "purchaseInvoicePriceChange" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "purchaseInvoicePriceChange" ADD CONSTRAINT "purchaseInvoicePriceChange_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "purchaseInvoicePriceChange_companyId_idx" ON "purchaseInvoicePriceChange" ("companyId");
+
+-- ─── purchaseInvoicePaymentRelation ← purchaseInvoice ───────────────────────
+ALTER TABLE "purchaseInvoicePaymentRelation" ADD COLUMN "companyId" TEXT;
+UPDATE "purchaseInvoicePaymentRelation" c SET "companyId" = p."companyId" FROM "purchaseInvoice" p WHERE c."invoiceId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "purchaseInvoicePaymentRelation" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('purchaseInvoice', 'invoiceId');
+ALTER TABLE "purchaseInvoicePaymentRelation" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "purchaseInvoicePaymentRelation" ADD CONSTRAINT "purchaseInvoicePaymentRelation_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "purchaseInvoicePaymentRelation_companyId_idx" ON "purchaseInvoicePaymentRelation" ("companyId");
+
+-- ─── pickingListLineTrackedEntity ← pickingListLine ─────────────────────────
+ALTER TABLE "pickingListLineTrackedEntity" ADD COLUMN "companyId" TEXT;
+UPDATE "pickingListLineTrackedEntity" c SET "companyId" = p."companyId" FROM "pickingListLine" p WHERE c."pickingListLineId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "pickingListLineTrackedEntity" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('pickingListLine', 'pickingListLineId');
+ALTER TABLE "pickingListLineTrackedEntity" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "pickingListLineTrackedEntity" ADD CONSTRAINT "pickingListLineTrackedEntity_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "pickingListLineTrackedEntity_companyId_idx" ON "pickingListLineTrackedEntity" ("companyId");
+
+-- ─── employeeShift ← shift (employeeId is a global user, so derive from shift) ─
+ALTER TABLE "employeeShift" ADD COLUMN "companyId" TEXT;
+UPDATE "employeeShift" c SET "companyId" = p."companyId" FROM "shift" p WHERE c."shiftId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "employeeShift" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('shift', 'shiftId');
+ALTER TABLE "employeeShift" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "employeeShift" ADD CONSTRAINT "employeeShift_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "employeeShift_companyId_idx" ON "employeeShift" ("companyId");
+
+-- ─── documentLabel ← document ───────────────────────────────────────────────
+ALTER TABLE "documentLabel" ADD COLUMN "companyId" TEXT;
+UPDATE "documentLabel" c SET "companyId" = p."companyId" FROM "document" p WHERE c."documentId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "documentLabel" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('document', 'documentId');
+ALTER TABLE "documentLabel" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "documentLabel" ADD CONSTRAINT "documentLabel_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "documentLabel_companyId_idx" ON "documentLabel" ("companyId");
+
+-- ─── contractorAbility ← contractor ─────────────────────────────────────────
+ALTER TABLE "contractorAbility" ADD COLUMN "companyId" TEXT;
+UPDATE "contractorAbility" c SET "companyId" = p."companyId" FROM "contractor" p WHERE c."contractorId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "contractorAbility" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('contractor', 'contractorId');
+ALTER TABLE "contractorAbility" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "contractorAbility" ADD CONSTRAINT "contractorAbility_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "contractorAbility_companyId_idx" ON "contractorAbility" ("companyId");
+
+-- ─── salesOrderStatusHistory ← salesOrder ───────────────────────────────────
+ALTER TABLE "salesOrderStatusHistory" ADD COLUMN "companyId" TEXT;
+UPDATE "salesOrderStatusHistory" c SET "companyId" = p."companyId" FROM "salesOrder" p WHERE c."salesOrderId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "salesOrderStatusHistory" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('salesOrder', 'salesOrderId');
+ALTER TABLE "salesOrderStatusHistory" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "salesOrderStatusHistory" ADD CONSTRAINT "salesOrderStatusHistory_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "salesOrderStatusHistory_companyId_idx" ON "salesOrderStatusHistory" ("companyId");
+
+-- ─── salesOrderTransaction ← salesOrder ─────────────────────────────────────
+ALTER TABLE "salesOrderTransaction" ADD COLUMN "companyId" TEXT;
+UPDATE "salesOrderTransaction" c SET "companyId" = p."companyId" FROM "salesOrder" p WHERE c."salesOrderId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "salesOrderTransaction" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('salesOrder', 'salesOrderId');
+ALTER TABLE "salesOrderTransaction" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "salesOrderTransaction" ADD CONSTRAINT "salesOrderTransaction_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "salesOrderTransaction_companyId_idx" ON "salesOrderTransaction" ("companyId");
+
+-- ─── purchaseOrderStatusHistory ← purchaseOrder ─────────────────────────────
+ALTER TABLE "purchaseOrderStatusHistory" ADD COLUMN "companyId" TEXT;
+UPDATE "purchaseOrderStatusHistory" c SET "companyId" = p."companyId" FROM "purchaseOrder" p WHERE c."purchaseOrderId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "purchaseOrderStatusHistory" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('purchaseOrder', 'purchaseOrderId');
+ALTER TABLE "purchaseOrderStatusHistory" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "purchaseOrderStatusHistory" ADD CONSTRAINT "purchaseOrderStatusHistory_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "purchaseOrderStatusHistory_companyId_idx" ON "purchaseOrderStatusHistory" ("companyId");
+
+-- ─── purchaseOrderTransaction ← purchaseOrder ───────────────────────────────
+ALTER TABLE "purchaseOrderTransaction" ADD COLUMN "companyId" TEXT;
+UPDATE "purchaseOrderTransaction" c SET "companyId" = p."companyId" FROM "purchaseOrder" p WHERE c."purchaseOrderId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "purchaseOrderTransaction" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('purchaseOrder', 'purchaseOrderId');
+ALTER TABLE "purchaseOrderTransaction" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "purchaseOrderTransaction" ADD CONSTRAINT "purchaseOrderTransaction_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "purchaseOrderTransaction_companyId_idx" ON "purchaseOrderTransaction" ("companyId");
+
+-- ─── purchaseInvoiceStatusHistory ← purchaseInvoice ─────────────────────────
+ALTER TABLE "purchaseInvoiceStatusHistory" ADD COLUMN "companyId" TEXT;
+UPDATE "purchaseInvoiceStatusHistory" c SET "companyId" = p."companyId" FROM "purchaseInvoice" p WHERE c."invoiceId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "purchaseInvoiceStatusHistory" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('purchaseInvoice', 'invoiceId');
+ALTER TABLE "purchaseInvoiceStatusHistory" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "purchaseInvoiceStatusHistory" ADD CONSTRAINT "purchaseInvoiceStatusHistory_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "purchaseInvoiceStatusHistory_companyId_idx" ON "purchaseInvoiceStatusHistory" ("companyId");
+
+-- ─── documentTransaction ← document ─────────────────────────────────────────
+ALTER TABLE "documentTransaction" ADD COLUMN "companyId" TEXT;
+UPDATE "documentTransaction" c SET "companyId" = p."companyId" FROM "document" p WHERE c."documentId" = p."id";
+CREATE TRIGGER "set_company_id" BEFORE INSERT ON "documentTransaction" FOR EACH ROW EXECUTE FUNCTION set_company_id_from_parent('document', 'documentId');
+ALTER TABLE "documentTransaction" ALTER COLUMN "companyId" SET NOT NULL;
+ALTER TABLE "documentTransaction" ADD CONSTRAINT "documentTransaction_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE;
+CREATE INDEX "documentTransaction_companyId_idx" ON "documentTransaction" ("companyId");
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
index 16e8fecf21..4d5c62eb0f 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
@@ -1,16 +1,18 @@
import { describe, expect, it } from "vitest";
import {
- assertReferentiallyClosed,
- buildRowTransforms,
type Catalog,
type ColumnInfo,
type CompanyBackup,
type ForeignKey,
- findDanglingReferences,
isUserScopedIdentityTable,
selectWipeableTables,
type TableInfo
} from "./company-backup";
+import {
+ assertReferentiallyClosed,
+ buildRowTransforms,
+ findDanglingReferences
+} from "./company-backup.transforms";
// ── Tiny synthetic-catalog builders ─────────────────────────────────────────
// The closure check is a pure function of (catalog, data), so these tests need
@@ -108,6 +110,53 @@ describe("findDanglingReferences", () => {
expect(result[0]?.fatal).toBe(false);
});
+ it("resolves a NOT-NULL FK against target substrate ids (a global row the backup omits)", () => {
+ // A company's materialDimension points at a globally-seeded materialForm
+ // (companyId IS NULL) that the backup deliberately omits. With no knowledge
+ // of the target it reads as a gap; once the target is known to hold that
+ // global row (substrate), it resolves. No allow-list, no nullable-column
+ // heuristic — driven by the actual ids present in the target.
+ const materialForm = table("materialForm", [col("id"), col("companyId")]);
+ const materialDimension = table(
+ "materialDimension",
+ [col("id"), col("materialFormId"), col("companyId")],
+ [fk("materialFormId", "materialForm")]
+ );
+ const cat = catalog([materialForm, materialDimension]);
+ const data = {
+ materialForm: [], // global rows live in the target seed, not the backup
+ materialDimension: [
+ { id: "md1", materialFormId: "round-bar", companyId: "c1" }
+ ]
+ };
+ // Without target knowledge the omitted global ref looks like a gap…
+ expect(findDanglingReferences(cat, data)).toHaveLength(1);
+ // …but when the target is known to hold that global row, it resolves.
+ const substrate = new Map([
+ ["materialForm", new Set<unknown>(["round-bar"])]
+ ]);
+ expect(findDanglingReferences(cat, data, substrate)).toEqual([]);
+ });
+
+ it("still flags a missing NOT-NULL FK into an ordinary company table (revert did not loosen general closure)", () => {
+ // A non-reference company table (item) is NOT in the deferral set, so a
+ // dangling NOT-NULL ref to it is a fatal closure gap, as before.
+ const result = findDanglingReferences(catalog([ITEM, NCI]), {
+ item: [],
+ nonConformanceItem: [{ id: "nc1", itemId: "gone", companyId: "c1" }]
+ });
+ expect(result).toEqual([
+ {
+ table: "nonConformanceItem",
+ column: "itemId",
+ refTable: "item",
+ fatal: true,
+ sampleValue: "gone",
+ count: 1
+ }
+ ]);
+ });
+
it("ignores a null FK value", () => {
const nciNullable = table(
"nonConformanceItem",
@@ -264,7 +313,7 @@ describe("buildRowTransforms", () => {
expect(out.parentId).toBeNull();
});
- it("throws on a NOT-NULL FK to a scoped row missing from the backup", () => {
+ it("throws on a NOT-NULL FK to a row in neither the backup nor the target", () => {
const t = table(
"nonConformanceItem",
[col("id"), col("companyId"), col("itemId")],
@@ -280,7 +329,124 @@ describe("buildRowTransforms", () => {
{ id: "nc1", companyId: "src-co", itemId: "ghost" },
ctx({ idMaps })
)
- ).toThrow(/isn't in the backup/);
+ ).toThrow(/isn't in the backup or the target/);
+ });
+
+ it("keeps a NOT-NULL FK to a target substrate id (a global row the backup omits)", () => {
+ // materialDimension → a globally-seeded materialForm (companyId IS NULL) the
+ // backup doesn't carry. Its stable id is present in the target, so the remap
+ // keeps it verbatim instead of treating it as a dangling gap.
+ const t = table(
+ "materialDimension",
+ [col("id"), col("companyId"), col("materialFormId")],
+ [fk("materialFormId", "materialForm")]
+ );
+ const idMaps = new Map([
+ ["materialDimension", new Map([["md1", "mdX"]])],
+ ["materialForm", new Map([["co-form", "co-formX"]])] // company forms remap
+ ]);
+ const substrateIds = new Map([
+ ["materialForm", new Set<unknown>(["angle"])] // global form present in target
+ ]);
+ const out = apply(
+ t,
+ { id: "md1", companyId: "src-co", materialFormId: "angle" },
+ ctx({ idMaps, substrateIds })
+ );
+ expect(out.materialFormId).toBe("angle");
+ });
+
+ it("remaps a company-singleton's id to the target company (its id IS the company)", () => {
+ const t = table(
+ "companySettings",
+ [col("id"), col("companyId"), col("useMetric")],
+ [fk("id", "company")]
+ );
+ const out = apply(
+ t,
+ { id: "src-co", companyId: "src-co", useMetric: true },
+ ctx()
+ );
+ expect(out).toEqual({
+ id: "target-co",
+ companyId: "target-co",
+ useMetric: true
+ });
+ });
+
+ it("rewrites a storage path to the shared template prefix when templateIndustryId is set", () => {
+ const t = table("item", [
+ col("id"),
+ col("companyId"),
+ col("modelPath", { nullable: true })
+ ]);
+ const out = apply(
+ t,
+ { id: "i1", companyId: "src-co", modelPath: "src-co/models/x.stl" },
+ ctx({ templateIndustryId: "metal" })
+ );
+ expect(out.modelPath).toBe("_templates/metal/models/x.stl");
+ });
+
+ it("nulls a nullable FK into a skipped (not-imported) table", () => {
+ const t = table(
+ "thing",
+ [col("id"), col("companyId"), col("inviteId", { nullable: true })],
+ [fk("inviteId", "invite")]
+ );
+ const out = apply(
+ t,
+ { id: "t1", companyId: "src-co", inviteId: "inv1" },
+ ctx({ skippedRefTables: new Set(["invite"]) })
+ );
+ expect(out.inviteId).toBeNull();
+ });
+
+ it("soft-records a non-nullable FK to a tenant table not imported, keeping the value", () => {
+ const recorded: string[] = [];
+ const t = table(
+ "thing",
+ [col("id"), col("companyId"), col("locationId")],
+ [fk("locationId", "location")]
+ );
+ const out = apply(
+ t,
+ { id: "t1", companyId: "src-co", locationId: "loc1" },
+ ctx({
+ catalogTableNames: new Set(["location"]),
+ onUnresolvedRef: (d) => recorded.push(d)
+ })
+ );
+ expect(out.locationId).toBe("loc1");
+ expect(recorded).toEqual(["thing.locationId -> location"]);
+ });
+
+ it("keeps a FK to a global-reference table verbatim (stable ids, not in catalog)", () => {
+ const t = table(
+ "item",
+ [col("id"), col("companyId"), col("uomCode")],
+ [fk("uomCode", "unitOfMeasure")]
+ );
+ const out = apply(
+ t,
+ { id: "i1", companyId: "src-co", uomCode: "EA" },
+ ctx()
+ );
+ expect(out.uomCode).toBe("EA");
+ });
+
+ it("scrubs an email column via the scrubEmail hook", () => {
+ const t = table("contact", [
+ col("id"),
+ col("companyId"),
+ col("email", { nullable: true })
+ ]);
+ const out = apply(
+ t,
+ { id: "c1", companyId: "src-co", email: "[email protected]" },
+ ctx({ scrubEmail: () => "[email protected]" })
+ );
+ expect(out.email).toBe("[email protected]");
});
});
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
new file mode 100644
index 0000000000..8e94f298c2
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.transforms.ts
@@ -0,0 +1,343 @@
+import type { KyselyDatabase } from "@carbon/database/client";
+import { type Kysely, sql } from "kysely";
+import {
+ type Catalog,
+ type ColumnInfo,
+ type CompanyBackup,
+ mapWithConcurrency,
+ RETAINED_REF_TABLES,
+ rewriteStoragePath,
+ rewriteToTemplateAssetPath,
+ STORAGE_PATH_COLUMNS,
+ type TableInfo
+} from "./company-backup";
+
+// Referential-closure checks and row-remap transforms for company backup/restore.
+// Extracted from company-backup.ts (which keeps catalog introspection, serialization
+// and storage). Pure except loadSubstrateIds (a single target probe); unit-tested in
+// company-backup.closure.test.ts. Imports one-directionally from company-backup.ts.
+
+/** FKs to these collapse to the importing user when re-stamping a foreign backup. */
+export const USER_REF_TABLES = new Set(["user", "employee"]);
+
+export type DanglingRef = {
+ table: string;
+ column: string;
+ refTable: string;
+ /** false → restore nulls it (warning); true → NOT NULL, restore cannot resolve. */
+ fatal: boolean;
+ sampleValue: string;
+ count: number;
+};
+
+/**
+ * Find FK values that point at a scoped row the backup does NOT contain — the exact
+ * gap that makes a restore dangle. A backup is "referentially closed" when this
+ * returns no `fatal` entries. Pure, so the SAME check runs as a unit test AND as
+ * the pre-wipe restore guard — one definition of closure, not two that can drift.
+ * Skips refs to `RETAINED_REF_TABLES` (resolved by collapse/identity) and to
+ * non-scoped global tables (`currency`, `country`, … — stable ids present in every
+ * target), since neither is a gap.
+ *
+ * `knownSubstrateIds` (per table) are ids that exist in the TARGET as substrate
+ * (`companyId IS NULL` global rows the backup deliberately omits — e.g. the
+ * seeded `material*` reference rows). A ref resolving to one of those is NOT a
+ * gap. The restore passes these from a live probe of the target; tests omit them.
+ */
+export function findDanglingReferences(
+ catalog: Catalog,
+ dataByTable: Record<string, Array<{ [col: string]: unknown }>>,
+ knownSubstrateIds?: Map<string, Set<unknown>>
+): DanglingRef[] {
+ const catalogNames = new Set(catalog.tables.map((t) => t.name));
+ const idsByTable = new Map<string, Set<unknown>>();
+ for (const t of catalog.tables) {
+ if (!t.hasId) continue;
+ const ids = new Set<unknown>();
+ for (const row of dataByTable[t.name] ?? []) ids.add(row.id);
+ idsByTable.set(t.name, ids);
+ }
+
+ const found = new Map<string, DanglingRef>();
+ for (const t of catalog.tables) {
+ const rows = dataByTable[t.name];
+ if (!rows?.length) continue;
+ const colByName = new Map(t.columns.map((c) => [c.name, c]));
+ for (const fk of t.foreignKeys) {
+ if (fk.refColumn !== "id") continue;
+ if (RETAINED_REF_TABLES.has(fk.refTable)) continue;
+ if (!catalogNames.has(fk.refTable)) continue; // non-scoped global → stable ids
+ const col = colByName.get(fk.column);
+ if (!col) continue;
+ const refIds = idsByTable.get(fk.refTable) ?? new Set();
+ const substrateIds = knownSubstrateIds?.get(fk.refTable);
+ for (const row of rows) {
+ const v = row[fk.column];
+ if (v == null) continue;
+ if (refIds.has(v)) continue;
+ if (substrateIds?.has(v)) continue;
+ const key = `${t.name}.${fk.column}->${fk.refTable}`;
+ const existing = found.get(key);
+ if (existing) {
+ existing.count++;
+ } else {
+ found.set(key, {
+ table: t.name,
+ column: fk.column,
+ refTable: fk.refTable,
+ fatal: !col.isNullable,
+ sampleValue: String(v),
+ count: 1
+ });
+ }
+ }
+ }
+ }
+ return [...found.values()];
+}
+
+/**
+ * Pre-wipe restore guard: refuse a backup that isn't referentially closed. A
+ * NOT-NULL FK pointing at a missing row would commit under relaxed FK checks and
+ * corrupt the restore, so this reports EVERY fatal gap at once — the whole list is
+ * surfaced before any data is touched, instead of one throw at a time mid-load.
+ */
+export function assertReferentiallyClosed(
+ catalog: Catalog,
+ backup: CompanyBackup,
+ knownSubstrateIds?: Map<string, Set<unknown>>
+): { ok: true } | { ok: false; reason: string } {
+ const fatal = findDanglingReferences(
+ catalog,
+ backup.data,
+ knownSubstrateIds
+ ).filter((d) => d.fatal);
+ if (fatal.length === 0) return { ok: true };
+ const lines = fatal
+ .map(
+ (d) =>
+ ` ${d.table}.${d.column} → ${d.refTable} (${d.count} row${
+ d.count === 1 ? "" : "s"
+ }, e.g. ${d.sampleValue})`
+ )
+ .join("\n");
+ return {
+ ok: false,
+ reason: `the backup is not self-contained — ${fatal.length} reference${
+ fatal.length === 1 ? "" : "s"
+ } point at rows it doesn't include:\n${lines}`
+ };
+}
+
+/**
+ * Load the TARGET's substrate ids — the `companyId IS NULL` (global) rows that a
+ * company backup deliberately omits because they're seeded into every
+ * environment (e.g. the global `material*` reference rows). Returns a per-table
+ * `id` set for every catalog table that (a) is the target of a NOT-NULL FK from
+ * data the backup carries and (b) has a direct scope column that could hold a
+ * global row. A company row's FK into one of these resolves against the target's
+ * own seed, not the backup — so feeding this to {@link assertReferentiallyClosed}
+ * stops it flagging that legitimate cross-boundary ref, while still catching a
+ * ref to a row that exists in neither the backup nor the target.
+ *
+ * List-free and data-driven: it probes the actual target, so it can't drift from
+ * a hand-maintained set of "reference tables". Tables with no global rows simply
+ * return an empty set. One query per referenced table.
+ */
+export async function loadSubstrateIds(
+ db: Kysely<KyselyDatabase>,
+ catalog: Catalog,
+ dataByTable: Record<string, Array<{ [col: string]: unknown }>>
+): Promise<Map<string, Set<unknown>>> {
+ const byName = new Map(catalog.tables.map((t) => [t.name, t]));
+ // Per ref table pointed at by a NOT-NULL FK from carried data: its scope column
+ // and the distinct ids referenced (so the probe only loads ids we actually need).
+ const wanted = new Map<string, { scopeColumn: string; ids: Set<unknown> }>();
+ for (const t of catalog.tables) {
+ const rows = dataByTable[t.name];
+ if (!rows?.length) continue;
+ const colByName = new Map(t.columns.map((c) => [c.name, c]));
+ for (const fk of t.foreignKeys) {
+ if (fk.refColumn !== "id") continue;
+ const ref = byName.get(fk.refTable);
+ if (!ref || ref.scope.kind !== "direct") continue; // only directly-scoped tables hold global rows
+ // A NOT-NULL scope column can't contain a `companyId IS NULL` row, so the
+ // probe would always be empty — skip it. (This is a sound optimization from
+ // the DB constraint, NOT a guess: a non-nullable column literally cannot
+ // hold the global rows we'd be looking for.)
+ const refScopeCol = ref.columns.find((c) => c.name === ref.scope.column);
+ if (!refScopeCol?.isNullable) continue;
+ const col = colByName.get(fk.column);
+ if (!col || col.isNullable) continue; // nullable → restore nulls a missing ref
+ const entry = wanted.get(fk.refTable) ?? {
+ scopeColumn: ref.scope.column,
+ ids: new Set<unknown>()
+ };
+ for (const row of rows) {
+ const v = row[fk.column];
+ if (v != null) entry.ids.add(v);
+ }
+ wanted.set(fk.refTable, entry);
+ }
+ }
+
+ const result = new Map<string, Set<unknown>>();
+ await mapWithConcurrency([...wanted.keys()], 6, async (refTable) => {
+ const { scopeColumn, ids } = wanted.get(refTable)!;
+ const idList = [...ids];
+ if (idList.length === 0) return;
+ const present = await sql<{ id: unknown }>`
+ SELECT ${sql.id("id")} AS id
+ FROM ${sql.id(refTable)}
+ WHERE ${sql.id(scopeColumn)} IS NULL
+ AND ${sql.id("id")} IN (${sql.join(idList.map((v) => sql`${v}`))})
+ `.execute(db);
+ result.set(refTable, new Set(present.rows.map((r) => r.id)));
+ });
+ return result;
+}
+
+export type RowTransform = (value: unknown) => unknown;
+
+/**
+ * Per-column transforms for re-stamping a FOREIGN backup onto this company —
+ * shared by the in-place restore (wipe + reload) and the reseed/template import
+ * (additive). Every id is remapped, companyId/companyGroupId point at the target,
+ * FKs follow the id remap, user refs collapse to the importing user, and storage
+ * paths are rewritten. For an OWN backup (remap=false) every column is identity.
+ * Pure (no DB), so it lives here with the other catalog helpers and is
+ * unit-tested directly. The optional `ctx` fields are the import/reseed-only
+ * policies; omit them and the behavior is the restore path's, unchanged.
+ */
+export function buildRowTransforms(
+ table: TableInfo,
+ columns: ColumnInfo[],
+ ctx: {
+ remap: boolean;
+ companyId: string;
+ userId: string;
+ targetGroupId: string | null;
+ sourceCompanyId: string;
+ idMaps: Map<string, Map<string, string>>;
+ idRewrite: Map<string, string>;
+ /** Per-table ids that exist in the TARGET as shared substrate (global
+ * `companyId IS NULL` rows the backup omits). A remapped FK whose value is
+ * one of these is kept verbatim — the stable id resolves against the
+ * target's own seed. From the same probe the closure guard uses. */
+ substrateIds?: Map<string, Set<unknown>>;
+ /** Reseed only: an onboarding demo template references shared assets at
+ * `_templates/<industryId>/` instead of per-company files — rewrite storage
+ * paths there (ids kept) rather than to `{companyId}/`. */
+ templateIndustryId?: string;
+ /** Reseed only: tenant tables NOT imported (skipped/secret). A nullable FK
+ * into one is nulled — its source id has no row in the target. */
+ skippedRefTables?: ReadonlySet<string>;
+ /** Reseed only: names of all catalog (tenant) tables, so a FK into a tenant
+ * table that wasn't imported is distinguished from one into a global
+ * reference table (whose ids are stable and kept verbatim). */
+ catalogTableNames?: ReadonlySet<string>;
+ /** Reseed only: called for a NON-nullable FK whose target row is in neither
+ * the backup nor the target (a soft warning instead of the restore-path
+ * throw — the reseed surfaces the whole list afterward). */
+ onUnresolvedRef?: (desc: string) => void;
+ /** Reseed only: rewrite an email value (a copied template's emails never
+ * belong to the target's people). */
+ scrubEmail?: (value: string) => string;
+ }
+): RowTransform[] {
+ const identity: RowTransform = (v) => v;
+ if (!ctx.remap) return columns.map(() => identity);
+
+ const fkByColumn = new Map(table.foreignKeys.map((fk) => [fk.column, fk]));
+ // A company-singleton (one row per company) keys itself by `id -> company`, so
+ // its `id` IS the company id. On remap it must follow the company, not mint a
+ // fresh id (which would orphan the row and dangle the id->company FK).
+ const isCompanySingleton = fkByColumn.get("id")?.refTable === "company";
+
+ const build = (col: ColumnInfo): RowTransform => {
+ const fk = fkByColumn.get(col.name);
+ if (col.name === "id" && isCompanySingleton) {
+ return (v) => (v === ctx.sourceCompanyId ? ctx.companyId : v);
+ }
+ // Only id-keyed tables with a text/uuid id get an idMap (int/serial ids reuse
+ // verbatim — see idMaps build). Gate on the map's presence, not `hasId`, or an
+ // int-id table dereferences an undefined map.
+ const idMap = ctx.idMaps.get(table.name);
+ if (col.name === "id" && idMap) {
+ return (v) => idMap.get(v as string) ?? v;
+ }
+ if (col.name === "companyId") return () => ctx.companyId;
+ if (col.name === "companyGroupId") return () => ctx.targetGroupId;
+ if (STORAGE_PATH_COLUMNS.has(col.name)) {
+ const { sourceCompanyId, companyId, idRewrite, templateIndustryId } = ctx;
+ return (v) => {
+ if (typeof v !== "string") return v;
+ return templateIndustryId
+ ? rewriteToTemplateAssetPath(v, sourceCompanyId, templateIndustryId)
+ : rewriteStoragePath(v, sourceCompanyId, companyId, idRewrite);
+ };
+ }
+ if (fk) {
+ if (USER_REF_TABLES.has(fk.refTable)) {
+ return (v) => (v == null ? v : ctx.userId);
+ }
+ if (fk.refTable === "company") {
+ return (v) => (v === ctx.sourceCompanyId ? ctx.companyId : v);
+ }
+ if (fk.refTable === "companyGroup") {
+ return (v) => (v == null ? v : ctx.targetGroupId);
+ }
+ if (ctx.skippedRefTables?.has(fk.refTable) && col.isNullable) {
+ return () => null;
+ }
+ if (fk.refColumn === "id") {
+ const map = ctx.idMaps.get(fk.refTable);
+ const substrate = ctx.substrateIds?.get(fk.refTable);
+ // A "tenant" ref needs a row in the target (its id was/should-be
+ // remapped); a global-reference ref (country, currency, …) has stable
+ // ids kept verbatim. Map presence proves tenant; catalogTableNames
+ // (reseed) also flags a tenant table that simply wasn't imported here.
+ const isTenantRef =
+ map !== undefined ||
+ (ctx.catalogTableNames?.has(fk.refTable) ?? false);
+ if (!map && !substrate && !isTenantRef) return identity;
+ const refTable = fk.refTable;
+ const colName = col.name;
+ const nullable = col.isNullable;
+ const onUnresolvedRef = ctx.onUnresolvedRef;
+ return (v) => {
+ if (v == null) return v;
+ const mapped = map?.get(v as string);
+ if (mapped) return mapped;
+ if (substrate?.has(v)) return v;
+ if (!isTenantRef) return v; // global-reference id, stable across envs
+ // A tenant row in neither the backup nor the target.
+ if (nullable) return null;
+ if (onUnresolvedRef) {
+ onUnresolvedRef(`${table.name}.${colName} -> ${refTable}`);
+ return v;
+ }
+ throw new Error(
+ `Backup is inconsistent: ${table.name}.${colName} references a ` +
+ `${refTable} (${String(v)}) that isn't in the backup or the target.`
+ );
+ };
+ }
+ }
+ return identity;
+ };
+
+ return columns.map((col) => {
+ const base = build(col);
+ if (ctx.scrubEmail && /email/i.test(col.name)) {
+ const scrub = ctx.scrubEmail;
+ return (v) => {
+ const value = base(v);
+ return typeof value === "string" && value.includes("@")
+ ? scrub(value)
+ : value;
+ };
+ }
+ return base;
+ });
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 1de2172d6c..2f4193d61f 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import { createInterface } from "node:readline";
import { Readable } from "node:stream";
import { createGunzip, createGzip } from "node:zlib";
+import type { TableName } from "@carbon/database/audit.config";
import {
getPostgresClient,
getPostgresConnectionPool,
@@ -127,6 +128,21 @@ export const SECRET_TABLES = [
"oauthToken"
];
+/**
+ * Company-singleton config tables: one row per company, keyed by `id` (the row's
+ * `id` IS the company id, via an `id -> company` FK), with no `companyId` column.
+ * They're a company's data, so the catalog includes them scoped by `id` directly
+ * (`WHERE id = companyId`) — no redundant `companyId` column needed. `companyPlan`
+ * is a singleton too but is deliberately NOT listed: it's billing/Stripe identity
+ * tied to the target company and must never travel.
+ */
+export const COMPANY_SINGLETON_TABLES = [
+ "companySettings",
+ "terms",
+ "companyAccountsPayableBillingAddress",
+ "companyAccountsReceivableBillingAddress"
+] as const satisfies readonly TableName[];
+
/**
* Tenant-root tables that carry a scope column but are NOT tenant data — the
* company shell itself is created by onboarding, never imported. Excluded
@@ -189,7 +205,9 @@ export type ForeignKey = {
/**
* How a table's rows are scoped to a company:
- * - `direct`: the table itself has a `companyId`/`companyGroupId` column.
+ * - `direct`: the table itself has a scope column — `companyId`/`companyGroupId`,
+ * or `id` for a company-singleton (whose `id` IS the company id, see
+ * {@link COMPANY_SINGLETON_TABLES}).
* - `via`: the table has no scope column but a FK (`column` → `parent.refColumn`)
* to a table that IS scoped (possibly transitively). It inherits that scope —
* e.g. `customerContact.customerId → customer`. Resolved from the FK graph so
@@ -197,7 +215,7 @@ export type ForeignKey = {
* parent without a hand-maintained list.
*/
export type Scope =
- | { kind: "direct"; column: "companyId" | "companyGroupId" }
+ | { kind: "direct"; column: "companyId" | "companyGroupId" | "id" }
| { kind: "via"; column: string; refColumn: string; parent: string };
export type TableInfo = {
@@ -388,7 +406,9 @@ export async function readBackup(
.download(backupManifestPath(name));
if (mf.error || !mf.data) {
throw new Error(
- `Failed to download backup manifest ${name}: ${mf.error?.message}`
+ `Failed to download backup manifest ${name}: ${
+ mf.error?.message || JSON.stringify(mf.error) || "not found"
+ }`
);
}
const manifest = JSON.parse(await mf.data.text()) as Manifest;
@@ -406,7 +426,9 @@ export async function readBackup(
.download(backupTablePath(name, t.name));
if (f.error || !f.data) {
throw new Error(
- `Failed to download table ${t.name} for ${name}: ${f.error?.message}`
+ `Failed to download table ${t.name} for ${name}: ${
+ f.error?.message || JSON.stringify(f.error) || "not found"
+ }`
);
}
data[t.name] = await deserializeTable(await f.data.arrayBuffer());
@@ -541,6 +563,16 @@ export async function getCompanyTableCatalog(
scope.set(name, { kind: "direct", column });
scopeRoot.set(name, column);
}
+ // Company-singletons: keyed by `id` (= the company id via an id->company FK),
+ // with no companyId column. Scope them by `id` directly — a company's data
+ // without a redundant column. Inject BEFORE via-resolution so a FK to a scoped
+ // table (e.g. a notification-group ref) can't mis-scope them through it.
+ const existingTables = new Set(columns.rows.map((c) => c.table_name));
+ for (const name of COMPANY_SINGLETON_TABLES) {
+ if (!existingTables.has(name) || scope.has(name)) continue;
+ scope.set(name, { kind: "direct", column: "id" });
+ scopeRoot.set(name, "companyId");
+ }
let resolvedMore = true;
while (resolvedMore) {
resolvedMore = false;
@@ -693,9 +725,6 @@ export function assertBackupImportable(
return { ok: true };
}
-/** FKs to these collapse to the importing user when re-stamping a foreign backup. */
-export const USER_REF_TABLES = new Set(["user", "employee"]);
-
/**
* FK targets a restore resolves WITHOUT the referenced row being in the backup:
* `user` (global identity table, never in the catalog) and `company` (structural),
@@ -709,185 +738,6 @@ export const RETAINED_REF_TABLES = new Set([
"companyGroup"
]);
-export type DanglingRef = {
- table: string;
- column: string;
- refTable: string;
- /** false → restore nulls it (warning); true → NOT NULL, restore cannot resolve. */
- fatal: boolean;
- sampleValue: string;
- count: number;
-};
-
-/**
- * Find FK values that point at a scoped row the backup does NOT contain — the exact
- * gap that makes a restore dangle. A backup is "referentially closed" when this
- * returns no `fatal` entries. Pure (no DB), so the SAME check runs as a unit test
- * AND as the pre-wipe restore guard — there is one definition of closure, not two
- * that can drift. Skips refs to `RETAINED_REF_TABLES` (resolved by collapse/identity)
- * and to non-scoped global tables (`currency`, `country`, … — stable ids present in
- * every target), since neither is a gap.
- */
-export function findDanglingReferences(
- catalog: Catalog,
- dataByTable: Record<string, Array<{ [col: string]: unknown }>>
-): DanglingRef[] {
- const catalogNames = new Set(catalog.tables.map((t) => t.name));
- const idsByTable = new Map<string, Set<unknown>>();
- for (const t of catalog.tables) {
- if (!t.hasId) continue;
- const ids = new Set<unknown>();
- for (const row of dataByTable[t.name] ?? []) ids.add(row.id);
- idsByTable.set(t.name, ids);
- }
-
- const found = new Map<string, DanglingRef>();
- for (const t of catalog.tables) {
- const rows = dataByTable[t.name];
- if (!rows?.length) continue;
- const colByName = new Map(t.columns.map((c) => [c.name, c]));
- for (const fk of t.foreignKeys) {
- if (fk.refColumn !== "id") continue;
- if (RETAINED_REF_TABLES.has(fk.refTable)) continue;
- if (!catalogNames.has(fk.refTable)) continue; // non-scoped global → stable ids
- const col = colByName.get(fk.column);
- if (!col) continue;
- const refIds = idsByTable.get(fk.refTable) ?? new Set();
- for (const row of rows) {
- const v = row[fk.column];
- if (v == null) continue;
- if (refIds.has(v)) continue;
- const key = `${t.name}.${fk.column}->${fk.refTable}`;
- const existing = found.get(key);
- if (existing) {
- existing.count++;
- } else {
- found.set(key, {
- table: t.name,
- column: fk.column,
- refTable: fk.refTable,
- fatal: !col.isNullable,
- sampleValue: String(v),
- count: 1
- });
- }
- }
- }
- }
- return [...found.values()];
-}
-
-/**
- * Pre-wipe restore guard: refuse a backup that isn't referentially closed. A
- * NOT-NULL FK pointing at a missing row would commit under relaxed FK checks and
- * corrupt the restore, so this reports EVERY fatal gap at once — the whole list is
- * surfaced before any data is touched, instead of one throw at a time mid-load.
- */
-export function assertReferentiallyClosed(
- catalog: Catalog,
- backup: CompanyBackup
-): { ok: true } | { ok: false; reason: string } {
- const fatal = findDanglingReferences(catalog, backup.data).filter(
- (d) => d.fatal
- );
- if (fatal.length === 0) return { ok: true };
- const lines = fatal
- .map(
- (d) =>
- ` ${d.table}.${d.column} → ${d.refTable} (${d.count} row${
- d.count === 1 ? "" : "s"
- }, e.g. ${d.sampleValue})`
- )
- .join("\n");
- return {
- ok: false,
- reason: `the backup is not self-contained — ${fatal.length} reference${
- fatal.length === 1 ? "" : "s"
- } point at rows it doesn't include:\n${lines}`
- };
-}
-
-export type RowTransform = (value: unknown) => unknown;
-
-/**
- * Per-column transforms used when re-stamping a FOREIGN backup onto this company:
- * every id is remapped to a fresh one, companyId/companyGroupId point at the
- * target, FKs follow the id remap, user refs collapse to the importing user, and
- * storage paths are rewritten. For an OWN backup (remap=false) every column is
- * identity — ids and scope already belong here. Pure (no DB), so it lives here
- * with the other catalog helpers and is unit-tested directly.
- */
-export function buildRowTransforms(
- table: TableInfo,
- columns: ColumnInfo[],
- ctx: {
- remap: boolean;
- companyId: string;
- userId: string;
- targetGroupId: string | null;
- sourceCompanyId: string;
- idMaps: Map<string, Map<string, string>>;
- idRewrite: Map<string, string>;
- }
-): RowTransform[] {
- const identity: RowTransform = (v) => v;
- if (!ctx.remap) return columns.map(() => identity);
-
- const fkByColumn = new Map(table.foreignKeys.map((fk) => [fk.column, fk]));
- return columns.map((col) => {
- const fk = fkByColumn.get(col.name);
- // Only id-keyed tables with a text/uuid id get an idMap (int/serial ids reuse
- // verbatim — see idMaps build). Gate on the map's presence, not `hasId`, or an
- // int-id table dereferences an undefined map.
- const idMap = ctx.idMaps.get(table.name);
- if (col.name === "id" && idMap) {
- return (v) => idMap.get(v as string) ?? v;
- }
- if (col.name === "companyId") return () => ctx.companyId;
- if (col.name === "companyGroupId") return () => ctx.targetGroupId;
- if (STORAGE_PATH_COLUMNS.has(col.name)) {
- return (v) =>
- typeof v === "string"
- ? rewriteStoragePath(
- v,
- ctx.sourceCompanyId,
- ctx.companyId,
- ctx.idRewrite
- )
- : v;
- }
- if (fk) {
- if (USER_REF_TABLES.has(fk.refTable)) {
- return (v) => (v == null ? v : ctx.userId);
- }
- if (fk.refTable === "company") {
- return (v) => (v === ctx.sourceCompanyId ? ctx.companyId : v);
- }
- if (fk.refTable === "companyGroup") {
- return (v) => (v == null ? v : ctx.targetGroupId);
- }
- if (fk.refColumn === "id" && ctx.idMaps.has(fk.refTable)) {
- const map = ctx.idMaps.get(fk.refTable)!;
- return (v) => {
- if (v == null) return v;
- const mapped = map.get(v as string);
- if (mapped) return mapped;
- // The referenced row isn't in the backup. Keeping the stale id would
- // dangle (FK checks are relaxed during load, so it would commit and
- // only fail later in MRP/etc). Drop it when nullable; otherwise abort
- // the whole restore — never commit a corrupt reference.
- if (col.isNullable) return null;
- throw new Error(
- `Backup is inconsistent: ${table.name}.${col.name} references a ` +
- `${fk.refTable} (${String(v)}) that isn't in the backup.`
- );
- };
- }
- }
- return identity;
- });
-}
-
/**
* Kahn's algorithm over in-set FK edges (referenced tables first). Cycles
* are broken deterministically by picking the remaining table with the
@@ -1043,6 +893,16 @@ export async function findExportScopeViolations(
companyId,
companyGroupId
);
+ // A NOT-NULL FK is only a real gap when it points at ANOTHER company's row.
+ // A `companyId IS NULL` row is shared substrate (seeded `material*`,
+ // currencies, …) present in every target, so it is never a gap — widen the
+ // existence set to include it. A ref to a row owned by a different company
+ // (scopeCol = some other value) is still NOT matched, so it still surfaces.
+ // This is the one cross-tenant rule, no per-table allow-list.
+ const parentExistence =
+ parent.scope.kind === "direct"
+ ? sql`${parentScope} OR ${sql.id(parent.scope.column)} IS NULL`
+ : parentScope;
checks.push({
desc: `${t.name}.${fk.column} → ${fk.refTable}`,
query: sql<{ n: string }>`
@@ -1053,7 +913,7 @@ export async function findExportScopeViolations(
AND ${sql.id(fk.column)} NOT IN (
SELECT ${sql.id(fk.refColumn)}
FROM ${sql.id(parent.name)}
- WHERE ${parentScope}
+ WHERE ${parentExistence}
)`
});
}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index 6b263260b5..b4329c4d13 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -92,7 +92,10 @@ export async function buildCompanyBackup(
const name = opts.name ?? `${exportedAt.replace(/[:.]/g, "-")}${slug}`;
const catalog = await getCompanyTableCatalog(db);
- const secretTables = new Set(SECRET_TABLES);
+ // Secrets (credentials/tokens) never travel — they belong to the source
+ // company, not a copy. (Billing identity like companyPlan never enters the
+ // catalog: it's a company-singleton deliberately left out of the scoped set.)
+ const secretTables = new Set<string>(SECRET_TABLES);
const excludedTables = catalog.tables
.filter((t) => secretTables.has(t.name))
.map((t) => t.name);
diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.ts
index d626d13740..27d5ced4de 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -2,7 +2,6 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { chunkArray } from "@carbon/utils";
import { sql } from "kysely";
import { inngest } from "../../client";
-import type { ColumnInfo, TableInfo } from "./company-backup";
import {
assertBackupImportable,
BACKUP_INTEGRATION,
@@ -18,17 +17,15 @@ import {
RESEED_SKIPPED_TABLES,
readBackup,
restoreAssetsFromBackup,
- rewriteStoragePath,
- rewriteToTemplateAssetPath,
- SECRET_TABLES,
- STORAGE_PATH_COLUMNS
+ SECRET_TABLES
} from "./company-backup";
+import {
+ buildRowTransforms,
+ loadSubstrateIds
+} from "./company-backup.transforms";
const INSERT_CHUNK_SIZE = 200;
-/** FKs to these tables collapse to the importing user in reseed mode. */
-const USER_REF_TABLES = new Set(["user", "employee"]);
-
type LedgerRow = {
entityType: string;
entityId: string;
@@ -165,6 +162,10 @@ export const companyImportFunction = inngest.createFunction(
if (mode === "reseed") {
for (const table of importTables) {
if (!table.hasId) continue;
+ // Only text/uuid ids get remapped — an int/serial id can't take a
+ // nanoid (same gate as the restore path, so the two don't drift).
+ const idType = table.columns.find((c) => c.name === "id")?.udtName;
+ if (idType !== "uuid" && idType !== "text") continue;
const map = new Map<string, string>();
for (const row of backup.data[table.name]!) {
if (typeof row.id === "string")
@@ -202,108 +203,18 @@ export const companyImportFunction = inngest.createFunction(
// surfaced rather than silently corrupting referential integrity.
const unresolvedRefs = new Set<string>();
- // What happens to a column depends only on its metadata and the mode,
- // never on the row — so compile one transform per column per table and
- // keep the per-row path a flat loop.
- type Transform = (value: unknown) => unknown;
- const identity: Transform = (v) => v;
-
- const buildColumnTransforms = (
- table: TableInfo,
- columns: ColumnInfo[]
- ): Transform[] => {
- if (mode !== "reseed") return columns.map(() => identity);
-
- const fkByColumn = new Map(
- table.foreignKeys.map((fk) => [fk.column, fk])
- );
-
- return columns.map((col) => {
- let base = identity;
- const fk = fkByColumn.get(col.name);
-
- const idMap = idMaps.get(table.name);
- if (col.name === "id" && idMap) {
- base = (v) => idMap.get(v as string) ?? v;
- } else if (col.name === "companyId") {
- base = () => companyId;
- } else if (col.name === "companyGroupId") {
- base = () => targetGroupId;
- } else if (STORAGE_PATH_COLUMNS.has(col.name)) {
- // Storage path columns embed the companyId + an id that was just
- // remapped. A referenced template points them at the shared
- // `_templates/<industryId>/` asset (ids kept, not remapped); a real
- // backup points them at the per-company files restored below.
- base = referencedTemplate
- ? (v) =>
- typeof v === "string"
- ? rewriteToTemplateAssetPath(
- v,
- sourceCompanyId,
- templateIndustryId
- )
- : v
- : (v) =>
- typeof v === "string"
- ? rewriteStoragePath(
- v,
- sourceCompanyId,
- companyId,
- idRewrite
- )
- : v;
- } else if (fk) {
- if (USER_REF_TABLES.has(fk.refTable)) {
- base = (v) => (v == null ? v : userId);
- } else if (fk.refTable === "company") {
- base = (v) => (v === sourceCompanyId ? companyId : v);
- } else if (fk.refTable === "companyGroup") {
- base = (v) => (v == null ? v : targetGroupId);
- } else if (skipped.has(fk.refTable) && col.isNullable) {
- base = () => null;
- } else if (fk.refColumn === "id" && idMaps.has(fk.refTable)) {
- const map = idMaps.get(fk.refTable)!;
- base = (v) => (v == null ? v : (map.get(v as string) ?? v));
- } else if (
- fk.refColumn === "id" &&
- catalogTableNames.has(fk.refTable)
- ) {
- // Ref to a tenant table that wasn't imported (filtered out as
- // already-populated, or skipped + non-nullable). Source ids don't
- // exist in the target. Null it when allowed; otherwise keep the
- // value but record it — a non-null ref would dangle once FK
- // enforcement comes back after the transaction. (Refs to global,
- // non-tenant tables — country, currency, … — fall through to
- // identity: their ids are stable across companies.)
- if (col.isNullable) {
- base = () => null;
- } else {
- base = (v) => {
- if (v != null) {
- unresolvedRefs.add(
- `${table.name}.${col.name} -> ${fk.refTable}`
- );
- }
- return v;
- };
- }
- }
- }
-
- // PII scrub — emails in a copied template never belong to the
- // target company's people.
- if (/email/i.test(col.name)) {
- const inner = base;
- return (v) => {
- const value = inner(v);
- return typeof value === "string" && value.includes("@")
- ? `import-${++scrubCounter}@example.test`
- : value;
- };
- }
- return base;
- });
- };
+ // One transform builder for both restore and reseed import
+ // (buildRowTransforms in company-backup.ts) — the reseed-only policies are
+ // passed as knobs; preserve mode (remap=false) copies verbatim.
+ const remap = mode === "reseed";
+ // Global substrate (companyId IS NULL) ids the backup omits but the target
+ // holds by seed — a template's FK into a seeded global row resolves against
+ // these instead of dangling.
+ const substrateIds = remap
+ ? await loadSubstrateIds(db, catalog, backup.data)
+ : undefined;
+ const scrubEmail = () => `import-${++scrubCounter}@example.test`;
+ const recordUnresolvedRef = (desc: string) => unresolvedRefs.add(desc);
const replicaMode = await canSetReplicationRole(db);
if (!replicaMode) {
@@ -333,7 +244,23 @@ export const companyImportFunction = inngest.createFunction(
);
if (columns.length === 0) continue;
- const transforms = buildColumnTransforms(table, columns);
+ const transforms = buildRowTransforms(table, columns, {
+ remap,
+ companyId,
+ userId,
+ targetGroupId,
+ sourceCompanyId,
+ idMaps,
+ idRewrite,
+ substrateIds,
+ templateIndustryId: referencedTemplate
+ ? templateIndustryId
+ : undefined,
+ skippedRefTables: skipped,
+ catalogTableNames,
+ onUnresolvedRef: recordUnresolvedRef,
+ scrubEmail
+ });
const originalRows = backup.data[table.name]!;
// Hot path: indexed loops (no per-row `forEach` closure), packed
// output array, `out` keys in fixed column order (one hidden class
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index 2ced4da1d2..f1060b7340 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -5,13 +5,11 @@ import { inngest } from "../../client";
import type { Catalog, CompanyBackup } from "./company-backup";
import {
assertBackupImportable,
- assertReferentiallyClosed,
assertWipeSafe,
backupAssetsDir,
backupDir,
backupNameFromSource,
bindValue,
- buildRowTransforms,
canSetReplicationRole,
getCompanyTableCatalog,
getJobDatabaseClient,
@@ -25,6 +23,11 @@ import {
wipeScopedData,
writeBackupManifest
} from "./company-backup";
+import {
+ assertReferentiallyClosed,
+ buildRowTransforms,
+ loadSubstrateIds
+} from "./company-backup.transforms";
import { buildCompanyBackup } from "./company-export";
const INSERT_CHUNK_SIZE = 200;
@@ -52,9 +55,20 @@ async function wipeAndLoad(
remap: boolean;
includeGroup: boolean;
targetGroupId: string | null;
+ /** Target substrate ids (global rows the backup omits); only consulted on a
+ * remap (foreign/template) load so a FK into a seeded global row is kept
+ * verbatim instead of treated as a dangling gap. */
+ substrateIds?: Map<string, Set<unknown>>;
}
): Promise<{ rows: number; idRewrite: Map<string, string> }> {
- const { companyId, userId, remap, includeGroup, targetGroupId } = opts;
+ const {
+ companyId,
+ userId,
+ remap,
+ includeGroup,
+ targetGroupId,
+ substrateIds
+ } = opts;
// Refuse if the schema would let a kept row dangle once we wipe (drift guard).
const safe = assertWipeSafe(catalog);
@@ -138,7 +152,8 @@ async function wipeAndLoad(
targetGroupId,
sourceCompanyId: backup.manifest.sourceCompanyId,
idMaps,
- idRewrite
+ idRewrite,
+ substrateIds
});
for (let r = 0; r < sourceRows.length; r++) {
const row = sourceRows[r]!;
@@ -378,8 +393,17 @@ export const companyRestoreFunction = inngest.createFunction(
// Referential-closure preflight — BEFORE the snapshot/wipe so a backup
// that would dangle a NOT-NULL FK fails with the complete list of gaps
// and leaves the company's data untouched, rather than throwing on the
- // first bad row partway through the load.
- const closure = assertReferentiallyClosed(catalog, backup);
+ // first bad row partway through the load. A company row's FK into shared
+ // substrate (global `material*`/currency rows the backup omits) is not a
+ // gap when the row exists in THIS target's seed — loadSubstrateIds probes
+ // the live target for exactly those ids so the guard doesn't false-flag
+ // them, while still catching a ref present in neither backup nor target.
+ const substrateIds = await loadSubstrateIds(db, catalog, backup.data);
+ const closure = assertReferentiallyClosed(
+ catalog,
+ backup,
+ substrateIds
+ );
if (!closure.ok) {
throw new Error(`This backup can't be restored: ${closure.reason}`);
}
@@ -425,7 +449,8 @@ export const companyRestoreFunction = inngest.createFunction(
userId,
remap: foreign,
includeGroup,
- targetGroupId
+ targetGroupId,
+ substrateIds
});
// 3. Files (best-effort, non-transactional) — copied BEFORE marking ready