diff --git "a/web/src/customer-grid/MapView.tsx" "b/web/src/customer-grid/MapView.tsx" --- "a/web/src/customer-grid/MapView.tsx" +++ "b/web/src/customer-grid/MapView.tsx" @@ -92,7 +92,21 @@ import { zoomLimits, } from "./mapProjection"; import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection"; -import { LP_INK, LP_MAP_SELECTED } from "./theme"; +import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP } from "./theme"; +import { RouteNav } from "./RouteNav"; +import { normalizedRouteMapLinks } from "./routeLinks"; +import { + requestRouteDelivery, + usesNormalizedCustomerZones, + zoneCollectionPath, + zoneItemPath, + zoneMutationPayload, +} from "./routeZoneApi"; +import { mapNavigatorMode, normalizedZoneZipCodes, routeSourceStopIds, toggleRouteSelection, zoneMembershipPids } from "./routeZoneTypes"; +import type { + MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto, + RouteDeliveryDto, RouteDeliveryRequest, RouteSelectionRequest, RouteSelectionResponse, +} from "./routeZoneTypes"; import "./map.css"; /** @@ -293,14 +307,15 @@ interface RouteDepot { } /** - * The pin palette: C1's cycle (blue -> green -> yellow -> red) then its + * The Map starts in the Group-purple family. Colour-by retains its distinct + * series after that first default, while an unencoded point never regresses to blue. * 20%-darkened variants, exactly as the contract specifies for series colour. * `fill` is the pastel; `line` is a darker companion, because a C1 pastel * measures 1.4-1.9:1 on white and a fill alone would be a smudge (the same * measurement that drove the I7c amendment). */ const SERIES: { fill: string; line: string }[] = [ - { fill: "#9DBFF2", line: "#5F7FB0" }, + { fill: LP_PURPLE, line: LP_PURPLE_DEEP }, { fill: "#A5D8B4", line: "#5E9C74" }, { fill: "#F5D989", line: "#B39A46" }, { fill: "#F0A8A0", line: "#B76D65" }, @@ -312,9 +327,9 @@ const SERIES: { fill: string; line: string }[] = [ /** Anything past the palette, plus the blank bucket. Neutral ON PURPOSE: a * ninth colour that repeats the first would make two meanings look identical. */ const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" }; -const DEFAULT_PIN = { fill: "#9DBFF2", line: "#4F6079" }; +const DEFAULT_PIN = { fill: LP_PURPLE, line: LP_PURPLE_DEEP }; const ZONE_COLOR_CHOICES = [ - { value: "#9DBFF2", label: "Blue" }, + { value: LP_PURPLE, label: "Purple" }, { value: "#A5D8B4", label: "Green" }, { value: "#F5D989", label: "Yellow" }, { value: "#F0A8A0", label: "Red" }, @@ -344,39 +359,14 @@ export function translateZoneGeometry( /** C3's durable map-domain DTO. Zones are not generic fields: geometry, visibility and the * membership snapshot only make sense to this projection. */ -interface MapZone { - id: string; - name: string; - color: string; - geometryGeoJson: ZoneGeometry; - visible: boolean; - geographicField: string; - memberships: number[]; - createdBy?: string; - createdAt?: string; -} +type MapZone = MapZoneDto; interface ZoneMove { zone: MapZone; + geometry: ZoneGeometry; start: Pt; } -interface RouteDelivery { - id: string; - name: string; - recipient: string; - schedule: { cron?: string; enabled?: boolean }; - snapshot: { - sourceViewId: string; - sourceViewRevision: string; - sourceViewName: string; - timezone: string; - routeField: string; - orderedStopIds: number[]; - mapsPerLink: number; - }; -} - /** Immutable provenance supplied by the host grid for a scheduled route snapshot. */ export interface RouteSourceView { id: string; @@ -431,6 +421,8 @@ export function MapView({ allRows, activeView, tableKey, + onManagedRouteViewState, + onZoneChanged, }: { /** DISTINCT data rows from the full pipeline, overlay edits layered — the * calendar/kanban contract, verbatim. */ @@ -472,6 +464,11 @@ export function MapView({ activeView: RouteSourceView | null; /** Canonical database identity for durable, table-scoped Zones. */ tableKey: string; + /** C2 handoff: the server alone returns the managed route-membership clause. */ + onManagedRouteViewState?: (viewState: Record) => void; + /** Customer Zones also project into the read-only grid field, so a successful normalized + * mutation invalidates the host row payload instead of leaving that projection stale. */ + onZoneChanged?: () => void; /** * ⭐⭐ OWNER ITEM 9 — THE WHOLE BOOK, so a stop can be added that the VIEW filtered out. * @@ -489,7 +486,6 @@ export function MapView({ const [routeOn, setRouteOn] = useState(false); /** Route navigation is an index first; planning begins only after the explicit Create route * action or an existing saved route has been opened. */ - const [routeCreateOpen, setRouteCreateOpen] = useState(false); const [roundTrip, setRoundTrip] = useState(false); const [routeStartPid, setRouteStartPid] = useState(null); const askRoadRef = useRef(false); @@ -533,18 +529,58 @@ export function MapView({ /** C3 Zone chooser/editor state. `null` means the tenant read has not answered; an empty * array is an honest, editable no-Zones state. */ const [zones, setZones] = useState(null); + /** C2 named-route read model. Legacy route-order columns remain compatibility only. */ + const [namedRoutes, setNamedRoutes] = useState([]); + const [routeFolders, setRouteFolders] = useState([]); + const [createdRoute, setCreatedRoute] = useState(null); + const [selectedRouteIds, setSelectedRouteIds] = useState>(new Set()); + /** The Route detail is the only pin-edit target. Route selection never chooses it implicitly. */ + const [activeRouteId, setActiveRouteId] = useState(null); + const [routePinPrompt, setRoutePinPrompt] = useState<{ + routeId: string; customerPid: number; title: string; present: boolean; + } | null>(null); + const [routePinNotice, setRoutePinNotice] = useState(null); + const [routePinBusy, setRoutePinBusy] = useState(false); + const [managedRouteViewState, setManagedRouteViewState] = useState | null>(null); + const [routeSelectionWarning, setRouteSelectionWarning] = useState(null); const [activeZoneIds, setActiveZoneIds] = useState>(new Set()); - const [zoneChooserOpen, setZoneChooserOpen] = useState(false); + const [zoneNavigatorOpen, setZoneNavigatorOpen] = useState(false); + const [zoneEditorOpen, setZoneEditorOpen] = useState(false); const [zoneEditorId, setZoneEditorId] = useState(""); const [zoneName, setZoneName] = useState(""); const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value); const [zoneGeographicField, setZoneGeographicField] = useState(""); const [zoneGeographicValue, setZoneGeographicValue] = useState(""); + const [zoneZipCodes, setZoneZipCodes] = useState(""); const [drawnZoneGeometry, setDrawnZoneGeometry] = useState(null); const [zoneMove, setZoneMove] = useState(null); const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null); const [zoneBusy, setZoneBusy] = useState(false); const [zoneErr, setZoneErr] = useState(null); + const normalizedCustomerZones = usesNormalizedCustomerZones(tableKey); + const mapNavigator = mapNavigatorMode(routePanelOpen, zoneNavigatorOpen); + const activeNamedRoute = useMemo( + () => activeRouteId ? namedRoutes.find((route) => route.id === activeRouteId) || null : null, + [activeRouteId, namedRoutes] + ); + useEffect(() => { + setRoutePinPrompt(null); + setRoutePinNotice(null); + }, [activeRouteId]); + useEffect(() => { + if (activeRouteId && !activeNamedRoute) setActiveRouteId(null); + }, [activeNamedRoute, activeRouteId]); + useEffect(() => { + if (routePanelOpen) { + setZoneNavigatorOpen(false); + setZoneEditorOpen(false); + return; + } + setActiveRouteId(null); + setRoutePinPrompt(null); + setRoutePinNotice(null); + setRoutePinBusy(false); + }, [routePanelOpen]); /** * W37-T36 — the ROAD answer, which is the half arithmetic cannot produce. * @@ -598,14 +634,11 @@ export function MapView({ const [routeEditNote, setRouteEditNote] = useState(""); const [routeEditBusy, setRouteEditBusy] = useState(false); const [routeEditErr, setRouteEditErr] = useState(null); - /** C2 keeps this bounded value in every frozen route snapshot. */ - const [mapsPerLink, setMapsPerLink] = useState(10); + /** The legacy on-map planner still chunks a preview at ten stops. Scheduled normalized Routes + * own their independently editable 2-10 choice inside RouteNav. */ + const mapsPerLink = 10; const [routeCopyMsg, setRouteCopyMsg] = useState(null); - const [routeRecipient, setRouteRecipient] = useState(""); - const [routeScheduleBusy, setRouteScheduleBusy] = useState(false); - const [routeScheduleMsg, setRouteScheduleMsg] = useState(null); - const [routeScheduleErr, setRouteScheduleErr] = useState(null); - const [routeDeliveries, setRouteDeliveries] = useState(null); + const [routeDeliveries, setRouteDeliveries] = useState(null); /** Which saved column a save writes to. `""` = a new field, named in the prompt below. */ const [saveTarget, setSaveTarget] = useState(""); /** @@ -623,7 +656,7 @@ export function MapView({ * wall, reported as `mine`). Collapsing them into one control would either offer a Save that * earns a 403 or hide a route the person is allowed to read. */ - const [openedRoute, setOpenedRoute] = useState(""); + const [, setOpenedRoute] = useState(""); const [openErr, setOpenErr] = useState(null); /** * ⭐⭐ OWNER ITEM 5 (2026-08-23) — THE NAME IS ASKED FOR, AND ITS DEFAULT COMES FROM THE SERVER. @@ -826,7 +859,7 @@ export function MapView({ const loadZones = useCallback(async () => { try { - const res = await fetch(`/api/v1/geo/zones?tableKey=${encodeURIComponent(tableKey)}`, { + const res = await fetch(zoneCollectionPath(tableKey), { credentials: "same-origin", }); const body = res.ok ? await res.json().catch(() => null) : null; @@ -836,6 +869,223 @@ export function MapView({ } }, [tableKey]); useEffect(() => { void loadZones(); }, [loadZones]); + const visibleRoutePids = useMemo( + () => [...new Set(rows.map((row) => row.pid))].sort((a, b) => a - b).join(","), + [rows] + ); + const loadNamedRoutes = useCallback(async () => { + try { + const res = await fetch(`/api/v1/customers/routes?visiblePids=${encodeURIComponent(visibleRoutePids)}`, { + credentials: "same-origin", + }); + const body = res.ok ? await res.json().catch(() => null) : null; + if (Array.isArray(body?.routes)) setNamedRoutes(body.routes); + if (Array.isArray(body?.folders)) setRouteFolders(body.folders); + } catch { /* Keep the last honest Route navigation when a refresh is temporarily unavailable. */ } + }, [visibleRoutePids]); + useEffect(() => { void loadNamedRoutes(); }, [loadNamedRoutes, routePanelOpen]); + useEffect(() => { + // A managed clause belongs to one saved View. Never carry it into another View's authored state. + setManagedRouteViewState(null); + setSelectedRouteIds(new Set()); + setRouteSelectionWarning(null); + }, [activeView?.id]); + const routeFilterSignature = useMemo( + () => JSON.stringify({ filters: activeView?.config?.filters || [], filterConj: activeView?.config?.filterConj || "and" }), + [activeView?.config?.filterConj, activeView?.config?.filters] + ); + const routeFilterSignatureRef = useRef({ viewId: activeView?.id || "", signature: routeFilterSignature }); + useEffect(() => { + const prior = routeFilterSignatureRef.current; + const viewId = activeView?.id || ""; + const changed = prior.viewId === viewId && prior.signature !== routeFilterSignature; + routeFilterSignatureRef.current = { viewId, signature: routeFilterSignature }; + if (!changed || !activeView || selectedRouteIds.size === 0) return; + void (async () => { + try { + const res = await fetch("/api/v1/customers/routes/selection", { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ routeIds: [], viewState: activeView.config as unknown as Record } satisfies RouteSelectionRequest), + }); + const body = await res.json().catch(() => null) as RouteSelectionResponse | null; + if (!res.ok || body?.managedBy !== "loopable" || !body.viewState) throw new Error("managed selection refusal"); + setSelectedRouteIds(new Set()); + setManagedRouteViewState(body.viewState); + onManagedRouteViewState?.(body.viewState); + setRouteSelectionWarning("Route selection cleared because the View filter changed."); + } catch { + setRouteSelectionWarning("Route selection could not be cleared after the View filter changed."); + } + })(); + }, [activeView, onManagedRouteViewState, routeFilterSignature, selectedRouteIds]); + const toggleNamedRoute = useCallback(async (route: MapRouteDto) => { + const isAdding = !selectedRouteIds.has(route.id); + if (isAdding) { + if (route.outsideFilter && !window.confirm(`${route.name} is outside this filter. Include only this route's managed membership group?`)) return; + } + const next = toggleRouteSelection(selectedRouteIds, route.id); + if (!activeView) { + setRouteSelectionWarning("Select a saved View before adding a route inclusion."); + return; + } + const routeIds = [...next]; + try { + const request: RouteSelectionRequest = { + routeIds, + viewState: managedRouteViewState || (activeView.config as unknown as Record), + }; + const res = await fetch("/api/v1/customers/routes/selection", { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify(request), + }); + const body = await res.json().catch(() => null) as RouteSelectionResponse | null; + if (!res.ok || body?.managedBy !== "loopable" || !body.viewState) { + setRouteSelectionWarning(body && "error" in body ? String((body as { error?: { message?: string } }).error?.message || "Route inclusion could not be changed.") : "Route inclusion could not be changed."); + return; + } + setSelectedRouteIds(next); + setManagedRouteViewState(body.viewState); + onManagedRouteViewState?.(body.viewState); + setRouteSelectionWarning(route.outsideFilter && next.has(route.id) ? `${route.name} is included through its managed route group.` : null); + const pids = namedRoutes.filter((item) => next.has(item.id)).flatMap((item) => item.visibleStopIds); + onSelectPids([...new Set(pids)], "add"); + } catch { setRouteSelectionWarning("Route inclusion could not be changed."); } + }, [activeView, managedRouteViewState, namedRoutes, onManagedRouteViewState, onSelectPids, selectedRouteIds]); + const moveNamedRouteStop = useCallback(async (route: MapRouteDto, customerPid: number, order: number): Promise => { + try { + const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/stops/move`, { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ customerPid, order }), + }); + const body = await res.json().catch(() => null); + if (res.status === 409 && body?.error?.code === "no_route_stop") return "This route has no matching stop to move."; + if (!res.ok) return body?.error?.message || "The stop order could not be changed."; + const routeUpdate = body?.route as MapRouteDto | undefined; + if (routeUpdate) setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id + ? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder } + : item)); + return null; + } catch { return "The stop order could not be changed."; } + }, []); + + const updateNamedRoute = useCallback(async ( + route: MapRouteDto, patch: MapRouteUpdate + ): Promise => { + if (!route.permission.canEdit || route.compatibility === "legacy-route-order") + return "This Route is read-only."; + try { + const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, { + method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify(patch), + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be updated."; + const routeUpdate = body?.route as MapRouteDto | undefined; + if (!routeUpdate) return "The Route update returned no Route."; + setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id + ? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder } + : item)); + return null; + } catch { return "The Route could not be updated."; } + }, []); + + const deleteNamedRoute = useCallback(async (route: MapRouteDto): Promise => { + if (!route.permission.canEdit || route.compatibility === "legacy-route-order") + return "This Route is read-only."; + try { + const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, { + method: "DELETE", credentials: "same-origin", + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be deleted."; + + const nextSelected = new Set(selectedRouteIds); + const removedSelection = nextSelected.delete(route.id); + setNamedRoutes((current) => current.filter((item) => item.id !== route.id)); + setCreatedRoute((current) => current?.id === route.id ? null : current); + setSelectedRouteIds(nextSelected); + if (activeRouteId === route.id) setActiveRouteId(null); + setRoutePinPrompt(null); + setRoutePinNotice(null); + + if (removedSelection && activeView) { + try { + const selectionRes = await fetch("/api/v1/customers/routes/selection", { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + routeIds: [...nextSelected], + viewState: managedRouteViewState || (activeView.config as unknown as Record), + } satisfies RouteSelectionRequest), + }); + const selectionBody = await selectionRes.json().catch(() => null) as RouteSelectionResponse | null; + if (!selectionRes.ok || selectionBody?.managedBy !== "loopable" || !selectionBody.viewState) + throw new Error("managed selection refusal"); + setManagedRouteViewState(selectionBody.viewState); + onManagedRouteViewState?.(selectionBody.viewState); + setRouteSelectionWarning(null); + } catch { + setRouteSelectionWarning("The Route was deleted, but its View inclusion could not be cleared."); + } + } + return null; + } catch { return "The Route could not be deleted."; } + }, [activeRouteId, activeView, managedRouteViewState, onManagedRouteViewState, selectedRouteIds]); + + const requestRoutePinMembership = useCallback((customerPid: number, title: string) => { + setRoutePinNotice(null); + if (!activeNamedRoute) { + setRoutePinPrompt(null); + setRoutePinNotice("Open a route first."); + return; + } + if (!activeNamedRoute.permission.canEdit || activeNamedRoute.compatibility === "legacy-route-order") { + setRoutePinPrompt(null); + setRoutePinNotice("This Route is read-only."); + return; + } + const isMember = activeNamedRoute.visibleStopIds.includes(customerPid); + setRoutePinPrompt({ + routeId: activeNamedRoute.id, + customerPid, + title: title || `Record ${customerPid}`, + present: !isMember, + }); + }, [activeNamedRoute]); + + const confirmRoutePinMembership = useCallback(async () => { + const prompt = routePinPrompt; + if (!prompt || routePinBusy) return; + setRoutePinBusy(true); + setRoutePinNotice(null); + try { + const res = await fetch( + `/api/v1/customers/routes/${encodeURIComponent(prompt.routeId)}/stops/membership`, + { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ customerPid: prompt.customerPid, present: prompt.present }), + } + ); + const body = await res.json().catch(() => null); + if (!res.ok) { + setRoutePinNotice(body?.error?.message || body?.detail?.message || "The Route stop could not be changed."); + return; + } + const routeUpdate = body?.route as MapRouteDto | undefined; + if (!routeUpdate) { + setRoutePinNotice("The Route stop update returned no Route."); + return; + } + setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id + ? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder } + : item)); + setRoutePinPrompt(null); + setRoutePinNotice(`${prompt.title} was ${prompt.present ? "added to" : "removed from"} ${routeUpdate.name}.`); + } catch { + setRoutePinNotice("The Route stop could not be changed."); + } finally { + setRoutePinBusy(false); + } + }, [routePinBusy, routePinPrompt]); const activeZones = useMemo( () => (zones || []).filter((zone) => zone.visible && activeZoneIds.has(zone.id)), @@ -846,10 +1096,157 @@ export function MapView({ for (const zone of activeZones) for (const pid of zone.memberships || []) pids.add(pid); return pids; }, [activeZones]); + const routeSources = useMemo(() => [ + { id: "selection", label: "Current selection", pids: routeSourceStopIds(selectedPids) }, + { id: "zones", label: "Selected Zones", pids: routeSourceStopIds(activeZonePids) }, + ], [activeZonePids, selectedPids]); + const createNamedRoute = useCallback(async (name: string, source: MapRouteSource): Promise => { + if (!activeView) return "Select a saved View before creating a Route."; + if (!source.pids.length) return "Choose a Route source with at least one customer."; + try { + const res = await fetch("/api/v1/customers/routes", { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name, stops: source.pids, sourceViewId: activeView.id }), + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || "The Route could not be created."; + if (body?.route) { + setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.navOrder - b.navOrder)); + setCreatedRoute(body.route as MapRouteDto); + await loadNamedRoutes(); + } + return null; + } catch { return "The Route could not be created."; } + }, [activeView, loadNamedRoutes]); + const duplicateNamedRoute = useCallback(async (route: MapRouteDto): Promise => { + try { + const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/duplicate`, { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name: `${route.name} copy` }), + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be duplicated."; + if (!body?.route) return "The duplicate returned no Route."; + setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.navOrder - b.navOrder)); + setCreatedRoute(body.route as MapRouteDto); + await loadNamedRoutes(); + return null; + } catch { return "The Route could not be duplicated."; } + }, [loadNamedRoutes]); + const shareNamedRoute = useCallback(async (route: MapRouteDto): Promise => { + if (!route.permission.canEdit || route.compatibility === "legacy-route-order") + return "Only the Route owner can share this Route."; + try { + const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/share-ready`, { + method: "POST", credentials: "same-origin", + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "Sharing could not be opened."; + window.dispatchEvent(new CustomEvent("aios:share-open", { + detail: { kind: body?.kind || "field", id: body?.id || route.shareId, label: body?.label || route.name }, + })); + return null; + } catch { return "Sharing could not be opened."; } + }, []); + const moveNamedRoute = useCallback(async (route: MapRouteDto, folderId: string | null): Promise => { + try { + const res = await fetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/folder`, { + method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ folderId }), + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be moved."; + if (body?.route) setNamedRoutes((current) => current.map((item) => item.id === route.id ? body.route : item)); + if (Array.isArray(body?.folders)) setRouteFolders(body.folders); + return null; + } catch { return "The Route could not be moved."; } + }, []); + const reorderNamedRoutes = useCallback(async (order: string[]): Promise => { + try { + const res = await fetch("/api/v1/customers/routes/reorder", { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ order }), + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route order could not be saved."; + await loadNamedRoutes(); + return null; + } catch { return "The Route order could not be saved."; } + }, [loadNamedRoutes]); + const createNamedRouteFolder = useCallback(async (name: string, parent: string | null): Promise => { + try { + const res = await fetch("/api/v1/customers/route-folders", { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name, parent }), + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be created."; + if (Array.isArray(body?.folders)) setRouteFolders(body.folders); + return null; + } catch { return "The folder could not be created."; } + }, []); + const updateNamedRouteFolder = useCallback(async ( + folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null } + ): Promise => { + try { + const res = await fetch(`/api/v1/customers/route-folders/${encodeURIComponent(folder.id)}`, { + method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify(patch), + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be updated."; + if (Array.isArray(body?.folders)) setRouteFolders(body.folders); + return null; + } catch { return "The folder could not be updated."; } + }, []); + const deleteNamedRouteFolder = useCallback(async (folder: MapRouteFolderDto): Promise => { + try { + const res = await fetch(`/api/v1/customers/route-folders/${encodeURIComponent(folder.id)}`, { + method: "DELETE", credentials: "same-origin", + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be deleted."; + if (Array.isArray(body?.folders)) setRouteFolders(body.folders); + await loadNamedRoutes(); + return null; + } catch { return "The folder could not be deleted."; } + }, [loadNamedRoutes]); + const reorderNamedRouteFolders = useCallback(async (order: string[]): Promise => { + try { + const res = await fetch("/api/v1/customers/route-folders/reorder", { + method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ order }), + }); + const body = await res.json().catch(() => null); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder order could not be saved."; + await loadNamedRoutes(); + return null; + } catch { return "The folder order could not be saved."; } + }, [loadNamedRoutes]); const zoneEditor = useMemo( () => (zones || []).find((zone) => zone.id === zoneEditorId) || null, [zones, zoneEditorId] ); + const beginNewZone = useCallback(() => { + setZoneEditorId(""); + setZoneName(""); + setZoneColor(ZONE_COLOR_CHOICES[0].value); + setZoneZipCodes(""); + setDrawnZoneGeometry(null); + setZoneErr(null); + setZoneEditorOpen(true); + }, []); + const beginEditZone = useCallback((zone: MapZone) => { + setZoneEditorId(zone.id); + setZoneName(zone.name); + setZoneColor(zone.color); + setZoneGeographicField(zone.geographicField || ""); + setZoneGeographicValue(""); + setZoneZipCodes((zone.zipCodes || []).join(", ")); + setDrawnZoneGeometry(null); + setZoneErr(null); + setZoneEditorOpen(true); + }, []); /** * Zone visibility is a checkbox chooser, not a ctrl-click native multi-select. A toggle also * immediately projects the Zone's durable membership onto the grid selection; removing one @@ -869,25 +1266,21 @@ export function MapView({ else for (const pid of zone.memberships || []) if (!stillHeld.has(pid)) selection.delete(pid); onSelectPids([...selection], "replace"); setActiveZoneIds(next); - if (checked) { - setZoneEditorId(zone.id); - setZoneName(zone.name); - setZoneColor(zone.color); - setZoneGeographicField(zone.geographicField || ""); - } }, [activeZoneIds, zones, selectedPids, onSelectPids]); const zonePolygons = useMemo(() => activeZones.flatMap((zone) => { const geometry = zoneGeometryDraft?.id === zone.id ? zoneGeometryDraft.geometry : zone.geometryGeoJson; - const polygons = geometry?.type === "Polygon" + if (!geometry) return []; + const polygons = geometry.type === "Polygon" ? [geometry.coordinates as number[][][]] - : geometry?.type === "MultiPolygon" + : geometry.type === "MultiPolygon" ? geometry.coordinates as number[][][][] : []; return polygons.flatMap((polygon, polygonIndex) => polygon.map((ring, ringIndex) => ({ key: `${zone.id}:${polygonIndex}:${ringIndex}`, zone, + geometry, points: ring .filter((pair) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1])) .map((pair) => project(pair[0], pair[1])), @@ -912,28 +1305,36 @@ export function MapView({ }, [drawnZoneGeometry, points, selectedPids]); const saveZone = useCallback(async (existing?: MapZone) => { - const geometryGeoJson = selectionZoneGeometry(); + const geometryGeoJson = drawnZoneGeometry || existing?.geometryGeoJson || selectionZoneGeometry(); const name = zoneName.trim() || existing?.name || ""; - if (!name || !geometryGeoJson) { - setZoneErr("Name a Zone and draw or select at least two mapped records first."); + const zipCodes = normalizedZoneZipCodes(zoneZipCodes); + if (!name || (!geometryGeoJson && zipCodes.length === 0)) { + setZoneErr("Name a Zone and add a boundary or at least one ZIP code."); return; } + if (normalizedCustomerZones && !existing && !activeView?.id) { + setZoneErr("Open a saved View before creating a Customer Zone."); + return; + } + const memberships = zoneMembershipPids( + selectedPids, allRows || mapRows, zipCodes, zoneGeographicField + ); setZoneBusy(true); setZoneErr(null); try { - const res = await fetch(existing ? `/api/v1/geo/zones/${encodeURIComponent(existing.id)}` : "/api/v1/geo/zones", { + const res = await fetch(existing ? zoneItemPath(tableKey, existing.id) : zoneCollectionPath(tableKey), { method: existing ? "PATCH" : "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - tableKey, + body: JSON.stringify(zoneMutationPayload(tableKey, existing?.sourceViewId || activeView?.id || null, { name, color: zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value, geometryGeoJson, visible: existing?.visible ?? true, geographicField: zoneGeographicField, - memberships: [...selectedPids], - }), + zipCodes, + memberships, + })), }); const body = await res.json().catch(() => null); if (!res.ok) { @@ -946,7 +1347,15 @@ export function MapView({ const without = (current || []).filter((zone) => zone.id !== saved.id); return [...without, saved].sort((a, b) => a.name.localeCompare(b.name)); }); - setActiveZoneIds((current) => new Set([...current, saved.id])); + setActiveZoneIds((current) => { + const next = new Set(current); + if (saved.visible) next.add(saved.id); + else next.delete(saved.id); + return next; + }); + setZoneEditorId(saved.id); + setZoneEditorOpen(false); + if (normalizedCustomerZones) onZoneChanged?.(); } setDrawnZoneGeometry(null); setZoneName(""); @@ -955,17 +1364,19 @@ export function MapView({ } finally { setZoneBusy(false); } - }, [selectionZoneGeometry, zoneName, zoneColor, zoneGeographicField, selectedPids, tableKey]); + }, [drawnZoneGeometry, selectionZoneGeometry, zoneName, zoneColor, zoneGeographicField, + zoneZipCodes, selectedPids, allRows, mapRows, tableKey, normalizedCustomerZones, + activeView?.id, onZoneChanged]); const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => { setZoneBusy(true); setZoneErr(null); try { - const res = await fetch(`/api/v1/geo/zones/${encodeURIComponent(zone.id)}`, { + const res = await fetch(zoneItemPath(tableKey, zone.id), { method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ tableKey, visible }), + body: JSON.stringify(zoneMutationPayload(tableKey, zone.sourceViewId || activeView?.id || null, { visible })), }); const body = await res.json().catch(() => null); if (!res.ok) { @@ -973,24 +1384,30 @@ export function MapView({ return; } const saved = body?.zone as MapZone | undefined; - if (saved) setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item)); + if (saved) { + setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item)); + if (!saved.visible && activeZoneIds.has(saved.id)) toggleZone(zone, false); + if (normalizedCustomerZones) onZoneChanged?.(); + } } catch { setZoneErr("The Zone visibility could not be updated."); } finally { setZoneBusy(false); } - }, [tableKey]); + }, [tableKey, activeZoneIds, toggleZone, activeView?.id, normalizedCustomerZones, onZoneChanged]); /** Persist a direct boundary drag without re-deriving membership from the current selection. */ const persistZoneGeometry = useCallback(async (zone: MapZone, geometryGeoJson: ZoneGeometry) => { setZoneBusy(true); setZoneErr(null); try { - const res = await fetch(`/api/v1/geo/zones/${encodeURIComponent(zone.id)}`, { + const res = await fetch(zoneItemPath(tableKey, zone.id), { method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ tableKey, geometryGeoJson }), + body: JSON.stringify(zoneMutationPayload( + tableKey, zone.sourceViewId || activeView?.id || null, { geometryGeoJson }, + )), }); const body = await res.json().catch(() => null); if (!res.ok) { @@ -998,13 +1415,50 @@ export function MapView({ return; } const saved = body?.zone as MapZone | undefined; - if (saved) setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item)); + if (saved) { + setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item)); + if (normalizedCustomerZones) onZoneChanged?.(); + } } catch { setZoneErr("The Zone boundary could not be saved."); } finally { setZoneBusy(false); } - }, [tableKey]); + }, [tableKey, activeView?.id, normalizedCustomerZones, onZoneChanged]); + + const deleteZone = useCallback(async (zone: MapZone) => { + setZoneBusy(true); + setZoneErr(null); + try { + const generic = !normalizedCustomerZones; + const res = await fetch(zoneItemPath(tableKey, zone.id), { + method: "DELETE", + credentials: "same-origin", + ...(generic ? { + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ tableKey }), + } : {}), + }); + const body = await res.json().catch(() => null); + if (!res.ok) { + setZoneErr(body?.error?.message || body?.detail?.message || "The Zone could not be deleted."); + return; + } + setZones((current) => (current || []).filter((item) => item.id !== zone.id)); + setActiveZoneIds((current) => { + const next = new Set(current); + next.delete(zone.id); + return next; + }); + setZoneEditorId(""); + setZoneEditorOpen(false); + if (normalizedCustomerZones) onZoneChanged?.(); + } catch { + setZoneErr("The Zone could not be deleted."); + } finally { + setZoneBusy(false); + } + }, [normalizedCustomerZones, onZoneChanged, tableKey]); // The fit is the INITIAL view, not the projection (see mapProjection.ts). const fit = useMemo( @@ -1160,6 +1614,27 @@ export function MapView({ [] ); + const activeRouteMaps = useMemo(() => { + if (!activeNamedRoute) return { links: [], missingStopIds: [], refusal: null }; + const wanted = new Set(activeNamedRoute.visibleStopIds); + const located = [] as { pid: number; lat: number; lon: number }[]; + for (const row of (allRows?.length ? allRows : mapRows)) { + if (!wanted.has(row.pid)) continue; + const at = coordField + ? parseLatLon(row[coordField.key]) + : (() => { + const lat = coord(row.lat); + const lon = coord(row.lon); + return lat == null || lon == null || !isPlottable(lat, lon) ? null : { lat, lon }; + })(); + if (at) located.push({ pid: row.pid, lat: at.lat, lon: at.lon }); + } + return normalizedRouteMapLinks(activeNamedRoute.visibleStopIds, located, coarsePointer); + }, [activeNamedRoute, allRows, coarsePointer, coordField, mapRows]); + const activeRouteMapsRefusal = activeRouteMaps.missingStopIds.length + ? `${activeRouteMaps.missingStopIds.length.toLocaleString()} Route stop${activeRouteMaps.missingStopIds.length === 1 ? " has" : "s have"} no map location. Add coordinates before opening Maps links.` + : activeRouteMaps.refusal; + /** Selected pins that can actually be routed, in a STABLE order (by pid) — * a Set's iteration order must not be what decides a route. */ const customerRoutable = useMemo( @@ -1447,13 +1922,16 @@ export function MapView({ } }, []); - const loadRouteDeliveries = useCallback(async () => { + const loadRouteDeliveries = useCallback(async (routeId: string): Promise => { try { - const res = await fetch("/api/v1/customers/route-deliveries", { credentials: "same-origin" }); + const res = await fetch( + `/api/v1/customers/routes/${encodeURIComponent(routeId)}/deliveries`, + { credentials: "same-origin" }, + ); const body = res.ok ? await res.json().catch(() => null) : null; - setRouteDeliveries(Array.isArray(body?.deliveries) ? body.deliveries : []); + return Array.isArray(body?.deliveries) ? body.deliveries : []; } catch { - setRouteDeliveries([]); + return []; } }, []); @@ -1466,8 +1944,13 @@ export function MapView({ if ((routePanelOpen || routeOn) && routeCols === null) void loadRouteCols(); }, [routePanelOpen, routeOn, routeCols, loadRouteCols]); useEffect(() => { - if (routePanelOpen && routeDeliveries === null) void loadRouteDeliveries(); - }, [routePanelOpen, routeDeliveries, loadRouteDeliveries]); + let current = true; + setRouteDeliveries(null); + if (routePanelOpen && activeRouteId) void loadRouteDeliveries(activeRouteId).then((deliveries) => { + if (current) setRouteDeliveries(deliveries); + }); + return () => { current = false; }; + }, [activeRouteId, loadRouteDeliveries, routePanelOpen]); const updateRouteDetails = useCallback(async () => { if (!routeEditKey || !routeEditName.trim()) return; @@ -1511,58 +1994,35 @@ export function MapView({ } }, [plan]); - const scheduleRouteDelivery = useCallback(async () => { - if (!plan || !routeRecipient.trim()) return; - if (!activeView?.id) { - setRouteScheduleErr("Open a saved View before scheduling a route."); - return; - } - const orderedStopIds = plan.ordered.map((point) => point.pid).filter((pid) => pid > 0); - if (orderedStopIds.length < 2) return; - setRouteScheduleBusy(true); - setRouteScheduleErr(null); - setRouteScheduleMsg(null); + const scheduleNamedRouteDelivery = useCallback(async ( + route: MapRouteDto, + request: RouteDeliveryRequest, + ): Promise => { + const result = await requestRouteDelivery(route.id, request); + if (result.error || !result.delivery) return result.error || "The Route delivery was not saved."; + setRouteDeliveries((current) => [...(current || []).filter( + (delivery) => delivery.id !== result.delivery!.id + ), result.delivery!]); + return null; + }, []); + + const deleteNamedRouteDelivery = useCallback(async ( + route: MapRouteDto, + delivery: RouteDeliveryDto, + ): Promise => { try { - const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; - const res = await fetch("/api/v1/customers/route-deliveries", { - method: "POST", - credentials: "same-origin", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - name: openedRoute - ? `${(routeCols || []).find((route) => route.key === openedRoute)?.label || "Route"} delivery` - : "Scheduled route", - recipient: routeRecipient.trim(), - schedule: { cron: "0 8 * * *", enabled: true }, - routeSnapshot: { - // This route's stop ids are frozen below. The View config is only a compare guard: - // the API resolves this saved View and mints the durable revision itself. - sourceViewId: activeView.id, - sourceViewConfig: activeView.config, - sourceViewName: activeView.name, - timezone, - routeField: saveTarget || openedRoute, - orderedStopIds, - mapsPerLink, - }, - }), - }); + const res = await fetch( + `/api/v1/customers/routes/${encodeURIComponent(route.id)}/deliveries/${encodeURIComponent(delivery.id)}`, + { method: "DELETE", credentials: "same-origin" }, + ); const body = await res.json().catch(() => null); - if (!res.ok) { - setRouteScheduleErr(body?.error?.message || "The route schedule could not be saved."); - return; - } - setRouteScheduleMsg(`Scheduled ${orderedStopIds.length.toLocaleString()} frozen stops to ${routeRecipient.trim()} each day at 08:00.`); - setRouteDeliveries((current) => { - const delivery = body?.delivery as RouteDelivery | undefined; - return delivery ? [...(current || []), delivery] : current; - }); + if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route delivery could not be removed."; + setRouteDeliveries((current) => (current || []).filter((item) => item.id !== delivery.id)); + return null; } catch { - setRouteScheduleErr("The route schedule could not be saved."); - } finally { - setRouteScheduleBusy(false); + return "The Route delivery could not be removed."; } - }, [plan, routeRecipient, openedRoute, routeCols, activeView, saveTarget, mapsPerLink]); + }, []); /** * ⭐⭐ OWNER, 2026-08-23 — **OPEN A SAVED ROUTE AND SEE IT ON THE MAP.** @@ -1913,6 +2373,18 @@ export function MapView({ [plan] ); + // The legacy route-order calculation remains available to the existing map drawing and data + // migration code, but its second navigator is deliberately gone. Keep these compatibility + // hooks live until route-order columns are retired server-side; none renders a second Route UI. + void [ + formatDuration, ROUTE_STOP_CAP, RecordPicker, setRoundTrip, setDepot, setTravelMode, travelModes, + roadBusy, roadErr, routeEditBusy, routeEditErr, routeCopyMsg, + openErr, naming, nameDraft, setNameDraft, + saveBusy, saveMsg, saveErr, selectFilteredRouteRecords, unroutable, unroutableNames, + updateRouteDetails, copyRouteLinks, openSavedRoute, saveRouteOrder, + orderStale, removeStop, addRecord, addableRecords, moveStop, + ]; + const paint = useCallback( (p: MapPoint) => { if (!colorBuckets) return DEFAULT_PIN; @@ -2091,7 +2563,7 @@ export function MapView({ const current = unproject(fromScreen({ x, y }, view)); setZoneGeometryDraft({ id: zoneMove.zone.id, - geometry: translateZoneGeometry(zoneMove.zone.geometryGeoJson, { + geometry: translateZoneGeometry(zoneMove.geometry, { lon: current.lon - origin.lon, lat: current.lat - origin.lat, }), @@ -2196,6 +2668,19 @@ export function MapView({ [onSelectPids, selectedPids] ); + const pinAriaLabel = useCallback((point: MapPoint) => { + const title = point.title || "Untitled record"; + const selectionHint = "Shift-click or press Space to select."; + if (!routePanelOpen) + return `${title}. Click or press Enter to open the record. ${selectionHint}`; + if (!activeNamedRoute) + return `${title}. Routes are open. Open a route first. ${selectionHint}`; + if (!activeNamedRoute.permission.canEdit || activeNamedRoute.compatibility === "legacy-route-order") + return `${title}. ${activeNamedRoute.name} is read-only. ${selectionHint}`; + const action = activeNamedRoute.visibleStopIds.includes(point.pid) ? "remove" : "add"; + return `${title}. Plain click or Enter asks to ${action} this stop ${action === "add" ? "to" : "from"} ${activeNamedRoute.name}. ${selectionHint}`; + }, [activeNamedRoute, routePanelOpen]); + const onPointerUp = useCallback( (e: ReactPointerEvent) => { if (zoneMove) { @@ -2399,6 +2884,28 @@ export function MapView({ )} + {zones !== null && ( + + )} {/* ═══════════════════════════════════════════════════════════════════════════════════ THE ROUTE PANEL — rebuilt for owner items 2, 4, 6, 8 and 9. @@ -2415,898 +2922,216 @@ export function MapView({ body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing selected is a crash, not a blank. ═══════════════════════════════════════════════════════════════════════════════════ */} - {routePanelOpen && !routeCreateOpen && ( + {mapNavigator === "routes" && ( )} - {routePanelOpen && routeCreateOpen && ( - + )} + {zones !== null && mapNavigator === "zones" && zoneEditorOpen && ( + )} {/* Every gesture the map has, named. `alt` (add to the selection rather than replace it, onPointerUp) shipped in wave 8 and was disclosed @@ -3314,7 +3139,13 @@ export function MapView({ knew about. It needs shift too — alt alone still pans. */} Scroll to zoom · drag to pan · {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "} - · shift-alt-drag to extend the selection · click a pin to open the record · shift-click a + · shift-alt-drag to extend the selection · {routePanelOpen + ? activeNamedRoute + ? activeNamedRoute.permission.canEdit && activeNamedRoute.compatibility !== "legacy-route-order" + ? `click or press Enter on a pin to ask to add or remove it from ${activeNamedRoute.name}` + : `${activeNamedRoute.name} is read-only; plain click or Enter does not open a record` + : "open a route first; plain click or Enter does not open a record" + : "click or press Enter on a pin to open the record"} · shift-click or press Space on a pin to add or remove it from the selection @@ -3324,6 +3155,7 @@ export function MapView({ role="group" aria-label="Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north." onKeyDown={onFrameKeyDown} + onPointerDown={() => { if (!routePanelOpen) signal(NAV_MINIMIZE_EVENT); }} > setHoverPid(p.pid)} onMouseLeave={() => setHoverPid((h) => (h === p.pid ? null : h))} onFocus={() => setHoverPid(p.pid)} @@ -3522,6 +3355,10 @@ export function MapView({ pinSelect(p.pid, true); return; } + if (routePanelOpen) { + requestRoutePinMembership(p.pid, p.title); + return; + } // ⭐⭐ W41-T48 (owner instruction 22) — OPENING A RECORD FOLDS THE RAIL, ON // THE MAP EXACTLY AS IN THE GRID. `CustomerGrid.tsx::onCellClicked` raises // this on every cell click; the map was the one surface that opened a record @@ -3556,6 +3393,7 @@ export function MapView({ onDoubleClick={(e) => { if (movedRef.current) return; e.preventDefault(); + if (routePanelOpen) return; onOpen(p.pid); }} onKeyDown={(e) => { @@ -3567,6 +3405,10 @@ export function MapView({ // disambiguate, so the guard the pointer needs would only be superstition. if (e.key === "Enter") { e.preventDefault(); + if (routePanelOpen) { + if (!e.repeat) requestRoutePinMembership(p.pid, p.title); + return; + } // W41-T48 — the keyboard mirror of the plain click, so it folds the rail // for the same reason. ⚠ `!e.repeat` is this path's `e.detail <= 1`: a HELD // Enter auto-repeats keydown for as long as the finger is down, and every