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.7 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 { downloadBlob, downloadUrl } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { toast } from "@carbon/react";
import { useCallback } from "react";
import { useUser } from "~/hooks";
import type { Job, StorageItem } from "~/services/types";
import { path } from "~/utils/path";

const log = getLogger("mes", "job-operation");

export function useFiles(job: Job) {
  const user = useUser();

  const getFilePath = useCallback(
    (file: StorageItem) => {
      if (file.storagePath) return file.storagePath;
      const companyId = user.company.id;
      const { bucket } = file;
      let id: string | null = "";

      switch (bucket) {
        case "job":
          id = job.id;
          break;
        case "opportunity-line":
          id = job.salesOrderLineId ?? job.quoteLineId;
          break;
        case "parts":
          id = file.itemId ?? job.itemId;
          break;
      }

      return `${companyId}/${bucket}/${id}/${file.name}`;
    },
    [job.id, job.itemId, job.quoteLineId, job.salesOrderLineId, user.company.id]
  );

  const downloadFile = useCallback(
    async (file: StorageItem) => {
      const url = path.to.file.previewFile(`private/${getFilePath(file)}`);
      try {
        await downloadUrl(url, file.name);
      } catch (error) {
        toast.error("Error downloading file");
        log.error("Error downloading file", { error });
      }
    },
    [getFilePath]
  );

  const downloadModel = useCallback(
    async (model: { modelId: string | null; modelName: string | null }) => {
      if (!model.modelId || !model.modelName) {
        toast.error("Model data is missing");
        return;
      }

      // 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;
        }
        downloadBlob(await response.blob(), model.modelName);
      } catch (error) {
        toast.error("Error downloading file");
        log.error("Error downloading file", { error });
      }
    },
    []
  );

  return {
    downloadFile,
    downloadModel,
    getFilePath
  };
}