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.

Kanban Schedule (#84)

Brad Barbinff4aef17bd47
diff --git a/apps/carbon/app/components/ItemThumbnail.tsx b/apps/carbon/app/components/ItemThumbnail.tsx
index 5cbaf770c0..ab6ae656dc 100644
--- a/apps/carbon/app/components/ItemThumbnail.tsx
+++ b/apps/carbon/app/components/ItemThumbnail.tsx
@@ -63,7 +63,6 @@ const iconVariants = cva("text-muted-foreground", {
const ItemThumbnail = ({
thumbnailPath,
- modelId,
type,
size = "md",
}: ItemThumbnailProps) => {
diff --git a/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx
index f7568e2b19..ce6533869f 100644
--- a/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/carbon/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -27,7 +27,7 @@ const inventoryRoutes: AuthenticatedRouteGroup[] = [
name: "Configure",
routes: [
{
- name: "Shipping Methods",
+ name: "Shipping",
to: path.to.shippingMethods,
role: "employee",
icon: <LuTruck />,
diff --git a/apps/carbon/app/modules/production/production.models.ts b/apps/carbon/app/modules/production/production.models.ts
index 44d830a77b..c583d3a541 100644
--- a/apps/carbon/app/modules/production/production.models.ts
+++ b/apps/carbon/app/modules/production/production.models.ts
@@ -425,3 +425,9 @@ export const productionQuantityValidator = z.object({
createdBy: zfd.text(z.string().optional()),
quantity: zfd.numeric(z.number().min(0)),
});
+
+export const scheduleOperationUpdateValidator = z.object({
+ id: z.string().min(1, { message: "ID is required" }),
+ columnId: z.string().min(1, { message: "Column is required" }),
+ priority: zfd.numeric(z.number().min(0).optional()),
+});
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index c30bf9787c..45c186f458 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -58,6 +58,17 @@ export async function deleteProductionQuantity(
.eq("id", productionQuantityId);
}
+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 getJobDocuments(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/carbon/app/components/Kanban/Kanban.tsx b/apps/carbon/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
similarity index 55%
rename from apps/carbon/app/components/Kanban/Kanban.tsx
rename to apps/carbon/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
index 0dd7eedcd1..e9d16b8910 100644
--- a/apps/carbon/app/components/Kanban/Kanban.tsx
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
@@ -16,8 +16,10 @@ import {
useSensors,
} from "@dnd-kit/core";
import { SortableContext, arrayMove } from "@dnd-kit/sortable";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useFetchers, useSubmit } from "@remix-run/react";
+import { useRef, useState } from "react";
import { createPortal } from "react-dom";
+import { path } from "~/utils/path";
import { BoardContainer, ColumnCard } from "./components/ColumnCard";
import { ItemCard } from "./components/ItemCard";
import type { Column, DisplaySettings, Item } from "./types";
@@ -29,14 +31,31 @@ type KanbanProps = {
} & DisplaySettings;
const Kanban = ({
- columns: initialColumns,
+ columns,
items: initialItems,
...displaySettings
}: KanbanProps) => {
- const [columns, setColumns] = useState<Column[]>(initialColumns);
- const [items, setItems] = useState<Item[]>(initialItems);
+ const submit = useSubmit();
+ const [columnOrder, setColumnOrder] = useState<string[]>(
+ columns.map((col) => col.id)
+ );
+
+ const itemsById = new Map<string, Item>(
+ initialItems.map((item) => [item.id, item])
+ );
+ const pendingItems = usePendingItems();
+
+ // merge pending items and existing items
+ for (let pendingItem of pendingItems) {
+ let item = itemsById.get(pendingItem.id);
+ if (item) {
+ itemsById.set(pendingItem.id, { ...item, ...pendingItem });
+ }
+ }
- const columnIds = useMemo(() => columns.map((col) => col.id), [columns]);
+ const items = Array.from(itemsById.values()).sort(
+ (a, b) => a.priority - b.priority
+ );
const pickedUpItemColumn = useRef<string | null>(null);
const [activeColumn, setActiveColumn] = useState<Column | null>(null);
@@ -50,10 +69,6 @@ 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);
@@ -69,11 +84,11 @@ const Kanban = ({
onDragStart({ active }) {
if (!hasDraggableData(active)) return;
if (active.data.current?.type === "column") {
- const startstringx = columnIds.findIndex((id) => id === active.id);
- const startColumn = columns[startstringx];
+ 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: ${
- startstringx + 1
- } of ${columnIds.length}`;
+ startIndex + 1
+ } of ${columnOrder.length}`;
} else if (active.data.current?.type === "item") {
pickedUpItemColumn.current = active.data.current.item.columnId;
const { itemsInColumn, itemPosition, column } = getDraggingItemData(
@@ -92,10 +107,10 @@ const Kanban = ({
active.data.current?.type === "column" &&
over.data.current?.type === "column"
) {
- const overstringx = columnIds.findIndex((id) => id === over.id);
+ 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 ${overstringx + 1} of ${columnIds.length}`;
+ } at position ${overIndex + 1} of ${columnOrder.length}`;
} else if (
active.data.current?.type === "item" &&
over.data.current?.type === "item"
@@ -125,12 +140,14 @@ const Kanban = ({
active.data.current?.type === "column" &&
over.data.current?.type === "column"
) {
- const overColumnPosition = columnIds.findIndex((id) => id === over.id);
+ const overColumnPosition = columnOrder.findIndex(
+ (id) => id === over.id
+ );
return `Column ${
active.data.current.column.title
} was dropped into position ${overColumnPosition + 1} of ${
- columnIds.length
+ columnOrder.length
}`;
} else if (
active.data.current?.type === "item" &&
@@ -169,15 +186,19 @@ const Kanban = ({
onDragOver={onDragOver}
>
<BoardContainer>
- <SortableContext items={columnIds}>
- {columns.map((col) => (
- <ColumnCard
- key={col.id}
- column={col}
- items={items.filter((item) => item.columnId === col.id)}
- {...displaySettings}
- />
- ))}
+ <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>
@@ -240,11 +261,11 @@ const Kanban = ({
const isActiveAColumn = activeData?.type === "column";
if (!isActiveAColumn) return;
- setColumns((columns) => {
- const activeColumnIndex = columns.findIndex((col) => col.id === activeId);
- const overColumnIndex = columns.findIndex((col) => col.id === overId);
+ setColumnOrder((prevOrder) => {
+ const activeColumnIndex = prevOrder.findIndex((id) => id === activeId);
+ const overColumnIndex = prevOrder.findIndex((id) => id === overId);
- return arrayMove(columns, activeColumnIndex, overColumnIndex);
+ return arrayMove(prevOrder, activeColumnIndex, overColumnIndex);
});
}
@@ -262,48 +283,142 @@ const Kanban = ({
const activeData = active.data.current;
const overData = over.data.current;
+ const overColumn =
+ overData?.type === "item"
+ ? columns.find((col) => col.id === overData.item.columnId)
+ : overData?.column;
+
+ const isActiveAnItem = activeData?.type === "item";
+ const isOverAnItem = overData?.type === "item";
- const isActiveAItem = activeData?.type === "item";
- const isOverAItem = overData?.type === "item";
+ const activeItem = itemsById.get(activeId.toString());
+ const overItem = itemsById.get(overId.toString());
- if (!isActiveAItem) return;
- if (activeData?.item.columnType !== overData?.item?.columnType) return; // only allow drop if both columns are same type
+ if (!isActiveAnItem) return;
+
+ // only allow drop if column type array includes item's column type
+ if (!overColumn?.type.includes(activeData?.item.columnType)) return;
// Im dropping a Item over another Item
- if (isActiveAItem && isOverAItem) {
- setItems((items) => {
- const activeIndex = items.findIndex((t) => t.id === activeId);
- const overIndex = items.findIndex((t) => t.id === overId);
- const activeItem = items[activeIndex];
- const overItem = items[overIndex];
- if (
- activeItem &&
- overItem &&
- activeItem.columnId !== overItem.columnId
- ) {
- activeItem.columnId = overItem.columnId;
- return arrayMove(items, activeIndex, overIndex - 1);
+ if (isActiveAnItem && isOverAnItem && activeItem && overItem) {
+ let priorityBefore = 0;
+ let priorityAfter = 0;
+ if (
+ activeItem.priority > overItem.priority ||
+ activeItem.columnId !== overItem.columnId
+ ) {
+ priorityAfter = overItem.priority;
+
+ for (let i = items.length - 1; i >= 0; i--) {
+ const item = items[i];
+ if (
+ item.columnId === overItem.columnId &&
+ item.priority < priorityAfter
+ ) {
+ priorityBefore = item.priority ?? 0;
+ break;
+ }
}
+ } else {
+ priorityBefore = overItem.priority;
+ priorityAfter =
+ items.find(
+ (item) =>
+ item.columnId === overItem.columnId &&
+ item.priority > priorityBefore
+ )?.priority ?? priorityBefore + 1;
+ }
+
+ const newPriority = (priorityBefore + priorityAfter) / 2;
+
+ if (activeItem.columnId !== overItem.columnId) {
+ submit(
+ {
+ id: activeItem.id,
+ columnId: overItem.columnId,
+ priority: newPriority,
+ },
+ {
+ method: "post",
+ action: path.to.scheduleOperationUpdate,
+ navigate: false,
+ fetcherKey: `item:${activeItem.id}`,
+ }
+ );
+ return;
+ }
- return arrayMove(items, activeIndex, overIndex);
- });
+ if (activeItem && overItem) {
+ submit(
+ {
+ id: activeItem.id,
+ columnId: activeItem.columnId,
+ priority: newPriority,
+ },
+ {
+ method: "post",
+ action: path.to.scheduleOperationUpdate,
+ navigate: false,
+ fetcherKey: `item:${activeItem.id}`,
+ }
+ );
+ }
+ return;
}
const isOverAColumn = overData?.type === "column";
// Im dropping a Item over a column
- if (isActiveAItem && isOverAColumn) {
- setItems((items) => {
- const activeIndex = items.findIndex((t) => t.id === activeId);
- const activeItem = items[activeIndex];
- if (activeItem) {
- activeItem.columnId = overId as string;
- return arrayMove(items, activeIndex, activeIndex);
- }
- return items;
- });
+ if (isActiveAnItem && isOverAColumn) {
+ const activeItem = itemsById.get(activeId.toString());
+ const columnId = overId as string;
+
+ if (activeItem) {
+ const firstItemInColumn = items.find(
+ (item) => item.columnId === columnId
+ );
+ const priorityBefore = 0;
+ const priorityAfter = firstItemInColumn?.priority ?? 1;
+
+ const newPriority = (priorityBefore + priorityAfter) / 2;
+
+ submit(
+ {
+ id: activeItem.id,
+ columnId,
+ priority: newPriority,
+ },
+ {
+ method: "post",
+ action: path.to.scheduleOperationUpdate,
+ navigate: false,
+ fetcherKey: `item:${activeItem.id}`,
+ }
+ );
+ }
}
}
};
+function usePendingItems() {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.scheduleOperationUpdate;
+ })
+ .map((fetcher) => {
+ let columnId = String(fetcher.formData.get("columnId"));
+ let id = String(fetcher.formData.get("id"));
+ let priority = Number(fetcher.formData.get("priority"));
+ let item: { id: string; priority: number; columnId: string } = {
+ id,
+ priority,
+ columnId,
+ };
+ return item;
+ });
+}
+
export default Kanban;
diff --git a/apps/carbon/app/components/Kanban/components/ColumnCard.tsx b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
similarity index 77%
rename from apps/carbon/app/components/Kanban/components/ColumnCard.tsx
rename to apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
index 52faf8f2fa..15409077c5 100644
--- a/apps/carbon/app/components/Kanban/components/ColumnCard.tsx
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
@@ -3,6 +3,7 @@ import {
Card,
CardContent,
CardHeader,
+ cn,
ScrollArea,
ScrollBar,
} from "@carbon/react";
@@ -13,6 +14,7 @@ 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";
import type { Column, ColumnDragData, DisplaySettings, Item } from "../types";
import { ItemCard } from "./ItemCard";
@@ -28,6 +30,8 @@ export function ColumnCard({
isOverlay,
...displaySettings
}: ColumnCardProps) {
+ const [params] = useUrlParams();
+ const currentFilters = params.getAll("filter");
const itemsIds = useMemo(() => {
return items.map((item) => item.id);
}, [items]);
@@ -60,7 +64,7 @@ export function ColumnCard({
};
const variants = cva(
- "w-[350px] max-w-full bg-primary-foreground flex flex-col flex-shrink-0 snap-center",
+ "w-[350px] max-w-full bg-primary-foreground flex flex-col flex-shrink-0 snap-center rounded-none",
{
variants: {
dragging: {
@@ -76,19 +80,28 @@ export function ColumnCard({
<Card
ref={setNodeRef}
style={style}
- className={variants({
- dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
- })}
+ className={cn(
+ `${variants({
+ dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
+ })} flex flex-col p-[1px] pt-0`,
+ currentFilters.length > 0
+ ? "h-[calc(100dvh-135px)]"
+ : "h-[calc(100dvh-98px)]"
+ )}
>
- <CardHeader className="p-4 w-full font-semibold text-left flex flex-row space-between items-center">
+ <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 && (
+ {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>
@@ -96,14 +109,14 @@ export function ColumnCard({
variant={"ghost"}
{...attributes}
{...listeners}
- className=" p-1 text-foreground/50 -ml-2 h-auto cursor-grab relative"
+ className="p-1 text-foreground/50 -ml-2 h-auto cursor-grab relative"
>
<span className="sr-only">{`Move column: ${column.title}`}</span>
<LuGripVertical />
</Button>
</CardHeader>
- <ScrollArea>
- <CardContent className="flex flex-grow flex-col gap-2 p-2">
+ <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} />
@@ -118,7 +131,7 @@ export function ColumnCard({
export function BoardContainer({ children }: { children: React.ReactNode }) {
const dndContext = useDndContext();
- const variations = cva("px-2 md:px-0 flex lg:justify-center pb-4", {
+ const variations = cva("px-0 flex lg:justify-center", {
variants: {
dragging: {
default: "snap-x snap-mandatory",
@@ -133,7 +146,7 @@ export function BoardContainer({ children }: { children: React.ReactNode }) {
dragging: dndContext.active ? "active" : "default",
})}
>
- <div className="flex gap-0.5 items-start flex-row justify-start p-0.5">
+ <div className="flex gap-0 items-start flex-row justify-start p-0">
{children}
</div>
<ScrollBar orientation="horizontal" />
diff --git a/apps/carbon/app/components/Kanban/components/ItemCard.tsx b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
similarity index 81%
rename from apps/carbon/app/components/Kanban/components/ItemCard.tsx
rename to apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
index 8e5fdf8d7d..310c6449cf 100644
--- a/apps/carbon/app/components/Kanban/components/ItemCard.tsx
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
@@ -50,17 +50,17 @@ const cardVariants = cva(
"ring-2 ring-primary hover:from-muted hover:via-muted hover:to-muted",
},
status: {
- IN_PROGRESS: "border-emerald-600/30 from-emerald-600/10",
- READY: "",
- DONE: "",
- PAUSED: "",
- CANCELED: "",
- WAITING: "border-red-500/30 from-red-500/10",
- TODO: "border-border",
+ "In Progress": "border-emerald-600/30 from-emerald-600/10",
+ Ready: "",
+ Done: "",
+ Paused: "border-yellow-500/30 from-yellow-500/10",
+ Canceled: "border-red-500/30 from-red-500/10",
+ Waiting: "border-yellow-500/30 from-yellow-500/10",
+ Todo: "border-border",
},
},
defaultVariants: {
- status: "TODO",
+ status: "Todo",
},
}
);
@@ -68,17 +68,17 @@ const cardVariants = cva(
const cardHeaderVariants = cva("border-b", {
variants: {
status: {
- IN_PROGRESS: "border-emerald-600/30",
- READY: "",
- DONE: "",
- PAUSED: "",
- CANCELED: "",
- WAITING: "border-red-500/30",
- TODO: "border-border",
+ "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",
+ status: "Todo",
},
});
@@ -144,11 +144,13 @@ export function ItemCard({
<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 truncate">
+ <span className="text-xs text-muted-foreground line-clamp-1">
{item.subtitle}
</span>
)}
- <span className="mr-auto font-semibold truncate">{item.title}</span>
+ <span className="mr-auto font-semibold line-clamp-1">
+ {item.title}
+ </span>
</div>
<Button
variant={"ghost"}
@@ -162,10 +164,10 @@ export function ItemCard({
</div>
{showProgress &&
- ["PAUSED", "DONE", "IN_PROGRESS"].includes(item.status!) && (
+ ["Paused", "Done", "In Progress"].includes(item.status!) && (
<Progress
indicatorClassName={
- item.status === "PAUSED" ? "bg-yellow-500" : ""
+ item.status === "Paused" ? "bg-yellow-500" : ""
}
numerator={
item.progress ? formatDurationMilliseconds(item.progress) : ""
@@ -185,16 +187,16 @@ export function ItemCard({
{showDescription && item.description && (
<HStack className="justify-start space-x-2">
<LuClipboardCheck className="text-muted-foreground" />
- <span className="text-sm">{item.description}</span>
+ <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">{getStatusText(item.status)}</span>
+ <span className="text-sm">{item.status}</span>
</HStack>
)}
- {showDuration && item.duration && (
+ {showDuration && typeof item.duration === "number" && (
<HStack className="justify-start space-x-2">
<LuTimer className="text-muted-foreground" />
<span className="text-sm">
@@ -246,38 +248,19 @@ export function ItemCard({
function getStatusIcon(status: Item["status"]) {
switch (status) {
- case "READY":
- case "TODO":
+ case "Ready":
+ case "Todo":
return <TodoStatusIcon className="text-foreground" />;
- case "WAITING":
- case "CANCELED":
+ case "Waiting":
+ case "Canceled":
return <LuXCircle className="text-muted-foreground" />;
- case "DONE":
+ case "Done":
return <LuCheckCircle className="text-blue-600" />;
- case "IN_PROGRESS":
+ case "In Progress":
return <AlmostDoneIcon />;
- case "PAUSED":
+ case "Paused":
return <InProgressStatusIcon />;
default:
return null;
}
}
-
-function getStatusText(status: Item["status"], overdue: boolean = false) {
- switch (status) {
- case "READY":
- return "Ready";
- case "TODO":
- return "Todo";
- case "WAITING":
- return "Waiting";
- case "CANCELED":
- return "Canceled";
- case "DONE":
- return "Done";
- case "IN_PROGRESS":
- return "In progress";
- case "PAUSED":
- return "Paused";
- }
-}
diff --git a/apps/carbon/app/components/Kanban/index.ts b/apps/carbon/app/modules/production/ui/Schedule/Kanban/index.ts
similarity index 100%
rename from apps/carbon/app/components/Kanban/index.ts
rename to apps/carbon/app/modules/production/ui/Schedule/Kanban/index.ts
diff --git a/apps/carbon/app/components/Kanban/types.ts b/apps/carbon/app/modules/production/ui/Schedule/Kanban/types.ts
similarity index 86%
rename from apps/carbon/app/components/Kanban/types.ts
rename to apps/carbon/app/modules/production/ui/Schedule/Kanban/types.ts
index dfad2cf2dc..ff921c71ad 100644
--- a/apps/carbon/app/components/Kanban/types.ts
+++ b/apps/carbon/app/modules/production/ui/Schedule/Kanban/types.ts
@@ -1,11 +1,11 @@
import { z } from "zod";
-import { deadlineTypes } from "~/modules/production";
+import { deadlineTypes, jobOperationStatus } from "~/modules/production";
export const columnValidator = z.object({
id: z.string(),
title: z.string(),
active: z.boolean().optional(),
- type: z.string(),
+ type: z.array(z.string()),
});
export type Column = z.infer<typeof columnValidator>;
@@ -33,6 +33,7 @@ const itemValidator = z.object({
columnType: z.string(),
title: z.string(),
subtitle: z.string().optional(),
+ priority: z.number(),
customerId: z.string().optional(),
employeeIds: z.array(z.string()).optional(),
description: z.string().optional(),
@@ -40,17 +41,7 @@ const itemValidator = z.object({
duration: z.number().optional(), // miliseconds
deadlineType: z.enum(deadlineTypes).optional(),
progress: z.number().optional(), // miliseconds
- status: z
- .enum([
- "CANCELED",
- "DONE",
- "IN_PROGRESS",
- "PAUSED",
- "READY",
- "TODO",
- "WAITING",
- ])
- .optional(),
+ status: z.enum(jobOperationStatus).optional(),
});
export type Item = z.infer<typeof itemValidator>;
diff --git a/apps/carbon/app/components/Kanban/utils.ts b/apps/carbon/app/modules/production/ui/Schedule/Kanban/utils.ts
similarity index 100%
rename from apps/carbon/app/components/Kanban/utils.ts
rename to apps/carbon/app/modules/production/ui/Schedule/Kanban/utils.ts
diff --git a/apps/carbon/app/modules/production/ui/Schedule/index.ts b/apps/carbon/app/modules/production/ui/Schedule/index.ts
new file mode 100644
index 0000000000..ca9fa78b94
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Schedule/index.ts
@@ -0,0 +1,2 @@
+export { Kanban } from "./Kanban";
+export type { Column, Item } from "./Kanban";
diff --git a/apps/carbon/app/modules/production/ui/index.ts b/apps/carbon/app/modules/production/ui/index.ts
index 7898de7c0f..5ca76c5569 100644
--- a/apps/carbon/app/modules/production/ui/index.ts
+++ b/apps/carbon/app/modules/production/ui/index.ts
@@ -1,4 +1,4 @@
import useProductionSubmodules from "./useProductionSubmodules";
export * from "./Jobs";
-
+export * from "./Schedule";
export { useProductionSubmodules };
diff --git a/apps/carbon/app/modules/production/ui/useProductionSubmodules.tsx b/apps/carbon/app/modules/production/ui/useProductionSubmodules.tsx
index 8389dc6af3..e3bac18c32 100644
--- a/apps/carbon/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/carbon/app/modules/production/ui/useProductionSubmodules.tsx
@@ -1,4 +1,4 @@
-import { LuHardHat } from "react-icons/lu";
+import { LuCalendarClock, LuHardHat } from "react-icons/lu";
import type { RouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -11,6 +11,11 @@ const productionRoutes: RouteGroup[] = [
to: path.to.jobs,
icon: <LuHardHat />,
},
+ {
+ name: "Schedule",
+ to: path.to.schedule,
+ icon: <LuCalendarClock />,
+ },
],
},
];
diff --git a/apps/carbon/app/modules/resources/resources.service.ts b/apps/carbon/app/modules/resources/resources.service.ts
index 8bf7d36a66..ef836376b7 100644
--- a/apps/carbon/app/modules/resources/resources.service.ts
+++ b/apps/carbon/app/modules/resources/resources.service.ts
@@ -359,6 +359,17 @@ export async function getWorkCenters(
return query;
}
+export async function getWorkCentersByLocation(
+ client: SupabaseClient<Database>,
+ locationId: string
+) {
+ return client
+ .from("workCenters")
+ .select("*")
+ .eq("locationId", locationId)
+ .eq("active", true);
+}
+
export async function getWorkCentersList(
client: SupabaseClient<Database>,
companyId: string
diff --git a/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
index df7e70e1a0..7c8d402cce 100644
--- a/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
@@ -47,6 +47,7 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {
accessorKey: "name",
header: "Process",
cell: ({ row }) =>
+ row.original.processType === "Outside" ||
((row.original.workCenters as any[]) ?? []).length > 0 ? (
<Enumerable
value={row.original.name}
diff --git a/apps/carbon/app/routes/x+/schedule+/_layout.tsx b/apps/carbon/app/routes/x+/schedule+/_layout.tsx
new file mode 100644
index 0000000000..c7b8497973
--- /dev/null
+++ b/apps/carbon/app/routes/x+/schedule+/_layout.tsx
@@ -0,0 +1,19 @@
+import { Outlet } from "@remix-run/react";
+
+import type { MetaFunction } from "@vercel/remix";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Schedule" }];
+};
+
+export const handle: Handle = {
+ breadcrumb: "Production",
+ to: path.to.production,
+ module: "production",
+};
+
+export default function SchedulingRoute() {
+ return <Outlet />;
+}
diff --git a/apps/carbon/app/routes/x+/schedule+/index.tsx b/apps/carbon/app/routes/x+/schedule+/index.tsx
new file mode 100644
index 0000000000..1811a578c6
--- /dev/null
+++ b/apps/carbon/app/routes/x+/schedule+/index.tsx
@@ -0,0 +1,242 @@
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { HStack } from "@carbon/react";
+import { useLoaderData } from "@remix-run/react";
+import { json, redirect, type LoaderFunctionArgs } from "@vercel/remix";
+import { useMemo } from "react";
+import { SearchFilter } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { ActiveFilters, Filter } from "~/components/Table/components/Filter";
+import type { ColumnFilter } from "~/components/Table/components/Filter/types";
+import { useUrlParams } from "~/hooks";
+import type { Column, Item } from "~/modules/production";
+import { getActiveJobOperationsByLocation, Kanban } from "~/modules/production";
+import {
+ getLocationsList,
+ getProcessesList,
+ getWorkCentersByLocation,
+} from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { makeDurations } from "~/utils/duration";
+
+export const handle: Handle = {
+ breadcrumb: "Schedule",
+ to: path.to.schedule,
+ module: "schedule",
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ 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[] = [];
+ 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];
+ }
+ }
+ }
+ }
+
+ let locationId = searchParams.get("location");
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ path.to.inventory,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data?.[0].id as string;
+ }
+
+ const [workCenters, processes, operations] = await Promise.all([
+ getWorkCentersByLocation(client, locationId),
+ getProcessesList(client, companyId),
+ getActiveJobOperationsByLocation(client, locationId, 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 (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,
+ status: op.operationStatus,
+ };
+ }) ?? []) satisfies Item[],
+ processes: processes.data ?? [],
+ });
+}
+
+export default function ScheduleRoute() {
+ const { columns, items, processes } = useLoaderData<typeof loader>();
+ const [params] = useUrlParams();
+ const currentFilters = params.getAll("filter");
+ const filters = useMemo<ColumnFilter[]>(() => {
+ return [
+ {
+ accessorKey: "workCenterId",
+ header: "Work Center",
+ filter: {
+ type: "static",
+ options: columns.map((col) => ({
+ label: <Enumerable value={col.title} />,
+ value: col.id,
+ })),
+ },
+ },
+ {
+ accessorKey: "processId",
+ header: "Process",
+ filter: {
+ type: "static",
+ options: processes.map((p) => ({
+ label: <Enumerable value={p.name} />,
+ value: p.id,
+ })),
+ },
+ },
+ ];
+ }, [columns, processes]);
+
+ return (
+ <div className="flex flex-col h-full max-h-full overflow-auto relative">
+ <HStack className="px-4 py-2 justify-between bg-card border-b border-border">
+ <HStack>
+ <SearchFilter param="search" size="sm" placeholder="Search" />
+
+ <Filter filters={filters} />
+ </HStack>
+ </HStack>
+ {currentFilters.length > 0 && (
+ <HStack className="px-4 py-1.5 justify-between bg-card border-b border-border w-full">
+ <HStack>
+ <ActiveFilters filters={filters} />
+ </HStack>
+ </HStack>
+ )}
+ <div className="flex flex-grow h-full items-stretch overflow-hidden relative">
+ <div className="flex flex-grow h-full items-stretch overflow-hidden relative">
+ <div className="flex flex-1 min-h-0 w-full relative">
+ <Kanban
+ columns={columns}
+ items={items}
+ showCustomer
+ showDescription
+ showDueDate
+ showDuration
+ showEmployee
+ showProgress={false}
+ showStatus
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/schedule+/operation.update.tsx b/apps/carbon/app/routes/x+/schedule+/operation.update.tsx
new file mode 100644
index 0000000000..d37cd7f1fe
--- /dev/null
+++ b/apps/carbon/app/routes/x+/schedule+/operation.update.tsx
@@ -0,0 +1,36 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { scheduleOperationUpdateValidator } from "~/modules/production/production.models";
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, userId } = await requirePermissions(request, {
+ update: "production",
+ });
+ const validation = await validator(scheduleOperationUpdateValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return json({
+ success: false,
+ message: "Invalid form data",
+ });
+ }
+
+ const { error } = await client
+ .from("jobOperation")
+ .update({
+ workCenterId: validation.data.columnId,
+ priority: validation.data.priority,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", validation.data.id);
+
+ if (error) {
+ return json({ success: false, message: error.message });
+ }
+
+ return json({ success: true });
+}
diff --git a/apps/carbon/app/routes/x+/scheduling+/kanban.tsx b/apps/carbon/app/routes/x+/scheduling+/kanban.tsx
deleted file mode 100644
index 43a9cc7e25..0000000000
--- a/apps/carbon/app/routes/x+/scheduling+/kanban.tsx
+++ /dev/null
@@ -1,326 +0,0 @@
-import {
- Button,
- HStack,
- Popover,
- PopoverContent,
- PopoverTrigger,
- Switch,
- useLocalStorage,
-} from "@carbon/react";
-import { useLoaderData, useRevalidator } from "@remix-run/react";
-import type { LoaderFunctionArgs } from "@vercel/remix";
-import { json } from "@vercel/remix";
-import { HiOutlineAdjustmentsHorizontal } from "react-icons/hi2";
-import { LuListFilter, LuRefreshCcw } from "react-icons/lu";
-import { SearchFilter } from "~/components";
-import type { Column, DisplaySettings, Item } from "~/components/Kanban";
-import { Kanban } from "~/components/Kanban";
-
-export async function loader({ request }: LoaderFunctionArgs) {
- return json({
- columns: [
- {
- id: "1",
- type: "assembly",
- title: "Assembly Station 1",
- active: true,
- },
- {
- id: "2",
- type: "assembly",
- title: "Assembly Station 2",
- },
- {
- id: "3",
- type: "saw",
- title: "Band Saw",
- },
- {
- id: "4",
- type: "grinder",
- title: "Bench Grinder",
- active: true,
- },
- {
- id: "5",
- title: "CNC Mill 1",
- type: "cnc",
- },
- ] satisfies Column[],
- items: [
- {
- id: "item0",
- columnId: "4",
- columnType: "grinder",
- title: "1503",
- subtitle: "F011432",
- description: "Grind",
- customerId: "ca2f11f8-1464-4753-9690-00107f141f3a",
- dueDate: "2024-05-28",
- duration: 30 * 60 * 1000,
- deadlineType: "Hard Deadline",
- progress: 5 * 60 * 1000,
- status: "IN_PROGRESS",
- },
- {
- id: "item1",
- columnId: "3",
- columnType: "saw",
- title: "1032",
- subtitle: "F011432",
- description: "Cut",
- dueDate: "2024-05-30",
- duration: 2 * 60 * 60 * 1000,
- deadlineType: "Soft Deadline",
- status: "PAUSED",
- progress: 1.3 * 60 * 60 * 1000,
- },
- {
- id: "item2",
- columnId: "3",
- columnType: "saw",
- title: "1023",
- subtitle: "F011432",
- description: "Cut",
- dueDate: "2024-05-20",
- duration: 2 * 60 * 60 * 1000,
- deadlineType: "ASAP",
- customerId: "ca2f11f8-1464-4753-9690-00107f141f3a",
- status: "READY",
- },
- {
- id: "item3",
- columnId: "3",
- columnType: "saw",
- title: "1022",
- subtitle: "F011432",
- description: "Cut",
- duration: 10 * 60 * 1000,
- 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: getRandomBetweenRange(1, 2),
- columnType: "assembly",
- title: "1492",
- subtitle: "F011432",
- description: "Assemble",
- duration: 4 * 60 * 60 * 1000,
- deadlineType: "No Deadline",
- status: "WAITING",
- },
- {
- id: "item5",
- columnId: getRandomBetweenRange(1, 2),
- columnType: "assembly",
- title: "1109",
- subtitle: "F011432",
- description: "Assemble",
- dueDate: "2024-05-20",
- duration: 4 * 60 * 60 * 1000,
- deadlineType: "Soft Deadline",
- status: "WAITING",
- },
-
- {
- id: "item7",
- columnId: getRandomBetweenRange(1, 2),
- columnType: "assembly",
- title: "1014",
- subtitle: "F011432",
- description: "Assemble",
- dueDate: "2024-06-20",
- duration: 20 * 60 * 1000,
- deadlineType: "Hard Deadline",
- customerId: "bcbe0bca-6516-4a6c-bb8a-b3942f1a9a33",
- status: "TODO",
- },
- {
- id: "item8",
- columnId: getRandomBetweenRange(1, 2),
- columnType: "assembly",
- title: "1032",
- subtitle: "F011432",
- description: "Assemble",
- dueDate: "2024-05-24",
- duration: 2 * 60 * 60 * 1000,
- deadlineType: "Soft Deadline",
- customerId: "ca2f11f8-1464-4753-9690-00107f141f3a",
- status: "TODO",
- },
- {
- id: "item9",
- columnId: getRandomBetweenRange(1, 2),
- columnType: "assembly",
- title: "1010",
- subtitle: "F011432",
- description: "Assemble",
- dueDate: "2024-05-20",
- duration: 32 * 1000,
- deadlineType: "ASAP",
- status: "TODO",
- },
- {
- id: "item10",
- columnId: getRandomBetweenRange(1, 2),
- columnType: "assembly",
- title: "1403",
- subtitle: "F011432",
- description: "Assemble",
- dueDate: "2024-05-20",
- duration: 6 * 60 * 60 * 1000,
- deadlineType: "No Deadline",
- customerId: "bcbe0bca-6516-4a6c-bb8a-b3942f1a9a33",
- status: "TODO",
- },
- ] satisfies Item[],
- });
-}
-
-export default function KanbanView() {
- const { columns, items } = useLoaderData<typeof loader>();
- const [kanbanSettings, setKanbanSettings] = useKanbanSettings();
- const revalidator = useRevalidator();
-
- return (
- <div className="flex flex-col h-full max-h-full overflow-auto relative">
- <HStack className="px-4 py-2 justify-between bg-card border-b border-border">
- <HStack>
- <SearchFilter param="search" size="sm" placeholder="Search" />
- {/* <Filter filters={filters} /> */}
- <Button
- rightIcon={<LuListFilter />}
- role="combobox"
- variant="secondary"
- className={"!border-dashed border-border"}
- >
- Filter
- </Button>
- </HStack>
- <HStack>
- <Popover>
- <PopoverTrigger asChild>
- <Button
- leftIcon={<HiOutlineAdjustmentsHorizontal />}
- variant="secondary"
- >
- Display
- </Button>
- </PopoverTrigger>
- <PopoverContent
- className="overflow-y-auto p-2 scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-fit"
- align="end"
- >
- <div className="flex flex-col items-end gap-2 pl-4">
- <Switch
- variant="small"
- label="Description"
- checked={kanbanSettings.showDescription}
- onCheckedChange={(e) =>
- setKanbanSettings("showDescription", e.valueOf())
- }
- />
- <Switch
- variant="small"
- label="Customer"
- checked={kanbanSettings.showCustomer}
- onCheckedChange={(e) =>
- setKanbanSettings("showCustomer", e.valueOf())
- }
- />
- <Switch
- variant="small"
- label="Employee"
- checked={kanbanSettings.showEmployee}
- onCheckedChange={(e) =>
- setKanbanSettings("showEmployee", e.valueOf())
- }
- />
- <Switch
- variant="small"
- label="Due Date"
- checked={kanbanSettings.showDueDate}
- onCheckedChange={(e) =>
- setKanbanSettings("showDueDate", e.valueOf())
- }
- />
- <Switch
- variant="small"
- label="Duration"
- checked={kanbanSettings.showDuration}
- onCheckedChange={(e) =>
- setKanbanSettings("showDuration", e.valueOf())
- }
- />
- <Switch
- variant="small"
- label="Progress"
- checked={kanbanSettings.showProgress}
- onCheckedChange={(e) =>
- setKanbanSettings("showProgress", e.valueOf())
- }
- />
- </div>
- </PopoverContent>
- </Popover>
- <Button
- leftIcon={<LuRefreshCcw />}
- variant="secondary"
- onClick={revalidator.revalidate}
- >
- Rebalance
- </Button>
- </HStack>
- </HStack>
- <div className="flex flex-grow h-full items-stretch overflow-hidden relative">
- <div className="flex flex-grow h-full items-stretch overflow-hidden relative">
- <div className="flex flex-1 min-h-0 w-full relative">
- <Kanban columns={columns} items={items} {...kanbanSettings} />
- </div>
- </div>
- </div>
- </div>
- );
-}
-
-function useKanbanSettings() {
- const [kanbanSettings, setKanbanSettings] = useLocalStorage<DisplaySettings>(
- "kanbanSettings",
- {
- showCustomer: false,
- showDescription: false,
- showDueDate: false,
- showDuration: false,
- showEmployee: false,
- showProgress: false,
- showStatus: false,
- }
- );
-
- const updateKanbanSettings = (
- key: keyof typeof kanbanSettings,
- value: boolean
- ) => {
- setKanbanSettings({ ...kanbanSettings, [key]: value });
- };
-
- return [kanbanSettings, updateKanbanSettings] as const;
-}
-
-function getRandomBetweenRange(min: number, max: number) {
- return Math.floor(Math.random() * (max - min + 1) + min).toString();
-}
diff --git a/apps/carbon/app/styles/tailwind.css b/apps/carbon/app/styles/tailwind.css
index bdb2310b50..dd090cd8be 100644
--- a/apps/carbon/app/styles/tailwind.css
+++ b/apps/carbon/app/styles/tailwind.css
@@ -1,6 +1,24 @@
@import url("non.geist");
@import url("non.geist/mono");
+@tailwind base;
+
+/* Chrome, Edge, and Safari */
+*::-webkit-scrollbar {
+ width: 15px;
+}
+
+*::-webkit-scrollbar-track {
+ background: var(--primary);
+ border-radius: 5px;
+}
+
+*::-webkit-scrollbar-thumb {
+ background-color: var(--secondary);
+ border-radius: 14px;
+ border: 3px solid var(--primary);
+}
+
@tailwind base;
@tailwind components;
@tailwind utilities;
diff --git a/apps/carbon/app/utils/duration.ts b/apps/carbon/app/utils/duration.ts
new file mode 100644
index 0000000000..96efa94bf3
--- /dev/null
+++ b/apps/carbon/app/utils/duration.ts
@@ -0,0 +1,183 @@
+export function makeDurations<
+ T extends {
+ setupTime: number;
+ setupUnit: string;
+ laborTime: number;
+ laborUnit: string;
+ machineTime: number;
+ machineUnit: string;
+ operationQuantity: number | null;
+ }
+>(
+ operation: T
+): T & {
+ duration: number;
+ setupDuration: number;
+ laborDuration: number;
+ machineDuration: number;
+} {
+ let setupDuration = 0;
+ let laborDuration = 0;
+ let machineDuration = 0;
+
+ // Calculate setup duration
+ switch (operation.setupUnit) {
+ case "Total Hours":
+ setupDuration = operation.setupTime * 3600000; // Convert hours to milliseconds
+ break;
+ case "Total Minutes":
+ setupDuration = operation.setupTime * 60000; // Convert minutes to milliseconds
+ break;
+ case "Hours/Piece":
+ setupDuration =
+ operation.setupTime * (operation.operationQuantity ?? 0) * 3600000;
+ break;
+ case "Hours/100 Pieces":
+ setupDuration =
+ (operation.setupTime / 100) *
+ (operation.operationQuantity ?? 0) *
+ 3600000;
+ break;
+ case "Hours/1000 Pieces":
+ setupDuration =
+ (operation.setupTime / 1000) *
+ (operation.operationQuantity ?? 0) *
+ 3600000;
+ break;
+ case "Minutes/Piece":
+ setupDuration =
+ operation.setupTime * (operation.operationQuantity ?? 0) * 60000;
+ break;
+ case "Minutes/100 Pieces":
+ setupDuration =
+ (operation.setupTime / 100) *
+ (operation.operationQuantity ?? 0) *
+ 60000;
+ break;
+ case "Minutes/1000 Pieces":
+ setupDuration =
+ (operation.setupTime / 1000) *
+ (operation.operationQuantity ?? 0) *
+ 60000;
+ break;
+ case "Pieces/Hour":
+ setupDuration =
+ ((operation.operationQuantity ?? 0) / operation.setupTime) * 3600000;
+ break;
+ case "Pieces/Minute":
+ setupDuration =
+ ((operation.operationQuantity ?? 0) / operation.setupTime) * 60000;
+ break;
+ case "Seconds/Piece":
+ setupDuration =
+ operation.setupTime * (operation.operationQuantity ?? 0) * 1000;
+ break;
+ }
+
+ // Calculate labor duration
+ switch (operation.laborUnit) {
+ case "Hours/Piece":
+ laborDuration =
+ operation.laborTime * (operation.operationQuantity ?? 0) * 3600000;
+ break;
+ case "Hours/100 Pieces":
+ laborDuration =
+ (operation.laborTime / 100) *
+ (operation.operationQuantity ?? 0) *
+ 3600000;
+ break;
+ case "Hours/1000 Pieces":
+ laborDuration =
+ (operation.laborTime / 1000) *
+ (operation.operationQuantity ?? 0) *
+ 3600000;
+ break;
+ case "Minutes/Piece":
+ laborDuration =
+ operation.laborTime * (operation.operationQuantity ?? 0) * 60000;
+ break;
+ case "Minutes/100 Pieces":
+ laborDuration =
+ (operation.laborTime / 100) *
+ (operation.operationQuantity ?? 0) *
+ 60000;
+ break;
+ case "Minutes/1000 Pieces":
+ laborDuration =
+ (operation.laborTime / 1000) *
+ (operation.operationQuantity ?? 0) *
+ 60000;
+ break;
+ case "Pieces/Hour":
+ laborDuration =
+ ((operation.operationQuantity ?? 0) / operation.laborTime) * 3600000;
+ break;
+ case "Pieces/Minute":
+ laborDuration =
+ ((operation.operationQuantity ?? 0) / operation.laborTime) * 60000;
+ break;
+ case "Seconds/Piece":
+ laborDuration =
+ operation.laborTime * (operation.operationQuantity ?? 0) * 1000;
+ break;
+ }
+
+ // Calculate machine duration
+ switch (operation.machineUnit) {
+ case "Hours/Piece":
+ machineDuration =
+ operation.machineTime * (operation.operationQuantity ?? 0) * 3600000;
+ break;
+ case "Hours/100 Pieces":
+ machineDuration =
+ (operation.machineTime / 100) *
+ (operation.operationQuantity ?? 0) *
+ 3600000;
+ break;
+ case "Hours/1000 Pieces":
+ machineDuration =
+ (operation.machineTime / 1000) *
+ (operation.operationQuantity ?? 0) *
+ 3600000;
+ break;
+ case "Minutes/Piece":
+ machineDuration =
+ operation.machineTime * (operation.operationQuantity ?? 0) * 60000;
+ break;
+ case "Minutes/100 Pieces":
+ machineDuration =
+ (operation.machineTime / 100) *
+ (operation.operationQuantity ?? 0) *
+ 60000;
+ break;
+ case "Minutes/1000 Pieces":
+ machineDuration =
+ (operation.machineTime / 1000) *
+ (operation.operationQuantity ?? 0) *
+ 60000;
+ break;
+ case "Pieces/Hour":
+ machineDuration =
+ ((operation.operationQuantity ?? 0) / operation.machineTime) * 3600000;
+ break;
+ case "Pieces/Minute":
+ machineDuration =
+ ((operation.operationQuantity ?? 0) / operation.machineTime) * 60000;
+ break;
+ case "Seconds/Piece":
+ machineDuration =
+ operation.machineTime * (operation.operationQuantity ?? 0) * 1000;
+ break;
+ }
+
+ const totalDuration = setupDuration + laborDuration + machineDuration;
+
+ // @ts-ignore
+ return {
+ ...operation,
+ duration: totalDuration,
+ setupDuration,
+ laborDuration,
+ machineDuration,
+ };
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 89bc33f6b6..13098d8d1a 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -734,7 +734,8 @@ export const path = {
salesRfqRoot: `${x}/sales-rfq`,
salesRfqStatus: (id: string) => generatePath(`${x}/sales-rfq/${id}/status`),
salesRfqs: `${x}/sales/rfqs`,
- scheduling: `${x}/scheduling`,
+ schedule: `${x}/schedule`,
+ scheduleOperationUpdate: `${x}/schedule/operation/update`,
service: (id: string) => generatePath(`${x}/service/${id}`),
services: `${x}/items/services`,
serviceDetails: (id: string) => `${x}/service/${id}/details`,
diff --git a/apps/developers/app/styles/tailwind.css b/apps/developers/app/styles/tailwind.css
index bdb2310b50..0790d0d1dc 100644
--- a/apps/developers/app/styles/tailwind.css
+++ b/apps/developers/app/styles/tailwind.css
@@ -1,6 +1,22 @@
@import url("non.geist");
@import url("non.geist/mono");
+/* Chrome, Edge, and Safari */
+*::-webkit-scrollbar {
+ width: 15px;
+}
+
+*::-webkit-scrollbar-track {
+ background: var(--primary);
+ border-radius: 5px;
+}
+
+*::-webkit-scrollbar-thumb {
+ background-color: var(--secondary);
+ border-radius: 14px;
+ border: 3px solid var(--primary);
+}
+
@tailwind base;
@tailwind components;
@tailwind utilities;
diff --git a/apps/mes/app/styles/tailwind.css b/apps/mes/app/styles/tailwind.css
index 11cb7b9827..ab49d8067d 100644
--- a/apps/mes/app/styles/tailwind.css
+++ b/apps/mes/app/styles/tailwind.css
@@ -1,6 +1,22 @@
@import url("non.geist");
@import url("non.geist/mono");
+/* Chrome, Edge, and Safari */
+*::-webkit-scrollbar {
+ width: 15px;
+}
+
+*::-webkit-scrollbar-track {
+ background: var(--primary);
+ border-radius: 5px;
+}
+
+*::-webkit-scrollbar-thumb {
+ background-color: var(--secondary);
+ border-radius: 14px;
+ border: 3px solid var(--primary);
+}
+
@tailwind base;
@tailwind components;
@tailwind utilities;
diff --git a/apps/www/app/styles/tailwind.css b/apps/www/app/styles/tailwind.css
index 6a2e451f74..49de77d32d 100644
--- a/apps/www/app/styles/tailwind.css
+++ b/apps/www/app/styles/tailwind.css
@@ -1,6 +1,22 @@
@import url("non.geist");
@import url("non.geist/mono");
+/* Chrome, Edge, and Safari */
+*::-webkit-scrollbar {
+ width: 15px;
+}
+
+*::-webkit-scrollbar-track {
+ background: var(--primary);
+ border-radius: 5px;
+}
+
+*::-webkit-scrollbar-thumb {
+ background-color: var(--secondary);
+ border-radius: 14px;
+ border: 3px solid var(--primary);
+}
+
@tailwind base;
@tailwind components;
@tailwind utilities;
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 832eb462e5..c1440d9759 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -7824,6 +7824,7 @@ export type Database = {
operationUnitCost: number
order: number
overheadRate: number
+ priority: number
processId: string
quantityComplete: number | null
quantityReworked: number | null
@@ -7860,6 +7861,7 @@ export type Database = {
operationUnitCost?: number
order?: number
overheadRate?: number
+ priority?: number
processId: string
quantityComplete?: number | null
quantityReworked?: number | null
@@ -7896,6 +7898,7 @@ export type Database = {
operationUnitCost?: number
order?: number
overheadRate?: number
+ priority?: number
processId?: string
quantityComplete?: number | null
quantityReworked?: number | null
@@ -25534,14 +25537,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -27296,14 +27299,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -29197,6 +29200,39 @@ export type Database = {
quantityScrapped: number
}[]
}
+ get_active_job_operations_by_location: {
+ Args: {
+ location_id: string
+ work_center_ids: string[]
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ priority: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ jobCustomerId: string
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
get_claims: {
Args: {
uid: string
@@ -29321,6 +29357,69 @@ export type Database = {
workInstruction: Json
}[]
}
+ get_job_operations_by_location:
+ | {
+ Args: {
+ location_id: string
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
+ | {
+ Args: {
+ location_id: string
+ work_center_ids: string[]
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ jobCustomerId: string
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
get_job_operations_by_work_center: {
Args: {
work_center_id: string
@@ -29975,7 +30074,6 @@ export type Database = {
owner_id: string | null
path_tokens: string[] | null
updated_at: string | null
- user_metadata: Json | null
version: string | null
}
Insert: {
@@ -29989,7 +30087,6 @@ export type Database = {
owner_id?: string | null
path_tokens?: string[] | null
updated_at?: string | null
- user_metadata?: Json | null
version?: string | null
}
Update: {
@@ -30003,7 +30100,6 @@ export type Database = {
owner_id?: string | null
path_tokens?: string[] | null
updated_at?: string | null
- user_metadata?: Json | null
version?: string | null
}
Relationships: [
@@ -30025,7 +30121,6 @@ export type Database = {
key: string
owner_id: string | null
upload_signature: string
- user_metadata: Json | null
version: string
}
Insert: {
@@ -30036,7 +30131,6 @@ export type Database = {
key: string
owner_id?: string | null
upload_signature: string
- user_metadata?: Json | null
version: string
}
Update: {
@@ -30047,7 +30141,6 @@ export type Database = {
key?: string
owner_id?: string | null
upload_signature?: string
- user_metadata?: Json | null
version?: string
}
Relationships: [
@@ -30184,10 +30277,6 @@ export type Database = {
updated_at: string
}[]
}
- operation: {
- Args: Record<PropertyKey, never>
- Returns: string
- }
search: {
Args: {
prefix: string
diff --git a/packages/database/supabase/functions/lib/scheduling/engine.ts b/packages/database/supabase/functions/lib/scheduling/engine.ts
index 219df7872a..aad2495fda 100644
--- a/packages/database/supabase/functions/lib/scheduling/engine.ts
+++ b/packages/database/supabase/functions/lib/scheduling/engine.ts
@@ -57,13 +57,15 @@ class SchedulingEngine {
continue;
}
- const result = operation.workCenterId
- ? this.resourceManager.getPriorityByWorkCenterId(
- operation.workCenterId
- )
- : this.resourceManager.getWorkCenterAndPriorityByProcessId(
- operation.processId
- );
+ const result =
+ operation.workCenterId &&
+ this.resourceManager.hasWorkCenter(operation.workCenterId)
+ ? this.resourceManager.getPriorityByWorkCenterId(
+ operation.workCenterId
+ )
+ : this.resourceManager.getWorkCenterAndPriorityByProcessId(
+ operation.processId
+ );
console.log(
`Updating operation ${operation.id} with priority ${result.priority} and work center ${result.workCenter}`
diff --git a/packages/database/supabase/functions/lib/scheduling/resource-manager.ts b/packages/database/supabase/functions/lib/scheduling/resource-manager.ts
index eddbdb76ea..5dc6b4cb1f 100644
--- a/packages/database/supabase/functions/lib/scheduling/resource-manager.ts
+++ b/packages/database/supabase/functions/lib/scheduling/resource-manager.ts
@@ -64,6 +64,7 @@ class ResourceManager {
.select(["id", "locationId"])
.where("locationId", "=", this.job?.locationId)
.where("companyId", "=", this.companyId)
+ .where("active", "=", true)
.execute(),
]);
@@ -309,6 +310,10 @@ class ResourceManager {
};
}
+ hasWorkCenter(workCenterId: string): boolean {
+ return this.operationsByWorkCenter.has(workCenterId);
+ }
+
addOperationToWorkCenter(workCenterId: string, operation: BaseOperation) {
if (!this.operationsByWorkCenter.has(workCenterId)) {
this.operationsByWorkCenter.set(workCenterId, []);
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 832eb462e5..c1440d9759 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -7824,6 +7824,7 @@ export type Database = {
operationUnitCost: number
order: number
overheadRate: number
+ priority: number
processId: string
quantityComplete: number | null
quantityReworked: number | null
@@ -7860,6 +7861,7 @@ export type Database = {
operationUnitCost?: number
order?: number
overheadRate?: number
+ priority?: number
processId: string
quantityComplete?: number | null
quantityReworked?: number | null
@@ -7896,6 +7898,7 @@ export type Database = {
operationUnitCost?: number
order?: number
overheadRate?: number
+ priority?: number
processId?: string
quantityComplete?: number | null
quantityReworked?: number | null
@@ -25534,14 +25537,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -27296,14 +27299,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -29197,6 +29200,39 @@ export type Database = {
quantityScrapped: number
}[]
}
+ get_active_job_operations_by_location: {
+ Args: {
+ location_id: string
+ work_center_ids: string[]
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ priority: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ jobCustomerId: string
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
get_claims: {
Args: {
uid: string
@@ -29321,6 +29357,69 @@ export type Database = {
workInstruction: Json
}[]
}
+ get_job_operations_by_location:
+ | {
+ Args: {
+ location_id: string
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
+ | {
+ Args: {
+ location_id: string
+ work_center_ids: string[]
+ }
+ Returns: {
+ id: string
+ jobId: string
+ operationOrder: number
+ processId: string
+ workCenterId: string
+ description: string
+ setupTime: number
+ setupUnit: Database["public"]["Enums"]["factor"]
+ laborTime: number
+ laborUnit: Database["public"]["Enums"]["factor"]
+ machineTime: number
+ machineUnit: Database["public"]["Enums"]["factor"]
+ operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
+ jobReadableId: string
+ jobStatus: Database["public"]["Enums"]["jobStatus"]
+ jobDueDate: string
+ jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
+ jobCustomerId: string
+ parentMaterialId: string
+ itemReadableId: string
+ operationStatus: Database["public"]["Enums"]["jobOperationStatus"]
+ operationQuantity: number
+ quantityComplete: number
+ quantityScrapped: number
+ }[]
+ }
get_job_operations_by_work_center: {
Args: {
work_center_id: string
@@ -29975,7 +30074,6 @@ export type Database = {
owner_id: string | null
path_tokens: string[] | null
updated_at: string | null
- user_metadata: Json | null
version: string | null
}
Insert: {
@@ -29989,7 +30087,6 @@ export type Database = {
owner_id?: string | null
path_tokens?: string[] | null
updated_at?: string | null
- user_metadata?: Json | null
version?: string | null
}
Update: {
@@ -30003,7 +30100,6 @@ export type Database = {
owner_id?: string | null
path_tokens?: string[] | null
updated_at?: string | null
- user_metadata?: Json | null
version?: string | null
}
Relationships: [
@@ -30025,7 +30121,6 @@ export type Database = {
key: string
owner_id: string | null
upload_signature: string
- user_metadata: Json | null
version: string
}
Insert: {
@@ -30036,7 +30131,6 @@ export type Database = {
key: string
owner_id?: string | null
upload_signature: string
- user_metadata?: Json | null
version: string
}
Update: {
@@ -30047,7 +30141,6 @@ export type Database = {
key?: string
owner_id?: string | null
upload_signature?: string
- user_metadata?: Json | null
version?: string
}
Relationships: [
@@ -30184,10 +30277,6 @@ export type Database = {
updated_at: string
}[]
}
- operation: {
- Args: Record<PropertyKey, never>
- Returns: string
- }
search: {
Args: {
prefix: string
diff --git a/packages/database/supabase/functions/scheduler/index.ts b/packages/database/supabase/functions/scheduler/index.ts
index ec80ed679d..db675e3bfc 100644
--- a/packages/database/supabase/functions/scheduler/index.ts
+++ b/packages/database/supabase/functions/scheduler/index.ts
@@ -5,7 +5,7 @@ import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsHeaders } from "../lib/headers.ts";
import { SchedulingEngine } from "../lib/scheduling/engine.ts";
import { SchedulingStrategy } from "../lib/scheduling/types.ts";
-import { getSupabaseServiceRole } from "../lib/supabase.ts";
+import { getSupabaseServiceRoleFromAuthorizationHeader } from "../lib/supabase.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -33,7 +33,9 @@ serve(async (req: Request) => {
userId,
});
- const client = getSupabaseServiceRole(req.headers.get("Authorization"));
+ const client = getSupabaseServiceRoleFromAuthorizationHeader(
+ req.headers.get("Authorization")
+ );
const engine = new SchedulingEngine({ client, db, jobId, companyId });
diff --git a/packages/database/supabase/migrations/20241024111311_active-job-operations.sql b/packages/database/supabase/migrations/20241024111311_active-job-operations.sql
new file mode 100644
index 0000000000..db3d6c454e
--- /dev/null
+++ b/packages/database/supabase/migrations/20241024111311_active-job-operations.sql
@@ -0,0 +1,81 @@
+CREATE OR REPLACE FUNCTION get_active_job_operations_by_location(
+ location_id TEXT,
+ work_center_ids TEXT[]
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "jobId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "priority" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ "description" TEXT,
+ "setupTime" NUMERIC(10,2),
+ "setupUnit" factor,
+ "laborTime" NUMERIC(10,2),
+ "laborUnit" factor,
+ "machineTime" NUMERIC(10,2),
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "jobCustomerId" TEXT,
+ "parentMaterialId" TEXT,
+ "itemReadableId" TEXT,
+ "operationStatus" "jobOperationStatus",
+ "operationQuantity" NUMERIC(10,2),
+ "quantityComplete" NUMERIC(10,2),
+ "quantityScrapped" NUMERIC(10,2)
+)
+SECURITY INVOKER
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH relevant_jobs AS (
+ SELECT *
+ FROM "job"
+ WHERE "locationId" = location_id
+ AND ("status" = 'Ready' OR "status" = 'In Progress' OR "status" = 'Paused')
+ )
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."order" AS "operationOrder",
+ jo."priority",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ rj."jobId" AS "jobReadableId",
+ rj."status" AS "jobStatus",
+ rj."dueDate" AS "jobDueDate",
+ rj."deadlineType" AS "jobDeadlineType",
+ rj."customerId" AS "jobCustomerId",
+ jmm."parentMaterialId",
+ i."readableId" as "itemReadableId",
+ CASE
+ WHEN rj."status" = 'Paused' THEN 'Paused'
+ ELSE jo."status"
+ END AS "operationStatus",
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityScrapped"
+ FROM "jobOperation" jo
+ JOIN relevant_jobs rj ON rj.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ WHERE CASE
+ WHEN array_length(work_center_ids, 1) > 0 THEN jo."workCenterId" = ANY(work_center_ids)
+ ELSE TRUE
+ END
+ ORDER BY jo."priority";
+END;
+$$ LANGUAGE plpgsql;
\ No newline at end of file
diff --git a/prompts/migration.md b/prompts/migration.md
deleted file mode 100644
index fd27faaaa0..0000000000
--- a/prompts/migration.md
+++ /dev/null
@@ -1,139 +0,0 @@
-# PostgreSQL SQL Style Guide
-
-## General
-
-- Use uppercase for SQL reserved words to maintain consistency and readability.
-- Employ consistent, descriptive identifiers for tables, columns, and other database objects.
-- Use white space and indentation to enhance the readability of your code.
-- Store dates in ISO 8601 format (`yyyy-mm-ddThh:mm:ss.sssss`).
-- Include comments for complex logic, using '/_ ... _/' for block comments and '--' for line comments.
-
-## Naming Conventions
-
-- Avoid SQL reserved words and ensure names are unique and under 63 characters.
-- Use camelCase for tables and columns.
-- Prefer singular for table names
-- Prefer plural for views
-- Prefer singular names for columns.
-
-## Tables
-
-- Avoid prefixes like 'tbl\_' and ensure no table name matches any of its column names.
-- Always add an `id` column of type `TEXT DEFAULT xid()` unless otherwise specified. Use it as the primary key.
-- Always add the schema to SQL queries for clarity.
-- Always add a `companyId` column of type `TEXT NOT NULL` that references `company("id")` unless otherwise specified.
-- Always include an `assignee` column which references `user("id")` unless otherwise specified
-- Always include a `customFields` column of type `JSONB` unless otherwise specified.
-- Always include a `createdBy`, `createdAt`, `updatedBy` and `updatedAt` column unless otherwise specified.
-
-## Columns
-
-- Use singular names and avoid generic names like 'id'.
-- For references to foreign tables, use the singular of the table name with the `Id` suffix. For example `userId` to reference the `user` table
-- Always use lowercase except in cases involving acronyms or when readability would be enhanced by an exception.
-
-#### Examples:
-
-```sql
-CREATE TABLE "quote" (
- "id" TEXT NOT NULL DEFAULT xid(),
- "quoteId" TEXT NOT NULL,
- "revisionId" INTEGER NOT NULL DEFAULT 0,
- "salesRfqId" TEXT,
- "dueDate" DATE,
- "expirationDate" DATE,
- "status" "quoteStatus" NOT NULL DEFAULT 'Draft',
- "notes" JSON DEFAULT '{}'::json,
- "salesPersonId" TEXT,
- "estimatorId" TEXT,
- "customerId" TEXT NOT NULL,
- "customerLocationId" TEXT,
- "customerContactId" TEXT,
- "customerReference" TEXT,
- "locationId" TEXT,
- "assignee" TEXT,
- "customFields" JSONB,
- "companyId" TEXT NOT NULL,
- "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
- "createdBy" TEXT NOT NULL,
- "updatedAt" TIMESTAMP WITH TIME ZONE,
- "updatedBy" TEXT,
-
- CONSTRAINT "quote_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "quote_quoteId_key" UNIQUE ("quoteId", "companyId"),
- CONSTRAINT "quote_salesRfqId_fkey" FOREIGN KEY ("salesRfqId") REFERENCES "salesRfq" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "quote_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "quote_customerLocationId_fkey" FOREIGN KEY ("customerLocationId") REFERENCES "customerLocation" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "quote_customerContactId_fkey" FOREIGN KEY ("customerContactId") REFERENCES "customerContact" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "quote_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "quote_salesPersonId_fkey" FOREIGN KEY ("salesPersonId") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "quote_estimatorId_fkey" FOREIGN KEY ("estimatorId") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "quote_assignee_fkey" FOREIGN KEY ("assignee") REFERENCES "user" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
- CONSTRAINT "quote_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "quote_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "quote_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
-);
-```
-
-## Queries
-
-- When the query is shorter keep it on just a few lines. As it gets larger start adding newlines for readability
-- Add spaces for readability.
-
-Smaller queries:
-
-```sql
-SELECT *
-FROM "employee"
-WHERE "endDate" IS NULL;
-
-UPDATE "employee"
-SET "endDate" = '2023-12-31'
-WHERE "id" = '1234';
-```
-
-Larger queries:
-
-```sql
-SELECT
- "firstName",
- "lastName"
-FROM
- "employee"
-WHERE
- "startDate" BETWEEN '2021-01-01' AND '2021-12-31'
-AND
- "status" = 'employed';
-```
-
-### Joins and Subqueries
-
-- Format joins and subqueries for clarity, aligning them with related SQL clauses.
-- Prefer full table names when referencing tables. This helps for readability.
-
-```sql
-SELECT
- "employee"."employeeName",
- "department"."departmentName"
-FROM
- "employee" e
-JOIN
- "department" d on e."departmentId" = d."id"
-WHERE
- "employee"."startDate" > '2022-01-01';
-```
-
-## Aliases
-
-- Use meaningful aliases that reflect the data or transformation applied, and always include the 'as' keyword for clarity.
-
-```sql
-SELECT count(*) AS "totalEmployees"
-FROM "employee"
-WHERE "endDate" IS NULL;
-```
-
-## Complex queries and CTEs
-
-- If a query is extremely complex, prefer a CTE.
-- Make sure the CTE is clear and linear Prefer readability over performance.