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.

fix(erp): commit schedule board updates on drop (#1297)

Umar Khan446b5a4e9788
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 443d66ce6f..3ca265c828 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1,5 +1,6 @@
import type { Database } from "@carbon/database";
import { textToTiptap } from "@carbon/utils";
+import { parseDate } from "@internationalized/date";
import { z } from "zod";
import { zfd } from "zod-form-data";
import {
@@ -80,6 +81,57 @@ export function isJobLocked(status: string | null | undefined): boolean {
);
}
+export const DATE_COLUMN_SENTINELS = [
+ "unscheduled",
+ "next-week",
+ "next-month"
+] as const;
+
+export type DateColumnSentinel = (typeof DATE_COLUMN_SENTINELS)[number];
+
+const DATE_COLUMN_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
+
+export function isDateColumnId(value: string): boolean {
+ if (!DATE_COLUMN_PATTERN.test(value)) return false;
+
+ try {
+ parseDate(value);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function isDateColumnSentinel(
+ value: string
+): value is DateColumnSentinel {
+ return DATE_COLUMN_SENTINELS.includes(value as DateColumnSentinel);
+}
+
+export function isScheduleDateColumnId(value: string): boolean {
+ return isDateColumnSentinel(value) || isDateColumnId(value);
+}
+
+/**
+ * Convert a validated Dates board column to the persisted due date. The
+ * sentinel columns intentionally all persist as null; a value outside the
+ * canonical board vocabulary returns undefined for callers that need to
+ * distinguish invalid input from a valid null due date.
+ */
+export function getDueDateForColumn(
+ columnId: string
+): string | null | undefined {
+ if (isDateColumnId(columnId)) return columnId;
+ if (isDateColumnSentinel(columnId)) return null;
+ return undefined;
+}
+
+export const schedulePriorityValidator = z.preprocess(
+ (value) =>
+ typeof value === "string" && value.trim().length === 0 ? undefined : value,
+ zfd.numeric(z.number().refine(Number.isFinite, "Priority must be finite"))
+);
+
/**
* A Queued assemblyPlanJob older than this never got picked up by the worker
* (pickup normally takes seconds) — treat it as dead rather than blocking the
@@ -967,13 +1019,17 @@ export const productionQuantityValidator = z
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())
+ priority: schedulePriorityValidator
});
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())
+ locationId: z.string().trim().min(1, { message: "Location is required" }),
+ columnId: z
+ .string()
+ .min(1, { message: "Column is required" })
+ .refine(isScheduleDateColumnId, { message: "Invalid date column" }),
+ priority: schedulePriorityValidator
});
export const scrapReasonValidator = z.object({
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx
index 78a0a0ccce..b8f73676b2 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx
@@ -1,6 +1,12 @@
import { getLogger } from "@carbon/logger";
-import { ClientOnly, toast } from "@carbon/react";
-import type { DragOverEvent, DragStartEvent } from "@dnd-kit/core";
+import { ClientOnly, cn, toast } from "@carbon/react";
+import type {
+ Active,
+ DragEndEvent,
+ DragOverEvent,
+ DragStartEvent,
+ Over
+} from "@dnd-kit/core";
import {
DndContext,
DragOverlay,
@@ -11,46 +17,203 @@ import {
} from "@dnd-kit/core";
import { sortableKeyboardCoordinates } from "@dnd-kit/sortable";
import { useLingui } from "@lingui/react/macro";
-import { useEffect, useRef, useState } from "react";
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState
+} from "react";
import { createPortal } from "react-dom";
import { useFetchers, useSubmit } from "react-router";
import { path } from "~/utils/path";
import { BoardContainer, ColumnCard } from "./components/ColumnCard";
import { JobCard } from "./components/JobCard";
import { KanbanProvider } from "./context/KanbanContext";
+import { getDateOnly, getPendingDueDate } from "./date-utils";
+import {
+ comparePriorityThenId,
+ createDragOrigin,
+ type DragOrigin,
+ type DragPreview,
+ getColumnPlacement,
+ getItemPlacement,
+ isSamePlacement,
+ isSamePreview,
+ resolveInsertionMarker
+} from "./placement";
import type { Column, DisplaySettings, JobItem, Progress } from "./types";
-import { hasDraggableData } from "./utils";
+import { hasDraggableData, kanbanCollisionDetection } from "./utils";
const logger = getLogger("erp", "datekanban");
type DateKanbanProps = {
columns: Column[];
items: JobItem[];
+ locationId: string;
progressByItemId: Record<string, Progress>;
tags: { name: string }[];
} & DisplaySettings;
-function usePendingItems() {
+type DateDragOrigin = DragOrigin<JobItem> & {
+ dueDate: string | null | undefined;
+};
+
+type DateDragState = {
+ origin: DateDragOrigin;
+ preview: DragPreview | null;
+};
+
+const DateDragPreviewContext = createContext<DateDragState | null>(null);
+
+type DatePreviewJobCardProps = {
+ item: JobItem;
+ locationId: string;
+ isOverlay?: boolean;
+ progressByItemId: Record<string, Progress>;
+};
+
+function DatePreviewJobCard({
+ item,
+ locationId,
+ isOverlay,
+ progressByItemId
+}: DatePreviewJobCardProps) {
+ const dragState = useContext(DateDragPreviewContext);
+ const preview = dragState?.preview;
+ const marker =
+ preview?.targetType === "item" && preview.columnId === item.columnId
+ ? resolveInsertionMarker(preview.slot)
+ : null;
+ const showBefore = marker?.itemId === item.id && marker.position === "before";
+ const showAfter = marker?.itemId === item.id && marker.position === "after";
+
+ return (
+ <div className="relative max-w-[330px]">
+ {(showBefore || showAfter) && (
+ <div
+ aria-hidden
+ className={cn(
+ "pointer-events-none absolute inset-x-2 z-20 h-0.5 rounded-full bg-primary",
+ showBefore ? "-top-1" : "-bottom-1"
+ )}
+ />
+ )}
+ <JobCard
+ item={item}
+ locationId={locationId}
+ isOverlay={isOverlay}
+ progressByItemId={progressByItemId}
+ />
+ </div>
+ );
+}
+
+function isOriginItemDrag(active: Active, origin: DateDragOrigin) {
+ return (
+ hasDraggableData(active) &&
+ active.data.current?.type === "item" &&
+ String(active.id) === origin.item.id
+ );
+}
+
+function resolveDragPlacement(
+ origin: DateDragOrigin,
+ over: Over | null,
+ items: readonly JobItem[],
+ itemsById: ReadonlyMap<string, JobItem>,
+ columnsById: ReadonlyMap<string, Column>
+): DragPreview | null {
+ if (
+ !over ||
+ over.disabled ||
+ !hasDraggableData(over) ||
+ !itemsById.has(origin.item.id)
+ ) {
+ return null;
+ }
+
+ const overId = String(over.id);
+ if (overId === origin.item.id) {
+ return { ...origin.placement, targetType: "item" };
+ }
+
+ const overData = over.data.current;
+ if (overData?.type === "item") {
+ const overItem = itemsById.get(overId);
+ if (
+ !overItem ||
+ overData.item.id !== overId ||
+ overData.item.columnId !== overItem.columnId ||
+ !columnsById.has(overItem.columnId)
+ ) {
+ return null;
+ }
+
+ const placement = getItemPlacement(
+ origin,
+ items,
+ overItem.columnId,
+ overItem.id
+ );
+ return placement ? { ...placement, targetType: "item" } : null;
+ }
+
+ if (overData?.type === "column") {
+ if (
+ overData.column.id !== overId ||
+ !columnsById.has(overId) ||
+ overId === origin.placement.columnId
+ ) {
+ return null;
+ }
+
+ const placement = getColumnPlacement(origin, items, overId);
+ return placement ? { ...placement, targetType: "column" } : null;
+ }
+
+ return null;
+}
+
+function usePendingItems(locationId: string) {
type PendingItem = ReturnType<typeof useFetchers>[number] & {
formData: FormData;
};
+ type PendingProjection = {
+ id: string;
+ priority: number;
+ columnId: string;
+ dueDate: string | null | undefined;
+ };
return useFetchers()
.filter((fetcher): fetcher is PendingItem => {
- return fetcher.formAction === path.to.scheduleDatesUpdate;
+ return (
+ fetcher.formAction === path.to.scheduleDatesUpdate &&
+ fetcher.formData?.get("locationId") === locationId
+ );
})
- .map((fetcher) => {
+ .map((fetcher): PendingProjection => {
+ const persistenceColumnId = fetcher.formData.get("columnId");
const optimisticColumnId = fetcher.formData.get("optimisticColumnId");
- let columnId = optimisticColumnId
- ? String(optimisticColumnId)
- : 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,
+ const columnId =
+ typeof optimisticColumnId === "string" && optimisticColumnId.length > 0
+ ? optimisticColumnId
+ : typeof persistenceColumnId === "string"
+ ? persistenceColumnId
+ : "";
+ const id = fetcher.formData.get("id");
+ const priority = Number(fetcher.formData.get("priority"));
+
+ return {
+ id: typeof id === "string" ? id : "",
priority,
- columnId
+ columnId,
+ dueDate:
+ typeof persistenceColumnId === "string"
+ ? getPendingDueDate(persistenceColumnId)
+ : undefined
};
- return item;
});
}
@@ -92,12 +255,19 @@ function useDateUpdateFailureToast() {
const DateKanban = ({
columns,
items: initialItems,
+ locationId,
progressByItemId,
tags,
...displaySettings
}: DateKanbanProps) => {
const submit = useSubmit();
const [selectedGroup, setSelectedGroup] = useState<string | null>(null);
+ const DateCardComponent = useCallback(
+ (props: Omit<DatePreviewJobCardProps, "locationId">) => (
+ <DatePreviewJobCard {...props} locationId={locationId} />
+ ),
+ [locationId]
+ );
// For date-based kanban, always use the column order from props (don't persist)
const [columnOrder, setColumnOrder] = useState<string[]>(
@@ -113,22 +283,21 @@ const DateKanban = ({
initialItems.map((item) => [item.id, item])
);
- const pendingItems = usePendingItems();
+ const pendingItems = usePendingItems(locationId);
useDateUpdateFailureToast();
// Merge pending items and existing items for optimistic updates
- for (let pendingItem of pendingItems) {
- let item = itemsById.get(pendingItem.id);
+ for (const pendingItem of pendingItems) {
+ const 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 baseItems = Array.from(itemsById.values()).sort(comparePriorityThenId);
+ const columnsMap = new Map(columns.map((column) => [column.id, column]));
+ const dragOriginRef = useRef<DateDragOrigin | null>(null);
+ const [dragState, setDragState] = useState<DateDragState | null>(null);
const sensors = useSensors(
useSensor(PointerSensor),
@@ -137,138 +306,122 @@ const DateKanban = ({
})
);
+ function clearDragState() {
+ dragOriginRef.current = null;
+ setDragState(null);
+ }
+
function onDragStart(event: DragStartEvent) {
- if (!hasDraggableData(event.active)) return;
- const data = event.active.data.current;
+ if (
+ !hasDraggableData(event.active) ||
+ event.active.data.current?.type !== "item"
+ ) {
+ clearDragState();
+ return;
+ }
- // Only handle item dragging, not column dragging (dates are fixed)
- if (data?.type === "item") {
- setActiveItem(data.item as JobItem);
+ const activeItem = itemsById.get(String(event.active.id));
+ if (!activeItem || !columnsMap.has(activeItem.columnId)) {
+ clearDragState();
+ return;
+ }
+
+ const placementOrigin = createDragOrigin(baseItems, activeItem);
+ if (!placementOrigin) {
+ clearDragState();
return;
}
- }
- function onDragEnd() {
- setActiveItem(null);
+ const origin: DateDragOrigin = {
+ ...placementOrigin,
+ dueDate:
+ activeItem.dueDate === undefined
+ ? undefined
+ : getDateOnly(activeItem.dueDate)
+ };
+ dragOriginRef.current = origin;
+ setDragState({ origin, preview: 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;
+ const origin = dragOriginRef.current;
+ if (!origin) return;
+
+ if (!isOriginItemDrag(event.active, origin)) {
+ setDragState((current) =>
+ current?.origin === origin && isSamePreview(current.preview, null)
+ ? current
+ : { origin, preview: null }
+ );
+ return;
+ }
- if (
- activeItem.priority > overItem.priority ||
- activeItem.columnId !== overItem.columnId
- ) {
- priorityAfter = overItem.priority;
+ const placement = resolveDragPlacement(
+ origin,
+ event.over,
+ baseItems,
+ itemsById,
+ columnsMap
+ );
+ const preview =
+ placement && !isSamePlacement(origin.placement, placement)
+ ? placement
+ : null;
+
+ setDragState((current) =>
+ current?.origin === origin && isSamePreview(current.preview, preview)
+ ? current
+ : { origin, preview }
+ );
+ }
- 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;
- }
+ function onDragEnd(event: DragEndEvent) {
+ const origin = dragOriginRef.current;
+ const placement =
+ origin && isOriginItemDrag(event.active, origin)
+ ? resolveDragPlacement(
+ origin,
+ event.over,
+ baseItems,
+ itemsById,
+ columnsMap
+ )
+ : null;
+
+ if (
+ origin &&
+ origin.dueDate !== undefined &&
+ placement &&
+ !isSamePlacement(origin.placement, placement)
+ ) {
+ const isSameDisplayBucket =
+ placement.columnId === origin.placement.columnId;
+ submit(
+ {
+ id: origin.item.id,
+ locationId,
+ columnId: isSameDisplayBucket
+ ? (origin.dueDate ?? origin.placement.columnId)
+ : placement.columnId,
+ optimisticColumnId: placement.columnId,
+ priority: placement.priority
+ },
+ {
+ method: "post",
+ action: path.to.scheduleDatesUpdate,
+ navigate: false,
+ flushSync: true,
+ fetcherKey: `job:${origin.item.id}`
}
- } 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}`
- }
- );
- }
- }
+ clearDragState();
}
- const columnsMap = new Map(columns.map((col) => [col.id, col]));
+ function onDragCancel() {
+ clearDragState();
+ }
const isInitialMount = useRef(true);
@@ -287,56 +440,82 @@ const DateKanban = ({
tags={tags}
columnIds={columns.map((col) => col.id)}
>
- <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}
- isDateView={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
+ <DateDragPreviewContext.Provider value={dragState}>
+ <DndContext
+ sensors={sensors}
+ collisionDetection={kanbanCollisionDetection}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ onDragOver={onDragOver}
+ onDragCancel={onDragCancel}
+ >
+ <BoardContainer>
+ {columnOrder.map((colId) => {
+ const col = columnsMap.get(colId);
+ if (!col) return null;
+ const columnItems = baseItems.filter(
+ (item) => item.columnId === col.id
+ );
+ const showColumnPreview =
+ dragState?.preview?.targetType === "column" &&
+ dragState.preview.columnId === col.id;
+
+ return (
+ <div key={col.id} className="relative flex flex-shrink-0">
+ <ColumnCard
+ column={col}
+ items={columnItems}
progressByItemId={progressByItemId}
+ isDateView={true}
+ disableColumnDrag={true}
+ CardComponent={DateCardComponent}
/>
- )}
- </DragOverlay>,
- document.body
- )
- }
- </ClientOnly>
- </DndContext>
+ {showColumnPreview && (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-1 z-20 ring-2 ring-inset ring-primary"
+ />
+ )}
+ </div>
+ );
+ })}
+ </BoardContainer>
+
+ <ClientOnly fallback={null}>
+ {() =>
+ createPortal(
+ <DragOverlay>
+ {dragState && (
+ <JobCard
+ item={{
+ ...dragState.origin.item,
+ status: progressByItemId[dragState.origin.item.id]
+ ?.active
+ ? "In Progress"
+ : dragState.origin.item.status,
+ employeeIds: progressByItemId[dragState.origin.item.id]
+ ?.employees
+ ? Array.from(
+ progressByItemId[dragState.origin.item.id]
+ .employees!
+ )
+ : undefined,
+ progress:
+ progressByItemId[dragState.origin.item.id]
+ ?.progress ?? 0
+ }}
+ locationId={locationId}
+ isOverlay
+ progressByItemId={progressByItemId}
+ />
+ )}
+ </DragOverlay>,
+ document.body
+ )
+ }
+ </ClientOnly>
+ </DndContext>
+ </DateDragPreviewContext.Provider>
</KanbanProvider>
);
};
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
index 9155909ff8..e5867cd18c 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
@@ -1,9 +1,11 @@
-import { ClientOnly } from "@carbon/react";
+import { ClientOnly, cn } from "@carbon/react";
import type {
+ Active,
Announcements,
DragEndEvent,
DragOverEvent,
DragStartEvent,
+ Over,
UniqueIdentifier
} from "@dnd-kit/core";
import {
@@ -16,15 +18,30 @@ import {
useSensors
} from "@dnd-kit/core";
import { arrayMove, SortableContext } from "@dnd-kit/sortable";
-import { useEffect, useRef, useState } from "react";
+import { createContext, useContext, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useFetchers, useSubmit } from "react-router";
import { path } from "~/utils/path";
import { BoardContainer, ColumnCard } from "./components/ColumnCard";
import { ItemCard } from "./components/ItemCard";
import { KanbanProvider } from "./context/KanbanContext";
+import {
+ comparePriorityThenId,
+ createDragOrigin,
+ type DragOrigin,
+ type DragPreview,
+ getColumnPlacement,
+ getItemPlacement,
+ isSamePlacement,
+ isSamePreview,
+ resolveInsertionMarker
+} from "./placement";
import type { Column, DisplaySettings, Item, Progress } from "./types";
-import { coordinateGetter, hasDraggableData } from "./utils";
+import {
+ coordinateGetter,
+ hasDraggableData,
+ kanbanCollisionDetection
+} from "./utils";
type KanbanProps = {
columns: Column[];
@@ -35,6 +52,129 @@ type KanbanProps = {
const COLUMN_ORDER_KEY = "kanban-column-order";
+type OperationDragOrigin = DragOrigin<Item>;
+
+type KanbanDragState = {
+ origin: OperationDragOrigin;
+ preview: DragPreview | null;
+};
+
+const KanbanDragPreviewContext = createContext<KanbanDragState | null>(null);
+
+function PreviewItemCard({
+ item,
+ isOverlay,
+ progressByItemId
+}: {
+ item: Item;
+ isOverlay?: boolean;
+ progressByItemId: Record<string, Progress>;
+}) {
+ const dragState = useContext(KanbanDragPreviewContext);
+ const preview = dragState?.preview;
+ const marker =
+ preview?.targetType === "item" && preview.columnId === item.columnId
+ ? resolveInsertionMarker(preview.slot)
+ : null;
+ const showBefore = marker?.itemId === item.id && marker.position === "before";
+ const showAfter = marker?.itemId === item.id && marker.position === "after";
+
+ return (
+ <div className="relative max-w-[330px]">
+ {(showBefore || showAfter) && (
+ <div
+ aria-hidden
+ className={cn(
+ "pointer-events-none absolute inset-x-2 z-20 h-0.5 rounded-full bg-primary",
+ showBefore ? "-top-1" : "-bottom-1"
+ )}
+ />
+ )}
+ <ItemCard
+ item={item}
+ isOverlay={isOverlay}
+ progressByItemId={progressByItemId}
+ />
+ </div>
+ );
+}
+
+function isOriginItemDrag(active: Active, origin: OperationDragOrigin) {
+ return (
+ hasDraggableData(active) &&
+ active.data.current?.type === "item" &&
+ String(active.id) === origin.item.id
+ );
+}
+
+function resolveDragPlacement(
+ origin: OperationDragOrigin,
+ over: Over | null,
+ items: readonly Item[],
+ itemsById: ReadonlyMap<string, Item>,
+ columnsById: ReadonlyMap<string, Column>
+): DragPreview | null {
+ if (
+ !over ||
+ over.disabled ||
+ !hasDraggableData(over) ||
+ !itemsById.has(origin.item.id)
+ ) {
+ return null;
+ }
+
+ const overId = String(over.id);
+ if (overId === origin.item.id) {
+ return { ...origin.placement, targetType: "item" };
+ }
+
+ const overData = over.data.current;
+ if (overData?.type === "item") {
+ const overItem = itemsById.get(overId);
+ if (
+ !overItem ||
+ overData.item.id !== overId ||
+ overData.item.columnId !== overItem.columnId ||
+ !columnsById.has(overItem.columnId)
+ ) {
+ return null;
+ }
+
+ const destinationColumn = columnsById.get(overItem.columnId);
+ if (!destinationColumn?.type.includes(origin.item.columnType)) {
+ return null;
+ }
+
+ const placement = getItemPlacement(
+ origin,
+ items,
+ overItem.columnId,
+ overItem.id
+ );
+ return placement ? { ...placement, targetType: "item" } : null;
+ }
+
+ if (overData?.type === "column") {
+ if (
+ overData.column.id !== overId ||
+ !columnsById.has(overId) ||
+ overId === origin.placement.columnId
+ ) {
+ return null;
+ }
+
+ const destinationColumn = columnsById.get(overId);
+ if (!destinationColumn?.type.includes(origin.item.columnType)) {
+ return null;
+ }
+
+ const placement = getColumnPlacement(origin, items, overId);
+ return placement ? { ...placement, targetType: "column" } : null;
+ }
+
+ return null;
+}
+
const Kanban = ({
columns,
items: initialItems,
@@ -72,18 +212,20 @@ const Kanban = ({
const pendingItems = usePendingItems();
// merge pending items and existing items
- for (let pendingItem of pendingItems) {
- let item = itemsById.get(pendingItem.id);
+ for (const pendingItem of pendingItems) {
+ const 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 items = Array.from(itemsById.values()).sort(comparePriorityThenId);
+ const columnsById = new Map(columns.map((column) => [column.id, column]));
const pickedUpItemColumn = useRef<string | null>(null);
+ const dragOriginRef = useRef<OperationDragOrigin | null>(null);
+ const dragTypeRef = useRef<"item" | "column" | null>(null);
+ const [dragState, setDragState] = useState<KanbanDragState | null>(null);
const [activeColumn, setActiveColumn] = useState<Column | null>(null);
const [activeItem, setActiveItem] = useState<Item | null>(null);
@@ -208,242 +350,217 @@ const Kanban = ({
setSelectedGroup={setSelectedGroup}
tags={tags}
>
- <DndContext
- accessibility={{
- announcements
- }}
- sensors={sensors}
- onDragStart={onDragStart}
- onDragEnd={onDragEnd}
- onDragOver={onDragOver}
- >
- <BoardContainer>
- <SortableContext items={columnOrder}>
- {columnOrder.map((colId) => {
- const col = columns.find((c) => c.id === colId);
- if (!col) return null;
- return (
- <ColumnCard
- key={col.id}
- column={col}
- items={items.filter((item) => item.columnId === col.id)}
- progressByItemId={progressByItemId}
- />
- );
- })}
- </SortableContext>
- </BoardContainer>
-
- <ClientOnly fallback={null}>
- {() =>
- createPortal(
- <DragOverlay>
- {activeColumn && (
+ <KanbanDragPreviewContext.Provider value={dragState}>
+ <DndContext
+ accessibility={{
+ announcements
+ }}
+ sensors={sensors}
+ collisionDetection={kanbanCollisionDetection}
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ onDragOver={onDragOver}
+ onDragCancel={onDragCancel}
+ >
+ <BoardContainer>
+ <SortableContext items={columnOrder}>
+ {columnOrder.map((colId) => {
+ const col = columns.find((c) => c.id === colId);
+ if (!col) return null;
+ return (
<ColumnCard
- isOverlay
- column={activeColumn}
- items={items.filter(
- (item) => item.columnId === activeColumn.id
- )}
+ key={col.id}
+ column={col}
+ items={items.filter((item) => item.columnId === col.id)}
progressByItemId={progressByItemId}
+ CardComponent={PreviewItemCard}
/>
- )}
- {activeItem && (
- <ItemCard
- // @ts-expect-error TS2322 - TODO: fix type
- 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>
+ );
+ })}
+ </SortableContext>
+ </BoardContainer>
+
+ <ClientOnly fallback={null}>
+ {() =>
+ createPortal(
+ <DragOverlay>
+ {activeColumn && (
+ <ColumnCard
+ isOverlay
+ column={activeColumn}
+ items={items.filter(
+ (item) => item.columnId === activeColumn.id
+ )}
+ progressByItemId={progressByItemId}
+ />
+ )}
+ {activeItem && (
+ <ItemCard
+ // @ts-expect-error TS2322 - TODO: fix type
+ 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>
+ </KanbanDragPreviewContext.Provider>
</KanbanProvider>
);
+ function clearDragState() {
+ pickedUpItemColumn.current = null;
+ dragOriginRef.current = null;
+ dragTypeRef.current = null;
+ setDragState(null);
+ setActiveItem(null);
+ setActiveColumn(null);
+ }
+
function onDragStart(event: DragStartEvent) {
- if (!hasDraggableData(event.active)) return;
+ if (!hasDraggableData(event.active)) {
+ clearDragState();
+ return;
+ }
+
const data = event.active.data.current;
if (data?.type === "column") {
+ clearDragState();
+ dragTypeRef.current = "column";
setActiveColumn(data.column);
return;
}
if (data?.type === "item") {
+ clearDragState();
+ const activeItem = itemsById.get(String(event.active.id));
+ const origin = activeItem ? createDragOrigin(items, activeItem) : null;
+
+ if (!origin) return;
+
+ dragOriginRef.current = origin;
+ dragTypeRef.current = "item";
+ pickedUpItemColumn.current = data.item.columnId;
+ setDragState({ origin, preview: null });
setActiveItem(data.item);
- return;
}
}
function onDragEnd(event: DragEndEvent) {
- setActiveColumn(null);
- setActiveItem(null);
-
+ const origin = dragOriginRef.current;
const { active, over } = event;
+ const activeData = hasDraggableData(active)
+ ? active.data.current
+ : undefined;
+
+ if (
+ !dragTypeRef.current ||
+ !hasDraggableData(active) ||
+ !over ||
+ !hasDraggableData(over)
+ ) {
+ clearDragState();
+ return;
+ }
- if (!over) return;
-
- const activeId = active.id;
- const overId = over.id;
-
- if (!hasDraggableData(active)) return;
-
- const activeData = active.data.current;
-
- if (activeId === overId) return;
-
- const isActiveAColumn = activeData?.type === "column";
- if (!isActiveAColumn) return;
-
- setColumnOrder((prevOrder) => {
- const activeColumnIndex = prevOrder.findIndex((id) => id === activeId);
- const overColumnIndex = prevOrder.findIndex((id) => id === overId);
-
- return arrayMove(prevOrder, activeColumnIndex, overColumnIndex);
- });
- }
-
- 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 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 activeItem = itemsById.get(activeId.toString());
- const overItem = itemsById.get(overId.toString());
-
- if (!isActiveAnItem) return;
-
- // only allow drop if column type array includes item's column type
- if (!overColumn?.type.includes(activeData?.item.columnType)) return;
+ if (
+ dragTypeRef.current === "column" &&
+ activeData?.type === "column" &&
+ over.data.current?.type === "column"
+ ) {
+ const activeId = active.id;
+ const overId = over.id;
+ if (activeId !== overId) {
+ const activeColumnIndex = columnOrder.findIndex(
+ (id) => id === activeId
+ );
+ const overColumnIndex = columnOrder.findIndex((id) => id === overId);
- // Im dropping a Item over another Item
- 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;
- }
+ if (activeColumnIndex >= 0 && overColumnIndex >= 0) {
+ setColumnOrder(
+ arrayMove(columnOrder, activeColumnIndex, overColumnIndex)
+ );
}
- } 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;
}
+ clearDragState();
+ return;
+ }
- if (activeItem && overItem) {
+ if (
+ dragTypeRef.current === "item" &&
+ activeData?.type === "item" &&
+ origin &&
+ isOriginItemDrag(active, origin)
+ ) {
+ const placement = resolveDragPlacement(
+ origin,
+ over,
+ items,
+ itemsById,
+ columnsById
+ );
+
+ if (placement && !isSamePlacement(origin.placement, placement)) {
submit(
{
- id: activeItem.id,
- columnId: activeItem.columnId,
- priority: newPriority
+ id: origin.item.id,
+ columnId: placement.columnId,
+ priority: placement.priority
},
{
method: "post",
action: path.to.scheduleOperationUpdate,
navigate: false,
- fetcherKey: `item:${activeItem.id}`
+ flushSync: true,
+ fetcherKey: `item:${origin.item.id}`
}
);
}
- return;
}
- const isOverAColumn = overData?.type === "column";
-
- // Im dropping a Item over a column
- 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;
+ clearDragState();
+ }
- const newPriority = (priorityBefore + priorityAfter) / 2;
+ function onDragOver(event: DragOverEvent) {
+ const origin = dragOriginRef.current;
+ if (!origin || !isOriginItemDrag(event.active, origin)) return;
+
+ const placement = resolveDragPlacement(
+ origin,
+ event.over,
+ items,
+ itemsById,
+ columnsById
+ );
+ const preview =
+ placement && !isSamePlacement(origin.placement, placement)
+ ? placement
+ : null;
+
+ setDragState((current) =>
+ current?.origin === origin && isSamePreview(current.preview, preview)
+ ? current
+ : { origin, preview }
+ );
+ }
- submit(
- {
- id: activeItem.id,
- columnId,
- priority: newPriority
- },
- {
- method: "post",
- action: path.to.scheduleOperationUpdate,
- navigate: false,
- fetcherKey: `item:${activeItem.id}`
- }
- );
- }
- }
+ function onDragCancel() {
+ clearDragState();
}
};
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 112c30e64f..e3e4da1409 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
@@ -23,21 +23,23 @@ import { path } from "~/utils/path";
import type { Column, Item, Progress } from "../types";
import { ItemCard } from "./ItemCard";
-type ColumnCardProps = {
+type CardComponentProps<T extends Item> = {
+ item: T;
+ isOverlay?: boolean;
+ progressByItemId: Record<string, Progress>;
+};
+
+type ColumnCardProps<T extends Item> = {
column: Column;
- items: Item[];
+ items: T[];
isOverlay?: boolean;
progressByItemId: Record<string, Progress>;
isDateView?: boolean;
disableColumnDrag?: boolean;
- CardComponent?: ComponentType<{
- item: Item;
- isOverlay?: boolean;
- progressByItemId: Record<string, Progress>;
- }>;
+ CardComponent?: ComponentType<CardComponentProps<T>>;
};
-export function ColumnCard({
+export function ColumnCard<T extends Item = Item>({
column,
items,
isOverlay,
@@ -45,7 +47,7 @@ export function ColumnCard({
isDateView = false,
disableColumnDrag = false,
CardComponent = ItemCard
-}: ColumnCardProps) {
+}: ColumnCardProps<T>) {
const [params] = useUrlParams();
const currentFilters = params.getAll("filter").filter(Boolean);
const itemsIds = useMemo(() => {
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
index 5c8288556b..eacd39c42a 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
@@ -44,6 +44,11 @@ import { useCustomers } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
import JobStatus from "../../../Jobs/JobStatus";
import { useKanban } from "../context/KanbanContext";
+import {
+ getDateOnly,
+ getInlineDueDateUpdateFields,
+ isDateColumnId
+} from "../date-utils";
import type { JobItem } from "../types";
import { useScheduleToday } from "../useScheduleToday";
@@ -54,60 +59,6 @@ interface Progress {
employees?: Set<string>;
}
-const DATE_COLUMN_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
-
-function getDateOnly(value?: string | null) {
- return value?.split("T")[0] ?? null;
-}
-
-function getOptimisticColumnId(dueDate: string, columnIds: string[]) {
- if (columnIds.includes(dueDate)) {
- return dueDate;
- }
-
- if (columnIds.includes("next-week")) {
- return "next-week";
- }
-
- if (columnIds.includes("next-month")) {
- const selectedDate = parseDate(dueDate);
- const dateColumns = columnIds
- .filter((id) => DATE_COLUMN_PATTERN.test(id))
- .sort();
-
- for (const columnId of dateColumns) {
- const weekStart = parseDate(columnId);
- const weekEnd = weekStart.add({ days: 6 });
-
- if (
- selectedDate.compare(weekStart) >= 0 &&
- selectedDate.compare(weekEnd) <= 0
- ) {
- return columnId;
- }
- }
-
- return "next-month";
- }
-
- return dueDate;
-}
-
-function getEmptyDueDateColumnId(
- columnIds: string[],
- fallbackColumnId: string
-) {
- if (columnIds.includes("next-week")) {
- return "next-week";
- }
-
- if (columnIds.includes("next-month")) {
- return "next-month";
- }
-
- return fallbackColumnId;
-}
-
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)]",
{
@@ -141,11 +92,17 @@ const cardVariants = cva(
type JobCardProps = {
item: JobItem;
+ locationId: string;
isOverlay?: boolean;
progressByItemId: Record<string, Progress>;
};
-export function JobCard({ item, isOverlay, progressByItemId }: JobCardProps) {
+export function JobCard({
+ item,
+ locationId,
+ isOverlay,
+ progressByItemId
+}: JobCardProps) {
const { t } = useLingui();
const submit = useSubmit();
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
@@ -188,25 +145,18 @@ export function JobCard({ item, isOverlay, progressByItemId }: JobCardProps) {
const customer = customers.find((s) => s.id === item.customerId);
const scheduleToday = useScheduleToday();
const dueDate = getDateOnly(item.dueDate);
- const isDueDateValid = Boolean(dueDate && DATE_COLUMN_PATTERN.test(dueDate));
+ const isDueDateValid = Boolean(dueDate && isDateColumnId(dueDate));
const dueDateValue = isDueDateValid && dueDate ? dueDate : null;
const scheduleColumnIds = columnIds ?? [];
function submitDueDate(nextDueDate: string | null) {
- const columnId = nextDueDate
- ? nextDueDate
- : getEmptyDueDateColumnId(scheduleColumnIds, item.columnId);
- const optimisticColumnId = nextDueDate
- ? getOptimisticColumnId(nextDueDate, scheduleColumnIds)
- : columnId;
-
submit(
- {
- id: item.id,
- columnId,
- optimisticColumnId,
- priority: item.priority
- },
+ getInlineDueDateUpdateFields(
+ item,
+ locationId,
+ nextDueDate,
+ scheduleColumnIds
+ ),
{
method: "post",
action: path.to.scheduleDatesUpdate,
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/date-utils.test.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/date-utils.test.ts
new file mode 100644
index 0000000000..b9d933cc4c
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/date-utils.test.ts
@@ -0,0 +1,143 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+
+import {
+ getDueDateForColumn,
+ schedulePriorityValidator
+} from "../../../production.models";
+import {
+ getDateOnly,
+ getEmptyDueDateColumnId,
+ getInlineDueDateUpdateFields,
+ getOptimisticColumnId,
+ getPendingDueDate,
+ isDateColumnId,
+ isDateColumnSentinel
+} from "./date-utils";
+
+describe("Dates board date helpers", () => {
+ it("extracts the exact persisted date", () => {
+ expect(getDateOnly("2026-08-09T15:30:00.000Z")).toBe("2026-08-09");
+ expect(getDateOnly(null)).toBeNull();
+ });
+
+ it("recognizes only valid ISO dates and canonical sentinels", () => {
+ expect(isDateColumnId("2026-02-28")).toBe(true);
+ expect(isDateColumnId("2026-02-29")).toBe(false);
+ expect(isDateColumnId("2026-2-9")).toBe(false);
+ expect(isDateColumnSentinel("unscheduled")).toBe(true);
+ expect(isDateColumnSentinel("unknown")).toBe(false);
+ });
+
+ it("centralizes sentinel persistence as null and preserves exact dates", () => {
+ expect(getDueDateForColumn("2026-08-09")).toBe("2026-08-09");
+ expect(getDueDateForColumn("unscheduled")).toBeNull();
+ expect(getDueDateForColumn("next-week")).toBeNull();
+ expect(getDueDateForColumn("next-month")).toBeNull();
+ expect(getDueDateForColumn("not-a-column")).toBeUndefined();
+ });
+
+ it.each([
+ ["2026-08-09", "2026-08-09"],
+ ["unscheduled", null],
+ ["next-week", null],
+ ["next-month", null]
+ ])("maps pending persistence column %s to %s", (columnId, dueDate) => {
+ expect(getPendingDueDate(columnId)).toBe(dueDate);
+ });
+
+ it("does not invent a pending date for missing or invalid persistence input", () => {
+ expect(getPendingDueDate(undefined)).toBeUndefined();
+ expect(getPendingDueDate("2026-02-29")).toBeUndefined();
+ });
+
+ it("maps an exact date into a visible month bucket", () => {
+ expect(
+ getOptimisticColumnId("2026-08-09", [
+ "unscheduled",
+ "2026-08-01",
+ "2026-08-08",
+ "next-month"
+ ])
+ ).toBe("2026-08-08");
+ });
+
+ it("keeps sentinel fallbacks canonical", () => {
+ expect(
+ getEmptyDueDateColumnId(["2026-08-01", "next-week"], "2026-08-01")
+ ).toBe("next-week");
+ expect(
+ getEmptyDueDateColumnId(["2026-08-01", "next-month"], "2026-08-01")
+ ).toBe("next-month");
+ expect(getEmptyDueDateColumnId(["2026-08-01"], "2026-08-01")).toBe(
+ "2026-08-01"
+ );
+ });
+
+ it("builds location-scoped inline exact-date and clear submissions", () => {
+ const item = {
+ id: "job-1",
+ columnId: "2026-08-08",
+ priority: 4
+ };
+ const columnIds = ["2026-08-01", "2026-08-08", "next-month"];
+
+ expect(
+ getInlineDueDateUpdateFields(item, "location-1", "2026-08-09", columnIds)
+ ).toEqual({
+ id: "job-1",
+ locationId: "location-1",
+ columnId: "2026-08-09",
+ optimisticColumnId: "2026-08-08",
+ priority: 4
+ });
+ expect(
+ getInlineDueDateUpdateFields(item, "location-1", null, columnIds)
+ ).toEqual({
+ id: "job-1",
+ locationId: "location-1",
+ columnId: "next-month",
+ optimisticColumnId: "next-month",
+ priority: 4
+ });
+ });
+});
+
+describe("shared schedule priority validation", () => {
+ it.each([
+ undefined,
+ "",
+ " ",
+ "\t",
+ "\n",
+ " \t\n"
+ ])("rejects blank priority %j", (value) => {
+ expect(schedulePriorityValidator.safeParse(value).success).toBe(false);
+ });
+
+ it.each([
+ [" 4.25 ", 4.25],
+ ["-3.5", -3.5]
+ ])("accepts finite numeric priority %s", (value, expected) => {
+ expect(schedulePriorityValidator.safeParse(value)).toMatchObject({
+ success: true,
+ data: expected
+ });
+ });
+
+ it.each([
+ "NaN",
+ "Infinity",
+ "-Infinity"
+ ])("rejects non-finite priority %s", (value) => {
+ expect(schedulePriorityValidator.safeParse(value).success).toBe(false);
+ });
+});
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/date-utils.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/date-utils.ts
new file mode 100644
index 0000000000..36323f072e
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/date-utils.ts
@@ -0,0 +1,100 @@
+import { parseDate } from "@internationalized/date";
+import {
+ getDueDateForColumn,
+ isDateColumnId,
+ isDateColumnSentinel
+} from "../../../production.models";
+
+export { getDueDateForColumn, isDateColumnId, isDateColumnSentinel };
+
+export function getPendingDueDate(
+ persistenceColumnId: string | null | undefined
+): string | null | undefined {
+ if (!persistenceColumnId) return undefined;
+ return getDueDateForColumn(persistenceColumnId);
+}
+
+export function getDateOnly(value?: string | null): string | null {
+ return value?.split("T")[0] ?? null;
+}
+
+type DueDateUpdateItem = {
+ id: string;
+ columnId: string;
+ priority: number;
+};
+
+/** Build the inline due-date request from the current board context. */
+export function getInlineDueDateUpdateFields(
+ item: DueDateUpdateItem,
+ locationId: string,
+ nextDueDate: string | null,
+ columnIds: readonly string[]
+) {
+ const columnId = nextDueDate
+ ? nextDueDate
+ : getEmptyDueDateColumnId(columnIds, item.columnId);
+ const optimisticColumnId = nextDueDate
+ ? getOptimisticColumnId(nextDueDate, columnIds)
+ : columnId;
+
+ return {
+ id: item.id,
+ locationId,
+ columnId,
+ optimisticColumnId,
+ priority: item.priority
+ };
+}
+
+/**
+ * Map a persisted due date to the visible Dates board column. Week columns
+ * represent exact dates; month columns represent seven-day buckets.
+ */
+export function getOptimisticColumnId(
+ dueDate: string,
+ columnIds: readonly string[]
+): string {
+ if (columnIds.includes(dueDate)) return dueDate;
+
+ if (columnIds.includes("next-week")) return "next-week";
+
+ if (columnIds.includes("next-month")) {
+ let selectedDate: ReturnType<typeof parseDate>;
+ try {
+ selectedDate = parseDate(dueDate);
+ } catch {
+ return "next-month";
+ }
+
+ const dateColumns = columnIds
+ .filter(isDateColumnId)
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
+
+ for (const columnId of dateColumns) {
+ const weekStart = parseDate(columnId);
+ const weekEnd = weekStart.add({ days: 6 });
+
+ if (
+ selectedDate.compare(weekStart) >= 0 &&
+ selectedDate.compare(weekEnd) <= 0
+ ) {
+ return columnId;
+ }
+ }
+
+ return "next-month";
+ }
+
+ return dueDate;
+}
+
+/** Pick the canonical null-producing sentinel when an inline date is cleared. */
+export function getEmptyDueDateColumnId(
+ columnIds: readonly string[],
+ fallbackColumnId: string
+): string {
+ if (columnIds.includes("next-week")) return "next-week";
+ if (columnIds.includes("next-month")) return "next-month";
+ return fallbackColumnId;
+}
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx
new file mode 100644
index 0000000000..3b37426af3
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx
@@ -0,0 +1,743 @@
+import type { ReactElement } from "react";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { DateKanban } from "./DateKanban";
+import Kanban from "./Kanban";
+import type { Column, Item, JobItem } from "./types";
+
+const submit = vi.hoisted(() => vi.fn());
+const arrayMove = vi.hoisted(() =>
+ vi.fn((items: string[], from: number, to: number) => {
+ const next = [...items];
+ const [moved] = next.splice(from, 1);
+ next.splice(to, 0, moved);
+ return next;
+ })
+);
+const capturedDndProps = vi.hoisted(() => ({
+ current: null as DndProps | null
+}));
+
+type DragItem = Item & {
+ columnType: string;
+};
+
+type DragActive = {
+ id: string;
+ data: {
+ current: { type: "item" | "column"; item?: DragItem; column?: Column };
+ };
+};
+
+type DragOver = DragActive & {
+ disabled: boolean;
+};
+
+type DndProps = {
+ onDragStart: (event: { active: DragActive }) => void;
+ onDragOver: (event: { active: DragActive; over: DragOver | null }) => void;
+ onDragEnd: (event: { active: DragActive; over: DragOver | null }) => void;
+ onDragCancel: () => void;
+};
+
+type TestFetcher = {
+ formAction: string;
+ formData: FormData | undefined;
+ key: string;
+ state: "loading" | "submitting";
+ data?: unknown;
+};
+
+const fetchers = vi.hoisted(() => ({ current: [] as TestFetcher[] }));
+
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+vi.mock("@carbon/logger", () => ({
+ getLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() })
+}));
+vi.mock("@carbon/react", () => ({
+ ClientOnly: () => null,
+ cn: (...classes: unknown[]) => classes.filter(Boolean).join(" "),
+ toast: { error: vi.fn() }
+}));
+vi.mock("@lingui/react/macro", () => ({
+ useLingui: () => ({ t: () => "translated" })
+}));
+vi.mock("@dnd-kit/core", async () => {
+ const actual =
+ await vi.importActual<typeof import("@dnd-kit/core")>("@dnd-kit/core");
+ return {
+ ...actual,
+ DndContext: (props: DndProps) => {
+ capturedDndProps.current = props;
+ return null;
+ },
+ KeyboardSensor: {},
+ MouseSensor: {},
+ PointerSensor: {},
+ TouchSensor: {},
+ useSensor: vi.fn((sensor) => sensor),
+ useSensors: vi.fn((...sensors) => sensors)
+ };
+});
+vi.mock("@dnd-kit/sortable", async () => {
+ const actual =
+ await vi.importActual<typeof import("@dnd-kit/sortable")>(
+ "@dnd-kit/sortable"
+ );
+ return {
+ ...actual,
+ SortableContext: () => null,
+ arrayMove,
+ sortableKeyboardCoordinates: vi.fn()
+ };
+});
+vi.mock("react-router", () => ({
+ useFetchers: () => fetchers.current,
+ useSubmit: () => submit
+}));
+vi.mock("~/utils/path", () => ({
+ path: {
+ to: {
+ scheduleDatesUpdate: "/schedule/dates/update",
+ scheduleOperationUpdate: "/schedule/operations/update"
+ }
+ }
+}));
+vi.mock("./components/ColumnCard", () => ({
+ BoardContainer: () => null,
+ ColumnCard: () => null
+}));
+vi.mock("./components/ItemCard", () => ({
+ ItemCard: () => null
+}));
+vi.mock("./components/JobCard", () => ({
+ JobCard: () => null
+}));
+
+const settings = {
+ showCustomer: false,
+ showDescription: false,
+ showDueDate: false,
+ showDuration: false,
+ showEmployee: false,
+ showProgress: false,
+ showQuantity: false,
+ showStatus: false,
+ showSalesOrder: false,
+ showThumbnail: false
+};
+
+const operationColumns: Column[] = [
+ { id: "wc-1", title: "Work Center 1", type: ["Process"] },
+ { id: "wc-2", title: "Work Center 2", type: ["Process"] }
+];
+
+const operationItems = [
+ {
+ id: "operation-a",
+ columnId: "wc-1",
+ columnType: "Process",
+ priority: 0,
+ title: "Operation A"
+ },
+ {
+ id: "operation-b",
+ columnId: "wc-1",
+ columnType: "Process",
+ priority: 10,
+ title: "Operation B"
+ },
+ {
+ id: "operation-c",
+ columnId: "wc-2",
+ columnType: "Process",
+ priority: 20,
+ title: "Operation C"
+ }
+] as DragItem[];
+
+const dateColumns: Column[] = [
+ { id: "2026-08-08", title: "Aug 8", type: ["Job"] },
+ { id: "2026-08-15", title: "Aug 15", type: ["Job"] }
+];
+
+const dateItems = [
+ {
+ id: "job-a",
+ columnId: "2026-08-08",
+ columnType: "Job",
+ priority: 0,
+ dueDate: "2026-08-09T15:30:00.000Z",
+ title: "Job A"
+ },
+ {
+ id: "job-b",
+ columnId: "2026-08-08",
+ columnType: "Job",
+ priority: 10,
+ dueDate: "2026-08-10T15:30:00.000Z",
+ title: "Job B"
+ },
+ {
+ id: "job-c",
+ columnId: "2026-08-15",
+ columnType: "Job",
+ priority: 20,
+ dueDate: "2026-08-16T15:30:00.000Z",
+ title: "Job C"
+ }
+] as JobItem[];
+
+function itemActive(item: DragItem): DragActive {
+ return {
+ id: item.id,
+ data: { current: { type: "item" as const, item } }
+ };
+}
+
+function itemOver(item: DragItem): DragOver {
+ return { ...itemActive(item), disabled: false };
+}
+
+function columnActive(column: Column): DragActive {
+ return {
+ id: column.id,
+ data: { current: { type: "column" as const, column } }
+ };
+}
+
+function columnOver(column: Column): DragOver {
+ return { ...columnActive(column), disabled: false };
+}
+
+function captureBoard(
+ Board: (props: any) => ReactElement,
+ props: Record<string, unknown>
+): DndProps {
+ capturedDndProps.current = null;
+ renderToStaticMarkup(createElement(Board, props));
+ if (!capturedDndProps.current) {
+ throw new Error("DndContext was not rendered");
+ }
+ return capturedDndProps.current;
+}
+
+function captureOperationsBoard(
+ items: DragItem[] = operationItems,
+ columns: Column[] = operationColumns
+) {
+ return captureBoard(Kanban, {
+ ...settings,
+ columns,
+ items,
+ progressByItemId: {},
+ tags: []
+ });
+}
+
+function captureDatesBoard(
+ items: JobItem[] = dateItems,
+ columns: Column[] = dateColumns
+) {
+ return captureBoard(DateKanban, {
+ ...settings,
+ columns,
+ items,
+ locationId: "location-1",
+ progressByItemId: {},
+ tags: []
+ });
+}
+
+function pendingDateFetcher({
+ id = "job-a",
+ locationId = "location-1",
+ priority = "5",
+ columnId,
+ optimisticColumnId = columnId
+}: {
+ id?: string;
+ locationId?: string;
+ priority?: string;
+ columnId?: string;
+ optimisticColumnId?: string;
+}): TestFetcher {
+ const formData = new FormData();
+ formData.set("id", id);
+ formData.set("locationId", locationId);
+ formData.set("priority", priority);
+ if (columnId !== undefined) {
+ formData.set("columnId", columnId);
+ }
+ if (optimisticColumnId !== undefined) {
+ formData.set("optimisticColumnId", optimisticColumnId);
+ }
+ return {
+ formAction: "/schedule/dates/update",
+ formData,
+ key: `job:${id}`,
+ state: "loading"
+ };
+}
+
+function startItemDrag(board: DndProps, item: DragItem) {
+ board.onDragStart({ active: itemActive(item) });
+}
+
+beforeEach(() => {
+ submit.mockClear();
+ arrayMove.mockClear();
+ fetchers.current = [];
+ capturedDndProps.current = null;
+ Object.defineProperty(globalThis, "localStorage", {
+ configurable: true,
+ value: {
+ getItem: () => null,
+ setItem: vi.fn()
+ }
+ });
+});
+
+describe("Dates board drag lifecycle", () => {
+ it("submits once on the final changed drop, never during circuitous hover, and preserves the exact date", () => {
+ const board = captureDatesBoard();
+ const active = dateItems[0];
+
+ startItemDrag(board, active);
+ board.onDragOver({
+ active: itemActive(active),
+ over: itemOver(dateItems[2])
+ });
+ board.onDragOver({
+ active: itemActive(active),
+ over: columnOver(dateColumns[1])
+ });
+ board.onDragOver({
+ active: itemActive(active),
+ over: itemOver(dateItems[1])
+ });
+
+ expect(submit).not.toHaveBeenCalled();
+
+ board.onDragEnd({
+ active: itemActive(active),
+ over: itemOver(dateItems[1])
+ });
+
+ expect(submit).toHaveBeenCalledTimes(1);
+ expect(submit).toHaveBeenCalledWith(
+ {
+ id: "job-a",
+ locationId: "location-1",
+ columnId: "2026-08-09",
+ optimisticColumnId: "2026-08-08",
+ priority: 11
+ },
+ expect.objectContaining({ action: "/schedule/dates/update" })
+ );
+ });
+
+ it("uses the pending exact persisted date for a chained same-bucket reorder", () => {
+ const active = {
+ ...dateItems[0],
+ columnId: "2026-08-15",
+ dueDate: "2026-08-16T15:30:00.000Z"
+ };
+ const target = {
+ ...dateItems[2],
+ id: "job-exact-target",
+ columnId: "2026-08-08"
+ };
+ fetchers.current = [
+ pendingDateFetcher({
+ columnId: "2026-08-09",
+ optimisticColumnId: "2026-08-08"
+ })
+ ];
+ const board = captureDatesBoard([active, target]);
+
+ startItemDrag(board, active);
+ board.onDragOver({ active: itemActive(active), over: itemOver(target) });
+ expect(submit).not.toHaveBeenCalled();
+
+ board.onDragEnd({ active: itemActive(active), over: itemOver(target) });
+
+ expect(submit).toHaveBeenCalledWith(
+ {
+ id: "job-a",
+ locationId: "location-1",
+ columnId: "2026-08-09",
+ optimisticColumnId: "2026-08-08",
+ priority: 21
+ },
+ expect.objectContaining({ action: "/schedule/dates/update" })
+ );
+ expect(submit).not.toHaveBeenCalledWith(
+ expect.objectContaining({ columnId: "2026-08-16" }),
+ expect.anything()
+ );
+ });
+
+ it("ignores pending date data from another location", () => {
+ fetchers.current = [
+ pendingDateFetcher({
+ locationId: "location-2",
+ columnId: "2026-08-16",
+ optimisticColumnId: "2026-08-15"
+ })
+ ];
+ const board = captureDatesBoard();
+ const active = dateItems[0];
+
+ startItemDrag(board, active);
+ board.onDragEnd({
+ active: itemActive(active),
+ over: itemOver(dateItems[2])
+ });
+
+ expect(submit).toHaveBeenCalledWith(
+ expect.objectContaining({
+ locationId: "location-1",
+ columnId: "2026-08-15"
+ }),
+ expect.objectContaining({ action: "/schedule/dates/update" })
+ );
+ expect(submit).not.toHaveBeenCalledWith(
+ expect.objectContaining({ columnId: "2026-08-16" }),
+ expect.anything()
+ );
+ });
+
+ it("ignores a Dates fetcher without form data and preserves the next drag origin", () => {
+ fetchers.current = [
+ {
+ formAction: "/schedule/dates/update",
+ formData: undefined,
+ key: "job:job-a",
+ state: "loading"
+ }
+ ];
+ const board = captureDatesBoard();
+ const active = dateItems[0];
+
+ startItemDrag(board, active);
+ board.onDragEnd({
+ active: itemActive(active),
+ over: itemOver(dateItems[1])
+ });
+
+ expect(submit).toHaveBeenCalledTimes(1);
+ expect(submit).toHaveBeenCalledWith(
+ {
+ id: "job-a",
+ locationId: "location-1",
+ columnId: "2026-08-09",
+ optimisticColumnId: "2026-08-08",
+ priority: 11
+ },
+ expect.objectContaining({ action: "/schedule/dates/update" })
+ );
+ });
+
+ it.each([
+ ["missing", undefined],
+ ["invalid", "2026-02-29"]
+ ] as const)("does not submit an unknown pending persisted date (%s)", (_kind, columnId) => {
+ const active = {
+ ...dateItems[0],
+ columnId: "2026-08-15",
+ dueDate: "2026-08-16T15:30:00.000Z"
+ };
+ const target = {
+ ...dateItems[2],
+ id: "job-exact-target",
+ columnId: "2026-08-08"
+ };
+ fetchers.current = [
+ pendingDateFetcher({
+ columnId,
+ optimisticColumnId: "2026-08-08"
+ })
+ ];
+ const board = captureDatesBoard([active, target]);
+
+ startItemDrag(board, active);
+ board.onDragOver({ active: itemActive(active), over: itemOver(target) });
+ expect(submit).not.toHaveBeenCalled();
+
+ board.onDragEnd({ active: itemActive(active), over: itemOver(target) });
+
+ expect(submit).toHaveBeenCalledTimes(0);
+ expect(submit).not.toHaveBeenCalledWith(
+ expect.objectContaining({ columnId: "2026-08-16" }),
+ expect.anything()
+ );
+ for (const unsafeColumnId of [
+ "2026-08-08",
+ "unscheduled",
+ "next-week",
+ "next-month"
+ ]) {
+ expect(submit).not.toHaveBeenCalledWith(
+ expect.objectContaining({ columnId: unsafeColumnId }),
+ expect.anything()
+ );
+ }
+ });
+
+ it("uses null for a pending sentinel during a chained same-bucket reorder", () => {
+ const sentinelTarget = {
+ ...dateItems[2],
+ id: "job-null-target",
+ columnId: "next-week",
+ dueDate: undefined
+ } as JobItem;
+ const columns = [
+ ...dateColumns,
+ { id: "next-week", title: "Next Week", type: ["Job"] }
+ ];
+ fetchers.current = [
+ pendingDateFetcher({
+ columnId: "next-week",
+ optimisticColumnId: "next-week"
+ })
+ ];
+ const board = captureDatesBoard([dateItems[0], sentinelTarget], columns);
+ const active = dateItems[0];
+
+ startItemDrag(board, active);
+ board.onDragOver({
+ active: itemActive(active),
+ over: itemOver(sentinelTarget)
+ });
+ expect(submit).not.toHaveBeenCalled();
+
+ board.onDragEnd({
+ active: itemActive(active),
+ over: itemOver(sentinelTarget)
+ });
+
+ expect(submit).toHaveBeenCalledWith(
+ {
+ id: "job-a",
+ locationId: "location-1",
+ columnId: "next-week",
+ optimisticColumnId: "next-week",
+ priority: 21
+ },
+ expect.objectContaining({ action: "/schedule/dates/update" })
+ );
+ expect(submit).not.toHaveBeenCalledWith(
+ expect.objectContaining({ columnId: "2026-08-09" }),
+ expect.anything()
+ );
+ });
+
+ it.each([
+ ["outside", null],
+ ["self-target", itemOver(dateItems[0])]
+ ])("submits zero times for a %s drag end", (_name, over) => {
+ const board = captureDatesBoard();
+ const active = dateItems[0];
+
+ startItemDrag(board, active);
+ board.onDragEnd({ active: itemActive(active), over });
+
+ expect(submit).not.toHaveBeenCalled();
+ });
+
+ it("does not commit a cached hover when ending back on the source card", () => {
+ const board = captureDatesBoard();
+ const active = dateItems[0];
+
+ startItemDrag(board, active);
+ board.onDragOver({
+ active: itemActive(active),
+ over: itemOver(dateItems[1])
+ });
+ board.onDragEnd({ active: itemActive(active), over: itemOver(active) });
+
+ expect(submit).not.toHaveBeenCalled();
+ });
+
+ it("clears cancellation, permits a fresh drag, and submits only once", () => {
+ const board = captureDatesBoard();
+ const active = dateItems[0];
+
+ startItemDrag(board, active);
+ board.onDragOver({
+ active: itemActive(active),
+ over: itemOver(dateItems[1])
+ });
+ board.onDragCancel();
+ board.onDragEnd({
+ active: itemActive(active),
+ over: itemOver(dateItems[1])
+ });
+ expect(submit).not.toHaveBeenCalled();
+
+ startItemDrag(board, active);
+ board.onDragEnd({
+ active: itemActive(active),
+ over: itemOver(dateItems[1])
+ });
+ expect(submit).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not submit when an end callback repeats after success", () => {
+ const board = captureDatesBoard();
+ const active = dateItems[0];
+ const over = itemOver(dateItems[1]);
+
+ startItemDrag(board, active);
+ board.onDragEnd({ active: itemActive(active), over });
+ board.onDragEnd({ active: itemActive(active), over });
+
+ expect(submit).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("Operations board drag lifecycle", () => {
+ it("submits once on the final changed drop and never during circuitous hover", () => {
+ const board = captureOperationsBoard();
+ const active = operationItems[0];
+
+ startItemDrag(board, active);
+ board.onDragOver({
+ active: itemActive(active),
+ over: itemOver(operationItems[1])
+ });
+ board.onDragOver({
+ active: itemActive(active),
+ over: columnOver(operationColumns[1])
+ });
+ board.onDragOver({
+ active: itemActive(active),
+ over: itemOver(operationItems[2])
+ });
+
+ expect(submit).not.toHaveBeenCalled();
+
+ board.onDragEnd({
+ active: itemActive(active),
+ over: itemOver(operationItems[2])
+ });
+
+ expect(submit).toHaveBeenCalledTimes(1);
+ expect(submit).toHaveBeenCalledWith(
+ { id: "operation-a", columnId: "wc-2", priority: 19 },
+ expect.objectContaining({ action: "/schedule/operations/update" })
+ );
+ });
+
+ it.each([
+ ["outside", null],
+ ["self-target", itemOver(operationItems[0])]
+ ])("submits zero times for a %s drag end", (_name, over) => {
+ const board = captureOperationsBoard();
+ const active = operationItems[0];
+
+ startItemDrag(board, active);
+ board.onDragEnd({ active: itemActive(active), over });
+
+ expect(submit).not.toHaveBeenCalled();
+ });
+
+ it("does not commit a cached hover when ending back on the source card", () => {
+ const board = captureOperationsBoard();
+ const active = operationItems[0];
+
+ startItemDrag(board, active);
+ board.onDragOver({
+ active: itemActive(active),
+ over: itemOver(operationItems[2])
+ });
+ board.onDragEnd({ active: itemActive(active), over: itemOver(active) });
+
+ expect(submit).not.toHaveBeenCalled();
+ });
+
+ it("clears item cancellation, permits a fresh drag, and submits only once", () => {
+ const board = captureOperationsBoard();
+ const active = operationItems[0];
+ const over = itemOver(operationItems[2]);
+
+ startItemDrag(board, active);
+ board.onDragOver({ active: itemActive(active), over });
+ board.onDragCancel();
+ board.onDragEnd({ active: itemActive(active), over });
+ expect(submit).not.toHaveBeenCalled();
+
+ startItemDrag(board, active);
+ board.onDragEnd({ active: itemActive(active), over });
+ expect(submit).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not submit when an end callback repeats after success", () => {
+ const board = captureOperationsBoard();
+ const active = operationItems[0];
+ const over = itemOver(operationItems[2]);
+
+ startItemDrag(board, active);
+ board.onDragEnd({ active: itemActive(active), over });
+ board.onDragEnd({ active: itemActive(active), over });
+
+ expect(submit).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects an incompatible process/work-centre drop without submitting", () => {
+ const incompatibleColumn = {
+ id: "wc-2",
+ title: "Assembly Center",
+ type: ["Assembly"]
+ };
+ const board = captureOperationsBoard(operationItems, [
+ operationColumns[0],
+ incompatibleColumn
+ ]);
+ const active = operationItems[0];
+
+ startItemDrag(board, active);
+ board.onDragEnd({
+ active: itemActive(active),
+ over: columnOver(incompatibleColumn)
+ });
+
+ expect(submit).not.toHaveBeenCalled();
+ });
+
+ it("reorders columns locally without submitting an item update", () => {
+ const board = captureOperationsBoard();
+
+ board.onDragStart({ active: columnActive(operationColumns[0]) });
+ board.onDragEnd({
+ active: columnActive(operationColumns[0]),
+ over: columnOver(operationColumns[1])
+ });
+
+ expect(arrayMove).toHaveBeenCalledWith(["wc-1", "wc-2"], 0, 1);
+ expect(submit).not.toHaveBeenCalled();
+ });
+
+ it("clears a cancelled column gesture without reordering or submitting", () => {
+ const board = captureOperationsBoard();
+
+ board.onDragStart({ active: columnActive(operationColumns[0]) });
+ board.onDragCancel();
+ board.onDragEnd({
+ active: columnActive(operationColumns[0]),
+ over: columnOver(operationColumns[1])
+ });
+
+ expect(arrayMove).not.toHaveBeenCalled();
+ expect(submit).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/placement.test.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/placement.test.ts
new file mode 100644
index 0000000000..6490019580
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/placement.test.ts
@@ -0,0 +1,220 @@
+import { describe, expect, it } from "vitest";
+import {
+ calculateFractionalPriority,
+ comparePriorityThenId,
+ createDragOrigin,
+ getColumnPlacement,
+ getItemPlacement,
+ isSamePlacement,
+ resolveInsertionMarker
+} from "./placement";
+
+type TestItem = {
+ id: string;
+ columnId: string;
+ priority: number;
+};
+
+const item = (id: string, priority: number, columnId = "a"): TestItem => ({
+ id,
+ columnId,
+ priority
+});
+
+describe("placement", () => {
+ it("sorts equal priorities by id", () => {
+ expect(
+ [item("b", 1), item("a", 1), item("c", 0)].sort(comparePriorityThenId)
+ ).toEqual([item("c", 0), item("a", 1), item("b", 1)]);
+ });
+
+ it("excludes the active item from the origin and destination siblings", () => {
+ const origin = createDragOrigin(
+ [item("a", 0), item("b", 1), item("c", 2)],
+ item("b", 1)
+ );
+
+ expect(origin?.placement.slot).toEqual({
+ index: 1,
+ previousItemId: "a",
+ nextItemId: "c"
+ });
+
+ const placement = getItemPlacement(
+ origin!,
+ [item("a", 0), item("b", 1), item("c", 2)],
+ "a",
+ "c"
+ );
+ expect(placement?.priority).toBe(3);
+ expect(placement?.slot).toEqual({
+ index: 2,
+ previousItemId: "c",
+ nextItemId: null
+ });
+ });
+
+ it("calculates an upward same-column insertion before the target", () => {
+ const origin = createDragOrigin(
+ [item("a", 0), item("b", 1), item("c", 2)],
+ item("c", 2)
+ );
+
+ const placement = getItemPlacement(
+ origin!,
+ [item("a", 0), item("b", 1), item("c", 2)],
+ "a",
+ "a"
+ );
+
+ expect(placement).toMatchObject({
+ priority: -1,
+ slot: { previousItemId: null, nextItemId: "a" }
+ });
+ });
+
+ it("calculates a cross-column insertion before the target", () => {
+ const origin = createDragOrigin([item("a", 0)], item("a", 0));
+ const destination = [item("b", 10, "b"), item("c", 20, "b")];
+
+ const placement = getItemPlacement(
+ origin!,
+ [item("a", 0), ...destination],
+ "b",
+ "c"
+ );
+
+ expect(placement).toMatchObject({
+ columnId: "b",
+ priority: 15,
+ slot: { previousItemId: "b", nextItemId: "c" }
+ });
+ });
+
+ it("allows zero and negative priorities at the top", () => {
+ const zeroOrigin = createDragOrigin([item("a", 0)], item("a", 0));
+ const zeroPlacement = getItemPlacement(
+ zeroOrigin!,
+ [item("a", 0), item("b", 0, "b")],
+ "b",
+ "b"
+ );
+ expect(zeroPlacement?.priority).toBe(-1);
+
+ const negativeOrigin = createDragOrigin([item("a", -10)], item("a", -10));
+ const negativePlacement = getItemPlacement(
+ negativeOrigin!,
+ [item("a", -10), item("b", -2, "b")],
+ "b",
+ "b"
+ );
+ expect(negativePlacement?.priority).toBe(-3);
+ });
+
+ it("uses the midpoint in the middle and previous+1 at the bottom", () => {
+ const crossColumnOrigin = createDragOrigin([item("a", 0)], item("a", 0));
+ const destinationItems = [
+ item("a", 0),
+ item("b", 0, "b"),
+ item("c", 2, "b")
+ ];
+
+ expect(
+ getItemPlacement(crossColumnOrigin!, destinationItems, "b", "c")?.priority
+ ).toBe(1);
+
+ const sameColumnOrigin = createDragOrigin(
+ [item("a", 0), item("b", 1), item("c", 2)],
+ item("b", 1)
+ );
+ expect(
+ getItemPlacement(
+ sameColumnOrigin!,
+ [item("a", 0), item("b", 1), item("c", 2)],
+ "a",
+ "c"
+ )?.priority
+ ).toBe(3);
+ });
+
+ it("accepts an empty column and uses the finite drag-start priority", () => {
+ const origin = createDragOrigin([item("a", 7)], item("a", 7));
+
+ expect(getColumnPlacement(origin!, [item("a", 7)], "empty")).toMatchObject({
+ columnId: "empty",
+ priority: 7,
+ slot: { index: 0 }
+ });
+ });
+
+ it("rejects a populated column with an exact priority collision", () => {
+ const origin = createDragOrigin([item("a", 7)], item("a", 7));
+
+ expect(
+ getColumnPlacement(
+ origin!,
+ [item("a", 7), item("b", 0, "b"), item("c", 7, "b")],
+ "b"
+ )
+ ).toBeNull();
+ });
+
+ it("does not reuse an earlier card-hover priority for a column fallback", () => {
+ const origin = createDragOrigin([item("a", 7)], item("a", 7));
+ const items = [item("a", 7), item("b", 0, "b"), item("c", 10, "b")];
+ const cardPlacement = getItemPlacement(origin!, items, "b", "c");
+
+ expect(cardPlacement?.priority).toBe(5);
+ expect(getColumnPlacement(origin!, items, "b")?.priority).toBe(7);
+ });
+
+ it("calculates overflow-safe midpoints across large and mixed signs", () => {
+ expect(
+ calculateFractionalPriority(Number.MAX_VALUE / 2, Number.MAX_VALUE)
+ ).toBe(1.3482698511467367e308);
+ expect(
+ calculateFractionalPriority(-Number.MAX_VALUE, -Number.MAX_VALUE / 2)
+ ).toBe(-1.3482698511467367e308);
+ expect(
+ calculateFractionalPriority(-Number.MAX_VALUE, Number.MAX_VALUE)
+ ).toBe(0);
+ });
+
+ it("rejects non-finite inputs and adjacent values without a midpoint", () => {
+ expect(calculateFractionalPriority(Number.NaN, 1)).toBeNull();
+ expect(calculateFractionalPriority(1, Number.POSITIVE_INFINITY)).toBeNull();
+ expect(calculateFractionalPriority(1, 1 + Number.EPSILON)).toBeNull();
+ });
+
+ it("treats the original logical slot as a no-op", () => {
+ const origin = createDragOrigin(
+ [item("a", 0), item("b", 1), item("c", 2)],
+ item("b", 1)
+ );
+
+ expect(
+ isSamePlacement(origin!.placement, {
+ columnId: "a",
+ priority: 1,
+ slot: { index: 1, previousItemId: "a", nextItemId: "c" }
+ })
+ ).toBe(true);
+ });
+
+ it("resolves before and after insertion markers", () => {
+ expect(
+ resolveInsertionMarker({
+ index: 0,
+ previousItemId: null,
+ nextItemId: "a"
+ })
+ ).toEqual({ itemId: "a", position: "before" });
+ expect(
+ resolveInsertionMarker({
+ index: 2,
+ previousItemId: "b",
+ nextItemId: null
+ })
+ ).toEqual({ itemId: "b", position: "after" });
+ });
+});
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/placement.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/placement.ts
new file mode 100644
index 0000000000..7c531d6eae
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/placement.ts
@@ -0,0 +1,255 @@
+export type PrioritizedItem = {
+ id: string;
+ columnId: string;
+ priority: number;
+};
+
+export type LogicalSlot = {
+ index: number;
+ previousItemId: string | null;
+ nextItemId: string | null;
+};
+
+export type DragPlacement = {
+ columnId: string;
+ priority: number;
+ slot: LogicalSlot;
+};
+
+export type DragOrigin<T extends PrioritizedItem> = {
+ item: T;
+ placement: DragPlacement;
+};
+
+export type DragPreview = DragPlacement & {
+ targetType: "item" | "column";
+};
+
+export type InsertionMarker = {
+ itemId: string;
+ position: "before" | "after";
+};
+
+export function comparePriorityThenId<T extends PrioritizedItem>(
+ a: T,
+ b: T
+): number {
+ const aPriority = Number.isFinite(a.priority)
+ ? a.priority
+ : Number.POSITIVE_INFINITY;
+ const bPriority = Number.isFinite(b.priority)
+ ? b.priority
+ : Number.POSITIVE_INFINITY;
+
+ if (aPriority !== bPriority) return aPriority - bPriority;
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
+}
+
+export function getItemsInColumn<T extends PrioritizedItem>(
+ items: readonly T[],
+ columnId: string,
+ activeItemId?: string
+): T[] {
+ return items
+ .filter(
+ (item) =>
+ item.columnId === columnId &&
+ (activeItemId === undefined || item.id !== activeItemId)
+ )
+ .sort(comparePriorityThenId);
+}
+
+export function getLogicalSlot<T extends PrioritizedItem>(
+ items: readonly T[],
+ requestedIndex: number
+): LogicalSlot {
+ const index = Math.max(0, Math.min(requestedIndex, items.length));
+ return {
+ index,
+ previousItemId: items[index - 1]?.id ?? null,
+ nextItemId: items[index]?.id ?? null
+ };
+}
+
+export function createDragOrigin<T extends PrioritizedItem>(
+ items: readonly T[],
+ activeItem: T
+): DragOrigin<T> | null {
+ if (!Number.isFinite(activeItem.priority)) return null;
+
+ const sourceItems = getItemsInColumn(items, activeItem.columnId);
+ const activeIndex = sourceItems.findIndex(
+ (item) => item.id === activeItem.id
+ );
+ if (activeIndex < 0) return null;
+
+ const sourceItemsWithoutActive = getItemsInColumn(
+ items,
+ activeItem.columnId,
+ activeItem.id
+ );
+
+ return {
+ item: { ...activeItem },
+ placement: {
+ columnId: activeItem.columnId,
+ priority: activeItem.priority,
+ slot: getLogicalSlot(sourceItemsWithoutActive, activeIndex)
+ }
+ };
+}
+
+export function getInsertionIndex<T extends PrioritizedItem>(
+ destinationItems: readonly T[],
+ targetItemId: string,
+ sameColumn: boolean,
+ originSlotIndex: number
+): number | null {
+ const targetIndex = destinationItems.findIndex(
+ (item) => item.id === targetItemId
+ );
+ if (targetIndex < 0) return null;
+
+ return sameColumn && targetIndex >= originSlotIndex
+ ? targetIndex + 1
+ : targetIndex;
+}
+
+export function calculateFractionalPriority(
+ previousPriority: number | undefined,
+ nextPriority: number | undefined
+): number | null {
+ if (previousPriority !== undefined && !Number.isFinite(previousPriority)) {
+ return null;
+ }
+ if (nextPriority !== undefined && !Number.isFinite(nextPriority)) {
+ return null;
+ }
+
+ let candidate: number;
+ if (previousPriority === undefined && nextPriority !== undefined) {
+ candidate = nextPriority - 1;
+ } else if (previousPriority !== undefined && nextPriority === undefined) {
+ candidate = previousPriority + 1;
+ } else if (previousPriority !== undefined && nextPriority !== undefined) {
+ candidate = previousPriority / 2 + nextPriority / 2;
+ } else {
+ return null;
+ }
+
+ if (!Number.isFinite(candidate)) return null;
+ if (previousPriority !== undefined && !(candidate > previousPriority)) {
+ return null;
+ }
+ if (nextPriority !== undefined && !(candidate < nextPriority)) {
+ return null;
+ }
+
+ return candidate;
+}
+
+export function getItemPlacement<T extends PrioritizedItem>(
+ origin: DragOrigin<T>,
+ items: readonly T[],
+ destinationColumnId: string,
+ targetItemId: string
+): DragPlacement | null {
+ const destinationItems = getItemsInColumn(
+ items,
+ destinationColumnId,
+ origin.item.id
+ );
+ const sameColumn = origin.placement.columnId === destinationColumnId;
+ const insertionIndex = getInsertionIndex(
+ destinationItems,
+ targetItemId,
+ sameColumn,
+ origin.placement.slot.index
+ );
+ if (insertionIndex === null) return null;
+
+ const priority = calculateFractionalPriority(
+ destinationItems[insertionIndex - 1]?.priority,
+ destinationItems[insertionIndex]?.priority
+ );
+ if (priority === null) return null;
+
+ return {
+ columnId: destinationColumnId,
+ priority,
+ slot: getLogicalSlot(destinationItems, insertionIndex)
+ };
+}
+
+export function getColumnPlacement<T extends PrioritizedItem>(
+ origin: DragOrigin<T>,
+ items: readonly T[],
+ destinationColumnId: string
+): DragPlacement | null {
+ if (origin.placement.columnId === destinationColumnId) return null;
+ if (!Number.isFinite(origin.placement.priority)) return null;
+
+ const destinationItems = getItemsInColumn(
+ items,
+ destinationColumnId,
+ origin.item.id
+ );
+
+ // A background drop has no exact card slot. Use the origin priority only if
+ // it will not create another visible duplicate in the selected position.
+ if (
+ destinationItems.some((item) => item.priority === origin.placement.priority)
+ ) {
+ return null;
+ }
+
+ const insertionIndex = destinationItems.findIndex(
+ (item) => item.priority > origin.placement.priority
+ );
+ const resolvedIndex =
+ insertionIndex < 0 ? destinationItems.length : insertionIndex;
+
+ return {
+ columnId: destinationColumnId,
+ priority: origin.placement.priority,
+ slot: getLogicalSlot(destinationItems, resolvedIndex)
+ };
+}
+
+export function isSamePlacement(
+ origin: DragPlacement,
+ placement: DragPlacement
+): boolean {
+ return (
+ origin.columnId === placement.columnId &&
+ origin.slot.previousItemId === placement.slot.previousItemId &&
+ origin.slot.nextItemId === placement.slot.nextItemId
+ );
+}
+
+export function isSamePreview(
+ previous: DragPreview | null,
+ next: DragPreview | null
+): boolean {
+ if (previous === next) return true;
+ if (!previous || !next) return false;
+
+ return (
+ previous.targetType === next.targetType &&
+ previous.columnId === next.columnId &&
+ previous.priority === next.priority &&
+ isSamePlacement(previous, next)
+ );
+}
+
+export function resolveInsertionMarker(
+ slot: LogicalSlot
+): InsertionMarker | null {
+ if (slot.nextItemId) {
+ return { itemId: slot.nextItemId, position: "before" };
+ }
+ if (slot.previousItemId) {
+ return { itemId: slot.previousItemId, position: "after" };
+ }
+ return null;
+}
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 4016992150..fbc534e896 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
@@ -53,7 +53,7 @@ const baseItemValidator = z.object({
customerId: z.string().optional(),
deadlineType: z.enum(deadlineTypes).optional(),
description: z.string().optional(),
- dueDate: z.string().optional(), // 2024-05-28
+ dueDate: z.string().nullable().optional(), // 2024-05-28
employeeIds: z.array(z.string()).optional(),
itemDescription: z.string().optional(),
itemReadableId: z.string(),
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/utils.test.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/utils.test.ts
new file mode 100644
index 0000000000..e7f9e741cd
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/utils.test.ts
@@ -0,0 +1,162 @@
+import type {
+ Active,
+ ClientRect,
+ Collision,
+ CollisionDetection,
+ DroppableContainer
+} from "@dnd-kit/core";
+import { describe, expect, it } from "vitest";
+import { hasDraggableData, kanbanCollisionDetection } from "./utils";
+
+type Target = {
+ id: string;
+ type: "item" | "column";
+ rect: ClientRect;
+};
+
+const rect = (
+ left: number,
+ top: number,
+ width: number,
+ height: number
+): ClientRect => ({
+ left,
+ top,
+ width,
+ height,
+ right: left + width,
+ bottom: top + height
+});
+
+function targetContainer(target: Target): DroppableContainer {
+ return {
+ id: target.id,
+ key: target.id,
+ disabled: false,
+ data: { current: { type: target.type } },
+ node: { current: null },
+ rect: { current: target.rect }
+ };
+}
+
+function detect(
+ activeType: "item" | "column",
+ collisionRect: ClientRect,
+ targets: readonly Target[]
+): Collision[] {
+ const active = {
+ id: "active",
+ data: { current: { type: activeType } },
+ rect: {
+ current: { initial: collisionRect, translated: collisionRect }
+ }
+ } as Active;
+ const droppableContainers = targets.map(targetContainer);
+ const droppableRects = new Map(
+ targets.map((target) => [target.id, target.rect])
+ );
+
+ return (kanbanCollisionDetection as CollisionDetection)({
+ active,
+ collisionRect,
+ droppableRects,
+ droppableContainers,
+ pointerCoordinates: null
+ });
+}
+
+describe("Kanban drag utilities", () => {
+ it("accepts the actual lowercase drag metadata", () => {
+ expect(
+ hasDraggableData({
+ id: "item-1",
+ data: { current: { type: "item", item: {} } }
+ } as any)
+ ).toBe(true);
+ expect(
+ hasDraggableData({
+ id: "column-1",
+ data: { current: { type: "column", column: {} } }
+ } as any)
+ ).toBe(true);
+ expect(
+ hasDraggableData({
+ id: "column-1",
+ data: { current: { type: "Column", column: {} } }
+ } as any)
+ ).toBe(false);
+ });
+
+ it("prefers an intersecting card over its parent column", () => {
+ const collisions = detect("item", rect(50, 50, 40, 40), [
+ { id: "column-a", type: "column", rect: rect(0, 0, 200, 200) },
+ { id: "item-a", type: "item", rect: rect(40, 40, 60, 60) }
+ ]);
+
+ expect(collisions.map(({ id }) => id)).toEqual(["item-a"]);
+ });
+
+ it("falls back to an intersecting empty column", () => {
+ const collisions = detect("item", rect(250, 50, 40, 40), [
+ { id: "column-empty", type: "column", rect: rect(200, 0, 200, 200) }
+ ]);
+
+ expect(collisions.map(({ id }) => id)).toEqual(["column-empty"]);
+ });
+
+ it("uses a populated column for an intersecting background drop", () => {
+ const collisions = detect("item", rect(10, 10, 20, 20), [
+ { id: "column-a", type: "column", rect: rect(0, 0, 200, 200) },
+ { id: "item-a", type: "item", rect: rect(100, 100, 50, 50) }
+ ]);
+
+ expect(collisions.map(({ id }) => id)).toEqual(["column-a"]);
+ });
+
+ it("returns no collision outside all targets", () => {
+ expect(
+ detect("item", rect(500, 500, 40, 40), [
+ { id: "column-a", type: "column", rect: rect(0, 0, 200, 200) },
+ { id: "item-a", type: "item", rect: rect(40, 40, 60, 60) }
+ ])
+ ).toEqual([]);
+ });
+
+ it("excludes the active card from item collisions", () => {
+ const collisions = detect("item", rect(50, 50, 40, 40), [
+ { id: "active", type: "item", rect: rect(40, 40, 60, 60) },
+ { id: "sibling", type: "item", rect: rect(300, 40, 60, 60) }
+ ]);
+
+ expect(collisions).toEqual([]);
+ });
+
+ it("does not choose a nearby sibling for a no-motion drag", () => {
+ const collisions = detect("item", rect(50, 50, 40, 40), [
+ { id: "active", type: "item", rect: rect(50, 50, 40, 40) },
+ { id: "sibling", type: "item", rect: rect(95, 50, 40, 40) },
+ { id: "column-a", type: "column", rect: rect(0, 0, 200, 200) }
+ ]);
+
+ expect(collisions.map(({ id }) => id)).toEqual(["column-a"]);
+ });
+
+ it("does not choose the nearest column for an outside column drag", () => {
+ expect(
+ detect("column", rect(500, 500, 40, 40), [
+ { id: "column-a", type: "column", rect: rect(0, 0, 200, 200) },
+ { id: "column-b", type: "column", rect: rect(250, 0, 200, 200) }
+ ])
+ ).toEqual([]);
+ });
+
+ it("keeps column dragging over a real column working", () => {
+ const collisions = detect("column", rect(250, 50, 40, 40), [
+ { id: "column-a", type: "column", rect: rect(0, 0, 200, 200) },
+ { id: "column-b", type: "column", rect: rect(200, 0, 200, 200) },
+ { id: "item-b", type: "item", rect: rect(220, 40, 80, 80) }
+ ]);
+
+ expect(collisions.map(({ id }) => id)).toEqual(["column-b"]);
+ });
+});
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/utils.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/utils.ts
index 060e23a532..8e8bfd549a 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/utils.ts
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/utils.ts
@@ -1,11 +1,17 @@
import type {
Active,
+ CollisionDetection,
DataRef,
DroppableContainer,
KeyboardCoordinateGetter,
Over
} from "@dnd-kit/core";
-import { closestCorners, getFirstCollision, KeyboardCode } from "@dnd-kit/core";
+import {
+ closestCorners,
+ getFirstCollision,
+ KeyboardCode,
+ rectIntersection
+} from "@dnd-kit/core";
import type { DraggableData } from "./types";
const directions: string[] = [
@@ -15,6 +21,50 @@ const directions: string[] = [
KeyboardCode.Left
];
+function containersOfType(
+ containers: readonly DroppableContainer[],
+ type: "item" | "column"
+) {
+ return containers.filter(
+ (container) => container.data.current?.type === type
+ );
+}
+
+/**
+ * Use actual rectangle intersections for pointer/touch drops. Cards are
+ * checked first so a card nested inside a column wins; columns are only a
+ * fallback for empty-column and background drops. Keyboard movement keeps its
+ * directional nearest-target coordinate getter below.
+ */
+export const kanbanCollisionDetection: CollisionDetection = (args) => {
+ const droppableContainers = args.droppableContainers.filter(
+ (container) => !container.disabled && container.id !== args.active.id
+ );
+ const activeType = args.active.data.current?.type;
+
+ if (activeType === "item") {
+ const itemCollisions = rectIntersection({
+ ...args,
+ droppableContainers: containersOfType(droppableContainers, "item")
+ });
+ if (itemCollisions.length > 0) return itemCollisions;
+
+ return rectIntersection({
+ ...args,
+ droppableContainers: containersOfType(droppableContainers, "column")
+ });
+ }
+
+ if (activeType === "column") {
+ return rectIntersection({
+ ...args,
+ droppableContainers: containersOfType(droppableContainers, "column")
+ });
+ }
+
+ return rectIntersection({ ...args, droppableContainers });
+};
+
export const coordinateGetter: KeyboardCoordinateGetter = (
event,
{ context: { active, droppableRects, droppableContainers, collisionRect } }
@@ -44,8 +94,8 @@ export const coordinateGetter: KeyboardCoordinateGetter = (
if (data) {
const { type, children } = data;
- if (type === "Column" && children?.length > 0) {
- if (active.data.current?.type !== "Column") {
+ if (type === "column" && children?.length > 0) {
+ if (active.data.current?.type !== "column") {
return;
}
}
@@ -53,7 +103,7 @@ export const coordinateGetter: KeyboardCoordinateGetter = (
switch (event.code) {
case KeyboardCode.Down:
- if (active.data.current?.type === "Column") {
+ if (active.data.current?.type === "column") {
return;
}
if (collisionRect.top < rect.top) {
@@ -62,7 +112,7 @@ export const coordinateGetter: KeyboardCoordinateGetter = (
}
break;
case KeyboardCode.Up:
- if (active.data.current?.type === "Column") {
+ if (active.data.current?.type === "column") {
return;
}
if (collisionRect.top > rect.top) {
diff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsx
index 4025faa269..c48ca31e4d 100644
--- a/apps/erp/app/routes/x+/schedule+/dates.tsx
+++ b/apps/erp/app/routes/x+/schedule+/dates.tsx
@@ -49,9 +49,11 @@ import { ActiveFilters, Filter } from "~/components/Table/components/Filter";
import type { ColumnFilter } from "~/components/Table/components/Filter/types";
import { useUrlParams } from "~/hooks";
import { getJobsByDateRange, getUnscheduledJobs } from "~/modules/production";
+import { isDateColumnSentinel } from "~/modules/production/production.models";
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 { comparePriorityThenId } from "~/modules/production/ui/Schedule/Kanban/placement";
import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";
import { getTagsList } from "~/modules/shared";
import { resolveLocationId } from "~/modules/shared/location.server";
@@ -513,7 +515,7 @@ function DateKanbanSchedule() {
const columns = useMemo(() => {
return loaderColumns.map((col) => {
// Skip non-date columns
- if (["unscheduled", "next-week", "next-month"].includes(col.id)) {
+ if (isDateColumnSentinel(col.id)) {
if (col.id === "next-month") {
// Reformat the month name with locale
const monthStart = startOfMonth(parseDate(currentDate));
@@ -575,7 +577,7 @@ function DateKanbanSchedule() {
}, [initialItems]);
const sortItems = useCallback((items: JobItem[]) => {
- return [...items].sort((a, b) => a.priority - b.priority);
+ return [...items].sort(comparePriorityThenId);
}, []);
useEffect(() => {
@@ -862,6 +864,7 @@ function DateKanbanSchedule() {
<DateKanban
columns={columns}
items={items}
+ locationId={locationId}
progressByItemId={{}}
tags={tags}
showCustomer={displaySettings.showCustomer}
diff --git a/apps/erp/app/routes/x+/schedule+/dates.update.test.ts b/apps/erp/app/routes/x+/schedule+/dates.update.test.ts
new file mode 100644
index 0000000000..29fcdd127d
--- /dev/null
+++ b/apps/erp/app/routes/x+/schedule+/dates.update.test.ts
@@ -0,0 +1,281 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+
+import { triggerJobSchedule } from "~/modules/production/production.service";
+import { action } from "./dates.update";
+
+vi.mock("@carbon/auth/auth.server", () => ({
+ requirePermissions: vi.fn()
+}));
+vi.mock("@carbon/logger", () => ({
+ getLogger: () => ({ error: vi.fn(), info: vi.fn(), warn: vi.fn() })
+}));
+vi.mock("~/modules/production/production.service", () => ({
+ triggerJobSchedule: vi.fn()
+}));
+
+type QueryResult = {
+ data: { id: string } | null;
+ error: { message: string } | null;
+};
+
+function createActionMocks() {
+ const events: string[] = [];
+ const result: QueryResult = {
+ data: { id: "job-1" },
+ error: null
+ };
+ const query = {
+ update: vi.fn((_payload: unknown) => {
+ events.push("update");
+ return query;
+ }),
+ eq: vi.fn((column: string, value: unknown) => {
+ events.push(`eq:${column}:${String(value)}`);
+ return query;
+ }),
+ not: vi.fn((column: string, operator: string, value: unknown) => {
+ events.push(`not:${column}:${operator}:${String(value)}`);
+ return query;
+ }),
+ select: vi.fn((columns: string) => {
+ events.push(`select:${columns}`);
+ return query;
+ }),
+ maybeSingle: vi.fn(async () => {
+ events.push("maybeSingle");
+ return result;
+ })
+ };
+ const client = {
+ from: vi.fn((table: string) => {
+ events.push(`from:${table}`);
+ return query;
+ })
+ };
+
+ return { client, events, query, result };
+}
+
+type ActionMocks = ReturnType<typeof createActionMocks>;
+let mocks: ActionMocks;
+
+function updateRequest(fields: Record<string, string>) {
+ const body = new FormData();
+ for (const [key, value] of Object.entries(fields)) body.set(key, value);
+ return new Request("http://localhost/x/schedule/dates/update", {
+ method: "POST",
+ body
+ });
+}
+
+async function runAction(fields: Record<string, string>) {
+ return action({
+ request: updateRequest(fields),
+ params: {},
+ context: {}
+ } as any);
+}
+
+const baseFields = {
+ id: "job-1",
+ locationId: "location-1",
+ columnId: "2026-08-09",
+ priority: "-2.5"
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks = createActionMocks();
+ vi.mocked(requirePermissions).mockResolvedValue({
+ client: mocks.client,
+ companyId: "company-1",
+ userId: "user-1"
+ } as any);
+ vi.mocked(triggerJobSchedule).mockImplementation(async () => {
+ mocks.events.push("scheduler");
+ return { success: true };
+ });
+});
+
+describe("Dates schedule update action", () => {
+ it("completes the scoped update before scheduling", async () => {
+ const result = await runAction(baseFields);
+
+ expect(mocks.client.from).toHaveBeenCalledWith("job");
+ expect(mocks.query.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ dueDate: "2026-08-09",
+ priority: -2.5,
+ updatedBy: "user-1"
+ })
+ );
+ expect(mocks.events).toEqual([
+ "from:job",
+ "update",
+ "eq:id:job-1",
+ "eq:companyId:company-1",
+ "eq:locationId:location-1",
+ "not:status:in:(Completed,Closed,Cancelled)",
+ "select:id",
+ "maybeSingle",
+ "scheduler"
+ ]);
+ expect(result).toEqual({ success: true });
+ });
+
+ it.each([
+ "unscheduled",
+ "next-week",
+ "next-month"
+ ])("persists %s as a null due date", async (columnId) => {
+ await runAction({ ...baseFields, columnId });
+ expect(mocks.query.update).toHaveBeenCalledWith(
+ expect.objectContaining({ dueDate: null })
+ );
+ expect(mocks.events.at(-1)).toBe("scheduler");
+ });
+
+ it.each([
+ ["missing", undefined],
+ ["blank", " "]
+ ])("rejects a %s location before writing or scheduling", async (_name, locationId) => {
+ const fields = { ...baseFields } as Record<string, string>;
+ if (locationId === undefined) {
+ delete fields.locationId;
+ } else {
+ fields.locationId = locationId;
+ }
+
+ const result = await runAction(fields);
+
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expect(mocks.query.update).not.toHaveBeenCalled();
+ expect(triggerJobSchedule).not.toHaveBeenCalled();
+ });
+
+ it("rejects an invalid date column without writing or scheduling", async () => {
+ const result = await runAction({ ...baseFields, columnId: "2026-02-29" });
+
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expect(mocks.query.update).not.toHaveBeenCalled();
+ expect(triggerJobSchedule).not.toHaveBeenCalled();
+ });
+
+ it("accepts finite negative priorities", async () => {
+ const result = await runAction({ ...baseFields, priority: "-100" });
+
+ expect(result).toEqual({ success: true });
+ expect(mocks.query.update).toHaveBeenCalledWith(
+ expect.objectContaining({ priority: -100 })
+ );
+ });
+
+ it("accepts surrounding whitespace around a finite number", async () => {
+ const result = await runAction({ ...baseFields, priority: " 4.25 " });
+
+ expect(result).toEqual({ success: true });
+ expect(mocks.query.update).toHaveBeenCalledWith(
+ expect.objectContaining({ priority: 4.25 })
+ );
+ });
+
+ it.each([
+ " ",
+ "\t",
+ "\n"
+ ])("rejects whitespace-only priority %j before any database update", async (priority) => {
+ const result = await runAction({ ...baseFields, priority });
+
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expect(mocks.query.update).not.toHaveBeenCalled();
+ expect(triggerJobSchedule).not.toHaveBeenCalled();
+ });
+
+ it("rejects missing priority before any database update", async () => {
+ const { priority: _priority, ...fields } = baseFields;
+ const result = await runAction(fields);
+
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expect(mocks.query.update).not.toHaveBeenCalled();
+ });
+
+ it("rejects an empty priority before any database update", async () => {
+ const result = await runAction({ ...baseFields, priority: "" });
+
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expect(mocks.query.update).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ "Infinity",
+ "-Infinity",
+ "NaN"
+ ])("rejects non-finite priority %s", async (priority) => {
+ const result = await runAction({ ...baseFields, priority });
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expect(mocks.query.update).not.toHaveBeenCalled();
+ expect(triggerJobSchedule).not.toHaveBeenCalled();
+ });
+
+ it("treats a location mismatch as a failed zero-row update", async () => {
+ mocks.result.data = null;
+ const result = await runAction({
+ ...baseFields,
+ locationId: "location-2"
+ });
+
+ expect(result).toEqual({
+ success: false,
+ message: "Job unavailable or locked"
+ });
+ expect(mocks.events).toEqual([
+ "from:job",
+ "update",
+ "eq:id:job-1",
+ "eq:companyId:company-1",
+ "eq:locationId:location-2",
+ "not:status:in:(Completed,Closed,Cancelled)",
+ "select:id",
+ "maybeSingle"
+ ]);
+ expect(triggerJobSchedule).not.toHaveBeenCalled();
+ });
+
+ it("does not schedule after a database error", async () => {
+ mocks.result.data = null;
+ mocks.result.error = { message: "database failure" };
+
+ const result = await runAction(baseFields);
+
+ expect(result).toEqual({ success: false, message: "database failure" });
+ expect(mocks.events).toContain("maybeSingle");
+ expect(mocks.events).not.toContain("scheduler");
+ expect(triggerJobSchedule).not.toHaveBeenCalled();
+ });
+
+ it("keeps scheduler failures best-effort after one successful update", async () => {
+ vi.mocked(triggerJobSchedule).mockRejectedValueOnce(
+ new Error("Inngest down")
+ );
+
+ await expect(runAction(baseFields)).resolves.toEqual({ success: true });
+ expect(mocks.events).not.toContain("scheduler");
+ expect(triggerJobSchedule).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/erp/app/routes/x+/schedule+/dates.update.tsx b/apps/erp/app/routes/x+/schedule+/dates.update.tsx
index 4ea37db4fd..e5d51608ca 100644
--- a/apps/erp/app/routes/x+/schedule+/dates.update.tsx
+++ b/apps/erp/app/routes/x+/schedule+/dates.update.tsx
@@ -2,7 +2,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
-import { scheduleJobUpdateValidator } from "~/modules/production/production.models";
+import {
+ getDueDateForColumn,
+ JOB_LOCKED_STATUSES,
+ scheduleJobUpdateValidator
+} from "~/modules/production/production.models";
import { triggerJobSchedule } from "~/modules/production/production.service";
const logger = getLogger("erp", "dates-update");
@@ -23,19 +27,9 @@ export async function action({ request }: ActionFunctionArgs) {
};
}
- // 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", "next-month", or "unscheduled"
- // we'll set dueDate to null
- let dueDate: string | null = null;
-
- if (
- validation.data.columnId !== "unscheduled" &&
- 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 dueDate = getDueDateForColumn(validation.data.columnId);
+ if (dueDate === undefined) {
+ return { success: false, message: "Invalid form data" };
}
const updateData = {
@@ -45,15 +39,24 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString()
};
- const { error } = await client
+ const { data, error } = await client
.from("job")
.update(updateData)
- .eq("id", validation.data.id);
+ .eq("id", validation.data.id)
+ .eq("companyId", companyId)
+ .eq("locationId", validation.data.locationId)
+ .not("status", "in", `(${JOB_LOCKED_STATUSES.join(",")})`)
+ .select("id")
+ .maybeSingle();
if (error) {
return { success: false, message: error.message };
}
+ if (data === null) {
+ return { success: false, message: "Job unavailable or locked" };
+ }
+
// Trigger background job rescheduling
try {
await triggerJobSchedule(validation.data.id, companyId, userId);
diff --git a/apps/erp/app/routes/x+/schedule+/operations.tsx b/apps/erp/app/routes/x+/schedule+/operations.tsx
index ca05b44f27..f4918d4887 100644
--- a/apps/erp/app/routes/x+/schedule+/operations.tsx
+++ b/apps/erp/app/routes/x+/schedule+/operations.tsx
@@ -54,6 +54,7 @@ import type {
Progress
} from "~/modules/production/ui/Schedule/Kanban";
import { Kanban } from "~/modules/production/ui/Schedule/Kanban";
+import { comparePriorityThenId } from "~/modules/production/ui/Schedule/Kanban/placement";
import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";
import {
getProcessesList,
@@ -341,7 +342,7 @@ function KanbanSchedule() {
}, [initialItems]);
const sortItems = useCallback((items: OperationItem[]) => {
- return [...items].sort((a, b) => a.priority - b.priority);
+ return [...items].sort(comparePriorityThenId);
}, []);
useEffect(() => {
diff --git a/apps/erp/app/routes/x+/schedule+/operations.update.test.ts b/apps/erp/app/routes/x+/schedule+/operations.update.test.ts
new file mode 100644
index 0000000000..7fd5136499
--- /dev/null
+++ b/apps/erp/app/routes/x+/schedule+/operations.update.test.ts
@@ -0,0 +1,432 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+
+import {
+ recalculateJobRequirements,
+ triggerJobSchedule
+} from "~/modules/production/production.service";
+import { action } from "./operations.update";
+
+vi.mock("@carbon/auth/auth.server", () => ({
+ requirePermissions: vi.fn()
+}));
+vi.mock("~/modules/production/production.service", () => ({
+ recalculateJobRequirements: vi.fn(),
+ triggerJobSchedule: vi.fn()
+}));
+
+type DatabaseError = { message: string } | null;
+type QueryResult<T> = {
+ data: T | null;
+ error: DatabaseError;
+};
+
+type SourceOperation = {
+ id: string;
+ jobId: string;
+ processId: string;
+ status: string;
+ companyId: string;
+};
+
+type ParentJob = {
+ id: string;
+ companyId: string;
+ locationId: string;
+ status: string;
+};
+
+type DestinationWorkCenter = {
+ id: string;
+ companyId: string;
+ active: boolean;
+ locationId: string | null;
+};
+
+type ProcessCompatibility = {
+ workCenterId: string;
+};
+
+type UpdatedOperation = {
+ id: string;
+};
+
+function createQueryChain<T>(
+ label: string,
+ result: QueryResult<T>,
+ events: string[]
+) {
+ const chain: Record<string, ReturnType<typeof vi.fn>> = {};
+ chain.select = vi.fn((columns: string) => {
+ events.push(`${label}:select:${columns}`);
+ return chain;
+ });
+ chain.update = vi.fn((_payload: unknown) => {
+ events.push(`${label}:update`);
+ return chain;
+ });
+ chain.eq = vi.fn((column: string, value: unknown) => {
+ events.push(`${label}:eq:${column}:${String(value)}`);
+ return chain;
+ });
+ chain.not = vi.fn((column: string, operator: string, value: unknown) => {
+ events.push(`${label}:not:${column}:${operator}:${String(value)}`);
+ return chain;
+ });
+ chain.maybeSingle = vi.fn(async () => {
+ events.push(`${label}:maybeSingle`);
+ return result;
+ });
+ return chain;
+}
+
+function createActionMocks() {
+ const events: string[] = [];
+ const results = {
+ source: {
+ data: {
+ id: "operation-1",
+ jobId: "job-1",
+ processId: "process-1",
+ status: "Ready",
+ companyId: "company-1"
+ },
+ error: null
+ } as QueryResult<SourceOperation>,
+ parent: {
+ data: {
+ id: "job-1",
+ companyId: "company-1",
+ locationId: "location-1",
+ status: "Ready"
+ },
+ error: null
+ } as QueryResult<ParentJob>,
+ destination: {
+ data: {
+ id: "work-center-2",
+ companyId: "company-1",
+ active: true,
+ locationId: "location-1"
+ },
+ error: null
+ } as QueryResult<DestinationWorkCenter>,
+ compatibility: {
+ data: { workCenterId: "work-center-2" },
+ error: null
+ } as QueryResult<ProcessCompatibility>,
+ mutation: {
+ data: { id: "operation-1" },
+ error: null
+ } as QueryResult<UpdatedOperation>
+ };
+
+ const chains = {
+ source: createQueryChain("source", results.source, events),
+ parent: createQueryChain("parent", results.parent, events),
+ destination: createQueryChain("destination", results.destination, events),
+ compatibility: createQueryChain(
+ "compatibility",
+ results.compatibility,
+ events
+ ),
+ mutation: createQueryChain("mutation", results.mutation, events)
+ };
+ const jobOperationChains = [chains.source, chains.mutation];
+ const client = {
+ from: vi.fn((table: string) => {
+ events.push(`from:${table}`);
+ if (table === "jobOperation") {
+ const chain = jobOperationChains.shift();
+ if (!chain) throw new Error("Unexpected jobOperation query");
+ return chain;
+ }
+ if (table === "job") return chains.parent;
+ if (table === "workCenter") return chains.destination;
+ if (table === "workCenterProcess") return chains.compatibility;
+ throw new Error(`Unexpected table: ${table}`);
+ })
+ };
+
+ return { chains, client, events, results };
+}
+
+type ActionMocks = ReturnType<typeof createActionMocks>;
+let mocks: ActionMocks;
+
+function updateRequest(fields: Record<string, string>) {
+ const body = new FormData();
+ for (const [key, value] of Object.entries(fields)) body.set(key, value);
+ return new Request("http://localhost/x/schedule/operations/update", {
+ method: "POST",
+ body
+ });
+}
+
+async function runAction(fields: Record<string, string>) {
+ return action({
+ request: updateRequest(fields),
+ params: {},
+ context: {}
+ } as any);
+}
+
+const baseFields = {
+ id: "operation-1",
+ columnId: "work-center-2",
+ priority: "-3.5"
+};
+
+function expectNoMutation() {
+ expect(mocks.chains.mutation.update).not.toHaveBeenCalled();
+ expect(mocks.events).not.toContain("mutation:update");
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks = createActionMocks();
+ vi.mocked(requirePermissions).mockResolvedValue({
+ client: mocks.client,
+ companyId: "company-1",
+ userId: "user-1"
+ } as any);
+});
+
+afterEach(() => {
+ expect(triggerJobSchedule).not.toHaveBeenCalled();
+ expect(recalculateJobRequirements).not.toHaveBeenCalled();
+});
+
+describe("Operations schedule update action", () => {
+ it("validates source, job, destination and process before exactly one update", async () => {
+ const result = await runAction(baseFields);
+
+ expect(mocks.events).toEqual([
+ "from:jobOperation",
+ "source:select:id, jobId, processId, status, companyId",
+ "source:eq:id:operation-1",
+ "source:eq:companyId:company-1",
+ "source:maybeSingle",
+ "from:job",
+ "parent:select:id, companyId, locationId, status",
+ "parent:eq:id:job-1",
+ "parent:eq:companyId:company-1",
+ "parent:maybeSingle",
+ "from:workCenter",
+ "destination:select:id, companyId, active, locationId",
+ "destination:eq:id:work-center-2",
+ "destination:eq:companyId:company-1",
+ "destination:maybeSingle",
+ "from:workCenterProcess",
+ "compatibility:select:workCenterId",
+ "compatibility:eq:workCenterId:work-center-2",
+ "compatibility:eq:processId:process-1",
+ "compatibility:eq:companyId:company-1",
+ "compatibility:maybeSingle",
+ "from:jobOperation",
+ "mutation:update",
+ "mutation:eq:id:operation-1",
+ "mutation:eq:companyId:company-1",
+ "mutation:eq:jobId:job-1",
+ "mutation:eq:processId:process-1",
+ "mutation:not:status:in:(Done,Canceled)",
+ "mutation:select:id",
+ "mutation:maybeSingle"
+ ]);
+ expect(mocks.chains.mutation.update).toHaveBeenCalledOnce();
+ expect(mocks.chains.mutation.update).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workCenterId: "work-center-2",
+ priority: -3.5,
+ updatedBy: "user-1",
+ updatedAt: expect.any(String)
+ })
+ );
+ expect(triggerJobSchedule).not.toHaveBeenCalled();
+ expect(recalculateJobRequirements).not.toHaveBeenCalled();
+ expect(result).toEqual({ success: true });
+ });
+
+ it("accepts finite negative priorities", async () => {
+ await runAction({ ...baseFields, priority: "-100" });
+ expect(mocks.chains.mutation.update).toHaveBeenCalledWith(
+ expect.objectContaining({ priority: -100 })
+ );
+ });
+
+ it("accepts surrounding whitespace around a finite number", async () => {
+ const result = await runAction({ ...baseFields, priority: " 4.25 " });
+
+ expect(result).toEqual({ success: true });
+ expect(mocks.chains.mutation.update).toHaveBeenCalledWith(
+ expect.objectContaining({ priority: 4.25 })
+ );
+ });
+
+ it.each([
+ " ",
+ "\t",
+ "\n"
+ ])("rejects whitespace-only priority %j before any database call", async (priority) => {
+ const result = await runAction({ ...baseFields, priority });
+
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expectNoMutation();
+ });
+
+ it("rejects missing priority before any database call", async () => {
+ const { priority: _priority, ...fields } = baseFields;
+ const result = await runAction(fields);
+
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expectNoMutation();
+ });
+
+ it.each([
+ "",
+ "Infinity",
+ "-Infinity",
+ "NaN"
+ ])("rejects invalid priority %j before any database call", async (priority) => {
+ const result = await runAction({ ...baseFields, priority });
+
+ expect(result).toEqual({ success: false, message: "Invalid form data" });
+ expect(mocks.client.from).not.toHaveBeenCalled();
+ expectNoMutation();
+ });
+
+ it("performs no update when the source operation is missing", async () => {
+ mocks.results.source.data = null;
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it("performs no update when the parent job is missing", async () => {
+ mocks.results.parent.data = null;
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it.each([
+ "Completed",
+ "Closed",
+ "Cancelled"
+ ])("performs no update for a %s parent job", async (status) => {
+ if (mocks.results.parent.data) mocks.results.parent.data.status = status;
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it.each([
+ "Done",
+ "Canceled"
+ ])("performs no update for a %s operation", async (status) => {
+ if (mocks.results.source.data) mocks.results.source.data.status = status;
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it("performs no update for a foreign-company destination", async () => {
+ if (mocks.results.destination.data) {
+ mocks.results.destination.data.companyId = "company-2";
+ }
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it("performs no update when the destination is missing", async () => {
+ mocks.results.destination.data = null;
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it("performs no update for an inactive destination", async () => {
+ if (mocks.results.destination.data) {
+ mocks.results.destination.data.active = false;
+ }
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it("performs no update for a destination at another location", async () => {
+ if (mocks.results.destination.data) {
+ mocks.results.destination.data.locationId = "location-2";
+ }
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it("performs no update for a process-incompatible destination", async () => {
+ mocks.results.compatibility.data = null;
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Invalid scheduling request"
+ });
+ expectNoMutation();
+ });
+
+ it("returns the update database error", async () => {
+ mocks.results.mutation.data = null;
+ mocks.results.mutation.error = { message: "database failure" };
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "database failure"
+ });
+ expect(mocks.chains.mutation.update).toHaveBeenCalledOnce();
+ });
+
+ it("does not treat a zero-row update as success", async () => {
+ mocks.results.mutation.data = null;
+
+ await expect(runAction(baseFields)).resolves.toEqual({
+ success: false,
+ message: "Operation unavailable"
+ });
+ expect(mocks.chains.mutation.update).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/erp/app/routes/x+/schedule+/operations.update.tsx b/apps/erp/app/routes/x+/schedule+/operations.update.tsx
index afb553a942..2b21f8650c 100644
--- a/apps/erp/app/routes/x+/schedule+/operations.update.tsx
+++ b/apps/erp/app/routes/x+/schedule+/operations.update.tsx
@@ -1,9 +1,18 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
-import { scheduleOperationUpdateValidator } from "~/modules/production/production.models";
+import {
+ isJobLocked,
+ scheduleOperationUpdateValidator
+} from "~/modules/production/production.models";
+
+const invalidSchedulingRequest = () => ({
+ success: false,
+ message: "Invalid scheduling request"
+});
+
export async function action({ request }: ActionFunctionArgs) {
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "production"
});
const validation = await validator(scheduleOperationUpdateValidator).validate(
@@ -17,19 +26,98 @@ export async function action({ request }: ActionFunctionArgs) {
};
}
- const { error } = await client
+ const sourceOperation = await client
+ .from("jobOperation")
+ .select("id, jobId, processId, status, companyId")
+ .eq("id", validation.data.id)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (
+ sourceOperation.error ||
+ sourceOperation.data === null ||
+ sourceOperation.data.id !== validation.data.id ||
+ sourceOperation.data.companyId !== companyId ||
+ sourceOperation.data.status === "Done" ||
+ sourceOperation.data.status === "Canceled"
+ ) {
+ return invalidSchedulingRequest();
+ }
+
+ const parentJob = await client
+ .from("job")
+ .select("id, companyId, locationId, status")
+ .eq("id", sourceOperation.data.jobId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (
+ parentJob.error ||
+ parentJob.data === null ||
+ parentJob.data.id !== sourceOperation.data.jobId ||
+ parentJob.data.companyId !== companyId ||
+ isJobLocked(parentJob.data.status)
+ ) {
+ return invalidSchedulingRequest();
+ }
+
+ const destinationWorkCenter = await client
+ .from("workCenter")
+ .select("id, companyId, active, locationId")
+ .eq("id", validation.data.columnId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (
+ destinationWorkCenter.error ||
+ destinationWorkCenter.data === null ||
+ destinationWorkCenter.data.id !== validation.data.columnId ||
+ destinationWorkCenter.data.companyId !== companyId ||
+ !destinationWorkCenter.data.active ||
+ destinationWorkCenter.data.locationId !== parentJob.data.locationId
+ ) {
+ return invalidSchedulingRequest();
+ }
+
+ const compatibleProcess = await client
+ .from("workCenterProcess")
+ .select("workCenterId")
+ .eq("workCenterId", destinationWorkCenter.data.id)
+ .eq("processId", sourceOperation.data.processId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (
+ compatibleProcess.error ||
+ compatibleProcess.data === null ||
+ compatibleProcess.data.workCenterId !== destinationWorkCenter.data.id
+ ) {
+ return invalidSchedulingRequest();
+ }
+
+ const { data, error } = await client
.from("jobOperation")
.update({
- workCenterId: validation.data.columnId,
+ workCenterId: destinationWorkCenter.data.id,
priority: validation.data.priority,
updatedBy: userId,
updatedAt: new Date().toISOString()
})
- .eq("id", validation.data.id);
+ .eq("id", sourceOperation.data.id)
+ .eq("companyId", companyId)
+ .eq("jobId", sourceOperation.data.jobId)
+ .eq("processId", sourceOperation.data.processId)
+ .not("status", "in", "(Done,Canceled)")
+ .select("id")
+ .maybeSingle();
if (error) {
return { success: false, message: error.message };
}
+ if (data === null) {
+ return { success: false, message: "Operation unavailable" };
+ }
+
return { success: true };
}