Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
// 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 { downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
import { toast } from "@carbon/react";
import { useCallback } from "react";
import { useNavigate } from "react-router";
import { usePermissions, useUrlParams, useUser } from "~/hooks";
import type {
DocumentTransactionType,
Document as DocumentType
} from "~/modules/documents/types";
import { path } from "~/utils/path";
const logger = getLogger("erp", "usedocument");
export const useDocument = () => {
const navigate = useNavigate();
const permissions = usePermissions();
const { carbon } = useCarbon();
const [params, setParams] = useUrlParams();
const user = useUser();
const canDelete = useCallback(
(doc: DocumentType) => {
return (
!permissions.can("delete", "documents") ||
!doc.writeGroups?.some((group) => user?.groups.includes(group))
);
},
[permissions, user]
);
const canUpdate = useCallback(
(document: DocumentType) => {
return (
!permissions.can("update", "documents") ||
!document.writeGroups?.some((group) => user?.groups.includes(group))
);
},
[permissions, user]
);
const insertTransaction = useCallback(
(document: DocumentType, type: DocumentTransactionType) => {
if (user?.id === undefined) throw new Error("User is undefined");
if (!document.id) throw new Error("Document id is undefined");
return carbon?.from("documentTransaction").insert({
documentId: document.id,
type,
companyId: user.company.id,
userId: user.id
});
},
[carbon, user?.id, user.company.id]
);
const deleteLabel = useCallback(
async (document: DocumentType, label: string) => {
if (!document.id) throw new Error("Document id is undefined");
if (user?.id === undefined) throw new Error("User is undefined");
return carbon
?.from("documentLabel")
.delete()
.eq("documentId", document.id)
.eq("userId", user.id)
.eq("label", label);
},
[carbon, user?.id]
);
const download = useCallback(
async (doc: DocumentType) => {
if (!doc.path) throw new Error("Document path is undefined");
const url = path.to.file.previewFile(`private/${doc.path}`);
try {
await downloadUrl(url, doc.name ?? "File");
} catch (error) {
toast.error("Error downloading file");
logger.error("Error", { error: error });
}
await insertTransaction(doc, "Download");
},
[insertTransaction]
);
const view = useCallback(
(document: DocumentType) => {
navigate(`${path.to.documentView(document.id!)}/?${params}`);
},
[navigate, params]
);
const edit = useCallback(
(document: DocumentType) =>
navigate(`${path.to.document(document.id!)}?${params}`),
[navigate, params]
);
const favorite = useCallback(
async (document: DocumentType) => {
if (document.favorite) {
await carbon
?.from("documentFavorite")
.delete()
.eq("documentId", document.id!)
.eq("userId", user?.id);
return insertTransaction(document, "Unfavorite");
} else {
await carbon
?.from("documentFavorite")
.insert({ documentId: document.id!, userId: user?.id });
return insertTransaction(document, "Favorite");
}
},
[insertTransaction, carbon, user?.id]
);
const isImage = useCallback((fileType: string) => {
return ["png", "jpg", "jpeg", "gif", "svg", "avif", "webp"].includes(
fileType
);
}, []);
const isPdf = useCallback((fileType: string) => {
return fileType === "pdf";
}, []);
const label = useCallback(
async (document: DocumentType, labels: string[]) => {
if (user?.id === undefined) throw new Error("User is undefined");
await carbon
?.from("documentLabel")
.delete()
.eq("documentId", document.id!)
.eq("userId", user.id)
.then(() => {
return carbon?.from("documentLabel").insert(
labels.map((label) => ({
documentId: document.id!,
label,
companyId: user.company.id,
userId: user.id
}))
);
});
return insertTransaction(document, "Label");
},
[insertTransaction, carbon, user.id, user.company.id]
);
const makePreview = useCallback(
async (doc: DocumentType) => {
if (!doc.path) throw new Error("Document path is undefined");
if (!carbon) {
toast.error("Error previewing file");
return null;
}
const { data, error } = await storage(carbon)
.company(user.company.id)
.download(doc.path);
if (!data) {
toast.error(error?.message || "Error previewing file");
return null;
}
return window.URL.createObjectURL(data);
},
[carbon, user.company.id]
);
const removeLabel = useCallback(
(document: DocumentType, label: string) => {
return carbon
?.from("documentLabel")
.delete()
.eq("documentId", document.id!)
.eq("userId", user?.id)
.eq("label", label);
},
[carbon, user?.id]
);
const setLabel = useCallback(
(label: string) => {
setParams({ label });
},
[setParams]
);
return {
canDelete,
canUpdate,
download,
deleteLabel,
edit,
favorite,
isImage,
isPdf,
label,
view,
makePreview,
removeLabel,
setLabel
};
};