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
feat: explain what a restore will change before it runs
aashu0d765759aa74
diff --git a/apps/erp/app/modules/settings/backups.areas.test.ts b/apps/erp/app/modules/settings/backups.areas.test.tsnew file mode 100644index 0000000000..8e205db4e7--- /dev/null+++ b/apps/erp/app/modules/settings/backups.areas.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { BACKUP_SUMMARY_GROUPS, tableArea } from "./backups.areas";++describe("tableArea", () => {+ it("maps a headline entity to its popover group", () => {+ expect(tableArea("salesOrder")).toBe("Sales");+ expect(tableArea("job")).toBe("Production");+ });++ it("maps a child table the popover never lists", () => {+ // The disclosure screen names tables the popover has no headline for, so+ // the map has to reach further than the groups do.+ expect(tableArea("jobOperationDependency")).toBe("Production");+ expect(tableArea("salesOrderLine")).toBe("Sales");+ });++ it("returns Other for an unmapped table rather than guessing", () => {+ expect(tableArea("someTableThatDoesNotExist")).toBe("Other");+ });++ it("keeps every group's own tables consistent with the group title", () => {+ // Guards against the two sources drifting: a table listed under "Quality"+ // in the popover must not resolve to "Items" on the disclosure screen.+ for (const group of BACKUP_SUMMARY_GROUPS) {+ for (const [, table] of group.entities) {+ expect(tableArea(table)).toBe(group.title);+ }+ }+ });+});diff --git a/apps/erp/app/modules/settings/backups.areas.ts b/apps/erp/app/modules/settings/backups.areas.tsnew file mode 100644index 0000000000..3ab9f98c68--- /dev/null+++ b/apps/erp/app/modules/settings/backups.areas.ts@@ -0,0 +1,176 @@+/**+ * Product areas for backup surfaces.+ *+ * One vocabulary, two consumers: the "what's in a backup" popover+ * (`api+/settings.backup-summary.ts`) and the pre-restore disclosure screen. The+ * disclosure screen groups its findings by area rather than by table, because+ * "Production" means something to the person deciding and `jobOperationDependency`+ * does not. Keeping both on the same list is what stops the two screens naming+ * the same data differently.+ */++export type Scope = "company" | "group";++/**+ * `scope` is the column rows are counted by: "company" (companyId, the default)+ * or "group" (companyGroupId — the shared chart of accounts / currencies /+ * dimensions).+ */+export type Entity = [label: string, table: string, scope?: Scope];++/**+ * Recognizable entities a backup carries, grouped for the popover. Not+ * exhaustive — the export covers every scoped table, these are the meaningful+ * headline counts.+ */+export const BACKUP_SUMMARY_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"]] }+];++/** Every table named by the groups above, plus the child tables a compatibility+ * finding is likely to name. Deliberately NOT exhaustive over the ~400 scoped+ * tables — see `tableArea`. */+const TABLE_AREAS: Record<string, string> = {+ ...Object.fromEntries(+ BACKUP_SUMMARY_GROUPS.flatMap((g) =>+ g.entities.map(([, table]) => [table, g.title])+ )+ ),++ // Sales+ quoteLine: "Sales",+ salesOrderLine: "Sales",+ salesInvoiceLine: "Sales",+ shipmentLine: "Sales",+ customerContact: "Sales",+ customerLocation: "Sales",+ opportunity: "Sales",++ // Purchasing+ purchaseOrderLine: "Purchasing",+ purchaseInvoiceLine: "Purchasing",+ receiptLine: "Purchasing",+ supplierContact: "Purchasing",+ supplierLocation: "Purchasing",+ supplierPart: "Purchasing",++ // Items+ item: "Items",+ itemReplenishment: "Items",+ itemPlanning: "Items",+ itemCost: "Items",+ itemUnitSalePrice: "Items",+ makeMethod: "Items",+ methodMaterial: "Items",+ methodOperation: "Items",+ consumable: "Items",+ service: "Items",+ pickMethod: "Items",++ // Production+ jobOperation: "Production",+ jobOperationDependency: "Production",+ jobMakeMethod: "Production",+ jobMaterial: "Production",+ productionEvent: "Production",+ productionQuantity: "Production",+ rework: "Production",+ workCenterProcess: "Production",++ // Inventory — its own area, not in the popover's headline list.+ // `itemLedger` is deliberately absent: the popover already files it under+ // Accounting, and one name in two places is worse than an imperfect name.+ location: "Inventory",+ shelf: "Inventory",+ trackedEntity: "Inventory",+ kanban: "Inventory",+ warehouseTransfer: "Inventory",++ // Accounting+ accountDefault: "Accounting",+ journal: "Accounting",+ costLedger: "Accounting",+ supplierLedger: "Accounting",+ fixedAsset: "Accounting",+ period: "Accounting",+ paymentTerm: "Accounting",++ // Quality+ nonConformanceJobOperation: "Quality",+ inspection: "Quality",+ qualityDocument: "Quality",++ // People+ employeeJob: "People",+ ability: "People"+};++/**+ * The product area a table belongs to, for user-facing copy.+ *+ * Returns `"Other"` for anything unmapped, and that is the honest answer rather+ * than a failure: there are roughly 400 tenant-scoped tables and hand-mapping all+ * of them would be stale within a release. A finding in `"Other"` still shows its+ * exact table name in the details expander, so nothing is hidden — it is just+ * grouped less helpfully. Widen the map when a real finding lands in `"Other"`+ * often enough to matter.+ */+export function tableArea(table: string): string {+ return TABLE_AREAS[table] ?? "Other";+}diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.tsindex 5e9eaa4cc7..0502b32c61 100644--- a/apps/erp/app/modules/settings/backups.service.ts+++ b/apps/erp/app/modules/settings/backups.service.ts@@ -62,6 +62,51 @@ export type CompanyBackupSummary = {rows: number;/** Total bundled asset bytes (the bulk of a backup's footprint). */sizeBytes: number;+ /**+ * Rows the export deliberately left out because a NOT-NULL reference escaped+ * company scope. The backup is still restorable — these rows could never have+ * been. Surfaced so the omission is disclosed rather than silent. Empty for+ * manifests written before the field existed.+ *+ * Carried in FULL, not as a bare count: a restore deletes today's data and+ * replaces it with the backup, so these rows exist right now and will be gone+ * afterwards. `RestoreDisclosure` needs the table to name the product area, and+ * "4 rows excluded" cannot tell anyone which part of their company that is.+ */+ excludedRows: Array<{+ table: string;+ column: string;+ refTable: string;+ rows: number;+ }>;+ /** Sum of `excludedRows[].rows` — the list row shows the number alone. */+ excludedRowCount: number;+ /**+ * The verdict from `compatibility.json`, written beside the manifest by the+ * export job and never refreshed — so `checkedAt` is the export date, and the+ * row's own exported-at line already dates it. Read as a plain file rather than+ * recomputed here: the comparison needs the live schema and lives in+ * `@carbon/jobs`, which app code may not import.+ *+ * A badge is therefore a dated fact, not a live promise. That is deliberate:+ * the hard refusal runs against the live schema inside the restore+ * (`assertBackupImportable`), and `RestoreDisclosure` prints `checkedAt` at the+ * one moment the answer changes a decision. Do not add a job to keep this fresh+ * — one existed and was removed for finding problems nobody was told about.+ *+ * `checkedAt: null` means no verdict has been written yet — the row says "not yet+ * checked", never "not restorable". An absent answer is not a bad one.+ */+ compatibility: {+ checkedAt: string | null;+ status: "ready" | "restorable-with-changes" | "not-restorable";+ findings: Array<{+ kind: "defaulted" | "discarded" | "blocked";+ table: string;+ column?: string;+ reason: string;+ }>;+ };};/**@@ -90,11 +135,35 @@ export async function listCompanyBackups(exportedAt: null,label: null,rows: 0,- sizeBytes: 0+ sizeBytes: 0,+ excludedRows: [],+ excludedRowCount: 0,+ compatibility: { checkedAt: null, status: "ready", findings: [] }};- const mf = await client.storage- .from(companyId)- .download(`exports/${folder.name}/manifest.json`);+ // Both objects are tiny and independent — fetch them together so adding the+ // verdict costs a parallel request, not a second serial round trip per row.+ const [mf, cf] = await Promise.all([+ client.storage+ .from(companyId)+ .download(`exports/${folder.name}/manifest.json`),+ client.storage+ .from(companyId)+ .download(`exports/${folder.name}/compatibility.json`)+ ]);+ if (cf.data) {+ try {+ const c = JSON.parse(+ await cf.data.text()+ ) as CompanyBackupSummary["compatibility"];+ summary.compatibility = {+ checkedAt: c.checkedAt ?? null,+ status: c.status ?? "ready",+ findings: c.findings ?? []+ };+ } catch {+ // Unreadable verdict is the same as an absent one: not yet checked.+ }+ }if (mf.data) {try {const m = JSON.parse(await mf.data.text()) as {@@ -102,6 +171,12 @@ export async function listCompanyBackups(label?: string | null;tables?: Array<{ rows?: number }>;storage?: Array<{ size?: number; included?: boolean }>;+ excludedRows?: Array<{+ table?: string;+ column?: string;+ refTable?: string;+ rows?: number;+ }>;};summary.status = "ready";summary.exportedAt = m.exportedAt ?? null;@@ -113,6 +188,26 @@ export async function listCompanyBackups(summary.sizeBytes = (m.storage ?? []).filter((x) => x.included).reduce((sum, x) => sum + (x.size ?? 0), 0);+ // Absent on manifests predating the field — read as empty, never as+ // "unknown", so an older backup does not display a scary blank. An+ // entry with no table name is dropped rather than rendered as a+ // mystery row: it could not be assigned to a product area anyway.+ summary.excludedRows = (m.excludedRows ?? []).flatMap((x) =>+ x.table+ ? [+ {+ table: x.table,+ column: x.column ?? "",+ refTable: x.refTable ?? "",+ rows: x.rows ?? 0+ }+ ]+ : []+ );+ summary.excludedRowCount = (m.excludedRows ?? []).reduce(+ (sum, x) => sum + (x.rows ?? 0),+ 0+ );} catch {// Manifest present but unreadable — treat as a partial/aborted export// (stays "pending"); still listed by name so the user can delete it.diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupChoices.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupChoices.tsxindex e8e36775f6..46f4587c0c 100644--- a/apps/erp/app/modules/settings/ui/Backups/BackupChoices.tsx+++ b/apps/erp/app/modules/settings/ui/Backups/BackupChoices.tsx@@ -1,4 +1,4 @@-import { Submit, useControlField } from "@carbon/form";+import { useControlField } from "@carbon/form";import { ChoiceSelect } from "@carbon/react";import { LuDatabaseBackup, LuFiles } from "react-icons/lu";@@ -65,10 +65,3 @@ export function RestoreIncludeChoice() {</>);}--// 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/RestoreDisclosure.tsx b/apps/erp/app/modules/settings/ui/Backups/RestoreDisclosure.tsxnew file mode 100644index 0000000000..5580dfe451--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/RestoreDisclosure.tsx@@ -0,0 +1,317 @@+import { useControlField } from "@carbon/form";+import {+ Button,+ Input,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useMemo, useState } from "react";+import { LuCircleAlert, LuInfo, LuTriangleAlert } from "react-icons/lu";+import { tableArea } from "../../backups.areas";+import type { CompanyBackupSummary } from "../../backups.service";+import { formatBackupDate, formatBackupName } from "./format";++/** The word a person types to confirm a restore that discards data. */+const CONFIRM_WORD = "restore";++type Finding = CompanyBackupSummary["compatibility"]["findings"][number];+type Excluded = CompanyBackupSummary["excludedRows"][number];++/**+ * What the person is told before their company's data is replaced.+ *+ * The verdict rendered here is the one stored beside the backup, so this screen+ * costs no schema read and can never disagree with the badge on the list. It is+ * DISCLOSURE, not authorization: the restore job runs the real gate itself, so a+ * verdict that has gone stale since it was written can leave this screen+ * under-informed but can never let through a restore the gate would refuse.+ */+export function RestoreDisclosure({+ backups,+ onConfirm+}: {+ backups: CompanyBackupSummary[];+ onConfirm: (values: { source: string; includeStorage: string }) => void;+}) {+ const { t } = useLingui();+ const [source] = useControlField<string>("source");+ const [includeStorage] = useControlField<string>("includeStorage");+ const [open, setOpen] = useState(false);+ const [typed, setTyped] = useState("");++ const backup = useMemo(+ () => backups.find((b) => `backup:${b.name}` === source),+ [backups, source]+ );++ // An UPLOADED backup is not in the list, so it has no stored verdict. The+ // consequences below still apply and are still shown; only the findings are+ // unknown, which the screen says rather than implying a clean bill of health.+ const findings = backup?.compatibility.findings ?? [];+ const checkedAt = backup?.compatibility.checkedAt ?? null;+ const excluded = backup?.excludedRows ?? [];+ const blocked = findings.some((f) => f.kind === "blocked");+ // Excluded rows count as a discard. They are not in the backup, they DO exist+ // in the company today, and a restore deletes today's data — so confirming+ // this restore loses them for good. That they were unrestorable junk does not+ // make their disappearance something to find out about afterwards.+ const discards =+ findings.some((f) => f.kind === "discarded") || excluded.length > 0;+ const confirmed = !discards || typed.trim().toLowerCase() === CONFIRM_WORD;++ const close = () => {+ setOpen(false);+ setTyped("");+ };++ return (+ <>+ <Button type="button" isDisabled={!source} onClick={() => setOpen(true)}>+ <Trans>Restore…</Trans>+ </Button>++ <Modal+ open={open}+ onOpenChange={(next) => {+ if (!next) close();+ }}+ >+ <ModalContent>+ <ModalHeader>+ <ModalTitle>+ <Trans>Restore this company from a backup</Trans>+ </ModalTitle>+ </ModalHeader>+ <ModalBody>+ <VStack spacing={4}>+ {backup ? (+ <p className="text-sm text-muted-foreground">+ {backup.label || formatBackupName(backup.name)}+ {backup.exportedAt+ ? ` · ${formatBackupDate(backup.exportedAt)}`+ : ""}+ </p>+ ) : (+ <p className="text-sm text-muted-foreground">+ <Trans>+ This backup has not been compared to the current schema yet.+ Differences will be found when the restore runs.+ </Trans>+ </p>+ )}++ {/* Always stated, in this order, findings or not — these are the+ consequences of the operation itself, not of any difference+ between the backup and today's schema. */}+ <VStack spacing={1}>+ <p className="text-sm">+ <Trans>+ Everything in this company today will be deleted and+ replaced with what is in this backup.+ </Trans>+ </p>+ <p className="text-sm">+ <Trans>+ A snapshot of today's data is taken first, before anything+ is deleted.+ </Trans>+ </p>+ <p className="text-sm">+ <Trans>+ Revert puts that snapshot back, exactly as it was.+ </Trans>+ </p>+ <p className="text-sm">+ <Trans>+ Keep drops the snapshot. After Keep, this cannot be undone.+ </Trans>+ </p>+ </VStack>++ {excluded.length > 0 ? (+ <ExcludedRows excluded={excluded} />+ ) : null}++ {findings.length > 0 ? (+ <FindingGroups findings={findings} checkedAt={checkedAt} />+ ) : null}++ {discards ? (+ <VStack spacing={1}>+ <label className="text-sm" htmlFor="restore-confirm">+ {/* Covers both losses above: values the schema will drop,+ and rows the backup never contained. */}+ <Trans>+ Some of your data will not survive this restore. Type{" "}+ <span className="font-medium">{CONFIRM_WORD}</span> to+ continue.+ </Trans>+ </label>+ <Input+ id="restore-confirm"+ value={typed}+ autoComplete="off"+ placeholder={CONFIRM_WORD}+ onChange={(e) => setTyped(e.target.value)}+ />+ </VStack>+ ) : null}+ </VStack>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" onClick={close}>+ <Trans>Cancel</Trans>+ </Button>+ {/* A blocked backup gets no confirm button at all. An explanation+ plus a disabled action reads as "try harder"; the only honest+ next step is to pick a different backup. */}+ {blocked ? null : (+ <Button+ isDisabled={!confirmed}+ onClick={() => {+ onConfirm({+ source: source ?? "",+ includeStorage: includeStorage ?? "all"+ });+ close();+ }}+ >+ {t`Replace this company's data`}+ </Button>+ )}+ </ModalFooter>+ </ModalContent>+ </Modal>+ </>+ );+}++/**+ * Rows the export left out, by product area.+ *+ * Distinct from a `discarded` finding and shown separately: a finding is about+ * the SCHEMA drifting since the backup was taken, this is about rows that were+ * never written to the backup in the first place, and the two have different+ * causes and different fixes. Both are losses, so both gate the typed+ * confirmation.+ *+ * Rendered ABOVE the findings because it is unconditional: a schema finding may+ * not apply to the reader's data, but an excluded row is a row that measurably+ * exists today and will not exist after.+ */+function ExcludedRows({ excluded }: { excluded: Excluded[] }) {+ const total = excluded.reduce((sum, x) => sum + x.rows, 0);+ const areas = [...new Set(excluded.map((x) => tableArea(x.table)))];++ return (+ <VStack spacing={1}>+ <span className="flex items-center gap-1.5 text-sm font-medium">+ <LuTriangleAlert className="h-4 w-4 shrink-0" />+ <Trans>Never included in this backup</Trans>+ </span>+ <span className="text-sm text-muted-foreground">+ <Trans>+ {total} records referenced another company's data, so they could not+ be backed up. They exist today and will be gone after this restore.+ </Trans>+ </span>+ {/* The area, not the table — same rule as the findings below. */}+ <span className="text-sm text-muted-foreground">{areas.join(", ")}</span>+ <details className="text-xs text-muted-foreground">+ <summary className="cursor-pointer">+ <Trans>Details</Trans>+ </summary>+ <ul className="mt-1 flex flex-col gap-0.5 pl-4">+ {excluded.map((x) => (+ <li key={`${x.table}.${x.column}`}>+ <span className="font-mono">+ {x.table}.{x.column}+ </span>+ {" → "}+ <span className="font-mono">{x.refTable}</span>+ {` — ${x.rows}`}+ </li>+ ))}+ </ul>+ </details>+ </VStack>+ );+}++const KIND_ORDER: Finding["kind"][] = ["blocked", "discarded", "defaulted"];++const KIND_ICON = {+ blocked: LuCircleAlert,+ discarded: LuTriangleAlert,+ defaulted: LuInfo+} as const;++/** Findings by kind, then by product area. Table names live in the expander. */+function FindingGroups({+ findings,+ checkedAt+}: {+ findings: Finding[];+ checkedAt: string | null;+}) {+ const { t } = useLingui();+ const kindLabel: Record<Finding["kind"], string> = {+ blocked: t`Cannot be restored`,+ discarded: t`Will be discarded`,+ defaulted: t`Will be filled with a default`+ };++ return (+ <VStack spacing={3}>+ {KIND_ORDER.filter((kind) => findings.some((f) => f.kind === kind)).map(+ (kind) => {+ const forKind = findings.filter((f) => f.kind === kind);+ const Icon = KIND_ICON[kind];+ const areas = [...new Set(forKind.map((f) => tableArea(f.table)))];+ return (+ <VStack key={kind} spacing={1}>+ <span className="flex items-center gap-1.5 text-sm font-medium">+ <Icon className="h-4 w-4 shrink-0" />+ {kindLabel[kind]}+ </span>+ {/* The area, not the table — "Production" means something to the+ person deciding; `jobOperationDependency` does not. */}+ <span className="text-sm text-muted-foreground">+ {areas.join(", ")}+ </span>+ <details className="text-xs text-muted-foreground">+ <summary className="cursor-pointer">+ <Trans>Details</Trans>+ </summary>+ <ul className="mt-1 flex flex-col gap-0.5 pl-4">+ {forKind.map((f) => (+ <li key={`${f.table}.${f.column ?? ""}`}>+ <span className="font-mono">+ {f.table}+ {f.column ? `.${f.column}` : ""}+ </span>+ {" — "}+ {f.reason}+ </li>+ ))}+ </ul>+ </details>+ </VStack>+ );+ }+ )}+ {checkedAt ? (+ <span className="text-xs text-muted-foreground">+ <Trans>Compared to the current schema on</Trans>{" "}+ {formatBackupDate(checkedAt)}+ </span>+ ) : null}+ </VStack>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Backups/format.ts b/apps/erp/app/modules/settings/ui/Backups/format.tsindex 681b46df77..720962dade 100644--- a/apps/erp/app/modules/settings/ui/Backups/format.ts+++ b/apps/erp/app/modules/settings/ui/Backups/format.ts@@ -36,6 +36,54 @@ export function formatElapsed(ms: number): string {return m > 0 ? `${m}m ${String(s % 60).padStart(2, "0")}s` : `${s}s`;}+/**+ * The ONLY five words a backup row is allowed to say about itself. Anything a+ * person reads here they may act on, so the vocabulary is closed: a new state gets+ * added here, with copy, rather than invented at a call site.+ *+ * `ready` doubles as "not yet checked" — a backup whose verdict has not been+ * written is not a problem to report, it is simply a backup nobody has compared to+ * the current schema yet.+ */+export type BackupStatus =+ | "ready"+ | "restorable-with-changes"+ | "not-restorable"+ | "incomplete"+ | "failed";++export function backupStatusLabel(status: BackupStatus): string {+ switch (status) {+ case "ready":+ return "Ready";+ case "restorable-with-changes":+ return "Restorable with changes";+ case "not-restorable":+ return "Not restorable";+ case "incomplete":+ return "Incomplete";+ case "failed":+ return "Failed";+ }+}++/** Which of the four badge colours a status wears. */+export function backupStatusVariant(+ status: BackupStatus+): "green" | "yellow" | "red" | "secondary" {+ switch (status) {+ case "ready":+ return "green";+ case "restorable-with-changes":+ return "yellow";+ case "not-restorable":+ case "failed":+ return "red";+ case "incomplete":+ return "secondary";+ }+}+export function formatBackupDate(iso: string | null | undefined,withTime = truediff --git a/apps/erp/app/modules/settings/ui/Backups/index.ts b/apps/erp/app/modules/settings/ui/Backups/index.tsindex 9d12c5a3e3..1093d82e46 100644--- a/apps/erp/app/modules/settings/ui/Backups/index.ts+++ b/apps/erp/app/modules/settings/ui/Backups/index.ts@@ -3,4 +3,5 @@ export * from "./BackupContentsInfo";export * from "./BackupProgressModal";export * from "./BackupSourcePicker";export * from "./format";+export * from "./RestoreDisclosure";export * from "./RestoreReviewRow";diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 83807a262e..f6851f196b 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-08-22T01:32:58.017Z",+ "generated": "2026-08-25T14:32:40.041Z","totalTools": 1443,"modules": 15,"tools": [diff --git a/apps/erp/app/routes/api+/settings.backup-summary.ts b/apps/erp/app/routes/api+/settings.backup-summary.tsindex 1357b2dab5..80dd0088b1 100644--- a/apps/erp/app/routes/api+/settings.backup-summary.ts+++ b/apps/erp/app/routes/api+/settings.backup-summary.ts@@ -1,73 +1,9 @@import { requirePermissions } from "@carbon/auth/auth.server";import type { SupabaseClient } from "@supabase/supabase-js";import type { LoaderFunctionArgs } from "react-router";+import { BACKUP_SUMMARY_GROUPS } from "~/modules/settings/backups.areas";import { canAccessBackups } from "~/utils/backups";-// 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,@@ -97,7 +33,7 @@ export async function loader({ request }: LoaderFunctionArgs) {throw new Response("Not found", { status: 404 });const groups = await Promise.all(- GROUPS.map(async (group) => {+ BACKUP_SUMMARY_GROUPS.map(async (group) => {const rows = await Promise.all(group.entities.map(async ([label, table, scope]) =>scope === "group"diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsxindex 7dfeca7e73..fb9aea6ce9 100644--- a/apps/erp/app/routes/x+/settings+/backups.tsx+++ b/apps/erp/app/routes/x+/settings+/backups.tsx@@ -11,6 +11,7 @@ import {validator} from "@carbon/form";import {+ Badge,Button,Card,CardContent,@@ -56,16 +57,19 @@ import {revertCompanyRestore,startCompanyRestore} from "~/modules/settings/backups.server";+import type { BackupStatus } from "~/modules/settings/ui/Backups";import {BackupContentsInfo,BackupSourcePicker,+ backupStatusLabel,+ backupStatusVariant,formatBackupDate,formatBackupName,IncludeStorageChoice,JobProgressModal,+ RestoreDisclosure,RestoreIncludeChoice,- RestoreReviewRow,- RestoreSubmit+ RestoreReviewRow} from "~/modules/settings/ui/Backups";import { canAccessBackups } from "~/utils/backups";import { getEdgeFunctionErrorMessage } from "~/utils/error";@@ -452,7 +456,18 @@ export default function BackupsRoute() {</div></CardContent><CardFooter>- <RestoreSubmit />+ {/* The disclosure screen is the only way this form submits — it+ submits through the fetcher rather than the form's own submit+ button, because the modal is portaled outside the <form>. */}+ <RestoreDisclosure+ backups={files.filter((f) => f.status === "ready")}+ onConfirm={({ source, includeStorage }) =>+ fetcher.submit(+ { intent: "restore", source, includeStorage },+ { method: "post" }+ )+ }+ /></CardFooter></ValidatedForm></Card>@@ -520,10 +535,14 @@ export default function BackupsRoute() {<HStack className="w-full justify-between rounded-lg border border-destructive/50 bg-destructive/5 p-3"><VStack spacing={0} className="min-w-0"><span className="text-sm font-medium">Backup failed</span>+ {/* Never "the system", and never "contact support" for+ something the reason already explains — the old copy+ blamed the product for what is usually a data problem+ the message itself names. */}<span className="break-words text-xs text-muted-foreground">- The system created an invalid backup — please contact- Carbon support.- {exportRun?.error ? ` (${exportRun.error})` : null}+ {exportRun?.error+ ? `This backup could not be completed. ${exportRun.error}`+ : "This backup could not be completed."}</span></VStack><Button@@ -592,6 +611,10 @@ function BackupRow({ file }: { file: CompanyBackupSummary }) {);});const name = file.label || formatBackupName(file.name);+ // A half-written folder has no verdict to report — the incompleteness is the+ // whole story, so it outranks whatever compatibility.json may or may not say.+ const status: BackupStatus =+ file.status === "pending" ? "incomplete" : file.compatibility.status;return (<HStack@@ -600,7 +623,12 @@ function BackupRow({ file }: { file: CompanyBackupSummary }) {}`}><VStack spacing={0}>- <span className="text-sm font-medium">{name}</span>+ <HStack spacing={2}>+ <span className="text-sm font-medium">{name}</span>+ <Badge variant={backupStatusVariant(status)}>+ {backupStatusLabel(status)}+ </Badge>+ </HStack><span className="text-xs text-muted-foreground">{file.status === "pending" ? (// A pending folder with no running export is a dead partial — never@@ -615,6 +643,16 @@ function BackupRow({ file }: { file: CompanyBackupSummary }) {{convertKbToString(Math.round(file.sizeBytes / 1024))}</>) : null}+ {/* A number, not an adjective. These rows referenced another+ company's data, so they could never have been restored —+ the backup is complete without them, and saying so beats+ silence. */}+ {file.excludedRowCount > 0 ? (+ <>+ {" · "}+ {file.excludedRowCount.toLocaleString()} rows excluded+ </>+ ) : null}</>)}</span>