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: show upload progress when uploading a backup for restore
aashub5858f444ef6
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsxindex c8cfe4d4eb..9231389a96 100644--- a/apps/erp/app/components/CadModel.tsx+++ b/apps/erp/app/components/CadModel.tsx@@ -36,7 +36,7 @@ import { useFetcher, useRevalidator } from "react-router";import { useModelUpload, useUser } from "~/hooks";import type { ModelUpload } from "~/types";import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";-import { ModelUploadProgress } from "./ModelUploadProgress";+import { UploadProgress } from "./UploadProgress";const SIZE_LIMIT = getFileSizeLimit("CAD_MODEL_UPLOAD");@@ -281,7 +281,9 @@ const CadModel = ({/>{upload !== null && (<div className="absolute inset-0 z-30 flex items-center justify-center rounded-lg bg-background/95 p-6">- <ModelUploadProgress+ <UploadProgress+ label="Uploading model"+ description="Uploading the CAD file"percent={upload.percent}uploaded={upload.uploaded}total={upload.total}diff --git a/apps/erp/app/components/ModelUploadProgress.tsx b/apps/erp/app/components/UploadProgress.tsxsimilarity index 83%rename from apps/erp/app/components/ModelUploadProgress.tsxrename to apps/erp/app/components/UploadProgress.tsxindex 8d1b51a73f..b430c2ae12 100644--- a/apps/erp/app/components/ModelUploadProgress.tsx+++ b/apps/erp/app/components/UploadProgress.tsx@@ -12,38 +12,42 @@ function formatBytes(n: number): string {return `${n} B`;}-export type ModelUploadProgressProps = {+export type UploadProgressProps = {percent: number;uploaded: number;total: number;+ label: string;+ description: string;className?: string;};/**- * Progress readout for a resumable model upload — the `BarProgress` visual+ * Progress readout for a file upload (CAD models, backup archives) — the `BarProgress` visual* language shared with assembly-convert / backups. Chrome-less on purpose (no* card border/background) so it drops straight into whatever container is* uploading — the dashed dropzone, or an overlay on the 3D viewer.*/-export function ModelUploadProgress({+export function UploadProgress({percent,uploaded,total,+ label,+ description,className-}: ModelUploadProgressProps) {+}: UploadProgressProps) {return (<div className={cn("flex w-full flex-col gap-2.5", className)}><BarProgressprogress={percent}max={100}- label="Uploading model"+ label={label}value={`${Math.round(percent)}%`}activeClassName="bg-primary"/><div className="flex items-center gap-2 text-xs text-muted-foreground"><LuLoaderCircle className="h-3.5 w-3.5 shrink-0 animate-spin text-primary motion-reduce:animate-none" /><span>- Uploading the CAD file ·{" "}+ {description} ·{" "}<span className="tabular-nums">{formatBytes(uploaded)} / {formatBytes(total)}</span>diff --git a/apps/erp/app/hooks/useModelUpload.ts b/apps/erp/app/hooks/useModelUpload.tsindex b96ef2a4e0..a3e68de23c 100644--- a/apps/erp/app/hooks/useModelUpload.ts+++ b/apps/erp/app/hooks/useModelUpload.ts@@ -15,7 +15,7 @@ export type ModelUploadProgress = {/*** Shared resumable (TUS) model-upload logic — the single source of truth for* every CAD upload surface (CadModel, PartForm, ToolForm). Owns the progress- * state (render it with `<ModelUploadProgress {...upload} />`) and swallows the+ * state (render it with `<UploadProgress {...upload} />`) and swallows the* upload into a `{ error }` result so callers keep their existing flow.*/export function useModelUpload() {diff --git a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx b/apps/erp/app/modules/items/ui/Parts/PartForm.tsxindex 6cc3f2bfc5..b21a6f1f4b 100644--- a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartForm.tsx@@ -46,7 +46,7 @@ import {UnitOfMeasure} from "~/components/Form";import { ReplenishmentSystemIcon } from "~/components/Icons";-import { ModelUploadProgress } from "~/components/ModelUploadProgress";+import { UploadProgress } from "~/components/UploadProgress";import {useCompanySettings,useCurrencyDecimals,@@ -386,7 +386,9 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {><input id="model-upload" {...getInputProps()} />{upload !== null ? (- <ModelUploadProgress+ <UploadProgress+ label="Uploading model"+ description="Uploading the CAD file"percent={upload.percent}uploaded={upload.uploaded}total={upload.total}diff --git a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsxindex 04b30a52ee..83e9485e59 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx@@ -45,7 +45,7 @@ import {UnitOfMeasure} from "~/components/Form";import { ReplenishmentSystemIcon, TrackingTypeIcon } from "~/components/Icons";-import { ModelUploadProgress } from "~/components/ModelUploadProgress";+import { UploadProgress } from "~/components/UploadProgress";import {useCompanySettings,useCurrencyDecimals,@@ -370,7 +370,9 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {><input id="model-upload" {...getInputProps()} />{upload !== null ? (- <ModelUploadProgress+ <UploadProgress+ label="Uploading model"+ description="Uploading the CAD file"percent={upload.percent}uploaded={upload.uploaded}total={upload.total}diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsxindex 48072ec26b..c380ceae09 100644--- a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx+++ b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useCarbon } from "@carbon/auth";import { TEMP_STAGING_BUCKET } from "@carbon/files";import { useControlField } from "@carbon/form";import {@@ -18,12 +17,25 @@ import {PopoverTrigger,toast} from "@carbon/react";+import { useLingui } from "@lingui/react/macro";import type { ChangeEvent } from "react";import { useMemo, useRef, useState } from "react";-import { LuArchive, LuChevronsUpDown, LuUpload } from "react-icons/lu";+import {+ LuArchive,+ LuChevronsUpDown,+ LuLoaderCircle,+ LuUpload+} from "react-icons/lu";import { useRevalidator } from "react-router";+import { UploadProgress } from "~/components/UploadProgress";+import { uploadToSignedUrlWithProgress } from "~/utils/signed-upload";import { formatBackupDate, formatBackupName } from "./format";+// The archive's bytes, then the server unpacking it (no byte progress there).+type UploadState =+ | { phase: "uploading"; uploaded: number; total: number }+ | { phase: "unpacking" };+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";@@ -34,11 +46,12 @@ export function BackupSourcePicker({}: {backups: { name: string; label: string | null; exportedAt: string | null }[];}) {- const { carbon } = useCarbon();+ const { t } = useLingui();const revalidator = useRevalidator();const [value, setValue] = useControlField<string>("source");const [open, setOpen] = useState(false);- const [uploading, setUploading] = useState(false);+ const [upload, setUpload] = useState<UploadState | null>(null);+ const uploading = upload !== null;const fileRef = useRef<HTMLInputElement>(null);const current = value ?? "";@@ -55,51 +68,37 @@ export function BackupSourcePicker({e.target.value = "";if (!file) return;if (!file.name.endsWith(".tar.gz") && !file.name.endsWith(".tgz")) {- toast.error("Select a .carbon.tar.gz backup");+ toast.error(t`Select a .carbon.tar.gz backup`);return;}- setUploading(true);- toast.info(`Uploading ${file.name}`);+ setUpload({ phase: "uploading", uploaded: 0, total: file.size });try {// Presigned upload straight to storage (the archive can exceed a// serverless request body), then the server unpacks it into `exports/<name>/`.- const signRes = await fetch("/api/settings/backup-upload", {- method: "POST",- body: toFormData({ intent: "sign" })- });- if (!signRes.ok) {- toast.error(`Failed to upload: ${await signRes.text()}`);- return;- }- const { path, token } = (await signRes.json()) as {+ const { path, token } = await postUploadIntent<{path: string;token: string;- };-- const upload = await carbon.storage- .from(TEMP_STAGING_BUCKET)- .uploadToSignedUrl(path, token, file, {- contentType: "application/gzip"- });- if (upload.error) {- toast.error(`Failed to upload: ${upload.error.message}`);- return;- }-- const res = await fetch("/api/settings/backup-upload", {- method: "POST",- body: toFormData({ intent: "unpack", path })+ }>({ intent: "sign" });+ await uploadToSignedUrlWithProgress({+ bucket: TEMP_STAGING_BUCKET,+ path,+ token,+ file,+ onProgress: (uploaded, total) =>+ setUpload({ phase: "uploading", uploaded, total })+ });+ setUpload({ phase: "unpacking" });+ const { name } = await postUploadIntent<{ name: string }>({+ intent: "unpack",+ path});- if (!res.ok) {- toast.error(`Failed to upload: ${await res.text()}`);- return;- }- const { name } = (await res.json()) as { name: string };setValue(`backup:${name}`);- toast.success("Backup uploaded");+ toast.success(t`Backup uploaded`);revalidator.revalidate();+ } catch (err) {+ toast.error(t`Failed to upload: ${(err as Error).message}`);} finally {- setUploading(false);+ setUpload(null);}};@@ -167,21 +166,42 @@ export function BackupSourcePicker({}}><LuUpload className="mr-2 h-4 w-4 opacity-60" />- {uploading ? "Uploading…" : "Upload new backup…"}+ {uploading ? t`Uploading…` : t`Upload new backup…`}</CommandItem></CommandGroup></CommandList></Command></PopoverContent></Popover>+ {upload?.phase === "uploading" && (+ <UploadProgress+ className="mt-3"+ percent={upload.total ? (upload.uploaded / upload.total) * 100 : 0}+ uploaded={upload.uploaded}+ total={upload.total}+ label={t`Uploading backup`}+ description={t`Uploading the backup file`}+ />+ )}+ {upload?.phase === "unpacking" && (+ <div className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">+ <LuLoaderCircle className="h-3.5 w-3.5 shrink-0 animate-spin text-primary motion-reduce:animate-none" />+ <span>{t`Preparing the backup for restore…`}</span>+ </div>+ )}</>);}-function toFormData(fields: Record<string, string>) {+async function postUploadIntent<T>(fields: Record<string, string>): Promise<T> {const formData = new FormData();for (const [key, value] of Object.entries(fields)) {formData.append(key, value);}- return formData;+ const res = await fetch("/api/settings/backup-upload", {+ method: "POST",+ body: formData+ });+ if (!res.ok) throw new Error(await res.text());+ return (await res.json()) as T;}diff --git a/apps/erp/app/utils/signed-upload.ts b/apps/erp/app/utils/signed-upload.tsnew file mode 100644index 0000000000..92f8dacbf6--- /dev/null+++ b/apps/erp/app/utils/signed-upload.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { SUPABASE_ANON_KEY, SUPABASE_URL } from "@carbon/auth";++/**+ * `storage.uploadToSignedUrl` with upload progress. supabase-js sends the PUT+ * through `fetch`, which exposes no upload progress, so this sends the same+ * request (multipart body, `cacheControl` + the file under an empty field name)+ * over XHR. Use it for paths the user cannot write directly, where the server+ * mints a signed upload token; user-writable paths use `uploadModelResumable`.+ */+export function uploadToSignedUrlWithProgress({+ bucket,+ path,+ token,+ file,+ onProgress+}: {+ bucket: string;+ path: string;+ token: string;+ file: File;+ onProgress: (uploaded: number, total: number) => void;+}): Promise<void> {+ const url = new URL(+ `${SUPABASE_URL}/storage/v1/object/upload/sign/${bucket}/${path}`+ );+ url.searchParams.set("token", token);++ const body = new FormData();+ body.append("cacheControl", "3600");+ body.append("", file);++ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open("PUT", url.toString());+ xhr.setRequestHeader("apikey", SUPABASE_ANON_KEY ?? "");+ xhr.setRequestHeader("x-upsert", "false");+ xhr.upload.onprogress = (e) => {+ if (e.lengthComputable) onProgress(e.loaded, e.total);+ };+ xhr.onload = () => {+ if (xhr.status >= 200 && xhr.status < 300) return resolve();+ reject(new Error(storageErrorMessage(xhr) ?? `HTTP ${xhr.status}`));+ };+ xhr.onerror = () => reject(new Error("Network error"));+ xhr.send(body);+ });+}++function storageErrorMessage(xhr: XMLHttpRequest): string | null {+ try {+ const parsed = JSON.parse(xhr.responseText) as { message?: string };+ return parsed.message ?? null;+ } catch {+ return xhr.responseText || null;+ }+}