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: simple scheduling algorithm

Brad Barbin7a71ec525c2b
diff --git a/apps/carbon/app/components/Kanban/Kanban.tsx b/apps/carbon/app/components/Kanban/Kanban.tsx
index 78eeaacce2..0dd7eedcd1 100644
--- a/apps/carbon/app/components/Kanban/Kanban.tsx
+++ b/apps/carbon/app/components/Kanban/Kanban.tsx
@@ -16,7 +16,7 @@ import {
useSensors,
} from "@dnd-kit/core";
import { SortableContext, arrayMove } from "@dnd-kit/sortable";
-import { useMemo, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { BoardContainer, ColumnCard } from "./components/ColumnCard";
import { ItemCard } from "./components/ItemCard";
@@ -34,13 +34,12 @@ const Kanban = ({
...displaySettings
}: KanbanProps) => {
const [columns, setColumns] = useState<Column[]>(initialColumns);
- const pickedUpItemColumn = useRef<string | null>(null);
- const columnIds = useMemo(() => columns.map((col) => col.id), [columns]);
-
const [items, setItems] = useState<Item[]>(initialItems);
- const [activeColumn, setActiveColumn] = useState<Column | null>(null);
+ const columnIds = useMemo(() => columns.map((col) => col.id), [columns]);
+ const pickedUpItemColumn = useRef<string | null>(null);
+ const [activeColumn, setActiveColumn] = useState<Column | null>(null);
const [activeItem, setActiveItem] = useState<Item | null>(null);
const sensors = useSensors(
@@ -51,6 +50,10 @@ const Kanban = ({
})
);
+ useEffect(() => {
+ setItems(initialItems);
+ }, [initialItems]);
+
function getDraggingItemData(itemId: UniqueIdentifier, columnId: string) {
const itemsInColumn = items.filter((item) => item.columnId === columnId);
const itemPosition = itemsInColumn.findIndex((item) => item.id === itemId);
diff --git a/apps/carbon/app/components/Kanban/components/ColumnCard.tsx b/apps/carbon/app/components/Kanban/components/ColumnCard.tsx
index 3a5d2ad55c..52faf8f2fa 100644
--- a/apps/carbon/app/components/Kanban/components/ColumnCard.tsx
+++ b/apps/carbon/app/components/Kanban/components/ColumnCard.tsx
@@ -33,7 +33,7 @@ export function ColumnCard({
}, [items]);
const totalDuration = items.reduce((acc, item) => {
- return acc + (item.duration ?? 0);
+ return acc + Math.max((item.duration ?? 0) - (item.progress ?? 0), 0);
}, 0);
const {
diff --git a/apps/carbon/app/components/Kanban/components/ItemCard.tsx b/apps/carbon/app/components/Kanban/components/ItemCard.tsx
index 769cc0208a..2e48d7bf32 100644
--- a/apps/carbon/app/components/Kanban/components/ItemCard.tsx
+++ b/apps/carbon/app/components/Kanban/components/ItemCard.tsx
@@ -29,7 +29,6 @@ import {
LuXCircle,
} from "react-icons/lu";
-import { motion } from "framer-motion";
import { AlmostDoneIcon } from "~/assets/icons/AlmostDoneIcon";
import { HighPriorityIcon } from "~/assets/icons/HighPriorityIcon";
import { InProgressStatusIcon } from "~/assets/icons/InProgressStatusIcon";
@@ -70,8 +69,6 @@ const cardVariants = cva(
}
);
-const MotionCard = motion(Card);
-
const cardHeaderVariants = cva("border-b", {
variants: {
status: {
@@ -129,7 +126,7 @@ export function ItemCard({
: false;
return (
- <MotionCard
+ <Card
ref={setNodeRef}
style={style}
className={cn(
@@ -247,7 +244,7 @@ export function ItemCard({
</HStack>
)}
</CardContent>
- </MotionCard>
+ </Card>
);
}
diff --git a/apps/carbon/app/routes/x+/scheduling+/index.tsx b/apps/carbon/app/routes/x+/scheduling+/index.tsx
index 8c0b27b342..c05db49c8f 100644
--- a/apps/carbon/app/routes/x+/scheduling+/index.tsx
+++ b/apps/carbon/app/routes/x+/scheduling+/index.tsx
@@ -8,6 +8,7 @@ import {
useLocalStorage,
} from "@carbon/react";
import type { LoaderFunctionArgs } from "@remix-run/node";
+import { useRevalidator } from "@remix-run/react";
import { HiOutlineAdjustmentsHorizontal } from "react-icons/hi2";
import { LuListFilter, LuRefreshCcw } from "react-icons/lu";
import { typedjson, useTypedLoaderData } from "remix-typedjson";
@@ -19,13 +20,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
return typedjson({
columns: [
{
- id: "1",
+ id: getRandomBetweenRange(1, 2),
type: "assembly",
title: "Assembly Station 1",
active: true,
},
{
- id: "2",
+ id: getRandomBetweenRange(1, 2),
type: "assembly",
title: "Assembly Station 2",
},
@@ -98,9 +99,22 @@ export async function loader({ request }: LoaderFunctionArgs) {
deadlineType: "NO_DEADLINE",
status: "READY",
},
+ {
+ id: "item6",
+ columnId: "1",
+ columnType: "assembly",
+ title: "1013",
+ subtitle: "F011432",
+ description: "Assemble",
+ deadlineType: "NO_DEADLINE",
+ duration: 2 * 60 * 60 * 1000,
+ employeeIds: ["52cdefed-f4b7-45b1-9ec8-701473671fb7"],
+ status: "IN_PROGRESS",
+ progress: 35 * 60 * 1000,
+ },
{
id: "item4",
- columnId: "2",
+ columnId: getRandomBetweenRange(1, 2),
columnType: "assembly",
title: "1492",
subtitle: "F011432",
@@ -111,7 +125,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
},
{
id: "item5",
- columnId: "2",
+ columnId: getRandomBetweenRange(1, 2),
columnType: "assembly",
title: "1109",
subtitle: "F011432",
@@ -121,22 +135,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
deadlineType: "SOFT_DEADLINE",
status: "WAITING",
},
- {
- id: "item6",
- columnId: "1",
- columnType: "assembly",
- title: "1013",
- subtitle: "F011432",
- description: "Assemble",
- deadlineType: "NO_DEADLINE",
- duration: 2 * 60 * 60 * 1000,
- employeeIds: ["52cdefed-f4b7-45b1-9ec8-701473671fb7"],
- status: "IN_PROGRESS",
- progress: 35 * 60 * 1000,
- },
+
{
id: "item7",
- columnId: "1",
+ columnId: getRandomBetweenRange(1, 2),
columnType: "assembly",
title: "1014",
subtitle: "F011432",
@@ -149,7 +151,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
},
{
id: "item8",
- columnId: "1",
+ columnId: getRandomBetweenRange(1, 2),
columnType: "assembly",
title: "1032",
subtitle: "F011432",
@@ -162,7 +164,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
},
{
id: "item9",
- columnId: "1",
+ columnId: getRandomBetweenRange(1, 2),
columnType: "assembly",
title: "1010",
subtitle: "F011432",
@@ -174,7 +176,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
},
{
id: "item10",
- columnId: "1",
+ columnId: getRandomBetweenRange(1, 2),
columnType: "assembly",
title: "1403",
subtitle: "F011432",
@@ -192,6 +194,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
export default function KanbanView() {
const { columns, items } = useTypedLoaderData<typeof loader>();
const [kanbanSettings, setKanbanSettings] = useKanbanSettings();
+ const revalidator = useRevalidator();
return (
<div className="flex flex-col h-full max-h-full overflow-auto relative">
@@ -274,7 +277,11 @@ export default function KanbanView() {
</div>
</PopoverContent>
</Popover>
- <Button leftIcon={<LuRefreshCcw />} variant="secondary">
+ <Button
+ leftIcon={<LuRefreshCcw />}
+ variant="secondary"
+ onClick={revalidator.revalidate}
+ >
Reschedule
</Button>
</HStack>
@@ -313,3 +320,7 @@ function useKanbanSettings() {
return [kanbanSettings, updateKanbanSettings] as const;
}
+
+function getRandomBetweenRange(min: number, max: number) {
+ return Math.floor(Math.random() * (max - min + 1) + min).toString();
+}
diff --git a/packages/database/supabase/functions/scheduler/data.ts b/packages/database/supabase/functions/scheduler/data.ts
new file mode 100644
index 0000000000..3a2f331aea
--- /dev/null
+++ b/packages/database/supabase/functions/scheduler/data.ts
@@ -0,0 +1,167 @@
+export const jobs = [
+ {
+ id: "10323",
+ deadlineDate: "2024-05-20",
+ deadlineType: "SOFT_DEADLINE",
+ operations: [
+ {
+ id: "operation0",
+ duration: 6 * 60 * 60 * 1000,
+ status: "DONE",
+ workCenterType: "cnc",
+ },
+ {
+ id: "operation1",
+ duration: 2 * 60 * 60 * 1000,
+ status: "IN_PROGRESS",
+ workCenterType: "assembly",
+ timecards: [
+ {
+ start: "2024-05-20T08:00:00",
+ end: "2024-05-20T9:00:00",
+ machine: "assembly1",
+ },
+ ],
+ },
+ {
+ id: "operation2",
+ duration: 4 * 60 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "inspection",
+ },
+ ],
+ },
+ {
+ id: "10324",
+ deadlineDate: "2024-06-20",
+ deadlineType: "HARD_DEADLINE",
+ operations: [
+ {
+ id: "operation3",
+ duration: 20 * 60 * 1000,
+ status: "WAITING",
+ workCenterType: "assembly",
+ },
+ {
+ id: "operation4",
+ duration: 10 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "inspection",
+ },
+ ],
+ },
+ {
+ id: "10325",
+ deadlineDate: "2024-07-20",
+ deadlineType: "SOFT_DEADLINE",
+ operations: [
+ {
+ id: "operation5",
+ duration: 8 * 60 * 60 * 1000,
+ status: "PAUSED",
+ workCenterType: "cnc",
+ timecards: [
+ {
+ start: "2024-07-20T08:00:00",
+ end: "2024-07-20T10:00:00",
+ machine: "cnc1",
+ },
+ ],
+ },
+ {
+ id: "operation6",
+ duration: 3 * 60 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "saw",
+ },
+ {
+ id: "operation7",
+ duration: 5 * 60 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "assembly",
+ },
+ ],
+ },
+ {
+ id: "10326",
+ deadlineDate: "2024-08-20",
+ deadlineType: "HARD_DEADLINE",
+ operations: [
+ {
+ id: "operation8",
+ duration: 15 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "saw",
+ },
+ {
+ id: "operation9",
+ duration: 12 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "inspection",
+ },
+ ],
+ },
+ {
+ id: "10327",
+ deadlineDate: "2024-09-20",
+ deadlineType: "SOFT_DEADLINE",
+ operations: [
+ {
+ id: "operation10",
+ duration: 10 * 60 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "cnc",
+ },
+ {
+ id: "operation11",
+ duration: 4 * 60 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "assembly",
+ },
+ {
+ id: "operation12",
+ duration: 6 * 60 * 60 * 1000,
+ status: "TODO",
+ workCenterType: "inspection",
+ },
+ ],
+ },
+];
+
+export const workCenters = [
+ {
+ id: "cnc1",
+ name: "CNC 1",
+ workCenterType: "cnc",
+ },
+ {
+ id: "cnc2",
+ name: "CNC 2",
+ workCenterType: "cnc",
+ },
+ {
+ id: "saw1",
+ name: "Saw 1",
+ workCenterType: "saw",
+ },
+ {
+ id: "saw2",
+ name: "Saw 2",
+ workCenterType: "saw",
+ },
+ {
+ id: "assembly1",
+ name: "Assembly 1",
+ workCenterType: "assembly",
+ },
+ {
+ id: "assembly2",
+ name: "Assembly 2",
+ workCenterType: "assembly",
+ },
+ {
+ id: "inspection1",
+ name: "Inspection 1",
+ workCenterType: "inspection",
+ },
+];
diff --git a/packages/database/supabase/functions/scheduler/index.ts b/packages/database/supabase/functions/scheduler/index.ts
new file mode 100644
index 0000000000..487c0e4e74
--- /dev/null
+++ b/packages/database/supabase/functions/scheduler/index.ts
@@ -0,0 +1,189 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+
+import { corsHeaders } from "../lib/headers.ts";
+import { jobs, workCenters } from "./data.ts";
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ try {
+ // const client = getSupabaseServiceRole(req.headers.get("Authorization"));
+ const workCenterManager = new LoadBalancer(workCenters);
+
+ const operationsByType = jobs.reduce((acc, job) => {
+ job.operations.forEach((operation) => {
+ if (operation.status === "DONE") return;
+ acc[operation.workCenterType] = acc[operation.workCenterType] || [];
+ acc[operation.workCenterType].push({
+ ...operation,
+ jobId: job.id,
+ deadlineDate: job.deadlineDate,
+ deadlineType: job.deadlineType,
+ });
+ });
+ return acc;
+ }, {} as Record<string, Operation[]>);
+
+ const sortedOperationsByType = Object.entries(operationsByType).reduce(
+ (acc, [workCenterType, operations]) => {
+ acc[workCenterType] = sortOperations(operations);
+ return acc;
+ },
+ {} as Record<string, Operation[]>
+ );
+
+ const operationsWithWorkCenter: OperationWithWorkCenter[] = Object.values(
+ sortedOperationsByType
+ ).flatMap((operations) =>
+ operations.map((operation) => {
+ const { workCenterType } = operation;
+
+ const workCenter =
+ workCenterManager.getWorkCenterWithLeastWork(workCenterType);
+
+ workCenterManager.addWorkToWorkCenter(
+ workCenterType,
+ workCenter.id,
+ operation.duration
+ );
+
+ return { ...operation, workCenterId: workCenter.id };
+ })
+ );
+
+ return new Response(
+ JSON.stringify({
+ operationsWithWorkCenter,
+ workCenters,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ }
+ );
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
+
+type WorkCenter = {
+ id: string;
+ name: string;
+ workCenterType: string;
+};
+
+type Operation = {
+ id: string;
+ jobId: string;
+ deadlineDate: string;
+ deadlineType: string;
+ duration: number;
+ status: string;
+ workCenterType: string;
+ timecards?: {
+ start: string;
+ end?: string;
+ machine?: string;
+ }[];
+};
+
+type OperationWithWorkCenter = Operation & {
+ workCenterId: string;
+};
+
+function sortOperations(operations: Operation[]) {
+ return operations.sort((a, b) => {
+ // First should come anything that's in progress
+ if (a.status === "IN_PROGRESS" && b.status !== "IN_PROGRESS") {
+ return -1;
+ } else if (a.status !== "IN_PROGRESS" && b.status === "IN_PROGRESS") {
+ return 1;
+ }
+ // Then anything that's paused
+ else if (a.status === "PAUSED" && b.status !== "PAUSED") {
+ return -1;
+ } else if (a.status !== "PAUSED" && b.status === "PAUSED") {
+ return 1;
+ }
+ // Then anything that's ASAP
+ else if (a.deadlineType === "ASAP" && b.deadlineType !== "ASAP") {
+ return -1;
+ } else if (a.deadlineType !== "ASAP" && b.deadlineType === "ASAP") {
+ return 1;
+ }
+ // Then we sort deadlines
+ else if (
+ a.deadlineType === "HARD_DEADLINE" ||
+ a.deadlineType === "SOFT_DEADLINE"
+ ) {
+ if (
+ b.deadlineType === "HARD_DEADLINE" ||
+ b.deadlineType === "SOFT_DEADLINE"
+ ) {
+ return a.deadlineDate.localeCompare(b.deadlineDate);
+ } else {
+ return -1;
+ }
+ }
+ // Finally we add anything that has no deadline
+ else if (
+ a.deadlineType === "NO_DEADLINE" &&
+ b.deadlineType !== "NO_DEADLINE"
+ ) {
+ return 1;
+ } else if (
+ a.deadlineType === "NO_DEADLINE" &&
+ b.deadlineType === "NO_DEADLINE"
+ ) {
+ return a.deadlineDate.localeCompare(b.deadlineDate);
+ } else {
+ return 0;
+ }
+ });
+}
+
+type WorkCenterWithDuration = WorkCenter & {
+ duration: number;
+};
+
+class LoadBalancer {
+ private workCentersByType: Record<string, WorkCenterWithDuration[]> = {};
+
+ constructor(workCenters: WorkCenter[]) {
+ this.workCentersByType = workCenters.reduce<
+ Record<string, WorkCenterWithDuration[]>
+ >((acc, machine) => {
+ acc[machine.workCenterType] = acc[machine.workCenterType] || [];
+ acc[machine.workCenterType].push({ ...machine, duration: 0 });
+ return acc;
+ }, {});
+ }
+
+ public getWorkCenterWithLeastWork(workCenterType: string) {
+ const workCenters = this.workCentersByType[workCenterType];
+ return workCenters.reduce((minWorkCenter, workCenter) =>
+ workCenter.duration < minWorkCenter.duration ? workCenter : minWorkCenter
+ );
+ }
+
+ public addWorkToWorkCenter(
+ workCenterType: string,
+ workCenterId: string,
+ duration: number
+ ) {
+ this.workCentersByType[workCenterType] = this.workCentersByType[
+ workCenterType
+ ].map((workCenter) => {
+ if (workCenter.id === workCenterId) {
+ return { ...workCenter, duration: workCenter.duration + duration };
+ }
+ return workCenter;
+ });
+ }
+}