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: schedule jobs by day/week basics

Brad Barbindc137df86e4f
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 710964c749..35ca47b8bb 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -837,6 +837,12 @@ export const scheduleOperationUpdateValidator = z.object({
priority: zfd.numeric(z.number().min(0).optional()),
});
+export const scheduleJobUpdateValidator = 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()),
+});
+
export const scrapReasonValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 26ee2dce75..20aaf246a7 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -20,6 +20,7 @@ import type {
operationToolValidator,
} from "../shared";
import type {
+ deadlineTypes,
jobMaterialValidator,
jobOperationStatus,
jobOperationValidator,
@@ -176,11 +177,20 @@ export async function convertSalesOrderLinesToJobs(
unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",
};
+ // Calculate priority based on due date and deadline type
+ const priority = await calculateJobPriority(serviceRole, {
+ dueDate: data.dueDate ?? null,
+ deadlineType: data.deadlineType,
+ companyId,
+ locationId: locationId!,
+ });
+
const createJob = await serviceRole
.from("job")
.insert({
...data,
jobId: nextSequence.data,
+ priority,
companyId,
createdBy: userId,
updatedBy: userId,
@@ -288,6 +298,97 @@ export async function convertSalesOrderLinesToJobs(
return salesOrder;
}
+/**
+ * Calculate the priority for a job based on its dueDate and deadlineType.
+ * Priority ordering: ASAP > Hard Deadline > Soft Deadline > No Deadline
+ *
+ * @param client - Supabase client
+ * @param params - Job details
+ * @returns The calculated priority number
+ */
+export async function calculateJobPriority(
+ client: SupabaseClient<Database>,
+ params: {
+ jobId?: string; // Optional - if updating an existing job
+ dueDate: string | null;
+ deadlineType: (typeof deadlineTypes)[number];
+ companyId: string;
+ locationId: string;
+ }
+): Promise<number> {
+ const { jobId, dueDate, deadlineType, companyId, locationId } = params;
+
+ // Define deadline type priority order (lower number = higher priority)
+ const deadlineTypePriority: Record<string, number> = {
+ "ASAP": 0,
+ "Hard Deadline": 1,
+ "Soft Deadline": 2,
+ "No Deadline": 3,
+ };
+
+ const currentJobPriority = deadlineTypePriority[deadlineType];
+
+ // Query all jobs with the same dueDate (or null if dueDate is null)
+ let query = client
+ .from("job")
+ .select("id, priority, deadlineType")
+ .eq("companyId", companyId)
+ .eq("locationId", locationId)
+ .order("priority", { ascending: true });
+
+ if (dueDate) {
+ query = query.eq("dueDate", dueDate);
+ } else {
+ query = query.is("dueDate", null);
+ }
+
+ // Exclude the current job if we're updating
+ if (jobId) {
+ query = query.neq("id", jobId);
+ }
+
+ const { data: existingJobs } = await query;
+
+ if (!existingJobs || existingJobs.length === 0) {
+ // No existing jobs with this due date, start at priority 0
+ return 0;
+ }
+
+ // Find the position where this job should be inserted based on deadlineType
+ let insertBeforeIndex = existingJobs.length; // Default to end of list
+
+ for (let i = 0; i < existingJobs.length; i++) {
+ const existingJobPriority = deadlineTypePriority[existingJobs[i].deadlineType];
+
+ // If the current job has higher priority (lower number) than this existing job,
+ // we should insert before this job
+ if (currentJobPriority < existingJobPriority) {
+ insertBeforeIndex = i;
+ break;
+ }
+ }
+
+ // Calculate the priority value using fractional indexing
+ let newPriority: number;
+
+ if (insertBeforeIndex === 0) {
+ // Insert at the beginning - use half of the first job's priority
+ const firstPriority = existingJobs[0].priority ?? 0;
+ newPriority = firstPriority > 0 ? firstPriority / 2 : -1;
+ } else if (insertBeforeIndex === existingJobs.length) {
+ // Insert at the end - add 1 to the last job's priority
+ const lastPriority = existingJobs[existingJobs.length - 1].priority ?? 0;
+ newPriority = lastPriority + 1;
+ } else {
+ // Insert between two jobs - average their priorities
+ const beforePriority = existingJobs[insertBeforeIndex - 1].priority ?? 0;
+ const afterPriority = existingJobs[insertBeforeIndex].priority ?? 0;
+ newPriority = (beforePriority + afterPriority) / 2;
+ }
+
+ return newPriority;
+}
+
export async function deleteDemandForecasts(
client: SupabaseClient<Database>,
params: {
@@ -477,6 +578,19 @@ export async function getActiveJobOperationsByLocation(
});
}
+export async function getJobsByDateRange(
+ client: SupabaseClient<Database>,
+ locationId: string,
+ startDate: string,
+ endDate: string
+) {
+ return client.rpc("get_jobs_by_date_range", {
+ location_id: locationId,
+ start_date: startDate,
+ end_date: endDate,
+ });
+}
+
export async function getActiveProductionEvents(
client: SupabaseClient<Database>,
companyId: string
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobStatus.tsx b/apps/erp/app/modules/production/ui/Jobs/JobStatus.tsx
index fdad53d01a..fae54d5381 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobStatus.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobStatus.tsx
@@ -3,26 +3,55 @@ import type { jobStatus } from "../../production.models";
type JobStatusProps = {
status?: (typeof jobStatus)[number] | null;
+ className?: string;
};
-function JobStatus({ status }: JobStatusProps) {
+function JobStatus({ status, className }: JobStatusProps) {
switch (status) {
case "Draft":
- return <Status color="gray">{status}</Status>;
+ return (
+ <Status color="gray" className={className}>
+ {status}
+ </Status>
+ );
case "Planned":
- return <Status color="yellow">{status}</Status>;
+ return (
+ <Status color="yellow" className={className}>
+ {status}
+ </Status>
+ );
case "Ready":
- return <Status color="blue">Released</Status>; // TODO: update this properly
+ return (
+ <Status color="blue" className={className}>
+ Released
+ </Status>
+ ); // TODO: update this properly
case "In Progress":
- return <Status color="blue">{status}</Status>;
+ return (
+ <Status color="blue" className={className}>
+ {status}
+ </Status>
+ );
case "Paused":
case "Due Today":
- return <Status color="orange">{status}</Status>;
+ return (
+ <Status color="orange" className={className}>
+ {status}
+ </Status>
+ );
case "Completed":
- return <Status color="green">{status}</Status>;
+ return (
+ <Status color="green" className={className}>
+ {status}
+ </Status>
+ );
case "Overdue":
case "Cancelled":
- return <Status color="red">{status}</Status>;
+ return (
+ <Status color="red" className={className}>
+ {status}
+ </Status>
+ );
default:
return null;
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx
new file mode 100644
index 0000000000..63ae7ae463
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx
@@ -0,0 +1,304 @@
+import type {
+ DragOverEvent,
+ DragStartEvent,
+} from "@dnd-kit/core";
+import {
+ DndContext,
+ DragOverlay,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import { sortableKeyboardCoordinates } from "@dnd-kit/sortable";
+import { useFetchers, useSubmit } from "@remix-run/react";
+import { useEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+
+import { ClientOnly } from "@carbon/react";
+import { path } from "~/utils/path";
+import { BoardContainer, ColumnCard } from "./components/ColumnCard";
+import { JobCard } from "./components/JobCard";
+import { KanbanProvider } from "./context/KanbanContext";
+import type { Column, DisplaySettings, JobItem, Progress } from "./types";
+import { hasDraggableData } from "./utils";
+
+type DateKanbanProps = {
+ columns: Column[];
+ items: JobItem[];
+ progressByItemId: Record<string, Progress>;
+ tags: { name: string }[];
+} & DisplaySettings;
+
+function usePendingItems() {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.scheduleDatesUpdate;
+ })
+ .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;
+ });
+}
+
+const DateKanban = ({
+ columns,
+ items: initialItems,
+ progressByItemId,
+ tags,
+ ...displaySettings
+}: DateKanbanProps) => {
+ const submit = useSubmit();
+ const [selectedGroup, setSelectedGroup] = useState<string | null>(null);
+
+ // For date-based kanban, always use the column order from props (don't persist)
+ const [columnOrder, setColumnOrder] = useState<string[]>(
+ columns.map((col) => col.id)
+ );
+
+ // Update column order when columns change (e.g., navigating to a different week/month)
+ useEffect(() => {
+ setColumnOrder(columns.map((col) => col.id));
+ }, [columns]);
+
+ const itemsById = new Map<string, JobItem>(
+ initialItems.map((item) => [item.id, item])
+ );
+
+ const pendingItems = usePendingItems();
+
+ // Merge pending items and existing items for optimistic updates
+ for (let pendingItem of pendingItems) {
+ let item = itemsById.get(pendingItem.id);
+ if (item) {
+ itemsById.set(pendingItem.id, { ...item, ...pendingItem });
+ }
+ }
+
+ const items = Array.from(itemsById.values()).sort(
+ (a, b) => a.priority - b.priority
+ );
+
+ const [activeItem, setActiveItem] = useState<JobItem | null>(null);
+
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ })
+ );
+
+ function onDragStart(event: DragStartEvent) {
+ if (!hasDraggableData(event.active)) return;
+ const data = event.active.data.current;
+
+ // Only handle item dragging, not column dragging (dates are fixed)
+ if (data?.type === "item") {
+ setActiveItem(data.item as JobItem);
+ return;
+ }
+ }
+
+ function onDragEnd() {
+ setActiveItem(null);
+ }
+
+ function onDragOver(event: DragOverEvent) {
+ const { active, over } = event;
+ if (!over) return;
+
+ const activeId = active.id;
+ const overId = over.id;
+
+ if (activeId === overId) return;
+
+ if (!hasDraggableData(active) || !hasDraggableData(over)) return;
+
+ const activeData = active.data.current;
+ const overData = over.data.current;
+
+ const isActiveAnItem = activeData?.type === "item";
+ const isOverAnItem = overData?.type === "item";
+
+ if (!isActiveAnItem) return;
+
+ const activeItem = itemsById.get(activeId.toString());
+ const overItem = itemsById.get(overId.toString());
+
+ // Dropping a job over another job
+ if (isActiveAnItem && isOverAnItem && activeItem && overItem) {
+ // Calculate priority
+ 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;
+
+ // Submit update when moving to a different column (date)
+ if (activeItem.columnId !== overItem.columnId) {
+ submit(
+ {
+ id: activeItem.id,
+ columnId: overItem.columnId,
+ priority: newPriority,
+ },
+ {
+ method: "post",
+ action: path.to.scheduleDatesUpdate,
+ navigate: false,
+ fetcherKey: `job:${activeItem.id}`,
+ }
+ );
+ return;
+ }
+
+ // Update priority within the same column
+ if (activeItem && overItem) {
+ submit(
+ {
+ id: activeItem.id,
+ columnId: activeItem.columnId,
+ priority: newPriority,
+ },
+ {
+ method: "post",
+ action: path.to.scheduleDatesUpdate,
+ navigate: false,
+ fetcherKey: `job:${activeItem.id}`,
+ }
+ );
+ }
+ }
+
+ const isOverAColumn = overData?.type === "column";
+
+ // Dropping a job over a column
+ if (isActiveAnItem && isOverAColumn && activeItem) {
+ const newColumnId = overId as string;
+
+ if (activeItem.columnId !== newColumnId) {
+ submit(
+ {
+ id: activeItem.id,
+ columnId: newColumnId,
+ priority: activeItem.priority,
+ },
+ {
+ method: "post",
+ action: path.to.scheduleDatesUpdate,
+ navigate: false,
+ fetcherKey: `job:${activeItem.id}`,
+ }
+ );
+ }
+ }
+ }
+
+ const columnsMap = new Map(columns.map((col) => [col.id, col]));
+
+ const isInitialMount = useRef(true);
+
+ useEffect(() => {
+ if (isInitialMount.current) {
+ isInitialMount.current = false;
+ return;
+ }
+ }, []);
+
+ return (
+ <KanbanProvider
+ displaySettings={displaySettings}
+ selectedGroup={selectedGroup}
+ setSelectedGroup={setSelectedGroup}
+ tags={tags}
+ >
+ <DndContext
+ sensors={sensors}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ onDragOver={onDragOver}
+ >
+ <BoardContainer>
+ {columnOrder.map((colId) => {
+ const col = columnsMap.get(colId);
+ if (!col) return null;
+ return (
+ <ColumnCard
+ key={col.id}
+ column={col}
+ items={items.filter((item) => item.columnId === col.id)}
+ progressByItemId={progressByItemId}
+ hideInactiveIndicator={true}
+ disableColumnDrag={true}
+ CardComponent={JobCard as any}
+ />
+ );
+ })}
+ </BoardContainer>
+
+ <ClientOnly fallback={null}>
+ {() =>
+ createPortal(
+ <DragOverlay>
+ {activeItem && (
+ <JobCard
+ item={{
+ ...activeItem,
+ status: progressByItemId[activeItem.id]?.active
+ ? "In Progress"
+ : activeItem.status,
+ employeeIds: progressByItemId[activeItem.id]?.employees
+ ? Array.from(progressByItemId[activeItem.id].employees!)
+ : undefined,
+ progress: progressByItemId[activeItem.id]?.progress ?? 0,
+ }}
+ isOverlay
+ progressByItemId={progressByItemId}
+ />
+ )}
+ </DragOverlay>,
+ document.body
+ )
+ }
+ </ClientOnly>
+ </DndContext>
+ </KanbanProvider>
+ );
+};
+
+export { DateKanban };
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx
new file mode 100644
index 0000000000..7667d15c4e
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx
@@ -0,0 +1,124 @@
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuIcon,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@carbon/react";
+import { useLocation, useNavigate } from "@remix-run/react";
+import {
+ LuCalendar,
+ LuCalendarDays,
+ LuChevronDown,
+ LuList,
+} from "react-icons/lu";
+import { path } from "~/utils/path";
+
+export function ScheduleNavigation() {
+ const location = useLocation();
+ const navigate = useNavigate();
+
+ const getCurrentView = () => {
+ if (location.pathname.includes(path.to.scheduleOperation))
+ return "operations";
+ if (
+ location.pathname.includes(path.to.scheduleDates) &&
+ location.search.includes("view=week")
+ )
+ return "week";
+ if (
+ location.pathname.includes(path.to.scheduleDates) &&
+ location.search.includes("view=month")
+ )
+ return "month";
+ return "operations";
+ };
+
+ const currentValue = getCurrentView();
+
+ const getViewLabel = (option: string) => {
+ switch (option) {
+ case "operations":
+ return "Operations";
+ case "week":
+ return "Week";
+ case "month":
+ return "Month";
+ default:
+ return "";
+ }
+ };
+
+ const getViewIcon = (option: string) => {
+ switch (option) {
+ case "operations":
+ return <LuList />;
+ case "week":
+ return <LuCalendarDays />;
+ case "month":
+ return <LuCalendar />;
+ default:
+ return <LuList />;
+ }
+ };
+
+ const navigateToView = (view: string) => {
+ const searchParams = new URLSearchParams(location.search);
+
+ switch (view) {
+ case "operations":
+ navigate(path.to.scheduleOperation + "?" + searchParams.toString());
+ break;
+ case "week":
+ searchParams.set("view", "week");
+ navigate(path.to.scheduleDates + "?" + searchParams.toString());
+ break;
+ case "month":
+ searchParams.set("view", "month");
+ navigate(path.to.scheduleDates + "?" + searchParams.toString());
+ break;
+ }
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ leftIcon={getViewIcon(currentValue)}
+ rightIcon={<LuChevronDown />}
+ variant="secondary"
+ >
+ {getViewLabel(currentValue)}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56">
+ <DropdownMenuRadioGroup
+ value={currentValue}
+ onValueChange={navigateToView}
+ >
+ <DropdownMenuRadioItem value="operations">
+ <DropdownMenuIcon icon={getViewIcon("operations")} />
+ {getViewLabel("operations")}
+ </DropdownMenuRadioItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Jobs</DropdownMenuLabel>
+ <DropdownMenuRadioItem value="week">
+ <DropdownMenuIcon icon={getViewIcon("week")} />
+ {getViewLabel("week")}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem value="month">
+ <DropdownMenuIcon icon={getViewIcon("month")} />
+ {getViewLabel("month")}
+ </DropdownMenuRadioItem>
+ </DropdownMenuGroup>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
index c4a70e6482..7f08e94fd0 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ColumnCard.tsx
@@ -11,6 +11,7 @@ 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 type { ComponentType } from "react";
import { useMemo } from "react";
import { LuGripVertical } from "react-icons/lu";
import type { Column, Item, Progress } from "../types";
@@ -21,6 +22,13 @@ type ColumnCardProps = {
items: Item[];
isOverlay?: boolean;
progressByItemId: Record<string, Progress>;
+ hideInactiveIndicator?: boolean;
+ disableColumnDrag?: boolean;
+ CardComponent?: ComponentType<{
+ item: Item;
+ isOverlay?: boolean;
+ progressByItemId: Record<string, Progress>;
+ }>;
};
export function ColumnCard({
@@ -28,6 +36,9 @@ export function ColumnCard({
items,
isOverlay,
progressByItemId,
+ hideInactiveIndicator = false,
+ disableColumnDrag = false,
+ CardComponent = ItemCard,
}: ColumnCardProps) {
const [params] = useUrlParams();
const currentFilters = params.getAll("filter").filter(Boolean);
@@ -90,7 +101,9 @@ export function ColumnCard({
>
<div className="p-4 w-full font-semibold text-left flex flex-row space-between items-center sticky top-0 bg-card z-1 border-b">
<div className="flex flex-grow items-start space-x-2">
- <PulsingDot inactive={!column.active} className="mt-2" />
+ {column.active || !hideInactiveIndicator ? (
+ <PulsingDot inactive={!column.active} className="mt-2" />
+ ) : null}
<div className="flex flex-col flex-grow">
<span className="mr-auto truncate"> {column.title}</span>
{totalDuration > 0 ? (
@@ -104,20 +117,22 @@ export function ColumnCard({
)}
</div>
</div>
- <IconButton
- aria-label={`Move column: ${column.title}`}
- icon={<LuGripVertical />}
- variant={"ghost"}
- {...attributes}
- {...listeners}
- className="cursor-grab relative"
- />
+ {!disableColumnDrag && (
+ <IconButton
+ aria-label={`Move column: ${column.title}`}
+ icon={<LuGripVertical />}
+ variant={"ghost"}
+ {...attributes}
+ {...listeners}
+ className="cursor-grab relative"
+ />
+ )}
</div>
<ScrollArea className="flex-grow">
<div className="flex flex-col gap-2 p-2">
<SortableContext items={itemsIds}>
{items.map((item) => (
- <ItemCard
+ <CardComponent
key={item.id!}
item={item}
progressByItemId={progressByItemId}
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
new file mode 100644
index 0000000000..7df15fedd1
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
@@ -0,0 +1,355 @@
+import {
+ Card,
+ CardContent,
+ CardFooter,
+ CardHeader,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Progress as ProgressComponent,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { useSortable } from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { cva } from "class-variance-authority";
+import {
+ LuCalendarDays,
+ LuEllipsisVertical,
+ LuFlashlight,
+ LuFlashlightOff,
+ LuGripVertical,
+ LuPencil,
+ LuStar,
+ LuUsers,
+} from "react-icons/lu";
+
+import { Link } from "@remix-run/react";
+import { RiProgress8Line } from "react-icons/ri";
+import { Assignee, EmployeeAvatarGroup } from "~/components";
+
+import { AiOutlinePartition } from "react-icons/ai";
+import { FaTasks } from "react-icons/fa";
+import { getDeadlineIcon } from "~/modules/production/ui/Jobs/Deadline";
+import { useCustomers } from "~/stores";
+import { getPrivateUrl, path } from "~/utils/path";
+import JobStatus from "../../../Jobs/JobStatus";
+import { useKanban } from "../context/KanbanContext";
+import type { JobItem } from "../types";
+
+interface Progress {
+ totalDuration: number;
+ progress: number;
+ active: boolean;
+ employees?: Set<string>;
+}
+
+const cardVariants = cva(
+ "bg-card hover:bg-muted/30 dark:border-none dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]",
+ {
+ variants: {
+ highlighted: {
+ true: "ring-2 ring-primary opacity-100",
+ false: "",
+ },
+ dragging: {
+ over: "ring-2 ring-primary opacity-30",
+ overlay: "ring-2 ring-primary hover:bg-muted",
+ },
+ status: {
+ Draft: "border-border",
+ Planned: "border-yellow-500/30",
+ Ready: "border-blue-500/30",
+ "In Progress": "border-emerald-600/30",
+ Paused: "border-orange-500/30",
+ Completed: "border-green-500/30",
+ Cancelled: "border-red-500/30",
+ Overdue: "border-red-500/50",
+ "Due Today": "border-orange-500/50",
+ },
+ },
+ defaultVariants: {
+ status: "Planned",
+ },
+ }
+);
+
+const cardHeaderVariants = cva(
+ "-mx-4 relative border-b border-border/50 pt-4 pl-4 pr-6 rounded-t-lg",
+ {
+ variants: {
+ status: {
+ Draft: "",
+ Planned: "",
+ Ready: "",
+ "In Progress": "",
+ Paused: "",
+ Completed: "",
+ Cancelled: "",
+ Overdue: "",
+ "Due Today": "",
+ },
+ },
+ defaultVariants: {
+ status: "Planned",
+ },
+ }
+);
+
+type JobCardProps = {
+ item: JobItem;
+ isOverlay?: boolean;
+ progressByItemId: Record<string, Progress>;
+};
+
+export function JobCard({ item, isOverlay, progressByItemId }: JobCardProps) {
+ const { displaySettings, selectedGroup, setSelectedGroup, tags } =
+ useKanban();
+ const {
+ setNodeRef,
+ attributes,
+ listeners,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({
+ id: item.id,
+ data: {
+ type: "item",
+ item,
+ },
+ attributes: {
+ roleDescription: "item",
+ },
+ });
+
+ const isHighlighted = selectedGroup === item.jobReadableId;
+
+ const style = {
+ transition,
+ transform: CSS.Translate.toString(transform),
+ };
+
+ const status = progressByItemId[item.id]?.active
+ ? "In Progress"
+ : item.status;
+ const employeeIds = progressByItemId[item.id]?.employees
+ ? Array.from(progressByItemId[item.id].employees!)
+ : undefined;
+
+ const [customers] = useCustomers();
+
+ const customer = customers.find((s) => s.id === item.customerId);
+
+ const isOverdue =
+ (item.dueDate &&
+ status !== "Completed" &&
+ new Date(item.dueDate) < new Date()) ||
+ (item.dueDate &&
+ item.completedDate &&
+ status === "Completed" &&
+ item.completedDate.split("T")[0] > item.dueDate);
+
+ return (
+ <Card
+ ref={setNodeRef}
+ style={style}
+ className={cn(
+ "max-w-[330px] shadow-sm dark:shadow-sm py-0",
+ cardVariants({
+ dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
+ status: status,
+ highlighted: isHighlighted,
+ })
+ )}
+ >
+ <CardHeader
+ className={cn(
+ cardHeaderVariants({
+ status: status,
+ })
+ )}
+ >
+ <div className="flex w-full max-w-full justify-between items-start gap-0">
+ <div className="flex flex-col gap-0.5 space-y-0 min-w-0">
+ {item.itemReadableId && (
+ <span className="text-xs text-muted-foreground line-clamp-1">
+ {item?.description || item.itemReadableId}
+ </span>
+ )}
+ <Link
+ to={item.link ?? path.to.job(item.jobId)}
+ className="mr-auto font-semibold line-clamp-2 leading-tight"
+ >
+ {item.jobReadableId}
+ </Link>
+ {customer && displaySettings.showCustomer && (
+ <span className="text-xs text-muted-foreground line-clamp-1">
+ {customer.name}
+ </span>
+ )}
+ </div>
+ <HStack spacing={1} className="flex-shrink-0 -mr-2">
+ <IconButton
+ aria-label="Move item"
+ icon={<LuGripVertical />}
+ variant={"ghost"}
+ {...attributes}
+ {...listeners}
+ className="cursor-grab"
+ />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More options"
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {item.link && (
+ <DropdownMenuItem asChild>
+ <Link to={item.link}>
+ <DropdownMenuIcon icon={<LuPencil />} />
+ Edit Job
+ </Link>
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ onClick={() =>
+ setSelectedGroup?.(
+ isHighlighted ? null : item.jobReadableId
+ )
+ }
+ destructive={isHighlighted}
+ >
+ <DropdownMenuIcon
+ icon={
+ isHighlighted ? <LuFlashlightOff /> : <LuFlashlight />
+ }
+ />
+ {isHighlighted ? "Remove Highlight" : "Highlight Job"}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </HStack>
+ </div>
+
+ {displaySettings.showProgress &&
+ Number.isFinite(item.progress) &&
+ Number(item.progress) >= 0 && (
+ <HStack>
+ <ProgressComponent
+ indicatorClassName={
+ status === "Paused"
+ ? "bg-yellow-500"
+ : status === "Completed"
+ ? "bg-green-500"
+ : ""
+ }
+ value={Math.min((item.progress ?? 0) * 100, 100)}
+ />
+ <FaTasks className="text-muted-foreground w-4 h-4" />
+ </HStack>
+ )}
+ </CardHeader>
+ <CardContent className="pt-3 px-1 gap-2 text-left whitespace-pre-wrap text-sm">
+ {displaySettings.showThumbnail && item.thumbnailPath && (
+ <div className="flex justify-center">
+ <img
+ src={getPrivateUrl(item.thumbnailPath)}
+ alt={item.itemDescription}
+ className="w-full h-auto rounded-lg"
+ />
+ </div>
+ )}
+ {displaySettings.showStatus && status && (
+ <HStack className="justify-start space-x-2">
+ <LuStar className="text-muted-foreground" />
+ <JobStatus status={status} className="flex-shrink-0" />
+ {isOverdue && (
+ <JobStatus status="Overdue" className="flex-shrink-0" />
+ )}
+ </HStack>
+ )}
+ <HStack className="justify-start space-x-2">
+ <AiOutlinePartition className="text-muted-foreground" />
+ <span className="text-sm line-clamp-1">{item.itemReadableId}</span>
+ </HStack>
+
+ {displaySettings.showDueDate && item.deadlineType && (
+ <HStack className="justify-start space-x-2">
+ {getDeadlineIcon(item.deadlineType)}
+ <Tooltip>
+ <TooltipTrigger>
+ <span className="text-sm">{item.deadlineType}</span>
+ </TooltipTrigger>
+ <TooltipContent side="right">{item.deadlineType}</TooltipContent>
+ </Tooltip>
+ </HStack>
+ )}
+ {displaySettings.showDueDate && item.dueDate && (
+ <HStack className="justify-start space-x-2">
+ <LuCalendarDays />
+ <span className="text-sm">{formatDate(item.dueDate)}</span>
+ </HStack>
+ )}
+
+ {displaySettings.showQuantity &&
+ Number.isFinite(item.quantity) &&
+ Number(item.quantity) > 0 && (
+ <HStack className="justify-start space-x-2">
+ <FaTasks className="text-muted-foreground" />
+ <span className="text-sm">
+ {item.quantityCompleted ?? 0} / {item.quantity} completed
+ </span>
+ </HStack>
+ )}
+
+ {displaySettings.showSalesOrder &&
+ item.salesOrderReadableId &&
+ item.salesOrderId &&
+ item.salesOrderLineId && (
+ <HStack className="justify-start space-x-2">
+ <RiProgress8Line className="text-muted-foreground" />
+ <Link
+ to={path.to.salesOrderLine(
+ item.salesOrderId,
+ item.salesOrderLineId
+ )}
+ className="text-sm"
+ >
+ {item.salesOrderReadableId}
+ </Link>
+ </HStack>
+ )}
+
+ {displaySettings.showEmployee &&
+ Array.isArray(employeeIds) &&
+ employeeIds.length > 0 && (
+ <HStack className="justify-start space-x-2">
+ <LuUsers className="text-muted-foreground" />
+ <EmployeeAvatarGroup employeeIds={employeeIds} />
+ </HStack>
+ )}
+ </CardContent>
+ <CardFooter className="bg-accent/50 -mx-4 border-t px-4 py-2 items-center justify-between rounded-b-lg">
+ <HStack className="justify-start gap-2 w-full">
+ <Assignee
+ table="job"
+ id={item.jobId}
+ size="sm"
+ value={item.assignee ?? undefined}
+ />
+ </HStack>
+ </CardFooter>
+ </Card>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
index 0d916f56f0..648f1a6d79 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
@@ -1,5 +1,9 @@
-import { z } from 'zod/v3';
-import { deadlineTypes, jobOperationStatus } from "../../../production.models";
+import { z } from "zod/v3";
+import {
+ deadlineTypes,
+ jobOperationStatus,
+ jobStatus,
+} from "../../../production.models";
import type { ProductionEvent } from "../../../types";
export const columnValidator = z.object({
@@ -36,7 +40,8 @@ export type Event = Pick<
"id" | "jobOperationId" | "duration" | "startTime" | "endTime" | "employeeId"
>;
-const itemValidator = z.object({
+// Base item fields shared by both job and operation items
+const baseItemValidator = z.object({
id: z.string(),
assignee: z.string().optional(),
columnId: z.string(),
@@ -45,15 +50,12 @@ const itemValidator = z.object({
deadlineType: z.enum(deadlineTypes).optional(),
description: z.string().optional(),
dueDate: z.string().optional(), // 2024-05-28
- duration: z.number().optional(), // miliseconds
employeeIds: z.array(z.string()).optional(),
itemDescription: z.string().optional(),
itemReadableId: z.string(),
jobId: z.string(),
jobReadableId: z.string(),
- laborDuration: z.number().optional(),
link: z.string().optional(),
- machineDuration: z.number().optional(),
priority: z.number(),
progress: z.number().optional(), // miliseconds
quantity: z.number().optional(),
@@ -62,15 +64,30 @@ const itemValidator = z.object({
salesOrderId: z.string().optional(),
salesOrderLineId: z.string().optional(),
salesOrderReadableId: z.string().optional(),
- setupDuration: z.number().optional(),
- status: z.enum(jobOperationStatus).optional(),
subtitle: z.string().optional(),
tags: z.array(z.string()).optional(),
thumbnailPath: z.string().optional(),
title: z.string(),
});
-export type Item = z.infer<typeof itemValidator>;
+// Operation item with operation-level status
+const operationItemValidator = baseItemValidator.extend({
+ duration: z.number().optional(), // miliseconds
+ laborDuration: z.number().optional(),
+ machineDuration: z.number().optional(),
+ setupDuration: z.number().optional(),
+ status: z.enum(jobOperationStatus).optional(),
+});
+
+// Job item with job-level status
+const jobItemValidator = baseItemValidator.extend({
+ status: z.enum(jobStatus).optional(),
+ completedDate: z.string().optional(),
+});
+
+export type OperationItem = z.infer<typeof operationItemValidator>;
+export type JobItem = z.infer<typeof jobItemValidator>;
+export type Item = OperationItem | JobItem;
export interface ItemDragData {
type: "item";
diff --git a/apps/erp/app/modules/production/ui/Schedule/index.ts b/apps/erp/app/modules/production/ui/Schedule/index.ts
index ca9fa78b94..32d5239e8b 100644
--- a/apps/erp/app/modules/production/ui/Schedule/index.ts
+++ b/apps/erp/app/modules/production/ui/Schedule/index.ts
@@ -1,2 +1,2 @@
export { Kanban } from "./Kanban";
-export type { Column, Item } from "./Kanban";
+export type { Column, Item, JobItem, OperationItem } from "./Kanban";
diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
index ab83833450..d459da009c 100644
--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
@@ -40,7 +40,7 @@ const productionRoutes: AuthenticatedRouteGroup[] = [
},
{
name: "Schedule",
- to: path.to.schedule,
+ to: path.to.scheduleDates,
icon: <LuSquareKanban />,
},
],
diff --git a/apps/erp/app/routes/x+/_index.tsx b/apps/erp/app/routes/x+/_index.tsx
index b044763826..3c466ae73a 100644
--- a/apps/erp/app/routes/x+/_index.tsx
+++ b/apps/erp/app/routes/x+/_index.tsx
@@ -48,15 +48,6 @@ const AppsPage = () => {
<Subheading>{formatter.format(date)}</Subheading>
<Hr />
<div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,300px),1fr))] gap-6 mb-8">
- {/* {permissions.can("view", "production") && (
- <ModuleCard
- module={{
- name: "Schedule",
- to: path.to.schedule,
- icon: LuCalendarClock,
- }}
- />
- )} */}
{modules
.filter((mod) => mod.name !== "Settings")
.map((module) => (
diff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsx
index 3c51ba4c5a..5b30122d58 100644
--- a/apps/erp/app/routes/x+/job+/new.tsx
+++ b/apps/erp/app/routes/x+/job+/new.tsx
@@ -10,7 +10,12 @@ import { redirect } from "@vercel/remix";
import { useUrlParams, useUser } from "~/hooks";
import { getDefaultShelfForJob } from "~/modules/inventory";
import { getItemReplenishment } from "~/modules/items";
-import { jobValidator, upsertJob, upsertJobMethod } from "~/modules/production";
+import {
+ calculateJobPriority,
+ jobValidator,
+ upsertJob,
+ upsertJobMethod,
+} from "~/modules/production";
import { JobForm } from "~/modules/production/ui/Jobs";
import { getNextSequence } from "~/modules/settings";
import type { MethodItemType } from "~/modules/shared";
@@ -86,10 +91,19 @@ export async function action({ request }: ActionFunctionArgs) {
companyId
);
+ // Calculate priority based on due date and deadline type
+ const priority = await calculateJobPriority(client, {
+ dueDate: data.dueDate ?? null,
+ deadlineType: data.deadlineType,
+ companyId,
+ locationId: validation.data.locationId,
+ });
+
const createJob = await upsertJob(client, {
...data,
jobId,
configuration,
+ priority,
shelfId: shelfId ?? undefined,
startDate: data.dueDate
? parseDate(data.dueDate).subtract({ days: leadTime }).toString()
diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsx
index 1d0821fdda..315535e883 100644
--- a/apps/erp/app/routes/x+/job+/update.tsx
+++ b/apps/erp/app/routes/x+/job+/update.tsx
@@ -4,6 +4,7 @@ import type { recalculateTask } from "@carbon/jobs/trigger/recalculate";
import { tasks } from "@trigger.dev/sdk";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import {
+ calculateJobPriority,
recalculateJobRequirements,
upsertJobMethod,
} from "~/modules/production";
@@ -121,9 +122,58 @@ export async function action({ request }: ActionFunctionArgs) {
}
return json(itemUpdate);
- case "customerId":
case "deadlineType":
case "dueDate":
+ // When dueDate or deadlineType changes, recalculate priority
+ for await (const id of ids) {
+ // Get the current job to access its data
+ const currentJob = await client
+ .from("job")
+ .select("dueDate, deadlineType, locationId")
+ .eq("id", id as string)
+ .eq("companyId", companyId)
+ .single();
+
+ if (currentJob.error || !currentJob.data) {
+ return json(currentJob);
+ }
+
+ // Determine the new dueDate and deadlineType after this update
+ const newDueDate = field === "dueDate" ? (value ?? null) : currentJob.data.dueDate;
+ const newDeadlineType = field === "deadlineType" ? value : currentJob.data.deadlineType;
+
+ if (!newDeadlineType) {
+ return json({ error: { message: "Invalid deadline type" }, data: null });
+ }
+
+ // Calculate new priority
+ const priority = await calculateJobPriority(client, {
+ jobId: id as string,
+ dueDate: newDueDate,
+ deadlineType: newDeadlineType as "ASAP" | "Hard Deadline" | "Soft Deadline" | "No Deadline",
+ companyId,
+ locationId: currentJob.data.locationId,
+ });
+
+ // Update the job with new field value and priority
+ const updateResult = await client
+ .from("job")
+ .update({
+ [field]: value ? value : null,
+ priority,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .eq("id", id as string)
+ .eq("companyId", companyId);
+
+ if (updateResult.error) {
+ return json(updateResult);
+ }
+ }
+
+ return json({ error: null, data: null });
+ case "customerId":
case "jobId":
case "locationId":
case "shelfId":
diff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsx
new file mode 100644
index 0000000000..d8975588f1
--- /dev/null
+++ b/apps/erp/app/routes/x+/schedule+/dates.tsx
@@ -0,0 +1,614 @@
+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 {
+ Button,
+ ClientOnly,
+ Combobox,
+ HStack,
+ IconButton,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Spinner,
+ Switch,
+ useLocalStorage,
+ VStack,
+} from "@carbon/react";
+import {
+ endOfMonth,
+ endOfWeek,
+ getLocalTimeZone,
+ now,
+ parseDate,
+ startOfMonth,
+ startOfWeek,
+ toCalendarDate,
+} from "@internationalized/date";
+import { useLoaderData, useNavigate, useSearchParams } from "@remix-run/react";
+import { json, redirect, type LoaderFunctionArgs } from "@vercel/remix";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { LuChevronLeft, LuChevronRight, LuSettings2 } from "react-icons/lu";
+import { SearchFilter } from "~/components";
+import { useLocations } from "~/components/Form/Location";
+import { ActiveFilters, Filter } from "~/components/Table/components/Filter";
+import type { ColumnFilter } from "~/components/Table/components/Filter/types";
+import { useUrlParams } from "~/hooks";
+import { getJobsByDateRange } from "~/modules/production";
+import type { Column, JobItem } from "~/modules/production/ui/Schedule";
+
+import type { DisplaySettings } from "~/modules/production/ui/Schedule/Kanban";
+import { DateKanban } from "~/modules/production/ui/Schedule/Kanban/DateKanban";
+import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";
+import { getTagsList } from "~/modules/shared";
+import { getUserDefaults } from "~/modules/users/users.server";
+import { usePeople } from "~/stores";
+
+export const handle: Handle = {
+ breadcrumb: "Schedule",
+ to: path.to.scheduleDates,
+ module: "production",
+};
+
+type ViewType = "week" | "month";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "production",
+ bypassRls: true,
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const filterParam = searchParams.getAll("filter");
+ const view = (searchParams.get("view") as ViewType) ?? "week";
+ const dateParam = searchParams.get("date");
+
+ const timezone = getLocalTimeZone();
+ const currentDate = dateParam
+ ? parseDate(dateParam)
+ : toCalendarDate(now(timezone));
+
+ let selectedSalesOrderIds: string[] = [];
+ let selectedTags: string[] = [];
+ let selectedAssignee: string[] = [];
+
+ if (filterParam) {
+ for (const filter of filterParam) {
+ const [key, operator, value] = filter.split(":");
+ if (key === "salesOrderId") {
+ if (operator === "in") {
+ selectedSalesOrderIds = value.split(",");
+ } else if (operator === "eq") {
+ selectedSalesOrderIds = [value];
+ }
+ } else if (key === "tag") {
+ if (operator === "in") {
+ selectedTags = value.split(",");
+ } else if (operator === "eq") {
+ selectedTags = [value];
+ }
+ } else if (key === "assignee") {
+ if (operator === "in") {
+ selectedAssignee = value.split(",");
+ } else if (operator === "eq") {
+ selectedAssignee = [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;
+ }
+
+ // Calculate date range based on view
+ let startDate: string;
+ let endDate: string;
+
+ if (view === "week") {
+ const weekStart = startOfWeek(currentDate, "en-GB"); // en-GB uses Monday as first day
+ const weekEnd = endOfWeek(currentDate, "en-GB");
+ startDate = weekStart.toString();
+ endDate = weekEnd.toString();
+ } else {
+ // Month view - start from first of month, include full weeks (may extend into next month)
+ const monthStart = startOfMonth(currentDate);
+ const monthEnd = endOfMonth(currentDate);
+
+ // Calculate the last week's end date
+ let lastWeekStart = monthStart;
+ while (lastWeekStart.compare(monthEnd) <= 0) {
+ lastWeekStart = lastWeekStart.add({ weeks: 1 });
+ }
+ // Go back one week to get the last week that starts within the month
+ lastWeekStart = lastWeekStart.add({ weeks: -1 });
+ const lastWeekEnd = lastWeekStart.add({ days: 6 });
+
+ startDate = monthStart.toString();
+ endDate = lastWeekEnd.toString();
+ }
+
+ const [jobs, tags] = await Promise.all([
+ getJobsByDateRange(client, locationId ?? "", startDate, endDate),
+ getTagsList(client, companyId, "job"),
+ ]);
+
+ console.log(jobs);
+
+ // Filter jobs
+ let filteredJobs = jobs.data ?? [];
+
+ if (selectedSalesOrderIds.length) {
+ filteredJobs = filteredJobs.filter((job) =>
+ selectedSalesOrderIds.includes(job.salesOrderId)
+ );
+ }
+
+ if (selectedTags.length) {
+ filteredJobs = filteredJobs.filter((job) => {
+ if (job.tags) {
+ return selectedTags.some((tag) => job.tags.includes(tag));
+ }
+ return false;
+ });
+ }
+
+ if (selectedAssignee.length) {
+ filteredJobs = filteredJobs.filter((job) =>
+ selectedAssignee.includes(job.assignee)
+ );
+ }
+
+ if (search) {
+ filteredJobs = filteredJobs.filter(
+ (job) =>
+ job.jobId.toLowerCase().includes(search.toLowerCase()) ||
+ job.itemReadableId?.toLowerCase().includes(search.toLowerCase()) ||
+ job.itemDescription?.toLowerCase().includes(search.toLowerCase())
+ );
+ }
+
+ // Jobs are already sorted by due date and priority from the SQL function
+
+ // Create columns based on view type
+ let columns: Column[] = [];
+ const todayDate = toCalendarDate(now(timezone));
+
+ if (view === "week") {
+ const weekStart = startOfWeek(currentDate, "en-GB"); // en-GB uses Monday as first day
+
+ // Create 7 columns for days of the week (Mon-Sun) + 1 for "Next Week"
+ for (let i = 0; i < 7; i++) {
+ const day = weekStart.add({ days: i });
+ const isToday = day.compare(todayDate) === 0;
+
+ columns.push({
+ id: day.toString(),
+ title: day.toDate(timezone).toLocaleDateString("en-US", {
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ }),
+ type: [],
+ active: isToday,
+ });
+ }
+
+ // Add "Next Week" column
+ columns.push({
+ id: "next-week",
+ title: "Next Week",
+ type: [],
+ active: false,
+ });
+ } else {
+ // Month view - create full 7-day week columns starting from the 1st of the month
+ const monthStart = startOfMonth(currentDate);
+ const monthEnd = endOfMonth(currentDate);
+
+ // Start from the first day of the month
+ let currentWeekStart = monthStart;
+
+ // Continue while we're still in the month
+ while (currentWeekStart.compare(monthEnd) <= 0) {
+ // Each week is exactly 7 days
+ const currentWeekEnd = currentWeekStart.add({ days: 6 });
+
+ // Check if this week contains today
+ const isTodayInWeek =
+ todayDate.compare(currentWeekStart) >= 0 &&
+ todayDate.compare(currentWeekEnd) <= 0;
+
+ const weekStartDate = currentWeekStart.toDate(timezone);
+ const weekEndDate = currentWeekEnd.toDate(timezone);
+
+ columns.push({
+ id: currentWeekStart.toString(),
+ title: `${weekStartDate.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ })} - ${weekEndDate.toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ })}`,
+ type: [],
+ active: isTodayInWeek,
+ });
+
+ // Move to the next week (7 days later)
+ currentWeekStart = currentWeekStart.add({ weeks: 1 });
+ }
+
+ // Add next month column with the month name
+ const nextMonth = monthEnd.add({ days: 1 });
+ const nextMonthName = nextMonth
+ .toDate(timezone)
+ .toLocaleDateString("en-US", {
+ month: "long",
+ });
+ columns.push({
+ id: "next-month",
+ title: nextMonthName,
+ type: [],
+ active: false,
+ });
+ }
+
+ return json({
+ columns,
+ items: (filteredJobs.map((job) => {
+ // Determine which column this item belongs to
+ let columnId = view === "week" ? "next-week" : "next-month";
+
+ if (job.dueDate) {
+ const dueDate = parseDate(job.dueDate.split("T")[0]);
+
+ if (view === "week") {
+ const weekStart = startOfWeek(currentDate, "en-GB"); // en-GB uses Monday as first day
+ const weekEnd = endOfWeek(currentDate, "en-GB");
+
+ if (
+ dueDate.compare(weekStart) >= 0 &&
+ dueDate.compare(weekEnd) <= 0
+ ) {
+ columnId = dueDate.toString();
+ }
+ } else {
+ const monthStart = startOfMonth(currentDate);
+ const monthEnd = endOfMonth(currentDate);
+
+ if (
+ dueDate.compare(monthStart) >= 0 &&
+ dueDate.compare(monthEnd) <= 0
+ ) {
+ // Find which week column this date belongs to
+ // Weeks start on the 1st, 8th, 15th, 22nd, etc.
+ let weekStart = monthStart;
+ while (weekStart.compare(monthEnd) <= 0) {
+ const weekEnd = weekStart.add({ days: 6 });
+ if (
+ dueDate.compare(weekStart) >= 0 &&
+ dueDate.compare(weekEnd) <= 0
+ ) {
+ columnId = weekStart.toString();
+ break;
+ }
+ weekStart = weekStart.add({ weeks: 1 });
+ }
+ }
+ }
+ }
+
+ return {
+ id: job.id,
+ columnId,
+ columnType: "", // Jobs don't have a specific process type
+ priority: job.priority ?? 0,
+ title: job.jobId,
+ link: path.to.job(job.id),
+ subtitle: job.itemReadableId ?? "",
+ assignee: job.assignee,
+ tags: job.tags,
+ description: job.itemDescription,
+ dueDate: job.dueDate,
+ completedDate: job.completedDate,
+ duration: 0, // Jobs don't have duration, only operations do
+ jobId: job.id,
+ jobReadableId: job.jobId,
+ itemReadableId: job.itemReadableId ?? "",
+ itemDescription: job.itemDescription,
+ progress: job.completedOperationCount / Math.max(job.operationCount, 1),
+ deadlineType: job.deadlineType,
+ customerId: job.customerId,
+ quantity: job.quantity,
+ quantityCompleted: job.quantityComplete,
+ quantityScrapped: 0,
+ salesOrderReadableId: job.salesOrderReadableId,
+ salesOrderId: job.salesOrderId,
+ salesOrderLineId: job.salesOrderLineId,
+ status: job.status,
+ setupDuration: 0,
+ laborDuration: 0,
+ machineDuration: 0,
+ thumbnailPath: job.thumbnailPath,
+ };
+ }) ?? []) satisfies JobItem[],
+ salesOrders: Object.entries(
+ filteredJobs?.reduce((acc, job) => {
+ if (job.salesOrderId) {
+ acc[job.salesOrderId] = job.salesOrderReadableId;
+ }
+ return acc;
+ }, {} as Record<string, string>) ?? {}
+ ).map(([id, readableId]) => ({ id, readableId })),
+ availableTags: Object.entries(
+ filteredJobs.reduce((acc, job) => {
+ if (job.tags) {
+ job.tags.forEach((tag: string) => (acc[tag] = true));
+ }
+ return acc;
+ }, {} as Record<string, boolean>)
+ ).map(([tag]) => tag),
+ tags: tags.data ?? [],
+ locationId,
+ view,
+ currentDate: currentDate.toString(),
+ });
+}
+
+const defaultDisplaySettings: DisplaySettings = {
+ showDuration: true,
+ showCustomer: true,
+ showDescription: true,
+ showDueDate: true,
+ showEmployee: true,
+ showProgress: true,
+ showQuantity: true,
+ showStatus: true,
+ showSalesOrder: true,
+ showThumbnail: true,
+};
+
+const DISPLAY_SETTINGS_KEY = "kanban-schedule-dates-display-settings";
+
+function DateKanbanSchedule() {
+ const {
+ columns,
+ items: initialItems,
+ salesOrders,
+ availableTags,
+ tags,
+ locationId,
+ view,
+ currentDate,
+ } = useLoaderData<typeof loader>();
+
+ const locations = useLocations();
+ const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
+
+ const [items, setItems] = useState<JobItem[]>(initialItems);
+ const [displaySettings, setDisplaySettings] = useLocalStorage(
+ DISPLAY_SETTINGS_KEY,
+ defaultDisplaySettings
+ );
+
+ useEffect(() => {
+ setItems(initialItems);
+ }, [initialItems]);
+
+ const sortItems = useCallback((items: JobItem[]) => {
+ return [...items].sort((a, b) => a.priority - b.priority);
+ }, []);
+
+ useEffect(() => {
+ setItems((prevItems) => sortItems(prevItems));
+ }, [sortItems]);
+
+ const [people] = usePeople();
+ const [params] = useUrlParams();
+
+ const currentFilters = params.getAll("filter").filter(Boolean);
+
+ const filters = useMemo<ColumnFilter[]>(() => {
+ return [
+ {
+ accessorKey: "salesOrderId",
+ header: "Sales Order",
+ filter: {
+ type: "static",
+ options: salesOrders.map((so) => ({
+ label: so.readableId,
+ value: so.id,
+ })),
+ },
+ },
+ {
+ accessorKey: "assignee",
+ header: "Assignee",
+ filter: {
+ type: "static",
+ options: people.map((p) => ({
+ label: p.name,
+ value: p.id,
+ })),
+ },
+ },
+ {
+ accessorKey: "tag",
+ header: "Tag",
+ filter: {
+ type: "static",
+ options: availableTags.map((tag) => ({
+ label: tag,
+ value: tag,
+ })),
+ },
+ },
+ ];
+ }, [salesOrders, people, availableTags]);
+
+ const parsedDate = parseDate(currentDate);
+
+ const navigateDate = (direction: "prev" | "next") => {
+ const newDate =
+ view === "week"
+ ? parsedDate.add({ weeks: direction === "next" ? 1 : -1 })
+ : parsedDate.add({ months: direction === "next" ? 1 : -1 });
+
+ const newParams = new URLSearchParams(searchParams);
+ newParams.set("date", newDate.toString());
+ navigate(`?${newParams.toString()}`);
+ };
+
+ const goToToday = () => {
+ const newParams = new URLSearchParams(searchParams);
+ newParams.delete("date"); // Removing date param will default to today
+ navigate(`?${newParams.toString()}`);
+ };
+
+ return (
+ <div className="flex flex-col h-full max-h-full overflow-auto relative">
+ <HStack className="px-4 py-2 flex justify-between bg-card border-b border-border">
+ <HStack>
+ <ScheduleNavigation />
+ <SearchFilter param="search" size="sm" placeholder="Search" />
+ <Filter filters={filters} />
+ </HStack>
+
+ <HStack>
+ <HStack>
+ <Button variant="secondary" onClick={goToToday}>
+ Today
+ </Button>
+ <IconButton
+ variant="secondary"
+ onClick={() => navigateDate("prev")}
+ icon={<LuChevronLeft />}
+ aria-label="Previous Date"
+ />
+
+ <IconButton
+ variant="secondary"
+ onClick={() => navigateDate("next")}
+ icon={<LuChevronRight />}
+ aria-label="Next Date"
+ />
+ </HStack>
+ <Combobox
+ asButton
+ size="sm"
+ value={locationId ?? undefined}
+ options={locations}
+ onChange={(selected) => {
+ const newParams = new URLSearchParams(searchParams);
+ newParams.set("location", selected);
+ window.location.href = `${
+ path.to.scheduleDates
+ }?${newParams.toString()}`;
+ }}
+ />
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ leftIcon={<LuSettings2 />}
+ variant="secondary"
+ className="border-dashed border-border"
+ >
+ Display
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-48">
+ <VStack>
+ {[
+ { key: "showCustomer", label: "Customer" },
+ { key: "showDueDate", label: "Due Date" },
+ { key: "showDuration", label: "Duration" },
+ { key: "showProgress", label: "Progress" },
+ { key: "showQuantity", label: "Quantity" },
+ { key: "showStatus", label: "Status" },
+ { key: "showSalesOrder", label: "Sales Order" },
+ { key: "showThumbnail", label: "Thumbnail" },
+ ].map(({ key, label }) => (
+ <Switch
+ key={key}
+ variant="small"
+ label={label}
+ checked={
+ displaySettings[key as keyof typeof displaySettings]
+ }
+ onCheckedChange={(checked) =>
+ setDisplaySettings((prev) => ({
+ ...prev,
+ [key]: checked,
+ }))
+ }
+ />
+ ))}
+ </VStack>
+ </PopoverContent>
+ </Popover>
+ </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-1 min-h-0 w-full relative">
+ <DateKanban
+ columns={columns}
+ items={items}
+ progressByItemId={{}}
+ tags={tags}
+ showCustomer={displaySettings.showCustomer}
+ showDescription={displaySettings.showDescription}
+ showDueDate={displaySettings.showDueDate}
+ showDuration={displaySettings.showDuration}
+ showEmployee={displaySettings.showEmployee}
+ showProgress={displaySettings.showProgress}
+ showQuantity={displaySettings.showQuantity}
+ showStatus={displaySettings.showStatus}
+ showSalesOrder={displaySettings.showSalesOrder}
+ showThumbnail={displaySettings.showThumbnail}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default function ScheduleRoute() {
+ return (
+ <ClientOnly
+ fallback={
+ <div className="flex h-full w-full items-center justify-center">
+ <Spinner className="h-8 w-8" />
+ </div>
+ }
+ >
+ {() => <DateKanbanSchedule />}
+ </ClientOnly>
+ );
+}
diff --git a/apps/erp/app/routes/x+/schedule+/dates.update.tsx b/apps/erp/app/routes/x+/schedule+/dates.update.tsx
new file mode 100644
index 0000000000..6d35bbcf68
--- /dev/null
+++ b/apps/erp/app/routes/x+/schedule+/dates.update.tsx
@@ -0,0 +1,53 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { validator } from "@carbon/form";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { scheduleJobUpdateValidator } from "~/modules/production/production.models";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, userId } = await requirePermissions(request, {
+ update: "production",
+ });
+
+ const validation = await validator(scheduleJobUpdateValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return json({
+ success: false,
+ message: "Invalid form data",
+ });
+ }
+
+ // Parse the columnId to determine the due date
+ // For date columns: columnId will be a date string like "2025-11-22"
+ // For special columns: "next-week" or "next-month" - we'll set dueDate to null
+ let dueDate: string | null = null;
+
+ if (
+ validation.data.columnId !== "next-week" &&
+ validation.data.columnId !== "next-month"
+ ) {
+ // It's a date string, use it as the due date
+ dueDate = validation.data.columnId;
+ }
+
+ const updateData = {
+ dueDate,
+ priority: validation.data.priority,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ };
+
+ const { error } = await client
+ .from("job")
+ .update(updateData)
+ .eq("id", validation.data.id);
+
+ if (error) {
+ return json({ success: false, message: error.message });
+ }
+
+ return json({ success: true });
+}
diff --git a/apps/erp/app/routes/x+/schedule+/index.tsx b/apps/erp/app/routes/x+/schedule+/operations.tsx
similarity index 96%
rename from apps/erp/app/routes/x+/schedule+/index.tsx
rename to apps/erp/app/routes/x+/schedule+/operations.tsx
index 42c9ddb69b..190352ff6a 100644
--- a/apps/erp/app/routes/x+/schedule+/index.tsx
+++ b/apps/erp/app/routes/x+/schedule+/operations.tsx
@@ -39,7 +39,7 @@ import type { ColumnFilter } from "~/components/Table/components/Filter/types";
import { useFilters } from "~/components/Table/components/Filter/useFilters";
import { useUrlParams, useUser } from "~/hooks";
import { getActiveJobOperationsByLocation } from "~/modules/production";
-import type { Column, Item } from "~/modules/production/ui/Schedule";
+import type { Column, OperationItem } from "~/modules/production/ui/Schedule";
import type {
DisplaySettings,
@@ -47,6 +47,7 @@ import type {
Progress,
} from "~/modules/production/ui/Schedule/Kanban";
import { Kanban } from "~/modules/production/ui/Schedule/Kanban";
+import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";
import {
getLocationsList,
getProcessesList,
@@ -59,7 +60,7 @@ import { makeDurations } from "~/utils/duration";
export const handle: Handle = {
breadcrumb: "Schedule",
- to: path.to.schedule,
+ to: path.to.scheduleOperation,
module: "schedule",
};
@@ -266,7 +267,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
machineDuration: operation.machineDuration,
thumbnailPath: op.thumbnailPath,
};
- }) ?? []) satisfies Item[],
+ }) ?? []) satisfies OperationItem[],
processes: processes.data ?? [],
salesOrders: Object.entries(
filteredOperations?.reduce((acc, op) => {
@@ -316,7 +317,7 @@ function KanbanSchedule() {
const locations = useLocations();
- const [items, setItems] = useState<Item[]>(initialItems);
+ const [items, setItems] = useState<OperationItem[]>(initialItems);
const [displaySettings, setDisplaySettings] = useLocalStorage(
DISPLAY_SETTINGS_KEY,
defaultDisplaySettings
@@ -326,7 +327,7 @@ function KanbanSchedule() {
setItems(initialItems);
}, [initialItems]);
- const sortItems = useCallback((items: Item[]) => {
+ const sortItems = useCallback((items: OperationItem[]) => {
return [...items].sort((a, b) => a.priority - b.priority);
}, []);
@@ -410,6 +411,7 @@ function KanbanSchedule() {
<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>
+ <ScheduleNavigation />
<SearchFilter param="search" size="sm" placeholder="Search" />
<Filter filters={filters} />
</HStack>
@@ -538,9 +540,9 @@ export default function ScheduleRoute() {
}
function useProgressByOperation(
- items: Item[],
- setItems: React.Dispatch<React.SetStateAction<Item[]>>,
- sortItems: (items: Item[]) => Item[]
+ items: OperationItem[],
+ setItems: React.Dispatch<React.SetStateAction<OperationItem[]>>,
+ sortItems: (items: OperationItem[]) => OperationItem[]
) {
const {
company: { id: companyId },
@@ -670,9 +672,9 @@ function useProgressByOperation(
switch (payload.eventType) {
case "UPDATE": {
const { new: updated } = payload;
- setItems((prevItems: Item[]) =>
+ setItems((prevItems: OperationItem[]) =>
sortItems(
- prevItems.map((item: Item) => {
+ prevItems.map((item: OperationItem) => {
if (item.id === updated.id) {
return {
...item,
@@ -688,9 +690,9 @@ function useProgressByOperation(
}
case "DELETE": {
const { old: deleted } = payload;
- setItems((prevItems: Item[]) =>
+ setItems((prevItems: OperationItem[]) =>
sortItems(
- prevItems.filter((item: Item) => item.id !== deleted.id)
+ prevItems.filter((item: OperationItem) => item.id !== deleted.id)
)
);
break;
@@ -763,5 +765,5 @@ function useProgressByOperation(
}
function getLocationPath(locationId: string) {
- return `${path.to.schedule}?location=${locationId}`;
+ return `${path.to.scheduleOperation}?location=${locationId}`;
}
diff --git a/apps/erp/app/routes/x+/schedule+/operation.update.tsx b/apps/erp/app/routes/x+/schedule+/operations.update.tsx
similarity index 100%
rename from apps/erp/app/routes/x+/schedule+/operation.update.tsx
rename to apps/erp/app/routes/x+/schedule+/operations.update.tsx
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 9902842ae3..280edeca79 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -743,7 +743,6 @@ export const path = {
issue: (id: string) => generatePath(`${x}/issue/${id}`),
issueDetails: (id: string) => generatePath(`${x}/issue/${id}/details`),
issueStatus: (id: string) => generatePath(`${x}/issue/${id}/status`),
-
issueActions: (id: string) => generatePath(`${x}/issue/${id}`),
issueDispositions: (id: string) =>
generatePath(`${x}/issue/${id}/dispositions`),
@@ -812,7 +811,6 @@ export const path = {
jobStatus: (id: string) => generatePath(`${x}/job/${id}/status`),
kanban: (id: string) => generatePath(`${x}/inventory/kanbans/${id}`),
kanbans: `${x}/inventory/kanbans`,
-
labelsSettings: `${x}/settings/labels`,
location: (id: string) => generatePath(`${x}/resources/locations/${id}`),
locations: `${x}/resources/locations`,
@@ -1035,7 +1033,6 @@ export const path = {
generatePath(`${x}/warehouse-transfer/${transferId}/details/new`),
newWorkCenter: `${x}/resources/work-centers/new`,
newWebhook: `${x}/settings/webhooks/new`,
-
noQuoteReasons: `${x}/sales/no-quote-reasons`,
noQuoteReason: (id: string) =>
generatePath(`${x}/sales/no-quote-reasons/${id}`),
@@ -1296,8 +1293,10 @@ export const path = {
salesSettings: `${x}/settings/sales`,
saveViews: `${x}/shared/views`,
saveViewOrder: `${x}/shared/view/order`,
- schedule: `${x}/schedule`,
- scheduleOperationUpdate: `${x}/schedule/operation/update`,
+ scheduleOperation: `${x}/schedule/operations`,
+ scheduleOperationUpdate: `${x}/schedule/operations/update`,
+ scheduleDates: `${x}/schedule/dates`,
+ scheduleDatesUpdate: `${x}/schedule/dates/update`,
scrapReason: (id: string) =>
generatePath(`${x}/production/scrap-reasons/${id}`),
scrapReasons: `${x}/production/scrap-reasons`,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 994506e290..ce566b9f26 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -9532,6 +9532,7 @@ export type Database = {
locationId: string
modelUploadId: string | null
notes: Json | null
+ priority: number
productionQuantity: number | null
quantity: number
quantityComplete: number
@@ -9571,6 +9572,7 @@ export type Database = {
locationId: string
modelUploadId?: string | null
notes?: Json | null
+ priority?: number
productionQuantity?: number | null
quantity?: number
quantityComplete?: number
@@ -9610,6 +9612,7 @@ export type Database = {
locationId?: string
modelUploadId?: string | null
notes?: Json | null
+ priority?: number
productionQuantity?: number | null
quantity?: number
quantityComplete?: number
@@ -49259,6 +49262,34 @@ export type Database = {
unitOfMeasureCode: string
}[]
}
+ get_jobs_by_date_range: {
+ Args: { end_date: string; location_id: string; start_date: string }
+ Returns: {
+ assignee: string
+ completedDate: string
+ completedOperationCount: number
+ customerId: string
+ customerName: string
+ deadlineType: Database["public"]["Enums"]["deadlineType"]
+ dueDate: string
+ id: string
+ itemDescription: string
+ itemId: string
+ itemReadableId: string
+ jobId: string
+ operationCount: number
+ priority: number
+ quantity: number
+ quantityComplete: number
+ quantityShipped: number
+ salesOrderId: string
+ salesOrderLineId: string
+ salesOrderReadableId: string
+ status: Database["public"]["Enums"]["jobStatus"]
+ tags: string[]
+ thumbnailPath: string
+ }[]
+ }
get_material_details: {
Args: { item_id: string }
Returns: {
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index da5052c211..e6c912345f 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -9532,6 +9532,7 @@ export type Database = {
locationId: string
modelUploadId: string | null
notes: Json | null
+ priority: number
productionQuantity: number | null
quantity: number
quantityComplete: number
@@ -9571,6 +9572,7 @@ export type Database = {
locationId: string
modelUploadId?: string | null
notes?: Json | null
+ priority?: number
productionQuantity?: number | null
quantity?: number
quantityComplete?: number
@@ -9610,6 +9612,7 @@ export type Database = {
locationId?: string
modelUploadId?: string | null
notes?: Json | null
+ priority?: number
productionQuantity?: number | null
quantity?: number
quantityComplete?: number
@@ -49255,6 +49258,34 @@ export type Database = {
unitOfMeasureCode: string
}[]
}
+ get_jobs_by_date_range: {
+ Args: { end_date: string; location_id: string; start_date: string }
+ Returns: {
+ assignee: string
+ completedDate: string
+ completedOperationCount: number
+ customerId: string
+ customerName: string
+ deadlineType: Database["public"]["Enums"]["deadlineType"]
+ dueDate: string
+ id: string
+ itemDescription: string
+ itemId: string
+ itemReadableId: string
+ jobId: string
+ operationCount: number
+ priority: number
+ quantity: number
+ quantityComplete: number
+ quantityShipped: number
+ salesOrderId: string
+ salesOrderLineId: string
+ salesOrderReadableId: string
+ status: Database["public"]["Enums"]["jobStatus"]
+ tags: string[]
+ thumbnailPath: string
+ }[]
+ }
get_material_details: {
Args: { item_id: string }
Returns: {
diff --git a/packages/database/supabase/migrations/20251122173055_schedule-jobs.sql b/packages/database/supabase/migrations/20251122173055_schedule-jobs.sql
new file mode 100644
index 0000000000..0a75f8006b
--- /dev/null
+++ b/packages/database/supabase/migrations/20251122173055_schedule-jobs.sql
@@ -0,0 +1,119 @@
+ALTER TABLE "job"
+ ADD COLUMN "priority" DOUBLE PRECISION NOT NULL DEFAULT 1;
+
+
+-- Get jobs by location and date range for scheduling
+DROP FUNCTION IF EXISTS get_jobs_by_date_range;
+CREATE OR REPLACE FUNCTION get_jobs_by_date_range(
+ location_id TEXT,
+ start_date DATE,
+ end_date DATE
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "jobId" TEXT,
+ "status" "jobStatus",
+ "dueDate" DATE,
+ "completedDate" TIMESTAMP WITH TIME ZONE,
+ "deadlineType" "deadlineType",
+ "customerId" TEXT,
+ "customerName" TEXT,
+ "salesOrderReadableId" TEXT,
+ "salesOrderId" TEXT,
+ "salesOrderLineId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "quantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityShipped" NUMERIC,
+ "priority" DOUBLE PRECISION,
+ "assignee" TEXT,
+ "tags" TEXT[],
+ "thumbnailPath" TEXT,
+ "operationCount" INTEGER,
+ "completedOperationCount" INTEGER
+)
+SECURITY INVOKER
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH relevant_jobs AS (
+ SELECT
+ j."id",
+ j."jobId",
+ j."status",
+ j."dueDate",
+ j."completedDate",
+ j."deadlineType",
+ j."customerId",
+ j."salesOrderLineId",
+ j."quantity",
+ j."quantityComplete",
+ j."quantityShipped",
+ j."priority",
+ j."assignee",
+ j."tags",
+ mu."thumbnailPath"
+ FROM "job" j
+ LEFT JOIN "modelUpload" mu ON mu.id = j."modelUploadId"
+ WHERE j."locationId" = location_id
+ AND j."dueDate" IS NOT NULL
+ AND j."dueDate" >= start_date
+ AND j."dueDate" <= end_date
+ ),
+ job_items AS (
+ SELECT DISTINCT ON (jmm."jobId")
+ jmm."jobId",
+ jmm."itemId",
+ i."readableId" AS "itemReadableId",
+ i."name" AS "itemDescription",
+ i."thumbnailPath" AS "itemThumbnailPath",
+ imu."thumbnailPath" AS "itemModelThumbnailPath"
+ FROM "jobMakeMethod" jmm
+ LEFT JOIN "item" i ON i.id = jmm."itemId"
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ WHERE jmm."parentMaterialId" IS NULL
+ ORDER BY jmm."jobId", jmm."createdAt"
+ ),
+ operation_stats AS (
+ SELECT
+ jo."jobId",
+ COUNT(*)::INTEGER AS "operationCount",
+ COUNT(*) FILTER (WHERE jo."status" = 'Done')::INTEGER AS "completedOperationCount"
+ FROM "jobOperation" jo
+ GROUP BY jo."jobId"
+ )
+ SELECT
+ rj."id",
+ rj."jobId",
+ rj."status",
+ rj."dueDate",
+ rj."completedDate",
+ rj."deadlineType",
+ rj."customerId",
+ c."name" AS "customerName",
+ so."salesOrderId" AS "salesOrderReadableId",
+ so."id" AS "salesOrderId",
+ rj."salesOrderLineId",
+ ji."itemId",
+ ji."itemReadableId",
+ ji."itemDescription",
+ rj."quantity",
+ rj."quantityComplete",
+ rj."quantityShipped",
+ rj."priority",
+ rj."assignee",
+ rj."tags",
+ COALESCE(ji."itemThumbnailPath", ji."itemModelThumbnailPath", rj."thumbnailPath") AS "thumbnailPath",
+ COALESCE(os."operationCount", 0) AS "operationCount",
+ COALESCE(os."completedOperationCount", 0) AS "completedOperationCount"
+ FROM relevant_jobs rj
+ LEFT JOIN "salesOrderLine" sol ON sol."id" = rj."salesOrderLineId"
+ LEFT JOIN "salesOrder" so ON so."id" = sol."salesOrderId"
+ LEFT JOIN "customer" c ON c."id" = rj."customerId"
+ LEFT JOIN job_items ji ON ji."jobId" = rj."id"
+ LEFT JOIN operation_stats os ON os."jobId" = rj."id"
+ ORDER BY rj."dueDate";
+END;
+$$ LANGUAGE plpgsql;