import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import type { ReactElement } from "react"; import { createPortal } from "react-dom"; import { FolderMark } from "./icons"; import { formatSeconds, haversineKm, parseRouteAnswer, previewSeconds, routeCaveats, routeSaving, routeTimeLabel, routeTimeTone, } from "./mapProjection"; import type { GeoStop, RouteAnswer } from "./mapProjection"; import { AnchoredOverlay, BodyPortal } from "./OverlaySurface"; import { normalizedRouteMapLinks, routePrintStops, routeReversePrintLabels } from "./routeLinks"; import type { NormalizedRouteMapLink } from "./routeLinks"; import { routingPreferenceKey } from "./routePrefs"; import { submitRouteStopMove } from "./routeStopMove"; import { boundedGoogleMapsUrl } from "./routeZoneTypes"; import { locatedRouteMovePlan, mergeLocatedOrderAtAnchors, routeLocationPartition, routeApplicationPath, routeStopIdentity, RoutingStopLabelErrors, } from "./routeZoneApi"; // W51-T28 / R6 + C8 — the wave-51 base kit's ONE confirm dialog. Consumed, never re-implemented. import { TruncatedName } from "../home/TruncatedName"; import { ConfirmDialog } from "../ui/ConfirmDialog"; import { useEscapeClose } from "../ui/useEscapeClose"; import type { MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto, RouteDeliveryRecipient, RouteDeliveryDto, RouteDeliveryRequest, } from "./routeZoneTypes"; import "../styles/wave42/route-nav.css"; import "./route-nav.css"; import "../styles/wave46/route-print.css"; import "../styles/sdlc78/routing.css"; /** Google's own Maps mark from `public/brand/`, relative to the document as vite `base: "./"` makes * every asset. No `import.meta` here: gates compile this file to CommonJS, where it is an error. */ export const GOOGLE_MAPS_MARK_SRC = "./brand/google-maps.svg"; /** The decorative 16 px Maps mark. The text beside it carries the name. */ export function GoogleMapsMark({ className = "cg-gmaps-mark" }: { className?: string }) { return ; } type Result = Promise; type RouteAction = "rename" | "duplicate" | "star" | "share" | "delete"; /* ═════════════════════════════ W46-T19 / INSTRUCTION 9 / R9 / C2 ═════════════════════════════ * * The drive time at the top of the Route, the saving a reorder would win, and the number that * moves while a stop is being dragged. * * ⛔⛔ THE DEBOUNCE IS A COURTESY LIMIT, NOT A NICETY. The door behind `ROUTE_DOOR` calls a free, * unauthenticated public routing service, twice per request (the order as it stands, then the * order it would choose), behind a process-wide 1100 ms throttle. One settled figure therefore * costs at least 2.2 s of that service's time. A drag emits dozens of events a second, so the * only safe wiring is the one C2 names: arithmetic during the drag, ONE request on drop, and * every earlier request cancelled the moment a new drag starts, or a slow answer lands on an * order nobody is looking at any more. */ /* ═════════════════════════════ W46-T20 / INSTRUCTION 10 / R6 / C6 ════════════════════════ * * "ADD an export button for routes regardless to give to the sales team", plus R6's addition: * "i also want the google map link clickable in that PDF." * * The export is the browser's own Save as PDF behind a print stylesheet, which is the pattern * the catalog export already proves here. Set on `` for the duration of one print and * taken off again however the dialog ends; `styles/wave46/route-print.css` carries the * isolation keyed off it. * * ⛔ A NAME OF ITS OWN, NEVER `cg-cat-printing`. The catalog's print block un-hides exactly * `.cg-cat-print-portal` and hides every other child of ``, so borrowing its class would * print a blank sheet with nothing anywhere reporting a fault. */ const ROUTE_PRINTING_CLASS = "cg-w46-route-printing"; /** The honest backstop when neither `afterprint` nor the print media query reports an end. */ const PRINT_RELEASE_MS = 120_000; const ROUTE_DOOR = "/api/v1/geo/route"; /** * OWNER 2026-08-31 item 2 - the six defaults a new Route is stamped with, offered back as an * edit. ⛔ THIS LIST IS A MIRROR OF `route_system.py::_ROUTE_COLORS` AND MUST STAY ONE. The * server is the authority: `_color` falls back to `_ROUTE_COLORS[ordinal % len]` for anything * `_COLOR_RE` refuses, so a swatch offered here that the server does not recognise would save * as a different colour than the one the person pressed. The free picker beside them is why the * list does not need to grow: it is a shortcut, not the vocabulary. */ const ROUTE_SWATCHES = ["#6E4AC7", "#1F4E78", "#C85A54", "#2F8F83", "#B57716", "#A14B8B"]; /** The rail's own top level, as a map key. A bare string keeps `foldersByParent` and * `routesByFolder` one type instead of `Map`, and no folder id can collide * with it: `route_system.py` mints folder ids, and none of them is empty. */ const ROOT_LEVEL = ""; /* ⛔ TWO DRAG TYPES, ONE PER ROW KIND, and that is the same discrimination `ViewSidebar` makes with `FOLD_DRAG_TYPE` against a view's own channel. Sharing one channel would let a folder dropped on a Route reorder the Routes, and the handler that fired first would decide which. */ const ROUTE_DRAG = "application/x-aios-route"; const ROUTE_FOLDER_DRAG = "application/x-aios-route-folder"; /** Owner item 3 - the ONE mark every Route row wears. Deliberately the SAME waypoint path * `viewModes.tsx::IconRouteZone` draws, at the same 1.5 stroke: the toolbar button that opens * this rail and the rows inside it are one family, and a second route glyph would read as two. */ function IconRoute() { return ( ); } const SETTLE_DEBOUNCE_MS = 400; /** ⛔ BOTH HALVES OF THE FIGURE MUST ASK THE SAME QUESTION, or the number jumps on drop by the * size of a closing edge and the reorder gets blamed for it. That is why the round-trip answer * travels as ONE value into `previewSeconds` during the drag and into the request body on drop. * * ⭐⭐ OWNER 2026-08-31: *"wtf I don't see the button to make it either 1 single trip or round * trip. The algorithm was there its not being displayed anymore"*. They are right, and the * record says so in code: `MapView.tsx` holds `roundTrip` state whose only writer, `setRoundTrip`, * sits in the retired `void []` compatibility list, so the value was pinned at false with no * control anywhere. The solver (`mapProjection.ts::planRoute`, `twoOptOrder`, `tourLength`) and * the server door (`routes_geo.py`, which reads `roundTrip` off the body) were both live the * whole time. So this is a control being re-attached to an algorithm, not a feature being built. * It is a PROP rather than local state because the map's drawn plan and this panel's timer must * answer the same question; two copies is how they come to disagree. */ const ROUTE_MODE = "driving"; /** * The order a drag would leave behind: `moved` taken out and put back where `over` sits now. * * ⛔ PURE, AND DELIBERATELY OUTSIDE THE COMPONENT. It is the only thing the drag path computes, * so keeping it here makes "the drag calls no network" a property of a function that has no * closure to hide one in. */ function orderAfterMove(pids: number[], moved: number, over: number): number[] { const from = pids.indexOf(moved); const to = pids.indexOf(over); if (from < 0 || to < 0 || from === to) return pids; const next = [...pids]; next.splice(to, 0, next.splice(from, 1)[0]); return next; } function mayRouteAction(route: MapRouteDto, action: RouteAction): boolean { return route.capabilities?.[action] === true; } export interface RoutingCustomerDetail { pid: number; name: string; fields: { key: string; label: string; value: string }[]; } function routingFieldUrl(value: string): string | null { try { const url = new URL(value); return /^https?:\/\//i.test(value.trim()) && (url.protocol === "http:" || url.protocol === "https:") ? url.href : null; } catch { return null; } } export function RouteCustomerPane({ detail, onBack }: { detail: RoutingCustomerDetail | null; onBack: () => void; }) { const pane = useRef(null); const opener = useRef(null); const previousPid = useRef(null); const [closingPid, setClosingPid] = useState(null); const closing = detail != null && closingPid === detail.pid; const close = () => { if (!detail) return; if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) onBack(); else setClosingPid(detail.pid); }; useEscapeClose(detail != null, close, { container: () => pane.current }); useLayoutEffect(() => { if (detail) { const active = document.activeElement; if ((active instanceof HTMLElement || active instanceof SVGElement) && !pane.current?.contains(active)) opener.current = active; pane.current?.querySelector(".cg-routing-detail-back")?.focus({ preventScroll: true }); } else if (previousPid.current !== null && opener.current?.isConnected) { opener.current.focus({ preventScroll: true }); } previousPid.current = detail?.pid ?? null; setClosingPid(null); }, [detail?.pid]); if (!detail) return null; return
{ if (event.target === event.currentTarget && closing) onBack(); }}>

{detail.name}

{detail.fields.map((field) => { const href = routingFieldUrl(field.value); return
{field.label}
{href ? {field.value} : field.value}
; })}
; } export function RouteNav(props: Parameters[0]) { return ; } function RouteNavContent({ routes, folders, selectedIds, activeRouteId, sources, storageKey, createdRoute, onCreatedDismiss, onToggle, onActiveRouteChange, onOpenRecord, onCreate, onMoveToOrder, onUpdate, onDuplicate, onDelete, onShare, onRouteMove, onRouteReorder, stopLabels = {}, stopCoords = {}, onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule, onDeleteDelivery, deliveryRecipients, deliveryRecipientError, onReloadDeliveryRecipients, zones = [], roundTrip = false, onRoundTripChange, routeStartPid = null, routeEndPid = null, onRouteStartChange, onRouteEndChange, onStopAdded, routesLoadError = false, onRetryRoutes, applicationName = "", applicationId, routesLoaded = true }: { routes: MapRouteDto[]; folders: MapRouteFolderDto[]; selectedIds: ReadonlySet; activeRouteId: string | null; sources: MapRouteSource[]; storageKey: string; createdRoute: MapRouteDto | null; onCreatedDismiss: () => void; onToggle: (route: MapRouteDto) => void; onActiveRouteChange: (routeId: string | null) => void; onOpenRecord: (pid: number) => void; /** Row-derived identity for every stop the host can name. Keyed by pid; both fields may be * empty, and `routeStopIdentity` owns what is shown when they are. * ⚠ OPTIONAL because this component also mounts in a render harness with no host grid behind * it; MapView always supplies it. The default is `{}`, which routes every stop through * `routeStopIdentity`'s final arm rather than rendering a blank. */ stopLabels?: Record; /** W46-T19 — where each stop IS, keyed by pid, in the coordinates the host already geocoded. * The drive time, the drag preview and the reorder offer all need a position rather than a * name, and `stopLabels` deliberately carries neither. * ⚠ OPTIONAL for the same reason `stopLabels` is: this component mounts in a render harness * with no host grid behind it. An absent or partial map is stated on screen, never rounded * down to a confident zero. */ stopCoords?: Record; onCreate: (name: string, source: MapRouteSource) => Result; onMoveToOrder: (route: MapRouteDto, customerPid: number, order: number) => Result; onUpdate: (route: MapRouteDto, patch: MapRouteUpdate) => Result; onDuplicate: (route: MapRouteDto) => Result; onDelete: (route: MapRouteDto) => Promise; onShare: (route: MapRouteDto) => Result; onRouteMove: (route: MapRouteDto, folderId: string | null) => Result; onRouteReorder: (order: string[]) => Result; onFolderCreate: (name: string, parent: string | null) => Result; onFolderUpdate: (folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null }) => Result; onFolderDelete: (folder: MapRouteFolderDto) => Result; onFolderReorder: (order: string[]) => Result; onCreateStart: () => void; mapLinks: NormalizedRouteMapLink[]; mapLinkRefusal: string | null; deliveries: RouteDeliveryDto[] | null; deliveryRecipients: RouteDeliveryRecipient[] | null; deliveryRecipientError: string | null; onReloadDeliveryRecipients: () => void; onSchedule: (route: MapRouteDto, request: RouteDeliveryRequest) => Result; onDeleteDelivery: (route: MapRouteDto, delivery: RouteDeliveryDto) => Result; /** D-599 / W46-T22 - the Zones this database has, so a Route can be put in one. The host * already holds them to draw the map, so this is a pass-through and never a second fetch. * ⚠ OPTIONAL with a `[]` default for the same reason `stopLabels` is: this component also * mounts in a render harness with no host behind it. An empty list renders the selector * disabled with a sentence, never a silently empty dropdown. */ zones?: MapZoneDto[]; /** Owner 2026-08-31 - one way, or back to where the driver started. Owned by the host so the * map's drawn plan and this panel's drive time cannot answer different questions. */ roundTrip?: boolean; onRoundTripChange?: (value: boolean) => void; /** Planner endpoints are owned by MapView, so the rail cannot disagree with the drawn route. */ routeStartPid?: number | null; routeEndPid?: number | null; onRouteStartChange?: (pid: number | null) => void; onRouteEndChange?: (pid: number | null) => void; /** The Route the membership door answered with, so the host's read model gains the new stop * without a second fetch. Mirrors what `moveNamedRouteStop` already does on a reorder. */ onStopAdded?: (route: MapRouteDto, applicationId?: string) => void; /** Present only when this trusted route surface was launched by a saved Application. */ applicationName?: string; applicationId?: string; /** False until the first saved-Route read answers, so an empty list is not read as "none". */ routesLoaded?: boolean; /** True when the last saved-Route read failed; the listed routes are the last good read. */ routesLoadError?: boolean; onRetryRoutes?: () => void; }) { const stopLabelErrors = useContext(RoutingStopLabelErrors); /* ⭐⭐ OWNER 2026-08-31 item 3 - THE ROUTES RAIL IS THE VIEWS RAIL, NOT A COUSIN OF IT. Owner: *"I need the routes LIST navigation and the routes itself to have the exact same interface just like how we have it with view, where you can just click it and drag it AND its fucking compact. Make it the exact same layout. The only difference is the icon."* and, in the grill: *"exactly like how Views rail is, with the +create for folder and find at the top. Exactly the same. instead of number it should all just be the same Route icon."* ⛔ SO THE BREADCRUMB PATH IS GONE, AND THAT IS THE STRUCTURAL HALF OF THE ASK. A folder used to be a place you NAVIGATED INTO (`levelAt` + `folderPath` + an `Up` button), which is a different interaction from the Views rail's disclosure groups however similar the rows look. Folders now open and shut in place, and the stored key holds the SHUT set rather than the current level - so a person who never touches a folder sees every Route, which is the behaviour a rail whose whole job is "pick one" should have. ⚠ THE ROW CLASSES ARE THE VIEWS RAIL'S OWN (`.cg-view-row`, `.cg-view-main`, `.cg-view-text`, `.cg-view-name`, `.cg-view-more`, `.cg-fold*`, `.cg-create-new`, `.cg-find-view`), reused rather than copied. Copying them into a `cg-w44-route-*` twin is how the two lists drift apart again the first time either is polished, and "exact same layout" is a promise that only a shared contract can keep. */ const routingAlive = useRef(true); useEffect(() => { routingAlive.current = true; return () => { routingAlive.current = false; }; }, []); const routePathKey = routingPreferenceKey(`aios-routes-shut-${storageKey}`, applicationId); const [shutFolders, setShutFolders] = useState>(() => { if (typeof window === "undefined") return new Set(); try { const raw = window.localStorage.getItem(routePathKey); const parsed = raw ? JSON.parse(raw) : null; return new Set(Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : []); } catch { return new Set(); } }); /** Owner item 3 - "find at the top". Local, never persisted: a search is a way of LOOKING at * the rail, not a property of it, which is the rule `ViewSidebar`'s own box already follows. */ const [routeQuery, setRouteQuery] = useState(""); /* ═════════════════ W50-T10 / INSTRUCTION 9 — THE FOUR MENUS PORTAL NOW ═════════════════ * * Owner: *"Clicking the '...' on each route (Duplicate/Star/Share/Delete) expands the whole * thing, and it cannot be closed."* All four menus in this rail were in-flow `
`s toggled * only by their own button: no outside-click dismiss, no Escape, no focus restore, and each one * pushed the rows below it down as it opened. `AnchoredOverlay` owns all four behaviours * already, so every one of them is now a portalled overlay instead. * * ⛔ THE ANCHOR RIDES IN THE STATE, AND IT IS READ FROM `event.currentTarget` IN THE HANDLER * BODY — never inside the updater. React sets `currentTarget = null` the moment the handler * returns, and a functional updater is re-invoked when React drains the queue, by which time it * reads null and the overlay degrades to a zero-rect at the viewport origin. `ViewSidebar.tsx` * carries the full account: that one line was the difference between its rail working and the * whole app going white, reproduced on the shipped build by `_qa_live_rail.py` on 2026-08-04. * * ⚠ NO CSS CAME WITH THIS. `body > .cg-overlay` already sits at `--cg-z-overlay` (110), which * outranks `--cg-z-mapchrome` (65) that the route popover stacks at, so a portalled menu is * above it by construction. Minting a z token here would be a second answer to a solved * question. */ const [createMenu, setCreateMenu] = useState<{ anchor: HTMLElement } | null>(null); /** The row being carried, and the row it would land ABOVE. Same two marks the Views rail uses. */ const [rowDrag, setRowDrag] = useState(null); const [rowOver, setRowOver] = useState(null); const [creating, setCreating] = useState(false); const [creatingFolder, setCreatingFolder] = useState(false); const [name, setName] = useState(""); const [folderName, setFolderName] = useState(""); const [sourceId, setSourceId] = useState("selection"); const [error, setError] = useState(null); const [orderErrors, setOrderErrors] = useState>({}); /** Owner 2026-08-31 - the add-record door's own two pieces of state. */ const [addStop, setAddStop] = useState<{ anchor: HTMLElement } | null>(null); const [addStopQuery, setAddStopQuery] = useState(""); const [titleDraft, setTitleDraft] = useState(null); const [editMapsUrl, setEditMapsUrl] = useState(""); /** D-599 - the Route's Zone, as a draft, saved by the same Save button as the Maps URL. */ const [editZoneId, setEditZoneId] = useState(""); /** OWNER 2026-08-31 item 2 - the Route's colour, as a draft, on the same Save button. * Seeded from the record so the swatch a person sees selected is the colour the map draws. */ const [editColor, setEditColor] = useState(ROUTE_SWATCHES[0]); const [deliveryRecipient, setDeliveryRecipient] = useState(""); const [deleteConfirm, setDeleteConfirm] = useState(false); const [menu, setMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null); /* ⭐⭐ W51-T28 / R6 — THE PENDING DELETE IS HOISTED TO THE COMPONENT, AND THAT IS THE WHOLE TRICK. Both row menus close themselves (`setMenu(null)`) in the same handler that used to raise `window.confirm`, and each menu is a conditional subtree (`{menu && menu.id === item.id && (`). A dialog rendered inside that subtree unmounts in the same commit and the person sees nothing at all. So the menu records WHAT was asked for, and the dialog is mounted from the component's own returned JSX, outside every menu conditional and outside `renderLevel`. ⚠ ONE state serves both deletes because it is DISCRIMINATED. Two booleans would let a folder delete and a route delete be pending at once, which is two dialogs on one screen. */ const [pendingDelete, setPendingDelete] = useState< | { kind: "folder"; folder: MapRouteFolderDto } | { kind: "route"; item: MapRouteDto } | null >(null); const [renameId, setRenameId] = useState(null); /** W54-T21 - raised by the rename's Escape claim so the blur it causes does not save. */ const renameEscaping = useRef(false); const [busy, setBusy] = useState(false); const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10); const [deliveryNotice, setDeliveryNotice] = useState(null); const [deliveryError, setDeliveryError] = useState(null); const [deliveryBusy, setDeliveryBusy] = useState(false); const [mapCopyNotice, setMapCopyNotice] = useState(null); const [mapCopyError, setMapCopyError] = useState(null); const route = activeRouteId ? routes.find((item) => item.id === activeRouteId) : null; const rail = useRef(null); // ⚠ The Routes list unmounts while a Route is open, so its scroll is kept here for Back. const listScroll = useRef(0); const previousRouteId = useRef(null); useLayoutEffect(() => { if (!applicationName) return; const list = rail.current?.querySelector(".cg-route-index-scroll"); if (!route && previousRouteId.current !== null && list) list.scrollTop = listScroll.current; previousRouteId.current = route?.id ?? null; }, [applicationName, route?.id]); const source = sources.find((item) => item.id === sourceId) || sources[0]; const mapsUrl = boundedGoogleMapsUrl(route?.mapsUrl); /** * W46-T22 / INSTRUCTION 19 — a stop can be taken OFF a Route from the Route itself. * * ⛔ THE WHOLE STOP LIST IS NEVER SUBMITTED. `visibleStopIds` is permission filtered on the * server, so PATCHing it back as this Route's `stops` would silently drop every stop outside * the reader's customer book. The membership door removes exactly one pid and re-densifies the * rest, which is why it exists. * ⛔ R14 (2026-09-03) MADE THIS ONE OF MEMBERSHIP'S TWO REMAINING DOORS. The map used to * offer a third: clicking a pin with the Routes panel open raised an add-or-remove prompt * on the same endpoint. That shortcut is retired, because it stole the plain click from * opening the record. Membership is now this per-stop control and the `Add record` picker * below, both of them visible, and both of them still calling `/stops/membership`. * * ⚠ THE HOST OWNS `namedRoutes` AND THIS COMPONENT HAS NO CALLBACK INTO IT, so a confirmed * removal is held here until the host refetches. The set self-heals rather than going stale: * it is keyed to one Route id, and any pid the host no longer reports is pruned, so a stop * re-added through the `Add record` picker reappears instead of staying invisible. */ const [removedStops, setRemovedStops] = useState<{ routeId: string; pids: number[] }>( { routeId: "", pids: [] } ); const activeStopIds = route?.visibleStopIds; const activeStopRouteId = route?.id || ""; useEffect(() => { const present = new Set(activeStopIds || []); setRemovedStops((current) => { if (current.routeId !== activeStopRouteId) return { routeId: activeStopRouteId, pids: [] }; const pids = current.pids.filter((pid) => present.has(pid)); return pids.length === current.pids.length ? current : { routeId: activeStopRouteId, pids }; }); }, [activeStopIds, activeStopRouteId]); const stopIds = useMemo( () => (activeStopIds || []).filter( (pid) => !(removedStops.routeId === activeStopRouteId && removedStops.pids.includes(pid)) ), [activeStopIds, activeStopRouteId, removedStops] ); /** * ⭐ OWNER 2026-08-31 - the records the add-record dropdown may offer: everything in the book * this panel already holds, minus what is already a stop. * * Every match remains reachable through the picker. */ const stopSet = useMemo(() => new Set(stopIds), [stopIds]); const addStopMatches = useMemo(() => { const needle = addStopQuery.trim().toLowerCase(); const out: { pid: number; label: string }[] = []; for (const [key, value] of Object.entries(stopLabels)) { const pid = Number(key); if (!Number.isSafeInteger(pid) || stopSet.has(pid)) continue; const label = routeStopIdentity(value, pid); if (needle && !label.toLowerCase().includes(needle)) continue; out.push({ pid, label }); } // ⛔ A NAMELESS RECORD SORTS LAST, AND THIS IS A MEASUREMENT, NOT A PREFERENCE. Tenant #0's // customer book carries 57 records whose name in Odoo is literally "?" (counted on the // deployed staging build). Plain `localeCompare` puts "?" before every letter, so all 57 // filled the first fifty rows and the menu opened on nothing anybody could pick. A label // with no letter or digit in it is a placeholder rather than a name, so it goes to the end; // it is still offered, still searchable, and no record is hidden. const named = (label: string) => /[\p{L}\p{N}]/u.test(label); out.sort((a, b) => (Number(named(b.label)) - Number(named(a.label))) || a.label.localeCompare(b.label)); return out; }, [addStopQuery, stopLabels, stopSet]); const addableStops = addStopMatches; const recipientNames = useMemo( () => new Set((deliveryRecipients || []).map((person) => person.username)), [deliveryRecipients] ); const knownFolders = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]); const deliveryTimezone = useMemo(() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; } catch { return "UTC"; } }, []); /** Child folders of one parent, in their stored order. `ROOT_LEVEL` is the rail's own top. */ const foldersByParent = useMemo(() => { const map = new Map(); for (const folder of folders) { const parent = folder.parent && knownFolders.has(folder.parent) ? folder.parent : ROOT_LEVEL; const bucket = map.get(parent); if (bucket) bucket.push(folder); else map.set(parent, [folder]); } for (const bucket of map.values()) bucket.sort((a, b) => (a.order || 0) - (b.order || 0)); return map; }, [folders, knownFolders]); /** Routes filed in one folder, in their stored rail order. A Route whose folder this reader * cannot see falls to the top level rather than disappearing. */ const routesByFolder = useMemo(() => { const map = new Map(); for (const item of routes) { const parent = item.folderId && knownFolders.has(item.folderId) ? item.folderId : ROOT_LEVEL; const bucket = map.get(parent); if (bucket) bucket.push(item); else map.set(parent, [item]); } for (const bucket of map.values()) bucket.sort((a, b) => (a.navOrder || 0) - (b.navOrder || 0)); return map; }, [routes, knownFolders]); /** ⚠ A FOLDER SURVIVES THE FIND BOX WHEN A DESCENDANT MATCHES, never only when its own name * does. Hiding a folder whose contents match is how a search convinces somebody a Route has * been deleted. `ViewSidebar` holds the same rule for its groups. */ const query = routeQuery.trim().toLowerCase(); const folderMatches = useMemo(() => { const hit = new Set(); if (!query) return hit; const walk = (parent: string): boolean => { let found = (routesByFolder.get(parent) || []).some( (item) => item.name.toLowerCase().includes(query) ); for (const child of foldersByParent.get(parent) || []) { const inside = walk(child.id); if (inside || child.name.toLowerCase().includes(query)) { hit.add(child.id); found = true; } } return found; }; walk(ROOT_LEVEL); return hit; }, [foldersByParent, query, routesByFolder]); const toggleFolder = (folderId: string) => { setMenu(null); setShutFolders((current) => { const next = new Set(current); if (next.has(folderId)) next.delete(folderId); else next.add(folderId); try { window.localStorage.setItem(routePathKey, JSON.stringify([...next])); } catch { /* The rail still opens and shuts when storage is unavailable. */ } return next; }); }; useEffect(() => { setTitleDraft(null); setEditMapsUrl(route?.mapsUrl || ""); setEditZoneId(route?.zoneId || ""); setEditColor((route?.color || ROUTE_SWATCHES[0]).toUpperCase()); setOrderErrors({}); setDeleteConfirm(false); setError(null); setDeliveryNotice(null); setDeliveryError(null); setMapCopyNotice(null); setMapCopyError(null); }, [route?.id, route?.mapsUrl, route?.name, route?.zoneId]); useEffect(() => { setDeliveryRecipient(""); }, [route?.id]); const copyMapLinks = () => { setMapCopyNotice(null); setMapCopyError(null); const clipboard = typeof navigator === "undefined" ? null : navigator.clipboard; if (!shownMapLinks.length || !clipboard?.writeText) { setMapCopyError("Maps links could not be copied in this browser."); return; } void clipboard.writeText(shownMapLinks.map((link) => link.url).join("\n")) .then(() => setMapCopyNotice( `${shownMapLinks.length.toLocaleString()} Maps link${shownMapLinks.length === 1 ? "" : "s"} copied.` )) .catch(() => setMapCopyError("Maps links could not be copied. Open each link instead.")); }; const scheduleDelivery = (target: MapRouteDto) => { const recipient = deliveryRecipient; if (!recipient || !recipientNames.has(recipient)) { setDeliveryError("Choose an active delivery recipient."); return; } setDeliveryBusy(true); setDeliveryError(null); setDeliveryNotice(null); void onSchedule(target, { recipient, timezone: deliveryTimezone, mapsPerLink: deliveryMapsPerLink, }).then((message) => { if (message) setDeliveryError(message); else setDeliveryNotice(`${target.name} will be delivered to ${recipient} daily at 08:00.`); }).finally(() => setDeliveryBusy(false)); }; const removeDelivery = (target: MapRouteDto, delivery: RouteDeliveryDto) => { setDeliveryBusy(true); setDeliveryError(null); setDeliveryNotice(null); void onDeleteDelivery(target, delivery).then((message) => { if (message) setDeliveryError(message); else setDeliveryNotice(`${delivery.name} was removed.`); }).finally(() => setDeliveryBusy(false)); }; const finish = (operation: Result) => { setBusy(true); void operation.then(setError).finally(() => setBusy(false)); }; const commitStopMove = (target: MapRouteDto, pid: number, raw: string) => { holdTimerCard(true); setBusy(true); setOrderErrors((current) => { const next = { ...current }; delete next[pid]; return next; }); void submitRouteStopMove(target, pid, raw, onMoveToOrder).then((result) => { if (result.error) { const message = result.error; setOrderErrors((current) => ({ ...current, [pid]: message })); setTimerHold(null); return; } setOrderErrors((current) => { const next = { ...current }; delete next[pid]; return next; }); }).finally(() => setBusy(false)); }; /** * Put ONE record onto this Route, through the same membership door the x uses. * * ⛔ NO OPTIMISTIC ROW. The server answers with the whole Route and `onMoveToOrder`'s host * already replaces the record from that answer; painting a stop locally first would show a * position the server has not agreed to, and a refusal would then have to un-paint it. */ const commitStopAdd = (target: MapRouteDto, pid: number) => { setBusy(true); setError(null); void (async () => { try { const res = await fetch( routeApplicationPath(`/api/v1/customers/routes/${encodeURIComponent(target.id)}/stops/membership`, applicationId), { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ customerPid: pid, present: true }), } ); const payload = await res.json().catch(() => null); if (!routingAlive.current) return; if (!res.ok) { setError(payload?.error?.message || payload?.detail?.message || "That record could not be added to this Route."); return; } // The removal ledger is what hides a stop this session took OFF the Route. Adding the // same record back has to clear its entry, or the row the server just returned would be // filtered straight back out and the button would look broken. setRemovedStops((current) => current.routeId === target.id ? { routeId: target.id, pids: current.pids.filter((item) => item !== pid) } : current); const routeUpdate = payload?.route as MapRouteDto | undefined; if (routeUpdate) onStopAdded?.(routeUpdate, applicationId); } catch { setError("That record could not be added to this Route."); } finally { setBusy(false); } })(); }; const commitStopRemove = (target: MapRouteDto, pid: number) => { setBusy(true); setOrderErrors((current) => { const next = { ...current }; delete next[pid]; return next; }); void (async () => { try { const res = await fetch( routeApplicationPath(`/api/v1/customers/routes/${encodeURIComponent(target.id)}/stops/membership`, applicationId), { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ customerPid: pid, present: false }), } ); const payload = await res.json().catch(() => null); if (!routingAlive.current) return; if (!res.ok) { const message = payload?.error?.message || payload?.detail?.message || "This stop could not be removed."; setOrderErrors((current) => ({ ...current, [pid]: message })); return; } setRemovedStops((current) => current.routeId === target.id ? (current.pids.includes(pid) ? current : { routeId: target.id, pids: [...current.pids, pid] }) : { routeId: target.id, pids: [pid] }); } catch { setOrderErrors((current) => ({ ...current, [pid]: "This stop could not be removed." })); } finally { setBusy(false); } })(); }; /* ── W46-T19: the drive time, the saving, and the number that moves during a drag ───────── The whole feature is state and arithmetic here, and exactly one request, so that the two numbers on screen can never come from two different questions. */ const [routeAnswer, setRouteAnswer] = useState(null); const [timerError, setTimerError] = useState(null); const [timerBusy, setTimerBusy] = useState(false); const [applyBusy, setApplyBusy] = useState(false); const [dragPid, setDragPid] = useState(null); const [dragOrder, setDragOrder] = useState(null); const [dragSeconds, setDragSeconds] = useState(null); /* S78-T08: the timer card keeps its pre-move height from a stop's pickup until the new drive time settles, so the stop list below it never jumps on drop or on Alt + Up / Alt + Down. */ const timerCardRef = useRef(null); const [timerHold, setTimerHold] = useState< { height: number; from: RouteAnswer | null; committed: boolean } | null>(null); const holdTimerCard = (committed: boolean) => { const height = timerCardRef.current?.getBoundingClientRect().height ?? 0; setTimerHold((current) => current ? { ...current, committed: current.committed || committed } : height > 0 ? { height, from: routeAnswer, committed } : null); }; /** W46-T20 — true only while one print is in flight. The printed sheet is mounted on * `document.body` for exactly that long, so it costs nothing the rest of the time and can * never be a second copy of the Route sitting invisibly in the panel. */ const [printing, setPrinting] = useState(false); /** A reverse label is prepared before mounting the print portal, never requested from a * browser/provider during print. The server may answer unavailable; that remains printable. */ const [preparingPrint, setPreparingPrint] = useState(false); const [reversePrintLabels, setReversePrintLabels] = useState>({}); /** ⚠ A LATCH, BECAUSE `window.print()` MUST HAPPEN ONCE. React's development strict mode * invokes an effect twice; without this the dialog opens, closes, and opens again. */ const printLatch = useRef(false); /** The in-flight print's own release, held so an unmount can take the printing class back * off `` without the effect needing a teardown of its own (see below). */ const releasePrint = useRef<(() => void) | null>(null); useEffect(() => () => { releasePrint.current?.(); }, []); /** * W46-T20 — open the print dialog once the printed sheet is in the document, and give the * app back to the person however the dialog ends. * * THREE WAYS OUT, because none of them is reliable alone: `afterprint` (which does not fire * on a cancelled dialog in every engine), the `print` media query going false (Safari's * route), and a timeout (the honest backstop). `finish` is idempotent, so whichever arrives * first wins. Leaving the class on would hide the entire app behind a print rule. * * ⛔⛔ THIS EFFECT DELIBERATELY RETURNS NO TEARDOWN, AND THAT IS THE WHOLE FIX. A cleanup * that cancelled the queued frame would run IMMEDIATELY under development strict mode, which * mounts, tears down and mounts again: the frame would be cancelled before it ever fired and * the Export button would silently do nothing in dev while working in production, which is * the worst shape a defect can take. The latch above makes the second invocation a no-op * instead, `finish` is the only teardown there is, and `releasePrint` above hands an unmount * the same exit so the printing class can never be left behind. */ useEffect(() => { if (!printing || printLatch.current) return; printLatch.current = true; const root = document.documentElement; const media = window.matchMedia ? window.matchMedia("print") : null; let done = false; let timer: ReturnType | undefined; function finish() { if (done) return; done = true; root.classList.remove(ROUTE_PRINTING_CLASS); window.removeEventListener("afterprint", finish); media?.removeEventListener?.("change", onMedia); if (timer !== undefined) clearTimeout(timer); printLatch.current = false; releasePrint.current = null; setPrinting(false); } function onMedia(event: MediaQueryListEvent) { if (!event.matches) finish(); } releasePrint.current = finish; root.classList.add(ROUTE_PRINTING_CLASS); window.addEventListener("afterprint", finish); media?.addEventListener?.("change", onMedia); timer = setTimeout(finish, PRINT_RELEASE_MS); // One frame, so the sheet has been laid out under the print rules before the engine // snapshots it. Chrome blocks inside `print()` until the dialog closes; Firefox returns // immediately. Both ends are handled above. `done` is re-read here because an unmount in // that one frame has already released the print, and a dialog opened after the sheet was // removed would print a blank page. window.requestAnimationFrame(() => { if (done) return; try { window.print(); } catch { finish(); } }); }, [printing]); const settleTimer = useRef(null); const settleAbort = useRef(null); const settleGeneration = useRef(0); /** C1 keeps both halves explicit: a missing coordinate is a named fixed anchor, never a stop * silently omitted from either the UI or the apply merge. */ const locationPartition = useMemo( () => routeLocationPartition(stopIds, stopLabels, stopCoords), [stopIds, stopLabels, stopCoords], ); const locatedStops = locationPartition.located; const locatedPids = locationPartition.locatedPids; const unlocated = locationPartition.unlocated; /** * ⭐⭐ W46-T22 / W46-T20 — THE MAPS LINKS MUST NOT OUTLIVE A REMOVED STOP. * * `mapLinks` and `mapLinkRefusal` are computed by MapView from the route's SERVER stop list, and * removing a stop writes only `removedStops` here: the host is never told, so until * `loadNamedRoutes` next fires the Google Maps section would still list, and Copy Maps links * would still copy, a customer the person has just removed. The printed PDF is already safe * because `routePrintStops` reads the pruned `stopIds`, and that is exactly why this one is * worth closing: the two hand-offs a rep actually leaves the building with would otherwise * DISAGREE about who is on the route. * * ⚠ Recomputed ONLY while a removal is pending. With none pending the host's own value is used * verbatim, so the normal path keeps MapView's `coarsePointer` and this cannot drift from it. */ const removalPending = removedStops.routeId === activeStopRouteId && removedStops.pids.length > 0; const prunedMapLinks = useMemo( () => (removalPending ? normalizedRouteMapLinks(stopIds, locatedStops) : null), [removalPending, stopIds, locatedStops] ); const shownMapLinks = prunedMapLinks ? prunedMapLinks.links : mapLinks; const shownMapLinkRefusal = prunedMapLinks ? prunedMapLinks.refusal : mapLinkRefusal; const startUnavailable = routeStartPid !== null && !locatedPids.includes(routeStartPid); const endUnavailable = routeEndPid !== null && !locatedPids.includes(routeEndPid); const endpointChoicesReady = locatedPids.length >= 2; // Endpoint and trip-shape choices change the route just as surely as a drag does. Include // them in the debounce key so a chosen end cannot leave the previous open-path timing visible. const timerKey = `${activeStopRouteId}:${locatedPids.join(",")}:${unlocated.map((stop) => `${stop.pid}:${stop.reason}`).join("|")}:${roundTrip ? "round" : "one"}:${routeStartPid ?? ""}:${roundTrip ? "" : routeEndPid ?? ""}`; /** * The number a drag moves. ⛔ ARITHMETIC ONLY: `previewSeconds` is `tourLength` over * coordinates already on screen, so this runs at pointer speed and costs nothing. Nothing in * this function, or in the two handlers that call it, may reach the network. */ const dragPreviewSeconds = (pids: number[]): number | null => { if (locatedStops.length < 2) return null; const seat = new Map(locatedStops.map((stop, index) => [stop.pid, index])); const order: number[] = []; for (const pid of pids) { const index = seat.get(pid); if (index !== undefined) order.push(index); } if (order.length < 2) return null; const geo: GeoStop[] = locatedStops.map((stop) => ({ lat: stop.lat, lon: stop.lon })); return previewSeconds(order, geo, haversineKm, roundTrip); }; const cancelSettle = () => { if (settleTimer.current !== null) { window.clearTimeout(settleTimer.current); settleTimer.current = null; } settleAbort.current?.abort(); settleAbort.current = null; }; /** The one request. It is never called from a drag; only from the debounced timer below. */ const settleRoute = async (pids: number[]) => { const byPid = new Map(locatedStops.map((stop) => [stop.pid, stop])); const stops = pids.map((pid) => byPid.get(pid)).filter(Boolean) .map((stop) => ({ lat: stop!.lat, lon: stop!.lon, pid: stop!.pid })); if (stops.length < 2) { setRouteAnswer(null); return; } const controller = new AbortController(); settleAbort.current = controller; const generation = settleGeneration.current + 1; settleGeneration.current = generation; setTimerBusy(true); setTimerError(null); try { const res = await fetch(routeApplicationPath(ROUTE_DOOR, applicationId), { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, signal: controller.signal, // ⛔ `pid` PER STOP IS LOAD-BEARING: without it the door answers with seat indices and // the one-click apply has no record to move. `fallback: true` is what makes an // arithmetic answer come back as `source: "haversine"` instead of an error. body: JSON.stringify({ stops, locatedPids: pids, unlocated, mode: ROUTE_MODE, roundTrip, fallback: true, // The server owns the exact closing leg and constrained optimization. Pids make the // selection stable across an order update; coordinates alone would turn it into seats. startPid: routeStartPid ?? undefined, endPid: roundTrip ? undefined : routeEndPid ?? undefined, }), }); const payload = await res.json().catch(() => null); if (!routingAlive.current) return; if (settleGeneration.current !== generation) return; const answer = res.ok ? parseRouteAnswer(payload) : null; if (!answer) { setRouteAnswer(null); setTimerError(payload?.error?.message || "This Route could not be timed just now."); return; } setRouteAnswer(answer); } catch (failure) { if ((failure as { name?: string } | null)?.name === "AbortError") return; if (settleGeneration.current !== generation) return; setRouteAnswer(null); setTimerError("This Route could not be timed just now."); } finally { if (settleGeneration.current === generation) setTimerBusy(false); } }; const scheduleSettle = (pids: number[]) => { cancelSettle(); settleTimer.current = window.setTimeout(() => { settleTimer.current = null; void settleRoute(pids); }, SETTLE_DEBOUNCE_MS); }; useEffect(() => { setRouteAnswer(null); setTimerError(null); if (locatedPids.length < 2) { cancelSettle(); return; } scheduleSettle(locatedPids); return () => cancelSettle(); // The key already carries the Route and its located stops in order; the callbacks below are // recreated every render and would restart the request on every keystroke elsewhere. // eslint-disable-next-line react-hooks/exhaustive-deps }, [timerKey]); const beginStopDrag = (pid: number) => { holdTimerCard(false); cancelSettle(); setDragPid(pid); setDragOrder(stopIds); setDragSeconds(dragPreviewSeconds(stopIds)); }; const previewStopDrag = (overPid: number) => { const moved = dragPid; if (moved === null || moved === overPid) return; const base = dragOrder || stopIds; const next = orderAfterMove(base, moved, overPid); if (next === base) return; setDragOrder(next); setDragSeconds(dragPreviewSeconds(next)); }; const endStopDrag = () => { setDragPid(null); setDragOrder(null); setDragSeconds(null); }; const dropStopDrag = (target: MapRouteDto, overPid: number) => { const moved = dragPid; const order = moved === null ? null : orderAfterMove(dragOrder || stopIds, moved, overPid); endStopDrag(); if (moved === null || !order) return; const seat = order.indexOf(moved); if (seat < 0 || stopIds[seat] === moved) return; commitStopMove(target, moved, String(seat + 1)); scheduleSettle(order.filter((pid) => locatedPids.includes(pid))); }; // A committed hold ends when the move has landed and a new drive time has settled. The timer // bounds it when no new answer comes (a refused move, fewer than two located stops). useEffect(() => { if (!timerHold?.committed) return; if (!busy && !timerBusy && routeAnswer !== null && routeAnswer !== timerHold.from) { setTimerHold(null); return; } const timer = window.setTimeout(() => setTimerHold(null), 8000); return () => window.clearTimeout(timer); }, [timerHold, busy, timerBusy, routeAnswer]); /** One click fills only the Route's located slots with the optimized located permutation. */ const applyOptimizedOrder = (target: MapRouteDto) => { const answer = routeAnswer; if (!answer || applyBusy) return; const merged = mergeLocatedOrderAtAnchors( stopIds, locatedPids, answer.optimized.ordered, ); const moves = merged && locatedRouteMovePlan(stopIds, merged, locatedPids); if (!merged || !moves) { setTimerError("The faster order no longer matches this Route's located stops."); return; } setApplyBusy(true); setTimerError(null); void (async () => { let failed = false; for (const move of moves) { const message = await onMoveToOrder(target, move.pid, move.position); if (message) { setTimerError(message); failed = true; break; } } setApplyBusy(false); if (!failed) scheduleSettle(answer.optimized.ordered); })(); }; const dragging = dragOrder !== null; const timerSaving = routeAnswer ? routeSaving(routeAnswer) : null; const timerCaveats = routeAnswer ? routeCaveats(routeAnswer) : []; const shownSeconds = dragging ? dragSeconds : dragPreviewSeconds(stopIds); const settledLabel = routeAnswer ? routeTimeLabel(routeAnswer.current) : null; const estimateLabel = shownSeconds === null ? null : `${formatSeconds(shownSeconds)} estimated`; const timerLabel = !dragging && settledLabel ? settledLabel : estimateLabel; const timerTone = !dragging && routeAnswer ? routeTimeTone(routeAnswer.current) : "estimated"; /* ═════════ W51-T28 / C8 — ESCAPE BACKS OUT OF AN OPEN SAVED ROUTE ══════════════════════ * * ⭐ THE LADDER THIS COMPLETES, TOP DOWN: the kit dialog, then the open Route, then the map * NAVIGATOR itself. The third rung is genuinely unreachable from this file and from MapView: * `mapNavigator === "routes"` is `routePanelOpen && !zoneNavigatorOpen`, and `routePanelOpen` * is `useState` in `CustomerGrid.tsx:3206` handed down as a read-only prop with no close * callback and no event channel. An optional prop nobody passes, or a client-side emit with no * listener, would each look exactly like a working close to a source scan while doing nothing * at all, so neither is here and no gate leg claims the rung. * * ⛔ THE CLAIM IS DROPPED WHILE THE TITLE IS BEING RENAMED, and that is not fussiness. The * arbiter's listener is CAPTURE PHASE on `document` and calls `stopPropagation`, so it runs * ahead of React's own handlers and the rename input's `Escape`-cancels-the-draft would simply * never fire again. Standing down while `titleDraft` is live leaves that behaviour exactly as * it shipped, and one Escape still means one close everywhere else. * * ⛔ `!deleteConfirm` IS THE SAME RULE APPLIED TO THE OTHER LIVE OVERLAY IN THIS PANEL. The * inline `role="alertdialog"` delete confirm below does not register with the arbiter and is * deliberately left as it is, because `verify_w44_map_routes.py`'s `route-update-delete` leg * pins that markup. Without this term Escape would resolve past it and close the whole Route * out from under an open confirm, which is a behaviour this ticket would have INTRODUCED. * ⚠ AND IT IS REACHED, THOUGH A GREP SAYS OTHERWISE. `grep deleteConfirm` finds no setter, * because the setter is `setDeleteConfirm` and the capital D breaks the substring; `Delete * Route` calls it, so that confirm really does open. * * ⚠ `cancelEditFirst` STAYS FALSE, matching the two Zone panels. One press, one close, which is * what every other overlay in this app already does. */ const backToRoutes = useCallback(() => onActiveRouteChange(null), [onActiveRouteChange]); useEscapeClose(route !== null && titleDraft === null && !deleteConfirm, backToRoutes); /* ═════════ W54-T21 / D-673 — THE RUNGS THAT USED TO BE COVERED BY SILENCE ═══════════════ * * ⛔⛔ THE STAND-DOWNS ABOVE ONLY WORKED WHILE NOTHING ELSE CLAIMED ESCAPE. Standing down means * "let the key fall through", and until this ticket it fell through to NOBODY, so React's own * handlers on the rename input and the search box still saw it and the delete confirm simply * ignored the press. D-673 puts a claim UNDERNEATH this whole panel - `CustomerGrid.tsx` closes * the navigator - so a fall-through now closes the entire navigator instead. Every surface the * open Route stands down for therefore has to claim the key itself, or the press it was meant * to reach would take the panel down with it. * * The route's close claim precedes these edit claims so the topmost edit receives Escape. * * ⚠ `renameEscaping` IS THE SAME ORDERING PROBLEM THE SHEET'S FORMULA EDITOR HAS. The arbiter * blurs the focused element before it calls close, and the folder rename input's blur is what * SAVES the new name, so a bare claim would have made Escape commit a rename it was pressed to * cancel. The blur defers its decision by one microtask and this flag, raised by the close, * wins that race by construction rather than by luck. * * ⚠ THE QUERY RUNG IS THE ONE BEHAVIOUR CHANGE, AND IT IS THE SMALL ONE. Escape with a typed * route filter clears the filter and leaves the panel open, which is what the box's own * handler always did; with the box empty there is nothing to clear and the press reaches the * navigator's close. The box keeps its own handler because `verify_map.py` pins it. */ useEscapeClose(titleDraft !== null, () => setTitleDraft(null)); useEscapeClose(deleteConfirm, () => setDeleteConfirm(false)); useEscapeClose(renameId !== null, () => { renameEscaping.current = true; setRenameId(null); }); useEscapeClose(routeQuery !== "", () => setRouteQuery("")); const routeDetail = () => { if (!route) return null; // ⭐ W46-T25 / RULING R2's guard stood here: a Route projected from a legacy `route_order` // column was refused until an administrator migrated it, because unlocking an unmigrated one // would leave two divergent copies. R2's order was migrate, verify, unlock, delete — and it // has now run to the end on every tenant schema, so there is no unmigrated Route left to // refuse and no legacy column left behind one. const canEdit = route.permission.canEdit; // ⚠ POSITIONS ARE READ OFF THE LIST THE PERSON IS LOOKING AT. Earlier, Later and the typed // Position box are all ordinal, and `routeStopMovePlan` validates against the ids it is // handed, so a just-removed stop still counted here would make every arrow below it move the // wrong stop for as long as the host had not refetched. const stopView: MapRouteDto = { ...route, visibleStopIds: stopIds }; const editActionReason = !canEdit ? "Only the owner or an editor of the source View can change this Route." : busy ? "Wait for the current Route update to finish." : null; const applyActionReason = editActionReason || (applyBusy ? "The faster order is being applied." : locatedPids.length < 2 ? "Add map locations to at least two stops before optimizing." : timerBusy ? "The located stops are still being measured." : !routeAnswer ? "A measured route is needed before a faster order can be applied." : !timerSaving?.offer ? "The current located order is already the fastest measured order." : null); // ⚠ THE LIST SHOWS THE DRAG, THE ROUTE STILL HOLDS THE SAVED ORDER. `stopView` above is // built from `stopIds` on purpose: a drop is validated against the order the server last // confirmed, never against the arrangement being previewed on screen. const displayIds = dragOrder || stopIds; // ⚠ THE SAVED ORDER, NOT THE DRAG PREVIEW. A sheet handed to a rep states what the Route // IS, and `stopIds` is the order the server last confirmed. `routeStopIdentity` is passed in so // the name on paper is the same function as the name on screen, and every stop is on the // page whether or not it has a coordinate. const printStops = routePrintStops( stopIds, stopLabels, stopCoords, (label, pid) => routeStopIdentity(label, pid, stopLabelErrors[pid]), reversePrintLabels, ); // ⚠ THE NAME HAS EXACTLY ONE WRITER NOW. `Save` below sends only the Maps URL, so an // abandoned draft in the title can never be committed by a control that says nothing about // names, and a saved rename can never be overwritten by a stale copy of the old one. const commitRouteRename = () => { const next = (titleDraft || "").trim(); if (!next || busy) return; if (next === route.name) { setTitleDraft(null); return; } setBusy(true); void onUpdate(route, { name: next }).then((message) => { setError(message); if (!message) setTitleDraft(null); }).finally(() => setBusy(false)); }; return (
{/* ── W46-T23 / INSTRUCTION 19: THE ONE PLACE A ROUTE IS RENAMED. ────────────── It used to be two: the row menu on the list, and a "Route name" box buried in the edit block far below. Both are gone. The title itself turns into the field, so what a person reads when they are not renaming is still a title. */}