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.

14.9 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 { useCarbon } from "@carbon/auth";
import {
  convertKbToString,
  downloadUrl,
  getDocumentType,
  storage
} from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { useRevalidator } from "@carbon/query";
import {
  Card,
  CardAction,
  CardContent,
  CardHeader,
  CardTitle,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  File,
  HStack,
  IconButton,
  MENU_ITEM_SHORTCUTS,
  Table,
  Tbody,
  Td,
  Th,
  Thead,
  Tr,
  toast
} from "@carbon/react";
import { MODEL_RAW_KEEP_MAX_BYTES } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuAxis3D, LuEllipsisVertical, LuUpload } from "react-icons/lu";
import { Link, useFetchers, useSubmit } from "react-router";
import {
  DateTime,
  DocumentPreview,
  FileDropzone,
  Hyperlink,
  ModelOptimizedIndicator
} from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { useFileUpload, usePermissions, useUser } from "~/hooks";
import type { ItemType, OptimisticFileObject } from "~/modules/shared/types";
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";

const logger = getLogger("erp", "itemdocuments");

type ItemDocumentsProps = {
  files: ItemFile[];
  itemId: string;
  modelUpload?: ModelUpload;
  type: ItemType;
  // Read-only: hide the upload affordances and disable delete. Used when the
  // owning record is closed (e.g. a completed/cancelled change notice). Defaults
  // to editable so the part detail page is unchanged.
  isReadOnly?: boolean;
  // Rendered beside the title when the embedding surface locked this card.
  titleExtras?: React.ReactNode;
};

const ItemDocuments = ({
  files,
  itemId,
  modelUpload,
  type,
  isReadOnly = false,
  titleExtras
}: ItemDocumentsProps) => {
  const { t } = useLingui();
  const {
    canDelete,
    download,
    downloadModel,
    deleteFile,
    deleteModel,
    getPath,
    getModelPath,
    upload
  } = useItemDocuments({
    itemId,
    type
  });

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      upload(acceptedFiles);
    },
    [upload]
  );

  const attachmentsByName = new Map<string, FileObject | OptimisticFileObject>(
    files.map((file) => [file.name, file])
  );
  const pendingItems = usePendingItems();
  for (let pendingItem of pendingItems) {
    let item = attachmentsByName.get(pendingItem.name);
    let merged = item ? { ...item, ...pendingItem } : pendingItem;
    attachmentsByName.set(pendingItem.name, merged);
  }

  const allFiles = Array.from(attachmentsByName.values()).sort((a, b) =>
    a.name.localeCompare(b.name)
  ) as FileObject[];

  return (
    <Card className="flex-grow">
      <HStack className="justify-between items-start">
        <CardHeader>
          <CardTitle className="flex flex-row items-center gap-2">
            <Trans>Files</Trans>
            {titleExtras}
          </CardTitle>
        </CardHeader>
        {!isReadOnly && (
          <CardAction>
            <HStack>
              <ItemDocumentForm type={type} itemId={itemId} />
            </HStack>
          </CardAction>
        )}
      </HStack>
      <CardContent>
        <Table>
          <Thead>
            <Tr>
              <Th>
                <Trans>Name</Trans>
              </Th>
              <Th>
                <Trans>Size</Trans>
              </Th>
              <Th>
                <Trans>Created</Trans>
              </Th>
              <Th></Th>
            </Tr>
          </Thead>
          <Tbody>
            {modelUpload?.modelId &&
              (modelUpload.modelSize ?? 0) <= MODEL_RAW_KEEP_MAX_BYTES && (
                <Tr>
                  <Td>
                    <HStack>
                      <LuAxis3D className="text-emerald-500 w-6 h-6" />
                      <Hyperlink target="_blank" to={getModelPath(modelUpload)}>
                        {modelUpload.modelName}
                      </Hyperlink>
                      <ModelOptimizedIndicator
                        modelPath={modelUpload.modelPath}
                      />
                    </HStack>
                  </Td>
                  <Td className="text-xs font-mono">
                    {modelUpload.modelSize
                      ? convertKbToString(
                          Math.floor((modelUpload.modelSize ?? 0) / 1024)
                        )
                      : "--"}
                  </Td>
                  <Td className="text-xs font-mono">--</Td>
                  <Td>
                    <div className="flex justify-end w-full">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <IconButton
                            aria-label={t`More`}
                            icon={<LuEllipsisVertical />}
                            variant="secondary"
                          />
                        </DropdownMenuTrigger>
                        <DropdownMenuContent>
                          <DropdownMenuItem
                            shortcut={MENU_ITEM_SHORTCUTS.view}
                            asChild
                          >
                            <Link to={getModelPath(modelUpload)}>
                              <Trans>View</Trans>
                            </Link>
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            shortcut={MENU_ITEM_SHORTCUTS.download}
                            onClick={() => downloadModel(modelUpload)}
                          >
                            Download
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            destructive
                            disabled={isReadOnly || !canDelete}
                            onClick={() => deleteModel()}
                          >
                            Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </Td>
                </Tr>
              )}
            {allFiles.map((file) => {
              const type = getDocumentType(file.name);
              return (
                <Tr key={file.id}>
                  <Td>
                    <HStack>
                      <DocumentIcon type={type} />
                      <span
                        className="font-medium"
                        onClick={() => {
                          if (["PDF", "Image"].includes(type)) {
                            window.open(
                              path.to.file.previewFile(
                                `${"private"}/${getPath(file)}`
                              ),
                              "_blank"
                            );
                          } else {
                            download(file);
                          }
                        }}
                      >
                        {["PDF", "Image"].includes(type) ? (
                          <DocumentPreview
                            bucket="private"
                            pathToFile={getPath(file)}
                            // @ts-expect-error
                            type={type}
                          >
                            {file.name}
                          </DocumentPreview>
                        ) : (
                          file.name
                        )}
                      </span>
                    </HStack>
                  </Td>
                  <Td className="text-xs font-mono">
                    {convertKbToString(
                      Math.floor((file.metadata?.size ?? 0) / 1024)
                    )}
                  </Td>
                  <Td className="text-xs font-mono">
                    {file.created_at ? (
                      <DateTime value={file.created_at} variant="date" />
                    ) : (
                      "--"
                    )}
                  </Td>
                  <Td>
                    <div className="flex justify-end w-full">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <IconButton
                            aria-label={t`More`}
                            icon={<LuEllipsisVertical />}
                            variant="secondary"
                          />
                        </DropdownMenuTrigger>
                        <DropdownMenuContent>
                          <DropdownMenuItem
                            shortcut={MENU_ITEM_SHORTCUTS.download}
                            onClick={() => download(file)}
                          >
                            Download
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            destructive
                            disabled={isReadOnly || !canDelete}
                            onClick={() => deleteFile(file)}
                          >
                            Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                  </Td>
                </Tr>
              );
            })}
            {allFiles.length === 0 && !modelUpload && (
              <Tr>
                <Td
                  colSpan={24}
                  className="py-8 text-muted-foreground text-center"
                >
                  <Trans>No files</Trans>
                </Td>
              </Tr>
            )}
          </Tbody>
        </Table>
        {!isReadOnly && <FileDropzone onDrop={onDrop} />}
      </CardContent>
    </Card>
  );
};

export default ItemDocuments;

type ItemDocumentFormProps = {
  itemId: string;
  type: ItemType;
};

const ItemDocumentForm = ({ itemId, type }: ItemDocumentFormProps) => {
  const permissions = usePermissions();
  const { upload } = useItemDocuments({ itemId, type });

  const uploadFiles = async (e: ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      upload(Array.from(e.target.files));
    }
  };

  return (
    <File
      isDisabled={!permissions.can("update", "parts")}
      leftIcon={<LuUpload />}
      onChange={uploadFiles}
      multiple
    >
      New
    </File>
  );
};

type Props = {
  itemId: string;
  type: ItemType;
};

export const useItemDocuments = ({ itemId, type }: Props) => {
  const { t } = useLingui();
  const permissions = usePermissions();
  const revalidator = useRevalidator();
  const { carbon } = useCarbon();
  const { company } = useUser();
  const submit = useSubmit();

  const canDelete = permissions.can("delete", "parts");
  const getPath = useCallback(
    (file: { name: string }) => {
      return `${company.id}/parts/${itemId}/${stripSpecialCharacters(
        file.name
      )}`;
    },
    [company.id, itemId]
  );

  const deleteFile = useCallback(
    async (file: FileObject) => {
      if (!carbon) {
        toast.error(t`Error deleting file`);
        return;
      }
      const { error } = await storage(carbon)
        .company(company.id)
        .remove([getPath(file)]);

      if (error) {
        toast.error(error.message || t`Error deleting file`);
        return;
      }

      toast.success(t`File deleted successfully`);
      revalidator.revalidate();
    },
    [getPath, carbon, revalidator, t, company.id]
  );

  const deleteModel = useCallback(async () => {
    if (!carbon) return;

    const { error } = await carbon
      .from("item")
      .update({ modelUploadId: null })
      .eq("id", itemId);
    if (error) {
      toast.error(t`Error removing model from item`);
      return;
    }
    toast.success(t`Model removed from item`);
    revalidator.revalidate();
  }, [carbon, itemId, revalidator, t]);

  const downloadModel = useCallback(
    async (model: ModelUpload) => {
      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`);
      }
    },

    [t]
  );

  const download = useCallback(
    async (file: FileObject) => {
      const url = path.to.file.previewFile(`private/${getPath(file)}`);
      try {
        await downloadUrl(url, file.name);
      } catch (error) {
        toast.error(t`Error downloading file`);
        logger.error("Error", { error: error });
      }
    },

    [getPath, t]
  );

  const getModelPath = useCallback((model: ModelUpload) => {
    if (!model?.modelId) {
      return "";
    }
    return path.to.file.cadModel(model.modelId);
  }, []);

  const { upload: uploadFiles } = useFileUpload();
  const upload = useCallback(
    async (files: File[]) => {
      await uploadFiles(files, {
        getPath,
        onSuccess: (file, uploadedPath) => {
          toast.success(t`Uploaded: ${file.name}`);
          const formData = new FormData();
          formData.append("path", uploadedPath);
          formData.append("name", file.name);
          formData.append("size", Math.round(file.size / 1024).toString());
          formData.append("sourceDocument", type);
          formData.append("sourceDocumentId", itemId);

          submit(formData, {
            method: "post",
            action: path.to.newDocument,
            navigate: false,
            fetcherKey: `item:${file.name}`
          });
        }
      });
      revalidator.revalidate();
    },
    [uploadFiles, getPath, revalidator, submit, type, itemId, t]
  );

  return {
    canDelete,
    deleteFile,
    deleteModel,
    download,
    downloadModel,
    getPath,
    getModelPath,
    upload
  };
};

const usePendingItems = () => {
  type PendingItem = ReturnType<typeof useFetchers>[number] & {
    formData: FormData;
  };

  return useFetchers()
    .filter((fetcher): fetcher is PendingItem => {
      return fetcher.formAction === path.to.newDocument;
    })
    .reduce<OptimisticFileObject[]>((acc, fetcher) => {
      const path = fetcher.formData.get("path") as string;
      const name = fetcher.formData.get("name") as string;
      const size = parseInt(fetcher.formData.get("size") as string, 10) * 1024;

      if (path && name && size) {
        const newItem: OptimisticFileObject = {
          id: path,
          name: name,
          bucket_id: "private",
          bucket: "private",
          metadata: {
            size,
            mimetype: getDocumentType(name)
          }
        };
        return [...acc, newItem];
      }
      return acc;
    }, []);
};