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 {
Badge,
Button,
Checkbox,
Combobox,
copyToClipboard,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
HoverCard,
HoverCardContent,
HoverCardTrigger,
HStack,
MENU_ITEM_SHORTCUTS,
MenuItem,
Modal,
ModalBody,
ModalContent,
ModalFooter,
ModalHeader,
ModalTitle,
PulsingDot,
Status,
Tooltip,
TooltipContent,
TooltipTrigger,
toast,
useDisclosure,
useViewport,
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
import type { Dispatch, ReactNode, SetStateAction } from "react";
import {
createContext,
memo,
useCallback,
useContext,
useMemo,
useState
} from "react";
import {
LuBlocks,
LuCalendar,
LuCheck,
LuContainer,
LuHash,
LuLink,
LuMapPin,
LuPencil,
LuPrinter,
LuQrCode,
LuRefreshCw,
LuSettings,
LuTag,
LuTrash,
LuUser
} from "react-icons/lu";
import { Link } from "react-router";
import {
DateTime,
EmployeeAvatar,
exportOnlyColumn,
Hyperlink,
ItemThumbnail,
MethodItemTypeIcon,
New,
SupplierAvatar,
Table
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { usePermissions, usePrinting, useUrlParams } from "~/hooks";
import { useQuantityFormatter } from "~/hooks/useQuantityFormatter";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { kanbanOutputTypes } from "~/modules/settings/settings.models";
import { useSuppliers } from "~/stores";
import { useItems } from "~/stores/items";
import { usePeople } from "~/stores/people";
import { path } from "~/utils/path";
import type { Kanban } from "../../types";
type KanbansTableProps = {
data: KanbanRow[];
count: number;
// The loader's cursor for the next page (infinite scroll).
nextCursor: string | null;
locationId: string;
kanbanOutput: (typeof kanbanOutputTypes)[number];
};
/** A list row: the kanban plus the projected quantity at its To storage unit
* (armed Transfer kanbans only; null otherwise). */
type KanbanRow = Kanban & { projectedQuantity: number | null };
const defaultColumnVisibility = {
createdBy: false,
// Blank for every Buy and Make kanban; shown from the column picker.
replenishmentLevel: false,
projectedQuantity: false,
supplierName: false,
createdAt: false,
updatedBy: false,
updatedAt: false
};
type KanbanQrCodeAction = "order" | "start" | "complete";
// One QR code popover open at a time across the whole table. Each hover card
// closes only after its own delay, so moving across the Create / Start /
// Complete badges used to leave several popovers open on top of each other.
const OpenQrCodeContext = createContext<
[string | null, Dispatch<SetStateAction<string | null>>] | null
>(null);
function KanbanQrCodeHoverCard({
kanbanId,
action,
label,
tooltip
}: {
kanbanId: string;
action: KanbanQrCodeAction;
label: ReactNode;
tooltip: ReactNode;
}) {
const openQrCode = useContext(OpenQrCodeContext);
const key = `${kanbanId}:${action}`;
const isOpen = openQrCode ? openQrCode[0] === key : undefined;
return (
<HoverCard
open={isOpen}
onOpenChange={(open) =>
openQrCode?.[1]((current) =>
open ? key : current === key ? null : current
)
}
>
<Tooltip>
<TooltipTrigger>
<HoverCardTrigger>
<Badge
variant="outline"
className="flex flex-row items-center gap-1 cursor-pointer"
>
<LuQrCode />
{label}
</Badge>
</HoverCardTrigger>
</TooltipTrigger>
<TooltipContent>{tooltip}</TooltipContent>
</Tooltip>
<HoverCardContent
align="center"
className="size-[236px] overflow-hidden z-[100] bg-white p-4"
>
<iframe
seamless
title={"Kanban QR Code"}
width="198"
height="198"
src={path.to.file.kanbanQrCode(kanbanId, action)}
/>
</HoverCardContent>
</HoverCard>
);
}
const KanbansTable = memo(
({
data,
count,
nextCursor,
locationId,
kanbanOutput
}: KanbansTableProps) => {
const [params] = useUrlParams();
const { t } = useLingui();
const formatQuantity = useQuantityFormatter();
const openQrCode = useState<string | null>(null);
const permissions = usePermissions();
const [people] = usePeople();
const [items] = useItems();
const [suppliers] = useSuppliers();
const locations = useLocations();
const { isPhone } = useViewport();
const columns = useMemo<ColumnDef<KanbanRow>[]>(
() => [
{
accessorKey: "kanbanId",
header: t`Kanban ID`,
cell: ({ row }) => (
<Hyperlink to={`${path.to.kanban(row.original.id!)}?${params}`}>
{row.original.kanbanId}
</Hyperlink>
),
meta: {
icon: <LuTag />
}
},
{
accessorKey: "itemId",
header: t`Item`,
cell: ({ row }) => (
<HStack className="py-1">
<ItemThumbnail
size="sm"
thumbnailPath={row.original.thumbnailPath}
/>
<Hyperlink to={`${path.to.kanban(row.original.id!)}?${params}`}>
<VStack spacing={0}>
<div className="flex gap-1 items-center">
<span>{row.original.name}</span>
</div>
<div className="text-muted-foreground text-xs">
{row.original.readableIdWithRevision}
</div>
</VStack>
</Hyperlink>
</HStack>
),
meta: {
mobile: "P1",
filter: {
type: "static",
options: items?.map((item) => ({
value: item.id,
label: item.readableIdWithRevision
}))
},
icon: <LuBlocks />,
// Without this the exporter substitutes the item's name for the id
// (Download.tsx idNameMaps), losing the readable id.
exportValue: (row) => row.readableIdWithRevision ?? null
}
},
exportOnlyColumn<KanbanRow>({
id: "itemName",
header: t`Item Name`,
value: (row) => row.name ?? null
}),
{
id: "job",
header: "",
cell: ({ row }) => {
if (!row.original.jobReadableId || !row.original.jobId) return null;
return (
<Badge variant="outline">
<Link
to={path.to.job(row.original.jobId)}
className="flex flex-row items-center gap-1"
>
{row.original.jobReadableId}
<PulsingDot />
</Link>
</Badge>
);
},
meta: {
mobile: "P2",
mobilePill: true
}
},
{
id: "links",
header: "",
cell: ({ row }) => (
<>
{kanbanOutput === "label" && (
<HStack>
<Tooltip>
<TooltipTrigger>
<a
href={path.to.file.kanbanLabelsPdf(
[row.original.id!],
"order"
)}
target="_blank"
rel="noreferrer"
>
<Badge
variant="outline"
className="flex flex-row items-center gap-1"
>
<LuTag />
<Trans>Create</Trans>
</Badge>
</a>
</TooltipTrigger>
<TooltipContent>
{t`Label to create a ${getKanbanCreateNoun(row.original.replenishmentSystem)} for this kanban`}
</TooltipContent>
</Tooltip>
{row.original.replenishmentSystem === "Make" && (
<>
<Tooltip>
<TooltipTrigger>
<a
href={path.to.file.kanbanLabelsPdf(
[row.original.id!],
"start"
)}
target="_blank"
rel="noreferrer"
>
<Badge
variant="outline"
className="flex flex-row items-center gap-1"
>
<LuTag />
<Trans>Start</Trans>
</Badge>
</a>
</TooltipTrigger>
<TooltipContent>
<Trans>
Label to start the next operation for this kanban
</Trans>
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger>
<a
href={path.to.file.kanbanLabelsPdf(
[row.original.id!],
"complete"
)}
target="_blank"
rel="noreferrer"
>
<Badge
variant="outline"
className="flex flex-row items-center gap-1"
>
<LuTag />
<Trans>Complete</Trans>
</Badge>
</a>
</TooltipTrigger>
<TooltipContent>
<Trans>
Label to complete the current operation for this
kanban
</Trans>
</TooltipContent>
</Tooltip>
</>
)}
</HStack>
)}
{kanbanOutput === "qrcode" && (
<HStack>
<KanbanQrCodeHoverCard
kanbanId={row.original.id!}
action="order"
label={<Trans>Create</Trans>}
tooltip={t`QR Code to create a ${getKanbanCreateNoun(row.original.replenishmentSystem)} for this kanban`}
/>
{row.original.replenishmentSystem === "Make" && (
<>
<KanbanQrCodeHoverCard
kanbanId={row.original.id!}
action="start"
label={<Trans>Start</Trans>}
tooltip={
<Trans>
QR Code to start the next operation for this kanban
</Trans>
}
/>
<KanbanQrCodeHoverCard
kanbanId={row.original.id!}
action="complete"
label={<Trans>Complete</Trans>}
tooltip={
<Trans>
QR Code to complete the current operation for this
kanban
</Trans>
}
/>
</>
)}
</HStack>
)}
{kanbanOutput === "url" && (
<HStack>
<CopyBadge
text="Create"
url={path.to.api.kanban(row.original.id!)}
tooltip={`Copy link to create a ${getKanbanCreateNoun(
row.original.replenishmentSystem
)} for this kanban`}
/>
{row.original.replenishmentSystem === "Make" && (
<>
<CopyBadge
text="Start"
url={path.to.api.kanbanStart(row.original.id!)}
tooltip={`Copy link to start the next operation for this kanban`}
/>
<CopyBadge
text="Complete"
url={path.to.api.kanbanComplete(row.original.id!)}
tooltip={`Copy link to complete the current operation for this kanban`}
/>
</>
)}
</HStack>
)}
</>
)
},
{
accessorKey: "quantity",
header: t`Reorder Qty.`,
cell: ({ row }) => {
const { quantity, purchaseUnitOfMeasureCode } = row.original;
const baseQuantity = quantity || 0;
return (
<span>
{baseQuantity}
{purchaseUnitOfMeasureCode && ` ${purchaseUnitOfMeasureCode}`}
</span>
);
},
meta: {
mobile: "P2",
icon: <LuHash />
}
},
{
accessorKey: "replenishmentLevel",
header: t`Replenishment Level`,
cell: ({ row }) =>
row.original.replenishmentLevel === null ||
row.original.replenishmentLevel === undefined
? null
: formatQuantity(row.original.replenishmentLevel),
meta: {
icon: <LuHash />
}
},
{
id: "projectedQuantity",
header: t`Projected (To)`,
cell: ({ row }) => {
const projected = row.original.projectedQuantity;
if (projected === null) return null;
const level = row.original.replenishmentLevel;
const isBelowLevel =
level !== null && level !== undefined && projected < level;
return (
<HStack spacing={2}>
<span>{formatQuantity(projected)}</span>
{isBelowLevel && (
<Status color="red">
<Trans>Below level</Trans>
</Status>
)}
</HStack>
);
},
meta: {
icon: <LuHash />
}
},
{
accessorKey: "replenishmentSystem",
header: t`Replenishment`,
cell: ({ row }) => (
<Enumerable value={row.original.replenishmentSystem} />
),
meta: {
mobile: "P2",
filter: {
type: "static",
options: ["Buy", "Make", "Transfer"].map((type) => ({
value: type,
label: <Enumerable value={type} />
}))
},
icon: <LuRefreshCw />
}
},
{
accessorKey: "supplierId",
header: t`Supplier`,
cell: ({ row }) => (
<SupplierAvatar supplierId={row.original.supplierId} />
),
meta: {
mobile: "P3",
icon: <LuContainer />,
filter: {
type: "static",
options: suppliers.map((supplier) => ({
value: supplier.id,
label: supplier.name
}))
}
}
},
{
accessorKey: "storageUnitName",
header: t`Storage Unit`,
cell: ({ row }) =>
row.original.replenishmentSystem === "Transfer" ? (
<span>
{row.original.fromStorageUnitName || "—"}
{" → "}
{row.original.storageUnitName || "—"}
</span>
) : (
row.original.storageUnitName || ""
),
meta: {
icon: <LuMapPin />
}
},
{
accessorKey: "autoRelease",
header: t`Release`,
cell: ({ row }) =>
row.original.replenishmentSystem === "Make" ? (
<div className="flex w-full items-center justify-center">
<Checkbox isChecked={row.original.autoRelease ?? false} />
</div>
) : null,
meta: {
icon: <LuCheck />,
filter: {
type: "static",
options: [
{ value: "true", label: "Yes" },
{ value: "false", label: "No" }
]
}
}
},
{
accessorKey: "autoStartJob",
header: t`Start`,
cell: ({ row }) =>
row.original.replenishmentSystem === "Make" ? (
<div className="flex w-full items-center justify-center">
<Checkbox isChecked={row.original.autoRelease ?? false} />
</div>
) : null,
meta: {
icon: <LuCheck />,
filter: {
type: "static",
options: [
{ value: "true", label: "Yes" },
{ value: "false", label: "No" }
]
}
}
},
{
accessorKey: "createdBy",
header: t`Created By`,
cell: ({ row }) => (
<EmployeeAvatar employeeId={row.original.createdBy} />
),
meta: {
filter: {
type: "static",
options: people.map((employee) => ({
value: employee.id,
label: <Enumerable value={employee.name} />
}))
},
icon: <LuUser />
}
},
{
accessorKey: "createdAt",
header: t`Created At`,
cell: ({ row }) => (
<DateTime value={row.original.createdAt} variant="date" />
),
meta: {
icon: <LuCalendar />
}
},
{
accessorKey: "updatedBy",
header: t`Updated By`,
cell: ({ row }) => (
<EmployeeAvatar employeeId={row.original.updatedBy} />
),
meta: {
filter: {
type: "static",
options: people.map((employee) => ({
value: employee.id,
label: <Enumerable value={employee.name} />
}))
},
icon: <LuUser />
}
},
{
accessorKey: "updatedAt",
header: t`Updated At`,
cell: ({ row }) => (
<DateTime value={row.original.updatedAt} variant="date" />
),
meta: {
icon: <LuCalendar />
}
}
],
[formatQuantity, items, kanbanOutput, params, people, suppliers, t]
);
/* Printing kanban cards (one row, or the selection): to a configured
printer, the location's Kanbans printer first (a Zebra prints at its own
media size), one card per action, so a Make kanban prints Create, Start
and Complete. With no printer, the same cards as one PDF at the
company's Label Size. */
const { printerRoutes, resolvePrinterRoute } = usePrinting();
const printerModal = useDisclosure();
const defaultPrinter = resolvePrinterRoute(locationId, "kanban");
const [printIds, setPrintIds] = useState<string[]>([]);
const [selectedPrinterId, setSelectedPrinterId] = useState<string>("");
const [isPrinting, setIsPrinting] = useState(false);
const handlePrintLabels = useCallback(
(ids: string[]) => {
if (ids.length === 0) return;
if (printerRoutes.length > 0) {
setPrintIds(ids);
setSelectedPrinterId(
defaultPrinter?.id ?? printerRoutes[0]?.id ?? ""
);
printerModal.onOpen();
} else {
window.open(path.to.file.kanbanLabelsPdf(ids, "all"), "_blank");
}
},
[printerRoutes, defaultPrinter?.id, printerModal]
);
// Raw fetch (not a fetcher): parallel submissions don't abort each other
// and nothing revalidates, so the selection stays intact.
const handleConfirmPrint = useCallback(async () => {
if (printIds.length === 0 || !selectedPrinterId) return;
setIsPrinting(true);
try {
const results = await Promise.allSettled(
printIds.map((id) =>
fetch(path.to.manualPrint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
sourceDocument: "Kanban",
sourceDocumentId: id,
locationId,
printerRouteId: selectedPrinterId
})
})
)
);
const failed = results.filter(
(r) => r.status === "rejected" || !r.value.ok
).length;
if (failed > 0) {
toast.error(t`${failed} of ${printIds.length} print jobs failed`);
} else {
toast.success(t`Queued ${printIds.length} kanbans for printing`);
}
} finally {
setIsPrinting(false);
printerModal.onClose();
}
}, [printIds, selectedPrinterId, locationId, printerModal, t]);
const renderContextMenu = useCallback(
(row: KanbanRow) => {
const canUpdate = permissions.can("update", "inventory");
const canDelete = permissions.can("delete", "inventory");
const canViewItems = permissions.can("view", "inventory");
return (
<>
{canUpdate && (
<MenuItem shortcut={MENU_ITEM_SHORTCUTS.edit} asChild>
<Link to={`${path.to.kanban(row.id!)}?${params}`}>
<LuPencil className="mr-2 size-4" />
<Trans>Edit</Trans>
</Link>
</MenuItem>
)}
<MenuItem onClick={() => handlePrintLabels([row.id!])}>
<LuPrinter className="mr-2 size-4" />
<Trans>Print Label</Trans>
</MenuItem>
{/* Phone rows drop the label links column; keep them reachable here */}
{isPhone && kanbanOutput === "label" && (
<>
<MenuItem asChild>
<a
href={path.to.file.kanbanLabelsPdf([row.id!], "order")}
target="_blank"
rel="noreferrer"
>
<LuTag className="mr-2 size-4" />
<Trans>Create</Trans>
</a>
</MenuItem>
{row.replenishmentSystem === "Make" && (
<>
<MenuItem asChild>
<a
href={path.to.file.kanbanLabelsPdf([row.id!], "start")}
target="_blank"
rel="noreferrer"
>
<LuTag className="mr-2 size-4" />
<Trans>Start</Trans>
</a>
</MenuItem>
<MenuItem asChild>
<a
href={path.to.file.kanbanLabelsPdf(
[row.id!],
"complete"
)}
target="_blank"
rel="noreferrer"
>
<LuTag className="mr-2 size-4" />
<Trans>Complete</Trans>
</a>
</MenuItem>
</>
)}
</>
)}
{canViewItems &&
row.itemId &&
(() => {
const item = items.find((i) => i.id === row.itemId);
const itemType = item?.type;
// Only show link for supported types (Service and Fixture not yet supported)
if (
itemType === "Service" ||
itemType === "Fixture" ||
!itemType
)
return null;
return (
<MenuItem shortcut={MENU_ITEM_SHORTCUTS.view} asChild>
<Link to={getLinkToItemDetails(itemType, row.itemId)}>
<MethodItemTypeIcon
type={itemType}
className="mr-2 size-4"
/>
View Item Master
</Link>
</MenuItem>
);
})()}
{canDelete && (
<MenuItem
shortcut={MENU_ITEM_SHORTCUTS.delete}
destructive
asChild
>
<Link to={`${path.to.deleteKanban(row.id!)}?${params}`}>
<LuTrash className="mr-2 size-4" />
Delete
</Link>
</MenuItem>
)}
</>
);
},
[
params,
permissions,
items.find,
isPhone,
kanbanOutput,
handlePrintLabels
]
);
const renderActions = useCallback(
(selectedRows: typeof data) => (
<DropdownMenuContent align="end" className="min-w-[200px]">
<DropdownMenuLabel>
<Trans>Actions</Trans>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem
onClick={() =>
handlePrintLabels(
selectedRows.map((row) => row.id).filter(Boolean) as string[]
)
}
>
<LuPrinter className="mr-2 size-4" />
Print Labels ({selectedRows.length})
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
),
[handlePrintLabels]
);
return (
<OpenQrCodeContext.Provider value={openQrCode}>
<Table<KanbanRow>
count={count}
columns={columns}
data={data}
// Location-scoped: no list registry entry, so no `listKey`.
infinite={{ dataKey: "kanbans", nextCursor }}
defaultColumnVisibility={defaultColumnVisibility}
primaryAction={
<div className="flex items-center gap-2">
<Combobox
asButton
size="sm"
value={locationId}
options={locations}
onChange={(selected) => {
// hard refresh because initialValues update has no effect otherwise
window.location.href = getLocationPath(selected);
}}
/>
<Button variant="secondary" asChild leftIcon={<LuSettings />}>
<Link to={path.to.inventorySettings}>Settings</Link>
</Button>
{permissions.can("create", "inventory") && (
<New label={t`Kanban`} to={path.to.newKanban} />
)}
</div>
}
renderActions={renderActions}
renderContextMenu={renderContextMenu}
title={t`Kanbans`}
table="kanban"
withSavedView
withSelectableRows
/>
{printerModal.isOpen && (
<Modal
open
onOpenChange={(open) => {
if (!open) printerModal.onClose();
}}
>
<ModalContent>
<ModalHeader>
<ModalTitle>
<Trans>Select Printer</Trans>
</ModalTitle>
</ModalHeader>
<ModalBody>
<div className="flex flex-col gap-1">
{printerRoutes.map((route) => (
<button
type="button"
key={route.id}
className={`flex items-center gap-3 rounded-lg border p-3 text-left transition-colors ${
selectedPrinterId === route.id
? "border-primary bg-primary/5"
: "border-border hover:bg-muted"
}`}
onClick={() => setSelectedPrinterId(route.id)}
>
<LuPrinter className="size-4 text-muted-foreground shrink-0" />
<div className="flex-1 min-w-0">
<span className="text-sm font-medium">
{route.name}
</span>
<span className="text-xs text-muted-foreground ml-2 uppercase">
{route.format}
</span>
{route.mediaSizeId && (
<span className="text-xs text-muted-foreground ml-2">
{route.mediaSizeId}
</span>
)}
</div>
{selectedPrinterId === route.id && (
<LuCheck className="size-4 text-primary shrink-0" />
)}
</button>
))}
</div>
</ModalBody>
<ModalFooter>
<HStack>
<Button
variant="primary"
leftIcon={<LuPrinter />}
isLoading={isPrinting}
disabled={!selectedPrinterId || isPrinting}
onClick={handleConfirmPrint}
>
<Trans>Print {printIds.length} Kanbans</Trans>
</Button>
<Button variant="solid" onClick={printerModal.onClose}>
<Trans>Cancel</Trans>
</Button>
</HStack>
</ModalFooter>
</ModalContent>
</Modal>
)}
</OpenQrCodeContext.Provider>
);
}
);
KanbansTable.displayName = "KanbansTable";
export default KanbansTable;
// The document a "create" scan produces: a Job for Make, a Transfer for
// Transfer, otherwise a purchase Order.
function getKanbanCreateNoun(replenishmentSystem: string | null) {
if (replenishmentSystem === "Make") return "Job";
if (replenishmentSystem === "Transfer") return "Transfer";
return "Order";
}
function getLocationPath(locationId: string) {
return `${path.to.kanbans}?location=${locationId}`;
}
function CopyBadge({
text,
url,
tooltip
}: {
text: string;
url: string;
tooltip: string;
}) {
const { t } = useLingui();
const [isCopied, setIsCopied] = useState(false);
const handleCopy = () => {
copyToClipboard(window.location.origin + url);
setIsCopied(true);
toast.success(t`Copied link to clipboard`);
setTimeout(() => setIsCopied(false), 1500);
};
return (
<Tooltip>
<TooltipTrigger>
<Badge
variant="outline"
className="flex flex-row items-center gap-1 cursor-pointer"
onClick={handleCopy}
>
{isCopied ? <LuCheck className="text-emerald-500" /> : <LuLink />}
{text}
</Badge>
</TooltipTrigger>
<TooltipContent>{tooltip}</TooltipContent>
</Tooltip>
);
}