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.

feat: add kanban schedule to mes

Brad Barbinf1321be6204a
diff --git a/apps/mes/app/components/Kanban/Kanban.tsx b/apps/mes/app/components/Kanban/Kanban.tsx
new file mode 100644
index 0000000000..35dbfc1448
--- /dev/null
+++ b/apps/mes/app/components/Kanban/Kanban.tsx
@@ -0,0 +1,195 @@
+import { ClientOnly } from "@carbon/react";
+import type {
+ Announcements,
+ DragEndEvent,
+ DragStartEvent,
+} from "@dnd-kit/core";
+import {
+ DndContext,
+ DragOverlay,
+ KeyboardSensor,
+ MouseSensor,
+ TouchSensor,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import { SortableContext, arrayMove } from "@dnd-kit/sortable";
+import { useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { BoardContainer, ColumnCard } from "./components/ColumnCard";
+import type { Column, DisplaySettings, Item } from "./types";
+import { coordinateGetter, hasDraggableData } from "./utils";
+
+type KanbanProps = {
+ columns: Column[];
+ items: Item[];
+} & DisplaySettings;
+
+const COLUMN_ORDER_KEY = "kanban-column-order";
+
+const Kanban = ({ columns, items, ...displaySettings }: KanbanProps) => {
+ const [columnOrder, setColumnOrder] = useState<string[]>(() => {
+ // Get stored column order from localStorage
+ const storedOrder = localStorage.getItem(COLUMN_ORDER_KEY);
+ if (storedOrder) {
+ const parsedOrder = JSON.parse(storedOrder) as string[];
+ // Add any new columns that aren't in stored order
+ const newOrder = [...parsedOrder];
+ columns.forEach((col) => {
+ if (!newOrder.includes(col.id)) {
+ newOrder.push(col.id);
+ }
+ });
+ return newOrder;
+ }
+ return columns.map((col) => col.id);
+ });
+
+ // Update localStorage when column order changes
+ useEffect(() => {
+ localStorage.setItem(COLUMN_ORDER_KEY, JSON.stringify(columnOrder));
+ }, [columnOrder]);
+
+ const [activeColumn, setActiveColumn] = useState<Column | null>(null);
+
+ const sensors = useSensors(
+ useSensor(MouseSensor),
+ useSensor(TouchSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter,
+ })
+ );
+
+ const announcements: Announcements = {
+ onDragStart({ active }) {
+ if (!hasDraggableData(active)) return;
+ if (active.data.current?.type === "column") {
+ const startIndex = columnOrder.findIndex((id) => id === active.id);
+ const startColumn = columns.find((col) => col.id === active.id);
+ return `Picked up Column ${startColumn?.title} at position: ${
+ startIndex + 1
+ } of ${columnOrder.length}`;
+ }
+ },
+ onDragOver({ active, over }) {
+ if (!hasDraggableData(active) || !hasDraggableData(over)) return;
+
+ if (
+ active.data.current?.type === "column" &&
+ over.data.current?.type === "column"
+ ) {
+ const overIndex = columnOrder.findIndex((id) => id === over.id);
+ return `Column ${active.data.current.column.title} was moved over ${
+ over.data.current.column.title
+ } at position ${overIndex + 1} of ${columnOrder.length}`;
+ }
+ },
+ onDragEnd({ active, over }) {
+ if (!hasDraggableData(active) || !hasDraggableData(over)) return;
+
+ if (
+ active.data.current?.type === "column" &&
+ over.data.current?.type === "column"
+ ) {
+ const overColumnPosition = columnOrder.findIndex(
+ (id) => id === over.id
+ );
+
+ return `Column ${
+ active.data.current.column.title
+ } was dropped into position ${overColumnPosition + 1} of ${
+ columnOrder.length
+ }`;
+ }
+ },
+ onDragCancel({ active }) {
+ if (!hasDraggableData(active)) return;
+ return `Dragging ${active.data.current?.type} cancelled.`;
+ },
+ };
+
+ return (
+ <DndContext
+ accessibility={{
+ announcements,
+ }}
+ sensors={sensors}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ >
+ <BoardContainer>
+ <SortableContext items={columnOrder}>
+ {columnOrder.map((colId) => {
+ const col = columns.find((c) => c.id === colId);
+ if (!col) return null;
+ return (
+ <ColumnCard
+ key={col.id}
+ column={col}
+ items={items.filter((item) => item.columnId === col.id)}
+ {...displaySettings}
+ />
+ );
+ })}
+ </SortableContext>
+ </BoardContainer>
+
+ <ClientOnly fallback={null}>
+ {() =>
+ createPortal(
+ <DragOverlay>
+ {activeColumn && (
+ <ColumnCard
+ isOverlay
+ column={activeColumn}
+ items={items.filter(
+ (item) => item.columnId === activeColumn.id
+ )}
+ {...displaySettings}
+ />
+ )}
+ </DragOverlay>,
+ document.body
+ )
+ }
+ </ClientOnly>
+ </DndContext>
+ );
+
+ function onDragStart(event: DragStartEvent) {
+ if (!hasDraggableData(event.active)) return;
+ const data = event.active.data.current;
+ if (data?.type === "column") {
+ setActiveColumn(data.column);
+ }
+ }
+
+ function onDragEnd(event: DragEndEvent) {
+ setActiveColumn(null);
+
+ const { active, over } = event;
+
+ if (!over) return;
+
+ const activeId = active.id;
+ const overId = over.id;
+
+ if (!hasDraggableData(active)) return;
+
+ const activeData = active.data.current;
+
+ if (activeId === overId) return;
+
+ const isActiveAColumn = activeData?.type === "column";
+ if (!isActiveAColumn) return;
+
+ setColumnOrder((prevOrder) => {
+ const activeColumnIndex = prevOrder.findIndex((id) => id === activeId);
+ const overColumnIndex = prevOrder.findIndex((id) => id === overId);
+
+ return arrayMove(prevOrder, activeColumnIndex, overColumnIndex);
+ });
+ }
+};
+
+export default Kanban;
diff --git a/apps/mes/app/components/Kanban/components/ColumnCard.tsx b/apps/mes/app/components/Kanban/components/ColumnCard.tsx
new file mode 100644
index 0000000000..58b40f038b
--- /dev/null
+++ b/apps/mes/app/components/Kanban/components/ColumnCard.tsx
@@ -0,0 +1,165 @@
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ cn,
+ IconButton,
+ ScrollArea,
+ ScrollBar,
+} from "@carbon/react";
+import { formatDurationMilliseconds } from "@carbon/utils";
+import { useDndContext } from "@dnd-kit/core";
+import { SortableContext, useSortable } from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { cva } from "class-variance-authority";
+import { useMemo } from "react";
+import { LuGripVertical } from "react-icons/lu";
+import { useUrlParams } from "~/hooks/useUrlParams";
+import type { Column, ColumnDragData, DisplaySettings, Item } from "../types";
+import { ItemCard } from "./ItemCard";
+
+type ColumnCardProps = {
+ column: Column;
+ items: Item[];
+ isOverlay?: boolean;
+} & DisplaySettings;
+
+export function ColumnCard({
+ column,
+ items,
+ isOverlay,
+ ...displaySettings
+}: ColumnCardProps) {
+ const [params] = useUrlParams();
+ const currentFilters = params.getAll("filter");
+ const itemsIds = useMemo(() => {
+ return items.map((item) => item.id);
+ }, [items]);
+
+ const totalDuration = items.reduce((acc, item) => {
+ return acc + Math.max((item.duration ?? 0) - (item.progress ?? 0), 0);
+ }, 0);
+
+ const {
+ setNodeRef,
+ attributes,
+ listeners,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({
+ id: column.id,
+ data: {
+ type: "column",
+ column,
+ } satisfies ColumnDragData,
+ attributes: {
+ roleDescription: `Column: ${column.title}`,
+ },
+ });
+
+ const style = {
+ transition,
+ transform: CSS.Translate.toString(transform),
+ };
+
+ const variants = cva(
+ "w-[350px] max-w-full bg-primary-foreground flex flex-col flex-shrink-0 snap-center rounded-none",
+ {
+ variants: {
+ dragging: {
+ default: "border-2 border-transparent",
+ over: "ring-2 opacity-30",
+ overlay: "ring-2 ring-primary",
+ },
+ },
+ }
+ );
+
+ return (
+ <Card
+ ref={setNodeRef}
+ style={style}
+ className={cn(
+ `${variants({
+ dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
+ })} flex flex-col p-[1px] pt-0`,
+ currentFilters.length > 0
+ ? `h-[calc(100dvh-var(--header-height)-var(--filters-height))]`
+ : `h-[calc(100dvh-var(--header-height))]`
+ )}
+ >
+ <CardHeader className="p-4 w-full font-semibold text-left flex flex-row space-between items-center sticky top-0 bg-card z-10 border-b">
+ <div className="flex flex-grow items-start space-x-2">
+ {column.active && <PulsingDot />}
+ <div className="flex flex-col flex-grow">
+ <span className="mr-auto truncate"> {column.title}</span>
+ {totalDuration > 0 ? (
+ <span className="text-muted-foreground text-xs">
+ {formatDurationMilliseconds(totalDuration)}
+ </span>
+ ) : (
+ <span className="text-muted-foreground text-xs">
+ No scheduled time
+ </span>
+ )}
+ </div>
+ </div>
+ <IconButton
+ aria-label={`Move column: ${column.title}`}
+ icon={<LuGripVertical />}
+ variant={"ghost"}
+ {...attributes}
+ {...listeners}
+ className="cursor-grab relative"
+ />
+ </CardHeader>
+ <ScrollArea className="flex-grow">
+ <CardContent className="flex flex-col gap-2 p-2">
+ <SortableContext items={itemsIds}>
+ {items.map((item) => (
+ <ItemCard key={item.id} item={item} {...displaySettings} />
+ ))}
+ </SortableContext>
+ </CardContent>
+ </ScrollArea>
+ </Card>
+ );
+}
+
+export function BoardContainer({ children }: { children: React.ReactNode }) {
+ const dndContext = useDndContext();
+
+ const variations = cva("px-0 flex lg:justify-center", {
+ variants: {
+ dragging: {
+ default: "snap-x snap-mandatory",
+ active: "snap-none",
+ },
+ },
+ });
+
+ return (
+ <ScrollArea
+ className={variations({
+ dragging: dndContext.active ? "active" : "default",
+ })}
+ >
+ <div className="flex gap-0 items-start flex-row justify-start p-0">
+ {children}
+ </div>
+ <ScrollBar orientation="horizontal" />
+ </ScrollArea>
+ );
+}
+
+function PulsingDot() {
+ return (
+ <span className="relative flex h-2 w-2 mt-2">
+ <span
+ className={`absolute h-full w-full animate-ping rounded-full border border-emerald-500 opacity-100 duration-1000`}
+ />
+ <span className={`h-2 w-2 rounded-full bg-emerald-500`} />
+ </span>
+ );
+}
diff --git a/apps/mes/app/components/Kanban/components/ItemCard.tsx b/apps/mes/app/components/Kanban/components/ItemCard.tsx
new file mode 100644
index 0000000000..911e96db83
--- /dev/null
+++ b/apps/mes/app/components/Kanban/components/ItemCard.tsx
@@ -0,0 +1,224 @@
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ cn,
+ HStack,
+ IconButton,
+ Progress,
+} from "@carbon/react";
+import {
+ convertDateStringToIsoString,
+ formatDurationMilliseconds,
+ formatRelativeTime,
+} from "@carbon/utils";
+import { cva } from "class-variance-authority";
+import {
+ LuCheckCircle,
+ LuClipboardCheck,
+ LuExternalLink,
+ LuTimer,
+ LuXCircle,
+} from "react-icons/lu";
+
+import { Link } from "@remix-run/react";
+import { RiProgress8Line } from "react-icons/ri";
+import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
+import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
+import { TodoStatusIcon } from "~/assets/icons/TodoStatusIcon";
+
+import { DeadlineIcon } from "~/components/Icons";
+import type { DisplaySettings, Item } from "../types";
+
+type ItemCardProps = {
+ item: Item;
+} & DisplaySettings;
+
+const cardVariants = cva(
+ "dark:bg-gradient-to-bl dark:via-card dark:to-card dark:hover:to-muted/30 dark:hover:via-muted/30 bg-card hover:bg-muted/30",
+ {
+ variants: {
+ status: {
+ "In Progress":
+ "border-emerald-600/30 dark:from-emerald-600/10 bg-emerald-600/5",
+ Ready: "",
+ Done: "",
+ Paused: "border-yellow-500/30 dark:from-yellow-500/10 bg-yellow-500/5",
+ Canceled: "border-red-500/30 dark:from-red-500/10 bg-red-500/5",
+ Waiting: "border-yellow-500/30 dark:from-yellow-500/10 bg-yellow-500/5",
+ Todo: "border-border",
+ },
+ },
+ defaultVariants: {
+ status: "Todo",
+ },
+ }
+);
+
+const cardHeaderVariants = cva("border-b", {
+ variants: {
+ status: {
+ "In Progress": "border-emerald-600/10",
+ Ready: "",
+ Done: "",
+ Paused: "border-yellow-500/10",
+ Canceled: "border-red-500/10",
+ Waiting: "border-yellow-500/10",
+ Todo: "border-border",
+ },
+ },
+ defaultVariants: {
+ status: "Todo",
+ },
+});
+
+export function ItemCard({
+ item,
+ showCustomer,
+ showDescription,
+ showDueDate,
+ showDuration,
+ showEmployee,
+ showProgress,
+ showStatus,
+ showSalesOrder,
+}: ItemCardProps) {
+ const isOverdue =
+ item.deadlineType !== "No Deadline" && item.dueDate
+ ? new Date(item.dueDate) < new Date()
+ : false;
+
+ return (
+ <Card
+ className={cn(
+ "max-w-[330px]",
+ cardVariants({
+ status: item.status,
+ })
+ )}
+ >
+ <CardHeader
+ className={cn(
+ "max-w-full p-3 border-b relative",
+ cardHeaderVariants({
+ status: item.status,
+ })
+ )}
+ >
+ <div className="flex w-full max-w-full justify-between">
+ <div className="flex flex-col space-y-0">
+ {item.subtitle && (
+ <span className="text-xs text-muted-foreground line-clamp-1">
+ {item.subtitle}
+ </span>
+ )}
+ <Link
+ to={`${item.link}?selectedOperation=${item.id}`}
+ className="mr-auto font-semibold line-clamp-1"
+ >
+ {item.title}
+ </Link>
+ </div>
+ {item.link && (
+ <Link to={`${item.link}?selectedOperation=${item.id}`}>
+ <IconButton
+ aria-label="Link to job operation"
+ icon={<LuExternalLink />}
+ variant={"ghost"}
+ />
+ </Link>
+ )}
+ </div>
+
+ {showProgress &&
+ ["Paused", "Done", "In Progress"].includes(item.status!) && (
+ <Progress
+ indicatorClassName={
+ item.status === "Paused" ? "bg-yellow-500" : ""
+ }
+ numerator={
+ item.progress ? formatDurationMilliseconds(item.progress) : ""
+ }
+ denominator={
+ item.duration ? formatDurationMilliseconds(item.duration) : ""
+ }
+ value={
+ item.progress && item.duration
+ ? (item.progress / item.duration) * 100
+ : 0
+ }
+ />
+ )}
+ </CardHeader>
+ <CardContent className="p-3 space-y-2 text-left whitespace-pre-wrap text-sm">
+ {showDescription && item.description && (
+ <HStack className="justify-start space-x-2">
+ <LuClipboardCheck className="text-muted-foreground" />
+ <span className="text-sm line-clamp-1">{item.description}</span>
+ </HStack>
+ )}
+ {showStatus && item.status && (
+ <HStack className="justify-start space-x-2">
+ {getStatusIcon(item.status)}
+ <span className="text-sm">{item.status}</span>
+ </HStack>
+ )}
+ {showDuration && typeof item.duration === "number" && (
+ <HStack className="justify-start space-x-2">
+ <LuTimer className="text-muted-foreground" />
+ <span className="text-sm">
+ {formatDurationMilliseconds(item.duration)}
+ </span>
+ </HStack>
+ )}
+ {showDueDate && item.deadlineType && (
+ <HStack className="justify-start space-x-2">
+ <DeadlineIcon
+ deadlineType={item.deadlineType}
+ overdue={isOverdue}
+ />
+
+ <span className={cn("text-sm", isOverdue ? "text-red-500" : "")}>
+ {["ASAP", "No Deadline"].includes(item.deadlineType)
+ ? item.deadlineType
+ : item.dueDate
+ ? `Due ${formatRelativeTime(
+ convertDateStringToIsoString(item.dueDate)
+ )}`
+ : "–"}
+ </span>
+ </HStack>
+ )}
+
+ {showSalesOrder &&
+ item.salesOrderReadableId &&
+ item.salesOrderId &&
+ item.salesOrderLineId && (
+ <HStack className="justify-start space-x-2">
+ <RiProgress8Line className="text-muted-foreground" />
+ <span className="text-sm">{item.salesOrderReadableId}</span>
+ </HStack>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
+
+function getStatusIcon(status: Item["status"]) {
+ switch (status) {
+ case "Ready":
+ case "Todo":
+ return <TodoStatusIcon className="text-foreground" />;
+ case "Waiting":
+ case "Canceled":
+ return <LuXCircle className="text-muted-foreground" />;
+ case "Done":
+ return <LuCheckCircle className="text-blue-600" />;
+ case "In Progress":
+ return <AlmostDoneIcon />;
+ case "Paused":
+ return <InProgressStatusIcon />;
+ default:
+ return null;
+ }
+}
diff --git a/apps/mes/app/components/Kanban/index.ts b/apps/mes/app/components/Kanban/index.ts
new file mode 100644
index 0000000000..90c062f88c
--- /dev/null
+++ b/apps/mes/app/components/Kanban/index.ts
@@ -0,0 +1,4 @@
+import Kanban from "./Kanban";
+
+export * from "./types";
+export { Kanban };
diff --git a/apps/mes/app/components/Kanban/types.ts b/apps/mes/app/components/Kanban/types.ts
new file mode 100644
index 0000000000..2765f4d534
--- /dev/null
+++ b/apps/mes/app/components/Kanban/types.ts
@@ -0,0 +1,84 @@
+import { z } from "zod";
+import {
+ deadlineTypes,
+ jobOperationStatus,
+} from "~/services/operations.service";
+
+export const columnValidator = z.object({
+ id: z.string(),
+ title: z.string(),
+ active: z.boolean().optional(),
+ type: z.array(z.string()),
+});
+
+export type Column = z.infer<typeof columnValidator>;
+
+export interface ColumnDragData {
+ type: "column";
+ column: Column;
+}
+
+export type DisplaySettings = {
+ showCustomer: boolean;
+ showDescription: boolean;
+ showDueDate: boolean;
+ showDuration: boolean;
+ showEmployee: boolean;
+ showProgress: boolean;
+ showStatus: boolean;
+ showSalesOrder: boolean;
+};
+
+export type DraggableData = ColumnDragData | ItemDragData;
+
+const itemValidator = z.object({
+ id: z.string(),
+ columnId: z.string(),
+ columnType: z.string(),
+ title: z.string(),
+ link: z.string().optional(),
+ subtitle: z.string().optional(),
+ priority: z.number(),
+ customerId: z.string().optional(),
+ employeeIds: z.array(z.string()).optional(),
+ description: z.string().optional(),
+ dueDate: z.string().optional(), // 2024-05-28
+ duration: z.number().optional(), // miliseconds
+ deadlineType: z.enum(deadlineTypes).optional(),
+ progress: z.number().optional(), // miliseconds
+ status: z.enum(jobOperationStatus).optional(),
+ salesOrderReadableId: z.string().optional(),
+ salesOrderId: z.string().optional(),
+ salesOrderLineId: z.string().optional(),
+});
+
+export type Item = z.infer<typeof itemValidator>;
+
+export interface ItemDragData {
+ type: "item";
+ item: Item;
+}
+
+export enum ItemStatus {
+ Canceled = "CANCELED",
+ Done = "DONE",
+ InProgress = "IN_PROGRESS",
+ Paused = "PAUSED",
+ Ready = "READY",
+ Todo = "TODO",
+ Waiting = "WAITING",
+}
+
+export enum ItemDeadline {
+ ASAP = "ASAP",
+ HardDeadline = "Hard Deadline",
+ SoftDeadline = "Soft Deadline",
+ NoDeadline = "No Deadline",
+}
+
+export enum ItemPriority {
+ ASAP = "ASAP",
+ High = "HIGH",
+ Average = "AVERAGE",
+ Low = "LOW",
+}
diff --git a/apps/mes/app/components/Kanban/utils.ts b/apps/mes/app/components/Kanban/utils.ts
new file mode 100644
index 0000000000..8d39bf7a2e
--- /dev/null
+++ b/apps/mes/app/components/Kanban/utils.ts
@@ -0,0 +1,129 @@
+import type {
+ Active,
+ DataRef,
+ DroppableContainer,
+ KeyboardCoordinateGetter,
+ Over,
+} from "@dnd-kit/core";
+import { KeyboardCode, closestCorners, getFirstCollision } from "@dnd-kit/core";
+import type { DraggableData } from "./types";
+
+const directions: string[] = [
+ KeyboardCode.Down,
+ KeyboardCode.Right,
+ KeyboardCode.Up,
+ KeyboardCode.Left,
+];
+
+export const coordinateGetter: KeyboardCoordinateGetter = (
+ event,
+ { context: { active, droppableRects, droppableContainers, collisionRect } }
+) => {
+ if (directions.includes(event.code)) {
+ event.preventDefault();
+
+ if (!active || !collisionRect) {
+ return;
+ }
+
+ const filteredContainers: DroppableContainer[] = [];
+
+ droppableContainers.getEnabled().forEach((entry) => {
+ if (!entry || entry?.disabled) {
+ return;
+ }
+
+ const rect = droppableRects.get(entry.id);
+
+ if (!rect) {
+ return;
+ }
+
+ const data = entry.data.current;
+
+ if (data) {
+ const { type, children } = data;
+
+ if (type === "Column" && children?.length > 0) {
+ if (active.data.current?.type !== "Column") {
+ return;
+ }
+ }
+ }
+
+ switch (event.code) {
+ case KeyboardCode.Down:
+ if (active.data.current?.type === "Column") {
+ return;
+ }
+ if (collisionRect.top < rect.top) {
+ // find all droppable areas below
+ filteredContainers.push(entry);
+ }
+ break;
+ case KeyboardCode.Up:
+ if (active.data.current?.type === "Column") {
+ return;
+ }
+ if (collisionRect.top > rect.top) {
+ // find all droppable areas above
+ filteredContainers.push(entry);
+ }
+ break;
+ case KeyboardCode.Left:
+ if (collisionRect.left >= rect.left + rect.width) {
+ // find all droppable areas to left
+ filteredContainers.push(entry);
+ }
+ break;
+ case KeyboardCode.Right:
+ // find all droppable areas to right
+ if (collisionRect.left + collisionRect.width <= rect.left) {
+ filteredContainers.push(entry);
+ }
+ break;
+ }
+ });
+ const collisions = closestCorners({
+ active,
+ collisionRect: collisionRect,
+ droppableRects,
+ droppableContainers: filteredContainers,
+ pointerCoordinates: null,
+ });
+ const closestId = getFirstCollision(collisions, "id");
+
+ if (closestId != null) {
+ const newDroppable = droppableContainers.get(closestId);
+ const newNode = newDroppable?.node.current;
+ const newRect = newDroppable?.rect.current;
+
+ if (newNode && newRect) {
+ return {
+ x: newRect.left,
+ y: newRect.top,
+ };
+ }
+ }
+ }
+
+ return undefined;
+};
+
+export function hasDraggableData<T extends Active | Over>(
+ entry: T | null | undefined
+): entry is T & {
+ data: DataRef<DraggableData>;
+} {
+ if (!entry) {
+ return false;
+ }
+
+ const data = entry.data.current;
+
+ if (data?.type === "column" || data?.type === "item") {
+ return true;
+ }
+
+ return false;
+}
diff --git a/apps/mes/app/routes/x+/_index.tsx b/apps/mes/app/routes/x+/_index.tsx
index 8b286cb833..959e525c1d 100644
--- a/apps/mes/app/routes/x+/_index.tsx
+++ b/apps/mes/app/routes/x+/_index.tsx
@@ -1,15 +1,7 @@
-import { requirePermissions } from "@carbon/auth/auth.server";
import type { LoaderFunction } from "@vercel/remix";
import { redirect } from "@vercel/remix";
-import { getLocationAndWorkCenter } from "~/services/location.server";
import { path } from "~/utils/path";
export const loader: LoaderFunction = async ({ request }) => {
- const { client, companyId, userId } = await requirePermissions(request, {});
- const { workCenter } = await getLocationAndWorkCenter(request, client, {
- companyId,
- userId,
- });
-
- return redirect(path.to.workCenter(workCenter));
+ return redirect(path.to.operations);
};
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index f019a646c1..b9f34bbe61 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -11,7 +11,7 @@ import {
TooltipProvider,
} from "@carbon/react";
import type { ShouldRevalidateFunction } from "@remix-run/react";
-import { useLoaderData, useNavigation } from "@remix-run/react";
+import { Outlet, useLoaderData, useNavigation } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import NProgress from "nprogress";
@@ -138,11 +138,14 @@ export default function AuthenticatedRoute() {
locations={locations}
/>
<SidebarInset>
- <header className="flex h-16 shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12">
+ <header className="flex h-[var(--header-height)] shrink-0 items-center gap-2 transition-[width,height] ease-linear group-has-[[data-collapsible=icon]]/sidebar-wrapper:h-12 border-b">
<div className="flex items-center gap-2 px-4">
<SidebarTrigger className="-ml-1" />
</div>
</header>
+ <main className="flex flex-1 w-full h-[calc(100vh-var(--header-height))] overflow-hidden">
+ <Outlet />
+ </main>
</SidebarInset>
</TooltipProvider>
<Toaster position="bottom-left" />
diff --git a/apps/mes/app/routes/x+/active.$operationId.tsx b/apps/mes/app/routes/x+/old-active.$operationId.tsx
similarity index 100%
rename from apps/mes/app/routes/x+/active.$operationId.tsx
rename to apps/mes/app/routes/x+/old-active.$operationId.tsx
diff --git a/apps/mes/app/routes/x+/operations.$workCenterId.$operationId.tsx b/apps/mes/app/routes/x+/old-operations.$workCenterId.$operationId.tsx
similarity index 100%
rename from apps/mes/app/routes/x+/operations.$workCenterId.$operationId.tsx
rename to apps/mes/app/routes/x+/old-operations.$workCenterId.$operationId.tsx
diff --git a/apps/mes/app/routes/x+/operations.$workCenterId.tsx b/apps/mes/app/routes/x+/old-operations.$workCenterId.tsx
similarity index 100%
rename from apps/mes/app/routes/x+/operations.$workCenterId.tsx
rename to apps/mes/app/routes/x+/old-operations.$workCenterId.tsx
diff --git a/apps/mes/app/routes/x+/operations._index.tsx b/apps/mes/app/routes/x+/old-operations._index.tsx
similarity index 100%
rename from apps/mes/app/routes/x+/operations._index.tsx
rename to apps/mes/app/routes/x+/old-operations._index.tsx
diff --git a/apps/mes/app/routes/x+/recent.$operationId.tsx b/apps/mes/app/routes/x+/old-recent.$operationId.tsx
similarity index 100%
rename from apps/mes/app/routes/x+/recent.$operationId.tsx
rename to apps/mes/app/routes/x+/old-recent.$operationId.tsx
diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsx
new file mode 100644
index 0000000000..5345aa3741
--- /dev/null
+++ b/apps/mes/app/routes/x+/operations.tsx
@@ -0,0 +1,218 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { ClientOnly, Spinner } from "@carbon/react";
+import { json, useLoaderData } from "@remix-run/react";
+import type { LoaderFunctionArgs } from "@vercel/remix";
+import { LuAlertTriangle } from "react-icons/lu";
+import type { Column, Item } from "~/components/Kanban";
+import { Kanban } from "~/components/Kanban";
+import { getLocationAndWorkCenter } from "~/services/location.server";
+import {
+ getActiveJobOperationsByLocation,
+ getProcessesList,
+ getWorkCentersByLocation,
+} from "~/services/operations.service";
+import { makeDurations } from "~/utils/durations";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {});
+ const serviceRole = await getCarbonServiceRole();
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const filterParam = searchParams.getAll("filter");
+
+ let selectedWorkCenterIds: string[] = [];
+ let selectedProcessIds: string[] = [];
+ let selectedSalesOrderIds: string[] = [];
+ if (filterParam) {
+ for (const filter of filterParam) {
+ const [key, operator, value] = filter.split(":");
+ if (key === "workCenterId") {
+ if (operator === "in") {
+ selectedWorkCenterIds = value.split(",");
+ } else if (operator === "eq") {
+ selectedWorkCenterIds = [value];
+ }
+ } else if (key === "processId") {
+ if (operator === "in") {
+ selectedProcessIds = value.split(",");
+ } else if (operator === "eq") {
+ selectedProcessIds = [value];
+ }
+ } else if (key === "salesOrderId") {
+ if (operator === "in") {
+ selectedSalesOrderIds = value.split(",");
+ } else if (operator === "eq") {
+ selectedSalesOrderIds = [value];
+ }
+ }
+ }
+ }
+
+ const { location } = await getLocationAndWorkCenter(request, serviceRole, {
+ companyId,
+ userId,
+ });
+
+ const [workCenters, processes, operations] = await Promise.all([
+ getWorkCentersByLocation(serviceRole, location),
+ getProcessesList(serviceRole, companyId),
+ getActiveJobOperationsByLocation(
+ serviceRole,
+ location,
+ selectedWorkCenterIds
+ ),
+ ]);
+
+ const activeWorkCenters = new Set();
+ operations.data?.forEach((op) => {
+ if (op.operationStatus === "In Progress") {
+ activeWorkCenters.add(op.workCenterId);
+ }
+ });
+
+ let filteredOperations = selectedWorkCenterIds.length
+ ? operations.data?.filter((op) =>
+ selectedWorkCenterIds.includes(op.workCenterId)
+ ) ?? []
+ : operations.data ?? [];
+
+ if (selectedSalesOrderIds.length) {
+ filteredOperations = filteredOperations.filter((op) =>
+ selectedSalesOrderIds.includes(op.salesOrderId)
+ );
+ }
+
+ if (search) {
+ filteredOperations = filteredOperations.filter(
+ (op) =>
+ op.jobReadableId.toLowerCase().includes(search.toLowerCase()) ||
+ op.itemReadableId.toLowerCase().includes(search.toLowerCase()) ||
+ op.description?.toLowerCase().includes(search.toLowerCase())
+ );
+ }
+
+ const filteredWorkCenters =
+ workCenters.data?.filter((wc: any) => {
+ if (selectedWorkCenterIds.length && selectedProcessIds.length) {
+ return (
+ selectedWorkCenterIds.includes(wc.id!) &&
+ wc.processes?.some((p: { id: string }) =>
+ selectedProcessIds.includes(p.id)
+ )
+ );
+ } else if (selectedWorkCenterIds.length) {
+ return selectedWorkCenterIds.includes(wc.id!);
+ } else if (selectedProcessIds.length) {
+ return wc.processes?.some((p: { id: string }) =>
+ selectedProcessIds.includes(p.id)
+ );
+ }
+ return true;
+ }) ?? [];
+
+ return json({
+ columns: filteredWorkCenters
+ .map((wc) => ({
+ id: wc.id!,
+ title: wc.name!,
+ type:
+ (wc.processes as { id: string; name: string }[] | undefined)?.map(
+ (p) => p.id
+ ) ?? [],
+ active: activeWorkCenters.has(wc.id),
+ }))
+ .sort((a, b) => a.title.localeCompare(b.title)) satisfies Column[],
+ items: (filteredOperations.map((op) => {
+ const operation = makeDurations(op);
+ return {
+ id: op.id,
+ columnId: op.workCenterId,
+ columnType: op.processId,
+ priority: op.priority,
+ title: op.jobReadableId,
+
+ subtitle: op.itemReadableId,
+ description: op.description,
+ dueDate: op.jobDueDate,
+ duration:
+ operation.setupDuration +
+ Math.max(operation.laborDuration, operation.machineDuration),
+ deadlineType: op.jobDeadlineType,
+ customerId: op.jobCustomerId,
+ salesOrderReadableId: op.salesOrderReadableId,
+ salesOrderId: op.salesOrderId,
+ salesOrderLineId: op.salesOrderLineId,
+ status: op.operationStatus,
+ };
+ }) ?? []) satisfies Item[],
+ processes: processes.data ?? [],
+ salesOrders: Object.entries(
+ filteredOperations?.reduce((acc, op) => {
+ if (op.salesOrderId) {
+ acc[op.salesOrderId] = op.salesOrderReadableId;
+ }
+ return acc;
+ }, {} as Record<string, string>) ?? {}
+ ).map(([id, readableId]) => ({ id, readableId })),
+ });
+}
+
+export default function Operations() {
+ const { columns, items, processes } = useLoaderData<typeof loader>();
+ const hasFilters = false; // TODO: implement filters
+
+ return (
+ <div className="flex flex-col h-full max-h-full overflow-auto relative">
+ <div className="flex flex-grow h-full items-stretch overflow-hidden relative">
+ <div className="flex flex-1 min-h-0 w-full relative">
+ {columns.length > 0 ? (
+ <ClientOnly
+ fallback={
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner className="h-8 w-8" />
+ </div>
+ }
+ >
+ {() => (
+ <Kanban
+ columns={columns}
+ items={items}
+ showCustomer
+ showDescription
+ showDueDate
+ showDuration
+ showEmployee
+ showProgress={false}
+ showStatus
+ showSalesOrder
+ />
+ )}
+ </ClientOnly>
+ ) : hasFilters ? (
+ <div className="flex flex-col w-full h-full items-center justify-center gap-4">
+ <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">
+ <LuAlertTriangle className="h-6 w-6" />
+ </div>
+ <span className="text-xs font-mono font-light text-foreground uppercase">
+ No results
+ </span>
+ {/* <Button onClick={clearFilters}>Clear Filters</Button> */}
+ </div>
+ ) : (
+ <div className="flex flex-col w-full h-full items-center justify-center gap-4">
+ <div className="flex justify-center items-center h-12 w-12 rounded-full bg-foreground text-background">
+ <LuAlertTriangle className="h-6 w-6" />
+ </div>
+ <span className="text-xs font-mono font-light text-foreground uppercase">
+ No work centers exist
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 9c891c52e0..0535f59519 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -74,6 +74,32 @@ export const documentTypes = [
"Other",
] as const;
+export const deadlineTypes = [
+ "ASAP",
+ "Hard Deadline",
+ "Soft Deadline",
+ "No Deadline",
+] as const;
+
+export const jobStatus = [
+ "Draft",
+ "Ready",
+ "In Progress",
+ "Paused",
+ "Completed",
+ "Cancelled",
+] as const;
+
+export const jobOperationStatus = [
+ "Todo",
+ "Ready",
+ "Waiting",
+ "In Progress",
+ "Paused",
+ "Done",
+ "Canceled",
+] as const;
+
export const productionEventType = ["Setup", "Labor", "Machine"] as const;
export const productionEventAction = ["Start", "End"] as const;
@@ -142,6 +168,17 @@ export async function getActiveJobOperationsByEmployee(
});
}
+export async function getActiveJobOperationsByLocation(
+ client: SupabaseClient<Database>,
+ locationId: string,
+ workCenterIds: string[] = []
+) {
+ return client.rpc("get_active_job_operations_by_location", {
+ location_id: locationId,
+ work_center_ids: workCenterIds,
+ });
+}
+
export async function getActiveJobCount(
client: SupabaseClient<Database>,
args: {
@@ -196,36 +233,6 @@ export function getFileType(fileName: string): (typeof documentTypes)[number] {
return "Other";
}
-export async function getThumbnailPathByItemId(
- client: SupabaseClient<Database>,
- itemId: string
-) {
- const { data: item } = await client
- .from("item")
- .select("thumbnailPath, modelUploadId")
- .eq("id", itemId)
- .single();
-
- if (!item) return null;
-
- const { thumbnailPath, modelUploadId } = item;
-
- if (!modelUploadId) return thumbnailPath;
-
- const { data: modelUpload } = await client
- .from("modelUpload")
- .select("thumbnailPath")
- .eq("id", modelUploadId)
- .single();
-
- const modelUploadThumbnailPath = modelUpload?.thumbnailPath;
-
- if (!thumbnailPath && modelUploadThumbnailPath) {
- return modelUploadThumbnailPath;
- }
- return thumbnailPath;
-}
-
export async function getJobFiles(
client: SupabaseClient<Database>,
companyId: string,
@@ -316,6 +323,17 @@ export async function getLocationsByCompany(
.order("name", { ascending: true });
}
+export async function getProcessesList(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("process")
+ .select(`id, name`)
+ .eq("companyId", companyId)
+ .order("name");
+}
+
export async function getProductionEventsForJobOperation(
client: SupabaseClient<Database>,
args: {
@@ -363,6 +381,36 @@ export async function getScrapReasonsList(
.order("name");
}
+export async function getThumbnailPathByItemId(
+ client: SupabaseClient<Database>,
+ itemId: string
+) {
+ const { data: item } = await client
+ .from("item")
+ .select("thumbnailPath, modelUploadId")
+ .eq("id", itemId)
+ .single();
+
+ if (!item) return null;
+
+ const { thumbnailPath, modelUploadId } = item;
+
+ if (!modelUploadId) return thumbnailPath;
+
+ const { data: modelUpload } = await client
+ .from("modelUpload")
+ .select("thumbnailPath")
+ .eq("id", modelUploadId)
+ .single();
+
+ const modelUploadThumbnailPath = modelUpload?.thumbnailPath;
+
+ if (!thumbnailPath && modelUploadThumbnailPath) {
+ return modelUploadThumbnailPath;
+ }
+ return thumbnailPath;
+}
+
export async function getWorkCenter(
client: SupabaseClient<Database>,
workCenterId: string
@@ -375,7 +423,7 @@ export async function getWorkCentersByLocation(
locationId: string
) {
return client
- .from("workCenter")
+ .from("workCenters")
.select("*")
.eq("locationId", locationId)
.eq("active", true)
diff --git a/apps/mes/app/styles/tailwind.css b/apps/mes/app/styles/tailwind.css
index 5e5585e4c2..6f28b6092d 100644
--- a/apps/mes/app/styles/tailwind.css
+++ b/apps/mes/app/styles/tailwind.css
@@ -17,6 +17,9 @@
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
+
+ --header-height: 50px;
+ --filters-height: 50px;
}
.dark {
diff --git a/apps/mes/package.json b/apps/mes/package.json
index f08181a70d..74647ae166 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -10,6 +10,8 @@
"@carbon/kv": "*",
"@carbon/form": "*",
"@carbon/utils": "*",
+ "@dnd-kit/core": "^6.1.0",
+ "@dnd-kit/sortable": "^8.0.0",
"@internationalized/date": "^3.5.2",
"@react-aria/i18n": "^3.11.0",
"@remix-run/dev": "~2.10.2",
diff --git a/package-lock.json b/package-lock.json
index 40caf040e9..48d1ff6b57 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -201,6 +201,8 @@
"@carbon/logger": "*",
"@carbon/react": "*",
"@carbon/utils": "*",
+ "@dnd-kit/core": "^6.1.0",
+ "@dnd-kit/sortable": "^8.0.0",
"@internationalized/date": "^3.5.2",
"@react-aria/i18n": "^3.11.0",
"@remix-run/dev": "~2.10.2",