Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

test(roadtrip): cover the routing, corridor and panel behaviour

Mauriced6955f20a6ad
diff --git a/client/src/components/Roadtrip/RoadtripCorridorPanel.test.tsx b/client/src/components/Roadtrip/RoadtripCorridorPanel.test.tsx
new file mode 100644
index 000000000..2213281cd
--- /dev/null
+++ b/client/src/components/Roadtrip/RoadtripCorridorPanel.test.tsx
@@ -0,0 +1,235 @@
+import React from 'react'
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, within, fireEvent } from '@testing-library/react'
+import { TranslationProvider } from '../../i18n'
+import RoadtripCorridorPanel from './RoadtripCorridorPanel'
+import type { CorridorPoi } from './useCorridorPois'
+import type { RoadtripCorridor } from './useRoadtripCorridor'
+import type { RoadtripDay, RoadtripRoutes, RoadtripStop } from './useRoadtripRoutes'
+
+const wrap = (ui: React.ReactElement) => render(<TranslationProvider>{ui}</TranslationProvider>)
+
+const stop = (id: number, name: string): RoadtripStop => ({
+ assignmentId: id,
+ placeId: id * 10,
+ name,
+ lat: 53.5,
+ lng: 9.9,
+ time: null,
+ dwellMinutes: null,
+ legMode: null,
+ incomingLegMode: null,
+})
+
+const day = (dayId: number, dayNumber: number): RoadtripDay => ({
+ dayId,
+ dayNumber,
+ date: null,
+ title: null,
+ stops: [stop(dayId * 10 + 1, 'Hamburg'), stop(dayId * 10 + 2, 'Berlin')],
+ legs: [],
+ schedule: { entries: [], warnings: [] },
+ geometry: [],
+ distance: 0,
+ duration: 0,
+})
+
+const routes = (days: RoadtripDay[]): RoadtripRoutes => ({
+ days,
+ lines: [],
+ segments: [],
+ totalDistance: 0,
+ totalDuration: 0,
+ totalStops: days.length * 2,
+ loading: false,
+})
+
+function poi(over: Partial<CorridorPoi> & { osm_id: string; name: string }): CorridorPoi {
+ return {
+ lat: 53.5,
+ lng: 9.9,
+ category: 'fuel',
+ poi_type: 'amenity=fuel',
+ address: null,
+ website: null,
+ phone: null,
+ opening_hours: null,
+ cuisine: null,
+ source: 'openstreetmap',
+ offRouteKm: 1.2,
+ alongKm: 40,
+ ...over,
+ } as CorridorPoi
+}
+
+function corridor(over: Partial<RoadtripCorridor> = {}, search: Partial<RoadtripCorridor['search']> = {}): RoadtripCorridor {
+ const days = over.day ? [over.day] : [day(1, 1)]
+ return {
+ dayId: String(days[0].dayId),
+ setDayId: vi.fn(),
+ day: days[0],
+ categories: ['fuel'],
+ toggleCategory: vi.fn(),
+ widthKm: 5,
+ setWidthKm: vi.fn(),
+ ...over,
+ search: {
+ results: [],
+ progress: { done: 0, total: 0 },
+ loading: false,
+ capped: false,
+ failedAreas: 0,
+ error: false,
+ search: vi.fn(),
+ clear: vi.fn(),
+ ...search,
+ },
+ }
+}
+
+describe('RoadtripCorridorPanel', () => {
+ it('FE-ROADTRIP-PANEL-001: searching is a button, never a side effect of opening the panel', () => {
+ const c = corridor()
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ expect(c.search.search).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: /search/i }))
+ expect(c.search.search).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-ROADTRIP-PANEL-002: nothing selected means nothing to search for', () => {
+ const c = corridor({ categories: [] })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ expect(screen.getByRole('button', { name: /search/i })).toBeDisabled()
+ })
+
+ it('FE-ROADTRIP-PANEL-003: a day with a single stop has no drive to search along', () => {
+ const lonely = { ...day(1, 1), stops: [stop(11, 'Hamburg')] }
+ const c = corridor({ day: lonely })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([lonely])} />)
+
+ expect(screen.getByRole('button', { name: /search/i })).toBeDisabled()
+ })
+
+ it('FE-ROADTRIP-PANEL-004: toggling a kind reports which one', () => {
+ const c = corridor()
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ fireEvent.click(screen.getByRole('button', { name: /campsite/i }))
+ expect(c.toggleCategory).toHaveBeenCalledWith('campsite')
+ // What is already selected reads as pressed rather than only looking different.
+ expect(screen.getByRole('button', { name: /fuel/i })).toHaveAttribute('aria-pressed', 'true')
+ })
+
+ it('FE-ROADTRIP-PANEL-005: the corridor width is a choice, and the current one is marked', () => {
+ const c = corridor()
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ const five = screen.getByRole('button', { name: '5 km' })
+ expect(five).toHaveAttribute('aria-pressed', 'true')
+ fireEvent.click(screen.getByRole('button', { name: '10 km' }))
+ expect(c.setWidthKm).toHaveBeenCalledWith(10)
+ })
+
+ it('FE-ROADTRIP-PANEL-006: the day picker only appears once there is more than one drive', () => {
+ const one = corridor()
+ const { unmount } = wrap(<RoadtripCorridorPanel corridor={one} routes={routes([day(1, 1)])} />)
+ expect(screen.queryByText('Day 1')).not.toBeInTheDocument()
+ unmount()
+
+ wrap(<RoadtripCorridorPanel corridor={corridor()} routes={routes([day(1, 1), day(2, 2)])} />)
+ expect(screen.getByText('Day 1')).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-PANEL-007: groups the hits by kind and counts each group', () => {
+ const c = corridor({ categories: ['fuel', 'campsite'] }, {
+ results: [
+ poi({ osm_id: 'a', name: 'Aral', alongKm: 10 }),
+ poi({ osm_id: 'b', name: 'Shell', alongKm: 20 }),
+ poi({ osm_id: 'c', name: 'Camping Elbe', category: 'campsite', alongKm: 30 }),
+ ],
+ })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ // "Fuel" is also a filter chip; the group header is the one inside a <header>.
+ const fuelGroup = screen.getAllByText('Fuel').map(el => el.closest('header')).find(Boolean)!
+ expect(within(fuelGroup).getByText('2')).toBeInTheDocument()
+ expect(screen.getByText('Camping Elbe')).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-PANEL-008: each hit says how far off the route and how far along it is', () => {
+ const c = corridor({}, { results: [poi({ osm_id: 'a', name: 'Aral', offRouteKm: 1.2, alongKm: 40 })] })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ const row = screen.getByText('Aral').closest('li')!
+ expect(within(row).getByText(/1\.2 km/)).toBeInTheDocument()
+ expect(within(row).getByText(/40 km/)).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-PANEL-009: a hit right at the start says so instead of "0 km along"', () => {
+ const c = corridor({}, { results: [poi({ osm_id: 'a', name: 'Aral', alongKm: 0.1 })] })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ expect(screen.getByText('Aral').closest('li')!.textContent).not.toContain('0 km along')
+ })
+
+ it('FE-ROADTRIP-PANEL-010: a chain shows its own logo ahead of its name', () => {
+ const c = corridor({}, { results: [poi({ osm_id: 'a', name: 'Aral', brand_wikidata: 'Q565734' } as Partial<CorridorPoi> & { osm_id: string; name: string })] })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ const row = screen.getByText('Aral').closest('li')!
+ const logo = row.querySelector('img')!
+ expect(logo).toHaveAttribute('src', '/api/maps/brand-logo/Q565734')
+ // Hidden until it has loaded, so a brand without one shows the category icon
+ // rather than a hole in the row.
+ expect(logo.className).toContain('opacity-0')
+ })
+
+ it('FE-ROADTRIP-PANEL-011: a wikidata id that is not one is never put in a URL', () => {
+ const c = corridor({}, { results: [poi({ osm_id: 'a', name: 'Aral', brand_wikidata: '../../etc/passwd' } as Partial<CorridorPoi> & { osm_id: string; name: string })] })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ expect(screen.getByText('Aral').closest('li')!.querySelector('img')).toBeNull()
+ })
+
+ it('FE-ROADTRIP-PANEL-012: adding a hit puts it on the day that was searched', () => {
+ const onAddPoi = vi.fn()
+ const c = corridor({}, { results: [poi({ osm_id: 'node:9', name: 'Aral' })] })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} onAddPoi={onAddPoi} />)
+
+ fireEvent.click(screen.getByRole('button', { name: /add/i }))
+ expect(onAddPoi).toHaveBeenCalledWith(expect.objectContaining({ osm_id: 'node:9' }), 1)
+ })
+
+ it('FE-ROADTRIP-PANEL-013: while searching it reports progress rather than sitting still', () => {
+ const c = corridor({}, { loading: true, progress: { done: 3, total: 12 } })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '25')
+ expect(screen.getByRole('button', { name: /3/ })).toBeDisabled()
+ })
+
+ it('FE-ROADTRIP-PANEL-014: a partial answer says which stretches nobody looked at', () => {
+ const c = corridor({}, { failedAreas: 2, results: [poi({ osm_id: 'a', name: 'Aral' })] })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ // The difference between "no fuel here" and "nobody looked here".
+ expect(screen.getByText('2 stretches could not be searched — the place search did not answer.')).toBeInTheDocument()
+ expect(screen.getByText('Aral')).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-PANEL-015: a total outage reads as a failure, not as an empty road', () => {
+ const c = corridor({}, { error: true, failedAreas: 4 })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ expect(screen.getByText('The place search is not answering right now.')).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-PANEL-016: a drive longer than the budget admits the tail went unsearched', () => {
+ const c = corridor({}, { capped: true })
+ wrap(<RoadtripCorridorPanel corridor={c} routes={routes([day(1, 1)])} />)
+
+ expect(screen.getByText('The route is long — only the first stretch was searched.')).toBeInTheDocument()
+ })
+})
diff --git a/client/src/components/Roadtrip/RoadtripSidebar.test.tsx b/client/src/components/Roadtrip/RoadtripSidebar.test.tsx
new file mode 100644
index 000000000..6092ad05d
--- /dev/null
+++ b/client/src/components/Roadtrip/RoadtripSidebar.test.tsx
@@ -0,0 +1,177 @@
+import React from 'react'
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, within, fireEvent } from '@testing-library/react'
+import { TranslationProvider } from '../../i18n'
+import RoadtripSidebar from './RoadtripSidebar'
+import RoadtripModeSwitch from './RoadtripModeSwitch'
+import type { RoadtripDay, RoadtripRoutes, RoadtripStop } from './useRoadtripRoutes'
+import type { RouteSegment } from '../../types'
+
+const wrap = (ui: React.ReactElement) => render(<TranslationProvider>{ui}</TranslationProvider>)
+
+function stop(over: Partial<RoadtripStop> & { assignmentId: number; name: string }): RoadtripStop {
+ return {
+ placeId: over.assignmentId * 10,
+ lat: 53.5,
+ lng: 9.9,
+ time: null,
+ dwellMinutes: null,
+ legMode: null,
+ incomingLegMode: null,
+ ...over,
+ }
+}
+
+const leg = (over: Partial<RouteSegment> = {}): RouteSegment =>
+ ({ distance: 100000, duration: 3600, distanceText: '100 km', durationText: '1 h', mode: 'driving', ...over }) as RouteSegment
+
+function day(over: Partial<RoadtripDay> = {}): RoadtripDay {
+ const stops = over.stops ?? [
+ stop({ assignmentId: 1, name: 'Hamburg' }),
+ stop({ assignmentId: 2, name: 'Berlin' }),
+ ]
+ return {
+ dayId: 1,
+ dayNumber: 1,
+ date: null,
+ title: null,
+ stops,
+ legs: [leg()],
+ schedule: { entries: stops.map(() => ({ arrival: null, departure: null, anchored: false, dayOffset: 0 })), warnings: [] },
+ geometry: [],
+ distance: 100000,
+ duration: 3600,
+ ...over,
+ }
+}
+
+function routes(over: Partial<RoadtripRoutes> = {}): RoadtripRoutes {
+ return {
+ days: [day()],
+ lines: [],
+ segments: [],
+ totalDistance: 100000,
+ totalDuration: 3600,
+ totalStops: 2,
+ loading: false,
+ ...over,
+ }
+}
+
+describe('RoadtripSidebar', () => {
+ /** The value shown in the totals card with this label. */
+ const total = (label: string): string =>
+ within(screen.getByText(label).closest('div.rounded-xl')!).getAllByText(/./)[1].textContent!
+
+ it('FE-ROADTRIP-SIDEBAR-001: leads with the totals for the whole drive', () => {
+ wrap(<RoadtripSidebar routes={routes({ totalDistance: 250000, totalDuration: 9000, totalStops: 5 })} />)
+
+ expect(total('Distance')).toBe('250 km')
+ expect(total('Driving time')).toBe('2 h 30 min')
+ expect(total('Stops')).toBe('5')
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-002: chains the stops with the drive between them', () => {
+ // Day totals deliberately differ from the single leg, so the leg is unambiguous.
+ wrap(<RoadtripSidebar routes={routes({ days: [day({ distance: 250000, duration: 9000 })] })} />)
+
+ expect(screen.getByText('Hamburg')).toBeInTheDocument()
+ expect(screen.getByText('Berlin')).toBeInTheDocument()
+ // The leg reads as one line between the two stops it connects.
+ expect(screen.getByText('100 km · 1 h')).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-003: says a leg is still coming rather than showing a blank', () => {
+ wrap(<RoadtripSidebar routes={routes({ days: [day({ legs: [undefined], distance: 0, duration: 0 })] })} />)
+
+ expect(screen.queryByText('100 km · 1 h')).not.toBeInTheDocument()
+ expect(screen.getByText('No route')).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-004: sets a pinned arrival apart from a computed one', () => {
+ const stops = [stop({ assignmentId: 1, name: 'Ferry' }), stop({ assignmentId: 2, name: 'Berlin' })]
+ const schedule = {
+ entries: [
+ { arrival: '09:00', departure: '09:30', anchored: true, dayOffset: 0 },
+ { arrival: '10:30', departure: '10:30', anchored: false, dayOffset: 0 },
+ ],
+ warnings: [],
+ }
+ wrap(<RoadtripSidebar routes={routes({ days: [day({ stops, schedule })] })} />)
+
+ expect(screen.getByText('09:00').className).toContain('font-semibold')
+ expect(screen.getByText('10:30').className).toContain('text-content-muted')
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-005: flags a stop the drive cannot reach in time', () => {
+ const stops = [stop({ assignmentId: 1, name: 'Hamburg' }), stop({ assignmentId: 2, name: 'Ferry' })]
+ const schedule = {
+ entries: stops.map(() => ({ arrival: '09:00', departure: '09:00', anchored: true, dayOffset: 0 })),
+ warnings: [{ index: 1, code: 'late' as const, minutes: 45 }],
+ }
+ wrap(<RoadtripSidebar routes={routes({ days: [day({ stops, schedule })] })} />)
+
+ expect(screen.getByLabelText(/45/)).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-006: shows how long a stop is planned to take', () => {
+ const stops = [stop({ assignmentId: 1, name: 'Museum', dwellMinutes: 90 }), stop({ assignmentId: 2, name: 'Berlin' })]
+ wrap(<RoadtripSidebar routes={routes({ days: [day({ stops })] })} />)
+
+ expect(screen.getByText('1 h 30 min')).toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-007: selecting a stop reports the place and the assignment', () => {
+ const onSelectStop = vi.fn()
+ wrap(<RoadtripSidebar routes={routes()} onSelectStop={onSelectStop} />)
+
+ fireEvent.click(screen.getByText('Berlin'))
+ expect(onSelectStop).toHaveBeenCalledWith(20, 2)
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-008: marks the selected stop for assistive tech', () => {
+ wrap(<RoadtripSidebar routes={routes()} selectedAssignmentId={2} />)
+
+ const selected = screen.getByText('Berlin').closest('button')!
+ expect(selected).toHaveAttribute('aria-current', 'true')
+ expect(screen.getByText('Hamburg').closest('button')).not.toHaveAttribute('aria-current')
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-009: a trip with nothing to drive explains itself', () => {
+ wrap(<RoadtripSidebar routes={routes({ days: [], totalDistance: 0, totalDuration: 0, totalStops: 0 })} />)
+
+ expect(screen.getByRole('heading', { level: 3 })).toBeInTheDocument()
+ expect(screen.queryByText('Hamburg')).not.toBeInTheDocument()
+ })
+
+ it('FE-ROADTRIP-SIDEBAR-010: each day carries its own distance and time', () => {
+ const second = day({ dayId: 2, dayNumber: 2, distance: 50000, duration: 1800, stops: [
+ stop({ assignmentId: 3, name: 'Dresden' }),
+ stop({ assignmentId: 4, name: 'Prague' }),
+ ] })
+ wrap(<RoadtripSidebar routes={routes({ days: [day(), second], totalStops: 4 })} />)
+
+ const headings = screen.getAllByRole('heading', { level: 3 })
+ expect(headings).toHaveLength(2)
+ expect(within(headings[1].parentElement!).getByText(/50 km/)).toBeInTheDocument()
+ })
+})
+
+describe('RoadtripModeSwitch', () => {
+ it('FE-ROADTRIP-MODESWITCH-001: offers both readings and marks the active one', () => {
+ wrap(<RoadtripModeSwitch active onChange={vi.fn()} />)
+
+ const tabs = screen.getAllByRole('tab')
+ expect(tabs).toHaveLength(2)
+ expect(tabs[0]).toHaveAttribute('aria-selected', 'false')
+ expect(tabs[1]).toHaveAttribute('aria-selected', 'true')
+ })
+
+ it('FE-ROADTRIP-MODESWITCH-002: switching back to the day plan reports false', () => {
+ const onChange = vi.fn()
+ wrap(<RoadtripModeSwitch active onChange={onChange} />)
+
+ fireEvent.click(screen.getAllByRole('tab')[0])
+ expect(onChange).toHaveBeenCalledWith(false)
+ })
+})
diff --git a/client/src/components/Roadtrip/corridor.test.ts b/client/src/components/Roadtrip/corridor.test.ts
index e02008d0a..4a2df1a92 100644
--- a/client/src/components/Roadtrip/corridor.test.ts
+++ b/client/src/components/Roadtrip/corridor.test.ts
@@ -102,6 +102,31 @@ describe('corridorTiles', () => {
expect(north.east - north.west).toBeGreaterThan(south.east - south.west)
})
+ it('covers the middle of a long straight leg, not only its two ends', () => {
+ // A motorway with no bend in it reduces to two points, 250 km apart. Tiling walks
+ // point to point, so without splitting the step everything between them goes
+ // unsearched while the search still reports itself complete.
+ const straight = [{ lat: 53.55, lng: 9.99 }, { lat: 52.52, lng: 13.4 }]
+ const tiles = corridorTiles(straight, 10)
+
+ expect(tiles.length).toBeGreaterThan(4)
+ // A box somewhere over the middle of the drive, which is what was missing.
+ const midLat = 53.03
+ const midLng = 11.7
+ expect(tiles.some(t => t.south <= midLat && t.north >= midLat && t.west <= midLng && t.east >= midLng)).toBe(true)
+ })
+
+ it('leaves no gap between consecutive boxes along a route', () => {
+ const tiles = corridorTiles([{ lat: 53.55, lng: 9.99 }, { lat: 52.52, lng: 13.4 }], 10)
+ for (let i = 1; i < tiles.length; i++) {
+ const a = tiles[i - 1]
+ const b = tiles[i]
+ // Overlapping or touching in both axes: a hole here is a stretch nobody looks at.
+ expect(Math.min(a.north, b.north) - Math.max(a.south, b.south)).toBeGreaterThanOrEqual(0)
+ expect(Math.min(a.east, b.east) - Math.max(a.west, b.west)).toBeGreaterThanOrEqual(0)
+ }
+ })
+
it('has nothing to cover for an empty route', () => {
expect(corridorTiles([], 10)).toEqual([])
})
diff --git a/client/src/components/Roadtrip/corridor.ts b/client/src/components/Roadtrip/corridor.ts
index 301189094..7449f612b 100644
--- a/client/src/components/Roadtrip/corridor.ts
+++ b/client/src/components/Roadtrip/corridor.ts
@@ -57,6 +57,9 @@ export function distanceToSegmentKm(p: LatLng, a: LatLng, b: LatLng): number {
* the drive — taking the segment's midpoint instead makes every petrol station on a long
* straight report the same position.
*/
+/** A segment shorter than a millimetre, squared — below this there is nothing to project onto. */
+const DEGENERATE_SEGMENT_KM2 = 1e-12
+
export function projectOnSegment(p: LatLng, a: LatLng, b: LatLng): { distanceKm: number; t: number } {
const latScale = KM_PER_DEG_LAT
const lngScale = KM_PER_DEG_LAT * Math.cos(toRad((a.lat + b.lat) / 2))
@@ -69,7 +72,10 @@ export function projectOnSegment(p: LatLng, a: LatLng, b: LatLng): { distanceKm:
const dx = bx - ax
const dy = by - ay
const lenSq = dx * dx + dy * dy
- if (lenSq === 0) return { distanceKm: haversineKm(p, a), t: 0 }
+ // A segment whose two ends are the same point to within a millimetre has no
+ // direction to project onto, so measure straight to it. Written as a range because
+ // the ends came through a chain of floating point arithmetic and never land on 0.
+ if (lenSq < DEGENERATE_SEGMENT_KM2) return { distanceKm: haversineKm(p, a), t: 0 }
// Clamped so a point beside the segment's end measures to the end, not to the
// infinite line — otherwise a stop 200 km past the destination looks "on the way".
const t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / lenSq))
@@ -117,6 +123,31 @@ export function projectOntoRoute(p: LatLng, line: LatLng[]): CorridorHit | null
* rather than sent as one. Boxes are grown along the route until one would exceed the
* span, so a straight motorway needs far fewer requests than a mountain road.
*/
+/**
+ * Splits a step that is longer than a box into even pieces.
+ *
+ * The simplifier is right to reduce a dead straight motorway stretch to its two ends,
+ * but tiling walks point to point: two ends 100 km apart produce a box at each end and
+ * nothing in between, so the middle of the drive would never be searched.
+ */
+function densify(line: LatLng[], maxStepDeg: number): LatLng[] {
+ if (line.length < 2) return line
+ const out: LatLng[] = [line[0]]
+ for (let i = 1; i < line.length; i++) {
+ const a = line[i - 1]
+ const b = line[i]
+ const span = Math.max(Math.abs(b.lat - a.lat), Math.abs(b.lng - a.lng))
+ const steps = Math.max(1, Math.ceil(span / maxStepDeg))
+ for (let s = 1; s <= steps; s++) {
+ out.push({
+ lat: a.lat + ((b.lat - a.lat) * s) / steps,
+ lng: a.lng + ((b.lng - a.lng) * s) / steps,
+ })
+ }
+ }
+ return out
+}
+
export function corridorTiles(line: LatLng[], widthKm: number, maxSpanDeg = 0.45): Bbox[] {
if (line.length === 0) return []
const padLat = widthKm / KM_PER_DEG_LAT
@@ -136,7 +167,7 @@ export function corridorTiles(line: LatLng[], widthKm: number, maxSpanDeg = 0.45
}
}
- for (const p of line) {
+ for (const p of densify(line, maxSpanDeg / 2)) {
if (!current) {
current = { south: p.lat, north: p.lat, west: p.lng, east: p.lng }
continue
diff --git a/client/src/components/Roadtrip/roadtripModel.ts b/client/src/components/Roadtrip/roadtripModel.ts
index 437527c83..93c69cec7 100644
--- a/client/src/components/Roadtrip/roadtripModel.ts
+++ b/client/src/components/Roadtrip/roadtripModel.ts
@@ -74,6 +74,27 @@ export interface Schedule {
* `legSeconds[i]` is the drive from stop i to stop i+1; a leg that never routed is
* `undefined` and breaks the chain rather than inventing a duration.
*/
+/**
+ * Where a stop's clock actually starts.
+ *
+ * A pinned time wins over whatever the drive before it worked out and restarts the
+ * cascade from there. When it sits before the arrival the drive implies, the plan does
+ * not fit: the caller is told by how much rather than the pinned time being moved.
+ */
+function resolveArrival(
+ anchor: number | null,
+ cursor: number | null,
+ dayOffset: number,
+): { arrival: number | null; lateBy: number | null } {
+ if (anchor === null) return { arrival: cursor, lateBy: null }
+ if (cursor === null) return { arrival: anchor, lateBy: null }
+ const anchorToday = anchor + dayOffset * 24 * 60
+ return {
+ arrival: anchorToday,
+ lateBy: cursor > anchorToday + 1 ? Math.round(cursor - anchorToday) : null,
+ }
+}
+
export function computeSchedule(stops: ScheduleStop[], legSeconds: (number | undefined)[]): Schedule {
const entries: ScheduleEntry[] = []
const warnings: ScheduleWarning[] = []
@@ -84,20 +105,8 @@ export function computeSchedule(stops: ScheduleStop[], legSeconds: (number | und
for (let i = 0; i < stops.length; i++) {
const stop = stops[i]
const anchor = parseClock(stop.anchor)
- let arrival: number | null = cursor
-
- if (anchor !== null) {
- if (arrival !== null) {
- const anchorToday = anchor + dayOffset * 24 * 60
- // The pinned time is in the past relative to the drive: the plan does not fit.
- if (arrival > anchorToday + 1) {
- warnings.push({ index: i, code: 'late', minutes: Math.round(arrival - anchorToday) })
- }
- arrival = anchorToday
- } else {
- arrival = anchor
- }
- }
+ const { arrival, lateBy } = resolveArrival(anchor, cursor, dayOffset)
+ if (lateBy !== null) warnings.push({ index: i, code: 'late', minutes: lateBy })
if (arrival === null) {
entries.push({ arrival: null, departure: null, anchored: false, dayOffset: 0 })
diff --git a/client/src/components/Roadtrip/useCorridorPois.test.ts b/client/src/components/Roadtrip/useCorridorPois.test.ts
new file mode 100644
index 000000000..640c48240
--- /dev/null
+++ b/client/src/components/Roadtrip/useCorridorPois.test.ts
@@ -0,0 +1,187 @@
+import { renderHook, waitFor, act } from '@testing-library/react'
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import type { LatLng } from './corridor'
+
+const { pois } = vi.hoisted(() => ({ pois: vi.fn() }))
+vi.mock('../../api/client', () => ({ mapsApi: { pois } }))
+vi.mock('../../i18n', () => ({ useTranslation: () => ({ locale: 'en-US' }) }))
+
+import { useCorridorPois } from './useCorridorPois'
+
+/** A short drive west out of Hamburg — enough route to tile, few enough boxes to be quick. */
+const LINE: LatLng[] = [
+ { lat: 53.55, lng: 9.99 },
+ { lat: 53.5, lng: 9.8 },
+ { lat: 53.45, lng: 9.6 },
+]
+
+const hit = (id: string, lat: number, lng: number, category = 'fuel') => ({
+ osm_id: id,
+ name: id,
+ lat,
+ lng,
+ category,
+ poi_type: 'amenity=fuel',
+ address: null,
+ website: null,
+ phone: null,
+ opening_hours: null,
+ cuisine: null,
+ source: 'openstreetmap',
+})
+
+const answer = (...items: ReturnType<typeof hit>[]) => ({ pois: items, source: 'openstreetmap', truncated: false, clamped: false })
+
+beforeEach(() => {
+ pois.mockReset()
+ pois.mockResolvedValue(answer())
+})
+
+describe('useCorridorPois', () => {
+ it('FE-ROADTRIP-CORRIDOR-001: asks each box once for every category together', async () => {
+ const { result } = renderHook(() => useCorridorPois(LINE, ['fuel', 'charging', 'rest_area'], 10))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(pois).toHaveBeenCalled()
+ // The whole point of the batching: the kinds ride along in one query per box.
+ for (const call of pois.mock.calls) expect(call[0]).toBe('fuel,charging,rest_area')
+ expect(result.current.progress.total).toBe(pois.mock.calls.length)
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-002: keeps what is near the route and drops what is not', async () => {
+ // One beside the line, one far north of it.
+ pois.mockResolvedValue(answer(hit('near', 53.5, 9.81), hit('far', 54.6, 9.8)))
+
+ const { result } = renderHook(() => useCorridorPois(LINE, ['fuel'], 5))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(result.current.results.map(r => r.osm_id)).toEqual(['near'])
+ expect(result.current.results[0].offRouteKm).toBeLessThan(5)
+ expect(result.current.results[0].alongKm).toBeGreaterThan(0)
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-003: orders hits by how far along the drive they are', async () => {
+ pois.mockResolvedValue(answer(
+ hit('late', 53.45, 9.61),
+ hit('early', 53.55, 9.98),
+ hit('middle', 53.5, 9.8),
+ ))
+
+ const { result } = renderHook(() => useCorridorPois(LINE, ['fuel'], 8))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(result.current.results.map(r => r.osm_id)).toEqual(['early', 'middle', 'late'])
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-004: the same place found in two overlapping boxes is listed once', async () => {
+ pois.mockResolvedValue(answer(hit('shared', 53.5, 9.81)))
+
+ const { result } = renderHook(() => useCorridorPois(LINE, ['fuel'], 10))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(result.current.results.filter(r => r.osm_id === 'shared')).toHaveLength(1)
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-005: a box that times out is asked again before it counts as unsearched', async () => {
+ let first = true
+ pois.mockImplementation(async () => {
+ if (first) { first = false; throw new Error('502') }
+ return answer(hit('found', 53.5, 9.81))
+ })
+
+ const { result } = renderHook(() => useCorridorPois(LINE, ['fuel'], 10))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(result.current.failedAreas).toBe(0)
+ expect(result.current.error).toBe(false)
+ expect(result.current.results.length).toBeGreaterThan(0)
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-006: a box that fails twice is reported rather than silently skipped', async () => {
+ pois.mockRejectedValue(new Error('502'))
+
+ const { result } = renderHook(() => useCorridorPois(LINE, ['fuel'], 10))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(result.current.failedAreas).toBeGreaterThan(0)
+ // Nothing answered at all, so this is an outage and not a partial result.
+ expect(result.current.error).toBe(true)
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-007: a drive longer than the request budget says the tail went unsearched', async () => {
+ const long: LatLng[] = Array.from({ length: 40 }, (_, i) => ({ lat: 53.5 - i * 0.25, lng: 9.9 + i * 0.35 }))
+
+ const { result } = renderHook(() => useCorridorPois(long, ['fuel'], 5))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(result.current.capped).toBe(true)
+ expect(result.current.progress.total).toBeLessThanOrEqual(16)
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-008: changing what is wanted drops the answers to the old question', async () => {
+ pois.mockResolvedValue(answer(hit('a', 53.5, 9.81)))
+
+ const { result, rerender } = renderHook(
+ ({ categories }: { categories: string[] }) => useCorridorPois(LINE, categories, 10),
+ { initialProps: { categories: ['fuel'] } },
+ )
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.results.length).toBeGreaterThan(0))
+
+ rerender({ categories: ['campsite'] })
+ await waitFor(() => expect(result.current.results).toEqual([]))
+ expect(result.current.progress).toEqual({ done: 0, total: 0 })
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-009: a route too short to search asks for nothing', async () => {
+ const { result } = renderHook(() => useCorridorPois([LINE[0]], ['fuel'], 10))
+ act(() => { result.current.search() })
+ await act(async () => {})
+
+ expect(pois).not.toHaveBeenCalled()
+ expect(result.current.loading).toBe(false)
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-010: with nothing selected there is nothing to look for', async () => {
+ const { result } = renderHook(() => useCorridorPois(LINE, [], 10))
+ act(() => { result.current.search() })
+ await act(async () => {})
+
+ expect(pois).not.toHaveBeenCalled()
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-011: clearing stops the run and empties the list', async () => {
+ pois.mockResolvedValue(answer(hit('a', 53.5, 9.81)))
+
+ const { result } = renderHook(() => useCorridorPois(LINE, ['fuel'], 10))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(result.current.results.length).toBeGreaterThan(0))
+
+ act(() => { result.current.clear() })
+ expect(result.current.results).toEqual([])
+ expect(result.current.loading).toBe(false)
+ expect(result.current.failedAreas).toBe(0)
+ })
+
+ it('FE-ROADTRIP-CORRIDOR-012: leaving the view aborts the boxes still in flight', async () => {
+ let seen: AbortSignal | undefined
+ pois.mockImplementation((_c: string, _b: unknown, _l: string, signal: AbortSignal) => {
+ seen = signal
+ return new Promise(() => {})
+ })
+
+ const { result, unmount } = renderHook(() => useCorridorPois(LINE, ['fuel'], 10))
+ act(() => { result.current.search() })
+ await waitFor(() => expect(seen).toBeDefined())
+
+ unmount()
+ expect(seen!.aborted).toBe(true)
+ })
+})
diff --git a/client/src/components/Roadtrip/useRoadtripCorridor.test.ts b/client/src/components/Roadtrip/useRoadtripCorridor.test.ts
new file mode 100644
index 000000000..93e861cb7
--- /dev/null
+++ b/client/src/components/Roadtrip/useRoadtripCorridor.test.ts
@@ -0,0 +1,147 @@
+import { renderHook, act } from '@testing-library/react'
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import type { LatLng } from './corridor'
+import type { RoadtripDay, RoadtripRoutes, RoadtripStop } from './useRoadtripRoutes'
+
+const { useCorridorPois } = vi.hoisted(() => ({ useCorridorPois: vi.fn() }))
+vi.mock('./useCorridorPois', () => ({ useCorridorPois }))
+
+import { useRoadtripCorridor, CORRIDOR_CATEGORY_KEYS, CORRIDOR_WIDTHS_KM } from './useRoadtripCorridor'
+
+const stop = (id: number, lat: number, lng: number): RoadtripStop => ({
+ assignmentId: id,
+ placeId: id * 10,
+ name: `Stop ${id}`,
+ lat,
+ lng,
+ time: null,
+ dwellMinutes: null,
+ legMode: null,
+ incomingLegMode: null,
+})
+
+function day(over: Partial<RoadtripDay> = {}): RoadtripDay {
+ return {
+ dayId: 1,
+ dayNumber: 1,
+ date: null,
+ title: null,
+ stops: [stop(1, 53.55, 9.99), stop(2, 52.52, 13.4)],
+ legs: [],
+ schedule: { entries: [], warnings: [] },
+ geometry: [],
+ distance: 0,
+ duration: 0,
+ ...over,
+ }
+}
+
+const routes = (days: RoadtripDay[]): RoadtripRoutes => ({
+ days,
+ lines: [],
+ segments: [],
+ totalDistance: 0,
+ totalDuration: 0,
+ totalStops: 0,
+ loading: false,
+})
+
+/** What the corridor hook was handed on the last render. */
+const lastCall = (): { line: LatLng[]; categories: string[]; widthKm: number } => {
+ const call = useCorridorPois.mock.calls.at(-1)!
+ return { line: call[0], categories: call[1], widthKm: call[2] }
+}
+
+beforeEach(() => {
+ useCorridorPois.mockReset()
+ useCorridorPois.mockReturnValue({
+ results: [], progress: { done: 0, total: 0 }, loading: false,
+ capped: false, failedAreas: 0, error: false, search: vi.fn(), clear: vi.fn(),
+ })
+})
+
+describe('useRoadtripCorridor', () => {
+ it('FE-ROADTRIP-CORRIDORSTATE-001: searches along the roads driven, not the line between stops', () => {
+ // The motorway swings north of the straight line; searching the straight line finds
+ // open country, which is the bug this replaced.
+ const geometry: [number, number][] = [[53.55, 9.99], [53.6, 11.2], [52.52, 13.4]]
+ renderHook(() => useRoadtripCorridor(routes([day({ geometry })])))
+
+ expect(lastCall().line).toEqual([
+ { lat: 53.55, lng: 9.99 },
+ { lat: 53.6, lng: 11.2 },
+ { lat: 52.52, lng: 13.4 },
+ ])
+ })
+
+ it('FE-ROADTRIP-CORRIDORSTATE-002: falls back to the stops until the day has routed', () => {
+ renderHook(() => useRoadtripCorridor(routes([day({ geometry: [] })])))
+
+ expect(lastCall().line).toEqual([
+ { lat: 53.55, lng: 9.99 },
+ { lat: 52.52, lng: 13.4 },
+ ])
+ })
+
+ it('FE-ROADTRIP-CORRIDORSTATE-003: opens on the first day with a drive, before anything is picked', () => {
+ const { result } = renderHook(() => useRoadtripCorridor(routes([day({ dayId: 4 }), day({ dayId: 5 })])))
+
+ expect(result.current.dayId).toBe('4')
+ expect(result.current.day?.dayId).toBe(4)
+ })
+
+ it('FE-ROADTRIP-CORRIDORSTATE-004: picking a day switches which drive is searched', () => {
+ const second = day({ dayId: 5, geometry: [[48.1, 11.5], [47.8, 12.1]] })
+ const { result } = renderHook(() => useRoadtripCorridor(routes([day({ dayId: 4 }), second])))
+
+ act(() => { result.current.setDayId('5') })
+
+ expect(result.current.day?.dayId).toBe(5)
+ expect(lastCall().line).toEqual([{ lat: 48.1, lng: 11.5 }, { lat: 47.8, lng: 12.1 }])
+ })
+
+ it('FE-ROADTRIP-CORRIDORSTATE-005: follows along when the chosen day disappears', () => {
+ const { result, rerender } = renderHook(
+ ({ days }: { days: RoadtripDay[] }) => useRoadtripCorridor(routes(days)),
+ { initialProps: { days: [day({ dayId: 4 }), day({ dayId: 5 })] } },
+ )
+ act(() => { result.current.setDayId('5') })
+ expect(result.current.day?.dayId).toBe(5)
+
+ rerender({ days: [day({ dayId: 4 })] })
+ expect(result.current.dayId).toBe('4')
+ })
+
+ it('FE-ROADTRIP-CORRIDORSTATE-006: toggling a kind adds it and toggling again removes it', () => {
+ const { result } = renderHook(() => useRoadtripCorridor(routes([day()])))
+ expect(result.current.categories).toEqual(['fuel'])
+
+ act(() => { result.current.toggleCategory('campsite') })
+ expect(result.current.categories).toEqual(['fuel', 'campsite'])
+
+ act(() => { result.current.toggleCategory('fuel') })
+ expect(result.current.categories).toEqual(['campsite'])
+ expect(lastCall().categories).toEqual(['campsite'])
+ })
+
+ it('FE-ROADTRIP-CORRIDORSTATE-007: the width is handed straight to the search', () => {
+ const { result } = renderHook(() => useRoadtripCorridor(routes([day()])))
+ expect(lastCall().widthKm).toBe(5)
+
+ act(() => { result.current.setWidthKm(10) })
+ expect(lastCall().widthKm).toBe(10)
+ })
+
+ it('FE-ROADTRIP-CORRIDORSTATE-008: a trip with no drive has nothing to search along', () => {
+ const { result } = renderHook(() => useRoadtripCorridor(routes([])))
+
+ expect(result.current.day).toBeUndefined()
+ expect(result.current.dayId).toBe('')
+ expect(lastCall().line).toEqual([])
+ })
+
+ it('FE-ROADTRIP-CORRIDORSTATE-009: the offered kinds and widths are the ones the panel draws', () => {
+ expect(CORRIDOR_CATEGORY_KEYS).toEqual(['fuel', 'charging', 'rest_area', 'campsite', 'restaurant', 'sights'])
+ expect(CORRIDOR_WIDTHS_KM).toEqual([2, 5, 10])
+ })
+})
diff --git a/client/src/components/Roadtrip/useRoadtripRoutes.test.ts b/client/src/components/Roadtrip/useRoadtripRoutes.test.ts
new file mode 100644
index 000000000..a652ee40c
--- /dev/null
+++ b/client/src/components/Roadtrip/useRoadtripRoutes.test.ts
@@ -0,0 +1,238 @@
+import { renderHook, waitFor, act } from '@testing-library/react'
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import type { Assignment, AssignmentsMap, Day } from '../../types'
+
+const { calculateRouteWithLegs } = vi.hoisted(() => ({ calculateRouteWithLegs: vi.fn() }))
+vi.mock('../Map/RouteCalculator', () => ({ calculateRouteWithLegs }))
+
+import { useRoadtripRoutes } from './useRoadtripRoutes'
+
+const HAMBURG: [number, number] = [53.5511, 9.9937]
+const LUENEBURG: [number, number] = [53.2464, 10.4115]
+const BERLIN: [number, number] = [52.52, 13.405]
+
+interface StopSpec {
+ id: number
+ at: [number, number]
+ time?: string | null
+ dwell?: number | null
+ legMode?: string | null
+ incoming?: string | null
+ noCoords?: boolean
+}
+
+function day(id: number, number: number, extra: Partial<Day> = {}): Day {
+ return { id, day_number: number, date: null, title: null, ...extra } as unknown as Day
+}
+
+function assignment(spec: StopSpec, order: number): Assignment {
+ return {
+ id: spec.id,
+ place_id: spec.id * 10,
+ order_index: order,
+ assignment_time: spec.time ?? null,
+ leg_transport_mode: spec.legMode ?? null,
+ incoming_leg_transport_mode: spec.incoming ?? null,
+ place: {
+ id: spec.id * 10,
+ name: `Stop ${spec.id}`,
+ lat: spec.noCoords ? null : spec.at[0],
+ lng: spec.noCoords ? null : spec.at[1],
+ place_time: null,
+ duration_minutes: spec.dwell ?? null,
+ },
+ } as unknown as Assignment
+}
+
+const map = (dayId: number, stops: StopSpec[]): AssignmentsMap =>
+ ({ [String(dayId)]: stops.map(assignment) }) as unknown as AssignmentsMap
+
+/** A router answer with one leg per consecutive pair, the way OSRM replies. */
+const routed = (legs: number, coordinates: [number, number][] = [HAMBURG, BERLIN]) => ({
+ coordinates,
+ distance: 100000,
+ duration: 3600,
+ legs: Array.from({ length: legs }, () => ({ distance: 100000 / legs, duration: 3600 / legs, text: '100 km' })),
+})
+
+beforeEach(() => {
+ calculateRouteWithLegs.mockReset()
+ calculateRouteWithLegs.mockResolvedValue(routed(1))
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+describe('useRoadtripRoutes', () => {
+ it('FE-ROADTRIP-ROUTES-001: routes a whole day in one request, not one per leg', async () => {
+ const days = [day(1, 1)]
+ const stops: StopSpec[] = [
+ { id: 1, at: HAMBURG },
+ { id: 2, at: LUENEBURG },
+ { id: 3, at: BERLIN },
+ ]
+ calculateRouteWithLegs.mockResolvedValue(routed(2))
+
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, map(1, stops)))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)
+ const [waypoints, options] = calculateRouteWithLegs.mock.calls[0]
+ expect(waypoints).toHaveLength(3)
+ expect(options).toMatchObject({ profile: 'driving', tripId: 7, dayId: 1 })
+ })
+
+ it('FE-ROADTRIP-ROUTES-002: a day whose legs are driven and cycled becomes two requests', async () => {
+ const days = [day(1, 1)]
+ const stops: StopSpec[] = [
+ { id: 1, at: HAMBURG, legMode: 'driving' },
+ { id: 2, at: LUENEBURG, legMode: 'cycling' },
+ { id: 3, at: BERLIN },
+ ]
+
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, map(1, stops)))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
+ const profiles = calculateRouteWithLegs.mock.calls.map(c => c[1].profile)
+ expect(profiles).toEqual(['driving', 'cycling'])
+ })
+
+ it("FE-ROADTRIP-ROUTES-003: the day's own default mode wins over the trip fallback", async () => {
+ const days = [day(1, 1, { default_transport_mode: 'walking' } as Partial<Day>)]
+ const stops: StopSpec[] = [{ id: 1, at: HAMBURG }, { id: 2, at: LUENEBURG }]
+
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, map(1, stops), 'driving'))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(calculateRouteWithLegs.mock.calls[0][1].profile).toBe('walking')
+ })
+
+ it('FE-ROADTRIP-ROUTES-004: drops a stop without coordinates and a day left with one stop', async () => {
+ const days = [day(1, 1), day(2, 2)]
+ const assignments = {
+ ...map(1, [{ id: 1, at: HAMBURG }, { id: 2, at: LUENEBURG, noCoords: true }]),
+ ...map(2, [{ id: 3, at: HAMBURG }, { id: 4, at: BERLIN }]),
+ } as AssignmentsMap
+
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, assignments))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ // Day 1 lost its second stop and with it its reason to appear at all.
+ expect(result.current.days.map(d => d.dayId)).toEqual([2])
+ expect(result.current.totalStops).toBe(2)
+ })
+
+ it('FE-ROADTRIP-ROUTES-005: sums the legs and hands the map one polyline per routed run', async () => {
+ const days = [day(1, 1)]
+ const stops: StopSpec[] = [{ id: 1, at: HAMBURG }, { id: 2, at: BERLIN }]
+ calculateRouteWithLegs.mockResolvedValue(routed(1, [HAMBURG, [53, 11], BERLIN]))
+
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, map(1, stops)))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(result.current.totalDistance).toBe(100000)
+ expect(result.current.totalDuration).toBe(3600)
+ expect(result.current.lines).toEqual([[HAMBURG, [53, 11], BERLIN]])
+ // The corridor search reads this: the roads driven, not the line between stops.
+ expect(result.current.days[0].geometry).toEqual([HAMBURG, [53, 11], BERLIN])
+ expect(result.current.segments).toHaveLength(1)
+ })
+
+ it('FE-ROADTRIP-ROUTES-006: walks the clock forward from the first pinned time', async () => {
+ const days = [day(1, 1)]
+ const stops: StopSpec[] = [
+ { id: 1, at: HAMBURG, time: '09:00', dwell: 30 },
+ { id: 2, at: BERLIN, dwell: 60 },
+ ]
+ // One hour of driving between them.
+ calculateRouteWithLegs.mockResolvedValue(routed(1))
+
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, map(1, stops)))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ const entries = result.current.days[0].schedule.entries
+ expect(entries[0]).toMatchObject({ arrival: '09:00', departure: '09:30', anchored: true })
+ expect(entries[1]).toMatchObject({ arrival: '10:30', departure: '11:30', anchored: false })
+ })
+
+ it('FE-ROADTRIP-ROUTES-007: retries a leg that did not route, then keeps it blank', async () => {
+ vi.useFakeTimers()
+ const days = [day(1, 1)]
+ const stops: StopSpec[] = [{ id: 1, at: HAMBURG }, { id: 2, at: BERLIN }]
+ calculateRouteWithLegs.mockRejectedValue(new Error('429'))
+
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, map(1, stops)))
+ // Two backoffs, then it gives up rather than inventing a duration.
+ await act(async () => { await vi.advanceTimersByTimeAsync(8000) })
+
+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(3)
+ expect(result.current.loading).toBe(false)
+ expect(result.current.days[0].legs).toEqual([undefined])
+ expect(result.current.totalDistance).toBe(0)
+ // A leg that never routed breaks the chain instead of guessing past it.
+ expect(result.current.days[0].schedule.entries[1].arrival).toBeNull()
+ })
+
+ it('FE-ROADTRIP-ROUTES-008: a leg that answers on the second try still lands', async () => {
+ vi.useFakeTimers()
+ const days = [day(1, 1)]
+ const stops: StopSpec[] = [{ id: 1, at: HAMBURG }, { id: 2, at: BERLIN }]
+ calculateRouteWithLegs
+ .mockRejectedValueOnce(new Error('429'))
+ .mockResolvedValue(routed(1))
+
+ const { result } = renderHook(() => useRoadtripRoutes(7, days, map(1, stops)))
+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })
+
+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
+ expect(result.current.totalDistance).toBe(100000)
+ })
+
+ it('FE-ROADTRIP-ROUTES-009: renaming a place does not re-ask the router', async () => {
+ const days = [day(1, 1)]
+ const stops: StopSpec[] = [{ id: 1, at: HAMBURG }, { id: 2, at: BERLIN }]
+ const first = map(1, stops)
+
+ const { result, rerender } = renderHook(
+ ({ assignments }: { assignments: AssignmentsMap }) => useRoadtripRoutes(7, days, assignments),
+ { initialProps: { assignments: first } },
+ )
+ await waitFor(() => expect(result.current.loading).toBe(false))
+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)
+
+ const renamed = JSON.parse(JSON.stringify(first)) as AssignmentsMap
+ renamed['1'][0].place!.name = 'Somewhere else entirely'
+ rerender({ assignments: renamed })
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)
+ })
+
+ it('FE-ROADTRIP-ROUTES-010: a trip with nothing to drive asks for nothing', async () => {
+ const { result } = renderHook(() => useRoadtripRoutes(7, [day(1, 1)], map(1, [{ id: 1, at: HAMBURG }])))
+ await waitFor(() => expect(result.current.loading).toBe(false))
+
+ expect(calculateRouteWithLegs).not.toHaveBeenCalled()
+ expect(result.current.days).toEqual([])
+ expect(result.current.totalStops).toBe(0)
+ })
+
+ it('FE-ROADTRIP-ROUTES-011: leaving the view aborts the request in flight', async () => {
+ const days = [day(1, 1)]
+ const stops: StopSpec[] = [{ id: 1, at: HAMBURG }, { id: 2, at: BERLIN }]
+ let seen: AbortSignal | undefined
+ calculateRouteWithLegs.mockImplementation((_wp: unknown, opts: { signal: AbortSignal }) => {
+ seen = opts.signal
+ return new Promise(() => {}) // never settles
+ })
+
+ const { unmount } = renderHook(() => useRoadtripRoutes(7, days, map(1, stops)))
+ await waitFor(() => expect(seen).toBeDefined())
+ expect(seen!.aborted).toBe(false)
+
+ unmount()
+ expect(seen!.aborted).toBe(true)
+ })
+})
diff --git a/server/src/nest/maps/maps.service.ts b/server/src/nest/maps/maps.service.ts
index 8fd19fbaa..52ce87aee 100644
--- a/server/src/nest/maps/maps.service.ts
+++ b/server/src/nest/maps/maps.service.ts
@@ -1209,7 +1209,7 @@ export class MapsService {
const osmLang = toApiLang(lang).split('-')[0].toLowerCase();
// Serve repeat pans/toggles of the same area straight from the cache.
- const cacheKey = `${[...categories].sort().join('+')}|${osmLang}|${south.toFixed(2)},${west.toFixed(2)},${north.toFixed(2)},${east.toFixed(2)}|${cap}`;
+ const cacheKey = `${[...categories].sort((a, b) => a.localeCompare(b)).join('+')}|${osmLang}|${south.toFixed(2)},${west.toFixed(2)},${north.toFixed(2)},${east.toFixed(2)}|${cap}`;
const cached = POI_CACHE.get(cacheKey);
if (cached && Date.now() - cached.at < POI_CACHE_TTL_MS) return cached.value;
if (cached) POI_CACHE.delete(cacheKey); // expired — drop it before refetching
diff --git a/server/tests/unit/nest/maps.controller.test.ts b/server/tests/unit/nest/maps.controller.test.ts
index 1567b4ebe..9ec209b96 100644
--- a/server/tests/unit/nest/maps.controller.test.ts
+++ b/server/tests/unit/nest/maps.controller.test.ts
@@ -438,4 +438,67 @@ describe('MapsController (parity with the legacy /api/maps route)', () => {
expect(reverse).toHaveBeenCalledWith('1', '2', 'fr');
});
});
+
+ describe('GET /brand-logo/:wikidataId', () => {
+ /** The same response double the photo-bytes cases use, minus their streaming. */
+ function makeRes() {
+ const sent: Buffer[] = [];
+ const res = {
+ statusCode: 200,
+ status: vi.fn((c: number) => { res.statusCode = c; return res; }),
+ set: vi.fn(),
+ type: vi.fn(),
+ send: vi.fn((b: Buffer) => { sent.push(b); return res; }),
+ end: vi.fn(),
+ json: vi.fn(),
+ body: () => Buffer.concat(sent),
+ };
+ return res as unknown as Response & {
+ status: ReturnType<typeof vi.fn>;
+ set: ReturnType<typeof vi.fn>;
+ type: ReturnType<typeof vi.fn>;
+ send: ReturnType<typeof vi.fn>;
+ end: ReturnType<typeof vi.fn>;
+ body: () => Buffer;
+ };
+ }
+
+ it('serves the flattened bytes with the type the service reports', async () => {
+ const bytes = Buffer.from('89504e470d0a1a0a', 'hex');
+ const brandLogo = vi.fn().mockResolvedValue({ bytes, contentType: 'image/png' });
+ const res = makeRes();
+
+ await makeController({ brandLogo }).brandLogo('Q565734', res);
+
+ expect(brandLogo).toHaveBeenCalledWith('Q565734');
+ expect(res.type).toHaveBeenCalledWith('image/png');
+ expect(res.set).toHaveBeenCalledWith('Cache-Control', 'public, max-age=2592000, immutable');
+ expect(res.body()).toEqual(bytes);
+ });
+
+ // A pin whose brand has no logo keeps its category icon. Answering 404 for each of
+ // those is the ban vector from #1727 all over again — a map full of them is a burst
+ // of 404s at the instance — so an unknown brand answers 204 with no body.
+ it('204 without a body, and without an immutable header, when there is no logo', async () => {
+ const res = makeRes();
+
+ await makeController({ brandLogo: vi.fn().mockResolvedValue(null) }).brandLogo('Q1', res);
+
+ expect(res.status).toHaveBeenCalledWith(204);
+ expect(res.end).toHaveBeenCalled();
+ expect(res.send).not.toHaveBeenCalled();
+ // A brand whose logo appears later must not stay hidden behind a month-old empty.
+ expect(res.set).toHaveBeenCalledWith('Cache-Control', 'no-store');
+ });
+
+ it('an id that is not a wikidata id is answered, not thrown at the caller', async () => {
+ const brandLogo = vi.fn().mockResolvedValue(null);
+ const res = makeRes();
+
+ await makeController({ brandLogo }).brandLogo('../../etc/passwd', res);
+
+ expect(res.status).toHaveBeenCalledWith(204);
+ expect(brandLogo).toHaveBeenCalledWith('../../etc/passwd');
+ });
+ });
});