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: UX improvements for backups

Sidwebworks1c420590fada
diff --git a/apps/erp/app/modules/settings/backups-archive.server.ts b/apps/erp/app/modules/settings/backups-archive.server.ts
new file mode 100644
index 0000000000..3b1a8a87a2
--- /dev/null
+++ b/apps/erp/app/modules/settings/backups-archive.server.ts
@@ -0,0 +1,65 @@
+import type { Readable } from "node:stream";
+import { createGunzip } from "node:zlib";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { extract as tarExtract } from "tar-stream";
+
+/**
+ * Unpack a `.carbon.tar.gz` (a whole backup folder) into a fresh
+ * `exports/<name>/` so restore/import can read it. Streams entry-by-entry — every
+ * file is small and under the bucket size cap — so a multi-GB prod backup is
+ * never uploaded as one (over-cap) object. Returns the folder name.
+ *
+ * Server-only (tar-stream + zlib). Shared by the Settings upload route and the
+ * onboarding "restore from a backup" flow.
+ */
+export async function unpackBackupArchive(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ source: Readable
+): Promise<{ name: string; fileErrors: number }> {
+ const ts = new Date().toISOString().replace(/[:.]/g, "-");
+ const name = `${ts}_uploaded`;
+ const dir = `exports/${name}`;
+ let manifestSeen = false;
+ let fileErrors = 0;
+
+ const extract = tarExtract();
+ const gunzip = createGunzip();
+ source.on("error", (err) => extract.destroy(err));
+ gunzip.on("error", (err) => extract.destroy(err));
+
+ await new Promise<void>((resolve, reject) => {
+ extract.on("entry", (header, stream, next) => {
+ const chunks: Buffer[] = [];
+ stream.on("data", (c: Buffer) => chunks.push(c));
+ stream.on("error", next);
+ stream.on("end", async () => {
+ try {
+ const rel = header.name;
+ // Reject path traversal; only land files inside this backup's folder.
+ if (rel.includes("..") || rel.startsWith("/")) {
+ 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++;
+ next();
+ } catch (err) {
+ next(err as Error);
+ }
+ });
+ });
+ extract.on("finish", resolve);
+ extract.on("error", reject);
+ source.pipe(gunzip).pipe(extract);
+ });
+
+ if (!manifestSeen) {
+ throw new Error("Archive is missing manifest.json");
+ }
+ return { name, fileErrors };
+}
diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.ts
index 5151b2ba72..2b0c005169 100644
--- a/apps/erp/app/modules/settings/backups.service.ts
+++ b/apps/erp/app/modules/settings/backups.service.ts
@@ -54,6 +54,9 @@ export async function exportCompanyBackup(
export type CompanyBackupSummary = {
/** Backup folder name (also the restore `source` identifier). */
name: string;
+ /** "ready" once manifest.json (the last-written commit marker) exists;
+ * "pending" while the export is still writing the folder. */
+ status: "ready" | "pending";
exportedAt: string | null;
label: string | null;
rows: number;
@@ -83,6 +86,7 @@ export async function listCompanyBackups(
folders.map(async (folder): Promise<CompanyBackupSummary> => {
const summary: CompanyBackupSummary = {
name: folder.name,
+ status: "pending",
exportedAt: null,
label: null,
rows: 0,
@@ -99,6 +103,7 @@ export async function listCompanyBackups(
tables?: Array<{ rows?: number }>;
storage?: Array<{ size?: number; included?: boolean }>;
};
+ summary.status = "ready";
summary.exportedAt = m.exportedAt ?? null;
summary.label = m.label ?? null;
summary.rows = (m.tables ?? []).reduce(
@@ -109,8 +114,8 @@ export async function listCompanyBackups(
.filter((x) => x.included)
.reduce((sum, x) => sum + (x.size ?? 0), 0);
} catch {
- // A folder without a readable manifest is a partial/aborted export —
- // still list it (by name) so the user can delete it.
+ // Manifest present but unreadable — treat as a partial/aborted export
+ // (stays "pending"); still listed by name so the user can delete it.
}
}
return summary;
diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
index 6f960d71ae..2b9b573d16 100644
--- a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
+++ b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
@@ -26,7 +26,7 @@ const triggerClass =
export function BackupSourcePicker({
backups
}: {
- backups: { name: string; exportedAt: string | null }[];
+ backups: { name: string; label: string | null; exportedAt: string | null }[];
}) {
const revalidator = useRevalidator();
const [value, setValue] = useControlField<string>("source");
@@ -38,7 +38,7 @@ export function BackupSourcePicker({
const label = useMemo(() => {
if (current.startsWith("backup:")) {
const match = backups.find((b) => `backup:${b.name}` === current);
- return match ? formatBackupName(match.name) : "Backup";
+ return match ? match.label || formatBackupName(match.name) : "Backup";
}
return "";
}, [current, backups]);
@@ -117,7 +117,7 @@ export function BackupSourcePicker({
>
<LuArchive className="mr-2 h-4 w-4 shrink-0 opacity-60" />
<span className="flex flex-col">
- <span>{formatBackupName(b.name)}</span>
+ <span>{b.label || formatBackupName(b.name)}</span>
<span className="text-xs text-muted-foreground">
{formatBackupDate(b.exportedAt, false)}
</span>
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index e6b073689c..975efcb2bf 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-06-25T03:20:04.068Z",
+ "generated": "2026-06-25T05:27:31.359Z",
"totalTools": 1215,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/api+/settings.backup-upload.ts b/apps/erp/app/routes/api+/settings.backup-upload.ts
index 67980957c1..343aebf534 100644
--- a/apps/erp/app/routes/api+/settings.backup-upload.ts
+++ b/apps/erp/app/routes/api+/settings.backup-upload.ts
@@ -1,15 +1,14 @@
import { Readable } from "node:stream";
-import { createGunzip } from "node:zlib";
import { requirePermissions } from "@carbon/auth/auth.server";
import { isInternalEmail } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
-import { extract as tarExtract } from "tar-stream";
+import { unpackBackupArchive } from "~/modules/settings/backups-archive.server";
/**
* Unpack an uploaded `.carbon.tar.gz` (a whole backup folder) into a fresh
- * `exports/<name>/` so the normal restore/import then finds it. Entries are
- * processed one at a time, so a large archive unpacks at flat memory. The raw
- * archive is the request body (never stored whole).
+ * `exports/<name>/` so the normal restore/import then finds it. The raw archive
+ * is the request body (never stored whole); a large archive unpacks at flat
+ * memory.
*
* NOTE: this receives the upload server-side, so a Vercel-hosted target caps the
* body size. It's for local / self-hosted import targets (the prod -> local case).
@@ -23,53 +22,12 @@ export async function action({ request }: ActionFunctionArgs) {
throw new Response("Expected a tar.gz body", { status: 400 });
}
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
- const name = `${ts}_uploaded`;
- const dir = `exports/${name}`;
-
- let manifestSeen = false;
- let fileErrors = 0;
-
- const extract = tarExtract();
const source = Readable.fromWeb(
request.body as Parameters<typeof Readable.fromWeb>[0]
);
- const gunzip = createGunzip();
- source.on("error", (err) => extract.destroy(err));
- gunzip.on("error", (err) => extract.destroy(err));
-
- await new Promise<void>((resolve, reject) => {
- extract.on("entry", (header, stream, next) => {
- const chunks: Buffer[] = [];
- stream.on("data", (c: Buffer) => chunks.push(c));
- stream.on("error", next);
- stream.on("end", async () => {
- try {
- const rel = header.name;
- // Reject path traversal; only land files inside this backup's folder.
- if (rel.includes("..") || rel.startsWith("/")) {
- 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++;
- next();
- } catch (err) {
- next(err as Error);
- }
- });
- });
- extract.on("finish", resolve);
- extract.on("error", reject);
- source.pipe(gunzip).pipe(extract);
- });
-
- if (!manifestSeen) {
- throw new Response("Archive is missing manifest.json", { status: 400 });
+ try {
+ return await unpackBackupArchive(client, companyId, source);
+ } catch (err) {
+ throw new Response((err as Error).message, { status: 400 });
}
-
- return { name, fileErrors };
}
diff --git a/apps/erp/app/routes/onboarding+/industry.tsx b/apps/erp/app/routes/onboarding+/industry.tsx
index 178e797535..f44ba5ce3e 100644
--- a/apps/erp/app/routes/onboarding+/industry.tsx
+++ b/apps/erp/app/routes/onboarding+/industry.tsx
@@ -33,7 +33,8 @@ import {
Form,
Link,
redirect,
- useLoaderData
+ useLoaderData,
+ useNavigation
} from "react-router";
import { z } from "zod";
import { Hidden, Submit } from "~/components/Form";
@@ -43,10 +44,7 @@ import {
getIndustries,
onboardingCompanyValidator
} from "~/modules/settings";
-import {
- fetchTemplateBackup,
- provisionOnboardingCompany
-} from "~/services/onboarding.server";
+import { provisionOnboardingCompany } from "~/services/onboarding.server";
import {
clearOnboardingDraft,
getOnboardingDraft,
@@ -129,8 +127,7 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(industryValidation.error);
}
- const { industryId, dataChoice } = industryValidation.data;
- const finalIndustryId = industryId || null;
+ const { dataChoice } = industryValidation.data;
// Carry forward the company data captured in the previous (company) step.
if (draft?.company) appendDraftCompany(formData, draft.company);
@@ -149,22 +146,18 @@ export async function action({ request }: ActionFunctionArgs) {
industryId: d.industryId || null
};
- // A demo template and "restore from a backup" both resolve to a backup file;
- // "none" → a clean seed. Only a template references shared assets; a user's
- // own uploaded backup ("import") stays self-contained and is copied per company.
+ // "Restore from a backup" → the user's uploaded `.carbon.tar.gz`; every other
+ // choice → a clean seed (no backup).
const backupFile = formData.get("backup");
const backup: Blob | null =
dataChoice === "import" && backupFile instanceof File && backupFile.size > 0
? backupFile
- : dataChoice === "template"
- ? await fetchTemplateBackup(serviceRole, finalIndustryId)
- : null;
+ : null;
const companyId = await provisionOnboardingCompany(serviceRole, client, {
userId,
companyData,
- backup,
- templateIndustryId: dataChoice === "template" ? finalIndustryId : null
+ backup
});
const companyRecord = await serviceRole
@@ -206,6 +199,10 @@ export default function OnboardingIndustry() {
const [step, setStep] = useState<Step>(getInitialStep);
const [dataChoice, setDataChoice] = useState<DataChoice>("template");
const [importFile, setImportFile] = useState<File | null>(null);
+ const navigation = useNavigation();
+ // Provisioning (unpack + seed + enqueue import) runs in the action and can take
+ // a while for a real backup — keep the button busy so the user doesn't re-submit.
+ const isSubmitting = navigation.state !== "idle";
const [selectedIndustryId, setSelectedIndustryId] = useState<string>(
company?.industryId ?? ""
);
@@ -284,14 +281,14 @@ export default function OnboardingIndustry() {
Choose your backup file
</span>
<span className="text-xs text-muted-foreground">
- A Carbon backup (.carbon.json.gz)
+ A Carbon backup (.carbon.tar.gz)
</span>
</>
)}
<input
type="file"
name="backup"
- accept=".gz,application/gzip"
+ accept=".tar.gz,.tgz,application/gzip"
className="sr-only"
onChange={(e) => setImportFile(e.target.files?.[0] ?? null)}
/>
@@ -303,6 +300,7 @@ export default function OnboardingIndustry() {
variant="solid"
size="md"
type="button"
+ isDisabled={isSubmitting}
onClick={() => setStep("data-question")}
>
Previous
@@ -311,9 +309,10 @@ export default function OnboardingIndustry() {
variant="primary"
size="md"
type="submit"
- isDisabled={!importFile}
+ isLoading={isSubmitting}
+ isDisabled={!importFile || isSubmitting}
>
- Create company
+ {isSubmitting ? "Setting up…" : "Create company"}
</Button>
</HStack>
</CardFooter>
diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsx
index 399ab4c111..7c4fe3b893 100644
--- a/apps/erp/app/routes/x+/settings+/backups.tsx
+++ b/apps/erp/app/routes/x+/settings+/backups.tsx
@@ -254,7 +254,9 @@ export default function BackupsRoute() {
const exportCompleted =
active?.mode === "export" &&
!!active.exportBaseline &&
- files.some((f) => !active.exportBaseline!.has(f.name));
+ files.some(
+ (f) => f.status === "ready" && !active.exportBaseline!.has(f.name)
+ );
// keep / dismiss / revert finalize the run via an async Inngest job, so the
// marker is still present on the next revalidation. Hide the row optimistically
@@ -356,7 +358,9 @@ export default function BackupsRoute() {
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-1.5">
<span className="text-sm">Source</span>
- <BackupSourcePicker backups={files} />
+ <BackupSourcePicker
+ backups={files.filter((f) => f.status === "ready")}
+ />
</div>
<div className="flex flex-col gap-1.5">
<span className="text-sm">Include</span>
@@ -432,35 +436,49 @@ export default function BackupsRoute() {
{files.map((file) => (
<HStack
key={file.name}
- className="w-full justify-between border rounded-lg p-3"
+ className={`w-full justify-between border rounded-lg p-3 ${
+ file.status === "pending" ? "opacity-70" : ""
+ }`}
>
<VStack spacing={0}>
<span className="text-sm font-medium">
- {formatBackupName(file.name)}
+ {file.label || formatBackupName(file.name)}
</span>
<span className="text-xs text-muted-foreground">
- {formatBackupDate(file.exportedAt)}
- {file.sizeBytes ? (
+ {file.status === "pending" ? (
+ <span className="animate-pulse">Preparing…</span>
+ ) : (
<>
- {" · "}
- {convertKbToString(
- Math.round(file.sizeBytes / 1024)
- )}
+ {formatBackupDate(file.exportedAt)}
+ {file.sizeBytes ? (
+ <>
+ {" · "}
+ {convertKbToString(
+ Math.round(file.sizeBytes / 1024)
+ )}
+ </>
+ ) : null}
</>
- ) : null}
+ )}
</span>
</VStack>
<HStack spacing={2}>
- <Button asChild variant="secondary">
- <a
- href={`/api/settings/backup-archive/${encodeURIComponent(
- file.name
- )}`}
- download
- >
+ {file.status === "ready" ? (
+ <Button asChild variant="secondary">
+ <a
+ href={`/api/settings/backup-archive/${encodeURIComponent(
+ file.name
+ )}`}
+ download
+ >
+ Download
+ </a>
+ </Button>
+ ) : (
+ <Button variant="secondary" isDisabled>
Download
- </a>
- </Button>
+ </Button>
+ )}
<Form method="post">
<input type="hidden" name="intent" value="delete" />
<input type="hidden" name="name" value={file.name} />
diff --git a/apps/erp/app/services/onboarding.server.ts b/apps/erp/app/services/onboarding.server.ts
index 322080631a..8c2bfce17b 100644
--- a/apps/erp/app/services/onboarding.server.ts
+++ b/apps/erp/app/services/onboarding.server.ts
@@ -1,3 +1,4 @@
+import { Readable } from "node:stream";
import { CarbonEdition } from "@carbon/auth";
import type { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
@@ -16,56 +17,26 @@ import {
seedCompany,
updateCompany
} from "~/modules/settings";
+import { unpackBackupArchive } from "~/modules/settings/backups-archive.server";
type ServiceRole = ReturnType<typeof getCarbonServiceRole>;
-/** Pull the onboarding backup template for an industry from the shared
- * company-templates bucket, or null when none is committed yet for that
- * industry (caller falls back to a clean company). Templates are uploaded at
- * deploy from packages/database/supabase/backups/<industryId>.carbon.json.gz. */
-export async function fetchTemplateBackup(
- serviceRole: ServiceRole,
- industryId: string | null
-): Promise<Blob | null> {
- if (!industryId) return null;
- const download = await serviceRole.storage
- .from("company-templates")
- .download(`templates/${industryId}.carbon.json.gz`);
- if (download.error) {
- // A missing template is expected (none authored for this industry yet) and
- // falls back to a clean seed. Log so a transient storage failure isn't
- // silently swallowed into an empty company.
- console.warn(
- `No backup template for industry "${industryId}":`,
- download.error.message
- );
- return null;
- }
- return download.data ?? null;
-}
-
/**
- * Provision a freshly-created company's data. Demo and "bring your own data"
- * both resolve to a backup that's reseed-imported on top of an identity-only
- * seed (the backup carries the chart of accounts + business data). With no
- * backup — a clean choice, or a demo with nothing published yet — fall back to
- * a full clean seed.
+ * Provision a freshly-created company's data. "Restore from a backup" resolves
+ * to the user's uploaded `.carbon.tar.gz`, reseed-imported on top of an
+ * identity-only seed (the backup carries the chart of accounts + business data).
+ * With no backup — a clean choice — fall back to a full clean seed.
*/
export async function provisionCompanyData(
serviceRole: ServiceRole,
{
companyId,
userId,
- backup,
- templateIndustryId
+ backup
}: {
companyId: string;
userId: string;
backup: Blob | null;
- /** Set when `backup` is a demo template (vs a user's own uploaded backup).
- * Makes the import reference the template's shared assets instead of
- * copying its files into this company's storage prefix. */
- templateIndustryId?: string | null;
}
): Promise<void> {
if (!backup) {
@@ -85,17 +56,18 @@ export async function provisionCompanyData(
throw new Error("Fatal: failed to seed company");
}
- const filePath = "exports/onboarding-import.carbon.json.gz";
- const upload = await serviceRole.storage
- .from(companyId)
- .upload(filePath, backup, {
- upsert: true,
- contentType: "application/gzip"
- });
- if (upload.error) {
- console.error(upload.error);
- throw new Error("Fatal: failed to upload import file");
- }
+ // The user's `.carbon.tar.gz`: unpack into a fresh `exports/<name>/` folder so
+ // it imports like any other backup. Uploading the archive as one object would
+ // exceed the bucket's per-object size cap (413) for a real prod backup carrying
+ // media. The import reads the folder via readBackup(<name>).
+ const source = Readable.fromWeb(
+ backup.stream() as Parameters<typeof Readable.fromWeb>[0]
+ );
+ const { name: filePath } = await unpackBackupArchive(
+ serviceRole,
+ companyId,
+ source
+ );
// Kick off the import. The job runs asynchronously (the company's data
// populates shortly after onboarding finishes), but the *enqueue* is awaited
@@ -109,8 +81,7 @@ export async function provisionCompanyData(
filePath,
mode: "reseed",
importRunId: nanoid(),
- autoFinalize: true,
- ...(templateIndustryId ? { templateIndustryId } : {})
+ autoFinalize: true
});
} catch (err) {
console.error(err);
@@ -122,7 +93,7 @@ export async function provisionCompanyData(
* Insert-or-update the onboarding company, provision its data, and create the
* headquarters location plus the owner's employee job. Returns the companyId.
* Shared by the public company step (clean seed, `backup: null`) and the
- * internal data-choice step (demo template / backup import).
+ * internal data-choice step (restore from an uploaded backup).
*/
export async function provisionOnboardingCompany(
serviceRole: ServiceRole,
@@ -130,8 +101,7 @@ export async function provisionOnboardingCompany(
{
userId,
companyData,
- backup,
- templateIndustryId
+ backup
}: {
userId: string;
companyData: z.infer<typeof companyValidator> & {
@@ -139,7 +109,6 @@ export async function provisionOnboardingCompany(
customIndustryDescription?: string | null;
};
backup: Blob | null;
- templateIndustryId?: string | null;
}
): Promise<string> {
const companies = await getCompanies(client, userId);
@@ -195,8 +164,7 @@ export async function provisionOnboardingCompany(
await provisionCompanyData(serviceRole, {
companyId,
userId,
- backup,
- templateIndustryId
+ backup
});
if (CarbonEdition === Edition.Cloud) {
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index 292cb3afcd..ca02d068d1 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -8,7 +8,7 @@ import {
type KyselyDatabase
} from "@carbon/database/client";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { type Kysely, PostgresDriver, sql } from "kysely";
+import { type Kysely, PostgresDriver, type RawBuilder, sql } from "kysely";
import { nanoid } from "nanoid";
/**
@@ -187,13 +187,30 @@ export type ForeignKey = {
refColumn: string;
};
+/**
+ * How a table's rows are scoped to a company:
+ * - `direct`: the table itself has a `companyId`/`companyGroupId` column.
+ * - `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
+ * child tables (contacts, locations, line prices, history) travel with their
+ * parent without a hand-maintained list.
+ */
+export type Scope =
+ | { kind: "direct"; column: "companyId" | "companyGroupId" }
+ | { kind: "via"; column: string; refColumn: string; parent: string };
+
export type TableInfo = {
name: string;
columns: ColumnInfo[];
+ /** How the table is scoped to a company (direct column or via a parent FK). */
+ scope: Scope;
/**
- * The tenant column the rows are filtered/stamped by. Most data is
- * `companyId`-scoped; the chart of accounts and other shared config
- * (account, currency, dimension, …) is `companyGroupId`-scoped.
+ * The resolved ROOT tenant column the rows ultimately belong to — `companyId`
+ * for most data, `companyGroupId` for shared config (chart of accounts,
+ * currencies, …). For a `via` table it's the root ancestor's column. Used for
+ * the "which tenant" decisions (wipe/reseed scope); the actual row filter is
+ * built by `buildScopeFilter`.
*/
scopeColumn: "companyId" | "companyGroupId";
/** primary key column names (empty when the table has no PK) */
@@ -272,6 +289,27 @@ export function backupAssetsDir(name: string): string {
return `${EXPORTS_PREFIX}/${name}/assets`;
}
+/**
+ * Write `manifest.json` — the LAST thing written for a backup, after every table
+ * file and asset is in place. Its presence is the "backup is complete" marker:
+ * the UI lists a folder without a manifest as still-preparing (no size yet), and
+ * restore/import refuse to read one until its manifest exists.
+ */
+export async function writeBackupManifest(
+ client: SupabaseClient,
+ companyId: string,
+ name: string,
+ manifest: Manifest
+): Promise<void> {
+ const up = await client.storage
+ .from(companyId)
+ .upload(backupManifestPath(name), Buffer.from(JSON.stringify(manifest)), {
+ contentType: "application/json",
+ upsert: true
+ });
+ if (up.error) throw new Error(`manifest: ${up.error.message}`);
+}
+
/**
* Gzip one table's rows as NDJSON (one JSON object per line). Streamed, so a huge
* table never builds a `>512MB` string.
@@ -407,7 +445,6 @@ export async function getCompanyTableCatalog(
scopeByTable.set(r.name, "companyGroupId");
}
}
- const tableSet = new Set(scopeByTable.keys());
const columns = await sql<{
table_name: string;
@@ -460,6 +497,49 @@ export async function getCompanyTableCatalog(
WHERE con.contype = 'f' AND nsp.nspname = 'public'
`.execute(db);
+ // FK graph for EVERY table (not just the directly-scoped ones), so scope can
+ // be resolved transitively below.
+ const allFksByTable = new Map<string, ForeignKey[]>();
+ for (const f of foreignKeys.rows) {
+ const list = allFksByTable.get(f.table_name) ?? [];
+ list.push({
+ column: f.column_name,
+ refTable: f.ref_table,
+ refColumn: f.ref_column
+ });
+ allFksByTable.set(f.table_name, list);
+ }
+
+ // Resolve scope transitively: a table with no companyId/companyGroupId column
+ // but a FK to an already-scoped table inherits that scope (nearest scoped
+ // parent wins — BFS by passes converges on the shortest path). This pulls in
+ // child tables (contacts, locations, line prices, status history, …) without a
+ // hand-maintained list.
+ const scope = new Map<string, Scope>();
+ const scopeRoot = new Map<string, "companyId" | "companyGroupId">();
+ for (const [name, column] of scopeByTable) {
+ scope.set(name, { kind: "direct", column });
+ scopeRoot.set(name, column);
+ }
+ let resolvedMore = true;
+ while (resolvedMore) {
+ resolvedMore = false;
+ for (const [name, fks] of allFksByTable) {
+ if (scope.has(name) || structural.has(name)) continue;
+ const fk = fks.find((f) => f.refTable !== name && scope.has(f.refTable));
+ if (!fk) continue;
+ scope.set(name, {
+ kind: "via",
+ column: fk.column,
+ refColumn: fk.refColumn,
+ parent: fk.refTable
+ });
+ scopeRoot.set(name, scopeRoot.get(fk.refTable)!);
+ resolvedMore = true;
+ }
+ }
+ const tableSet = new Set(scope.keys());
+
let schemaVersion = "unknown";
try {
const migration = await sql<{ version: string }>`
@@ -511,7 +591,8 @@ export async function getCompanyTableCatalog(
return {
name,
columns: columnsByTable.get(name) ?? [],
- scopeColumn: scopeByTable.get(name)!,
+ scope: scope.get(name)!,
+ scopeColumn: scopeRoot.get(name)!,
pkColumns,
hasId: pkColumns.length === 1 && pkColumns[0] === "id",
foreignKeys: fksByTable.get(name) ?? []
@@ -668,6 +749,41 @@ export function bindValue(value: unknown, col: ColumnInfo): unknown {
return value;
}
+/**
+ * A SQL predicate scoping a table's rows to one company. For a directly-scoped
+ * table it's `companyId = $`; for a `via` table it's
+ * `fk IN (SELECT parent.refColumn FROM parent WHERE <parent's predicate>)`,
+ * recursing to the scoped root. The subquery is NOT correlated (it lists the
+ * parent's ids for the company), so it stays a cheap semi-join. `byName` must
+ * hold every catalog table so parents resolve.
+ */
+export function buildScopeFilter(
+ table: TableInfo,
+ byName: Map<string, TableInfo>,
+ companyId: string,
+ companyGroupId: string | null
+): RawBuilder<unknown> {
+ if (table.scope.kind === "direct") {
+ const value =
+ table.scope.column === "companyGroupId" ? companyGroupId : companyId;
+ return sql`${sql.id(table.scope.column)} = ${value}`;
+ }
+ const parent = byName.get(table.scope.parent);
+ if (!parent) {
+ throw new Error(
+ `Scope parent "${table.scope.parent}" of "${table.name}" is not in the catalog`
+ );
+ }
+ return sql`${sql.id(table.scope.column)} IN (SELECT ${sql.id(
+ table.scope.refColumn
+ )} FROM ${sql.id(table.scope.parent)} WHERE ${buildScopeFilter(
+ parent,
+ byName,
+ companyId,
+ companyGroupId
+ )})`;
+}
+
/**
* Of the given tables, return only those the target has NOT yet populated in
* its scope (companyId or companyGroupId). Reseed import uses this so it
@@ -677,18 +793,16 @@ export function bindValue(value: unknown, col: ColumnInfo): unknown {
export async function filterUnpopulated(
db: Kysely<KyselyDatabase>,
tables: TableInfo[],
+ byName: Map<string, TableInfo>,
companyId: string,
companyGroupId: string | null
): Promise<TableInfo[]> {
const isEmpty = await Promise.all(
tables.map(async (t) => {
- const scopeValue =
- t.scopeColumn === "companyGroupId" ? companyGroupId : companyId;
- if (scopeValue === null) return true;
const result = await sql<{ present: boolean }>`
SELECT EXISTS(
SELECT 1 FROM ${sql.id(t.name)}
- WHERE ${sql.id(t.scopeColumn)} = ${scopeValue}
+ WHERE ${buildScopeFilter(t, byName, companyId, companyGroupId)}
) AS present
`.execute(db);
return !result.rows[0]?.present;
@@ -799,17 +913,16 @@ export function assertWipeSafe(
export async function wipeScopedData(
trx: Kysely<KyselyDatabase>,
tables: TableInfo[],
+ byName: Map<string, TableInfo>,
scope: { companyId: string; companyGroupId: string | null }
): Promise<void> {
for (const table of [...tables].reverse()) {
- const value =
- table.scopeColumn === "companyGroupId"
- ? scope.companyGroupId
- : scope.companyId;
- if (value == null) continue;
+ // buildScopeFilter scopes by parent FK for `via` tables; a null
+ // companyGroupId yields `= NULL` (no match), so group data is left untouched
+ // when the company has no group.
await sql`
DELETE FROM ${sql.id(table.name)}
- WHERE ${sql.id(table.scopeColumn)} = ${value}
+ WHERE ${buildScopeFilter(table, byName, scope.companyId, scope.companyGroupId)}
`.execute(trx);
}
}
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index 63135504b9..b0e2cd5c14 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -7,8 +7,8 @@ import {
BACKUP_KIND,
BACKUP_VERSION,
backupAssetsDir,
- backupManifestPath,
backupTablePath,
+ buildScopeFilter,
copyAssetsToBackup,
encodeValue,
getCompanyTableCatalog,
@@ -16,7 +16,8 @@ import {
mapWithConcurrency,
SECRET_TABLES,
STORAGE_BUCKET,
- serializeTable
+ serializeTable,
+ writeBackupManifest
} from "./company-backup";
// Assets are copied server-side into the backup's `assets/` folder (no bytes pass
@@ -95,24 +96,24 @@ export async function buildCompanyBackup(
.filter((t) => secretTables.has(t.name))
.map((t) => t.name);
const exportable = catalog.tables.filter((t) => !secretTables.has(t.name));
+ const byName = new Map(catalog.tables.map((t) => [t.name, t]));
// Dump each non-empty table to its own `tables/<table>.ndjson.gz`, in parallel.
const tableManifest: Manifest["tables"] = [];
await mapWithConcurrency(exportable, TABLE_CONCURRENCY, async (table) => {
- // companyGroup-scoped tables (chart of accounts, currencies, …) are filtered
- // by the company's group; everything else by companyId.
- const scopeValue =
- table.scopeColumn === "companyGroupId" ? companyGroupId : companyId;
const columns = table.columns.filter((c) => !c.isGenerated);
// a prior import's revert ledger must never travel in an artifact
const ledgerFilter =
table.name === "externalIntegrationMapping"
? sql` AND ${sql.id("integration")} != ${BACKUP_INTEGRATION}`
: sql``;
+ // Direct-scoped tables filter by their companyId/companyGroupId column;
+ // transitively-scoped child tables (contacts, line prices, …) filter through
+ // their parent FK — see buildScopeFilter.
const result = await sql<Record<string, unknown>>`
SELECT ${sql.join(columns.map((c) => sql.id(c.name)))}
FROM ${sql.id(table.name)}
- WHERE ${sql.id(table.scopeColumn)} = ${scopeValue}${ledgerFilter}
+ WHERE ${buildScopeFilter(table, byName, companyId, companyGroupId)}${ledgerFilter}
`.execute(db);
if (result.rows.length === 0) return; // empty tables get no file
@@ -181,16 +182,8 @@ export async function buildCompanyBackup(
excludedTables
};
- const manifestUpload = await client.storage
- .from(companyId)
- .upload(backupManifestPath(name), Buffer.from(JSON.stringify(manifest)), {
- contentType: "application/json",
- upsert: true
- });
- if (manifestUpload.error) {
- throw new Error(`manifest: ${manifestUpload.error.message}`);
- }
-
+ // The manifest is NOT written here — the caller writes it LAST (after assets)
+ // via writeBackupManifest, so its presence marks the backup as complete.
const rows = tableManifest.reduce((sum, t) => sum + t.rows, 0);
return { name, manifest, rows, assetSourcePaths };
}
@@ -218,14 +211,18 @@ export const companyExportFunction = inngest.createFunction(
});
// Copy the in-scope assets server-side into the backup's `assets/` folder.
- // Best-effort (matches restore/import): the table files + manifest are
- // already committed.
+ // Best-effort (matches restore/import): the table files are already
+ // committed; per-file copy failures only warn.
const assets = await copyAssetsToBackup(client, {
sourcePaths: assetSourcePaths,
destBucket: companyId,
destPrefix: backupAssetsDir(name)
});
+ // Manifest LAST — its presence marks the backup complete, so the list never
+ // shows a half-written backup as ready.
+ await writeBackupManifest(client, companyId, name, manifest);
+
console.log("Company export complete", {
companyId,
name,
diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.ts
index fdbd4c48ab..af549672bc 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-import.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts
@@ -147,11 +147,13 @@ export const companyImportFunction = inngest.createFunction(
// are non-empty replaces every hand-maintained "skip" list and is
// correct in both cases: a bare clone imports everything, an
// identity-seeded onboard skips exactly what's already there.
+ const byName = new Map(catalog.tables.map((t) => [t.name, t]));
const importTables =
mode === "reseed"
? await filterUnpopulated(
db,
candidateTables,
+ byName,
companyId,
targetGroupId
)
diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
index da0b171ec9..d3b149a904 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts
@@ -26,7 +26,8 @@ import {
rewriteStoragePath,
STORAGE_PATH_COLUMNS,
selectWipeableTables,
- wipeScopedData
+ wipeScopedData,
+ writeBackupManifest
} from "./company-backup";
import { buildCompanyBackup } from "./company-export";
@@ -147,6 +148,7 @@ async function wipeAndLoad(
// Wipe every restorable table (so tables empty in the backup end up empty);
// reload only those the backup actually has rows for.
+ const byName = new Map(catalog.tables.map((t) => [t.name, t]));
const wipeTables = selectWipeableTables(catalog, { includeGroup });
const loadTables = wipeTables.filter(
(t) => (backup.data[t.name]?.length ?? 0) > 0
@@ -186,7 +188,7 @@ async function wipeAndLoad(
await sql`SET LOCAL session_replication_role = 'replica'`.execute(trx);
}
- await wipeScopedData(trx, wipeTables, {
+ await wipeScopedData(trx, wipeTables, byName, {
companyId,
companyGroupId: targetGroupId
});
@@ -459,16 +461,23 @@ export const companyRestoreFunction = inngest.createFunction(
// capture the WIPED state and overwrite the real pre-restore copy.
let snapshotPath = existing?.metadata.snapshotPath ?? undefined;
if (!snapshotPath) {
- // buildCompanyBackup writes the snapshot folder (tables + manifest)
- // directly; the marker stores the folder name.
+ // buildCompanyBackup writes the snapshot's table files; the manifest is
+ // written last (its presence marks the snapshot complete). The marker
+ // stores the folder name.
snapshotPath = `_pre-restore-${restoreRunId}`;
- await buildCompanyBackup(client, db, {
+ const snapshot = await buildCompanyBackup(client, db, {
companyId,
userId,
label: `Pre-restore ${restoreRunId}`,
includeStorage: "all",
name: snapshotPath
});
+ await writeBackupManifest(
+ client,
+ companyId,
+ snapshotPath,
+ snapshot.manifest
+ );
await writeRestoreMarker(client, {
companyId,
userId,