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: backup restore

Sidwebworks3defdc5f6f82
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 6b5b9e543f..0bc0c6768b 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -65,3 +65,13 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** In migrations that insert `account` rows, resolve the parent group by `"isGroup" = TRUE AND name = '<Group Name>'` (optionally + class), never by number — and treat a NULL parent as an error or explicit fallback, never insert silently orphaned. `20260630093809_ar-ap-payments.sql` is the correct precedent. When a past migration did orphan accounts, ship a follow-up UPDATE re-parenting `parentId IS NULL` rows to the group `seed.data.ts` assigns (see `20260702192816`).
**Applies to:** `packages/database/supabase/migrations/` touching `account`; `packages/database/supabase/functions/lib/seed.data.ts`; anything walking the chart-of-accounts tree.
+
+## Client-side entity caches must be company-keyed in a multi-tenant app
+
+**Context:** A prod company export failed its closure guard: a `salesOrder` (and its `opportunity`) in one company referenced another company's customer. Root cause chain: `RealtimeDataProvider` (ERP + MES) cached the customer/item/supplier/people lists in IndexedDB under **global** keys (`"customers"`), and company switching is a client-side navigation — so after a switch, the previous company's cached list could hydrate the pickers before the properly-scoped server fetch landed. Nothing downstream caught the bad pick: zod validated `customerId` as a bare string, services inserted it blindly, RLS only checks the row's own `companyId`, and the FK was single-column (`customerId → customer(id)`).
+
+**Problem:** Any client cache (IndexedDB/localforage, localStorage, nanostores hydrated from them) that isn't keyed by `companyId` becomes a cross-tenant leak the moment a multi-company user switches companies without a full reload. Multi-company users legitimately pass RLS for both companies, so no server layer notices.
+
+**Rule:** (1) Key every persisted client cache entry by company (`customers:${companyId}`) and guard async hydration callbacks against mid-flight company switches. (2) Tenant-scoped references between tables should be composite FKs `(refId, companyId) → parent(id, companyId)` so the DB rejects cross-company refs from every write path (see `20260703143904_composite-tenant-fks.sql`, which converts customer/supplier refs introspectively and tolerates pre-existing bad rows via NOT VALID + warning).
+
+**Applies to:** `apps/{erp,mes}/app/components/RealtimeDataProvider.tsx`, `apps/erp/app/stores/*`, any new client-side cache; migrations adding FKs to company-scoped parents.
diff --git a/.ai/rules/company-backup-restore.md b/.ai/rules/company-backup-restore.md
index 5547af1043..4da5b66dda 100644
--- a/.ai/rules/company-backup-restore.md
+++ b/.ai/rules/company-backup-restore.md
@@ -109,6 +109,16 @@ postings simply has no `journalLine`/`costLedger` rows; that is data-absence, no
coverage gap. With `includeStorage: "all"`, `buildCompanyBackup` records the
in-scope asset paths in `manifest.storage` and returns them; the job then
`copyAssetsToBackup` them server-side into the backup's `.assets/` folder.
+- **Progress/failure marker**: one `externalIntegrationMapping` row per company
+ (`integration = "company-export"`, no run id — exports are one-at-a-time per
+ company). The job writes `{ status: "running", startedAt, progress }` heartbeats
+ (throttled 250ms), **clears the marker on success** (the new backup appearing in
+ the list is the completion signal), and **flips it to
+ `{ status: "failed", error }` on error** — it is NOT cleared on failure; a
+ cleared marker made a broken export indistinguishable from one that never ran.
+ The failed marker is dismissed from the UI via the `dismissExportFailure`
+ intent → `dismissCompanyExportFailure` (service role — the table has no DELETE
+ policy), and the next export's `upsertExportMarker` reuses the row.
- **Asset cap** (`company-export.ts`): no per-file cap (the bucket already bounds
uploads — 120MB CAD, 50MB docs; the `private` bucket's own limit is the dev
`50MiB` global in `config.toml`), only a `MAX_STORAGE_TOTAL_BYTES = 1GiB` guard on
@@ -192,17 +202,30 @@ snapshotPath, foreign, includeGroup }`. `revert` reads the marker and reloads
## ERP layer
- `backups.service.ts` — per-company bucket ops: `exportCompanyBackup`,
- `listCompanyBackupExports` (`from(companyId).list("exports")` — folder entries
- like `.assets/` have `id === null` and the loader filters them out, so only gz
- files show as backups), `getCompanyBackupSignedUrl`, `deleteCompanyBackupExport`
- (removes the gz **and** recursively its `.assets/` folder so the bucket space is
- released), `getCompanyRestoreRuns` (reads the markers).
+ `listCompanyBackups` (`from(companyId).list("exports")` folders; a folder is
+ "ready" once `manifest.json` exists, else "pending"), `deleteCompanyBackup`
+ (removes the whole `exports/<name>/` folder), `getCompanyRestoreRuns` (restore
+ markers), `getCompanyExportRun` (the export marker: `status:
+ "running" | "failed"`, `progress`, `startedAt`, `error`).
- `backups.server.ts` — server-only trigger wrappers (`startCompanyRestore`,
- `finalizeCompanyRestore`, `revertCompanyRestore`) — kept off the client to avoid
- `Buffer`-in-client.
+ `finalizeCompanyRestore`, `revertCompanyRestore`) plus
+ `dismissCompanyExportFailure` (service-role delete of the failed export
+ marker) — kept off the client to avoid `Buffer`-in-client.
- `routes/x+/settings+/backups.tsx` — **internal-gated** (`requireInternal`)
- loader/action (export / restore / keep / dismiss / revert / delete intents).
- `filePath` is forced under `exports/`.
+ loader/action (export / restore / keep / dismiss / revert / delete /
+ dismissExportFailure intents). `filePath` is forced under `exports/`. Export is
+ **non-blocking, row-first** (Supabase-style): clicking "Create backup" does NOT
+ open a modal — it drops a synthetic "Creating backup…" spinner row into the
+ Backups list **immediately** (optimistic client state `runningExport`, set the
+ instant the action returns `started: "export"`, before the job writes its first
+ marker), and clicking that row opens the detail progress modal. `runningExport`
+ is also **adopted from the marker** on mount for a run started elsewhere
+ (reload / another tab); its `baseline` = ready backups when tracking began, and
+ completion = a ready backup outside the baseline appearing in the revalidated
+ list (page revalidates every 2.5s while the modal is closed). A "failed" marker
+ renders a banner ("The system created an invalid backup — please contact Carbon
+ support." + error) with a Dismiss button; "pending" folders with no tracked
+ export are labeled "Incomplete backup — not restorable" (never "Preparing…").
- `routes/api+/settings.backup-summary.ts` — lazy "what's in a backup" counts,
grouped, per-entity `scope: company|group`.
- `routes/api+/settings.backup-restore-status.$restoreRunId.ts` — poll; `companyId`
diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsx
index ce0f957bf0..9240486f58 100644
--- a/apps/erp/app/components/RealtimeDataProvider.tsx
+++ b/apps/erp/app/components/RealtimeDataProvider.tsx
@@ -15,9 +15,16 @@ import {
import type { Item } from "~/stores/items";
import type { ListItem } from "~/types";
-let hydratedFromIdb = false;
+// IndexedDB entries are keyed per company (`customers:<companyId>`) — a global
+// key let one company's cached list hydrate the pickers after switching to
+// another company, which produced cross-tenant refs (e.g. a salesOrder pointing
+// at another company's customer). `activeCompanyId` also guards the async idb /
+// fetch callbacks racing a mid-flight company switch.
+let activeCompanyId: string | null = null;
let hydratedFromServer = false;
+const LEGACY_IDB_KEYS = ["customers", "items", "suppliers", "people"];
+
const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
const { carbon, accessToken } = useCarbon();
const {
@@ -81,21 +88,30 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
const hydrate = async () => {
const idb = (await import("localforage")).default;
- if (!hydratedFromIdb) {
- hydratedFromIdb = true;
+ const requestedCompanyId = companyId;
+ if (activeCompanyId !== requestedCompanyId) {
+ activeCompanyId = requestedCompanyId;
+
+ // pre-keying entries were global; purge so they can never hydrate again
+ for (const key of LEGACY_IDB_KEYS) {
+ void idb.removeItem(key);
+ }
- idb.getItem("customers").then((data) => {
- if (data && !hydratedFromServer) setCustomers(data as ListItem[], true);
+ const fresh = () =>
+ !hydratedFromServer && activeCompanyId === requestedCompanyId;
+
+ idb.getItem(`customers:${requestedCompanyId}`).then((data) => {
+ if (data && fresh()) setCustomers(data as ListItem[], true);
});
- idb.getItem("items").then((data) => {
- if (data && !hydratedFromServer) setItems(data as Item[], true);
+ idb.getItem(`items:${requestedCompanyId}`).then((data) => {
+ if (data && fresh()) setItems(data as Item[], true);
});
- idb.getItem("suppliers").then((data) => {
- if (data && !hydratedFromServer) setSuppliers(data as ListItem[], true);
+ idb.getItem(`suppliers:${requestedCompanyId}`).then((data) => {
+ if (data && fresh()) setSuppliers(data as ListItem[], true);
});
- idb.getItem("people").then((data) => {
+ idb.getItem(`people:${requestedCompanyId}`).then((data) => {
// @ts-ignore
- if (data && !hydratedFromServer) setPeople(data, true);
+ if (data && fresh()) setPeople(data, true);
});
}
@@ -175,6 +191,9 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
throw new Error("Failed to fetch people");
}
+ // company switched while fetching — these results belong to the old company
+ if (activeCompanyId !== requestedCompanyId) return;
+
hydratedFromServer = true;
const supersessionByItem = new Map(
@@ -191,10 +210,10 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
setPeople(people.data ?? []);
await Promise.all([
- idb.setItem("items", itemsWithLifecycle),
- idb.setItem("suppliers", suppliers.data),
- idb.setItem("customers", customers.data),
- idb.setItem("people", people.data)
+ idb.setItem(`items:${requestedCompanyId}`, itemsWithLifecycle),
+ idb.setItem(`suppliers:${requestedCompanyId}`, suppliers.data),
+ idb.setItem(`customers:${requestedCompanyId}`, customers.data),
+ idb.setItem(`people:${requestedCompanyId}`, people.data)
]);
fetchQuantities();
diff --git a/apps/erp/app/modules/settings/backups.server.ts b/apps/erp/app/modules/settings/backups.server.ts
index 11a0ed1a57..d2db3aac67 100644
--- a/apps/erp/app/modules/settings/backups.server.ts
+++ b/apps/erp/app/modules/settings/backups.server.ts
@@ -1,3 +1,4 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { trigger } from "@carbon/jobs";
import { nanoid } from "nanoid";
@@ -38,3 +39,20 @@ export async function revertCompanyRestore(args: {
}): Promise<void> {
await trigger("company-restore-revert", args);
}
+
+/**
+ * Clear the failed-export marker once the user has acknowledged it. Service
+ * role: `externalIntegrationMapping` has no DELETE policy, and the marker is
+ * written by the export job (see EXPORT_INTEGRATION in
+ * packages/jobs/src/inngest/functions/tasks/company-export.ts).
+ */
+export async function dismissCompanyExportFailure(
+ companyId: string
+): Promise<void> {
+ const serviceRole = getCarbonServiceRole();
+ await serviceRole
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("integration", "company-export")
+ .eq("companyId", companyId);
+}
diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.ts
index eecffa42f4..6e34251681 100644
--- a/apps/erp/app/modules/settings/backups.service.ts
+++ b/apps/erp/app/modules/settings/backups.service.ts
@@ -180,20 +180,25 @@ export async function getCompanyRestoreRuns(
return { data: runs, error: null };
}
+export type CompanyExportRun = {
+ status: "running" | "failed";
+ progress: { phase: string; done: number; total: number } | null;
+ startedAt: string | null;
+ error: string | null;
+};
+
/**
- * The in-flight export's live progress, or null when none is running. One marker
- * per company (integration = 'company-export'), written by the export job and
- * cleared when it finishes — so its absence means "not running" (the new backup
- * appearing in the list is what signals completion).
+ * The current export marker, or null when none. One marker per company
+ * (integration = 'company-export'), written by the export job: absent = not
+ * running (the new backup appearing in the list is what signals completion),
+ * "running" = in flight, "failed" = the last export died and the user hasn't
+ * dismissed it yet.
*/
export async function getCompanyExportRun(
client: SupabaseClient<Database>,
companyId: string
): Promise<{
- data: {
- progress: { phase: string; done: number; total: number } | null;
- startedAt: string | null;
- } | null;
+ data: CompanyExportRun | null;
error: Error | null;
}> {
const marker = await client
@@ -207,13 +212,17 @@ export async function getCompanyExportRun(
if (!marker.data) return { data: null, error: null };
const meta = (marker.data.metadata ?? {}) as {
+ status?: "running" | "failed";
startedAt?: string;
progress?: { phase: string; done: number; total: number };
+ error?: string;
};
return {
data: {
+ status: meta.status ?? "running",
progress: meta.progress ?? null,
- startedAt: meta.startedAt ?? marker.data.createdAt
+ startedAt: meta.startedAt ?? marker.data.createdAt,
+ error: meta.error ?? null
},
error: null
};
diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
index 081843ebca..1b0f8fe138 100644
--- a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
+++ b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
@@ -134,11 +134,14 @@ export function JobProgressModal({
}>();
// Export reports progress via a separate company-scoped marker (no run id).
const exportFetcher = useFetcher<{
+ status: "running" | "failed" | null;
progress: { phase: string; done: number; total: number } | null;
startedAt: string | null;
+ error: string | null;
}>();
const raw = statusFetcher.data?.status;
- const failed = !isExport && raw === "failed";
+ const exportFailed = isExport && exportFetcher.data?.status === "failed";
+ const failed = (!isExport && raw === "failed") || exportFailed;
const restoreReady = mode === "restore" && raw === "ready";
const revertDone = isRevert && raw === "gone";
@@ -146,7 +149,9 @@ export function JobProgressModal({
const done = success || failed;
const rows = statusFetcher.data?.rows ?? 0;
- const error = statusFetcher.data?.error;
+ const error = isExport
+ ? exportFetcher.data?.error
+ : statusFetcher.data?.error;
const progress = isExport
? (exportFetcher.data?.progress ?? null)
: (statusFetcher.data?.progress ?? null);
@@ -244,9 +249,11 @@ export function JobProgressModal({
? "Reverting…"
: "Restoring…";
const title = failed
- ? isRevert
- ? "Revert failed"
- : "Restore failed"
+ ? isExport
+ ? "Backup failed"
+ : isRevert
+ ? "Revert failed"
+ : "Restore failed"
: success
? isExport
? "Backup ready"
@@ -256,8 +263,10 @@ export function JobProgressModal({
: workingTitle;
// The modal just reports progress — keep/revert is decided from the review
- // card, so any terminal (or slow/stalled) state is dismissable.
- const dismissable = done || slow || stalled;
+ // card, so any terminal (or slow/stalled) state is dismissable. Export is
+ // dismissable from the start: the run is fully server-side, and the list
+ // shows an in-progress row that reopens this modal.
+ const dismissable = done || slow || stalled || isExport;
return (
<Modal
@@ -285,14 +294,30 @@ export function JobProgressModal({
) : failed ? (
<div className="flex flex-col items-center gap-3 py-4">
<LuTriangleAlert className="h-8 w-8 text-destructive-foreground duration-300 animate-in fade-in zoom-in-75 motion-reduce:animate-none" />
- <p className="text-center text-sm text-muted-foreground">
- {error ?? "Something went wrong."}
- </p>
- {!isRevert && (
- <p className="text-center text-xs text-muted-foreground">
- Your data was not changed — the restore stops before touching
- anything if it can't complete.
- </p>
+ {isExport ? (
+ <>
+ <p className="text-center text-sm text-muted-foreground">
+ The system created an invalid backup — please contact Carbon
+ support.
+ </p>
+ {error ? (
+ <p className="max-w-full break-words text-center text-xs text-muted-foreground">
+ {error}
+ </p>
+ ) : null}
+ </>
+ ) : (
+ <>
+ <p className="text-center text-sm text-muted-foreground">
+ {error ?? "Something went wrong."}
+ </p>
+ {!isRevert && (
+ <p className="text-center text-xs text-muted-foreground">
+ Your data was not changed — the restore stops before
+ touching anything if it can't complete.
+ </p>
+ )}
+ </>
)}
</div>
) : (
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 8d8b81597a..ddc21bbce1 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-07-04T04:05:20.422Z",
+ "generated": "2026-07-04T10:15:13.582Z",
"totalTools": 1254,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/api+/settings.backup-export-status.ts b/apps/erp/app/routes/api+/settings.backup-export-status.ts
index 56a8ffc731..a40eef863d 100644
--- a/apps/erp/app/routes/api+/settings.backup-export-status.ts
+++ b/apps/erp/app/routes/api+/settings.backup-export-status.ts
@@ -3,10 +3,11 @@ import { isInternalEmail } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { getCompanyExportRun } from "~/modules/settings";
-// Polled by the export progress modal for live phase/done/total. One marker per
-// company (the export job writes it while running, clears it when done), so a
-// null `progress` means the run hasn't written its first heartbeat yet OR has
-// finished — the modal uses the backup list appearing to confirm completion.
+// Polled by the export progress modal (and the in-progress list row) for live
+// phase/done/total. One marker per company: the export job writes it while
+// running, clears it on success and flips it to "failed" on error — so a null
+// `status` means the run hasn't written its first heartbeat yet OR has finished;
+// the modal uses the backup list appearing to confirm completion.
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, email } = await requirePermissions(request, {
update: "settings"
@@ -15,7 +16,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
const run = await getCompanyExportRun(client, companyId);
return {
+ status: run.data?.status ?? null,
progress: run.data?.progress ?? null,
- startedAt: run.data?.startedAt ?? null
+ startedAt: run.data?.startedAt ?? null,
+ error: run.data?.error ?? null
};
}
diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsx
index 7c4fe3b893..5ffb60a43b 100644
--- a/apps/erp/app/routes/x+/settings+/backups.tsx
+++ b/apps/erp/app/routes/x+/settings+/backups.tsx
@@ -26,17 +26,27 @@ import {
} from "@carbon/react";
import { convertKbToString, isInternalEmail } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { LuLoaderCircle } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, Form, redirect, useFetcher, useLoaderData } from "react-router";
+import {
+ data,
+ redirect,
+ useFetcher,
+ useLoaderData,
+ useRevalidator
+} from "react-router";
import { z } from "zod";
+import type { CompanyBackupSummary } from "~/modules/settings";
import {
deleteCompanyBackup,
exportCompanyBackup,
+ getCompanyExportRun,
getCompanyRestoreRuns,
listCompanyBackups
} from "~/modules/settings";
import {
+ dismissCompanyExportFailure,
finalizeCompanyRestore,
revertCompanyRestore,
startCompanyRestore
@@ -89,15 +99,17 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
requireInternal(email);
- const [backupsList, restoreRuns] = await Promise.all([
+ const [backupsList, restoreRuns, exportRun] = await Promise.all([
listCompanyBackups(client, companyId),
- getCompanyRestoreRuns(client, companyId)
+ getCompanyRestoreRuns(client, companyId),
+ getCompanyExportRun(client, companyId)
]);
return {
companyId,
files: backupsList.data ?? [],
- restoreRuns: restoreRuns.data ?? []
+ restoreRuns: restoreRuns.data ?? [],
+ exportRun: exportRun.data
};
}
@@ -214,6 +226,13 @@ export async function action({ request }: ActionFunctionArgs) {
};
}
+ // Acknowledge a failed export — clears the failure marker. Any partial
+ // backup folder stays in the list (as "Incomplete") until deleted.
+ case "dismissExportFailure": {
+ await dismissCompanyExportFailure(companyId);
+ return { success: true, message: "Dismissed" };
+ }
+
case "delete": {
const name = String(formData.get("name") ?? "");
if (!name || name.includes("/"))
@@ -234,7 +253,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function BackupsRoute() {
- const { files, restoreRuns } = useLoaderData<typeof loader>();
+ const { files, restoreRuns, exportRun } = useLoaderData<typeof loader>();
const fetcher = useFetcher<{
success?: boolean;
message?: string;
@@ -244,19 +263,75 @@ export default function BackupsRoute() {
const [active, setActive] = useState<{
runId?: string;
mode: "export" | "restore" | "revert";
- /** Export only: the backup paths present when the export started. The run is
- * done once a path outside this set appears in the (revalidated) list. */
- exportBaseline?: Set<string>;
} | null>(null);
- // Latest list, read without re-triggering the fetcher effect when it changes.
+ // Latest list, read without re-triggering effects when it changes.
const filesRef = useRef(files);
filesRef.current = files;
+
+ const exportRunning = exportRun?.status === "running";
+ const exportFailed = exportRun?.status === "failed";
+
+ // The in-progress export we're tracking this session. Set the instant the user
+ // clicks "Create backup" (optimistic — before the job writes its first marker,
+ // so the row shows immediately, Supabase-style) or adopted from the marker for
+ // a run started elsewhere (reload / another tab). `baseline` = the READY backups
+ // when tracking began; the run is complete once a ready backup outside it
+ // appears in the (revalidated) list.
+ const [runningExport, setRunningExport] = useState<{
+ startedAt: string | null;
+ baseline: Set<string>;
+ } | null>(null);
+
+ const readyBackupNames = useCallback(
+ () =>
+ new Set(
+ filesRef.current.filter((f) => f.status === "ready").map((f) => f.name)
+ ),
+ []
+ );
+
const exportCompleted =
- active?.mode === "export" &&
- !!active.exportBaseline &&
+ runningExport != null &&
files.some(
- (f) => f.status === "ready" && !active.exportBaseline!.has(f.name)
+ (f) => f.status === "ready" && !runningExport.baseline.has(f.name)
);
+ const runningExportStartedAt =
+ exportRun?.startedAt ?? runningExport?.startedAt ?? null;
+
+ // Adopt a run this session didn't start (page reload, another tab).
+ useEffect(() => {
+ if (exportRunning && !runningExport) {
+ setRunningExport({
+ startedAt: exportRun?.startedAt ?? null,
+ baseline: readyBackupNames()
+ });
+ }
+ }, [exportRunning, runningExport, exportRun, readyBackupNames]);
+
+ // Stop tracking once the run fails, or completes and isn't being shown in the
+ // detail modal (the modal keeps `completed` true until the user closes it).
+ useEffect(() => {
+ const exportModalOpen = active?.mode === "export";
+ if (
+ runningExport &&
+ (exportFailed || (exportCompleted && !exportModalOpen))
+ ) {
+ setRunningExport(null);
+ }
+ }, [runningExport, exportCompleted, exportFailed, active]);
+
+ const openExportProgress = useCallback(() => {
+ setActive({ mode: "export" });
+ }, []);
+
+ // The export runs fully server-side — poll the list to catch completion while
+ // the detail modal is closed (the modal runs its own faster poll when open).
+ const revalidator = useRevalidator();
+ useEffect(() => {
+ if (!runningExport || active) return;
+ const id = setInterval(() => revalidator.revalidate(), 2500);
+ return () => clearInterval(id);
+ }, [runningExport, active, revalidator]);
// 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
@@ -280,12 +355,13 @@ export default function BackupsRoute() {
useEffect(() => {
const result = fetcher.data;
if (result?.message === undefined) return;
- // Export and restore open a progress modal — let it own the feedback instead
- // of also firing a toast. Everything else (keep/revert/dismiss/errors) toasts.
+ // Export is non-blocking: drop an in-progress row immediately (the user opens
+ // the detail modal by clicking it) — no toast, no forced modal. Restore opens
+ // its modal directly. Everything else (keep/revert/dismiss/errors) toasts.
if (result.success && result.started === "export") {
- setActive({
- mode: "export",
- exportBaseline: new Set(filesRef.current.map((f) => f.name))
+ setRunningExport({
+ startedAt: new Date().toISOString(),
+ baseline: readyBackupNames()
});
return;
}
@@ -295,7 +371,7 @@ export default function BackupsRoute() {
}
if (result.success) toast.success(result.message);
else toast.error(result.message);
- }, [fetcher.data]);
+ }, [fetcher.data, readyBackupNames]);
return (
<ScrollArea className="w-full h-[calc(100dvh-49px)]">
@@ -429,66 +505,63 @@ export default function BackupsRoute() {
</CardDescription>
</CardHeader>
<CardContent>
- {files.length === 0 ? (
+ {files.length === 0 && !runningExport && !exportFailed ? (
<p className="text-sm text-muted-foreground">No backups yet.</p>
) : (
<VStack spacing={2}>
- {files.map((file) => (
- <HStack
- key={file.name}
- className={`w-full justify-between border rounded-lg p-3 ${
- file.status === "pending" ? "opacity-70" : ""
- }`}
+ {exportFailed && (
+ <HStack className="w-full justify-between rounded-lg border border-destructive/50 bg-destructive/5 p-3">
+ <VStack spacing={0} className="min-w-0">
+ <span className="text-sm font-medium">Backup failed</span>
+ <span className="break-words text-xs text-muted-foreground">
+ The system created an invalid backup — please contact
+ Carbon support.
+ {exportRun?.error ? ` (${exportRun.error})` : null}
+ </span>
+ </VStack>
+ <Button
+ variant="secondary"
+ onClick={() =>
+ fetcher.submit(
+ { intent: "dismissExportFailure" },
+ { method: "post" }
+ )
+ }
+ >
+ Dismiss
+ </Button>
+ </HStack>
+ )}
+
+ {/* The in-flight export — fully server-side; appears the instant
+ "Create backup" is clicked. Click it to open the progress
+ dialog. Its partially-written folder (if any) is hidden below
+ to avoid a duplicate row. */}
+ {runningExport && !exportCompleted && (
+ <button
+ type="button"
+ onClick={openExportProgress}
+ className="flex w-full items-center justify-between rounded-lg border p-3 text-left transition-colors hover:bg-muted/50"
>
<VStack spacing={0}>
<span className="text-sm font-medium">
- {file.label || formatBackupName(file.name)}
+ Creating backup…
</span>
<span className="text-xs text-muted-foreground">
- {file.status === "pending" ? (
- <span className="animate-pulse">Preparing…</span>
- ) : (
- <>
- {formatBackupDate(file.exportedAt)}
- {file.sizeBytes ? (
- <>
- {" · "}
- {convertKbToString(
- Math.round(file.sizeBytes / 1024)
- )}
- </>
- ) : null}
- </>
- )}
+ {runningExportStartedAt
+ ? `Started ${formatBackupDate(runningExportStartedAt)}`
+ : "Starting…"}
</span>
</VStack>
- <HStack spacing={2}>
- {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
- </Button>
- )}
- <Form method="post">
- <input type="hidden" name="intent" value="delete" />
- <input type="hidden" name="name" value={file.name} />
- <Button type="submit" variant="destructive">
- Delete
- </Button>
- </Form>
- </HStack>
- </HStack>
- ))}
+ <LuLoaderCircle className="h-4 w-4 shrink-0 animate-spin text-primary motion-reduce:animate-none" />
+ </button>
+ )}
+
+ {files
+ .filter((f) => !(runningExport && f.status === "pending"))
+ .map((file) => (
+ <BackupRow key={file.name} file={file} />
+ ))}
</VStack>
)}
</CardContent>
@@ -497,3 +570,72 @@ export default function BackupsRoute() {
</ScrollArea>
);
}
+
+// One backup row. Its own fetcher so Delete shows a spinner and dims the row
+// while the (async, storage-recursing) delete runs; the row drops out of the
+// list on the revalidation that follows.
+function BackupRow({ file }: { file: CompanyBackupSummary }) {
+ const deleteFetcher = useFetcher();
+ const isDeleting = deleteFetcher.state !== "idle";
+
+ return (
+ <HStack
+ className={`w-full justify-between border rounded-lg p-3 ${
+ file.status === "pending" || isDeleting ? "opacity-70" : ""
+ }`}
+ >
+ <VStack spacing={0}>
+ <span className="text-sm font-medium">
+ {file.label || formatBackupName(file.name)}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {file.status === "pending" ? (
+ // A pending folder with no running export is a dead partial — never
+ // lie with "Preparing…".
+ <>Incomplete backup — not restorable</>
+ ) : (
+ <>
+ {formatBackupDate(file.exportedAt)}
+ {file.sizeBytes ? (
+ <>
+ {" · "}
+ {convertKbToString(Math.round(file.sizeBytes / 1024))}
+ </>
+ ) : null}
+ </>
+ )}
+ </span>
+ </VStack>
+ <HStack spacing={2}>
+ {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
+ </Button>
+ )}
+ <deleteFetcher.Form method="post">
+ <input type="hidden" name="intent" value="delete" />
+ <input type="hidden" name="name" value={file.name} />
+ <Button
+ type="submit"
+ variant="destructive"
+ isLoading={isDeleting}
+ isDisabled={isDeleting}
+ >
+ Delete
+ </Button>
+ </deleteFetcher.Form>
+ </HStack>
+ </HStack>
+ );
+}
diff --git a/apps/mes/app/components/RealtimeDataProvider.tsx b/apps/mes/app/components/RealtimeDataProvider.tsx
index fbda6381df..0502f2dd01 100644
--- a/apps/mes/app/components/RealtimeDataProvider.tsx
+++ b/apps/mes/app/components/RealtimeDataProvider.tsx
@@ -10,9 +10,15 @@ import { useUser } from "~/hooks";
import { useItems, usePeople } from "~/stores";
import type { Item } from "~/stores/items";
-let hydratedFromIdb = false;
+// IndexedDB entries are keyed per company (`items:<companyId>`) — a global key
+// let one company's cached list hydrate the pickers after switching to another
+// company. `activeCompanyId` also guards async callbacks racing a mid-flight
+// company switch.
+let activeCompanyId: string | null = null;
let hydratedFromServer = false;
+const LEGACY_IDB_KEYS = ["items", "people"];
+
const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const { carbon, accessToken, isRealtimeAuthSet } = useCarbon();
@@ -32,15 +38,24 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
const channelRef = useRef<RealtimeChannel | null>(null);
const hydrate = async () => {
- if (!hydratedFromIdb) {
- hydratedFromIdb = true;
+ const requestedCompanyId = companyId;
+ if (activeCompanyId !== requestedCompanyId) {
+ activeCompanyId = requestedCompanyId;
+
+ // pre-keying entries were global; purge so they can never hydrate again
+ for (const key of LEGACY_IDB_KEYS) {
+ void idb.removeItem(key);
+ }
- idb.getItem("items").then((data) => {
- if (data && !hydratedFromServer) setItems(data as Item[], true);
+ const fresh = () =>
+ !hydratedFromServer && activeCompanyId === requestedCompanyId;
+
+ idb.getItem(`items:${requestedCompanyId}`).then((data) => {
+ if (data && fresh()) setItems(data as Item[], true);
});
- idb.getItem("people").then((data) => {
+ idb.getItem(`people:${requestedCompanyId}`).then((data) => {
// @ts-ignore
- if (data && !hydratedFromServer) setPeople(data, true);
+ if (data && fresh()) setPeople(data, true);
});
}
@@ -72,6 +87,9 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
throw new Error("Failed to fetch people");
}
+ // company switched while fetching — these results belong to the old company
+ if (activeCompanyId !== requestedCompanyId) return;
+
hydratedFromServer = true;
type ItemWithModelUpload = Item & {
diff --git a/packages/database/supabase/migrations/20260703143904_composite-tenant-fks.sql b/packages/database/supabase/migrations/20260703143904_composite-tenant-fks.sql
new file mode 100644
index 0000000000..44a14ffc94
--- /dev/null
+++ b/packages/database/supabase/migrations/20260703143904_composite-tenant-fks.sql
@@ -0,0 +1,121 @@
+-- Tenant-integrity FKs for customer/supplier references.
+--
+-- Every FK that referenced customer("id") / supplier("id") from a table that
+-- carries a "companyId" column is converted to a composite FK on
+-- (<column>, "companyId") -> (id, "companyId"), so the database itself rejects
+-- a row in company A pointing at a customer/supplier owned by company B.
+-- Single-column FKs allowed exactly that (see prod: a salesOrder + opportunity
+-- referencing another company's customer, and one supplierPart), which also
+-- breaks company export ("NOT-NULL reference(s) escape company scope").
+--
+-- Written to NEVER fail on pre-existing bad rows: constraints are re-added
+-- NOT VALID (new writes enforced immediately), then validated one by one --
+-- a constraint whose existing rows violate it stays NOT VALID with a WARNING
+-- listing it. After cleaning the offending rows run:
+-- ALTER TABLE "<table>" VALIDATE CONSTRAINT "<constraint>";
+
+-- Composite FK targets need a unique index on (id, "companyId"); id alone is
+-- already the PK, so this is trivially unique.
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'customer_id_companyId_key' AND conrelid = '"customer"'::regclass
+ ) THEN
+ ALTER TABLE "customer" ADD CONSTRAINT "customer_id_companyId_key" UNIQUE ("id", "companyId");
+ END IF;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'supplier_id_companyId_key' AND conrelid = '"supplier"'::regclass
+ ) THEN
+ ALTER TABLE "supplier" ADD CONSTRAINT "supplier_id_companyId_key" UNIQUE ("id", "companyId");
+ END IF;
+END $$;
+
+DO $$
+DECLARE
+ fk RECORD;
+ delete_rule TEXT;
+ update_rule TEXT;
+ defer_clause TEXT;
+BEGIN
+ FOR fk IN
+ SELECT
+ con.conname,
+ child.relname AS child_table,
+ parent.relname AS parent_table,
+ att.attname AS child_column,
+ con.confdeltype,
+ con.confupdtype,
+ con.condeferrable,
+ con.condeferred
+ FROM pg_constraint con
+ JOIN pg_class child ON child.oid = con.conrelid
+ JOIN pg_class parent ON parent.oid = con.confrelid
+ JOIN pg_namespace ns ON ns.oid = child.relnamespace
+ JOIN pg_attribute att
+ ON att.attrelid = con.conrelid AND att.attnum = con.conkey[1]
+ JOIN pg_attribute refatt
+ ON refatt.attrelid = con.confrelid AND refatt.attnum = con.confkey[1]
+ WHERE con.contype = 'f'
+ AND ns.nspname = 'public'
+ AND parent.relname IN ('customer', 'supplier')
+ AND array_length(con.conkey, 1) = 1 -- single-column FKs only
+ AND refatt.attname = 'id'
+ -- the child must be tenant-scoped itself, or there is nothing to pin
+ AND EXISTS (
+ SELECT 1 FROM pg_attribute a
+ WHERE a.attrelid = con.conrelid
+ AND a.attname = 'companyId'
+ AND NOT a.attisdropped
+ )
+ ORDER BY child.relname, con.conname
+ LOOP
+ -- ON UPDATE SET NULL/SET DEFAULT on a composite FK would also null/default
+ -- "companyId" (PG only supports a column list for ON DELETE). No current FK
+ -- uses these; if one appears, leave it alone rather than corrupt tenancy.
+ IF fk.confupdtype IN ('n', 'd') THEN
+ RAISE WARNING 'composite-tenant-fks: skipping %.% (ON UPDATE SET NULL/DEFAULT cannot be made composite safely)',
+ fk.child_table, fk.conname;
+ CONTINUE;
+ END IF;
+
+ update_rule := CASE fk.confupdtype
+ WHEN 'c' THEN 'ON UPDATE CASCADE'
+ WHEN 'r' THEN 'ON UPDATE RESTRICT'
+ ELSE ''
+ END;
+
+ -- SET NULL / SET DEFAULT must clear only the referencing column, never
+ -- "companyId" (PG15 column-list form).
+ delete_rule := CASE fk.confdeltype
+ WHEN 'c' THEN 'ON DELETE CASCADE'
+ WHEN 'r' THEN 'ON DELETE RESTRICT'
+ WHEN 'n' THEN format('ON DELETE SET NULL (%I)', fk.child_column)
+ WHEN 'd' THEN format('ON DELETE SET DEFAULT (%I)', fk.child_column)
+ ELSE ''
+ END;
+
+ defer_clause := CASE
+ WHEN fk.condeferrable AND fk.condeferred THEN 'DEFERRABLE INITIALLY DEFERRED'
+ WHEN fk.condeferrable THEN 'DEFERRABLE'
+ ELSE ''
+ END;
+
+ EXECUTE format('ALTER TABLE %I DROP CONSTRAINT %I', fk.child_table, fk.conname);
+ -- Same constraint name: PostgREST embeds and any FK-name hints keep resolving.
+ EXECUTE format(
+ 'ALTER TABLE %I ADD CONSTRAINT %I FOREIGN KEY (%I, "companyId") REFERENCES %I ("id", "companyId") %s %s %s NOT VALID',
+ fk.child_table, fk.conname, fk.child_column, fk.parent_table,
+ update_rule, delete_rule, defer_clause
+ );
+
+ BEGIN
+ EXECUTE format('ALTER TABLE %I VALIDATE CONSTRAINT %I', fk.child_table, fk.conname);
+ EXCEPTION WHEN OTHERS THEN
+ RAISE WARNING 'composite-tenant-fks: %.% has pre-existing cross-company rows and stays NOT VALID -- clean them up, then run: ALTER TABLE "%" VALIDATE CONSTRAINT "%"; (%)',
+ fk.child_table, fk.conname, fk.child_table, fk.conname, SQLERRM;
+ END;
+ END LOOP;
+END $$;
diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.ts
index cde3c90f4b..af657d76a3 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-export.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts
@@ -234,8 +234,10 @@ export async function buildCompanyBackup(
}
// One company-scoped progress marker (exports run one-at-a-time, so no run id).
-// The UI polls it for live phase/done/total; it's cleared when the run ends, and
-// the backup appearing in the list is what signals completion.
+// The UI polls it for live phase/done/total; it's cleared when the run succeeds
+// (the backup appearing in the list is what signals completion) and kept with
+// status "failed" when it doesn't — a cleared marker on failure made a broken
+// export indistinguishable from one that never ran.
const EXPORT_INTEGRATION = "company-export";
type ExportProgress = { phase: string; done: number; total: number };
@@ -243,7 +245,12 @@ async function upsertExportMarker(
client: ServiceRole,
companyId: string,
userId: string,
- metadata: { status: "running"; startedAt: string; progress?: ExportProgress }
+ metadata: {
+ status: "running" | "failed";
+ startedAt: string;
+ progress?: ExportProgress;
+ error?: string;
+ }
): Promise<void> {
const existing = await client
.from("externalIntegrationMapping")
@@ -295,8 +302,8 @@ export const companyExportFunction = inngest.createFunction(
const client = getCarbonServiceRole();
const db = getJobDatabaseClient(TABLE_CONCURRENCY);
- // Live-progress marker (cleared in `finally`, success or failure). Throttled
- // so a fast parallel dump doesn't hammer the row.
+ // Live-progress marker (cleared on success, flipped to "failed" on error).
+ // Throttled so a fast parallel dump doesn't hammer the row.
const startedAt = new Date().toISOString();
await upsertExportMarker(client, companyId, userId, {
status: "running",
@@ -360,9 +367,20 @@ export const companyExportFunction = inngest.createFunction(
assetsFailed: assets.failed
});
- return { name, tables: manifest.tables.length, rows };
- } finally {
await clearExportMarker(client, companyId);
+ return { name, tables: manifest.tables.length, rows };
+ } catch (err) {
+ // Keep the marker with the failure so the UI can tell the user the
+ // backup is invalid instead of showing "preparing" forever. A retry
+ // (retries: 1) overwrites it back to "running"; the user dismisses it
+ // from the Backups page, and the next export reuses the row.
+ const message = err instanceof Error ? err.message : String(err);
+ await upsertExportMarker(client, companyId, userId, {
+ status: "failed",
+ startedAt,
+ error: message.slice(0, 2000)
+ });
+ throw err;
}
});
}