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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Demo data and and resusable enviroments (#913)
Gaurav Bhattc9eb7f1b18a9
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.mdnew file mode 100644index 0000000000..a1db1966b0--- /dev/null+++ b/.claude/rules/company-backup-restore.md@@ -0,0 +1,173 @@+---+paths:+ - "packages/jobs/src/inngest/functions/tasks/company-backup.ts"+ - "packages/jobs/src/inngest/functions/tasks/company-export.ts"+ - "packages/jobs/src/inngest/functions/tasks/company-import.ts"+ - "packages/jobs/src/inngest/functions/tasks/company-restore.ts"+ - "apps/erp/app/modules/settings/backups.service.ts"+ - "apps/erp/app/modules/settings/backups.server.ts"+ - "apps/erp/app/modules/settings/ui/Backups/**"+ - "apps/erp/app/routes/x+/settings+/backups.tsx"+ - "apps/erp/app/routes/api+/settings.backup-summary.ts"+ - "apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts"+ - "apps/erp/app/services/onboarding.server.ts"+ - "apps/erp/app/services/onboarding-draft.server.ts"+ - "ci/src/upload-backup-templates.ts"+ - "packages/database/supabase/backups/**"+---++# Company Backup / Restore / Onboarding Seed++Per-company logical backup, in-place restore (with revert), and onboarding-seed+from a committed demo template. **Inngest tasks, NOT edge functions** — the old+`import-company` / `finalize-import` / `revert-import` edge functions and the+`company-revert` / `publish-demo` / `refresh-demo-catalog` jobs were deleted; this+is the replacement. Reader-facing docs: `docs/content/docs/platform/backups.mdx`+(kept deliberately impl-free — keep internals here, not there).++User-facing rules of the feature: backups are **company-owner only**+(`group.ownerId === userId` check in the route), exclude secrets, and a restore is+reversible via an auto-snapshot.++**Currently internal-only** (`isInternalEmail`, `@carbon/utils`) while the+multi-tenant caveats below are unhardened: the nav entry is in `internalOnlyRoutes`+(`useSettingsSubmodules.tsx`), and `requireOwner` (route loader/action) plus both+`api+/settings.backup-*` loaders 404/redirect non-internal users. Internal =+`@carbon.ms` / `@carbon.us.org`. Drop the gates to ship publicly.++## Shared engine — `company-backup.ts`++The catalog is **schema-introspected**, not a hand-maintained list:++- `getCompanyTableCatalog(sql)` reads `information_schema` for every public BASE+ TABLE carrying a `companyId` or `companyGroupId` column, builds `TableInfo`+ (columns, FK edges, `scopeColumn`, `hasId`/id type), and topologically sorts+ (referenced-first). **`companyId` wins** when a table has both columns.+- `scopeColumn: "companyId" | "companyGroupId"`. `companyId` = the company's own+ data; `companyGroupId` = config shared across a company group (chart of+ accounts, currencies, dimensions).+- Skip/scope sets: `SECRET_TABLES` (`apiKey`, `companyIntegration`, `webhook`,+ `oauthClient`, `oauthToken` — never travel), `STRUCTURAL_TABLES` (`company` —+ excluded from catalog), `RESEED_SKIPPED_TABLES` (memberships/invites/employee/+ externalIntegrationMapping — skipped on onboarding reseed),+ `IN_PLACE_SKIPPED_TABLES` (access/identity tables a restore must keep so the+ user isn't locked out).+- Versioning: `BACKUP_VERSION` in the manifest; `assertBackupImportable` rejects a+ file whose version no longer matches or that's missing a now-required column.+- Id minting: `newIdForTable(table)` → `randomUUID()` for uuid id columns else+ `nanoid()`. Id remap is **gated to text/uuid id columns** (serial/int ids are+ left alone).+- Storage path rewriting: `rewriteStoragePath` (swap `{sourceCompanyId}/` →+ `{targetCompanyId}/` + remapped id segments), `rewriteToTemplateAssetPath`+ (`{co}/…` → `_templates/{industryId}/…`). `STORAGE_PATH_COLUMNS` =+ `modelPath`, `thumbnailPath`.++Buckets (important, two different things):+- `STORAGE_BUCKET = "private"` — the **shared** bucket holding every company's+ uploaded assets under a `{companyId}/` prefix. Asset files in a backup go here.+- The **per-company bucket named by `companyId`** holds the backup `.gz` files+ (`exports/…`) and pre-restore snapshots — see `client.storage.from(companyId)`.+- `TEMPLATE_BUCKET = "company-templates"`, `TEMPLATE_ASSET_PREFIX = "_templates"`.++## Export — `company-export.ts`++Dumps each catalog table scoped by its scope column, gzips (`await gzipAsync`,+promisified). **Empty tables are skipped** (`if (result.rows.length === 0)+continue`) — so a backup of a company with no GL postings simply has no+`journalLine`/`costLedger` rows; that is data-absence, not a coverage gap. With+`includeStorage: "all"`, asset files under `private/{companyId}/` are base64-embedded.++## Restore — `company-restore.ts`++Three Inngest fns: `companyRestoreFunction`, `companyRestoreFinalizeFunction`,+`companyRestoreRevertFunction`. **Shared concurrency** key+`'company-restore-' + event.data.companyId`, scope `env`, limit `1` — one restore+per company at a time.++Forward flow:+1. `downloadBackup` from the per-company bucket; `gunzipAsync`.+2. Compute `targetGroupId`, then `groupCompanyCount` (count of companies with that+ `companyGroupId`). `includeGroup = groupCompanyCount === 1`. A **foreign**+ backup (`manifest.sourceCompanyId !== companyId`) onto a shared group+ (`!includeGroup`) **throws** rather than rewrite the shared chart of accounts.+3. Auto-snapshot current state to `snapshotPath` (idempotent — reuses an existing+ one). This is what `revert` restores.+4. `wipeAndLoad` in ONE transaction with `session_replication_role = 'replica'`+ (relaxes FK checks during load):+ - `selectWipeableTables(catalog, { includeGroup })` → company-scoped tables+ minus kept/secret; group-scoped tables included **only** when `includeGroup`.+ - `wipeScopedData` deletes each table in reverse-topo order, **always** scoped+ `WHERE <scopeColumn> = <value>`; a null scope value is skipped (no unscoped+ DELETE is possible).+ - `buildRowTransforms` re-stamps `companyId`→target, `companyGroupId`→+ `targetGroupId`; on a foreign/remap load it mints new ids (text/uuid only) and+ remaps FKs, with a dangling-ref guard (nullable FK → null, non-nullable →+ throw).+5. `restoreStorage` (outside the txn, non-transactional) uploads embedded files to+ `private/<rewritten path>` with `upsert: true`.+6. `assertWipeSafe(catalog)` guards the invariant that a KEPT table has no NOT-NULL+ FK into a WIPED table.++State marker: a row on `externalIntegrationMapping`, `integration =+"company-restore"`, `metadata = { status: running|ready|failed|reverting,+snapshotPath, foreign, includeGroup }`. `revert` reads the marker and reloads+`snapshotPath` (using `metadata.includeGroup`). Status is polled by the UI.++### Known caveats in the committed code (not yet hardened)++- **`restoreStorage` has no target-prefix assertion.** It writes to the shared+ `private` bucket via `rewriteStoragePath`, which only rewrites paths under+ `sourceCompanyId/`. A backup whose storage map holds a path NOT under+ `sourceCompanyId` would upload outside this company's prefix (cross-tenant write,+ `upsert:true`). Own/normal backups never trigger it; add a+ `targetPath.startsWith(\`${companyId}/\`)` guard if hardening.+- **Storage restore is best-effort** — upload failures `console.warn` only; the+ restore still reports success.+- **`company-import` id-gate drift** — restore gates id remap on column type+ (text/uuid); import still uses a `typeof row.id === "string"` heuristic. Share+ one transform builder to fix.+- Sequences: the only pg-native serials on backed-up tables are `entryNumber` on+ `itemLedger`/`costLedger`/`supplierLedger` (not PKs, not unique; PKs are all+ text). They are **global/shared across tenants** — never `setval` them scoped to+ one company; in-place restore needs no reset (other tenants hold the high-water+ mark).++## ERP layer++- `backups.service.ts` — per-company bucket ops: `exportCompanyBackup`,+ `listCompanyBackupExports` (`from(companyId).list("exports")`),+ `getCompanyBackupSignedUrl`, `deleteCompanyBackupExport`,+ `getCompanyRestoreRuns` (reads the markers).+- `backups.server.ts` — server-only trigger wrappers (`startCompanyRestore`,+ `finalizeCompanyRestore`, `revertCompanyRestore`) — kept off the client to avoid+ `Buffer`-in-client.+- `routes/x+/settings+/backups.tsx` — **owner-gated** loader/action (export /+ restore / keep / dismiss / revert / delete intents). `filePath` is forced under+ `exports/`.+- `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`+ from `requirePermissions`, so a user can't poll another company's run.+- UI: `modules/settings/ui/Backups/` — `BackupChoices` (Data only / Data + files),+ `BackupSourcePicker`, `BackupProgressModal`, `RestoreReviewRow` (Keep/Revert),+ `BackupContentsInfo` (lazy popover), `format.ts`.++## Onboarding seed++`routes/onboarding+/industry.tsx` → `dataChoice: "template" | "import" | "none"`+("Use a demo template" / "Restore from a backup" / "I don't need data"). A demo+template is a committed `.gz` at+`packages/database/supabase/backups/<industryId>.carbon.json.gz` (one per+`industry` row). `provisionCompanyData` (onboarding.server.ts) imports it on top of+an identity-only seed, **referencing** the shared `_templates/<industryId>/` assets+instead of copying files per company. No file → clean seed.++## CI publish++`ci/src/upload-backup-templates.ts` — **manual, idempotent** (`--force` to+overwrite). Uploads each committed `.gz` to every workspace's `company-templates`+bucket and fans its assets into `private/_templates/<industryId>/`. Run via the+`Publish backup templates` workflow (`.github/workflows/publish-templates.yml`,+`workflow_dispatch`) or `pnpm --filter ci ci:upload-backup-templates`. NOT run on+every deploy (templates are large + change rarely). The script hardcodes the+`_templates` literal — keep in sync with `TEMPLATE_ASSET_PREFIX`.diff --git a/.claude/skills/test/playbooks/backups-onboarding-test-path.md b/.claude/skills/test/playbooks/backups-onboarding-test-path.mdnew file mode 100644index 0000000000..f655b60d3d--- /dev/null+++ b/.claude/skills/test/playbooks/backups-onboarding-test-path.md@@ -0,0 +1,61 @@+# Backups + Onboarding — Full Test Path++Covers: company export / import / revert (Backups), onboarding data-choice (demo / import / none) + Option C industry table, the schema-version guard, and the renamed-UI changes.++## Prerequisites (one-time setup per fresh DB)+- **Ownership**: Backups is owner-gated. After any `db:build`/reset, `companyGroup.ownerId` is NULL → set it:+ ```sql+ UPDATE "companyGroup" SET "ownerId" = (select id from "user" where email='[email protected]');+ ```+- **Stack health**: export/import/revert run as Inngest jobs via edge functions. They need:+ - edge-runtime NOT CPU-saturated (`docker logs … edge-runtime` shows no "CPU time hard limit") — transient after rebuild, clears on its own.+ - edge→Inngest wired up — the edge-runtime container needs `INNGEST_DEV=1` + `INNGEST_BASE_URL=http://inngest:8288` in `docker-compose.dev.yml`'s `edge-runtime` service. Without it, edge fns 401 ("Event key not found") because their `inngest.send()` defaults to Inngest Cloud. (Fixed 2026-06-22 — see [[reference_edge_inngest_401]].)+- Use the `.dev` hostname (`ERP_URL`), not `localhost:<port>` — auth cookies/redirects are bound to the hostname.++---++## A. Backups — export → import → finalize / revert+Route: `/x/settings/backups`++1. **Page loads for owner** — nav + breadcrumb read "Backups"; "Create a backup", "Restore from a backup", "Backups" cards present. (Non-owner → redirected to settings with "Only the company owner can access backups".) ✅ verified live+2. **Export** — Label = "test", Files = "Data only" → *Create backup* → toast "Export started…". Wait ~10s, reload → a `*.carbon.json.gz` row appears under "Backups" with a size + Download/Delete.+ - Verify in DB: `select name from storage.objects where bucket_id='<companyId>' and name like 'exports/%'`.+3. **Export + files** — repeat with Files = "Data + uploaded files" (includeStorage=all) → larger artifact.+4. **Import (reseed)** — in "Restore from a backup", pick the backup, Mode = "Reseed", *Restore* → toast "Import started…". Wait → a "Pending restore" card appears with a run id + row count.+ - Verify: `select count(*) from "externalIntegrationMapping" where integration='company-template'` > 0 (the revert ledger).+5. **Revert** — on the pending run, *Revert* → toast "Revert started…". Wait, reload → pending card gone; ledger rows deleted; reseed-inserted rows removed.+6. **Import again → Finalize** — re-import, then *Finalize* → "Import finalized"; pending card clears; ledger deleted but inserted rows KEPT.+7. **Delete** — on a backup row, *Delete* → "Export deleted"; row gone from storage.+8. **Validation** — Restore with no file selected → "Select an export to import".++## B. Schema-version / "wrong schema" guard+The guard (`assertBackupImportable`) rejects an incompatible backup at import time with a specific reason.++1. **Out-of-date format** — export a backup, download it, then:+ ```bash+ gunzip -c backup.carbon.json.gz > b.json+ # set manifest.version to a wrong generation (current ARTIFACT_VERSION = 1)+ jq '.manifest.version = 999' b.json | gzip > bad.carbon.json.gz+ ```+ Upload `bad.carbon.json.gz` via "Restore from a backup" → *Restore* → import run fails with **"its format (generation 999) is no longer supported (current is 1)"**.+2. **Missing chart of accounts** — craft an artifact with `accountDefault` rows but empty `account` → rejected with "account defaults but no chart of accounts".+3. **Removed table / new required column** — only reproducible across a real breaking migration; the guard reports `table "X" no longer exists` or `"X" now requires column "Y", which this backup predates`. (Additive migrations stay compatible — no manual version bump.)++## C. Onboarding data choice + Option C industries+Route: `/onboarding/industry` (needs an **un-onboarded** user — the `test` user is already onboarded and redirects to `/x`; use a fresh user/company or reset onboarding state to exercise this).++1. **Data choice** — "Use demo data" / "Restore from a backup" / "I don't need data" all render. (The import option is now **always shown** — gating removed.)+2. **Industries come from the DB** (Option C) — the "Which best describes your company?" step lists the three `industry` rows (Robotics OEM, Precision Manufacturing, Motor Assembly) with bot/cog/wrench icons, fetched via `getIndustries`, not hardcoded.+ - Verify: `select id,name,"iconName" from industry order by "sortOrder"`.+3. **Demo** → pick an industry → submits `seedDemoData=true`, `industryId=<id>`; provisions from the published demo for that industry (or clean seed if none published).+4. **Custom** → leave industry unselected → `industryId` stored as **NULL** + `customIndustryDescription` free text (FK-safe).+5. **Import in onboarding** → choose "Restore from a backup", upload a `.carbon.json.gz` → identity-only seed + reseed import (chart of accounts comes from the artifact, no double-seed).++## D. Renamed / removed UI ("the changes I mentioned")+- ✅ "Backups" everywhere (nav, breadcrumb, headings) — renamed from data-management/"artifacts". verified live+- **No publish-demo in the UI** — the Backups page has export/import/finalize/revert/delete only; no "publish to catalog" control (the publish-demo + refresh-demo-catalog jobs were removed entirely).+- Demo-catalog copy: "Snapshot all of this company's data… Credentials, integration tokens and webhooks are never included."++## Live-verified (2026-06-22, after the edge→Inngest fix)+PASS: login, owner-gate, "Backups" terminology, **export** (job runs end-to-end → `*.carbon.json.gz` artifacts written, listed in UI with working signed Download URLs), **import pipeline** (no 401; reseed correctly rejected the already-seeded company → ledger=0, no pending run).+NOT YET RUN: a *successful* import → finalize/revert (needs a fresh company — the onboarding path, or a second empty company), and the version-guard tamper test (section B).diff --git a/.github/workflows/publish-templates.yml b/.github/workflows/publish-templates.ymlnew file mode 100644index 0000000000..044135bb75--- /dev/null+++ b/.github/workflows/publish-templates.yml@@ -0,0 +1,38 @@+name: Publish backup templates++# Manual only. Publishes the repo-committed onboarding backup templates+# (packages/database/supabase/backups/*.carbon.json.gz) and their storage assets+# into every workspace. Idempotent: anything that already exists is skipped, so+# re-running is a cheap no-op. To overwrite (republish an updated template), run+# with `force` = true.+on:+ workflow_dispatch:+ inputs:+ force:+ description: "Overwrite templates/assets that already exist"+ type: boolean+ default: false++jobs:+ publish:+ name: Publish templates+ runs-on: ubuntu-latest++ env:+ SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.SUPABASE_SERVICE_ROLE_KEY }}+ SUPABASE_URL: ${{ secrets.SUPABASE_URL }}++ steps:+ - uses: actions/checkout@v4++ - uses: pnpm/action-setup@v4+ - uses: actions/setup-node@v4+ with:+ node-version: "22"+ cache: pnpm++ - name: Install dependencies+ run: pnpm install --frozen-lockfile++ - name: Upload backup templates+ run: pnpm --filter ci ci:upload-backup-templates ${{ inputs.force && '--force' || '' }}diff --git a/.github/workflows/supabase.yml b/.github/workflows/supabase.ymlindex 399d563299..2681d048ee 100644--- a/.github/workflows/supabase.yml+++ b/.github/workflows/supabase.yml@@ -39,3 +39,8 @@ jobs:- name: Run migrationsrun: pnpm --filter ci ci:migrations++ # NOTE: onboarding backup templates are NOT published here. They change+ # rarely and are large, so publishing is a deliberate, manual step run via+ # the "Publish backup templates" workflow (.github/workflows/publish-templates.yml)+ # or `pnpm --filter ci ci:upload-backup-templates` — never on every migration.diff --git a/apps/erp/app/hooks/useFlags.tsx b/apps/erp/app/hooks/useFlags.tsxindex 6c6687ddd1..ef5ff79b44 100644--- a/apps/erp/app/hooks/useFlags.tsx+++ b/apps/erp/app/hooks/useFlags.tsx@@ -1,14 +1,12 @@import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";import { useEdition } from "@carbon/react";-import { Edition } from "@carbon/utils";+import { Edition, isInternalEmail } from "@carbon/utils";import { useUser } from "./useUser";export function useFlags() {const user = useUser();const edition = useEdition();- const isInternal = ["@carbon.us.org", "@carbon.ms"].some((domain) =>- user.email.toLowerCase().trim().endsWith(domain)- );+ const isInternal = isInternalEmail(user.email);return {isInternal,diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex 4573321cc1..e73d7484f2 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -1,5 +1,10 @@import type { Database, Json } from "@carbon/database";-import { getDateNYearsAgo, toStoredAmount } from "@carbon/utils";+import {+ getDateNYearsAgo,+ toDisplayCredit,+ toDisplayDebit,+ toStoredAmount+} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import { getNextSequence } from "~/modules/settings";@@ -1838,10 +1843,25 @@ export async function postJournalEntry(return { data: null, error: { message: "Journal entry has no lines" } };}- // 2. Validate balance (sum of amounts should be 0)- const total = lines.reduce((sum, l) => sum + Number(l.amount), 0);+ // 2. Validate balance. Amounts are stored in natural-balance convention+ // (toStoredAmount), so a balanced entry has Σdebits === Σcredits, not+ // Σamount === 0 (that only holds if every account were natural-debit).+ let debits = 0;+ let credits = 0;+ for (const line of lines) {+ const accountClass = line.account?.class;+ if (!accountClass) {+ return {+ data: null,+ error: { message: "Journal line is missing an account" }+ };+ }+ const amount = Number(line.amount);+ debits += toDisplayDebit(amount, accountClass);+ credits += toDisplayCredit(amount, accountClass);+ }- if (Math.abs(total) > 0.001) {+ if (Math.abs(debits - credits) > 0.001) {return {data: null,error: { message: "Total debits must equal total credits" }diff --git a/apps/erp/app/modules/settings/backups.server.ts b/apps/erp/app/modules/settings/backups.server.tsnew file mode 100644index 0000000000..11a0ed1a57--- /dev/null+++ b/apps/erp/app/modules/settings/backups.server.ts@@ -0,0 +1,40 @@+import { trigger } from "@carbon/jobs";+import { nanoid } from "nanoid";++// Server-only: enqueues the in-place restore inngest jobs. Kept out of the+// route module so `@carbon/jobs` (which pulls Node `Buffer` via the Inngest+// client) never lands in the browser bundle.++/**+ * Kick off an in-place restore of `filePath` (one of this company's own+ * backups). The job snapshots the current state, wipes the company's data and+ * loads the backup. Returns the restore run id used to poll status and to+ * keep/revert the result.+ */+export async function startCompanyRestore(args: {+ companyId: string;+ userId: string;+ filePath: string;+ includeStorage: "none" | "all";+ label?: string;+}): Promise<string> {+ const restoreRunId = nanoid();+ await trigger("company-restore", { ...args, restoreRunId });+ return restoreRunId;+}++/** Keep a restore — drop the pre-restore snapshot + marker. */+export async function finalizeCompanyRestore(args: {+ companyId: string;+ restoreRunId: string;+}): Promise<void> {+ await trigger("company-restore-finalize", args);+}++/** Undo a restore — wipe again and reload the pre-restore snapshot. */+export async function revertCompanyRestore(args: {+ companyId: string;+ restoreRunId: string;+}): Promise<void> {+ await trigger("company-restore-revert", args);+}diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.tsnew file mode 100644index 0000000000..4dbf0e81b1--- /dev/null+++ b/apps/erp/app/modules/settings/backups.service.ts@@ -0,0 +1,84 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";++// Company backup data access. The export edge function is a thin auth boundary;+// the heavy lifting runs in the carbon/company-export inngest job. Restore is+// enqueued server-side (see backups.server.ts) and tracked via the+// externalIntegrationMapping marker (getCompanyRestoreRuns).++export async function exportCompanyBackup(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ userId: string;+ label?: string;+ includeStorage?: "none" | "all";+ }+) {+ return client.functions.invoke("export-company", { body: args });+}++export async function listCompanyBackupExports(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client.storage.from(companyId).list("exports", {+ limit: 25,+ sortBy: { column: "created_at", order: "desc" }+ });+}++export async function getCompanyBackupSignedUrl(+ client: SupabaseClient<Database>,+ companyId: string,+ filePath: string+) {+ return client.storage.from(companyId).createSignedUrl(filePath, 60 * 60);+}++export async function deleteCompanyBackupExport(+ client: SupabaseClient<Database>,+ companyId: string,+ filePath: string+) {+ return client.storage.from(companyId).remove([filePath]);+}++/**+ * Pending in-place restore runs. One marker row per restore (integration =+ * 'company-restore'), holding the pre-restore snapshot path in metadata. A row+ * exists between the restore completing and the user keeping or reverting it.+ */+export async function getCompanyRestoreRuns(+ client: SupabaseClient<Database>,+ companyId: string+) {+ const markers = await client+ .from("externalIntegrationMapping")+ .select("entityId, metadata, createdAt")+ .eq("integration", "company-restore")+ .eq("companyId", companyId)+ .order("createdAt", { ascending: false });++ if (markers.error) return { data: null, error: markers.error };++ const runs = (markers.data ?? []).map((m) => {+ const meta = (m.metadata ?? {}) as {+ restoreRunId?: string;+ status?: "running" | "ready" | "failed" | "reverting";+ rows?: number;+ label?: string | null;+ error?: string | null;+ };+ return {+ restoreRunId: meta.restoreRunId ?? m.entityId,+ status: meta.status ?? "running",+ rows: meta.rows ?? 0,+ label: meta.label ?? null,+ error: meta.error ?? null,+ startedAt: m.createdAt+ };+ });++ return { data: runs, error: null };+}diff --git a/apps/erp/app/modules/settings/index.ts b/apps/erp/app/modules/settings/index.tsindex 0c0195d59e..326e02f846 100644--- a/apps/erp/app/modules/settings/index.ts+++ b/apps/erp/app/modules/settings/index.ts@@ -1,3 +1,4 @@+export * from "./backups.service";export * from "./settings.models";export * from "./settings.service";export * from "./types";diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex 012a5d3a58..a9c298d831 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -65,9 +65,8 @@ export const apiKeyValidator = z.object({)});-const company = {+const companyAddress = {name: z.string().min(1, { message: "Name is required" }),- taxId: zfd.text(z.string().optional()),addressLine1: z.string().min(1, { message: "Address is required" }),addressLine2: zfd.text(z.string().optional()),city: z.string().min(1, { message: "City is required" }),@@ -75,17 +74,34 @@ const company = {postalCode: z.string().min(1, { message: "Postal Code is required" }),countryCode: z.string().min(1, { message: "Country is required" }),baseCurrencyCode: zfd.text(z.string()),+ website: zfd.text(z.string().optional())+};++const company = {+ ...companyAddress,+ taxId: zfd.text(z.string().optional()),phone: zfd.text(z.string().optional()),fax: zfd.text(z.string().optional()),email: zfd.text(z.string().optional()),- website: zfd.text(z.string().optional()),vatNumber: zfd.text(z.string().optional()),eori: zfd.text(z.string().optional())};export const companyValidator = z.object(company);++// The onboarding company step collects only the address; the industry choice+// comes from the dedicated industry step that follows.+export const addressValidator = z.object({+ ...companyAddress,+ next: z.string().min(1, { message: "Next is required" })+});++// Onboarding-only: the industry fields live on the company row but are not part+// of the general company validator (kept off the settings forms).export const onboardingCompanyValidator = z.object({...company,+ industryId: zfd.text(z.string().optional()),+ customIndustryDescription: z.string().optional(),next: z.string().min(1, { message: "Next is required" })});diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex abbcc0cd6c..c0fa68bf7d 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -218,6 +218,14 @@ export async function getEmployeeCompanies(};}+export async function getIndustries(client: SupabaseClient<Database>) {+ return client+ .from("industry")+ .select("id, name, description, iconName")+ .eq("active", true)+ .order("sortOrder");+}+export async function getCompany(client: SupabaseClient<Database>,companyId: string@@ -743,13 +751,14 @@ export async function seedCompany(client: SupabaseClient<Database>,companyId: string,userId: string,- parentCompanyId?: string+ opts?: { parentCompanyId?: string; identityOnly?: boolean }) {return client.functions.invoke("seed-company", {body: {companyId,userId,- parentCompanyId+ parentCompanyId: opts?.parentCompanyId,+ identityOnly: opts?.identityOnly ?? false}});}diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupChoices.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupChoices.tsxnew file mode 100644index 0000000000..e8e36775f6--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/BackupChoices.tsx@@ -0,0 +1,74 @@+import { Submit, useControlField } from "@carbon/form";+import { ChoiceSelect } from "@carbon/react";+import { LuDatabaseBackup, LuFiles } from "react-icons/lu";++// What to bundle in a backup. Compact trigger; the trade-off shows on open.+export function IncludeStorageChoice() {+ const [value, setValue] = useControlField<"none" | "all">("includeStorage");+ const current = value ?? "none";+ return (+ <>+ <ChoiceSelect<"none" | "all">+ value={current}+ onChange={setValue}+ options={[+ {+ value: "none",+ title: "Data only",+ description:+ "Customers, items, orders and every record. Smaller and faster.",+ icon: <LuDatabaseBackup />+ },+ {+ value: "all",+ title: "Data + files",+ description:+ "Also bundles uploaded files — 3D models, documents and images.",+ icon: <LuFiles />+ }+ ]}+ />+ <input type="hidden" name="includeStorage" value={current} />+ </>+ );+}++// What to pull in on a restore. Data always loads; files are optional (and only+// present if the backup bundled them). A revert always restores files from the+// snapshot regardless, so the company never ends up missing its own files.+export function RestoreIncludeChoice() {+ const [value, setValue] = useControlField<"none" | "all">("includeStorage");+ const current = value ?? "all";+ return (+ <>+ <ChoiceSelect<"none" | "all">+ value={current}+ onChange={setValue}+ options={[+ {+ value: "all",+ title: "Data + files",+ description:+ "Records plus any uploaded files in the backup — 3D models, documents, images.",+ icon: <LuFiles />+ },+ {+ value: "none",+ title: "Data only",+ description:+ "Just the records. Skips bundled files — faster, and leaves current files in place.",+ icon: <LuDatabaseBackup />+ }+ ]}+ />+ <input type="hidden" name="includeStorage" value={current} />+ </>+ );+}++// Submit for the restore form — disabled until a source is chosen (the rest of+// the disabled/loading states come from Submit itself).+export function RestoreSubmit() {+ const [source] = useControlField<string>("source");+ return <Submit isDisabled={!source}>Restore</Submit>;+}diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupContentsInfo.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupContentsInfo.tsxnew file mode 100644index 0000000000..04fb6fda24--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/BackupContentsInfo.tsx@@ -0,0 +1,86 @@+import { Popover, PopoverContent, PopoverTrigger } from "@carbon/react";+import { useState } from "react";+import { LuInfo, LuLoaderCircle } from "react-icons/lu";+import { useFetcher } from "react-router";++// "i" popover with a compact table of how much of what a backup carries.+// Counts are lazy-loaded (head counts per entity) the first time it opens.+export function BackupContentsInfo() {+ const [open, setOpen] = useState(false);+ const summary = useFetcher<{+ groups: { title: string; rows: { label: string; count: number }[] }[];+ total: number;+ }>();+ const loaded = summary.data !== undefined;+ const loading = summary.state === "loading";++ return (+ <Popover+ open={open}+ onOpenChange={(o) => {+ setOpen(o);+ if (o && !loaded && summary.state === "idle") {+ summary.load("/api/settings/backup-summary");+ }+ }}+ >+ <PopoverTrigger asChild>+ <button+ type="button"+ aria-label="What a backup contains"+ className="text-muted-foreground hover:text-foreground"+ >+ <LuInfo className="h-3.5 w-3.5" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ className="w-72 max-h-[60dvh] overflow-y-auto"+ >+ <p className="text-sm font-medium">What's in a backup</p>+ <p className="text-xs text-muted-foreground mt-1 mb-3">+ Every company-scoped record. Credentials, integration tokens and+ webhooks are never included.+ </p>++ {loading && !loaded ? (+ <div className="flex items-center gap-2 py-3 text-xs text-muted-foreground">+ <LuLoaderCircle className="h-3.5 w-3.5 animate-spin" />+ Counting…+ </div>+ ) : (+ <div className="flex flex-col gap-3">+ {summary.data?.groups+ .filter((g) => g.rows.some((r) => r.count > 0))+ .map((group) => (+ <div key={group.title} className="flex flex-col gap-0.5">+ <p className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">+ {group.title}+ </p>+ {group.rows+ .filter((r) => r.count > 0)+ .map((row) => (+ <div+ key={row.label}+ className="flex items-center justify-between text-xs"+ >+ <span className="text-foreground">{row.label}</span>+ <span className="tabular-nums text-muted-foreground">+ {row.count.toLocaleString()}+ </span>+ </div>+ ))}+ </div>+ ))}+ <div className="flex items-center justify-between border-t pt-2 text-xs font-medium">+ <span>Total records</span>+ <span className="tabular-nums">+ {(summary.data?.total ?? 0).toLocaleString()}+ </span>+ </div>+ </div>+ )}+ </PopoverContent>+ </Popover>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsxnew file mode 100644index 0000000000..87bc41b8ce--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx@@ -0,0 +1,259 @@+import {+ Button,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalTitle+} from "@carbon/react";+import { useEffect, useState } from "react";+import { LuCheck, LuLoaderCircle, LuTriangleAlert } from "react-icons/lu";+import { useFetcher, useRevalidator } from "react-router";++// Simulated step labels per job. Restore/revert resolve from a real poll; export+// has no signal, so its steps play out then settle. Either way the steps make the+// wait legible — "what is it doing right now".+const STEP_SETS: Record<"export" | "restore" | "revert", string[]> = {+ export: [+ "Collecting records",+ "Bundling files",+ "Compressing",+ "Saving backup"+ ],+ restore: [+ "Snapshotting current data",+ "Clearing existing data",+ "Loading backup",+ "Restoring files"+ ],+ revert: ["Clearing restored data", "Restoring your snapshot"]+};++// The animated step checklist. Completed steps get a check that pops in+// (ease-out), the active step spins (constant motion → linear), pending steps sit+// dim. A thin bar fills as steps advance. All motion respects reduced-motion.+function StepChecklist({+ steps,+ step,+ done+}: {+ steps: string[];+ step: number;+ done: boolean;+}) {+ const fraction = done+ ? 1+ : (Math.min(step, steps.length - 1) + 0.5) / steps.length;+ return (+ <div className="flex w-full flex-col gap-4 py-2">+ <div className="h-1 w-full overflow-hidden rounded-full bg-muted">+ <div+ className="h-full origin-left rounded-full bg-primary transition-transform duration-700 ease-out motion-reduce:transition-none"+ style={{ transform: `scaleX(${fraction})` }}+ />+ </div>+ <div className="flex flex-col gap-2.5">+ {steps.map((label, i) => {+ const state =+ done || i < step ? "done" : i === step ? "active" : "pending";+ return (+ <div key={label} className="flex items-center gap-2.5 text-sm">+ <span className="flex h-5 w-5 shrink-0 items-center justify-center">+ {state === "done" ? (+ <LuCheck className="h-4 w-4 text-emerald-500 duration-200 animate-in fade-in zoom-in-75 motion-reduce:animate-none" />+ ) : state === "active" ? (+ <LuLoaderCircle className="h-4 w-4 animate-spin text-primary motion-reduce:animate-none" />+ ) : (+ <span className="h-1.5 w-1.5 rounded-full bg-muted-foreground/30" />+ )}+ </span>+ <span+ className={`transition-colors duration-300 ${+ state === "pending"+ ? "text-muted-foreground/40"+ : state === "active"+ ? "text-foreground"+ : "text-muted-foreground"+ }`}+ >+ {label}+ </span>+ </div>+ );+ })}+ </div>+ </div>+ );+}++// Stepped progress for export / restore / revert. Restore & revert track the real+// job via the status poll; export has no signal, so its steps simulate then+// settle and refresh the list. Shows working → success | failed.+export function JobProgressModal({+ mode,+ runId,+ onClose+}: {+ mode: "export" | "restore" | "revert";+ runId?: string;+ onClose: () => void;+}) {+ const isExport = mode === "export";+ const isRevert = mode === "revert";+ const revalidator = useRevalidator();+ const steps = STEP_SETS[mode];++ const statusFetcher = useFetcher<{+ status: "running" | "ready" | "failed" | "reverting" | "gone";+ rows: number;+ error: string | null;+ }>();+ const raw = statusFetcher.data?.status;+ const failed = !isExport && raw === "failed";+ const restoreReady = mode === "restore" && raw === "ready";+ const revertDone = isRevert && raw === "gone";++ const [step, setStep] = useState(0);+ const [simDone, setSimDone] = useState(false);+ const success = restoreReady || revertDone || (isExport && simDone);+ const done = success || failed;++ const rows = statusFetcher.data?.rows ?? 0;+ const error = statusFetcher.data?.error;+ const [ticks, setTicks] = useState(0);+ const slow = !done && ticks > 80;++ // Pre-heartbeat watchdog: if a restore never writes its first marker (the job+ // failed to start / never reached Inngest), the status stays "gone" forever.+ // Surface it instead of spinning indefinitely.+ const [sawMarker, setSawMarker] = useState(false);+ useEffect(() => {+ if (raw && raw !== "gone") setSawMarker(true);+ }, [raw]);+ const stalled = mode === "restore" && !done && !sawMarker && ticks > 40;++ // Poll the real job status (restore / revert only).+ const load = statusFetcher.load;+ useEffect(() => {+ if (isExport || !runId) return;+ if (done) {+ revalidator.revalidate();+ return;+ }+ const href = `/api/settings/backup-restore-status/${runId}`;+ load(href);+ const id = setInterval(() => {+ load(href);+ setTicks((t) => t + 1);+ }, 1500);+ return () => clearInterval(id);+ }, [isExport, runId, done, load, revalidator]);++ // Advance the visible steps on a cadence while the job runs.+ useEffect(() => {+ if (done) {+ setStep(steps.length);+ return;+ }+ const id = setInterval(+ () => setStep((s) => Math.min(s + 1, steps.length - 1)),+ 900+ );+ return () => clearInterval(id);+ }, [done, steps.length]);++ // Export has no completion signal — once the steps have played, settle and+ // refresh so the new backup shows in the list.+ useEffect(() => {+ if (!isExport || done || step < steps.length - 1) return;+ const t = setTimeout(() => {+ setSimDone(true);+ revalidator.revalidate();+ }, 900);+ return () => clearTimeout(t);+ }, [isExport, done, step, steps.length, revalidator]);++ const workingTitle = isExport+ ? "Creating backup…"+ : isRevert+ ? "Reverting…"+ : "Restoring…";+ const title = failed+ ? isRevert+ ? "Revert failed"+ : "Restore failed"+ : success+ ? isExport+ ? "Backup ready"+ : isRevert+ ? "Reverted"+ : "Restore complete"+ : 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;++ return (+ <Modal+ open+ onOpenChange={(o) => {+ if (!o && dismissable) onClose();+ }}+ >+ <ModalContent withCloseButton={dismissable}>+ <ModalHeader>+ <ModalTitle>{title}</ModalTitle>+ </ModalHeader>+ <ModalBody>+ {success ? (+ <div className="flex flex-col items-center gap-3 py-4">+ <LuCheck className="h-8 w-8 text-emerald-500 duration-300 animate-in fade-in zoom-in-75 motion-reduce:animate-none" />+ <p className="text-center text-sm text-muted-foreground">+ {isExport+ ? "Your backup is ready — it's in the list below."+ : isRevert+ ? "Your previous data is back, exactly as it was before the restore."+ : `Loaded ${rows.toLocaleString()} rows. Review it below — keep the restore, or revert to what was here before.`}+ </p>+ </div>+ ) : 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>+ )}+ </div>+ ) : (+ <>+ <StepChecklist steps={steps} step={step} done={done} />+ {stalled ? (+ <p className="text-center text-xs text-muted-foreground">+ Couldn't confirm the restore started. It may still be running+ — close this and check the list in a moment.+ </p>+ ) : slow ? (+ <p className="text-center text-xs text-muted-foreground">+ Still working — this is a large dataset. You can close this+ and check back in a bit.+ </p>+ ) : null}+ </>+ )}+ </ModalBody>+ <ModalFooter>+ {dismissable && (+ <Button onClick={onClose}>{success ? "Done" : "Close"}</Button>+ )}+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsxnew file mode 100644index 0000000000..00fd74079e--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx@@ -0,0 +1,150 @@+import { useCarbon } from "@carbon/auth";+import { useControlField } from "@carbon/form";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandSeparator,+ Popover,+ PopoverContent,+ PopoverTrigger,+ toast+} from "@carbon/react";+import type { ChangeEvent } from "react";+import { useMemo, useRef, useState } from "react";+import { LuArchive, LuChevronsUpDown, LuUpload } from "react-icons/lu";+import { useRevalidator } from "react-router";+import { formatBackupDate, formatBackupName } from "./format";++const triggerClass =+ "bg-transparent text-foreground flex h-10 w-full items-center justify-between gap-2 whitespace-nowrap rounded-md border border-input px-3 py-2 text-sm shadow-xs outline-none focus:border-ring focus:ring-[3px] focus:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50";++// One control combining your backups + upload new. Selecting one sets the+// hidden `source` field the restore form submits.+export function BackupSourcePicker({+ backups,+ companyId+}: {+ backups: { path: string; name: string; createdAt: string | null }[];+ companyId: string;+}) {+ const { carbon } = useCarbon();+ const revalidator = useRevalidator();+ const [value, setValue] = useControlField<string>("source");+ const [open, setOpen] = useState(false);+ const [uploading, setUploading] = useState(false);+ const fileRef = useRef<HTMLInputElement>(null);+ const current = value ?? "";++ const label = useMemo(() => {+ if (current.startsWith("backup:")) {+ const match = backups.find((b) => `backup:${b.path}` === current);+ return match ? formatBackupName(match.name) : "Backup";+ }+ return "";+ }, [current, backups]);++ const onUpload = async (e: ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ e.target.value = "";+ if (!file) return;+ if (!carbon) {+ toast.error("Carbon client not found");+ return;+ }+ if (!file.name.endsWith(".gz")) {+ toast.error("Select a .carbon.json.gz backup");+ return;+ }+ setUploading(true);+ toast.info(`Uploading ${file.name}`);+ const { error: uploadError } = await carbon.storage+ .from(companyId)+ .upload(`exports/${file.name}`, file, { upsert: true });+ setUploading(false);+ if (uploadError) {+ toast.error(`Failed to upload: ${uploadError.message}`);+ return;+ }+ setValue(`backup:exports/${file.name}`);+ toast.success("Backup uploaded");+ revalidator.revalidate();+ };++ return (+ <>+ <input type="hidden" name="source" value={current} />+ <input+ ref={fileRef}+ type="file"+ accept=".gz,application/gzip"+ className="hidden"+ onChange={onUpload}+ />+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button type="button" className={triggerClass}>+ <span+ className={+ current ? "truncate" : "truncate text-muted-foreground"+ }+ >+ {label || "Choose a backup"}+ </span>+ <LuChevronsUpDown className="h-4 w-4 shrink-0 opacity-50" />+ </button>+ </PopoverTrigger>+ <PopoverContent+ align="start"+ className="p-0 w-[var(--radix-popover-trigger-width)]"+ >+ <Command>+ <CommandInput placeholder="Search…" />+ <CommandList>+ <CommandEmpty>No matches</CommandEmpty>+ {backups.length > 0 && (+ <CommandGroup heading="Your backups">+ {backups.map((b) => (+ <CommandItem+ key={b.path}+ value={`backup ${b.name}`}+ onSelect={() => {+ setValue(`backup:${b.path}`);+ setOpen(false);+ }}+ >+ <LuArchive className="mr-2 h-4 w-4 shrink-0 opacity-60" />+ <span className="flex flex-col">+ <span>{formatBackupName(b.name)}</span>+ <span className="text-xs text-muted-foreground">+ {formatBackupDate(b.createdAt, false)}+ </span>+ </span>+ </CommandItem>+ ))}+ </CommandGroup>+ )}+ <CommandSeparator />+ <CommandGroup>+ <CommandItem+ value="upload new backup"+ disabled={uploading}+ onSelect={() => {+ setOpen(false);+ fileRef.current?.click();+ }}+ >+ <LuUpload className="mr-2 h-4 w-4 opacity-60" />+ {uploading ? "Uploading…" : "Upload new backup…"}+ </CommandItem>+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ </>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Backups/RestoreReviewRow.tsx b/apps/erp/app/modules/settings/ui/Backups/RestoreReviewRow.tsxnew file mode 100644index 0000000000..3a8fedb618--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/RestoreReviewRow.tsx@@ -0,0 +1,67 @@+import { Button, HStack, VStack } from "@carbon/react";+import { LuLoaderCircle } from "react-icons/lu";++export type RestoreRun = {+ restoreRunId: string;+ status: "running" | "ready" | "failed" | "reverting";+ rows: number;+ label: string | null;+ error: string | null;+ startedAt: string;+};++// One row in the "Restored — review" card, branching on the run's status.+export function RestoreReviewRow({+ run,+ onKeep,+ onRevert,+ onDismiss+}: {+ run: RestoreRun;+ onKeep: () => void;+ onRevert: () => void;+ onDismiss: () => void;+}) {+ const busy = run.status === "running" || run.status === "reverting";+ return (+ <HStack className="w-full justify-between border rounded-lg p-3">+ <VStack spacing={0} className="min-w-0">+ <span className="text-sm font-medium truncate">+ {run.label ?? "Restore"}+ </span>+ {run.status === "failed" ? (+ <span className="text-xs text-destructive-foreground">+ Failed — {run.error ?? "unknown error"}+ </span>+ ) : (+ <span className="text-xs text-muted-foreground">+ {new Date(run.startedAt).toLocaleString()} ·{" "}+ {run.status === "running"+ ? "restoring…"+ : run.status === "reverting"+ ? "reverting…"+ : `${run.rows.toLocaleString()} rows`}+ </span>+ )}+ </VStack>+ <HStack spacing={2} className="shrink-0">+ {run.status === "ready" && (+ <>+ <Button onClick={onKeep}>Keep</Button>+ <Button variant="destructive" onClick={onRevert}>+ Revert+ </Button>+ </>+ )}+ {run.status === "failed" && (+ <Button variant="secondary" onClick={onDismiss}>+ Dismiss+ </Button>+ )}+ {busy && (+ <LuLoaderCircle className="h-4 w-4 animate-spin text-muted-foreground" />+ )}+ </HStack>+ </HStack>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Backups/format.ts b/apps/erp/app/modules/settings/ui/Backups/format.tsnew file mode 100644index 0000000000..975944d525--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/format.ts@@ -0,0 +1,42 @@+// Backup filenames are `{timestamp}_{label-slug}.carbon.json.gz`. Turn the slug+// back into a readable title (the timestamp is shown separately as the date).+const BACKUP_ACRONYMS = new Set([+ "oem",+ "amr",+ "scara",+ "cad",+ "bom",+ "erp",+ "mes",+ "ai",+ "qa"+]);++export function formatBackupName(name: string): string {+ const base = name.replace(/\.carbon\.json\.gz$/i, "");+ const underscore = base.indexOf("_");+ const slug = underscore >= 0 ? base.slice(underscore + 1) : "";+ if (!slug) return "Untitled backup";+ return slug+ .split("-")+ .filter(Boolean)+ .map((word) =>+ BACKUP_ACRONYMS.has(word.toLowerCase())+ ? word.toUpperCase()+ : word.charAt(0).toUpperCase() + word.slice(1)+ )+ .join(" ");+}++export function formatBackupDate(+ iso: string | null | undefined,+ withTime = true+): string {+ if (!iso) return "";+ return new Date(iso).toLocaleString(+ undefined,+ withTime+ ? { dateStyle: "medium", timeStyle: "short" }+ : { dateStyle: "medium" }+ );+}diff --git a/apps/erp/app/modules/settings/ui/Backups/index.ts b/apps/erp/app/modules/settings/ui/Backups/index.tsnew file mode 100644index 0000000000..9d12c5a3e3--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/index.ts@@ -0,0 +1,6 @@+export * from "./BackupChoices";+export * from "./BackupContentsInfo";+export * from "./BackupProgressModal";+export * from "./BackupSourcePicker";+export * from "./format";+export * from "./RestoreReviewRow";diff --git a/apps/erp/app/modules/settings/ui/index.ts b/apps/erp/app/modules/settings/ui/index.tsindex 5b7066eb11..09265660ca 100644--- a/apps/erp/app/modules/settings/ui/index.ts+++ b/apps/erp/app/modules/settings/ui/index.ts@@ -3,6 +3,7 @@ import useSettingsSubmodules from "./useSettingsSubmodules";export * from "./ApiKeys";export * from "./Approvals";export * from "./AuditLog";+export * from "./Backups";export * from "./Companies";export * from "./Company";export * from "./CustomFields";diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsxindex a3d6246981..b0dbeca83a 100644--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx@@ -6,6 +6,7 @@ import {LuClipboardCheck,LuCreditCard,LuCrown,+ LuDatabase,LuFactory,LuFileText,LuHistory,@@ -28,7 +29,10 @@ import { useFlags } from "~/hooks/useFlags";import type { AuthenticatedRouteGroup, Role } from "~/types";import { path } from "~/utils/path";-const internalOnlyRoutes = new Set<string>([path.to.companies]);+const internalOnlyRoutes = new Set<string>([+ path.to.companies,+ path.to.backups+]);export default function useSettingsSubmodules() {const { t } = useLingui();@@ -75,6 +79,13 @@ export default function useSettingsSubmodules() {role: "employee",icon: <LuImage />},+ {+ name: t`Backups`,+ to: path.to.backups,+ role: "employee",+ icon: <LuDatabase />,+ requiresOwnership: true+ },{name: t`Printing`,to: path.to.printingSettings,diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex bd1ec79d47..400dd8b75d 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-06-21T22:03:32.744Z",- "totalTools": 1209,+ "generated": "2026-06-24T16:17:19.954Z",+ "totalTools": 1210,"modules": 15,"tools": [{@@ -33318,6 +33318,23 @@"properties": {}}},+ {+ "name": "settings_getIndustries",+ "module": "settings",+ "classification": "READ",+ "description": "get industries",+ "paramCount": 0,+ "serviceParams": [+ "client"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {}+ }+ },{"name": "settings_getCompany","module": "settings",diff --git a/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts b/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.tsnew file mode 100644index 0000000000..4384171ba8--- /dev/null+++ b/apps/erp/app/routes/api+/settings.backup-restore-status.$restoreRunId.ts@@ -0,0 +1,28 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { isInternalEmail } from "@carbon/utils";+import type { LoaderFunctionArgs } from "react-router";+import { getCompanyRestoreRuns } from "~/modules/settings";++// Polled by the restore progress modal. A restore run is "running" until its+// marker row appears (the job writes it once the wipe+load commits), then+// "ready" for keep/revert. Once kept or reverted the marker is gone again — the+// client knows which phase it's in, so it interprets absence accordingly.+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId, email } = await requirePermissions(request, {+ update: "settings"+ });+ if (!isInternalEmail(email)) throw new Response("Not found", { status: 404 });+ const restoreRunId = params.restoreRunId;++ const runs = await getCompanyRestoreRuns(client, companyId);+ const run = runs.data?.find((r) => r.restoreRunId === restoreRunId);++ // No marker → "gone". The client interprets it by phase: during a restore it+ // means the job hasn't written its first heartbeat yet (transient); during a+ // revert it means the revert finished (the marker is deleted on success).+ return {+ status: run?.status ?? ("gone" as const),+ rows: run?.rows ?? 0,+ error: run?.error ?? null+ };+}diff --git a/apps/erp/app/routes/api+/settings.backup-summary.ts b/apps/erp/app/routes/api+/settings.backup-summary.tsnew file mode 100644index 0000000000..96908ca1a0--- /dev/null+++ b/apps/erp/app/routes/api+/settings.backup-summary.ts@@ -0,0 +1,125 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { isInternalEmail } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { LoaderFunctionArgs } from "react-router";++// Recognizable entities a backup carries, grouped for the "what's in a backup"+// popover. Not exhaustive (the export covers every scoped table) — just the+// meaningful headline counts. `scope` is the column rows are counted by:+// "company" (companyId, the default) or "group" (companyGroupId — the shared+// chart of accounts / currencies / dimensions).+type Scope = "company" | "group";+type Entity = [label: string, table: string, scope?: Scope];++const GROUPS: { title: string; entities: Entity[] }[] = [+ {+ title: "Sales",+ entities: [+ ["Customers", "customer"],+ ["Quotes", "quote"],+ ["Sales orders", "salesOrder"],+ ["Sales invoices", "salesInvoice"],+ ["Shipments", "shipment"]+ ]+ },+ {+ title: "Purchasing",+ entities: [+ ["Suppliers", "supplier"],+ ["Purchase orders", "purchaseOrder"],+ ["Purchase invoices", "purchaseInvoice"],+ ["Receipts", "receipt"]+ ]+ },+ {+ title: "Items",+ entities: [+ ["Parts", "part"],+ ["Materials", "material"],+ ["Tools", "tool"]+ ]+ },+ {+ title: "Production",+ entities: [+ ["Jobs", "job"],+ ["Work centers", "workCenter"],+ ["Processes", "process"]+ ]+ },+ {+ title: "Accounting",+ entities: [+ ["Accounts", "account", "group"],+ ["Currencies", "currency", "group"],+ ["Dimensions", "dimension", "group"],+ ["Journal lines", "journalLine"],+ ["Item ledger", "itemLedger"],+ ["Cost ledger", "costLedger"]+ ]+ },+ {+ title: "Quality",+ entities: [+ ["Non-conformances", "nonConformance"],+ ["Gauges", "gauge"]+ ]+ },+ { title: "People", entities: [["Employees", "employee"]] }+];++async function countEntity(+ client: SupabaseClient,+ table: string,+ column: string,+ value: string | null+): Promise<number> {+ if (!value) return 0;+ try {+ const { count } = await client+ .from(table)+ .select("*", { count: "exact", head: true })+ .eq(column, value);+ return count ?? 0;+ } catch {+ return 0;+ }+}++// Lazy-loaded by the backup-contents popover (only when opened). Returns a+// headline row count per entity, grouped, plus a grand total.+export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId, companyGroupId, email } = await requirePermissions(+ request,+ { view: "settings" }+ );+ if (!isInternalEmail(email)) throw new Response("Not found", { status: 404 });++ const groups = await Promise.all(+ GROUPS.map(async (group) => {+ const rows = await Promise.all(+ group.entities.map(async ([label, table, scope]) =>+ scope === "group"+ ? {+ label,+ count: await countEntity(+ client,+ table,+ "companyGroupId",+ companyGroupId+ )+ }+ : {+ label,+ count: await countEntity(client, table, "companyId", companyId)+ }+ )+ );+ const subtotal = rows.reduce((sum, r) => sum + r.count, 0);+ return { title: group.title, rows, subtotal };+ })+ );++ const total = groups.reduce((sum, g) => sum + g.subtotal, 0);+ return { groups, total };+}diff --git a/apps/erp/app/routes/onboarding+/company.tsx b/apps/erp/app/routes/onboarding+/company.tsxindex fbc1ea293d..164f2d5ce4 100644--- a/apps/erp/app/routes/onboarding+/company.tsx+++ b/apps/erp/app/routes/onboarding+/company.tsx@@ -1,10 +1,6 @@-import { assertIsPost, CarbonEdition } from "@carbon/auth";+import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { setCompanyId } from "@carbon/auth/company.server";-import { updateCompanySession } from "@carbon/auth/session.server";import { ValidatedForm, validationError, validator } from "@carbon/form";-import { trigger } from "@carbon/jobs";import {Button,Card,@@ -15,11 +11,12 @@ import {HStack,VStack} from "@carbon/react";-import { Edition } from "@carbon/utils";-import { getLocalTimeZone } from "@internationalized/date";-import { Trans, useLingui } from "@lingui/react/macro";-import type { ActionFunctionArgs } from "react-router";-import { Link, redirect, useLoaderData } from "react-router";+import {+ type ActionFunctionArgs,+ Link,+ redirect,+ useLoaderData+} from "react-router";import {AddressAutocomplete,Currency,@@ -28,203 +25,87 @@ import {Submit} from "~/components/Form";import { useOnboarding } from "~/hooks";-import { insertEmployeeJob } from "~/modules/people";-import { getLocationsList, upsertLocation } from "~/modules/resources";+import { addressValidator, getCompany } from "~/modules/settings";import {- getCompanies,- getCompany,- insertCompany,- onboardingCompanyValidator,- seedCompany,- updateCompany-} from "~/modules/settings";+ getOnboardingDraft,+ setOnboardingDraft+} from "~/services/onboarding-draft.server";export async function loader({ request }: ActionFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});const company = await getCompany(client, companyId ?? 1);+ const draft = await getOnboardingDraft(request);if (company.error || !company.data) {return {- company: null+ company: null,+ draft};}- return { company: company.data };+ return { company: company.data, draft };}export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {});+ await requirePermissions(request, {});- // there are no entries in the userToCompany table which- // dictates RLS for the company table+ const formData = await request.formData();- const validation = await validator(onboardingCompanyValidator).validate(- await request.formData()- );+ const validation = await validator(addressValidator).validate(formData);if (validation.error) {return validationError(validation.error);}- const serviceRole = getCarbonServiceRole();-- const { next, ...d } = validation.data;-- let companyId: string | undefined;-- const companies = await getCompanies(client, userId);- const company = companies?.data?.[0];-- const locations = await getLocationsList(client, company?.id ?? "");- const location = locations?.data?.[0];-- if (company && location) {- const [companyUpdate, locationUpdate] = await Promise.all([- updateCompany(serviceRole, company.id!, {- ...d,- updatedBy: userId- }),- upsertLocation(serviceRole, {- ...location,- ...d,- timezone: getLocalTimeZone(),- updatedBy: userId- })- ]);- if (companyUpdate.error) {- console.error(companyUpdate.error);- throw new Error("Fatal: failed to update company");- }- if (locationUpdate.error) {- console.error(locationUpdate.error);- throw new Error("Fatal: failed to update location");- }- } else {- if (!companyId) {- const [companyInsert] = await Promise.all([- insertCompany(serviceRole, d)- ]);- if (companyInsert.error) {- console.error(companyInsert.error);- throw new Error("Fatal: failed to insert company");- }-- companyId = companyInsert.data?.id;- }-- if (!companyId) {- throw new Error("Fatal: failed to get company ID");- }-- const seed = await seedCompany(serviceRole, companyId, userId);- if (seed.error) {- console.error(seed.error);- throw new Error("Fatal: failed to seed company");- }-- if (CarbonEdition === Edition.Cloud) {- trigger("onboard", {- type: "lead",- companyId,- userId- });- }+ const { next, ...companyData } = validation.data;- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const { baseCurrencyCode, website, ...locationData } = d;-- // TODO: move all of this to transaction- const [locationInsert] = await Promise.all([- upsertLocation(serviceRole, {- ...locationData,- name: "Headquarters",- companyId,- timezone: getLocalTimeZone(),- createdBy: userId- })- ]);-- if (locationInsert.error) {- console.error(locationInsert.error);- throw new Error("Fatal: failed to insert location");- }-- const locationId = locationInsert.data?.id;- if (!locationId) {- throw new Error("Fatal: failed to get location ID");- }-- const [job] = await Promise.all([- insertEmployeeJob(serviceRole, {- id: userId,- companyId,- locationId- })- ]);-- if (job.error) {- console.error(job.error);- throw new Error("Fatal: failed to insert job");- }- }-- const { data: companyRecord } = await serviceRole- .from("company")- .select("companyGroupId")- .eq("id", companyId!)- .single();-- const sessionCookie = await updateCompanySession(- request,- companyId!,- companyRecord?.companyGroupId ?? ""- );- const companyIdCookie = setCompanyId(companyId!);+ // Store company data in session draft for the next step (industry)+ const draftCookie = await setOnboardingDraft(request, {+ company: companyData+ });throw redirect(next, {- headers: [- ["Set-Cookie", sessionCookie],- ["Set-Cookie", companyIdCookie]- ]+ headers: [["Set-Cookie", draftCookie]]});}export default function OnboardingCompany() {- const { t } = useLingui();- const { company } = useLoaderData<typeof loader>();+ const { company, draft } = useLoaderData<typeof loader>();const { next, previous } = useOnboarding();const initialValues = {- name: company?.name ?? "",- addressLine1: company?.addressLine1 ?? "",- city: company?.city ?? "",- stateProvince: company?.stateProvince ?? "",- postalCode: company?.postalCode ?? "",- countryCode: company?.countryCode ?? "US",- baseCurrencyCode: company?.baseCurrencyCode ?? "USD"+ name: company?.name ?? draft?.company?.name ?? "",+ addressLine1: company?.addressLine1 ?? draft?.company?.addressLine1 ?? "",+ addressLine2: company?.addressLine2 ?? draft?.company?.addressLine2 ?? "",+ city: company?.city ?? draft?.company?.city ?? "",+ stateProvince:+ company?.stateProvince ?? draft?.company?.stateProvince ?? "",+ postalCode: company?.postalCode ?? draft?.company?.postalCode ?? "",+ countryCode: company?.countryCode ?? draft?.company?.countryCode ?? "US",+ baseCurrencyCode:+ company?.baseCurrencyCode ?? draft?.company?.baseCurrencyCode ?? "USD",+ website: company?.website ?? draft?.company?.website ?? ""};return (<Card className="max-w-lg"><ValidatedForm- validator={onboardingCompanyValidator}+ validator={addressValidator}defaultValues={initialValues}method="post"><CardHeader>- <CardTitle>- <Trans>Now let's set up your company</Trans>- </CardTitle>+ <CardTitle>Now let's set up your company</CardTitle></CardHeader><CardContent><Hidden name="next" value={next} /><VStack spacing={4}>- <Input autoFocus name="name" label={t`Company Name`} />+ <Input autoFocus name="name" label="Company Name" /><AddressAutocomplete />- <Input name="website" label={t`Website`} />- <Currency name="baseCurrencyCode" label={t`Base Currency`} />+ <Input name="website" label="Website" />+ <Currency name="baseCurrencyCode" label="Base Currency" /></VStack></CardContent>@@ -238,12 +119,10 @@ export default function OnboardingCompany() {tabIndex={-1}><Link to={previous} prefetch="intent">- <Trans>Previous</Trans>+ Previous</Link></Button>- <Submit>- <Trans>Next</Trans>- </Submit>+ <Submit>Next</Submit></HStack></CardFooter></ValidatedForm>diff --git a/apps/erp/app/routes/onboarding+/industry.tsx b/apps/erp/app/routes/onboarding+/industry.tsxnew file mode 100644index 0000000000..e8d4994844--- /dev/null+++ b/apps/erp/app/routes/onboarding+/industry.tsx@@ -0,0 +1,512 @@+import { assertIsPost, CarbonEdition } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { setCompanyId } from "@carbon/auth/company.server";+import { updateCompanySession } from "@carbon/auth/session.server";+import { ValidatedForm, validationError, validator } from "@carbon/form";+import { trigger } from "@carbon/jobs";+import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ ChoiceCardGroup,+ type ChoiceCardOption,+ cn,+ HStack+} from "@carbon/react";+import { Edition } from "@carbon/utils";+import { getLocalTimeZone } from "@internationalized/date";+import { type ReactNode, useState } from "react";+import {+ LuBot,+ LuCog,+ LuDatabase,+ LuFactory,+ LuFileX,+ LuUpload,+ LuWrench+} from "react-icons/lu";+import {+ type ActionFunctionArgs,+ Form,+ Link,+ redirect,+ useLoaderData+} from "react-router";+import { z } from "zod";+import { Hidden, Submit } from "~/components/Form";+import { useOnboarding } from "~/hooks";+import { insertEmployeeJob } from "~/modules/people";+import { getLocationsList, upsertLocation } from "~/modules/resources";+import {+ getCompanies,+ getCompany,+ getIndustries,+ insertCompany,+ onboardingCompanyValidator,+ updateCompany+} from "~/modules/settings";+import {+ fetchTemplateBackup,+ provisionCompanyData+} from "~/services/onboarding.server";+import {+ clearOnboardingDraft,+ getOnboardingDraft,+ type OnboardingDraft+} from "~/services/onboarding-draft.server";++type DataChoice = "template" | "import" | "none";++const onboardingIndustryValidator = z+ .object({+ industryId: z.string().optional(),+ customIndustryDescription: z.string().optional(),+ dataChoice: z.enum(["template", "import", "none"]).default("none"),+ next: z.string()+ })+ .refine((data) => !(data.dataChoice === "template" && !data.industryId), {+ message: "Please select an industry for the demo template",+ path: ["industryId"]+ });++/** Industry icons live in code (JSX can't be stored in the DB); the `industry`+ * table carries an `iconName` that maps here. */+const INDUSTRY_ICONS: Record<string, ReactNode> = {+ bot: <LuBot className="h-5 w-5" />,+ cog: <LuCog className="h-5 w-5" />,+ wrench: <LuWrench className="h-5 w-5" />+};++/** Append the company data captured in the previous onboarding step. */+function appendDraftCompany(+ fd: FormData,+ company: NonNullable<OnboardingDraft["company"]>+) {+ for (const [key, value] of Object.entries(company)) {+ if (value) fd.append(key, value);+ }+}++export async function loader({ request }: ActionFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {});++ const company = await getCompany(client, companyId);+ const draft = await getOnboardingDraft(request);+ const industries = (await getIndustries(client)).data ?? [];++ if (company.error || !company.data) {+ return { company: null, draft, industries };+ }++ return { company: company.data, draft, industries };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {});++ // Get draft data from previous step (company)+ const draft = await getOnboardingDraft(request);++ const formData = await request.formData();++ // Validate industry fields+ const industryValidation = await validator(+ onboardingIndustryValidator+ ).validate(formData);++ if (industryValidation.error) {+ return validationError(industryValidation.error);+ }++ const { industryId, dataChoice } = industryValidation.data;+ const finalIndustryId = industryId || null;++ // Carry forward the company data captured in the previous (company) step.+ if (draft?.company) appendDraftCompany(formData, draft.company);++ const validation = await validator(onboardingCompanyValidator).validate(+ formData+ );+ if (validation.error) {+ return validationError(validation.error);+ }++ const serviceRole = getCarbonServiceRole();+ const { next, ...d } = validation.data;+ const companyData = {+ ...d,+ industryId: d.industryId || null+ };++ let companyId: string | undefined;++ const companies = await getCompanies(client, userId);+ const company = companies?.data?.[0];++ const locations = await getLocationsList(client, company?.id ?? "");+ const location = locations?.data?.[0];++ // Extract address data for location+ const addressData = {+ addressLine1: d.addressLine1,+ addressLine2: d.addressLine2,+ city: d.city,+ stateProvince: d.stateProvince,+ postalCode: d.postalCode,+ countryCode: d.countryCode+ };++ if (company && location) {+ // Update existing company and location+ const [companyUpdate, locationUpdate] = await Promise.all([+ updateCompany(serviceRole, company.id!, {+ ...companyData,+ updatedBy: userId+ }),+ upsertLocation(serviceRole, {+ ...location,+ ...addressData,+ timezone: getLocalTimeZone(),+ updatedBy: userId+ })+ ]);+ if (companyUpdate.error) {+ console.error(companyUpdate.error);+ throw new Error("Fatal: failed to update company");+ }+ if (locationUpdate.error) {+ console.error(locationUpdate.error);+ throw new Error("Fatal: failed to update location");+ }++ companyId = company.id!;+ } else {+ // Create new company.+ const companyInsert = await insertCompany(serviceRole, companyData);+ if (companyInsert.error) {+ console.error(companyInsert.error);+ throw new Error("Fatal: failed to insert company");+ }+ companyId = companyInsert.data?.id;+ if (!companyId) {+ throw new Error("Fatal: failed to get company ID");+ }++ // A demo template and "restore from a backup" both resolve to a backup+ // file; "none" → a clean seed. provisionCompanyData imports it or seeds.+ 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;++ await provisionCompanyData(serviceRole, {+ companyId,+ userId,+ backup,+ // Only a demo template references shared assets; a user's own uploaded+ // backup ("import") stays self-contained and is copied per company.+ templateIndustryId: dataChoice === "template" ? finalIndustryId : null+ });++ if (CarbonEdition === Edition.Cloud) {+ trigger("onboard", {+ type: "lead",+ companyId,+ userId+ });+ }++ // Create location+ const [locationInsert] = await Promise.all([+ upsertLocation(serviceRole, {+ ...addressData,+ name: "Headquarters",+ companyId,+ timezone: getLocalTimeZone(),+ createdBy: userId+ })+ ]);++ if (locationInsert.error) {+ console.error(locationInsert.error);+ throw new Error("Fatal: failed to insert location");+ }++ const locationId = locationInsert.data?.id;+ if (!locationId) {+ throw new Error("Fatal: failed to get location ID");+ }++ // Create employee job+ const [job] = await Promise.all([+ insertEmployeeJob(serviceRole, {+ id: userId,+ companyId,+ locationId+ })+ ]);++ if (job.error) {+ console.error(job.error);+ throw new Error("Fatal: failed to insert job");+ }+ }++ const companyRecord = await serviceRole+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId!)+ .single();+ const sessionCookie = await updateCompanySession(+ request,+ companyId!,+ companyRecord.data?.companyGroupId ?? ""+ );+ const companyIdCookie = setCompanyId(companyId!);+ const clearDraftCookie = await clearOnboardingDraft(request);++ throw redirect(next, {+ headers: [+ ["Set-Cookie", sessionCookie],+ ["Set-Cookie", companyIdCookie],+ ["Set-Cookie", clearDraftCookie]+ ]+ });+}++type Step = "data-question" | "industry-selection" | "import-upload";++export default function OnboardingIndustry() {+ const { company, industries } = useLoaderData<typeof loader>();+ const { next, previous } = useOnboarding();++ // Determine initial step based on existing company data+ const getInitialStep = (): Step => {+ if (company?.industryId) {+ return "industry-selection";+ }+ return "data-question";+ };++ const [step, setStep] = useState<Step>(getInitialStep);+ const [dataChoice, setDataChoice] = useState<DataChoice>("template");+ const [importFile, setImportFile] = useState<File | null>(null);+ const [selectedIndustryId, setSelectedIndustryId] = useState<string>(+ company?.industryId ?? ""+ );++ const initialValues = {+ industryId: industries.some((i) => i.id === company?.industryId)+ ? (company?.industryId ?? undefined)+ : undefined,+ customIndustryDescription: company?.customIndustryDescription ?? ""+ };++ const industryOptions: ChoiceCardOption[] = industries.map((i) => ({+ value: i.id,+ title: i.name,+ description: i.description ?? "",+ icon: INDUSTRY_ICONS[i.iconName ?? ""] ?? <LuFactory className="h-5 w-5" />+ }));++ const handleNext = () => {+ if (dataChoice === "template") setStep("industry-selection");+ else if (dataChoice === "import") setStep("import-upload");+ // "none" submits the form directly via the Submit button+ };++ const dataChoiceOptions: ChoiceCardOption<DataChoice>[] = [+ {+ value: "template",+ title: "Use a demo template",+ description:+ "We'll add sample customers, suppliers, parts and quotes to explore Carbon",+ icon: <LuDatabase className="h-5 w-5" />+ },+ {+ value: "import" as const,+ title: "Restore from a backup",+ description: "Set up from a Carbon backup of another company",+ icon: <LuUpload className="h-5 w-5" />+ },+ {+ value: "none",+ title: "I don't need data",+ description: "Start with a clean, empty environment",+ icon: <LuFileX className="h-5 w-5" />+ }+ ];++ if (step === "import-upload") {+ return (+ <Card className="max-w-lg">+ <Form method="post" encType="multipart/form-data">+ <CardHeader>+ <CardTitle>Restore from a backup</CardTitle>+ <CardDescription>+ Upload a Carbon backup and we'll set up your new company from it.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <input type="hidden" name="next" value={next} />+ <input type="hidden" name="dataChoice" value="import" />+ <label+ className={cn(+ "flex cursor-pointer flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed p-6 text-center transition-colors",+ "border-border hover:border-primary/50 hover:bg-accent/50"+ )}+ >+ <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted text-muted-foreground">+ <LuUpload className="h-5 w-5" />+ </div>+ {importFile ? (+ <span className="text-sm font-medium text-foreground">+ {importFile.name}+ </span>+ ) : (+ <>+ <span className="text-sm font-medium text-foreground">+ Choose your backup file+ </span>+ <span className="text-xs text-muted-foreground">+ A Carbon backup (.carbon.json.gz)+ </span>+ </>+ )}+ <input+ type="file"+ name="backup"+ accept=".gz,application/gzip"+ className="sr-only"+ onChange={(e) => setImportFile(e.target.files?.[0] ?? null)}+ />+ </label>+ </CardContent>+ <CardFooter>+ <HStack>+ <Button+ variant="solid"+ size="md"+ type="button"+ onClick={() => setStep("data-question")}+ >+ Previous+ </Button>+ <Button+ variant="primary"+ size="md"+ type="submit"+ isDisabled={!importFile}+ >+ Create company+ </Button>+ </HStack>+ </CardFooter>+ </Form>+ </Card>+ );+ }++ return (+ <Card className="max-w-lg">+ <ValidatedForm+ validator={onboardingIndustryValidator}+ defaultValues={initialValues}+ method="post"+ >+ {step === "data-question" ? (+ <>+ <CardHeader>+ <CardTitle>How would you like to start?</CardTitle>+ <CardDescription>+ Choose how to set up your new company.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Hidden name="next" value={next} />+ <Hidden name="dataChoice" value={dataChoice} />+ <ChoiceCardGroup+ className="max-w-md"+ value={dataChoice}+ onChange={setDataChoice}+ options={dataChoiceOptions}+ />+ </CardContent>++ <CardFooter>+ <HStack>+ <Button+ variant="solid"+ isDisabled={!previous}+ size="md"+ asChild+ tabIndex={-1}+ >+ <Link to={previous} prefetch="intent">+ Previous+ </Link>+ </Button>+ {dataChoice === "none" ? (+ <Submit>Next</Submit>+ ) : (+ <Button+ variant="primary"+ size="md"+ type="button"+ onClick={handleNext}+ >+ Next+ </Button>+ )}+ </HStack>+ </CardFooter>+ </>+ ) : (+ <>+ <CardHeader>+ <CardTitle>Which best describes your company?</CardTitle>+ <CardDescription>+ We'll set up demo data to match your industry+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Hidden name="next" value={next} />+ <Hidden name="dataChoice" value="template" />+ <Hidden name="industryId" value={selectedIndustryId} />+ <ChoiceCardGroup+ value={selectedIndustryId}+ onChange={setSelectedIndustryId}+ options={industryOptions}+ />+ </CardContent>++ <CardFooter>+ <HStack>+ <Button+ variant="solid"+ size="md"+ type="button"+ onClick={() => setStep("data-question")}+ >+ Previous+ </Button>+ <Submit isDisabled={!selectedIndustryId}>Next</Submit>+ </HStack>+ </CardFooter>+ </>+ )}+ </ValidatedForm>+ </Card>+ );+}diff --git a/apps/erp/app/routes/x+/inventory+/quantities.tsx b/apps/erp/app/routes/x+/inventory+/quantities.tsxindex 39007ee3b2..4f26d349d8 100644--- a/apps/erp/app/routes/x+/inventory+/quantities.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities.tsx@@ -51,7 +51,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const userDefaults = await getUserDefaults(client, userId, companyId);if (userDefaults.error) {throw redirect(- path.to.inventory,+ path.to.authenticatedRoot,await flash(request,error(userDefaults.error, "Failed to load default location")@@ -65,11 +65,19 @@ export async function loader({ request }: LoaderFunctionArgs) {if (!locationId) {const locations = await getLocationsList(client, companyId);if (locations.error || !locations.data?.length) {+ // `path.to.inventory` *is* this route — redirecting here loops forever.+ // On error bail to the app root; with zero locations (a company that+ // can't show inventory at all) send them to create one.throw redirect(- path.to.inventory,+ locations.error ? path.to.authenticatedRoot : path.to.locations,await flash(request,- error(locations.error, "Failed to load any locations")+ error(+ locations.error,+ locations.error+ ? "Failed to load any locations"+ : "Create a location to manage inventory"+ )));}diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsxnew file mode 100644index 0000000000..874767dea5--- /dev/null+++ b/apps/erp/app/routes/x+/settings+/backups.tsx@@ -0,0 +1,505 @@+// Settings → Backups (company export / in-place restore).+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { Database } from "@carbon/database";+import {+ Hidden,+ Input,+ Submit,+ ValidatedForm,+ validationError,+ validator+} from "@carbon/form";+import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ Heading,+ HStack,+ ScrollArea,+ toast,+ VStack+} from "@carbon/react";+import { convertKbToString, isInternalEmail } from "@carbon/utils";+import { msg } from "@lingui/core/macro";+import type { SupabaseClient } from "@supabase/supabase-js";+import { useEffect, useState } from "react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, Form, redirect, useFetcher, useLoaderData } from "react-router";+import { z } from "zod";+import {+ deleteCompanyBackupExport,+ exportCompanyBackup,+ getCompanyBackupSignedUrl,+ getCompanyRestoreRuns,+ listCompanyBackupExports+} from "~/modules/settings";+import {+ finalizeCompanyRestore,+ revertCompanyRestore,+ startCompanyRestore+} from "~/modules/settings/backups.server";+import {+ BackupContentsInfo,+ BackupSourcePicker,+ formatBackupDate,+ formatBackupName,+ IncludeStorageChoice,+ JobProgressModal,+ RestoreIncludeChoice,+ RestoreReviewRow,+ RestoreSubmit+} from "~/modules/settings/ui/Backups";+import { getEdgeFunctionErrorMessage } from "~/utils/error";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: msg`Backups`,+ to: path.to.backups+};++// Hidden pre-restore snapshots are named `_pre-restore-<runId>` — never shown+// in the backups list or offered as a restore source.+const SNAPSHOT_PREFIX = "_pre-restore-";++const exportValidator = z.object({+ intent: z.literal("export"),+ label: z.string().optional(),+ includeStorage: z.enum(["none", "all"])+});++// `source` is `backup:<path>` — one of this company's own exports (or an+// uploaded copy of one). Restore is always in-place into the current company.+// `includeStorage` picks whether uploaded files (3D models, docs) come along.+const restoreValidator = z.object({+ intent: z.literal("restore"),+ source: z.string().min(1, { message: "Choose a backup to restore" }),+ includeStorage: z.enum(["none", "all"])+});++async function requireOwner(+ request: Request,+ client: SupabaseClient<Database>,+ companyGroupId: string | null,+ userId: string,+ email: string | null+) {+ // Internal-only while multi-tenant hardening is pending.+ if (!isInternalEmail(email)) {+ throw redirect(path.to.settings);+ }++ const group = companyGroupId+ ? await client+ .from("companyGroup")+ .select("ownerId")+ .eq("id", companyGroupId)+ .single()+ : null;++ if (group?.data?.ownerId !== userId) {+ throw redirect(+ path.to.settings,+ await flash(+ request,+ error(null, "Only the company owner can access backups")+ )+ );+ }+}++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId, companyGroupId, userId, email } =+ await requirePermissions(request, {+ update: "settings"+ });+ await requireOwner(request, client, companyGroupId, userId, email);++ const [exportsList, restoreRuns] = await Promise.all([+ listCompanyBackupExports(client, companyId),+ getCompanyRestoreRuns(client, companyId)+ ]);++ const files = await Promise.all(+ (exportsList.data ?? [])+ // Drop folders and the hidden pre-restore snapshots.+ .filter((f) => f.id !== null && !f.name.startsWith(SNAPSHOT_PREFIX))+ .map(async (f) => {+ const filePath = `exports/${f.name}`;+ const signed = await getCompanyBackupSignedUrl(+ client,+ companyId,+ filePath+ );+ return {+ name: f.name,+ path: filePath,+ createdAt: f.created_at,+ size: (f.metadata as { size?: number } | null)?.size ?? 0,+ url: signed.data?.signedUrl ?? null+ };+ })+ );++ return {+ companyId,+ files,+ restoreRuns: restoreRuns.data ?? []+ };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, companyGroupId, userId, email } =+ await requirePermissions(request, {+ update: "settings"+ });+ await requireOwner(request, client, companyGroupId, userId, email);++ const formData = await request.formData();+ const intent = formData.get("intent");++ switch (intent) {+ case "export": {+ const validation = await validator(exportValidator).validate(formData);+ if (validation.error) return validationError(validation.error);++ const { label, includeStorage } = validation.data;+ const result = await exportCompanyBackup(client, {+ companyId,+ userId,+ label: label || undefined,+ includeStorage+ });+ if (result.error)+ return {+ success: false,+ message: await getEdgeFunctionErrorMessage(+ result.error,+ "Failed to start backup"+ )+ };+ return {+ success: true,+ message: "Backup started",+ started: "export" as const+ };+ }++ // Restore replaces the current company's data with a backup, in place. The+ // job snapshots first so it can be reverted. We return the run id so the+ // client can open the progress modal and poll for completion.+ case "restore": {+ const validation = await validator(restoreValidator).validate(formData);+ if (validation.error) return validationError(validation.error);++ const filePath = validation.data.source.replace(/^backup:/, "");+ if (!filePath.startsWith("exports/")) {+ return { success: false, message: "Choose one of your backups" };+ }++ // One restore at a time. A second restore while one is still pending review+ // would snapshot the already-restored state and tangle the revert chain.+ const inFlight = await getCompanyRestoreRuns(client, companyId);+ if (inFlight.data?.some((r) => r.status !== "failed")) {+ return {+ success: false,+ message: "Finish your current restore — keep or revert it — first."+ };+ }++ try {+ const restoreRunId = await startCompanyRestore({+ companyId,+ userId,+ filePath,+ includeStorage: validation.data.includeStorage,+ label: filePath.split("/").pop()+ });+ return { success: true, message: "Restore started", restoreRunId };+ } catch (err) {+ return {+ success: false,+ message:+ err instanceof Error ? err.message : "Failed to start restore"+ };+ }+ }++ // keep / dismiss / revert / delete are fetcher buttons (modal + review card+ // use them) and return JSON so the UI can react in place.+ case "keep": {+ const restoreRunId = String(formData.get("restoreRunId") ?? "");+ if (!restoreRunId)+ return { success: false, message: "Missing restore run" };+ await finalizeCompanyRestore({ companyId, restoreRunId });+ return { success: true, message: "Restore kept" };+ }++ // Same cleanup as keep (drop the snapshot + marker), but for a FAILED run —+ // nothing was changed, so it's a dismissal, not a "keep".+ case "dismiss": {+ const restoreRunId = String(formData.get("restoreRunId") ?? "");+ if (!restoreRunId)+ return { success: false, message: "Missing restore run" };+ await finalizeCompanyRestore({ companyId, restoreRunId });+ return { success: true, message: "Dismissed" };+ }++ case "revert": {+ const restoreRunId = String(formData.get("restoreRunId") ?? "");+ if (!restoreRunId)+ return { success: false, message: "Missing restore run" };+ await revertCompanyRestore({ companyId, restoreRunId });+ return {+ success: true,+ message: "Reverting — your previous data is being restored"+ };+ }++ case "delete": {+ const filePath = String(formData.get("filePath") ?? "");+ if (!filePath.startsWith("exports/"))+ return data({}, await flash(request, error(null, "Invalid file path")));++ const result = await deleteCompanyBackupExport(+ client,+ companyId,+ filePath+ );+ if (result.error)+ return data(+ {},+ await flash(request, error(result.error, "Failed to delete backup"))+ );+ return data({}, await flash(request, success("Backup deleted")));+ }++ default:+ return data({}, await flash(request, error(null, "Unknown action")));+ }+}++export default function BackupsRoute() {+ const { companyId, files, restoreRuns } = useLoaderData<typeof loader>();+ const fetcher = useFetcher<{+ success?: boolean;+ message?: string;+ restoreRunId?: string;+ started?: "export";+ }>();+ const [active, setActive] = useState<{+ runId?: string;+ mode: "export" | "restore" | "revert";+ } | null>(null);+ const startRevert = (runId: string) => {+ fetcher.submit(+ { intent: "revert", restoreRunId: runId },+ { method: "post" }+ );+ setActive({ runId, mode: "revert" });+ };++ 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.+ if (result.success && result.started === "export") {+ setActive({ mode: "export" });+ return;+ }+ if (result.success && result.restoreRunId) {+ setActive({ runId: result.restoreRunId, mode: "restore" });+ return;+ }+ if (result.success) toast.success(result.message);+ else toast.error(result.message);+ }, [fetcher.data]);++ return (+ <ScrollArea className="w-full h-[calc(100dvh-49px)]">+ <div className="py-12 px-4 max-w-[72rem] mx-auto flex flex-col gap-4">+ <Heading size="h3">Backups</Heading>++ {/* Create + Restore — equal-height cards, footers aligned. */}+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 items-stretch">+ <Card className="flex flex-col">+ <ValidatedForm+ method="post"+ validator={exportValidator}+ defaultValues={{ label: "", includeStorage: "none" }}+ fetcher={fetcher}+ className="flex flex-1 flex-col"+ >+ <CardHeader>+ <CardTitle className="flex items-center gap-1.5">+ Create a backup+ <BackupContentsInfo />+ </CardTitle>+ <CardDescription>+ Snapshot all of this company's non-sensitive data into a+ downloadable file.+ </CardDescription>+ </CardHeader>+ <CardContent className="flex-1">+ <Hidden name="intent" value="export" />+ <div className="flex flex-col gap-6">+ <Input name="label" label="Label" />+ <div className="flex flex-col gap-1.5">+ <span className="text-sm">Include</span>+ <IncludeStorageChoice />+ </div>+ </div>+ </CardContent>+ <CardFooter>+ <Submit>Create backup</Submit>+ </CardFooter>+ </ValidatedForm>+ </Card>++ <Card className="flex flex-col">+ <ValidatedForm+ method="post"+ validator={restoreValidator}+ defaultValues={{ source: "", includeStorage: "all" }}+ fetcher={fetcher}+ className="flex flex-1 flex-col"+ >+ <CardHeader>+ <CardTitle>Restore from a backup</CardTitle>+ <CardDescription>+ Replace this company's data with any backup — snapshotted+ first, so you can revert.+ </CardDescription>+ </CardHeader>+ <CardContent className="flex-1">+ <Hidden name="intent" value="restore" />+ <div className="flex flex-col gap-6">+ <div className="flex flex-col gap-1.5">+ <span className="text-sm">Source</span>+ <BackupSourcePicker backups={files} companyId={companyId} />+ </div>+ <div className="flex flex-col gap-1.5">+ <span className="text-sm">Include</span>+ <RestoreIncludeChoice />+ </div>+ </div>+ </CardContent>+ <CardFooter>+ <RestoreSubmit />+ </CardFooter>+ </ValidatedForm>+ </Card>+ </div>++ {restoreRuns.length > 0 && (+ <Card>+ <CardHeader>+ <CardTitle>Restored — review</CardTitle>+ <CardDescription>+ A restore replaced this company's data. Keep it, or revert to+ put back exactly what was here before.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <VStack spacing={2}>+ {restoreRuns.map((run) => (+ <RestoreReviewRow+ key={run.restoreRunId}+ run={run}+ onKeep={() =>+ fetcher.submit(+ { intent: "keep", restoreRunId: run.restoreRunId },+ { method: "post" }+ )+ }+ onRevert={() => startRevert(run.restoreRunId)}+ onDismiss={() =>+ fetcher.submit(+ { intent: "dismiss", restoreRunId: run.restoreRunId },+ { method: "post" }+ )+ }+ />+ ))}+ </VStack>+ </CardContent>+ </Card>+ )}++ {active && (+ <JobProgressModal+ mode={active.mode}+ runId={active.runId}+ onClose={() => setActive(null)}+ />+ )}++ <Card>+ <CardHeader>+ <CardTitle>Backups</CardTitle>+ <CardDescription>+ Past backups stored in this company's bucket.+ </CardDescription>+ </CardHeader>+ <CardContent>+ {files.length === 0 ? (+ <p className="text-sm text-muted-foreground">No backups yet.</p>+ ) : (+ <VStack spacing={2}>+ {files.map((file) => (+ <HStack+ key={file.path}+ className="w-full justify-between border rounded-lg p-3"+ >+ <VStack spacing={0}>+ <span className="text-sm font-medium">+ {formatBackupName(file.name)}+ </span>+ <span className="text-xs text-muted-foreground">+ {formatBackupDate(file.createdAt)}+ {file.size ? (+ <>+ {" · "}+ {convertKbToString(Math.round(file.size / 1024))}+ </>+ ) : null}+ </span>+ </VStack>+ <HStack spacing={2}>+ {file.url && (+ <Button asChild variant="secondary">+ <a href={file.url} download>+ Download+ </a>+ </Button>+ )}+ <Form method="post">+ <input type="hidden" name="intent" value="delete" />+ <input+ type="hidden"+ name="filePath"+ value={file.path}+ />+ <Button type="submit" variant="destructive">+ Delete+ </Button>+ </Form>+ </HStack>+ </HStack>+ ))}+ </VStack>+ )}+ </CardContent>+ </Card>+ </div>+ </ScrollArea>+ );+}diff --git a/apps/erp/app/routes/x+/settings+/companies.new.tsx b/apps/erp/app/routes/x+/settings+/companies.new.tsxindex ae49a174e6..ffdd38f58a 100644--- a/apps/erp/app/routes/x+/settings+/companies.new.tsx+++ b/apps/erp/app/routes/x+/settings+/companies.new.tsx@@ -68,7 +68,9 @@ export async function action({ request }: ActionFunctionArgs) {);}- const seed = await seedCompany(client, companyId, userId, parentCompanyId);+ const seed = await seedCompany(client, companyId, userId, {+ parentCompanyId+ });if (seed.error) {throw redirect(path.to.companies,diff --git a/apps/erp/app/services/onboarding-draft.server.ts b/apps/erp/app/services/onboarding-draft.server.tsnew file mode 100644index 0000000000..e44fefed83--- /dev/null+++ b/apps/erp/app/services/onboarding-draft.server.ts@@ -0,0 +1,66 @@+import { createCookieSessionStorage } from "react-router";++const ONBOARDING_DRAFT_KEY = "onboarding-draft";++const sessionStorage = createCookieSessionStorage({+ cookie: {+ name: ONBOARDING_DRAFT_KEY,+ path: "/",+ secure: false,+ httpOnly: true,+ sameSite: "lax",+ maxAge: 60 * 60 * 24 // 24 hours+ }+});++export type OnboardingDraft = {+ industry?: {+ industryId: string;+ customIndustryDescription?: string;+ };+ company?: {+ name?: string;+ addressLine1?: string;+ addressLine2?: string;+ city?: string;+ stateProvince?: string;+ postalCode?: string;+ countryCode?: string;+ baseCurrencyCode?: string;+ website?: string;+ };+};++export async function getOnboardingDraft(+ request: Request+): Promise<OnboardingDraft | null> {+ const session = await sessionStorage.getSession(+ request.headers.get("Cookie")+ );+ const draft = session.get(ONBOARDING_DRAFT_KEY) as+ | OnboardingDraft+ | undefined;+ return draft ?? null;+}++export async function setOnboardingDraft(+ request: Request,+ draft: Partial<OnboardingDraft>+): Promise<string> {+ const session = await sessionStorage.getSession(+ request.headers.get("Cookie")+ );+ const existingDraft =+ (session.get(ONBOARDING_DRAFT_KEY) as OnboardingDraft | undefined) ?? {};+ const updatedDraft = { ...existingDraft, ...draft };+ session.set(ONBOARDING_DRAFT_KEY, updatedDraft);+ return sessionStorage.commitSession(session);+}++export async function clearOnboardingDraft(request: Request): Promise<string> {+ const session = await sessionStorage.getSession(+ request.headers.get("Cookie")+ );+ session.set(ONBOARDING_DRAFT_KEY, undefined);+ return sessionStorage.commitSession(session);+}diff --git a/apps/erp/app/services/onboarding.server.ts b/apps/erp/app/services/onboarding.server.tsnew file mode 100644index 0000000000..a47ac3b201--- /dev/null+++ b/apps/erp/app/services/onboarding.server.ts@@ -0,0 +1,105 @@+import type { getCarbonServiceRole } from "@carbon/auth/client.server";+import { trigger } from "@carbon/jobs";+import { nanoid } from "nanoid";+import { seedCompany } from "~/modules/settings";++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.+ */+export async function provisionCompanyData(+ serviceRole: ServiceRole,+ {+ companyId,+ userId,+ backup,+ templateIndustryId+ }: {+ 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) {+ const seed = await seedCompany(serviceRole, companyId, userId);+ if (seed.error) {+ console.error(seed.error);+ throw new Error("Fatal: failed to seed company");+ }+ return;+ }++ const seed = await seedCompany(serviceRole, companyId, userId, {+ identityOnly: true+ });+ if (seed.error) {+ console.error(seed.error);+ 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");+ }++ // Kick off the import. The job runs asynchronously (the company's data+ // populates shortly after onboarding finishes), but the *enqueue* is awaited+ // and surfaced: a failed send (e.g. Inngest unreachable) would otherwise+ // leave the company with only the identity seed — an empty chart of accounts+ // — while onboarding reported success. Fail loudly instead, like the seed.+ try {+ await trigger("company-import", {+ companyId,+ userId,+ filePath,+ mode: "reseed",+ importRunId: nanoid(),+ autoFinalize: true,+ ...(templateIndustryId ? { templateIndustryId } : {})+ });+ } catch (err) {+ console.error(err);+ throw new Error("Fatal: failed to start company data import");+ }+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 075c73e9ae..1e034b14a6 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -439,6 +439,7 @@ export const path = {},onboarding: {company: `${onboarding}/company`,+ industry: `${onboarding}/industry`,location: `${onboarding}/location`,plan: `${onboarding}/plan`,root: `${onboarding}`,@@ -574,6 +575,7 @@ export const path = {company: `${x}/settings/company`,companySwitch: (companyId: string) =>generatePath(`${x}/settings/company/switch/${companyId}`),+ backups: `${x}/settings/backups`,companies: `${x}/settings/companies`,completeTrainingAssignment: (id: string) =>generatePath(`${share}/training/${id}`),@@ -1865,6 +1867,7 @@ export const onboardingSequence = [path.to.onboarding.theme,path.to.onboarding.user,path.to.onboarding.company,+ path.to.onboarding.industry,path.to.onboarding.plan] as const;diff --git a/ci/package.json b/ci/package.jsonindex 0299448db8..71e077d29c 100644--- a/ci/package.json+++ b/ci/package.json@@ -13,6 +13,7 @@"ci:migrations": "tsx src/migrations.ts","ci:deploy": "tsx src/deploy.ts","ci:jobs": "tsx src/jobs.ts",+ "ci:upload-backup-templates": "tsx src/upload-backup-templates.ts","test": "echo \"no tests\""},"devDependencies": {diff --git a/ci/src/upload-backup-templates.ts b/ci/src/upload-backup-templates.tsnew file mode 100644index 0000000000..f46b0f23a0--- /dev/null+++ b/ci/src/upload-backup-templates.ts@@ -0,0 +1,235 @@+import { readdir, readFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { gunzipSync } from "node:zlib";+import { createClient } from "@supabase/supabase-js";+import * as dotenv from "dotenv";++import { client } from "./client";++dotenv.config();++const TEMPLATE_BUCKET = "company-templates";+const BACKUP_SUFFIX = ".carbon.json.gz";++// The bucket the app serves per-company assets (3D models, …) from, and the+// shared prefix within it where each template's assets live ONCE per workspace.+// A template import references these instead of copying files per company.+// NOTE: `_templates` must match `TEMPLATE_ASSET_PREFIX` in+// packages/jobs/src/inngest/functions/tasks/company-backup.ts — keep in sync.+const PRIVATE_BUCKET = "private";+const TEMPLATE_ASSET_PREFIX = "_templates";++// Idempotent by default: skip any object that already exists, so re-running is a+// cheap no-op. Pass `--force` to overwrite (republish an updated template).+const FORCE = process.argv.includes("--force");++type StorageApi = ReturnType<typeof createClient>["storage"];++/**+ * Upload one object, idempotently. Without `--force`, an object that already+ * exists is left untouched and reported as "skipped" (the storage API returns a+ * 409 "Duplicate" we treat as success). With `--force`, it is overwritten.+ */+async function publishObject(+ storage: StorageApi,+ bucket: string,+ path: string,+ bytes: Buffer,+ contentType?: string+): Promise<"uploaded" | "skipped" | { error: string }> {+ const { error } = await storage+ .from(bucket)+ .upload(path, bytes, { upsert: FORCE, contentType });+ if (!error) return "uploaded";++ const alreadyExists =+ (error as { statusCode?: string }).statusCode === "409" ||+ /already exists|duplicate/i.test(error.message);+ if (!FORCE && alreadyExists) return "skipped";++ return { error: error.message };+}++// Repo-committed onboarding demo templates. Authored manually (export a+// populated company from Settings → Backups, download the .gz, commit it here),+// versioned so we control when to break backwards compatibility via the+// backup's own manifest version.+const BACKUPS_DIR = join(+ dirname(fileURLToPath(import.meta.url)),+ "..",+ "..",+ "packages",+ "database",+ "supabase",+ "backups"+);++type Workspace = {+ id: number;+ database_url: string | null;+ service_role_key: string | null;+};++type TemplateAsset = { path: string; bytes: Buffer };+type Template = {+ fileName: string;+ industryId: string;+ bytes: Buffer;+ assets: TemplateAsset[];+};++async function loadTemplates(): Promise<Template[]> {+ let entries: string[];+ try {+ entries = await readdir(BACKUPS_DIR);+ } catch {+ return [];+ }+ const files = entries.filter((f) => f.endsWith(BACKUP_SUFFIX));+ return Promise.all(+ files.map(async (fileName) => {+ const bytes = await readFile(join(BACKUPS_DIR, fileName));+ const industryId = fileName.slice(0, -BACKUP_SUFFIX.length);+ return {+ fileName,+ industryId,+ bytes,+ assets: extractTemplateAssets(industryId, bytes)+ };+ })+ );+}++// A template gz embeds its storage assets keyed by the source company's path+// (`{sourceCompanyId}/models/{id}.stl`). Pull them out and rekey to the shared+// `_templates/{industryId}/…` location so a referenced import can point at them+// without copying. Mirrors `rewriteToTemplateAssetPath` in @carbon/jobs.+function extractTemplateAssets(+ industryId: string,+ gzBytes: Buffer+): TemplateAsset[] {+ let backup: {+ manifest?: { sourceCompanyId?: string };+ storage?: Record<string, string>;+ };+ try {+ backup = JSON.parse(gunzipSync(gzBytes).toString());+ } catch (err) {+ console.error(`🔴 ${industryId}: failed to read template gz`, err);+ return [];+ }++ const sourceCompanyId = backup.manifest?.sourceCompanyId;+ const storage = backup.storage;+ if (!sourceCompanyId || !storage) return [];++ const assets: TemplateAsset[] = [];+ for (const [path, base64] of Object.entries(storage)) {+ const rest = path.startsWith(`${sourceCompanyId}/`)+ ? path.slice(sourceCompanyId.length + 1)+ : path;+ assets.push({+ path: `${TEMPLATE_ASSET_PREFIX}/${industryId}/${rest}`,+ bytes: Buffer.from(base64, "base64")+ });+ }+ return assets;+}++// Manual publish step (NOT run on every deploy — see the "Publish backup+// templates" workflow). Templates change rarely and are large, so they're+// published deliberately. Multi-tenant: each workspace is its own Supabase+// project (its own url + service-role key in the workspaces table), so we upload+// the repo templates into every workspace's company-templates bucket and fan+// their assets into the shared `_templates/` prefix. Onboarding then provisions+// a new company from the matching <industryId> template. Idempotent: existing+// objects are skipped unless `--force` is passed.+async function main(): Promise<void> {+ const templates = await loadTemplates();+ if (templates.length === 0) {+ console.log("⏭️ No backup templates committed — nothing to upload");+ return;+ }+ console.log(+ `✅ Publishing ${templates.length} backup template(s)${+ FORCE ? " (force overwrite)" : " (skip existing)"+ }: ${templates.map((t) => t.fileName).join(", ")}`+ );++ const { data: workspaces, error } = await client+ .from("workspaces")+ .select("id, database_url, service_role_key");++ if (error) {+ console.error("🔴 Failed to fetch workspaces", error);+ process.exit(1);+ }++ let hasErrors = false;++ for (const ws of (workspaces ?? []) as Workspace[]) {+ if (!ws.database_url || !ws.service_role_key) {+ console.log(`⏭️ Skipping workspace ${ws.id} — missing url/service key`);+ continue;+ }++ const storage = createClient(ws.database_url, ws.service_role_key).storage;+ for (const { fileName, bytes, assets } of templates) {+ const gz = await publishObject(+ storage,+ TEMPLATE_BUCKET,+ `templates/${fileName}`,+ bytes,+ "application/gzip"+ );+ if (typeof gz === "object") {+ console.error(+ `🔴 Workspace ${ws.id}: failed to upload templates/${fileName}`,+ gz.error+ );+ hasErrors = true;+ }++ // Fan the template's storage assets into the shared `_templates/` prefix+ // so onboarding-from-template can reference them instead of copying files+ // into every company's bucket.+ let uploaded = gz === "uploaded" ? 1 : 0;+ let skipped = gz === "skipped" ? 1 : 0;+ for (const asset of assets) {+ const result = await publishObject(+ storage,+ PRIVATE_BUCKET,+ asset.path,+ asset.bytes+ );+ if (typeof result === "object") {+ console.error(+ `🔴 Workspace ${ws.id}: failed to upload ${asset.path}`,+ result.error+ );+ hasErrors = true;+ } else if (result === "uploaded") {+ uploaded++;+ } else {+ skipped++;+ }+ }+ console.log(+ `✅ Workspace ${ws.id}: ${fileName} — ${uploaded} uploaded, ${skipped} skipped`+ );+ }+ }++ if (hasErrors) {+ console.error("🔴 Backup template upload completed with errors");+ process.exit(1);+ }++ console.log("✅ Uploaded backup templates to all workspaces");+}++main().catch((err) => {+ console.error("🔴 upload-backup-templates failed", err);+ process.exit(1);+});diff --git a/docs/content/docs/platform/backups.mdx b/docs/content/docs/platform/backups.mdxnew file mode 100644index 0000000000..46c34bf028--- /dev/null+++ b/docs/content/docs/platform/backups.mdx@@ -0,0 +1,58 @@+---+title: Backups+description: Snapshot a company's data and files, restore it in place with one-click revert, or stand up a new company from a demo template.+---++A backup is a single snapshot of one company: its records, and optionally the files it has uploaded. You make one from **Settings → Backups**, and you do two things with it. You **restore** it over the same company to undo a bad change, or you use it as the starting data for a brand-new company at sign-up. Same file, two jobs.++Backups belong to the company owner. Opening **Settings → Backups** as anyone else shows "Only the company owner can access backups".++<Callout type="warning" title="A backup is not disaster recovery">+This is a per-company snapshot for cloning environments and undoing a bad change, not a full database dump, and there is no scheduling or point-in-time recovery. Treat it as a working tool, not your only copy.+</Callout>++## What a backup contains++A backup captures the company's business data across the whole app: sales, purchasing, items, production, accounting, quality and people. The **i** button next to "Create a backup" opens a "What's in a backup" summary with a live count per area.++<Callout type="warning" title="Secrets never travel">+API keys, integration connections and webhooks are deliberately left out of every backup, so a restored or cloned company never carries another company's credentials. Re-connect your integrations after a restore.+</Callout>++When you export, **Include** offers two options:++<FieldTable>+ <Field name="Data only">Customers, items, orders and every record. Smaller and faster.</Field>+ <Field name="Data + files">Also bundles uploaded files, such as 3D models, documents and images.</Field>+</FieldTable>++## Create a backup++On **Settings → Backups**, the "Create a backup" card snapshots the company's data. Give it an optional label, choose **Data only** or **Data + files**, and select **Create backup**. It runs in the background and the finished file appears in the list below, where you can download or delete it.++<Screenshot label="Settings → Backups, the Create a backup card with the Data only / Data + files choice and the i contents button" caption="Export snapshots the company's data; the contents popover shows a live count per area." ratio="wide" />++## Restore in place++Restoring replaces the current company's data with a backup. In the "Restore from a backup" card, pick a **Source** backup, choose whether to also restore its files, and select **Restore**.++It is safe to try. Before anything is replaced, Carbon automatically snapshots the company's current state, so a restore is always reversible. When it finishes, the "Restored — review" card asks you to decide:++- **Keep** accepts the restored data.+- **Revert** rolls the company back to the snapshot taken just before the restore.++<Callout type="note" title="One restore at a time">+A restore stays open for review until you keep or revert it. Starting another beforehand is blocked, so the revert always returns you to the state from just before the last restore.+</Callout>++## Start a company from a template++The same backups power onboarding. When you create a new company, the industry step asks how to seed it:++<FieldTable>+ <Field name="Use a demo template">Adds sample customers, suppliers, parts and quotes for the chosen industry, so you can explore Carbon with realistic data.</Field>+ <Field name="Restore from a backup">Sets the new company up from a Carbon backup of another company.</Field>+ <Field name="I don't need data">Starts with a clean, empty environment.</Field>+</FieldTable>++A demo template is just a ready-made backup, one per industry, imported into the fresh company.diff --git a/docs/content/docs/platform/meta.json b/docs/content/docs/platform/meta.jsonindex aad6f8013c..a56c8edcff 100644--- a/docs/content/docs/platform/meta.json+++ b/docs/content/docs/platform/meta.json@@ -1,5 +1,5 @@{"title": "Platform","defaultOpen": true,- "pages": ["architecture", "self-hosting", "licensing"]+ "pages": ["architecture", "backups", "self-hosting", "licensing"]}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex a9585354b2..b01ff7530c 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -2426,10 +2426,13 @@ export type Database = {companyGroupId: string | nullcountryCode: string | nullcreatedAt: string+ customIndustryDescription: string | nullemail: string | nulleori: string | nullfax: string | null+ featureRequests: string | nullid: string+ industryId: string | nullisEliminationEntity: booleanlogoDark: string | nulllogoDarkIcon: string | null@@ -2440,6 +2443,7 @@ export type Database = {parentCompanyId: string | nullphone: string | nullpostalCode: string | null+ selectedModules: string[] | nullslackChannel: string | nullstateProvince: string | nullsuggestionNotificationGroup: string[]@@ -2458,10 +2462,13 @@ export type Database = {companyGroupId?: string | nullcountryCode?: string | nullcreatedAt?: string+ customIndustryDescription?: string | nullemail?: string | nulleori?: string | nullfax?: string | null+ featureRequests?: string | nullid?: string+ industryId?: string | nullisEliminationEntity?: booleanlogoDark?: string | nulllogoDarkIcon?: string | null@@ -2472,6 +2479,7 @@ export type Database = {parentCompanyId?: string | nullphone?: string | nullpostalCode?: string | null+ selectedModules?: string[] | nullslackChannel?: string | nullstateProvince?: string | nullsuggestionNotificationGroup?: string[]@@ -2490,10 +2498,13 @@ export type Database = {companyGroupId?: string | nullcountryCode?: string | nullcreatedAt?: string+ customIndustryDescription?: string | nullemail?: string | nulleori?: string | nullfax?: string | null+ featureRequests?: string | nullid?: string+ industryId?: string | nullisEliminationEntity?: booleanlogoDark?: string | nulllogoDarkIcon?: string | null@@ -2504,6 +2515,7 @@ export type Database = {parentCompanyId?: string | nullphone?: string | nullpostalCode?: string | null+ selectedModules?: string[] | nullslackChannel?: string | nullstateProvince?: string | nullsuggestionNotificationGroup?: string[]@@ -2562,6 +2574,13 @@ export type Database = {referencedRelation: "companyGroup"referencedColumns: ["id"]},+ {+ foreignKeyName: "company_industryId_fkey"+ columns: ["industryId"]+ isOneToOne: false+ referencedRelation: "industry"+ referencedColumns: ["id"]+ },{foreignKeyName: "company_parentCompanyId_fkey"columns: ["parentCompanyId"]@@ -12324,6 +12343,39 @@ export type Database = {},]}+ industry: {+ Row: {+ active: boolean+ createdAt: string+ description: string | null+ iconName: string | null+ id: string+ name: string+ sortOrder: number+ updatedAt: string | null+ }+ Insert: {+ active?: boolean+ createdAt?: string+ description?: string | null+ iconName?: string | null+ id: string+ name: string+ sortOrder?: number+ updatedAt?: string | null+ }+ Update: {+ active?: boolean+ createdAt?: string+ description?: string | null+ iconName?: string | null+ id?: string+ name?: string+ sortOrder?: number+ updatedAt?: string | null+ }+ Relationships: []+ }inspectionDocument: {Row: {companyId: string@@ -39227,49 +39279,7 @@ export type Database = {},]}- searchIndex_d8lth5d460h02afg19og: {- Row: {- createdAt: string- description: string | null- entityId: string- entityType: string- id: number- link: string- metadata: Json | null- searchVector: unknown- tags: string[] | null- title: string- updatedAt: string | null- }- Insert: {- createdAt?: string- description?: string | null- entityId: string- entityType: string- id?: number- link: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title: string- updatedAt?: string | null- }- Update: {- createdAt?: string- description?: string | null- entityId?: string- entityType?: string- id?: number- link?: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title?: string- updatedAt?: string | null- }- Relationships: []- }- searchIndex_M3T8GH5QxJoQYRZ3nQzQMQ: {+ searchIndex_d8u0tkkrs0h02bo0k2m0: {Row: {createdAt: stringdescription: string | null@@ -60495,14 +60505,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/backups/README.md b/packages/database/supabase/backups/README.mdnew file mode 100644index 0000000000..74471da87e--- /dev/null+++ b/packages/database/supabase/backups/README.md@@ -0,0 +1,39 @@+# Onboarding demo templates++Repo-committed company backups used as onboarding demo data. One file per+industry, named `<industryId>.carbon.json.gz` (the `industryId` must match a row+in the `industry` table — see the onboarding migration).++These are published into every workspace by `ci/src/upload-backup-templates.ts`+as a **manual** step — the `Publish backup templates` workflow+(`.github/workflows/publish-templates.yml`, `workflow_dispatch`) or+`pnpm --filter ci ci:upload-backup-templates` locally. It is **not** run on every+deploy (templates change rarely and are large). It uploads the `.gz` to each+workspace's private `company-templates` bucket and fans the template's storage+assets (3D models, …) into the shared `_templates/<industryId>/` prefix of the+`private` bucket. The publish is **idempotent** — anything that already exists is+skipped; pass `--force` (workflow input `force: true`) to overwrite an updated+template.++Onboarding's "template" data choice downloads the matching `.gz` and+reseed-imports it on top of an identity-only seed+(`apps/erp/app/services/onboarding.server.ts`). The import **references** the+shared `_templates/<industryId>/` assets instead of copying files into the new+company's bucket — so onboard/revert cycles do no per-company file I/O. If no file+exists for the chosen industry, onboarding falls back to a clean seed.++## Authoring / refreshing a template++1. Populate a company with the data you want as the demo set.+2. Settings → Backups → Export (choose storage inclusion), then download the+ resulting `.gz`.+3. Commit it here as `<industryId>.carbon.json.gz`, overwriting the old one.++## Versioning / backwards compatibility++Each backup carries a manifest `version` (`BACKUP_VERSION` in+`packages/jobs/src/inngest/functions/tasks/company-backup.ts`). The importer+rejects a file whose version no longer matches, and a structural guard+(`assertBackupImportable`) independently rejects a file missing a now-required+column. Bump `BACKUP_VERSION` only for a deliberate hard break, then re-export+every template here.diff --git a/packages/database/supabase/backups/robotics_oem.carbon.json.gz b/packages/database/supabase/backups/robotics_oem.carbon.json.gznew file mode 100644index 0000000000..71fecf422fBinary files /dev/null and b/packages/database/supabase/backups/robotics_oem.carbon.json.gz differdiff --git a/packages/database/supabase/functions/export-company/index.ts b/packages/database/supabase/functions/export-company/index.tsnew file mode 100644index 0000000000..95d9115af1--- /dev/null+++ b/packages/database/supabase/functions/export-company/index.ts@@ -0,0 +1,47 @@+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import {+ errorResponse,+ jsonResponse,+ requireCompanyOwner+} from "../lib/company-backup.ts";+import { corsHeaders } from "../lib/headers.ts";+import { sendInngestEvent } from "../lib/inngest.ts";+import { requirePermissions } from "../lib/supabase.ts";++/**+ * Thin auth boundary for company backup exports. Validates the caller is+ * the company owner, then hands the heavy lifting to the+ * `carbon/company-export` inngest job. The backup lands in the company's+ * bucket under `exports/`.+ */+serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ try {+ const { companyId, userId, label, includeStorage } = await req.json();++ if (!companyId) throw new Error("Payload is missing companyId");+ if (!userId) throw new Error("Payload is missing userId");+ if (includeStorage && !["none", "all"].includes(includeStorage)) {+ throw new Error("includeStorage must be 'none' or 'all'");+ }++ const client = await requirePermissions(req, companyId, userId, {+ update: "settings"+ });+ await requireCompanyOwner(client, companyId, userId);++ await sendInngestEvent("carbon/company-export", {+ companyId,+ userId,+ label: typeof label === "string" ? label.slice(0, 80) : undefined,+ includeStorage: includeStorage ?? "none"+ });++ return jsonResponse({ success: true }, 202, corsHeaders);+ } catch (err) {+ return errorResponse(err, 400, corsHeaders);+ }+});diff --git a/packages/database/supabase/functions/lib/company-backup.ts b/packages/database/supabase/functions/lib/company-backup.tsnew file mode 100644index 0000000000..2c6a49467b--- /dev/null+++ b/packages/database/supabase/functions/lib/company-backup.ts@@ -0,0 +1,72 @@+import type { createClient } from "@supabase/supabase-js";+import type { Database } from "./types.ts";++export const BACKUP_INTEGRATION = "company-backup";+export const EXPORTS_PREFIX = "exports";++type Client = ReturnType<typeof createClient<Database>>;++/** Extract the authenticated user id (JWT `sub`) from the request. */+export function getUserIdFromRequest(req: Request): string | null {+ const token =+ req.headers.get("Authorization")?.replace(/^Bearer\s+/i, "").trim() ?? "";+ const parts = token.split(".");+ if (parts.length !== 3) return null;+ try {+ const payload = JSON.parse(atob(parts[1]!)) as { sub?: string };+ return payload.sub ?? null;+ } catch {+ return null;+ }+}++/**+ * Company data export/import is owner-only — the same gate the settings UI+ * applies via `requiresOwnership`.+ */+export async function requireCompanyOwner(+ client: Client,+ companyId: string,+ userId: string+): Promise<void> {+ const company = await client+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();+ if (company.error) throw new Error(company.error.message);+ if (!company.data?.companyGroupId) {+ throw new Error("Company has no company group");+ }++ const group = await client+ .from("companyGroup")+ .select("ownerId")+ .eq("id", company.data.companyGroupId)+ .single();+ if (group.error) throw new Error(group.error.message);+ if (group.data?.ownerId !== userId) {+ throw new Error("Only the company owner can manage company data");+ }+}++export function jsonResponse(+ body: Record<string, unknown>,+ status: number,+ corsHeaders: Record<string, string>+): Response {+ return new Response(JSON.stringify(body), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status+ });+}++export function errorResponse(+ err: unknown,+ status: number,+ corsHeaders: Record<string, string>+): Response {+ const message = err instanceof Error ? err.message : String(err);+ console.error(message);+ return jsonResponse({ success: false, message }, status, corsHeaders);+}diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex a9585354b2..b01ff7530c 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -2426,10 +2426,13 @@ export type Database = {companyGroupId: string | nullcountryCode: string | nullcreatedAt: string+ customIndustryDescription: string | nullemail: string | nulleori: string | nullfax: string | null+ featureRequests: string | nullid: string+ industryId: string | nullisEliminationEntity: booleanlogoDark: string | nulllogoDarkIcon: string | null@@ -2440,6 +2443,7 @@ export type Database = {parentCompanyId: string | nullphone: string | nullpostalCode: string | null+ selectedModules: string[] | nullslackChannel: string | nullstateProvince: string | nullsuggestionNotificationGroup: string[]@@ -2458,10 +2462,13 @@ export type Database = {companyGroupId?: string | nullcountryCode?: string | nullcreatedAt?: string+ customIndustryDescription?: string | nullemail?: string | nulleori?: string | nullfax?: string | null+ featureRequests?: string | nullid?: string+ industryId?: string | nullisEliminationEntity?: booleanlogoDark?: string | nulllogoDarkIcon?: string | null@@ -2472,6 +2479,7 @@ export type Database = {parentCompanyId?: string | nullphone?: string | nullpostalCode?: string | null+ selectedModules?: string[] | nullslackChannel?: string | nullstateProvince?: string | nullsuggestionNotificationGroup?: string[]@@ -2490,10 +2498,13 @@ export type Database = {companyGroupId?: string | nullcountryCode?: string | nullcreatedAt?: string+ customIndustryDescription?: string | nullemail?: string | nulleori?: string | nullfax?: string | null+ featureRequests?: string | nullid?: string+ industryId?: string | nullisEliminationEntity?: booleanlogoDark?: string | nulllogoDarkIcon?: string | null@@ -2504,6 +2515,7 @@ export type Database = {parentCompanyId?: string | nullphone?: string | nullpostalCode?: string | null+ selectedModules?: string[] | nullslackChannel?: string | nullstateProvince?: string | nullsuggestionNotificationGroup?: string[]@@ -2562,6 +2574,13 @@ export type Database = {referencedRelation: "companyGroup"referencedColumns: ["id"]},+ {+ foreignKeyName: "company_industryId_fkey"+ columns: ["industryId"]+ isOneToOne: false+ referencedRelation: "industry"+ referencedColumns: ["id"]+ },{foreignKeyName: "company_parentCompanyId_fkey"columns: ["parentCompanyId"]@@ -12324,6 +12343,39 @@ export type Database = {},]}+ industry: {+ Row: {+ active: boolean+ createdAt: string+ description: string | null+ iconName: string | null+ id: string+ name: string+ sortOrder: number+ updatedAt: string | null+ }+ Insert: {+ active?: boolean+ createdAt?: string+ description?: string | null+ iconName?: string | null+ id: string+ name: string+ sortOrder?: number+ updatedAt?: string | null+ }+ Update: {+ active?: boolean+ createdAt?: string+ description?: string | null+ iconName?: string | null+ id?: string+ name?: string+ sortOrder?: number+ updatedAt?: string | null+ }+ Relationships: []+ }inspectionDocument: {Row: {companyId: string@@ -39227,49 +39279,7 @@ export type Database = {},]}- searchIndex_d8lth5d460h02afg19og: {- Row: {- createdAt: string- description: string | null- entityId: string- entityType: string- id: number- link: string- metadata: Json | null- searchVector: unknown- tags: string[] | null- title: string- updatedAt: string | null- }- Insert: {- createdAt?: string- description?: string | null- entityId: string- entityType: string- id?: number- link: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title: string- updatedAt?: string | null- }- Update: {- createdAt?: string- description?: string | null- entityId?: string- entityType?: string- id?: number- link?: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title?: string- updatedAt?: string | null- }- Relationships: []- }- searchIndex_M3T8GH5QxJoQYRZ3nQzQMQ: {+ searchIndex_d8u0tkkrs0h02bo0k2m0: {Row: {createdAt: stringdescription: string | null@@ -60495,14 +60505,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.tsindex c8d680c90f..3007b9a70c 100644--- a/packages/database/supabase/functions/seed-company/index.ts+++ b/packages/database/supabase/functions/seed-company/index.ts@@ -31,13 +31,15 @@ serve(async (req: Request) => {if (req.method === "OPTIONS") {return new Response("ok", { headers: corsHeaders });}- const { companyId: id, userId, parentCompanyId } = await req.json();+ const { companyId: id, userId, parentCompanyId, identityOnly } =+ await req.json();console.log({function: "seed-company",id,userId,parentCompanyId,+ identityOnly: identityOnly === true,});try {@@ -59,6 +61,28 @@ serve(async (req: Request) => {if (company.error) throw new Error(company.error.message);if (!company.data) throw new Error("Company not found");+ // Idempotency guard. The whole seed runs in a single transaction, so a+ // committed run has inserted `userToCompany(userId, companyId)`. The+ // service-role client retries on timeout / transient 5xx (fetchWithRetry),+ // so a seed that committed but whose HTTP response was lost gets re-invoked+ // with the same payload — re-running would throw 23505 on the identity+ // inserts. If the link already exists, the prior run finished: no-op.+ const existingLink = await client+ .from("userToCompany")+ .select("userId", { count: "exact", head: true })+ .eq("userId", userId)+ .eq("companyId", companyId);++ if ((existingLink.count ?? 0) > 0) {+ return new Response(+ JSON.stringify({ success: true, alreadySeeded: true }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ }+ );+ }+// Determine if this is a new root company or joining an existing grouplet companyGroupId = company.data.companyGroupId;const isNewGroup = !companyGroupId && !parentCompanyId;@@ -125,7 +149,10 @@ serve(async (req: Request) => {.values([{ userId, companyId, role: "employee" }]).execute();- // high-order groups+ // high-order groups — identity infrastructure: the employeeType insert+ // below fires a trigger that creates a membership row referencing these,+ // so they must exist even in identity-only mode. (The onboarding import+ // skips `group` so the template doesn't duplicate them.)await trx.insertInto("group").values(@@ -200,6 +227,11 @@ serve(async (req: Request) => {]).execute();+ // Reference + accounting data (customer statuses, UoMs, sequences,+ // chart of accounts, …). Skipped in identity-only mode — a company+ // backup carries all of this, so onboarding-from-a-backup seeds only+ // the identity layer above and lets the import provide the rest.+ if (!identityOnly) {// customer statusawait trx.insertInto("customerStatus")@@ -357,6 +389,7 @@ serve(async (req: Request) => {}))).execute();+ } // end if (!identityOnly)const user = await client.from("userPermission")diff --git a/packages/database/supabase/migrations/20260617100002_onboarding-and-backups.sql b/packages/database/supabase/migrations/20260617100002_onboarding-and-backups.sqlnew file mode 100644index 0000000000..f2941045c2--- /dev/null+++ b/packages/database/supabase/migrations/20260617100002_onboarding-and-backups.sql@@ -0,0 +1,62 @@+-- Onboarding industry picker + the backup-template bucket.+-- 1. The industry list + the industry / data-choice fields on the company shell.+-- 2. The shared bucket holding the backup templates onboarding provisions from.++-- ─── 1. Industry catalog + onboarding fields on company ─────────────────────+-- Industries are data, not an enum, so the picker list can be curated+-- (added / renamed) without a migration. Companies FK to it by id; a NULL+-- industryId means "custom" (free-text in customIndustryDescription). The+-- onboarding demo template for an industry is a repo-committed backup file+-- (packages/database/supabase/backups/<industryId>.carbon.json.gz), published to+-- the company-templates bucket by a manual step (ci/src/upload-backup-templates.ts)+-- — it is not tracked on this table.++CREATE TABLE "industry" (+ "id" TEXT PRIMARY KEY,+ "name" TEXT NOT NULL,+ "description" TEXT,+ "iconName" TEXT,+ "sortOrder" INTEGER NOT NULL DEFAULT 0,+ "active" BOOLEAN NOT NULL DEFAULT TRUE,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedAt" TIMESTAMP WITH TIME ZONE+);++INSERT INTO "industry" ("id", "name", "description", "iconName", "sortOrder")+VALUES+ ('robotics_oem', 'Robotics OEM',+ 'Original Equipment Manufacturer building robots and automation systems',+ 'bot', 1),+ ('precision_manufacturing', 'Precision Manufacturing',+ 'Contract manufacturer — CNC machining and sheet-metal fabrication',+ 'cog', 2),+ ('automotive_precision', 'Motor Assembly',+ 'Manufacturer producing precision motor assemblies and components',+ 'wrench', 3);++ALTER TABLE "industry" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "Authenticated users can view industries"+ ON "industry" FOR SELECT+ USING (auth.role() = 'authenticated');++ALTER TABLE "company" DROP CONSTRAINT IF EXISTS "company_industryId_fkey";+ALTER TABLE "company" DROP COLUMN IF EXISTS "industryId";++ALTER TABLE "company"+ ADD COLUMN "industryId" TEXT REFERENCES "industry"("id") ON DELETE SET NULL,+ ADD COLUMN IF NOT EXISTS "customIndustryDescription" TEXT,+ ADD COLUMN IF NOT EXISTS "selectedModules" TEXT[],+ ADD COLUMN IF NOT EXISTS "featureRequests" TEXT,+ ADD COLUMN IF NOT EXISTS "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW();++CREATE INDEX IF NOT EXISTS "company_industryId_idx" ON "company"("industryId");++-- ─── 2. Backup-template bucket ──────────────────────────────────────────────+-- Shared, env-agnostic, private bucket holding the onboarding demo templates+-- (one repo-committed backup per industry, uploaded at deploy). A per-company+-- bucket can't serve these (onboarding runs outside the target company, and+-- tenants can't read each other's buckets). Access is service-role only: the+-- manual publish script writes here, the onboarding consume step reads here.+INSERT INTO storage.buckets (id, name, public)+VALUES ('company-templates', 'company-templates', FALSE);diff --git a/packages/database/supabase/migrations/20260624153000_api-key-rate-limit-rls.sql b/packages/database/supabase/migrations/20260624153000_api-key-rate-limit-rls.sqlnew file mode 100644index 0000000000..1ebdf49f41--- /dev/null+++ b/packages/database/supabase/migrations/20260624153000_api-key-rate-limit-rls.sql@@ -0,0 +1,25 @@+-- apiKeyRateLimit shipped without RLS but is exposed through PostgREST, so any+-- authenticated user could read every company's rate-limit counters or POST to+-- tamper with them. It is an internal counter table written only by+-- check_api_key_rate_limit() (SECURITY DEFINER, bypasses RLS), so enabling RLS+-- does not affect rate limiting. It has no companyId column, so reach the owning+-- company through the parent apiKey.++ALTER TABLE "public"."apiKeyRateLimit" ENABLE ROW LEVEL SECURITY;++-- Read: employees who can view API keys, scoped to the parent key's company.+CREATE POLICY "SELECT" ON "public"."apiKeyRateLimit"+FOR SELECT USING (+ EXISTS (+ SELECT 1 FROM "apiKey" k+ WHERE k."id" = "apiKeyRateLimit"."apiKeyId"+ AND k."companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_view'))::text[]+ )+ )+);++-- No INSERT/UPDATE/DELETE policies: counters are written exclusively by the+-- SECURITY DEFINER function check_api_key_rate_limit() (and the service role),+-- both of which bypass RLS. Tenant clients must never write this table directly,+-- so RLS leaves writes denied.diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.ymlindex a8724aef8c..216fdc9396 100644--- a/packages/dev/docker/docker-compose.dev.yml+++ b/packages/dev/docker/docker-compose.dev.yml@@ -204,6 +204,13 @@ services:SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}SUPABASE_DB_URL: postgresql://postgres:postgres@postgres:5432/postgresVERIFY_JWT: "false"+ # Backups edge fns (export/import/revert) send Inngest events. The edge+ # runtime is a separate env from the ERP app, so without these its+ # inngest.send() defaults to Inngest Cloud → 401. Point it at the local+ # dev server via the compose-network alias (NOT localhost — that's the+ # edge container itself).+ INNGEST_DEV: "1"+ INNGEST_BASE_URL: http://inngest:8288volumes:- ./packages/database/supabase/functions:/home/deno/functions:ro- ./packages/database/src:/home/src:rodiff --git a/packages/glossary/src/terms.ts b/packages/glossary/src/terms.tsindex fe3f14a5cd..af9db2f374 100644--- a/packages/glossary/src/terms.ts+++ b/packages/glossary/src/terms.ts@@ -25,6 +25,11 @@ export const terms = {definition:"A company that designs and builds its own finished products end to end (here, the shop building humanoid robots) rather than making parts to another company's specification."},+ "company-group": {+ term: "Company group",+ definition:+ "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."+ },"method-type": {term: "Method type",definition:diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.tsnew file mode 100644index 0000000000..8ee90dd96d--- /dev/null+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts@@ -0,0 +1,645 @@+import { randomUUID } from "node:crypto";+import {+ getPostgresClient,+ getPostgresConnectionPool,+ type KyselyDatabase+} from "@carbon/database/client";+import { type Kysely, PostgresDriver, sql } from "kysely";+import { nanoid } from "nanoid";++/**+ * Shared core for company backup export/import.+ *+ * The table catalog is derived from the live database schema+ * (information_schema + pg_constraint) rather than a hand-maintained list,+ * so new company-scoped tables are picked up automatically.+ */++export const BACKUP_KIND = "carbon-company-backup";+export const BACKUP_VERSION = 1;+export const BACKUP_INTEGRATION = "company-backup";+export const EXPORTS_PREFIX = "exports";+/** Shared, env-agnostic bucket holding the onboarding backup templates. */+export const TEMPLATE_BUCKET = "company-templates";++/**+ * The bucket the app stores per-company assets in (3D models, item thumbnails,+ * document attachments), all under a `{companyId}/` prefix. A self-contained+ * backup must embed these — they are NOT in the per-company bucket.+ */+export const STORAGE_BUCKET = "private";++/**+ * TEXT columns that hold a storage path (`{companyId}/…/{id}.ext`). On reseed+ * the companyId and the embedded ids both change, so these must be rewritten in+ * lock-step with the files they point at (see `rewriteStoragePath`).+ */+export const STORAGE_PATH_COLUMNS = new Set(["modelPath", "thumbnailPath"]);++/**+ * Prefix in the `private` bucket where onboarding demo-template assets live ONCE+ * per workspace (3D models, etc.), uploaded at deploy from the committed+ * template gz. A template import references these instead of copying the files+ * into every onboarded company's `{companyId}/` prefix.+ *+ * NOTE: `ci/src/upload-backup-templates.ts` (a plain Node script that can't+ * import this Deno/Inngest module cheaply) hardcodes the same literal — keep+ * the two in sync.+ */+export const TEMPLATE_ASSET_PREFIX = "_templates";++/**+ * Rewrite a `{sourceCompanyId}/…` storage path to its shared template location+ * `_templates/{industryId}/…`, keeping the trailing segments (and their ids)+ * intact — the canonical asset is shared across every company onboarded from+ * the template, so ids are NOT remapped. Used both when fanning a template's+ * assets into the shared prefix at deploy and when pointing a referenced+ * import's path columns at them. A no-op if the path isn't under the source+ * company prefix.+ */+export function rewriteToTemplateAssetPath(+ path: string,+ sourceCompanyId: string,+ industryId: string+): string {+ if (path.startsWith(`${sourceCompanyId}/`)) {+ return `${TEMPLATE_ASSET_PREFIX}/${industryId}/${path.slice(+ sourceCompanyId.length + 1+ )}`;+ }+ return path;+}++/**+ * Rewrite a storage path for the target company. Swaps the leading+ * `{sourceCompanyId}/` and any path segment whose id was remapped on reseed+ * (e.g. `{co}/models/{modelId}.stl`, `{co}/thumbnails/{itemId}/{file}`). A+ * no-op for preserve-mode (same company, empty `idRewrite`). The same function+ * is applied to both the uploaded file path and the DB path columns so they+ * stay consistent.+ */+export function rewriteStoragePath(+ path: string,+ sourceCompanyId: string,+ targetCompanyId: string,+ idRewrite: Map<string, string>+): string {+ let p = path;+ if (+ sourceCompanyId !== targetCompanyId &&+ p.startsWith(`${sourceCompanyId}/`)+ ) {+ p = `${targetCompanyId}/${p.slice(sourceCompanyId.length + 1)}`;+ }+ if (idRewrite.size === 0) return p;+ return p+ .split("/")+ .map((seg) => {+ const dot = seg.indexOf(".");+ const idPart = dot >= 0 ? seg.slice(0, dot) : seg;+ const rest = dot >= 0 ? seg.slice(dot) : "";+ const mapped = idRewrite.get(idPart);+ return mapped ? mapped + rest : seg;+ })+ .join("/");+}++/**+ * Tables whose contents must never travel in a backup — credentials,+ * integration tokens and webhook targets stay with the source company.+ */+export const SECRET_TABLES = [+ "apiKey",+ "companyIntegration",+ "webhook",+ "oauthClient",+ "oauthToken"+];++/**+ * Tenant-root tables that carry a scope column but are NOT tenant data — the+ * company shell itself is created by onboarding, never imported. Excluded+ * from the catalog entirely.+ */+export const STRUCTURAL_TABLES = ["company"];++/**+ * Additional tables skipped in `reseed` mode — memberships, invites and+ * integration state belong to the source company's users, not to a copy.+ * The importing company already has its admin membership from onboarding.+ */+export const RESEED_SKIPPED_TABLES = [+ "userToCompany",+ "employee",+ "employeeType",+ "employeeTypePermission",+ "invite",+ "externalIntegrationMapping"+];++/**+ * Tables an in-place restore must NOT wipe or reload — the caller's own access+ * and identity. Wiping these mid-restore would lock the user out of the company+ * they're restoring. The backup still carries them; they're simply left as-is.+ */+export const IN_PLACE_SKIPPED_TABLES = new Set([+ "userToCompany",+ "employee",+ "employeeType",+ "employeeTypePermission",+ "invite",+ "externalIntegrationMapping"+]);++/** Integration key for the in-place restore marker (holds the snapshot path). */+export const RESTORE_INTEGRATION = "company-restore";++export type ColumnInfo = {+ name: string;+ /** information_schema data_type, e.g. 'ARRAY', 'jsonb', 'USER-DEFINED' */+ dataType: string;+ /** information_schema udt_name, e.g. '_text', 'jsonb', 'bytea' */+ udtName: string;+ isNullable: boolean;+ /** GENERATED ALWAYS / identity columns — excluded from export & insert */+ isGenerated: boolean;+ /** has a column default (so a backup that omits it can still insert) */+ hasDefault: boolean;+};++export type ForeignKey = {+ column: string;+ refTable: string;+ refColumn: string;+};++export type TableInfo = {+ name: string;+ columns: ColumnInfo[];+ /**+ * 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.+ */+ scopeColumn: "companyId" | "companyGroupId";+ /** primary key column names (empty when the table has no PK) */+ pkColumns: string[];+ /** true when the primary key is exactly the single column "id" */+ hasId: boolean;+ foreignKeys: ForeignKey[];+};++export type Catalog = {+ schemaVersion: string;+ /** topologically sorted — referenced tables come first */+ tables: TableInfo[];+};++export type Manifest = {+ kind: typeof BACKUP_KIND;+ version: typeof BACKUP_VERSION;+ schemaVersion: string;+ sourceCompanyId: string;+ sourceCompanyGroupId: string | null;+ sourceCompanyName: string | null;+ exportedAt: string;+ exportedBy: string;+ label: string | null;+ includeStorage: "none" | "all";+ tables: Array<{ name: string; rows: number; columns: string[] }>;+ storage: Array<{ path: string; size: number; included: boolean }>;+ excludedTables: string[];+};++export type CompanyBackup = {+ manifest: Manifest;+ data: Record<string, Record<string, unknown>[]>;+ /** path within the company bucket -> base64 contents */+ storage?: Record<string, string>;+};++export function getJobDatabaseClient(size = 1) {+ const pool = getPostgresConnectionPool(size);+ return getPostgresClient(+ pool,+ PostgresDriver+ ) as unknown as Kysely<KyselyDatabase>;+}++/**+ * Build the catalog of tenant-scoped tables (public base tables with a+ * "companyId" or "companyGroupId" column), their columns, FK edges and a+ * topological order. A table that has both columns is treated as+ * companyId-scoped.+ */+export async function getCompanyTableCatalog(+ db: Kysely<KyselyDatabase>+): Promise<Catalog> {+ const scopeRows = await sql<{ name: string; column_name: string }>`+ SELECT c.table_name AS name, c.column_name+ FROM information_schema.columns c+ JOIN information_schema.tables t+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name+ WHERE c.table_schema = 'public'+ AND c.column_name IN ('companyId', 'companyGroupId')+ AND t.table_type = 'BASE TABLE'+ `.execute(db);++ // companyId wins when a table carries both columns.+ const structural = new Set(STRUCTURAL_TABLES);+ const scopeByTable = new Map<string, "companyId" | "companyGroupId">();+ for (const r of scopeRows.rows) {+ if (structural.has(r.name)) continue;+ if (r.column_name === "companyId") {+ scopeByTable.set(r.name, "companyId");+ } else if (!scopeByTable.has(r.name)) {+ scopeByTable.set(r.name, "companyGroupId");+ }+ }+ const tableSet = new Set(scopeByTable.keys());++ const columns = await sql<{+ table_name: string;+ column_name: string;+ data_type: string;+ udt_name: string;+ is_nullable: string;+ is_generated: string;+ identity_generation: string | null;+ column_default: string | null;+ }>`+ SELECT table_name, column_name, data_type, udt_name, is_nullable,+ is_generated, identity_generation, column_default+ FROM information_schema.columns+ WHERE table_schema = 'public'+ `.execute(db);++ const primaryKeys = await sql<{+ table_name: string;+ column_name: string;+ ordinal_position: string | number;+ }>`+ SELECT tc.table_name, kcu.column_name, kcu.ordinal_position+ FROM information_schema.table_constraints tc+ JOIN information_schema.key_column_usage kcu+ ON kcu.constraint_name = tc.constraint_name+ AND kcu.table_schema = tc.table_schema+ WHERE tc.table_schema = 'public' AND tc.constraint_type = 'PRIMARY KEY'+ ORDER BY tc.table_name, kcu.ordinal_position+ `.execute(db);++ const foreignKeys = await sql<{+ table_name: string;+ column_name: string;+ ref_table: string;+ ref_column: string;+ }>`+ SELECT src.relname AS table_name, att.attname AS column_name,+ tgt.relname AS ref_table, tatt.attname AS ref_column+ FROM pg_constraint con+ JOIN pg_class src ON src.oid = con.conrelid+ JOIN pg_namespace nsp ON nsp.oid = src.relnamespace+ JOIN pg_class tgt ON tgt.oid = con.confrelid+ CROSS JOIN LATERAL unnest(con.conkey, con.confkey)+ WITH ORDINALITY AS u(attnum, fattnum, ord)+ JOIN pg_attribute att+ ON att.attrelid = src.oid AND att.attnum = u.attnum+ JOIN pg_attribute tatt+ ON tatt.attrelid = tgt.oid AND tatt.attnum = u.fattnum+ WHERE con.contype = 'f' AND nsp.nspname = 'public'+ `.execute(db);++ let schemaVersion = "unknown";+ try {+ const migration = await sql<{ version: string }>`+ SELECT version FROM supabase_migrations.schema_migrations+ ORDER BY version DESC LIMIT 1+ `.execute(db);+ schemaVersion = migration.rows[0]?.version ?? "unknown";+ } catch {+ // migrations table unavailable — leave as unknown+ }++ const columnsByTable = new Map<string, ColumnInfo[]>();+ for (const c of columns.rows) {+ if (!tableSet.has(c.table_name)) continue;+ const list = columnsByTable.get(c.table_name) ?? [];+ list.push({+ name: c.column_name,+ dataType: c.data_type,+ udtName: c.udt_name,+ isNullable: c.is_nullable === "YES",+ isGenerated:+ c.is_generated === "ALWAYS" || c.identity_generation !== null,+ hasDefault: c.column_default !== null+ });+ columnsByTable.set(c.table_name, list);+ }++ const pkColumnsByTable = new Map<string, string[]>();+ for (const p of primaryKeys.rows) {+ const list = pkColumnsByTable.get(p.table_name) ?? [];+ list.push(p.column_name);+ pkColumnsByTable.set(p.table_name, list);+ }++ const fksByTable = new Map<string, ForeignKey[]>();+ for (const f of foreignKeys.rows) {+ if (!tableSet.has(f.table_name)) continue;+ const list = fksByTable.get(f.table_name) ?? [];+ list.push({+ column: f.column_name,+ refTable: f.ref_table,+ refColumn: f.ref_column+ });+ fksByTable.set(f.table_name, list);+ }++ const tables: TableInfo[] = [...tableSet].sort().map((name) => {+ const pkColumns = pkColumnsByTable.get(name) ?? [];+ return {+ name,+ columns: columnsByTable.get(name) ?? [],+ scopeColumn: scopeByTable.get(name)!,+ pkColumns,+ hasId: pkColumns.length === 1 && pkColumns[0] === "id",+ foreignKeys: fksByTable.get(name) ?? []+ };+ });++ return { schemaVersion, tables: topologicalSort(tables) };+}++/**+ * Decide whether a backup can be imported into the *current* schema. A backup+ * is a point-in-time snapshot; a breaking migration since then would make the+ * insert fail. Incompatible when, for a table the backup populates, the live+ * schema either no longer has the table, or has gained a required column (NOT+ * NULL, no default, not generated) the backup can't supply. Additive migrations+ * (new nullable/defaulted columns, new tables) stay compatible automatically —+ * so there's no version to bump by hand.+ */+export function assertBackupImportable(+ catalog: Catalog,+ backup: CompanyBackup+): { ok: true } | { ok: false; reason: string } {+ const { manifest } = backup;++ if (manifest.version !== BACKUP_VERSION) {+ return {+ ok: false,+ reason: `its format (generation ${manifest.version}) is no longer supported (current is ${BACKUP_VERSION})`+ };+ }++ // Account defaults reference the chart of accounts, so the two must travel+ // together; defaults without accounts came from a groupless company and would+ // leave a dangling FK (the export-side guard now prevents producing these).+ if (+ (backup.data.accountDefault?.length ?? 0) > 0 &&+ (backup.data.account?.length ?? 0) === 0+ ) {+ return {+ ok: false,+ reason:+ "it has account defaults but no chart of accounts (exported from a company with no group)"+ };+ }++ const liveByName = new Map(catalog.tables.map((t) => [t.name, t]));+ for (const backupTable of manifest.tables) {+ const live = liveByName.get(backupTable.name);+ if (!live) {+ return {+ ok: false,+ reason: `table "${backupTable.name}" no longer exists in the current schema`+ };+ }+ const backupCols = new Set(backupTable.columns);+ const missing = live.columns.find(+ (c) =>+ !c.isNullable &&+ !c.hasDefault &&+ !c.isGenerated &&+ !backupCols.has(c.name)+ );+ if (missing) {+ return {+ ok: false,+ reason: `"${backupTable.name}" now requires column "${missing.name}", which this backup predates`+ };+ }+ }+ return { ok: true };+}++/**+ * Kahn's algorithm over in-set FK edges (referenced tables first). Cycles+ * are broken deterministically by picking the remaining table with the+ * fewest unmet dependencies (then alphabetically). Order is best-effort:+ * imports run with FK enforcement relaxed when possible.+ */+export function topologicalSort(tables: TableInfo[]): TableInfo[] {+ const byName = new Map(tables.map((t) => [t.name, t]));+ const remaining = new Set(byName.keys());+ const deps = new Map<string, Set<string>>();++ for (const t of tables) {+ const set = new Set<string>();+ for (const fk of t.foreignKeys) {+ if (fk.refTable !== t.name && byName.has(fk.refTable)) {+ set.add(fk.refTable);+ }+ }+ deps.set(t.name, set);+ }++ const sorted: TableInfo[] = [];+ while (remaining.size > 0) {+ let next: string | null = null;+ let fewest = Infinity;+ for (const name of [...remaining].sort()) {+ const unmet = [...(deps.get(name) ?? [])].filter((d) =>+ remaining.has(d)+ ).length;+ if (unmet === 0) {+ next = name;+ break;+ }+ if (unmet < fewest) {+ fewest = unmet;+ next = name;+ }+ }+ if (!next) break;+ remaining.delete(next);+ sorted.push(byName.get(next)!);+ }++ return sorted;+}++/**+ * A fresh primary-key value for a table, matching its `id` column's type as the+ * schema defines it — a real UUID for `uuid` columns, otherwise a nanoid (what+ * the `id()` default produces). Used wherever reseed/restore remaps ids, so we+ * never feed a nanoid into a uuid column.+ */+export function newIdForTable(table: TableInfo): string {+ const idCol = table.columns.find((c) => c.name === "id");+ return idCol?.udtName === "uuid" ? randomUUID() : nanoid();+}++/** Convert a pg-returned value into a JSON-safe backup value. */+export function encodeValue(value: unknown, col: ColumnInfo): unknown {+ if (value === null || value === undefined) return null;+ if (col.udtName === "bytea" && Buffer.isBuffer(value)) {+ return value.toString("base64");+ }+ if (value instanceof Date) return value.toISOString();+ return value;+}++/**+ * Convert a backup value into a parameter node-pg can bind for this+ * column. Strings pass through untyped so Postgres coerces them into+ * enums/timestamps/numerics by column type; json(b) values are stringified+ * so JS arrays inside jsonb are not mistaken for Postgres arrays.+ */+export function bindValue(value: unknown, col: ColumnInfo): unknown {+ if (value === null || value === undefined) return null;+ if (col.udtName === "bytea" && typeof value === "string") {+ return Buffer.from(value, "base64");+ }+ if (col.udtName === "json" || col.udtName === "jsonb") {+ return JSON.stringify(value);+ }+ return value;+}++/**+ * 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+ * never overwrites data the target already owns — a bare clone keeps every+ * table, an identity-seeded onboard drops the ones its seed/triggers filled.+ */+export async function filterUnpopulated(+ db: Kysely<KyselyDatabase>,+ tables: 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}+ ) AS present+ `.execute(db);+ return !result.rows[0]?.present;+ })+ );+ return tables.filter((_, i) => isEmpty[i]);+}++/**+ * Probe whether this connection may disable triggers/FK enforcement via+ * `session_replication_role`. True on local dev (superuser); on hosted+ * Supabase it depends on the grants of the connecting role.+ */+export async function canSetReplicationRole(+ db: Kysely<KyselyDatabase>+): Promise<boolean> {+ try {+ await db.transaction().execute(async (trx) => {+ await sql`SET LOCAL session_replication_role = 'replica'`.execute(trx);+ throw new Error("__rollback__");+ });+ return true;+ } catch (err) {+ return err instanceof Error && err.message === "__rollback__";+ }+}++/**+ * The companyId-scoped tables an in-place restore may clear and reload: minus+ * the access/identity tables (kept, so the user isn't locked out) and secrets+ * (never travel). companyGroupId-scoped tables (chart of accounts, currencies)+ * are excluded — shared across the group, so a single company's restore must+ * not touch them. Returned in catalog (topological) order.+ *+ * The full set is WIPED (so a table empty in the backup ends up empty, matching+ * the snapshot exactly); only the subset with rows in the backup is reloaded.+ */+export function selectWipeableTables(+ catalog: Catalog,+ opts: { includeGroup?: boolean } = {}+): TableInfo[] {+ const skip = new Set([...SECRET_TABLES, ...IN_PLACE_SKIPPED_TABLES]);+ return catalog.tables.filter(+ (t) =>+ !skip.has(t.name) &&+ (t.scopeColumn === "companyId" ||+ (opts.includeGroup === true && t.scopeColumn === "companyGroupId"))+ );+}++/**+ * Guard the in-place restore invariant: a KEPT table (access/secret tables that+ * survive a wipe) must not hold a NOT-NULL foreign key into a WIPED table. If it+ * did, wiping the referenced table would dangle the kept row (own restore could+ * leave it pointing at an emptied table; foreign restore remaps to new ids).+ * Currently holds — this catches future schema drift before it corrupts data.+ */+export function assertWipeSafe(+ catalog: Catalog+): { ok: true } | { ok: false; reason: string } {+ const wipeable = new Set(+ selectWipeableTables(catalog, { includeGroup: true }).map((t) => t.name)+ );+ const kept = new Set([...IN_PLACE_SKIPPED_TABLES, ...SECRET_TABLES]);+ for (const table of catalog.tables) {+ if (!kept.has(table.name)) continue;+ const colByName = new Map(table.columns.map((c) => [c.name, c]));+ for (const fk of table.foreignKeys) {+ const col = colByName.get(fk.column);+ if (col && !col.isNullable && wipeable.has(fk.refTable)) {+ return {+ ok: false,+ reason: `"${table.name}.${fk.column}" requires "${fk.refTable}", which a restore wipes — it would be left dangling`+ };+ }+ }+ }+ return { ok: true };+}++/**+ * Delete every row of the given tables for one company, in REVERSE topological+ * order (children before parents) so FK constraints hold by construction.+ * `tables` is expected in catalog (referenced-first) order; this reverses it.+ * Each table is scoped by its own column — companyId-scoped by `companyId`,+ * companyGroupId-scoped by `companyGroupId`. Run inside the caller's+ * transaction, ideally with `session_replication_role = 'replica'` set.+ */+export async function wipeScopedData(+ trx: Kysely<KyselyDatabase>,+ tables: 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;+ await sql`+ DELETE FROM ${sql.id(table.name)}+ WHERE ${sql.id(table.scopeColumn)} = ${value}+ `.execute(trx);+ }+}diff --git a/packages/jobs/src/inngest/functions/tasks/company-export.ts b/packages/jobs/src/inngest/functions/tasks/company-export.tsnew file mode 100644index 0000000000..9950e9475d--- /dev/null+++ b/packages/jobs/src/inngest/functions/tasks/company-export.ts@@ -0,0 +1,251 @@+import { promisify } from "node:util";+import { gzip } from "node:zlib";++const gzipAsync = promisify(gzip);++import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { sql } from "kysely";+import { inngest } from "../../client";+import type { CompanyBackup, Manifest } from "./company-backup";+import {+ BACKUP_INTEGRATION,+ BACKUP_KIND,+ BACKUP_VERSION,+ EXPORTS_PREFIX,+ encodeValue,+ getCompanyTableCatalog,+ getJobDatabaseClient,+ SECRET_TABLES,+ STORAGE_BUCKET+} from "./company-backup";++/** Per-file and total caps for embedded storage files (base64 inflates ~33%). */+const MAX_STORAGE_FILE_BYTES = 25 * 1024 * 1024;+const MAX_STORAGE_TOTAL_BYTES = 200 * 1024 * 1024;++type ServiceRole = ReturnType<typeof getCarbonServiceRole>;+type JobDatabase = ReturnType<typeof getJobDatabaseClient>;++/**+ * Build a gzipped company backup (data + optional storage files). Exported so+ * the same logic that backs the export job can author onboarding templates.+ */+export async function buildCompanyBackup(+ client: ServiceRole,+ db: JobDatabase,+ opts: {+ companyId: string;+ userId: string;+ label?: string | null;+ includeStorage: "none" | "all";+ }+): Promise<{ compressed: Buffer; manifest: Manifest; rows: number }> {+ const { companyId, userId, includeStorage } = opts;+ const label = opts.label ?? null;++ const company = await client+ .from("company")+ .select("id, name, companyGroupId")+ .eq("id", companyId)+ .single();+ if (company.error) throw new Error(company.error.message);+ const companyGroupId = company.data?.companyGroupId ?? null;++ // A companyGroup-scoped backup (chart of accounts, currencies, dimensions) is+ // meaningless without a group. Fail loudly rather than silently omitting it —+ // a groupless shell company once produced "valid"-looking backups with an+ // empty chart of accounts that then propagated to every onboarded company.+ if (companyGroupId === null) {+ throw new Error(+ `Company ${companyId} has no companyGroup — a backup would omit the chart ` ++ "of accounts, currencies and dimensions. Seed the company before backing it up."+ );+ }++ const catalog = await getCompanyTableCatalog(db);+ const secretTables = new Set(SECRET_TABLES);++ const data: CompanyBackup["data"] = {};+ const tableManifest: Manifest["tables"] = [];+ const excludedTables: string[] = [];++ for (const table of catalog.tables) {+ if (secretTables.has(table.name)) {+ excludedTables.push(table.name);+ continue;+ }++ // 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``;+ 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}+ `.execute(db);++ if (result.rows.length === 0) continue;++ data[table.name] = result.rows.map((row) => {+ const encoded: Record<string, unknown> = {};+ for (const col of columns) {+ encoded[col.name] = encodeValue(row[col.name], col);+ }+ return encoded;+ });++ tableManifest.push({+ name: table.name,+ rows: result.rows.length,+ columns: columns.map((c) => c.name)+ });+ }++ // Optionally embed the company's storage assets so the backup is a+ // self-contained unit. These live in the shared `private` bucket under a+ // `{companyId}/` prefix (3D models, item thumbnails, attachments) — NOT in+ // the per-company bucket. Skip anything over the size caps.+ const storageManifest: Manifest["storage"] = [];+ let storageFiles: Record<string, string> | undefined;++ if (includeStorage === "all") {+ storageFiles = {};+ let totalBytes = 0;+ const paths = await listBucketFilesRecursive(+ client,+ STORAGE_BUCKET,+ companyId+ );++ for (const file of paths) {+ let included =+ file.size <= MAX_STORAGE_FILE_BYTES &&+ totalBytes + file.size <= MAX_STORAGE_TOTAL_BYTES;++ if (included) {+ const download = await client.storage+ .from(STORAGE_BUCKET)+ .download(file.path);+ if (download.error || !download.data) {+ console.error("Failed to download storage file", {+ path: file.path,+ error: download.error+ });+ included = false;+ } else {+ storageFiles[file.path] = Buffer.from(+ await download.data.arrayBuffer()+ ).toString("base64");+ totalBytes += file.size;+ }+ }++ storageManifest.push({ path: file.path, size: file.size, included });+ }+ }++ const manifest: Manifest = {+ kind: BACKUP_KIND,+ version: BACKUP_VERSION,+ schemaVersion: catalog.schemaVersion,+ sourceCompanyId: companyId,+ sourceCompanyGroupId: companyGroupId,+ sourceCompanyName: company.data?.name ?? null,+ exportedAt: new Date().toISOString(),+ exportedBy: userId,+ label,+ includeStorage,+ tables: tableManifest,+ storage: storageManifest,+ excludedTables+ };++ const backup: CompanyBackup = { manifest, data, storage: storageFiles };+ const compressed = await gzipAsync(Buffer.from(JSON.stringify(backup)));+ const rows = tableManifest.reduce((sum, t) => sum + t.rows, 0);+ return { compressed, manifest, rows };+}++export const companyExportFunction = inngest.createFunction(+ {+ id: "company-export",+ retries: 1,+ concurrency: { key: "event.data.companyId", limit: 1 }+ },+ { event: "carbon/company-export" },+ async ({ event, step }) => {+ const { companyId, userId, label, includeStorage } = event.data;++ return await step.run("export-company", async () => {+ const client = getCarbonServiceRole();+ const db = getJobDatabaseClient(1);++ const { compressed, manifest, rows } = await buildCompanyBackup(+ client,+ db,+ { companyId, userId, label, includeStorage }+ );++ const timestamp = manifest.exportedAt.replace(/[:.]/g, "-");+ const slug = label+ ? `_${label+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .slice(0, 40)}`+ : "";+ const path = `${EXPORTS_PREFIX}/${timestamp}${slug}.carbon.json.gz`;++ const upload = await client.storage+ .from(companyId)+ .upload(path, compressed, {+ contentType: "application/gzip",+ upsert: false+ });+ if (upload.error) throw new Error(upload.error.message);++ console.log("Company export complete", {+ companyId,+ path,+ tables: manifest.tables.length,+ rows,+ bytes: compressed.byteLength+ });++ return { path, tables: manifest.tables.length, rows };+ });+ }+);++async function listBucketFilesRecursive(+ client: ServiceRole,+ bucket: string,+ prefix = ""+): Promise<Array<{ path: string; size: number }>> {+ const files: Array<{ path: string; size: number }> = [];+ const { data, error } = await client.storage.from(bucket).list(prefix, {+ limit: 1000+ });+ if (error || !data) return files;++ for (const entry of data) {+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;+ if (entry.id === null) {+ // folder+ files.push(...(await listBucketFilesRecursive(client, bucket, path)));+ } else {+ files.push({+ path,+ size: (entry.metadata as { size?: number } | null)?.size ?? 0+ });+ }+ }+ return files;+}diff --git a/packages/jobs/src/inngest/functions/tasks/company-import.ts b/packages/jobs/src/inngest/functions/tasks/company-import.tsnew file mode 100644index 0000000000..64e002dfea--- /dev/null+++ b/packages/jobs/src/inngest/functions/tasks/company-import.ts@@ -0,0 +1,524 @@+import { promisify } from "node:util";+import { gunzip } from "node:zlib";++const gunzipAsync = promisify(gunzip);++import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { chunkArray } from "@carbon/utils";+import { sql } from "kysely";+import { inngest } from "../../client";+import type { ColumnInfo, CompanyBackup, TableInfo } from "./company-backup";+import {+ assertBackupImportable,+ BACKUP_INTEGRATION,+ BACKUP_KIND,+ bindValue,+ canSetReplicationRole,+ filterUnpopulated,+ getCompanyTableCatalog,+ getJobDatabaseClient,+ newIdForTable,+ RESEED_SKIPPED_TABLES,+ rewriteStoragePath,+ rewriteToTemplateAssetPath,+ SECRET_TABLES,+ STORAGE_BUCKET,+ STORAGE_PATH_COLUMNS+} from "./company-backup";++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;+ externalId: string;+};++export const companyImportFunction = inngest.createFunction(+ {+ id: "company-import",+ retries: 1,+ concurrency: { key: "event.data.companyId", limit: 1 }+ },+ { event: "carbon/company-import" },+ async ({ event, step }) => {+ const {+ companyId,+ userId,+ filePath,+ mode,+ importRunId,+ autoFinalize,+ templateIndustryId+ } = event.data;++ // Onboarding demo templates reference shared assets at+ // `_templates/<industryId>/` (uploaded once per workspace at deploy) rather+ // than copying every file into this company's `{companyId}/` prefix. Real+ // backups have no industryId and stay self-contained (files embedded + copied).+ const referencedTemplate =+ typeof templateIndustryId === "string" && templateIndustryId.length > 0;++ return await step.run("import-company", async () => {+ const client = getCarbonServiceRole();+ const db = getJobDatabaseClient(1);++ // Idempotency guard — a retry after a partial failure must not+ // duplicate rows that already committed under this run id.+ const existing = await client+ .from("externalIntegrationMapping")+ .select("id", { count: "exact", head: true })+ .eq("integration", BACKUP_INTEGRATION)+ .eq("companyId", companyId)+ .filter("metadata->>importRunId", "eq", importRunId);+ if ((existing.count ?? 0) > 0) {+ console.log("Import run already applied, skipping", { importRunId });+ return { importRunId, skipped: true };+ }++ const download = await client.storage.from(companyId).download(filePath);+ if (download.error || !download.data) {+ throw new Error(+ `Failed to download artifact ${filePath}: ${download.error?.message}`+ );+ }++ const backup = JSON.parse(+ (+ await gunzipAsync(Buffer.from(await download.data.arrayBuffer()))+ ).toString()+ ) as CompanyBackup;++ if (backup.manifest?.kind !== BACKUP_KIND) {+ throw new Error("File is not a Carbon company backup");+ }+ if (+ mode === "preserve" &&+ backup.manifest.sourceCompanyId !== companyId+ ) {+ throw new Error(+ "Preserve mode requires importing into the same company the artifact " ++ `was exported from (${backup.manifest.sourceCompanyId}). ` ++ "Use reseed mode to import into a different company."+ );+ }++ // Reseed populates a fresh company; refuse a target that's already been+ // set up (the edge function gates this too — this is defense in depth+ // for retries or direct triggers). accountDefault is the seed marker.+ if (mode === "reseed") {+ const seeded = await client+ .from("accountDefault")+ .select("companyId", { count: "exact", head: true })+ .eq("companyId", companyId);+ if ((seeded.count ?? 0) > 0) {+ throw new Error(+ `Reseed target ${companyId} is already set up — reseed requires a ` ++ "freshly created company"+ );+ }+ }++ // The target company's group receives the companyGroup-scoped data+ // (chart of accounts, currencies, …).+ const targetCompany = await client+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();+ if (targetCompany.error) throw new Error(targetCompany.error.message);+ const targetGroupId = targetCompany.data?.companyGroupId ?? null;++ const catalog = await getCompanyTableCatalog(db);+ const compatibility = assertBackupImportable(catalog, backup);+ if (!compatibility.ok) {+ throw new Error(+ `This backup can't be restored: ${compatibility.reason}.`+ );+ }+ const catalogTableNames = new Set(catalog.tables.map((t) => t.name));++ const skipped = new Set([+ ...SECRET_TABLES,+ ...(mode === "reseed" ? RESEED_SKIPPED_TABLES : [])+ ]);+ const backupColumns = new Map(+ backup.manifest.tables.map((t) => [t.name, new Set(t.columns)])+ );+ const candidateTables = catalog.tables.filter(+ (t) => !skipped.has(t.name) && (backup.data[t.name]?.length ?? 0) > 0+ );++ // Reseed is additive into a fresh company: never touch a table the+ // target already populated itself — its identity seed, its triggers+ // (event subscriptions, search registry) or onboarding's own inserts+ // (location, employee job, groups). Asking the database which tables+ // 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 importTables =+ mode === "reseed"+ ? await filterUnpopulated(+ db,+ candidateTables,+ companyId,+ targetGroupId+ )+ : candidateTables;++ // Reseed: assign a fresh id to every row of every id-keyed table up+ // front so FK references can be rewritten in a single pass.+ const idMaps = new Map<string, Map<string, string>>();+ if (mode === "reseed") {+ for (const table of importTables) {+ if (!table.hasId) continue;+ const map = new Map<string, string>();+ for (const row of backup.data[table.name]!) {+ if (typeof row.id === "string")+ map.set(row.id, newIdForTable(table));+ }+ idMaps.set(table.name, map);+ }+ }++ // Flat old-id → new-id lookup across every remapped table, used to rewrite+ // ids embedded in storage paths (e.g. `{co}/models/{modelId}.stl`) so the+ // restored files and their DB path columns line up. Empty in preserve mode.+ const idRewrite = new Map<string, string>();+ for (const map of idMaps.values()) {+ for (const [oldId, newId] of map) idRewrite.set(oldId, newId);+ }++ // Group-scoped data needs a destination group on the target company.+ if (+ targetGroupId === null &&+ importTables.some((t) => t.scopeColumn === "companyGroupId")+ ) {+ throw new Error(+ `Target company ${companyId} has no companyGroup, but the artifact ` ++ "carries group-scoped data (chart of accounts, currencies). " ++ "Create the company's group before importing."+ );+ }++ const sourceCompanyId = backup.manifest.sourceCompanyId;+ let scrubCounter = 0;+ // FK columns pointing at a tenant table we did NOT import (it was already+ // populated by the target's own seed, or skipped). Their non-null source+ // ids don't exist here; collected so a dangling, non-nullable ref is+ // 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);++ if (col.name === "id" && table.hasId) {+ const map = idMaps.get(table.name)!;+ base = (v) => map.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;+ });+ };++ const replicaMode = await canSetReplicationRole(db);+ if (!replicaMode) {+ console.warn(+ "session_replication_role unavailable — importing with triggers " ++ "and FK enforcement active; relying on topological order"+ );+ }++ const counts: Record<string, number> = {};++ await db.transaction().execute(async (trx) => {+ if (replicaMode) {+ await sql`SET LOCAL session_replication_role = 'replica'`.execute(+ trx+ );+ }++ const ledger: LedgerRow[] = [];++ for (const table of importTables) {+ const backupCols =+ backupColumns.get(table.name) ??+ new Set(Object.keys(backup.data[table.name]![0] ?? {}));+ const columns = table.columns.filter(+ (c) => !c.isGenerated && backupCols.has(c.name)+ );+ if (columns.length === 0) continue;++ const transforms = buildColumnTransforms(table, columns);+ 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+ // per table).+ const colCount = columns.length;+ let rows: Record<string, unknown>[] = [];+ for (let r = 0; r < originalRows.length; r++) {+ const row = originalRows[r]!;+ const out: Record<string, unknown> = {};+ for (let c = 0; c < colCount; c++) {+ out[columns[c]!.name] = transforms[c]!(row[columns[c]!.name]);+ }+ rows.push(out);+ }++ // Collapsing user references onto one user can produce duplicate+ // primary keys in user-keyed tables — keep the first of each.+ if (mode === "reseed" && !table.hasId && table.pkColumns.length > 0) {+ const seen = new Set<string>();+ rows = rows.filter((row) => {+ const key = JSON.stringify(table.pkColumns.map((c) => row[c]));+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+ }++ for (const batch of chunkArray(rows, INSERT_CHUNK_SIZE)) {+ await sql`+ INSERT INTO ${sql.id(table.name)}+ (${sql.join(columns.map((c) => sql.id(c.name)))})+ VALUES ${sql.join(+ batch.map(+ (row) =>+ sql`(${sql.join(+ columns.map((c) => sql`${bindValue(row[c.name], c)}`)+ )})`+ )+ )}+ `.execute(trx);+ }++ counts[table.name] = rows.length;++ // Revert ledger — one row per inserted row. For id-keyed tables+ // entityId is the (new) id; for composite-keyed tables it's the+ // JSON-encoded primary key tuple.+ if (table.pkColumns.length === 0) {+ console.warn("Table has no primary key — revert will skip it", {+ table: table.name+ });+ continue;+ }+ if (table.hasId) {+ // dedupe above only applies to composite-keyed tables, so the+ // transformed rows still align index-wise with the originals+ rows.forEach((row, i) => {+ ledger.push({+ entityType: table.name,+ entityId: row.id as string,+ externalId:+ (originalRows[i]?.id as string) ?? (row.id as string)+ });+ });+ } else {+ for (const row of rows) {+ const key = JSON.stringify(+ table.pkColumns.map((c) => row[c] ?? null)+ );+ ledger.push({+ entityType: table.name,+ entityId: key,+ externalId: key+ });+ }+ }+ }++ for (const batch of chunkArray(ledger, INSERT_CHUNK_SIZE)) {+ await sql`+ INSERT INTO ${sql.id("externalIntegrationMapping")}+ ("entityType", "entityId", "integration", "externalId",+ "metadata", "companyId", "createdBy")+ VALUES ${sql.join(+ batch.map(+ (l) =>+ sql`(${l.entityType}, ${l.entityId}, ${BACKUP_INTEGRATION},+ ${l.externalId}, ${JSON.stringify({ importRunId })},+ ${companyId}, ${userId})`+ )+ )}+ `.execute(trx);+ }+ });++ if (unresolvedRefs.size > 0) {+ console.warn(+ "Reseed kept non-nullable references to tables it did not import " ++ "(the target already had them, so source ids could not be " ++ "remapped). These may dangle — the template likely needs those " ++ "columns made nullable or those tables left out of the seed:",+ [...unresolvedRefs]+ );+ }++ // Storage files travel outside the transaction — failures here leave+ // the imported rows intact and are surfaced as warnings. Restore into the+ // shared `private` bucket with the path rewritten for the target company+ // (and remapped ids on reseed), matching the path columns rewritten above.+ //+ // A referenced template skips this entirely: its assets already live once+ // per workspace at `_templates/<industryId>/` (the path columns above now+ // point there), so copying them into `{companyId}/` would defeat the+ // purpose. The embedded bytes in the gz are ignored here — they exist for+ // the deploy step that seeds the shared prefix.+ let storageUploaded = 0;+ if (backup.storage && !referencedTemplate) {+ for (const [path, base64] of Object.entries(backup.storage)) {+ const targetPath = rewriteStoragePath(+ path,+ sourceCompanyId,+ companyId,+ idRewrite+ );+ const upload = await client.storage+ .from(STORAGE_BUCKET)+ .upload(targetPath, Buffer.from(base64, "base64"), {+ upsert: true+ });+ if (upload.error) {+ console.warn("Failed to upload storage file", {+ path: targetPath,+ error: upload.error.message+ });+ } else {+ storageUploaded++;+ }+ }+ }++ // Onboarding-from-a-backup commits immediately — no human review — so+ // drop the revert ledger and skip the pending state.+ if (autoFinalize) {+ await sql`+ DELETE FROM ${sql.id("externalIntegrationMapping")}+ WHERE ${sql.id("integration")} = ${BACKUP_INTEGRATION}+ AND ${sql.id("companyId")} = ${companyId}+ AND metadata->>'importRunId' = ${importRunId}+ `.execute(db);+ }++ const totalRows = Object.values(counts).reduce((sum, n) => sum + n, 0);+ console.log(+ autoFinalize+ ? "Company import complete — auto-finalized"+ : "Company import complete — pending finalize/revert",+ {+ companyId,+ importRunId,+ mode,+ tables: Object.keys(counts).length,+ rows: totalRows,+ storageUploaded,+ ...(referencedTemplate+ ? { referencedTemplate: templateIndustryId }+ : {})+ }+ );++ return {+ importRunId,+ tables: Object.keys(counts).length,+ rows: totalRows,+ storageUploaded+ };+ });+ }+);diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.tsnew file mode 100644index 0000000000..57f1b1bf08--- /dev/null+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts@@ -0,0 +1,724 @@+import { promisify } from "node:util";+import { gunzip } from "node:zlib";++const gunzipAsync = promisify(gunzip);++import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { chunkArray } from "@carbon/utils";+import { sql } from "kysely";+import { inngest } from "../../client";+import type {+ Catalog,+ ColumnInfo,+ CompanyBackup,+ TableInfo+} from "./company-backup";+import {+ assertBackupImportable,+ assertWipeSafe,+ BACKUP_KIND,+ bindValue,+ canSetReplicationRole,+ getCompanyTableCatalog,+ getJobDatabaseClient,+ newIdForTable,+ RESTORE_INTEGRATION,+ rewriteStoragePath,+ STORAGE_BUCKET,+ STORAGE_PATH_COLUMNS,+ selectWipeableTables,+ wipeScopedData+} from "./company-backup";+import { buildCompanyBackup } from "./company-export";++const INSERT_CHUNK_SIZE = 200;+const EXPORTS_PREFIX = "exports";++/** FKs to these collapse to the importing user when re-stamping a foreign backup. */+const USER_REF_TABLES = new Set(["user", "employee"]);++type ServiceRole = ReturnType<typeof getCarbonServiceRole>;+type JobDatabase = ReturnType<typeof getJobDatabaseClient>;++/** Parse + structurally validate a gzipped backup blob. */+async function downloadBackup(+ client: ServiceRole,+ companyId: string,+ filePath: string+): Promise<CompanyBackup> {+ const download = await client.storage.from(companyId).download(filePath);+ if (download.error || !download.data) {+ throw new Error(+ `Failed to download backup ${filePath}: ${download.error?.message}`+ );+ }+ const backup = JSON.parse(+ (+ await gunzipAsync(Buffer.from(await download.data.arrayBuffer()))+ ).toString()+ ) as CompanyBackup;+ if (backup.manifest?.kind !== BACKUP_KIND) {+ throw new Error("File is not a Carbon company backup");+ }+ return backup;+}++type Transform = (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.+ */+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>;+ }+): Transform[] {+ const identity: Transform = (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);+ if (col.name === "id" && table.hasId) {+ const map = ctx.idMaps.get(table.name)!;+ return (v) => map.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;+ });+}++/**+ * Wipe the company's restorable tables and reload them from `backup`. Two modes:+ * - `remap=false` (own backup / snapshot): ids and scope already belong to this+ * company, so rows load verbatim.+ * - `remap=true` (foreign backup): the data belongs to another company, so every+ * id is remapped and companyId/group/FKs are re-stamped onto this company —+ * including the chart of accounts (group-scoped), which is why `includeGroup`+ * is set for foreign restores.+ * Runs in one transaction with FK enforcement relaxed when possible.+ */+async function wipeAndLoad(+ db: JobDatabase,+ catalog: Catalog,+ backup: CompanyBackup,+ opts: {+ companyId: string;+ userId: string;+ remap: boolean;+ includeGroup: boolean;+ targetGroupId: string | null;+ }+): Promise<{ rows: number; idRewrite: Map<string, string> }> {+ const { companyId, userId, remap, includeGroup, targetGroupId } = opts;++ // Refuse if the schema would let a kept row dangle once we wipe (drift guard).+ const safe = assertWipeSafe(catalog);+ if (!safe.ok) {+ throw new Error(`Restore is unsafe for this schema: ${safe.reason}.`);+ }++ // Wipe every restorable table (so tables empty in the backup end up empty);+ // reload only those the backup actually has rows for.+ const wipeTables = selectWipeableTables(catalog, { includeGroup });+ const loadTables = wipeTables.filter(+ (t) => (backup.data[t.name]?.length ?? 0) > 0+ );+ const backupColumns = new Map(+ backup.manifest.tables.map((t) => [t.name, new Set(t.columns)])+ );++ // Foreign: assign a fresh id to every id-keyed row up front so FKs (and the+ // ids embedded in storage paths) can be rewritten in a single pass. Only remap+ // string ids (text/uuid) — integer/serial ids (e.g. `journal`) can't take a+ // nanoid, and since the table is wiped first their original ids are free to+ // reuse verbatim (FKs to them stay valid by keeping the original value).+ const idMaps = new Map<string, Map<string, string>>();+ const idRewrite = new Map<string, string>();+ if (remap) {+ for (const t of loadTables) {+ if (!t.hasId) continue;+ const idType = t.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[t.name]!) {+ if (typeof row.id === "string") map.set(row.id, newIdForTable(t));+ }+ idMaps.set(t.name, map);+ }+ for (const map of idMaps.values()) {+ for (const [oldId, newId] of map) idRewrite.set(oldId, newId);+ }+ }++ const replicaMode = await canSetReplicationRole(db);+ let inserted = 0;++ await db.transaction().execute(async (trx) => {+ if (replicaMode) {+ await sql`SET LOCAL session_replication_role = 'replica'`.execute(trx);+ }++ await wipeScopedData(trx, wipeTables, {+ companyId,+ companyGroupId: targetGroupId+ });++ for (const table of loadTables) {+ const backupCols =+ backupColumns.get(table.name) ??+ new Set(Object.keys(backup.data[table.name]![0] ?? {}));+ const columns = table.columns.filter(+ (c) => !c.isGenerated && backupCols.has(c.name)+ );+ if (columns.length === 0) continue;++ // Hot path. Plain indexed loops (no per-row `forEach` closure), packed+ // output array, and `out` keys assigned in a fixed column order so every+ // row of a table shares one hidden class. Own restore skips transforms+ // entirely (verbatim copy) — that call site would otherwise be megamorphic+ // across the per-column closures.+ const sourceRows = backup.data[table.name]!;+ const colCount = columns.length;+ const rows: Record<string, unknown>[] = [];+ if (remap) {+ const transforms = buildRowTransforms(table, columns, {+ remap,+ companyId,+ userId,+ targetGroupId,+ sourceCompanyId: backup.manifest.sourceCompanyId,+ idMaps,+ idRewrite+ });+ for (let r = 0; r < sourceRows.length; r++) {+ const row = sourceRows[r]!;+ const out: Record<string, unknown> = {};+ for (let c = 0; c < colCount; c++) {+ out[columns[c]!.name] = transforms[c]!(row[columns[c]!.name]);+ }+ rows.push(out);+ }+ } else {+ for (let r = 0; r < sourceRows.length; r++) {+ const row = sourceRows[r]!;+ const out: Record<string, unknown> = {};+ for (let c = 0; c < colCount; c++) {+ const name = columns[c]!.name;+ out[name] = row[name];+ }+ rows.push(out);+ }+ }++ for (const batch of chunkArray(rows, INSERT_CHUNK_SIZE)) {+ await sql`+ INSERT INTO ${sql.id(table.name)}+ (${sql.join(columns.map((c) => sql.id(c.name)))})+ VALUES ${sql.join(+ batch.map(+ (row) =>+ sql`(${sql.join(+ columns.map((c) => sql`${bindValue(row[c.name], c)}`)+ )})`+ )+ )}+ `.execute(trx);+ }+ inserted += rows.length;+ }+ });++ return { rows: inserted, idRewrite };+}++/** Restore the backup's storage files into the shared private bucket. Same+ * company, so paths are unchanged. Outside the transaction — failures warn. */+async function restoreStorage(+ client: ServiceRole,+ backup: CompanyBackup,+ ctx: { companyId: string; idRewrite: Map<string, string> }+): Promise<void> {+ if (!backup.storage) return;+ const sourceCompanyId = backup.manifest.sourceCompanyId;+ for (const [path, base64] of Object.entries(backup.storage)) {+ // Own backup → path unchanged (same company, empty idRewrite). Foreign →+ // rewritten to this company's prefix with the remapped ids, matching the+ // path columns rewritten in wipeAndLoad.+ const targetPath = rewriteStoragePath(+ path,+ sourceCompanyId,+ ctx.companyId,+ ctx.idRewrite+ );+ const upload = await client.storage+ .from(STORAGE_BUCKET)+ .upload(targetPath, Buffer.from(base64, "base64"), { upsert: true });+ if (upload.error) {+ console.warn("Failed to restore storage file", {+ path: targetPath,+ error: upload.error.message+ });+ }+ }+}++type RestoreStatus = "running" | "ready" | "failed" | "reverting";+type RestoreMeta = {+ restoreRunId: string;+ status: RestoreStatus;+ snapshotPath?: string | null;+ rows?: number;+ label?: string | null;+ error?: string | null;+ /** True when the restored backup came from another company (its rows were+ * re-stamped onto this one). */+ foreign?: boolean;+ /** True when the run touched group-scoped data (chart of accounts, currencies,+ * dimensions) — only when this company is its group's sole member. A revert+ * must wipe + reload the same scope. */+ includeGroup?: boolean;+};++async function getCompanyGroupId(+ client: ServiceRole,+ companyId: string+): Promise<string | null> {+ const company = await client+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();+ if (company.error) throw new Error(company.error.message);+ return company.data?.companyGroupId ?? null;+}++async function readRestoreMarker(+ client: ServiceRole,+ companyId: string,+ restoreRunId: string+): Promise<{ id: string; metadata: RestoreMeta } | null> {+ const marker = await client+ .from("externalIntegrationMapping")+ .select("id, metadata")+ .eq("integration", RESTORE_INTEGRATION)+ .eq("companyId", companyId)+ .filter("metadata->>restoreRunId", "eq", restoreRunId)+ .maybeSingle();+ if (!marker.data) return null;+ return {+ id: marker.data.id,+ metadata: (marker.data.metadata ?? {}) as RestoreMeta+ };+}++/**+ * Upsert the restore marker, merging `patch` into its metadata. The marker is+ * the single source of truth for the restore's lifecycle — the status route and+ * the UI read `metadata.status` (running → ready, or failed with an error).+ */+async function writeRestoreMarker(+ client: ServiceRole,+ args: {+ companyId: string;+ restoreRunId: string;+ patch: Partial<RestoreMeta>;+ /** Required only when the marker doesn't exist yet (first write). */+ userId?: string;+ }+): Promise<void> {+ const { companyId, userId, restoreRunId, patch } = args;+ const existing = await readRestoreMarker(client, companyId, restoreRunId);+ const metadata: RestoreMeta = {+ restoreRunId,+ status: "running",+ ...existing?.metadata,+ ...patch+ };++ if (existing) {+ await client+ .from("externalIntegrationMapping")+ .update({+ metadata,+ externalId: metadata.snapshotPath ?? ""+ })+ .eq("id", existing.id)+ .eq("companyId", companyId);+ } else {+ await client.from("externalIntegrationMapping").insert({+ entityType: "restore",+ entityId: restoreRunId,+ integration: RESTORE_INTEGRATION,+ externalId: metadata.snapshotPath ?? "",+ metadata,+ companyId,+ createdBy: userId ?? ""+ });+ }+}++async function deleteRestoreMarker(+ client: ServiceRole,+ companyId: string,+ restoreRunId: string+): Promise<void> {+ await client+ .from("externalIntegrationMapping")+ .delete()+ .eq("integration", RESTORE_INTEGRATION)+ .eq("companyId", companyId)+ .filter("metadata->>restoreRunId", "eq", restoreRunId);+}++/**+ * In-place restore. Snapshots the company's current state to a hidden+ * `_pre-restore` file, wipes the company's data, then loads the backup. A+ * marker row records the snapshot path so the restore can be kept or reverted.+ */+export const companyRestoreFunction = inngest.createFunction(+ {+ id: "company-restore",+ retries: 1,+ concurrency: {+ // Shared across restore/finalize/revert (env scope + common key) so the+ // three never run concurrently for the same company.+ key: "'company-restore-' + event.data.companyId",+ scope: "env",+ limit: 1+ }+ },+ { event: "carbon/company-restore" },+ async ({ event, step }) => {+ const { companyId, userId, filePath, restoreRunId, label, includeStorage } =+ event.data;++ return await step.run("restore-company", async () => {+ const client = getCarbonServiceRole();+ const db = getJobDatabaseClient(1);++ // Idempotency — a retry after the run already reached a terminal state+ // must not wipe again.+ const existing = await readRestoreMarker(client, companyId, restoreRunId);+ if (existing && existing.metadata.status === "ready") {+ console.log("Restore already applied, skipping", { restoreRunId });+ return { restoreRunId, skipped: true };+ }++ // Marker exists from the first heartbeat onward, so the UI can tell+ // "running" from "failed" rather than inferring from absence.+ await writeRestoreMarker(client, {+ companyId,+ userId,+ restoreRunId,+ patch: { status: "running", label: label ?? null }+ });++ try {+ const backup = await downloadBackup(client, companyId, filePath);+ const targetGroupId = await getCompanyGroupId(client, companyId);++ // Group-scoped data (chart of accounts, currencies, dimensions) is shared+ // by every company in the group. We only wipe/reload it when this company+ // is the group's SOLE member — then the group is effectively this+ // company's, so a restore (own or foreign) covers it fully. In a+ // multi-company group it's left untouched and managed at the group level.+ const groupCompanyCount = targetGroupId+ ? ((+ await client+ .from("company")+ .select("id", { count: "exact", head: true })+ .eq("companyGroupId", targetGroupId)+ ).count ?? 1)+ : 0;+ const includeGroup = groupCompanyCount === 1;++ // A backup from ANOTHER company must re-stamp the chart of accounts onto+ // this group, so it's only allowed when the group is this company's alone.+ const foreign = backup.manifest.sourceCompanyId !== companyId;+ if (foreign && !includeGroup) {+ throw new Error(+ !targetGroupId+ ? "This backup is from a different company and carries a chart of " ++ "accounts, but this company has no group to receive it."+ : "This backup belongs to a different company. Restoring it " ++ "replaces shared data (chart of accounts) used by the other " ++ "companies in this group, so it's only allowed in a " ++ "single-company environment."+ );+ }++ const catalog = await getCompanyTableCatalog(db);+ const compatibility = assertBackupImportable(catalog, backup);+ if (!compatibility.ok) {+ throw new Error(+ `This backup can't be restored: ${compatibility.reason}.`+ );+ }++ // 1. Snapshot current state (incl. storage) so a revert can undo this.+ // IDEMPOTENT: if a prior attempt already recorded a snapshot, reuse+ // it — never re-snapshot, or a retry after the wipe committed would+ // capture the WIPED state and overwrite the real pre-restore copy.+ let snapshotPath = existing?.metadata.snapshotPath ?? undefined;+ if (!snapshotPath) {+ const snapshot = await buildCompanyBackup(client, db, {+ companyId,+ userId,+ label: `Pre-restore ${restoreRunId}`,+ includeStorage: "all"+ });+ snapshotPath = `${EXPORTS_PREFIX}/_pre-restore-${restoreRunId}.carbon.json.gz`;+ const snapshotUpload = await client.storage+ .from(companyId)+ .upload(snapshotPath, snapshot.compressed, {+ contentType: "application/gzip",+ upsert: true+ });+ if (snapshotUpload.error) {+ throw new Error(+ `Failed to snapshot before restore: ${snapshotUpload.error.message}`+ );+ }+ await writeRestoreMarker(client, {+ companyId,+ userId,+ restoreRunId,+ patch: { snapshotPath, foreign, includeGroup }+ });+ }++ // 2. Wipe + load (atomic). If this throws, the transaction rolls back —+ // the company's data is untouched and the marker goes to "failed".+ // Re-running on retry is safe: the wipe clears before the load, so a+ // second pass produces the same result. Foreign backups remap ids ++ // scope (and the group-scoped accounts).+ const { rows, idRewrite } = await wipeAndLoad(db, catalog, backup, {+ companyId,+ userId,+ remap: foreign,+ includeGroup,+ targetGroupId+ });++ // 3. Terminal: mark ready as soon as the data is committed — BEFORE the+ // (best-effort, non-transactional) file restore, so a storage hiccup+ // can't flip a committed restore back to "failed".+ await writeRestoreMarker(client, {+ companyId,+ userId,+ restoreRunId,+ patch: { status: "ready", rows }+ });++ // Files are optional, and the data is already committed — never let a+ // file error fail the run. A revert restores files from the snapshot.+ if (includeStorage === "all") {+ try {+ await restoreStorage(client, backup, { companyId, idRewrite });+ } catch (storageErr) {+ console.warn("Restore: file restore failed (data is intact)", {+ restoreRunId,+ error:+ storageErr instanceof Error+ ? storageErr.message+ : String(storageErr)+ });+ }+ }++ console.log("Company restore complete — pending keep/revert", {+ companyId,+ restoreRunId,+ rows,+ foreign,+ snapshotPath+ });+ return { restoreRunId, rows, snapshotPath };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ await writeRestoreMarker(client, {+ companyId,+ userId,+ restoreRunId,+ patch: { status: "failed", error: message }+ });+ console.error("Company restore failed", {+ companyId,+ restoreRunId,+ error: message+ });+ throw err;+ }+ });+ }+);++/** Keep an in-place restore — delete the pre-restore snapshot + marker. */+export const companyRestoreFinalizeFunction = inngest.createFunction(+ {+ id: "company-restore-finalize",+ retries: 1,+ concurrency: {+ // Shared across restore/finalize/revert (env scope + common key) so the+ // three never run concurrently for the same company.+ key: "'company-restore-' + event.data.companyId",+ scope: "env",+ limit: 1+ }+ },+ { event: "carbon/company-restore-finalize" },+ async ({ event, step }) => {+ const { companyId, restoreRunId } = event.data;++ return await step.run("finalize-restore", async () => {+ const client = getCarbonServiceRole();+ const marker = await readRestoreMarker(client, companyId, restoreRunId);+ const snapshotPath = marker?.metadata.snapshotPath;++ if (snapshotPath) {+ await client.storage.from(companyId).remove([snapshotPath]);+ }+ await deleteRestoreMarker(client, companyId, restoreRunId);++ console.log("Company restore kept", { companyId, restoreRunId });+ return { restoreRunId, kept: true };+ });+ }+);++/** Undo an in-place restore — wipe again and reload the pre-restore snapshot. */+export const companyRestoreRevertFunction = inngest.createFunction(+ {+ id: "company-restore-revert",+ retries: 1,+ concurrency: {+ // Shared across restore/finalize/revert (env scope + common key) so the+ // three never run concurrently for the same company.+ key: "'company-restore-' + event.data.companyId",+ scope: "env",+ limit: 1+ }+ },+ { event: "carbon/company-restore-revert" },+ async ({ event, step }) => {+ const { companyId, restoreRunId } = event.data;++ return await step.run("revert-restore", async () => {+ const client = getCarbonServiceRole();+ const db = getJobDatabaseClient(1);++ const marker = await readRestoreMarker(client, companyId, restoreRunId);+ const snapshotPath = marker?.metadata.snapshotPath;+ if (!snapshotPath) {+ console.log("Nothing to revert — no snapshot on marker", {+ restoreRunId+ });+ return { restoreRunId, reverted: false };+ }++ // Flag the run as reverting so the progress modal can show it live.+ await writeRestoreMarker(client, {+ companyId,+ restoreRunId,+ patch: { status: "reverting" }+ });++ try {+ // The snapshot is THIS company's own pre-restore data — ids and scope+ // already belong here, so it loads verbatim (no remap, no ownership+ // check). Wipe + reload the SAME scope the forward restore touched so the+ // undo is exact — including group data (chart of accounts) when the+ // forward run covered it.+ const snapshot = await downloadBackup(client, companyId, snapshotPath);+ const targetGroupId = await getCompanyGroupId(client, companyId);+ const catalog = await getCompanyTableCatalog(db);+ const { rows, idRewrite } = await wipeAndLoad(db, catalog, snapshot, {+ companyId,+ userId: "",+ remap: false,+ includeGroup: marker?.metadata.includeGroup ?? false,+ targetGroupId+ });+ await restoreStorage(client, snapshot, { companyId, idRewrite });++ await client.storage.from(companyId).remove([snapshotPath]);+ await deleteRestoreMarker(client, companyId, restoreRunId);++ console.log("Company restore reverted", {+ companyId,+ restoreRunId,+ rows+ });+ return { restoreRunId, reverted: true, rows };+ } catch (err) {+ const message = err instanceof Error ? err.message : String(err);+ // Leave the marker (with the snapshot still set) so the user can retry+ // the revert; surface the failure.+ await writeRestoreMarker(client, {+ companyId,+ restoreRunId,+ patch: { status: "failed", error: `Revert failed: ${message}` }+ });+ console.error("Company restore revert failed", {+ companyId,+ restoreRunId,+ error: message+ });+ throw err;+ }+ });+ }+);diff --git a/packages/jobs/src/inngest/functions/tasks/index.ts b/packages/jobs/src/inngest/functions/tasks/index.tsindex a66740cb9e..4958ed8d85 100644--- a/packages/jobs/src/inngest/functions/tasks/index.ts+++ b/packages/jobs/src/inngest/functions/tasks/index.ts@@ -1,3 +1,10 @@+export { companyExportFunction } from "./company-export";+export { companyImportFunction } from "./company-import";+export {+ companyRestoreFinalizeFunction,+ companyRestoreFunction,+ companyRestoreRevertFunction+} from "./company-restore";export { modelThumbnailFunction } from "./model-thumbnail";export { onboardFunction } from "./onboard";export { postTransactionFunction } from "./post-transaction";diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.tsindex 85598ffacb..2cdee57fdd 100644--- a/packages/jobs/src/inngest/index.ts+++ b/packages/jobs/src/inngest/index.ts@@ -39,6 +39,11 @@ import {weeklyFunction} from "./functions/scheduled";import {+ companyExportFunction,+ companyImportFunction,+ companyRestoreFinalizeFunction,+ companyRestoreFunction,+ companyRestoreRevertFunction,modelThumbnailFunction,onboardFunction,postTransactionFunction,@@ -65,6 +70,11 @@ export const functions = [workflowFunction,embeddingFunction,// Tasks+ companyExportFunction,+ companyImportFunction,+ companyRestoreFunction,+ companyRestoreFinalizeFunction,+ companyRestoreRevertFunction,modelThumbnailFunction,updatePermissionsFunction,recalculateFunction,diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex 99d4f84868..e2f4e792f7 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -64,6 +64,76 @@ export type Events = {};};+ // Company backup export — snapshot all company-scoped rows (and+ // optionally storage files) into a gzipped backup in the company bucket+ "carbon/company-export": {+ data: {+ companyId: string;+ userId: string;+ label?: string;+ includeStorage: "none" | "all";+ };+ };++ // Company backup import — two-phase: rows are inserted alongside an+ // externalIntegrationMapping ledger (integration = 'company-backup'),+ // then the user finalizes (keeps) or reverts (deletes) the run+ "carbon/company-import": {+ data: {+ companyId: string;+ userId: string;+ filePath: string;+ mode: "preserve" | "reseed";+ importRunId: string;+ /** Delete the revert ledger as soon as the import commits (no pending+ * review step). Used by onboarding-from-template. */+ autoFinalize?: boolean;+ /** Set when the source is an onboarding demo template. The template's+ * storage assets live once per workspace at `_templates/<industryId>/`+ * (uploaded at deploy), so the import REFERENCES them instead of copying+ * files into `{companyId}/` — storage path columns are rewritten to the+ * shared prefix and no per-company file upload happens. Absent for real+ * backups, which stay self-contained (files embedded + copied). */+ templateIndustryId?: string;+ };+ };++ // In-place restore — replace a company's own data with one of its backups.+ // Three-step: snapshot current state to a hidden _pre-restore file, WIPE the+ // company's companyId-scoped data, then load the backup (ids preserved). A+ // marker row (integration = 'company-restore') holds the snapshot path so the+ // restore can be kept or reverted. Distinct from carbon/company-import, which+ // is additive (reseed/onboarding) and never wipes.+ "carbon/company-restore": {+ data: {+ companyId: string;+ userId: string;+ /** The backup to restore (in this company's bucket, `exports/…`). */+ filePath: string;+ restoreRunId: string;+ /** Whether to also load the backup's bundled files. Data always loads. */+ includeStorage: "none" | "all";+ label?: string;+ };+ };++ // Keep an in-place restore — drop the hidden pre-restore snapshot + marker.+ "carbon/company-restore-finalize": {+ data: {+ companyId: string;+ restoreRunId: string;+ };+ };++ // Undo an in-place restore — wipe again and reload the pre-restore snapshot,+ // returning the company to its pre-restore state, then drop snapshot + marker.+ "carbon/company-restore-revert": {+ data: {+ companyId: string;+ restoreRunId: string;+ };+ };+// Permission updates"carbon/update-permissions": {data: {diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.tsindex 6cbdd100a5..350d32680a 100644--- a/packages/lib/src/trigger.ts+++ b/packages/lib/src/trigger.ts@@ -8,6 +8,11 @@ import { inngest } from "./inngest/client.ts";*/const taskToEvent = {"accounting-backfill": "carbon/accounting-backfill",+ "company-export": "carbon/company-export",+ "company-import": "carbon/company-import",+ "company-restore": "carbon/company-restore",+ "company-restore-finalize": "carbon/company-restore-finalize",+ "company-restore-revert": "carbon/company-restore-revert","model-thumbnail": "carbon/model-thumbnail",notify: "carbon/notify",onboard: "carbon/onboard",diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 9619f475ee..f5fcfd2aa5 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -1106,6 +1106,9 @@ msgstr "Zurück zur Rückverfolgbarkeit"msgid "Backflush"msgstr "Rücklauf"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "Bilanz"@@ -5685,9 +5688,6 @@ msgstr "Benachrichtigung"msgid "Notifications"msgstr "Benachrichtigungen"-msgid "Now let's set up your company"-msgstr "Richten wir jetzt dein Unternehmen ein"-msgid "Number"msgstr "Zahl"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 95f6975d6f..4fd1c497bf 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -1106,6 +1106,9 @@ msgstr "Back to traceability"msgid "Backflush"msgstr "Backflush"+msgid "Backups"+msgstr "Backups"+msgid "Balance Sheet"msgstr "Balance Sheet"@@ -5685,9 +5688,6 @@ msgstr "Notification"msgid "Notifications"msgstr "Notifications"-msgid "Now let's set up your company"-msgstr "Now let's set up your company"-msgid "Number"msgstr "Number"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex aa8cb05a39..eb71d4391b 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -1106,6 +1106,9 @@ msgstr "Volver a trazabilidad"msgid "Backflush"msgstr "Retroceso"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "Balance General"@@ -5685,9 +5688,6 @@ msgstr "Notificación"msgid "Notifications"msgstr "Notificaciones"-msgid "Now let's set up your company"-msgstr "Ahora configuremos tu empresa"-msgid "Number"msgstr "Número"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 46130f2f34..45cfebaf98 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -1106,6 +1106,9 @@ msgstr "Retour à la traçabilité"msgid "Backflush"msgstr "Retrait automatique"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "Bilan"@@ -5685,9 +5688,6 @@ msgstr "Notification"msgid "Notifications"msgstr "Notifications"-msgid "Now let's set up your company"-msgstr "Maintenant, configurons votre entreprise"-msgid "Number"msgstr "Nombre"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 9fcb44a2ca..837619540b 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -1106,6 +1106,9 @@ msgstr "ट्रेसेबिलिटी पर वापस जाएं"msgid "Backflush"msgstr "बैकफ्लश"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "बैलेंस शीट"@@ -5685,9 +5688,6 @@ msgstr "सूचना"msgid "Notifications"msgstr "सूचनाएं"-msgid "Now let's set up your company"-msgstr "अब अपनी कंपनी सेट अप करते हैं"-msgid "Number"msgstr "संख्या"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex f36b5244de..74607ac736 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -1106,6 +1106,9 @@ msgstr "Torna alla tracciabilità"msgid "Backflush"msgstr "Scarico automatico"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "Bilancio"@@ -5685,9 +5688,6 @@ msgstr "Notifica"msgid "Notifications"msgstr "Notifiche"-msgid "Now let's set up your company"-msgstr "Ora configuriamo la tua azienda"-msgid "Number"msgstr "Numero"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 1355c2cc47..2335f83fc2 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -1106,6 +1106,9 @@ msgstr "トレーサビリティに戻る"msgid "Backflush"msgstr "バックフラッシュ"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "貸借対照表"@@ -5685,9 +5688,6 @@ msgstr "通知"msgid "Notifications"msgstr "通知"-msgid "Now let's set up your company"-msgstr "それでは、あなたの会社をセットアップしましょう"-msgid "Number"msgstr "数字"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex dac427e2bd..0f070f35b0 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -1106,6 +1106,9 @@ msgstr "Wróć do śledzenia"msgid "Backflush"msgstr "Cofnięcie"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "Bilans"@@ -5685,9 +5688,6 @@ msgstr "Powiadomienie"msgid "Notifications"msgstr "Powiadomienia"-msgid "Now let's set up your company"-msgstr "Teraz skonfigurujmy Twoją firmę"-msgid "Number"msgstr "Liczba"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex cd5cbb6060..f7c0340e56 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -1106,6 +1106,9 @@ msgstr "Voltar para rastreabilidade"msgid "Backflush"msgstr "Descarga Automática"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "Balanço Patrimonial"@@ -5685,9 +5688,6 @@ msgstr "Notificação"msgid "Notifications"msgstr "Notificações"-msgid "Now let's set up your company"-msgstr "Agora vamos configurar sua empresa"-msgid "Number"msgstr "Número"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 1029e7a07f..b4c805272d 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -1106,6 +1106,9 @@ msgstr "Вернуться к отслеживанию"msgid "Backflush"msgstr "Обратный отвод"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "Баланс"@@ -5685,9 +5688,6 @@ msgstr "Уведомление"msgid "Notifications"msgstr "Уведомления"-msgid "Now let's set up your company"-msgstr "Теперь давайте настроим вашу компанию"-msgid "Number"msgstr "Число"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex a245db0b73..108d260997 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -1106,6 +1106,9 @@ msgstr "İzlenebilirliğe geri dön"msgid "Backflush"msgstr "Geri Akış"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "Bilanço"@@ -5685,9 +5688,6 @@ msgstr "Bildirim"msgid "Notifications"msgstr "Bildirimler"-msgid "Now let's set up your company"-msgstr "Şimdi şirketinizi kuralım"-msgid "Number"msgstr "Numara"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 0f57173adc..ad477113b7 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -1106,6 +1106,9 @@ msgstr "返回可追溯性"msgid "Backflush"msgstr "反冲"+msgid "Backups"+msgstr ""+msgid "Balance Sheet"msgstr "资产负债表"@@ -5685,9 +5688,6 @@ msgstr "通知"msgid "Notifications"msgstr "通知"-msgid "Now let's set up your company"-msgstr "现在让我们设置您的公司"-msgid "Number"msgstr "数字"diff --git a/packages/utils/src/const.ts b/packages/utils/src/const.tsindex 229f22e6a5..984d480859 100644--- a/packages/utils/src/const.ts+++ b/packages/utils/src/const.ts@@ -1,5 +1,16 @@export const SUPPORT_EMAIL = "[email protected]";+/** Carbon-internal email domains — the single source of truth for the+ * "is this a Carbon employee" gate (used both client- and server-side). */+export const INTERNAL_EMAIL_DOMAINS = ["@carbon.us.org", "@carbon.ms"];++/** True for Carbon-internal users; gates internal-only features. Normalizes the+ * address so the client flag and the server gate never diverge on casing. */+export function isInternalEmail(email: string | null | undefined): boolean {+ const normalized = (email ?? "").toLowerCase().trim();+ return INTERNAL_EMAIL_DOMAINS.some((domain) => normalized.endsWith(domain));+}+export const FILE_SIZE_LIMIT_MB = {CAD_MODEL_UPLOAD: 120,DOCUMENT_UPLOAD: 50