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.

2.4 KB
Raw Blame
// 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 { getDatasetAssetUrl } from "@carbon/database/dataset-assets";
import { isUnsafeStoragePath, PRIVATE_PREVIEW_ALIAS } from "../storage";

/**
 * Preview URL for a stored private-bucket file. Demo-template artwork ships
 * with the app, so it never goes through the storage proxy; anything else is
 * a real tenant file served by the apps' /file/preview route.
 */
// A `#` or `?` in a stored filename would otherwise truncate the request path.
const encodeStoragePath = (path: string) =>
  path.split("/").map(encodeURIComponent).join("/");

export const getPrivateUrl = (path: string) => {
  // Private files live in one bucket PER COMPANY and stored paths keep the
  // `${companyId}/...` first segment, so the bucket is that segment. A path
  // with no leading segment falls back to the `private` alias, which the
  // preview route serves from the caller's own company bucket.
  const bucket = path.split("/")[0] || PRIVATE_PREVIEW_ALIAS;
  return (
    getDatasetAssetUrl(path) ??
    `/file/preview/${encodeURIComponent(bucket)}/${encodeStoragePath(path)}`
  );
};

/**
 * Raw model source for the viewer's WASM fallback tier: the company bucket
 * once the raw is durable, `temp-staging` before that.
 */
export const getRawModelUrl = (bucket: string, path: string) => {
  return `/file/preview/${encodeURIComponent(bucket)}/${encodeStoragePath(path)}`;
};

/**
 * Parses a private-bucket job file path — the write side of this contract is
 * the MES step-record upload (`{companyId}/job/{operationId}/{stepId}/{nanoid}/{file}`),
 * the read side the ERP customer-portal file route. Supports both layouts:
 * - legacy flat:   {companyId}/job/{operationId}/{file}
 * - step records:  {companyId}/job/{operationId}/{stepId}/{nanoid}/{file}
 */
export function parseJobFilePath(
  path: string | undefined
): { companyId: string; operationId: string } | null {
  if (!path) return null;
  const [companyId, kind, operationId, ...rest] = path.split("/");
  if (kind !== "job" || !companyId || !operationId) return null;
  if (rest.length !== 1 && rest.length !== 3) return null;
  if (rest.some((segment) => !segment) || isUnsafeStoragePath(path))
    return null;
  return { companyId, operationId };
}