Promote dev → uat: GRO-2159 drag-to-reorder + re-optimize (#64)
CI / Test (push) Successful in 35s
CI / Lint & Typecheck (push) Successful in 44s
CI / Build & Push Docker Image (push) Successful in 11s
CI / Test (pull_request) Successful in 21s
CI / Lint & Typecheck (pull_request) Successful in 27s
CI / Build & Push Docker Image (pull_request) Successful in 12s
CI / Test (push) Successful in 35s
CI / Lint & Typecheck (push) Successful in 44s
CI / Build & Push Docker Image (push) Successful in 11s
CI / Test (pull_request) Successful in 21s
CI / Lint & Typecheck (pull_request) Successful in 27s
CI / Build & Push Docker Image (pull_request) Successful in 12s
This commit was merged in pull request #64.
This commit is contained in:
@@ -79,6 +79,9 @@ function mockFetch(meRole: "manager" | "groomer") {
|
||||
if (url === "/api/routes/optimize" && opts?.method === "POST") {
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve(ROUTE_RESPONSE) } as Response);
|
||||
}
|
||||
if (/^\/api\/routes\/[^/]+\/reorder$/.test(url) && opts?.method === "PATCH") {
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve(ROUTE_RESPONSE) } as Response);
|
||||
}
|
||||
return Promise.resolve({ ok: true, json: () => Promise.resolve({}) } as Response);
|
||||
});
|
||||
}
|
||||
@@ -124,6 +127,33 @@ describe("RoutesPage", () => {
|
||||
expect(screen.queryByText("Groomer")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders a drag handle for each stop (drag-to-reorder enabled)", async () => {
|
||||
global.fetch = mockFetch("manager") as unknown as typeof fetch;
|
||||
render(<RoutesPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("Alice")).toBeInTheDocument());
|
||||
expect(screen.getByLabelText("Drag to reorder Alice")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Drag to reorder Bob")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("flags the tight-schedule conflict on the affected stop", async () => {
|
||||
global.fetch = mockFetch("manager") as unknown as typeof fetch;
|
||||
render(<RoutesPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("Bob")).toBeInTheDocument());
|
||||
expect(
|
||||
screen.getByText(/Tight schedule — travel \+ buffer may exceed the gap/)
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not show the re-optimize hint before any manual reorder", async () => {
|
||||
global.fetch = mockFetch("manager") as unknown as typeof fetch;
|
||||
render(<RoutesPage />);
|
||||
|
||||
await waitFor(() => expect(screen.getByText("Alice")).toBeInTheDocument());
|
||||
expect(screen.queryByText("Re-optimize")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("calls the optimize endpoint when Optimize is clicked", async () => {
|
||||
const fetchMock = mockFetch("manager");
|
||||
global.fetch = fetchMock as unknown as typeof fetch;
|
||||
|
||||
+222
-48
@@ -1,4 +1,22 @@
|
||||
import { Suspense, lazy, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
TouchSensor,
|
||||
closestCenter,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type DragEndEvent,
|
||||
} from "@dnd-kit/core";
|
||||
import {
|
||||
SortableContext,
|
||||
arrayMove,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import { useBranding } from "../BrandingContext.js";
|
||||
import type { RouteMapStop } from "../components/RouteMap.js";
|
||||
|
||||
@@ -109,6 +127,100 @@ const inputStyle: React.CSSProperties = {
|
||||
fontSize: 14,
|
||||
};
|
||||
|
||||
/**
|
||||
* A single draggable stop card. The drag handle (⠿) carries the dnd-kit
|
||||
* listeners so the rest of the card stays scrollable/selectable; the handle is
|
||||
* sized for touch and works with pointer, touch and keyboard sensors.
|
||||
*/
|
||||
function SortableStop({
|
||||
stop,
|
||||
primaryColor,
|
||||
disabled,
|
||||
}: {
|
||||
stop: RouteStop;
|
||||
primaryColor: string;
|
||||
disabled: boolean;
|
||||
}) {
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
|
||||
useSortable({ id: stop.id, disabled });
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
style={{
|
||||
background: "#fff",
|
||||
border: `1px solid ${stop.conflict?.hasConflict ? "#fca5a5" : "#e2e8f0"}`,
|
||||
borderRadius: 8,
|
||||
padding: "0.7rem 0.85rem",
|
||||
display: "flex",
|
||||
gap: 10,
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.6 : 1,
|
||||
boxShadow: isDragging ? "0 6px 16px rgba(0,0,0,0.18)" : "none",
|
||||
touchAction: "none",
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Drag to reorder ${stop.clientName}`}
|
||||
disabled={disabled}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
alignSelf: "stretch",
|
||||
width: 28,
|
||||
border: "none",
|
||||
background: "transparent",
|
||||
color: "#94a3b8",
|
||||
fontSize: 18,
|
||||
lineHeight: 1,
|
||||
cursor: disabled ? "not-allowed" : "grab",
|
||||
touchAction: "none",
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
⠿
|
||||
</button>
|
||||
<div
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
width: 26,
|
||||
height: 26,
|
||||
borderRadius: "50%",
|
||||
background: primaryColor,
|
||||
color: "#fff",
|
||||
fontSize: 13,
|
||||
fontWeight: 700,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
{stop.stopOrder}
|
||||
</div>
|
||||
<div style={{ minWidth: 0, flex: 1 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
|
||||
<strong style={{ fontSize: 14, color: "#1a202c" }}>{stop.clientName}</strong>
|
||||
<span style={{ fontSize: 13, color: "#4b5563", whiteSpace: "nowrap" }}>{fmtTime(stop.appointmentStartTime)}</span>
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: "#6b7280", marginTop: 2 }}>{stop.clientAddress || "No address on file"}</div>
|
||||
<div style={{ fontSize: 12, color: "#6b7280", marginTop: 4 }}>
|
||||
{stop.stopOrder === 1 || stop.travelMinsFromPrev == null
|
||||
? "Start of route"
|
||||
: `${fmtDuration(stop.travelMinsFromPrev)} travel from previous`}
|
||||
</div>
|
||||
{stop.conflict?.hasConflict && (
|
||||
<div style={{ fontSize: 12, color: "#b91c1c", marginTop: 4, fontWeight: 600 }}>
|
||||
⚠ Tight schedule — travel + buffer may exceed the gap
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Page ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function RoutesPage() {
|
||||
@@ -124,6 +236,8 @@ export function RoutesPage() {
|
||||
const [data, setData] = useState<RouteResponse | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [optimizing, setOptimizing] = useState(false);
|
||||
const [reordering, setReordering] = useState(false);
|
||||
const [manuallyReordered, setManuallyReordered] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isGroomer = me?.role === "groomer";
|
||||
@@ -166,6 +280,7 @@ export function RoutesPage() {
|
||||
throw new Error(body.error || `Failed to load route (${r.status})`);
|
||||
}
|
||||
setData(await r.json());
|
||||
setManuallyReordered(false);
|
||||
} catch (e) {
|
||||
setData(null);
|
||||
setError(e instanceof Error ? e.message : "Failed to load route");
|
||||
@@ -193,6 +308,7 @@ export function RoutesPage() {
|
||||
throw new Error(body.error || `Optimization failed (${r.status})`);
|
||||
}
|
||||
setData(await r.json());
|
||||
setManuallyReordered(false);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Optimization failed");
|
||||
} finally {
|
||||
@@ -200,6 +316,71 @@ export function RoutesPage() {
|
||||
}
|
||||
}, [staffId, date]);
|
||||
|
||||
// Drag-to-reorder: pointer for desktop, touch (press-and-hold) for mobile
|
||||
// groomers, keyboard for accessibility. Touch uses a short delay so vertical
|
||||
// scrolling of the stop list still works without triggering a drag.
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
|
||||
useSensor(TouchSensor, { activationConstraint: { delay: 200, tolerance: 8 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
|
||||
);
|
||||
|
||||
// Persist a manually reordered stop list. Optimistic: the UI is updated
|
||||
// immediately from the dropped order and rolled back if the PATCH fails.
|
||||
const reorder = useCallback(
|
||||
async (orderedIds: string[]) => {
|
||||
const routeId = data?.route?.id;
|
||||
if (!routeId) return;
|
||||
const previous = data;
|
||||
// Optimistic local update: renumber stopOrder to match the new order so
|
||||
// the list and the map reflect the drop before the server responds.
|
||||
const byId = new Map((data?.stops ?? []).map((s) => [s.id, s]));
|
||||
const optimisticStops = orderedIds
|
||||
.map((id, i) => {
|
||||
const s = byId.get(id);
|
||||
return s ? { ...s, stopOrder: i + 1 } : null;
|
||||
})
|
||||
.filter((s): s is RouteStop => s !== null);
|
||||
setData((cur) => (cur ? { ...cur, stops: optimisticStops } : cur));
|
||||
setManuallyReordered(true);
|
||||
setReordering(true);
|
||||
setError(null);
|
||||
try {
|
||||
const r = await fetch(`/api/routes/${encodeURIComponent(routeId)}/reorder`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ stopOrder: orderedIds }),
|
||||
});
|
||||
if (!r.ok) {
|
||||
const body = await r.json().catch(() => ({}));
|
||||
throw new Error(body.error || `Reorder failed (${r.status})`);
|
||||
}
|
||||
// Server recomputes travel legs, buffers and conflict flags — adopt its
|
||||
// authoritative response over the optimistic guess.
|
||||
setData(await r.json());
|
||||
} catch (e) {
|
||||
setData(previous); // rollback
|
||||
setError(e instanceof Error ? e.message : "Reorder failed");
|
||||
} finally {
|
||||
setReordering(false);
|
||||
}
|
||||
},
|
||||
[data]
|
||||
);
|
||||
|
||||
const handleDragEnd = useCallback(
|
||||
(event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) return;
|
||||
const ids = (data?.stops ?? []).map((s) => s.id);
|
||||
const from = ids.indexOf(String(active.id));
|
||||
const to = ids.indexOf(String(over.id));
|
||||
if (from === -1 || to === -1) return;
|
||||
void reorder(arrayMove(ids, from, to));
|
||||
},
|
||||
[data, reorder]
|
||||
);
|
||||
|
||||
const mapStops: RouteMapStop[] = useMemo(
|
||||
() =>
|
||||
(data?.stops ?? []).map((s) => ({
|
||||
@@ -299,59 +480,52 @@ export function RoutesPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Stop list panel */}
|
||||
{/* Stop list panel — drag-to-reorder */}
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 10, maxHeight: 540, overflowY: "auto" }}>
|
||||
{stops.length === 0 && !loading && (
|
||||
<div style={{ color: "#6b7280", fontSize: 14, padding: "1rem" }}>No stops for this day.</div>
|
||||
)}
|
||||
{stops.map((s) => (
|
||||
<div
|
||||
key={s.id}
|
||||
style={{
|
||||
background: "#fff",
|
||||
border: `1px solid ${s.conflict?.hasConflict ? "#fca5a5" : "#e2e8f0"}`,
|
||||
borderRadius: 8,
|
||||
padding: "0.7rem 0.85rem",
|
||||
display: "flex",
|
||||
gap: 10,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
width: 26,
|
||||
height: 26,
|
||||
borderRadius: "50%",
|
||||
background: primaryColor,
|
||||
color: "#fff",
|
||||
fontSize: 13,
|
||||
fontWeight: 700,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
{stops.length > 0 && (
|
||||
<>
|
||||
{manuallyReordered && (
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, background: "#fffbeb", border: "1px solid #fde68a", borderRadius: 8, padding: "0.55rem 0.7rem" }}>
|
||||
<span style={{ fontSize: 12, color: "#92400e" }}>
|
||||
Stops reordered manually. Re-optimize to recompute the best route.
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={optimize}
|
||||
disabled={optimizing || reordering || !staffId}
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
padding: "0.35rem 0.7rem",
|
||||
borderRadius: 6,
|
||||
border: "none",
|
||||
background: primaryColor,
|
||||
color: "#fff",
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
cursor: optimizing || reordering || !staffId ? "not-allowed" : "pointer",
|
||||
opacity: optimizing || reordering || !staffId ? 0.6 : 1,
|
||||
}}
|
||||
>
|
||||
{optimizing ? "Optimizing…" : "Re-optimize"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={handleDragEnd}
|
||||
>
|
||||
{s.stopOrder}
|
||||
</div>
|
||||
<div style={{ minWidth: 0, flex: 1 }}>
|
||||
<div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
|
||||
<strong style={{ fontSize: 14, color: "#1a202c" }}>{s.clientName}</strong>
|
||||
<span style={{ fontSize: 13, color: "#4b5563", whiteSpace: "nowrap" }}>{fmtTime(s.appointmentStartTime)}</span>
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: "#6b7280", marginTop: 2 }}>{s.clientAddress || "No address on file"}</div>
|
||||
<div style={{ fontSize: 12, color: "#6b7280", marginTop: 4 }}>
|
||||
{s.stopOrder === 1 || s.travelMinsFromPrev == null
|
||||
? "Start of route"
|
||||
: `${fmtDuration(s.travelMinsFromPrev)} travel from previous`}
|
||||
</div>
|
||||
{s.conflict?.hasConflict && (
|
||||
<div style={{ fontSize: 12, color: "#b91c1c", marginTop: 4, fontWeight: 600 }}>
|
||||
⚠ Tight schedule — travel + buffer may exceed the gap
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<SortableContext items={stops.map((s) => s.id)} strategy={verticalListSortingStrategy}>
|
||||
{stops.map((s) => (
|
||||
<SortableStop key={s.id} stop={s} primaryColor={primaryColor} disabled={reordering} />
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user