Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(models): retain the original model file and always serve original bytes on download

Sidwebworksda0dbc7d26ba
diff --git a/.ai/playbooks/model-original-download.md b/.ai/playbooks/model-original-download.md
new file mode 100644
index 0000000000..5c82469787
--- /dev/null
+++ b/.ai/playbooks/model-original-download.md
@@ -0,0 +1,67 @@
+# Model Original Download (STEP/mesh raw bytes via api/model/download)
+
+Last tested: 2026-07-28
+Routes: `/api/model/download/:modelUploadId` (ERP + MES twins), `/file/preview/:bucket/*`
+
+## What this verifies
+
+Customers must always download the ORIGINAL uploaded bytes — never the
+compacted `.xbf.zst` (OCCT container) or an error body saved as `.step`.
+
+## Prerequisites
+
+- Full stack: docker services + ERP dev server + assembler (`crbn up --all`);
+ MES dev server too for the MES half.
+- Logged in via /auth ([email protected], company `d9h3of1gq0h02k8opfq0`).
+- A STEP fixture: `cargo test -p converter --test multibody_split` writes a
+ valid ~32 KB STEP to `$TMPDIR/carbon-multibody-2/fixture.step` (hermetic,
+ OCCT-generated). Binary STL is trivially synthesized with python struct.
+- `shasum -a 256` the fixture BEFORE uploading — the whole test is hash equality.
+
+## Steps
+
+### 1. Upload without touching the (WebGL-only) viewer page
+The part-details viewer 500s headless. Replicate the app's upload directly:
+- PUT bytes: `POST http://127.0.0.1:$PORT_API/storage/v1/object/temp-staging/{companyId}/models/{modelId}.step` with service-role apikey+bearer.
+- Register (authed browser): `fetch('/api/model/upload', {method:'POST', body: FormData{modelId, name, modelPath, size}})` → `{"success":true}` and model-optimize fires.
+
+### 2. Wait for the pipeline
+Poll psql (port `$PORT_DB`): `select "optimizeStatus","modelPath","originalPath" from "modelUpload" where id='...'`.
+Expected (STEP, assembler on): `Success | {id}.xbf.zst | {id}.step` within ~10-60s.
+Expected (STL): `Success | {id}.stl.zst | NULL` (zstd mode clears originalPath — the `.zst` IS the original).
+Storage check: `select bucket_id,name from storage.objects where name like '%{id}%'` — all three (original, xbf.zst, optimized.glb) land in `private` when ≤50 MB.
+
+### 3. Download + byte-compare (in-browser, no file save needed)
+```js
+fetch('/api/model/download/{modelId}').then(r=>{window.__st=r.status;return r.arrayBuffer()})
+ .then(b=>crypto.subtle.digest('SHA-256',b).then(h=>({status:window.__st,bytes:b.byteLength,
+ sha256:[...new Uint8Array(h)].map(x=>x.toString(16).padStart(2,'0')).join('')})))
+```
+PASS = status 200, sha256 equals the pre-upload fixture hash, content-type
+`application/step` / `application/stl` (proxy decompresses `.zst` server-side).
+
+### 4. Negative cases
+- Legacy row (insert a modelUpload with `modelPath='....xbf.zst'`, null originalPath) → download route returns **404** (client shows toast, never saves bytes).
+- `/file/preview/private/{companyId}/models/does-not-exist.step` → **404** (not 500).
+
+### 5. MES
+Open `https://mes.<prefix>.dev/login` (portless host — cookies shared with ERP;
+navigating to a raw `127.0.0.1:PORT` URL loses them). Repeat step 3/4 fetches.
+
+## Selector Notes
+- Login: fill email textbox, then `form.requestSubmit(submitButton)` — a click
+ does nothing (ValidatedForm).
+- No UI clicking needed for this test — it's all authed fetch + psql.
+
+## Common Failures
+- "User record not found" on login → docker stack partially down (postgrest/kong);
+ `docker compose ... --project-directory . up -d` (MUST pass `--project-directory .`
+ — compose volume paths are repo-root-relative; without it kong mounts a
+ phantom directory and crashloops on `kong.yml: Is a directory`).
+- MES fetch returns 200 + wrong hash (~33 KB) → you got the login page HTML;
+ authenticate on the MES portless host first.
+- `await` in agent-browser eval → SyntaxError; return promise chains.
+
+## Observed numbers (2026-07-28)
+- 32,572 B STEP → 1,153 B `.xbf.zst` + retained original (retention cost trivial).
+- Full upload→optimize→compact pipeline settled in <10 s locally.
diff --git a/apps/erp/app/components/Documents.tsx b/apps/erp/app/components/Documents.tsx
index 4d30755a8b..8982c86ad6 100644
--- a/apps/erp/app/components/Documents.tsx
+++ b/apps/erp/app/components/Documents.tsx
@@ -37,6 +37,7 @@ import { useDateFormatter, usePermissions, useUser } from "~/hooks";
import type { OptimisticFileObject } from "~/modules/shared";
import { getDocumentType } from "~/modules/shared";
import type { ModelUpload, StorageItem } from "~/types";
+import { downloadModelFile } from "~/utils/download";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
@@ -123,26 +124,11 @@ const Documents = ({
const downloadModel = useCallback(
async (model: ModelUpload) => {
- if (!model.modelPath || !model.modelName) {
- toast.error(t`Model data is missing`);
- return;
- }
-
- const url = path.to.file.previewFile(`temp-staging/${model.modelPath}`);
- try {
- const response = await fetch(url);
- const blob = await response.blob();
- const blobUrl = window.URL.createObjectURL(blob);
- const a = document.createElement("a");
- document.body.appendChild(a);
- a.href = blobUrl;
- a.download = model.modelName;
- a.click();
- window.URL.revokeObjectURL(blobUrl);
- document.body.removeChild(a);
- } catch (error) {
+ const result = await downloadModelFile(model);
+ if (result === "unavailable") {
+ toast.error(t`The original model file is no longer available`);
+ } else if (result === "error") {
toast.error(t`Error downloading file`);
- logger.error("Error", { error: error });
}
},
diff --git a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
index f41ece9713..3dad1d661d 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -38,6 +38,7 @@ import { useDateFormatter, usePermissions, useUser } from "~/hooks";
import type { ItemType, OptimisticFileObject } from "~/modules/shared";
import { getDocumentType } from "~/modules/shared";
import type { ModelUpload } from "~/types";
+import { downloadModelFile } from "~/utils/download";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
import type { ItemFile } from "../../types";
@@ -364,31 +365,11 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
const downloadModel = useCallback(
async (model: ModelUpload) => {
- if (!model.modelPath || !model.modelName) {
- toast.error(t`Model data is missing`);
- return;
- }
-
- if (!model.modelPath || !model.modelName) {
- toast.error(t`Model data is missing`);
- return;
- }
-
- const url = path.to.file.previewFile(`temp-staging/${model.modelPath}`);
- try {
- const response = await fetch(url);
- const blob = await response.blob();
- const blobUrl = window.URL.createObjectURL(blob);
- const a = document.createElement("a");
- document.body.appendChild(a);
- a.href = blobUrl;
- a.download = model.modelName;
- a.click();
- window.URL.revokeObjectURL(blobUrl);
- document.body.removeChild(a);
- } catch (error) {
+ const result = await downloadModelFile(model);
+ if (result === "unavailable") {
+ toast.error(t`The original model file is no longer available`);
+ } else if (result === "error") {
toast.error(t`Error downloading file`);
- logger.error("Error", { error: error });
}
},
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
index 1bfdcca83f..47d5f7baca 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
@@ -45,6 +45,7 @@ import { useDateFormatter, usePermissions, useUser } from "~/hooks";
import type { OptimisticFileObject } from "~/modules/shared";
import { getDocumentType } from "~/modules/shared";
import type { ModelUpload } from "~/types";
+import { downloadModelFile } from "~/utils/download";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
@@ -114,26 +115,11 @@ const useJobDocuments = ({
const downloadModel = useCallback(
async (model: ModelUpload) => {
- if (!model.modelPath || !model.modelName) {
- toast.error(t`Model data is missing`);
- return;
- }
-
- const url = path.to.file.previewFile(`temp-staging/${model.modelPath}`);
- try {
- const response = await fetch(url);
- const blob = await response.blob();
- const blobUrl = window.URL.createObjectURL(blob);
- const a = document.createElement("a");
- document.body.appendChild(a);
- a.href = blobUrl;
- a.download = model.modelName;
- a.click();
- window.URL.revokeObjectURL(blobUrl);
- document.body.removeChild(a);
- } catch (error) {
+ const result = await downloadModelFile(model);
+ if (result === "unavailable") {
+ toast.error(t`The original model file is no longer available`);
+ } else if (result === "error") {
toast.error(t`Error downloading file`);
- logger.error("Failed to process file operation", { error });
}
},
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
index 5af7313575..1ab16eb1d0 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
@@ -45,6 +45,7 @@ import { useDateFormatter, usePermissions, useUser } from "~/hooks";
import type { OptimisticFileObject } from "~/modules/shared";
import { getDocumentType } from "~/modules/shared";
import type { ModelUpload } from "~/types";
+import { downloadModelFile } from "~/utils/download";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
@@ -162,26 +163,11 @@ const useOpportunityLineDocuments = ({
const downloadModel = useCallback(
async (model: ModelUpload) => {
- if (!model.modelPath || !model.modelName) {
- toast.error(t`Model data is missing`);
- return;
- }
-
- const url = path.to.file.previewFile(`temp-staging/${model.modelPath}`);
- try {
- const response = await fetch(url);
- const blob = await response.blob();
- const blobUrl = window.URL.createObjectURL(blob);
- const a = document.createElement("a");
- document.body.appendChild(a);
- a.href = blobUrl;
- a.download = model.modelName;
- a.click();
- window.URL.revokeObjectURL(blobUrl);
- document.body.removeChild(a);
- } catch (error) {
+ const result = await downloadModelFile(model);
+ if (result === "unavailable") {
+ toast.error(t`The original model file is no longer available`);
+ } else if (result === "error") {
toast.error(t`Error downloading file`);
- logger.error("Failed to process file operation", { error });
}
},
diff --git a/apps/erp/app/routes/api+/model.download.$modelUploadId.ts b/apps/erp/app/routes/api+/model.download.$modelUploadId.ts
new file mode 100644
index 0000000000..c0454d9e6f
--- /dev/null
+++ b/apps/erp/app/routes/api+/model.download.$modelUploadId.ts
@@ -0,0 +1,62 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { isModelRawDownloadable } from "@carbon/utils";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { path } from "~/utils/path";
+
+// Resolves the DOWNLOADABLE bytes for a model — always the customer's original
+// upload, never a derived artifact. Compaction repoints `modelPath` at an OCCT
+// `.xbf.zst` no CAD tool can open; the original survives at `originalPath`
+// (mesh raws instead keep a `.zst` modelPath that decompresses byte-identical).
+// Redirects into the auth-checked /file/preview proxy, which decompresses `.zst`
+// server-side and sets the content type from the inner extension.
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+ const { modelUploadId } = params;
+ if (!modelUploadId) throw new Response("Not found", { status: 404 });
+
+ const model = await client
+ .from("modelUpload")
+ .select("modelPath, originalPath")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (model.error) throw new Response("Internal error", { status: 500 });
+ if (!model.data) throw new Response("Not found", { status: 404 });
+
+ // Original when tracked; else the raw modelPath as long as it still yields
+ // original bytes (pre-compact raws, mesh `.zst`). `.xbf` never qualifies —
+ // legacy rows compacted before originals were retained have no downloadable
+ // copy (404, surfaced as a toast client-side; never a corrupt file).
+ const candidate =
+ model.data.originalPath ??
+ (model.data.modelPath && isModelRawDownloadable(model.data.modelPath)
+ ? model.data.modelPath
+ : null);
+ if (!candidate) {
+ throw new Response("Original model file is not available", { status: 404 });
+ }
+
+ // Retained raws live in `private` once persisted, or `temp-staging` before
+ // compaction settles / when oversized — probe both (same resolution as the
+ // model.artifacts route).
+ const serviceRole = getCarbonServiceRole();
+ const probe = (bucket: "private" | "temp-staging") =>
+ serviceRole.storage
+ .from(bucket)
+ .info(candidate)
+ .catch(() => ({ data: null, error: true as const }));
+ const durable = await probe("private");
+ let bucket: string | null = !durable.error && durable.data ? "private" : null;
+ if (!bucket) {
+ const staged = await probe("temp-staging");
+ if (!staged.error && staged.data) bucket = "temp-staging";
+ }
+ if (!bucket) {
+ throw new Response("Original model file is not available", { status: 404 });
+ }
+
+ throw redirect(path.to.file.previewFile(`${bucket}/${candidate}`));
+}
diff --git a/apps/erp/app/routes/api+/model.upload.ts b/apps/erp/app/routes/api+/model.upload.ts
index a7ceb67a37..b6b6ce1122 100644
--- a/apps/erp/app/routes/api+/model.upload.ts
+++ b/apps/erp/app/routes/api+/model.upload.ts
@@ -43,6 +43,10 @@ export async function action({ request }: ActionFunctionArgs) {
// Frozen as-uploaded bytes: `size` is later overwritten with the compacted
// (.zst) stored size, but the viewer's reduction badge compares the original.
originalSize: size,
+ // Frozen as-uploaded path: `modelPath` is later repointed at the compacted
+ // artifact (STEP → `.xbf.zst`), but downloads must serve the original bytes.
+ // Mesh compaction nulls this again (its `.zst` decompresses to the original).
+ originalPath: modelPath,
companyId,
createdBy: userId
});
diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
index 9d00acfe86..2ecb56b6ca 100644
--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
@@ -32,7 +32,17 @@ const supportedFileTypes: Record<string, string> = {
fbx: "application/fbx",
ply: "application/ply",
off: "application/off",
- step: "application/step"
+ step: "application/step",
+ stp: "application/step",
+ iges: "application/iges",
+ igs: "application/iges",
+ brep: "application/octet-stream",
+ "3dm": "application/octet-stream",
+ "3ds": "application/octet-stream",
+ "3mf": "model/3mf",
+ amf: "application/octet-stream",
+ bim: "application/octet-stream",
+ dae: "model/vnd.collada+xml"
};
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
@@ -59,8 +69,10 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
const effectiveType = isZst
? path.slice(0, -4).split(".").pop()?.toLowerCase()
: fileType;
+ // Unknown extensions still get a Content-Type — a bare octet-stream beats
+ // omitting the header (browsers may otherwise sniff or mangle the download).
const contentType = effectiveType
- ? supportedFileTypes[effectiveType]
+ ? (supportedFileTypes[effectiveType] ?? "application/octet-stream")
: undefined;
// Authorize against the companyId as a full path segment (prefix or
@@ -93,7 +105,10 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
fileData = await downloadFile();
if (!fileData) {
- throw new Error("Failed to download file after retry");
+ // A missing object is a clean 404, not a 500 — consumers (e.g. the model
+ // download flow) branch on the status; an opaque error page body must
+ // never be saved to disk as if it were the file.
+ return new Response(null, { status: 404 });
}
}
diff --git a/apps/erp/app/utils/download.ts b/apps/erp/app/utils/download.ts
new file mode 100644
index 0000000000..576199ff93
--- /dev/null
+++ b/apps/erp/app/utils/download.ts
@@ -0,0 +1,39 @@
+import { path } from "~/utils/path";
+
+export type ModelDownloadResult = "ok" | "unavailable" | "error";
+
+/**
+ * Download a model's ORIGINAL file bytes via the api/model/download route
+ * (which resolves `originalPath` and redirects through the auth-checked
+ * /file/preview proxy — `.zst` raws are decompressed server-side).
+ *
+ * Returns a result instead of toasting so callers keep their own (localized)
+ * error copy. "unavailable" = no original exists for this model (legacy rows
+ * compacted before originals were retained); "error" = network/server failure.
+ * Never saves a non-OK response body to disk — that is how corrupt "STEP"
+ * downloads were born.
+ */
+export async function downloadModelFile(model: {
+ modelId: string | null;
+ modelName: string | null;
+}): Promise<ModelDownloadResult> {
+ if (!model.modelId || !model.modelName) return "error";
+ try {
+ const response = await fetch(path.to.api.modelDownload(model.modelId));
+ if (!response.ok) {
+ return response.status === 404 ? "unavailable" : "error";
+ }
+ const blob = await response.blob();
+ const blobUrl = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ document.body.appendChild(a);
+ a.href = blobUrl;
+ a.download = model.modelName;
+ a.click();
+ window.URL.revokeObjectURL(blobUrl);
+ document.body.removeChild(a);
+ return "ok";
+ } catch {
+ return "error";
+ }
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 1236d1f128..cc3ff3c46e 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -150,6 +150,8 @@ export const path = {
generatePath(`${api}/model/artifacts/${modelUploadId}`),
modelConvertStatus: (modelUploadId: string) =>
generatePath(`${api}/model/convert-status/${modelUploadId}`),
+ modelDownload: (modelUploadId: string) =>
+ generatePath(`${api}/model/download/${modelUploadId}`),
modelOptimizeCancel: `${api}/model/optimize-cancel`,
modelReoptimize: `${api}/model/reoptimize`,
modelUpload: `${api}/model/upload`,
diff --git a/apps/mes/app/components/JobOperation/hooks/useFiles.tsx b/apps/mes/app/components/JobOperation/hooks/useFiles.tsx
index 8abaf7f047..f49676bcef 100644
--- a/apps/mes/app/components/JobOperation/hooks/useFiles.tsx
+++ b/apps/mes/app/components/JobOperation/hooks/useFiles.tsx
@@ -56,15 +56,26 @@ export function useFiles(job: Job) {
);
const downloadModel = useCallback(
- async (model: { modelPath: string; modelName: string }) => {
- if (!model.modelPath || !model.modelName) {
+ async (model: { modelId: string | null; modelName: string | null }) => {
+ if (!model.modelId || !model.modelName) {
toast.error("Model data is missing");
return;
}
- const url = path.to.file.previewFile(`private/${model.modelPath}`);
+ // The download route resolves the customer's ORIGINAL file — fetching
+ // `modelPath` directly would serve the compacted `.xbf.zst` (an OCCT
+ // container no CAD tool opens) once compaction has repointed it.
+ const url = path.to.api.modelDownload(model.modelId);
try {
const response = await fetch(url);
+ if (!response.ok) {
+ toast.error(
+ response.status === 404
+ ? "The original model file is no longer available"
+ : "Error downloading file"
+ );
+ return;
+ }
const blob = await response.blob();
const blobUrl = window.URL.createObjectURL(blob);
const a = document.createElement("a");
diff --git a/apps/mes/app/routes/api+/model.download.$modelUploadId.ts b/apps/mes/app/routes/api+/model.download.$modelUploadId.ts
new file mode 100644
index 0000000000..c0454d9e6f
--- /dev/null
+++ b/apps/mes/app/routes/api+/model.download.$modelUploadId.ts
@@ -0,0 +1,62 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { isModelRawDownloadable } from "@carbon/utils";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { path } from "~/utils/path";
+
+// Resolves the DOWNLOADABLE bytes for a model — always the customer's original
+// upload, never a derived artifact. Compaction repoints `modelPath` at an OCCT
+// `.xbf.zst` no CAD tool can open; the original survives at `originalPath`
+// (mesh raws instead keep a `.zst` modelPath that decompresses byte-identical).
+// Redirects into the auth-checked /file/preview proxy, which decompresses `.zst`
+// server-side and sets the content type from the inner extension.
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+ const { modelUploadId } = params;
+ if (!modelUploadId) throw new Response("Not found", { status: 404 });
+
+ const model = await client
+ .from("modelUpload")
+ .select("modelPath, originalPath")
+ .eq("id", modelUploadId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (model.error) throw new Response("Internal error", { status: 500 });
+ if (!model.data) throw new Response("Not found", { status: 404 });
+
+ // Original when tracked; else the raw modelPath as long as it still yields
+ // original bytes (pre-compact raws, mesh `.zst`). `.xbf` never qualifies —
+ // legacy rows compacted before originals were retained have no downloadable
+ // copy (404, surfaced as a toast client-side; never a corrupt file).
+ const candidate =
+ model.data.originalPath ??
+ (model.data.modelPath && isModelRawDownloadable(model.data.modelPath)
+ ? model.data.modelPath
+ : null);
+ if (!candidate) {
+ throw new Response("Original model file is not available", { status: 404 });
+ }
+
+ // Retained raws live in `private` once persisted, or `temp-staging` before
+ // compaction settles / when oversized — probe both (same resolution as the
+ // model.artifacts route).
+ const serviceRole = getCarbonServiceRole();
+ const probe = (bucket: "private" | "temp-staging") =>
+ serviceRole.storage
+ .from(bucket)
+ .info(candidate)
+ .catch(() => ({ data: null, error: true as const }));
+ const durable = await probe("private");
+ let bucket: string | null = !durable.error && durable.data ? "private" : null;
+ if (!bucket) {
+ const staged = await probe("temp-staging");
+ if (!staged.error && staged.data) bucket = "temp-staging";
+ }
+ if (!bucket) {
+ throw new Response("Original model file is not available", { status: 404 });
+ }
+
+ throw redirect(path.to.file.previewFile(`${bucket}/${candidate}`));
+}
diff --git a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
index 26a90944e2..ff83522434 100644
--- a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
@@ -32,7 +32,17 @@ const supportedFileTypes: Record<string, string> = {
fbx: "application/fbx",
ply: "application/ply",
off: "application/off",
- step: "application/step"
+ step: "application/step",
+ stp: "application/step",
+ iges: "application/iges",
+ igs: "application/iges",
+ brep: "application/octet-stream",
+ "3dm": "application/octet-stream",
+ "3ds": "application/octet-stream",
+ "3mf": "model/3mf",
+ amf: "application/octet-stream",
+ bim: "application/octet-stream",
+ dae: "model/vnd.collada+xml"
};
export let loader = async ({ request, params }: LoaderFunctionArgs) => {
@@ -51,11 +61,28 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
if (!fileType) {
return new Response(null, { status: 400 });
}
- const contentType = supportedFileTypes[fileType];
+ // Retained CAD raws are stored zstd-compressed (`raw.step.zst`, …) to keep
+ // them from lingering as the fat upload. Decompress on the way out so a
+ // download yields the original, openable file. The content-type + extension
+ // come from the underlying format, not the `.zst` wrapper.
+ const isZst = fileType === "zst";
+ const effectiveType = isZst
+ ? path.slice(0, -4).split(".").pop()?.toLowerCase()
+ : fileType;
+ // Unknown extensions still get a Content-Type — a bare octet-stream beats
+ // omitting the header (browsers may otherwise sniff or mangle the download).
+ const contentType = effectiveType
+ ? (supportedFileTypes[effectiveType] ?? "application/octet-stream")
+ : undefined;
- // Check if the decoded path includes companyId for security
+ // Authorize against the companyId as a full path segment (prefix or
+ // slash-bounded), not a loose substring — `.includes(companyId)` lets
+ // `<otherCo>/.../<yourCompanyId>.pdf` serve another company's private file.
const decodedPath = decodeURIComponent(path);
- if (!decodedPath.includes(companyId)) {
+ const ownsPath =
+ decodedPath.startsWith(`${companyId}/`) ||
+ decodedPath.includes(`/${companyId}/`);
+ if (!ownsPath) {
return new Response(null, { status: 403 });
}
@@ -78,7 +105,10 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
fileData = await downloadFile();
if (!fileData) {
- throw new Error("Failed to download file after retry");
+ // A missing object is a clean 404, not a 500 — consumers (e.g. the model
+ // download flow) branch on the status; an opaque error page body must
+ // never be saved to disk as if it were the file.
+ return new Response(null, { status: 404 });
}
}
@@ -90,5 +120,21 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {
headers.set("Content-Type", contentType);
}
+ if (isZst) {
+ // Stream the storage object through a zstd decompress transform (Node
+ // >=22.15/24) rather than buffering the whole file — the decompressed source
+ // can be large, and this keeps memory flat.
+ const { createZstdDecompress } = await import("node:zlib");
+ const { Readable } = await import("node:stream");
+ const source = Readable.fromWeb(
+ fileData.stream() as import("node:stream/web").ReadableStream
+ );
+ const decompressed = source.pipe(createZstdDecompress());
+ return new Response(
+ Readable.toWeb(decompressed) as unknown as ReadableStream,
+ { status: 200, headers }
+ );
+ }
+
return new Response(fileData, { status: 200, headers });
};
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index fc12278329..f2cc8b303f 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -21,6 +21,8 @@ export const path = {
failureModes: `${api}/failure-modes`,
modelArtifacts: (modelUploadId: string) =>
generatePath(`${api}/model/artifacts/${modelUploadId}`),
+ modelDownload: (modelUploadId: string) =>
+ generatePath(`${api}/model/download/${modelUploadId}`),
modelOptimizeCancel: `${api}/model/optimize-cancel`,
modelReoptimize: `${api}/model/reoptimize`,
pickedAllocation: (jobMaterialId: string) =>
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 0fb6962fc0..3044c99a22 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -50721,6 +50721,159 @@ export default {
tags: ["userAttributeValue"]
}
},
+ "/notificationPreference": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.channel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.topic"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.enabled"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/notificationPreference"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["notificationPreference"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.notificationPreference"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["notificationPreference"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.channel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.topic"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.enabled"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["notificationPreference"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.userId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.channel"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.topic"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.enabled"
+ },
+ {
+ $ref: "#/parameters/rowFilter.notificationPreference.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.notificationPreference"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["notificationPreference"]
+ }
+ },
"/fiscalYearSettings": {
get: {
parameters: [
@@ -55071,6 +55224,9 @@ export default {
{
$ref: "#/parameters/rowFilter.modelUpload.originalSize"
},
+ {
+ $ref: "#/parameters/rowFilter.modelUpload.originalPath"
+ },
{
$ref: "#/parameters/select"
},
@@ -55199,6 +55355,9 @@ export default {
{
$ref: "#/parameters/rowFilter.modelUpload.originalSize"
},
+ {
+ $ref: "#/parameters/rowFilter.modelUpload.originalPath"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -55281,6 +55440,9 @@ export default {
{
$ref: "#/parameters/rowFilter.modelUpload.originalSize"
},
+ {
+ $ref: "#/parameters/rowFilter.modelUpload.originalPath"
+ },
{
$ref: "#/parameters/body.modelUpload"
},
@@ -57036,9 +57198,6 @@ export default {
{
$ref: "#/parameters/rowFilter.agentThread.lastContext"
},
- {
- $ref: "#/parameters/rowFilter.agentThread.archivedAt"
- },
{
$ref: "#/parameters/rowFilter.agentThread.createdBy"
},
@@ -57128,9 +57287,6 @@ export default {
{
$ref: "#/parameters/rowFilter.agentThread.lastContext"
},
- {
- $ref: "#/parameters/rowFilter.agentThread.archivedAt"
- },
{
$ref: "#/parameters/rowFilter.agentThread.createdBy"
},
@@ -57174,9 +57330,6 @@ export default {
{
$ref: "#/parameters/rowFilter.agentThread.lastContext"
},
- {
- $ref: "#/parameters/rowFilter.agentThread.archivedAt"
- },
{
$ref: "#/parameters/rowFilter.agentThread.createdBy"
},
@@ -80589,9 +80742,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.aiAgentEnabled"
- },
{
$ref: "#/parameters/select"
},
@@ -80777,9 +80927,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.aiAgentEnabled"
- },
{
$ref: "#/parameters/preferReturn"
}
@@ -80919,9 +81066,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.plmReleaseControl"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.aiAgentEnabled"
- },
{
$ref: "#/parameters/body.companySettings"
},
@@ -83043,6 +83187,49 @@ export default {
tags: ["(rpc) suppliers_search"]
}
},
+ "/rpc/recompute_service_line_fulfillment": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_sales_order_line_id: {
+ format: "text",
+ type: "string"
+ },
+ p_user_id: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_sales_order_line_id", "p_company_id", "p_user_id"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) recompute_service_line_fulfillment"]
+ }
+ },
"/rpc/get_companies_with_any_role": {
post: {
parameters: [
@@ -89600,6 +89787,51 @@ export default {
tags: ["(rpc) increment_webhook_success"]
}
},
+ "/rpc/sync_job_recompute_service_line": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_new: {
+ format: "jsonb"
+ },
+ p_old: {
+ format: "jsonb"
+ },
+ p_operation: {
+ format: "text",
+ type: "string"
+ },
+ p_table: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_table", "p_operation", "p_new", "p_old"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) sync_job_recompute_service_line"]
+ }
+ },
"/rpc/uuid_generate_v4": {
get: {
produces: [
@@ -116129,6 +116361,56 @@ export default {
},
type: "object"
},
+ notificationPreference: {
+ required: [
+ "id",
+ "userId",
+ "companyId",
+ "channel",
+ "topic",
+ "enabled",
+ "updatedAt"
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ userId: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ channel: {
+ format: "text",
+ type: "string"
+ },
+ topic: {
+ format: "text",
+ type: "string"
+ },
+ enabled: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
+ },
+ updatedAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
fiscalYearSettings: {
required: ["companyId", "startMonth", "taxStartMonth", "updatedBy"],
properties: {
@@ -118443,6 +118725,10 @@ export default {
originalSize: {
format: "bigint",
type: "integer"
+ },
+ originalPath: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -119347,10 +119633,6 @@ export default {
lastContext: {
format: "jsonb"
},
- archivedAt: {
- format: "timestamp with time zone",
- type: "string"
- },
createdBy: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -130810,8 +131092,7 @@ export default {
"assetTaxDepreciationEnabled",
"showSupplierReadableId",
"showCustomerReadableId",
- "plmReleaseControl",
- "aiAgentEnabled"
+ "plmReleaseControl"
],
properties: {
id: {
@@ -131042,11 +131323,6 @@ export default {
default: "enforce",
format: "text",
type: "string"
- },
- aiAgentEnabled: {
- default: true,
- format: "boolean",
- type: "boolean"
}
},
type: "object"
@@ -158266,6 +158542,57 @@ export default {
in: "query",
type: "string"
},
+ "body.notificationPreference": {
+ name: "notificationPreference",
+ description: "notificationPreference",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/notificationPreference"
+ }
+ },
+ "rowFilter.notificationPreference.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.notificationPreference.userId": {
+ name: "userId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.notificationPreference.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.notificationPreference.channel": {
+ name: "channel",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.notificationPreference.topic": {
+ name: "topic",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.notificationPreference.enabled": {
+ name: "enabled",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.notificationPreference.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.fiscalYearSettings": {
name: "fiscalYearSettings",
description: "fiscalYearSettings",
@@ -160966,6 +161293,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.modelUpload.originalPath": {
+ name: "originalPath",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.costLedger": {
name: "costLedger",
description: "costLedger",
@@ -161883,12 +162216,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.agentThread.archivedAt": {
- name: "archivedAt",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.agentThread.createdBy": {
name: "createdBy",
required: false,
@@ -174923,12 +175250,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.companySettings.aiAgentEnabled": {
- name: "aiAgentEnabled",
- required: false,
- in: "query",
- type: "string"
- },
"body.part": {
name: "part",
description: "part",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 92b68b9d46..0ce13ad464 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1971,7 +1971,6 @@ export type Database = {
}
agentThread: {
Row: {
- archivedAt: string | null
companyId: string
createdAt: string
createdBy: string
@@ -1984,7 +1983,6 @@ export type Database = {
userId: string
}
Insert: {
- archivedAt?: string | null
companyId: string
createdAt?: string
createdBy: string
@@ -1997,7 +1995,6 @@ export type Database = {
userId: string
}
Update: {
- archivedAt?: string | null
companyId?: string
createdAt?: string
createdBy?: string
@@ -6660,7 +6657,6 @@ export type Database = {
accountsPayableEmail: string | null
accountsReceivableAddress: boolean | null
accountsReceivableEmail: string | null
- aiAgentEnabled: boolean
assetTaxDepreciationEnabled: boolean
assetTaxRate: number | null
consoleEnabled: boolean
@@ -6705,7 +6701,6 @@ export type Database = {
accountsPayableEmail?: string | null
accountsReceivableAddress?: boolean | null
accountsReceivableEmail?: string | null
- aiAgentEnabled?: boolean
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
consoleEnabled?: boolean
@@ -6750,7 +6745,6 @@ export type Database = {
accountsPayableEmail?: string | null
accountsReceivableAddress?: boolean | null
accountsReceivableEmail?: string | null
- aiAgentEnabled?: boolean
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
consoleEnabled?: boolean
@@ -27980,6 +27974,7 @@ export type Database = {
optimizedSize: number | null
optimizeError: string | null
optimizeStatus: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalPath: string | null
originalSize: number | null
processedAt: string | null
processingError: string | null
@@ -28005,6 +28000,7 @@ export type Database = {
optimizedSize?: number | null
optimizeError?: string | null
optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalPath?: string | null
originalSize?: number | null
processedAt?: string | null
processingError?: string | null
@@ -28030,6 +28026,7 @@ export type Database = {
optimizedSize?: number | null
optimizeError?: string | null
optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalPath?: string | null
originalSize?: number | null
processedAt?: string | null
processingError?: string | null
@@ -63188,14 +63185,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -68221,14 +68218,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -74157,6 +74154,14 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ recompute_service_line_fulfillment: {
+ Args: {
+ p_company_id: string
+ p_sales_order_line_id: string
+ p_user_id: string
+ }
+ Returns: undefined
+ }
resolve_shelf_life_start_for_receipt: {
Args: { p_item_id: string; p_receipt_id: string }
Returns: string
@@ -74371,6 +74376,10 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ sync_job_recompute_service_line: {
+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
+ Returns: undefined
+ }
sync_on_maintenance_dispatch_complete: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 92b68b9d46..0ce13ad464 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -1971,7 +1971,6 @@ export type Database = {
}
agentThread: {
Row: {
- archivedAt: string | null
companyId: string
createdAt: string
createdBy: string
@@ -1984,7 +1983,6 @@ export type Database = {
userId: string
}
Insert: {
- archivedAt?: string | null
companyId: string
createdAt?: string
createdBy: string
@@ -1997,7 +1995,6 @@ export type Database = {
userId: string
}
Update: {
- archivedAt?: string | null
companyId?: string
createdAt?: string
createdBy?: string
@@ -6660,7 +6657,6 @@ export type Database = {
accountsPayableEmail: string | null
accountsReceivableAddress: boolean | null
accountsReceivableEmail: string | null
- aiAgentEnabled: boolean
assetTaxDepreciationEnabled: boolean
assetTaxRate: number | null
consoleEnabled: boolean
@@ -6705,7 +6701,6 @@ export type Database = {
accountsPayableEmail?: string | null
accountsReceivableAddress?: boolean | null
accountsReceivableEmail?: string | null
- aiAgentEnabled?: boolean
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
consoleEnabled?: boolean
@@ -6750,7 +6745,6 @@ export type Database = {
accountsPayableEmail?: string | null
accountsReceivableAddress?: boolean | null
accountsReceivableEmail?: string | null
- aiAgentEnabled?: boolean
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
consoleEnabled?: boolean
@@ -27980,6 +27974,7 @@ export type Database = {
optimizedSize: number | null
optimizeError: string | null
optimizeStatus: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalPath: string | null
originalSize: number | null
processedAt: string | null
processingError: string | null
@@ -28005,6 +28000,7 @@ export type Database = {
optimizedSize?: number | null
optimizeError?: string | null
optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalPath?: string | null
originalSize?: number | null
processedAt?: string | null
processingError?: string | null
@@ -28030,6 +28026,7 @@ export type Database = {
optimizedSize?: number | null
optimizeError?: string | null
optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
+ originalPath?: string | null
originalSize?: number | null
processedAt?: string | null
processingError?: string | null
@@ -63188,14 +63185,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -68221,14 +68218,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -74157,6 +74154,14 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ recompute_service_line_fulfillment: {
+ Args: {
+ p_company_id: string
+ p_sales_order_line_id: string
+ p_user_id: string
+ }
+ Returns: undefined
+ }
resolve_shelf_life_start_for_receipt: {
Args: { p_item_id: string; p_receipt_id: string }
Returns: string
@@ -74371,6 +74376,10 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ sync_job_recompute_service_line: {
+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
+ Returns: undefined
+ }
sync_on_maintenance_dispatch_complete: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
diff --git a/packages/database/supabase/migrations/20260727183030_model-original-path.sql b/packages/database/supabase/migrations/20260727183030_model-original-path.sql
new file mode 100644
index 0000000000..53fb669c48
--- /dev/null
+++ b/packages/database/supabase/migrations/20260727183030_model-original-path.sql
@@ -0,0 +1,6 @@
+-- Track the as-uploaded original model file separately from "modelPath", which
+-- compaction repoints at a derived artifact (STEP → OCCT BinXCAF "{id}.xbf.zst").
+-- The original is what customers download; ".xbf" is not openable by CAD tools.
+-- Null = original not available (legacy rows compacted before this column, or
+-- mesh rows whose ".zst" modelPath decompresses to the identical original bytes).
+ALTER TABLE "modelUpload" ADD COLUMN "originalPath" TEXT;
diff --git a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
index c53abc7af9..b977aef681 100644
--- a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
@@ -414,27 +414,35 @@ export const cleanupFunction = inngest.createFunction(
return;
}
- // Orphans only — never delete an object a modelUpload still points at.
- // A referenced fat raw means compaction hasn't succeeded yet (compact
- // retries independently of optimise); deleting it would destroy the only
- // copy of the model and break assemblies. True strays (upload recorded
- // no row, or the row was repointed/deleted) are the actual dead weight.
- const referenced = await serviceRole
- .from("modelUpload")
- .select("modelPath")
- .in("modelPath", big);
- if (referenced.error) {
+ // Orphans only — never delete an object a modelUpload still points at,
+ // via EITHER column: `modelPath` (a referenced fat raw means compaction
+ // hasn't succeeded yet) or `originalPath` (xbf compaction repoints
+ // `modelPath` at the derived `.xbf.zst` but retains the customer's
+ // original, which must survive for downloads). True strays (upload
+ // recorded no row, or the row was deleted) are the actual dead weight.
+ const [referenced, referencedOriginals] = await Promise.all([
+ serviceRole
+ .from("modelUpload")
+ .select("modelPath")
+ .in("modelPath", big),
+ serviceRole
+ .from("modelUpload")
+ .select("originalPath")
+ .in("originalPath", big)
+ ]);
+ if (referenced.error || referencedOriginals.error) {
logger.error(
"Error resolving referenced staged raws — skipping prune",
{
- error: referenced.error
+ error: referenced.error ?? referencedOriginals.error
}
);
return;
}
- const referencedPaths = new Set(
- (referenced.data ?? []).map((r) => r.modelPath)
- );
+ const referencedPaths = new Set([
+ ...(referenced.data ?? []).map((r) => r.modelPath),
+ ...(referencedOriginals.data ?? []).map((r) => r.originalPath)
+ ]);
const orphans = big.filter((n) => !referencedPaths.has(n));
if (orphans.length === 0) {
logger.info("No orphaned large staged raws to prune", {
diff --git a/packages/jobs/src/inngest/functions/tasks/model-compact.ts b/packages/jobs/src/inngest/functions/tasks/model-compact.ts
index b154781c9c..b9440187d3 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-compact.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-compact.ts
@@ -20,17 +20,21 @@ const MAX_COMPACT_WAIT_MS = 15 * 60 * 1000;
/**
* Persist a model's retained raw to DURABLE storage. Uploads and compaction stage
* in the EPHEMERAL `temp-staging` bucket; the retained raw (the source for the WASM
- * fallback, re-optimise, lazy assembly-plan, and mesh download) must not live there
+ * fallback, re-optimise, lazy assembly-plan, and download) must not live there
* or it is lost when staging is cleared. This function:
*
* - When the assembler is available and the source is a compactable mesh: compacts
* it (STEP → OCCT BinXCAF `{id}.xbf.zst`; mesh → `{id}.{ext}.zst`), then
* relocates the compacted `.zst` to `private` if it fits the 50 MB served cap.
+ * - The customer's ORIGINAL bytes always survive. xbf compaction is a format
+ * conversion (no CAD tool opens `.xbf`), so the original STEP is kept alongside
+ * it — relocated to `private` when ≤ 50 MB, else left in staging tracked by
+ * `modelUpload.originalPath` (the staged-raw sweep spares both columns). zstd
+ * compaction is pure compression (the `.zst` decompresses byte-identical), so
+ * the `.zst` replaces the original and `originalPath` is cleared.
* - Otherwise (assembler off, non-mesh, or already `.zst`): relocates the raw
- * as-is to `private` if it fits.
- * - When it can't fit `private` (> 50 MB): PRUNE the raw if an optimised GLB
- * preview already exists (the preview is enough); else leave it in staging (a
- * big model with no GLB can't render anyway, and it's the only copy).
+ * as-is to `private` if it fits; oversized raws stay in staging (never pruned —
+ * they may be the only copy of the customer's file).
*
* Fired after model-optimize settles (success, failure, or assembler-off skip), so
* a failed/skipped optimise still gets its raw persisted. Own retries.
@@ -51,7 +55,7 @@ export const modelCompactFunction = inngest.createFunction(
const upload = await client
.from("modelUpload")
.select(
- "id, modelPath, size, originalSize, optimizeStatus, optimizedModelPath, glbPath"
+ "id, modelPath, originalPath, size, originalSize, optimizeStatus, optimizedModelPath, glbPath"
)
.eq("id", modelUploadId)
.eq("companyId", companyId)
@@ -67,6 +71,7 @@ export const modelCompactFunction = inngest.createFunction(
);
return {
modelPath: upload.data.modelPath,
+ originalPath: upload.data.originalPath as string | null,
size: upload.data.size as number | null,
originalSize: upload.data.originalSize as number | null,
optimizeStatus: upload.data.optimizeStatus,
@@ -119,23 +124,16 @@ export const modelCompactFunction = inngest.createFunction(
});
return { modelUploadId, status: "Relocated" as const };
}
- if (hasGlb) {
- // Too big for `private`, but the GLB preview survives → prune the raw.
- await client.storage
- .from(RAW_STAGING_BUCKET)
- .remove([model.modelPath]);
- logger.info("oversized raw pruned (GLB preview exists)", {
- modelUploadId,
- modelPath: model.modelPath
- });
- return { modelUploadId, status: "Pruned" as const };
- }
- // Too big AND no GLB — it's the only copy and can't fit durable storage.
- // Leave it in staging (a > 50 MB raw with no GLB can't render anyway).
- logger.warn("oversized raw with no GLB left in staging", {
+ // Too big for `private` — never prune: this object is the only copy of
+ // the customer's file (raw original, or a mesh `.zst` that decompresses
+ // to it), and downloads must always be able to serve the original bytes.
+ // It stays in staging, still referenced by `modelPath`, so the staged-raw
+ // sweep won't touch it.
+ logger.warn("oversized raw left in staging", {
modelUploadId,
modelPath: model.modelPath,
- rawSize
+ rawSize,
+ hasGlb
});
return { modelUploadId, status: "KeptInStaging" as const };
});
@@ -188,21 +186,54 @@ export const modelCompactFunction = inngest.createFunction(
const client = getCarbonServiceRole();
const fits =
compactedSize != null && compactedSize <= MODEL_RAW_KEEP_MAX_BYTES;
+ // xbf compaction is a FORMAT CONVERSION (STEP → OCCT BinXCAF) — the `.zst`
+ // does not decompress back to the customer's STEP, so the original file
+ // must survive alongside it (downloads always serve original bytes).
+ // zstd compaction is pure compression — the `.zst` decompresses to the
+ // byte-identical original, so it REPLACES the original (no duplication)
+ // and `originalPath` is cleared.
+ const isXbf = mode === "xbf";
+
+ // Where the retained original ends up (xbf only): `private` when it fits
+ // the served cap, else it stays in staging — referenced via `originalPath`
+ // so the staged-raw sweep won't prune it.
+ const retainOriginal = async () => {
+ const rawSize = model.originalSize ?? model.size;
+ if (rawSize != null && rawSize <= MODEL_RAW_KEEP_MAX_BYTES) {
+ const err = await moveRawToDurable(client, model.modelPath);
+ // Non-fatal: on failure the original stays in staging, still tracked
+ // by `originalPath` (the download route probes both buckets).
+ if (err) {
+ logger.warn("original raw not relocated — staying in staging", {
+ modelUploadId,
+ originalPath: model.modelPath,
+ error: err
+ });
+ }
+ }
+ };
if (fits) {
- // Relocate the compacted raw to durable storage, repoint `modelPath` at
- // it, then drop the fat original from staging.
+ // Relocate the compacted raw to durable storage and repoint `modelPath`
+ // at it. xbf: also retain the original; zstd: drop the fat original
+ // (the `.zst` IS the original, compressed).
const err = await moveRawToDurable(client, compactPath);
if (err) throw new Error(`relocate compacted raw to durable: ${err}`);
+ if (isXbf) await retainOriginal();
await client
.from("modelUpload")
.update({
modelPath: compactPath,
+ originalPath: isXbf ? model.modelPath : null,
...originalSizeUpdate,
size: compactedSize
})
.eq("id", modelUploadId);
- await client.storage.from(RAW_STAGING_BUCKET).remove([model.modelPath]);
+ if (!isXbf) {
+ await client.storage
+ .from(RAW_STAGING_BUCKET)
+ .remove([model.modelPath]);
+ }
logger.info("raw compacted and relocated to durable", {
modelUploadId,
compactPath,
@@ -212,29 +243,35 @@ export const modelCompactFunction = inngest.createFunction(
}
if (hasGlb) {
- // Compacted raw still exceeds the durable cap, but the GLB preview
- // survives → prune both the compacted output and the original.
- await client.storage
- .from(RAW_STAGING_BUCKET)
- .remove([compactPath, model.modelPath]);
- logger.info("oversized compacted raw pruned (GLB preview exists)", {
+ // Compacted output still exceeds the durable cap, but the GLB preview
+ // survives → prune the compacted artifact (it is derived and can be
+ // regenerated). The ORIGINAL stays in staging, still referenced by
+ // `modelPath` (never repointed on this branch), so downloads and a
+ // later re-compact keep working.
+ await client.storage.from(RAW_STAGING_BUCKET).remove([compactPath]);
+ logger.info("oversized compacted artifact pruned (original kept)", {
modelUploadId,
compactPath
});
- return { modelUploadId, status: "Pruned" as const };
+ return { modelUploadId, status: "KeptInStaging" as const };
}
// Too big for durable AND no GLB — keep the compacted `.zst` in staging
- // (best available), repoint, drop the fat original.
+ // (best available for the viewer/plan) and repoint. xbf: the original also
+ // stays in staging (tracked by `originalPath` for the sweep + downloads);
+ // zstd: drop the fat original (the `.zst` has the bytes).
await client
.from("modelUpload")
.update({
modelPath: compactPath,
+ originalPath: isXbf ? model.modelPath : null,
...originalSizeUpdate,
...(compactedSize != null ? { size: compactedSize } : {})
})
.eq("id", modelUploadId);
- await client.storage.from(RAW_STAGING_BUCKET).remove([model.modelPath]);
+ if (!isXbf) {
+ await client.storage.from(RAW_STAGING_BUCKET).remove([model.modelPath]);
+ }
logger.warn("oversized compacted raw with no GLB kept in staging", {
modelUploadId,
compactPath
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 5dd77fabee..452cb80b20 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Fehlende Lieferanten"
msgid "Mobile Phone"
msgstr "Mobiltelefon"
-msgid "Model data is missing"
-msgstr "Modelldaten fehlen"
-
msgid "Model Number"
msgstr "Modellnummer"
@@ -12698,6 +12695,9 @@ msgstr "Die geordnete Liste der Aufgaben, die Probleme mit diesem Workflow ausf
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "Die geordnete Abfolge von Operationen, die ein Auftrag durchläuft, kopiert aus der Prozeßliste des Verfahrens."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Das ausgehende Buchungsdokument, das Waren aus dem Lager zu einem Kunden herausnimmt und dabei COGS bucht."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 56aebcacec..26ec41905a 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Missing Suppliers"
msgid "Mobile Phone"
msgstr "Mobile Phone"
-msgid "Model data is missing"
-msgstr "Model data is missing"
-
msgid "Model Number"
msgstr "Model Number"
@@ -12698,6 +12695,9 @@ msgstr "The ordered list of tasks issues using this workflow must complete; the
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "The ordered sequence of operations a job runs through, copied from the method's bill of process."
+msgid "The original model file is no longer available"
+msgstr "The original model file is no longer available"
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index b8f862c1a7..99d28dec51 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Proveedores Faltantes"
msgid "Mobile Phone"
msgstr "Teléfono Móvil"
-msgid "Model data is missing"
-msgstr "Los datos del modelo faltan"
-
msgid "Model Number"
msgstr "Número de Modelo"
@@ -12698,6 +12695,9 @@ msgstr "La lista ordenada de tareas que deben completar los problemas que usan e
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "La secuencia ordenada de operaciones que ejecuta un trabajo, copiada de la lista de procesos del método."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "El documento de contabilización de salida que saca bienes del inventario a un cliente, contabilizando COGS en el camino."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 8d11b632b2..2a7242adb1 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Fournisseurs manquants"
msgid "Mobile Phone"
msgstr "Téléphone Mobile"
-msgid "Model data is missing"
-msgstr "Les données du modèle sont manquantes"
-
msgid "Model Number"
msgstr "Numéro de modèle"
@@ -12698,6 +12695,9 @@ msgstr "La liste ordonnée des tâches que les problèmes utilisant ce flux de t
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "La séquence ordonnée des opérations qu'une tâche exécute, copiée de la liste des processus de la méthode."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Le document de comptabilisation sortante qui sort les marchandises du stock vers un client, en comptabilisant le COGS en cours de route."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index dc71163945..c5e3aa0789 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -7709,9 +7709,6 @@ msgstr "आपूर्तिकर्ता गायब हैं"
msgid "Mobile Phone"
msgstr "मोबाइल फोन"
-msgid "Model data is missing"
-msgstr "मॉडल डेटा गायब है"
-
msgid "Model Number"
msgstr "मॉडल नंबर"
@@ -12698,6 +12695,9 @@ msgstr "कार्यों की क्रमित सूची जो इ
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "संचालन का क्रमित क्रम जो एक काम चलाता है, विधि के बिल ऑफ प्रोसेस से कॉपी किया गया।"
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "बाहरी पोस्टिंग दस्तावेज़ जो स्टॉक से माल को ग्राहक के पास ले जाता है, रास्ते में COGS पोस्ट करता है।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 1b513a8f76..74a2df5927 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Fornitori Mancanti"
msgid "Mobile Phone"
msgstr "Telefono Mobile"
-msgid "Model data is missing"
-msgstr "I dati del modello sono mancanti"
-
msgid "Model Number"
msgstr "Numero Modello"
@@ -12698,6 +12695,9 @@ msgstr "L'elenco ordinato delle attività che i problemi che utilizzano questo f
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "La sequenza ordinata delle operazioni che un lavoro esegue, copiata dal distinta base dei processi del metodo."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Il documento di contabilizzazione in uscita che estrae i beni da magazzino a un cliente, contabilizzando COGS mentre procede."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index a5fa686039..3ecb7bf80c 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -7709,9 +7709,6 @@ msgstr "サプライヤーが見つかりません"
msgid "Mobile Phone"
msgstr "携帯電話"
-msgid "Model data is missing"
-msgstr "モデルデータが見つかりません"
-
msgid "Model Number"
msgstr "型番"
@@ -12698,6 +12695,9 @@ msgstr "このワークフローを使用するイシューが完了する必要
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "メソッドのプロセス一覧から コピーされた、ジョブが実行される操作の順序付きシーケンス。"
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "在庫から顧客に商品を取り出す発信転記文書。転記時にCOGSを転記します。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 89c7b1082f..87f1dd9ef7 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -7709,9 +7709,6 @@ msgstr "누락된 공급업체"
msgid "Mobile Phone"
msgstr "휴대전화"
-msgid "Model data is missing"
-msgstr "모델 데이터가 없습니다"
-
msgid "Model Number"
msgstr "모델 번호"
@@ -12698,6 +12695,9 @@ msgstr "이 워크플로를 사용하는 이슈가 완료해야 하는 작업의
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "작업이 거쳐가는 공정작업의 순서로, 방법의 공정(BOP)에서 복사됩니다."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "재화를 재고에서 고객에게 출고시키는 출고 전표로, 진행되면서 매출원가(COGS)를 계상합니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 28fda71681..f298b6d8d2 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Brakujący dostawcy"
msgid "Mobile Phone"
msgstr "Telefon komórkowy"
-msgid "Model data is missing"
-msgstr "Brakuje danych modelu"
-
msgid "Model Number"
msgstr "Numer modelu"
@@ -12698,6 +12695,9 @@ msgstr "Uporządkowana lista zadań, które problemy korzystające z tego przep
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "Uporządkowana sekwencja operacji, przez którą przechodzi zadanie, skopiowana z listy procesów metody."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Dokument buchowania wychodzącego, który wyjmuje towary z magazynu do klienta, księgując COGS w drodze."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 9245ae8985..29ba75418f 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Fornecedores Ausentes"
msgid "Mobile Phone"
msgstr "Telefone Móvel"
-msgid "Model data is missing"
-msgstr "Os dados do modelo estão faltando"
-
msgid "Model Number"
msgstr "Número do Modelo"
@@ -12698,6 +12695,9 @@ msgstr "A lista ordenada de tarefas que os problemas usando este fluxo de trabal
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "A sequência ordenada de operações que um trabalho executa, copiada da lista de processos do método."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "O documento de contabilização de saída que remove bens do estoque para um cliente, contabilizando o COGS no processo."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 36ed0d3377..cf3a78cd04 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Отсутствуют поставщики"
msgid "Mobile Phone"
msgstr "Мобильный телефон"
-msgid "Model data is missing"
-msgstr "Данные модели отсутствуют"
-
msgid "Model Number"
msgstr "Номер модели"
@@ -12698,6 +12695,9 @@ msgstr "Упорядоченный список задач, которые до
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "Упорядоченная последовательность операций, которые выполняет задание, скопированная из расчета процессов метода."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Документ исходящего учета, который выводит товары со склада к клиенту, осуществляя учет себестоимости проданных товаров."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 8c01c701d4..a571b10528 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -7709,9 +7709,6 @@ msgstr "Tedarikçi Eksikleri"
msgid "Mobile Phone"
msgstr "Cep Telefonu"
-msgid "Model data is missing"
-msgstr "Model verisi eksik"
-
msgid "Model Number"
msgstr "Model Numarası"
@@ -12698,6 +12695,9 @@ msgstr "Bu iş akışını kullanan sorunların tamamlaması gereken görevlerin
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "Bir işin çalıştırılmış olduğu işlemlerin sıralanmış sırası, yöntemin süreç faturasından kopyalanmıştır."
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "Malları envanterten bir müşteriye çıkaran ve yol boyunca COGS'yi deftere geçiren giden deftere nakil belgesi."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 24e7238ef1..c461f015ac 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -7709,9 +7709,6 @@ msgstr "缺少供应商"
msgid "Mobile Phone"
msgstr "手机"
-msgid "Model data is missing"
-msgstr "模型数据缺失"
-
msgid "Model Number"
msgstr "型号"
@@ -12698,6 +12695,9 @@ msgstr "使用此工作流的问题必须完成的任务的有序列表;此处
msgid "The ordered sequence of operations a job runs through, copied from the method's bill of process."
msgstr "工作执行的操作的有序序列,从方法的流程清单中复制。"
+msgid "The original model file is no longer available"
+msgstr ""
+
msgid "The outbound posting document that takes goods out of stock to a customer, posting COGS as it goes."
msgstr "将商品从库存中取出给客户的出账凭证,沿途过账销售成本。"
diff --git a/packages/viewer/src/useOptimizedModel.ts b/packages/viewer/src/useOptimizedModel.ts
index 0b5d81a0d9..0c6a53347c 100644
--- a/packages/viewer/src/useOptimizedModel.ts
+++ b/packages/viewer/src/useOptimizedModel.ts
@@ -33,8 +33,10 @@ export type ModelArtifacts = {
/**
* modelUpload.id is the model's filename (`${company}/models/${id}.ext`), so the
* id — and thus its artifact paths — is recoverable from `modelPath` alone.
- * Retained raws are compacted in place (`${id}.step` → `${id}.step.zst`); the
- * `.zst` wrapper is peeled before the source extension.
+ * Compaction repoints `modelPath` at the compacted artifact (STEP →
+ * `${id}.xbf.zst`, mesh → `${id}.{ext}.zst`, with the original STEP retained
+ * separately at `originalPath`); the `.zst` wrapper is peeled before the
+ * source extension.
*/
export function modelIdFromPath(modelPath: string | null): string | null {
if (!modelPath) return null;