fix(roadtrip): a booked ferry is driven to, and one without a date says so

A ferry between two stops without a clock was seated by the clock alone, which files a
ride with nothing timed before it at the end of the day. The desktop day list stored that
slot, and the road trip drove overland to the far shore and back to the pier before the
crossing. A ride that leaves and lands on the same day, with both terminals located, now
takes the seat between the clocks that adds the fewest straight-line kilometres. One rule
in shared seats it for the day list, the slot the desktop stores, the phone and PDF lists
and the road trip in the browser and on the server. Slots already stored are left alone.

A flight, train, ferry, cruise or bus on no day made no seam and said nothing, while the
map still drew its arc. The rail and the phone tab now name such a booking with a way to
open it, and calculate_roadtrip lists it under undatedRides.
This commit is contained in:
Maurice
2026-09-23 10:21:00 +02:00
parent e6daed9403
commit ab3a81a9eb
37 changed files with 823 additions and 41 deletions
@@ -2522,6 +2522,55 @@ describe('DayPlanSidebar', () => {
expect(stored!.day_plan_position).toBe(positions[1].day_plan_position)
})
// The crossing from the report behind #2461: Amsterdam and Newcastle on the day, the
// ferry from IJmuiden to the Port of Tyne in the evening. The slot written here is the
// one every other reader takes from then on, the road trip included.
const crossing = (newcastleAt: string | null, withAmsterdam = true) => {
const day = buildDay({ id: 10, date: '2026-10-06', title: 'Day 2' })
const amsterdam = buildPlace({ id: 1, name: 'Amsterdam', lat: 52.3731, lng: 4.8926 })
const newcastle = buildPlace({ id: 2, name: 'Newcastle', lat: 54.9783, lng: -1.6178, place_time: newcastleAt })
const stops = [
buildAssignment({ id: 11, day_id: 10, order_index: 0, place: amsterdam }),
buildAssignment({ id: 12, day_id: 10, order_index: 1, place: newcastle }),
].filter(a => withAmsterdam || a.id !== 11)
const ferry = buildReservation({
id: 69, type: 'ferry', title: 'IJmuiden to Newcastle', day_id: 10,
reservation_time: '2026-10-06T17:30', reservation_end_time: '2026-10-06T23:00',
endpoints: [
{ role: 'from', sequence: 0, name: 'IJmuiden', code: null, lat: 52.4581, lng: 4.5879, timezone: null, local_date: null, local_time: null },
{ role: 'to', sequence: 1, name: 'Port of Tyne', code: null, lat: 54.9925, lng: -1.4522, timezone: null, local_date: null, local_time: null },
],
})
seedStore(useTripStore, { reservations: [ferry] })
render(<DayPlanSidebar {...makeDefaultProps({
days: [day], places: [amsterdam, newcastle], reservations: [ferry], assignments: { '10': stops },
})} />)
}
it('FE-PLANNER-DAYPLAN-218: a ferry between two untimed stops on its two shores is given the slot between them (#2461)', async () => {
const { reservationsApi } = await import('../../api/client')
crossing(null)
await waitFor(() => expect(vi.mocked(reservationsApi.updatePositions)).toHaveBeenCalled())
// By the clock alone it closed the day at 2.5, and the drive went overland first.
expect(vi.mocked(reservationsApi.updatePositions).mock.calls[0][1]).toEqual([{ id: 69, day_plan_position: 0.5 }])
expect(useTripStore.getState().reservations.find(r => r.id === 69)!.day_plan_position).toBe(0.5)
})
it('FE-PLANNER-DAYPLAN-219: a stop timed before the ferry keeps it behind that stop (#2461)', async () => {
const { reservationsApi } = await import('../../api/client')
crossing('10:00')
await waitFor(() => expect(vi.mocked(reservationsApi.updatePositions)).toHaveBeenCalled())
expect(vi.mocked(reservationsApi.updatePositions).mock.calls[0][1]).toEqual([{ id: 69, day_plan_position: 1.5 }])
})
it('FE-PLANNER-DAYPLAN-220: a ferry landing next to the only stop of the day opens it (#2461)', async () => {
const { reservationsApi } = await import('../../api/client')
crossing(null, false)
await waitFor(() => expect(vi.mocked(reservationsApi.updatePositions)).toHaveBeenCalled())
// Ahead of Newcastle, which is stored at order_index 1 here.
expect(vi.mocked(reservationsApi.updatePositions).mock.calls[0][1]).toEqual([{ id: 69, day_plan_position: 0.5 }])
})
it('FE-PLANNER-DAYPLAN-204: a rejected slot write puts the bookings back where the server has them', async () => {
const { reservationsApi } = await import('../../api/client')
vi.mocked(reservationsApi.updatePositions).mockRejectedValueOnce(new Error('offline'))
@@ -35,7 +35,7 @@ import { isDayInAccommodationRange, getAccommodationAnchors, getDayBookendHotels
import {
TRANSPORT_TYPES, parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getDisplayTimeForDay, getTransportRouteEndpoints,
getTransportForDay as _getTransportForDay, getMergedItems as _getMergedItems, isCarrierTransport, hasCarrierEndpointOnDay,
getAssignmentReservations, timedSlot,
getAssignmentReservations, timedSlot, rideSeatKey,
type MergedItem,
} from '../../utils/dayMerge'
import { withinDriveRange } from '../../utils/geo'
@@ -439,6 +439,13 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// Compute initial day_plan_position for a transport based on time
const computeTransportPosition = (r, da) => {
// A ride that lands today goes where it adds the least road between the same clocks,
// by the rule the list and the road trip seat it with (`rideSeatKey`). This slot is
// stored, so seated by the clock alone a ferry between two untimed stops stayed at
// the end of the day, and the drive went overland before the crossing (#2461).
const seat = rideSeatKey(r, da.map(a => ({ type: 'place' as const, sortKey: a.order_index, data: a })))
if (seat === -Infinity) return Math.min(...da.map(a => a.order_index)) - 0.5
if (seat !== null) return seat + 0.5
const minutes = parseTimeToMinutes(r.reservation_time) ?? 0
// Find the last place with time <= transport time
let afterIdx = -1
@@ -1397,4 +1397,41 @@ describe('RoadtripSidebar with the drive in from the day before (#2461)', () =>
wrap(<RoadtripSidebar routes={routes({ days: [joined({ arrivingLine: undefined })] })} onAskAlternatives={vi.fn()} />)
expect(screen.getAllByLabelText('Other ways')).toHaveLength(1)
})
describe('a ride on no day (#2461)', () => {
const terminals = [
{ role: 'from', sequence: 0, name: 'IJmuiden', code: null, lat: 52.4581, lng: 4.5879, timezone: null, local_date: null, local_time: null },
{ role: 'to', sequence: 1, name: 'Port of Tyne', code: null, lat: 54.9925, lng: -1.4522, timezone: null, local_date: null, local_time: null },
]
const ferry = (over: Partial<Reservation>): Reservation =>
({ id: 70, trip_id: 1, type: 'ferry', title: 'IJmuiden to Newcastle', status: 'confirmed', day_id: null, endpoints: terminals, ...over }) as unknown as Reservation
it('FE-ROADTRIP-SIDEBAR-062: is named under the totals with its booking a click away; one on a day or without terminals is not', () => {
const onOpenBooking = vi.fn()
const reservations = [
ferry({}),
// On a day it is on the drive already; without terminals nothing says where it runs.
ferry({ id: 71, title: 'Dated ferry', day_id: 1 }),
ferry({ id: 72, title: 'Unlocated ferry', endpoints: [] } as Partial<Reservation>),
ferry({ id: 73, title: 'Table', type: 'restaurant' }),
]
wrap(<RoadtripSidebar routes={routes()} reservations={reservations} onOpenBooking={onOpenBooking} />)
const notice = screen.getByRole('status')
expect(within(notice).getByText('IJmuiden to Newcastle has no date, so the drive does not use it.')).toBeInTheDocument()
expect(within(notice).getAllByRole('listitem')).toHaveLength(1)
fireEvent.click(within(notice).getByRole('button', { name: 'Open booking' }))
expect(onOpenBooking).toHaveBeenCalledWith(70)
})
it('FE-ROADTRIP-SIDEBAR-063: says so without a button where bookings cannot be opened, and says nothing when every ride has a day', () => {
const reader = wrap(<RoadtripSidebar routes={routes()} reservations={[ferry({})]} />)
expect(screen.getByText('IJmuiden to Newcastle has no date, so the drive does not use it.')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Open booking' })).toBeNull()
reader.unmount()
wrap(<RoadtripSidebar routes={routes()} reservations={[ferry({ day_id: 1 })]} onOpenBooking={vi.fn()} />)
expect(screen.queryByRole('status')).toBeNull()
})
})
})
@@ -23,7 +23,7 @@ import StopKindPicker from './StopKindPicker'
import StopFillPicker from './StopFillPicker'
import { useVehicleRange } from './useVehicleRange'
import { MAX_TRIP_DAYS, type RoadtripStopType } from '@trek/shared'
import { isCarrierMode, type CarrierTerminal } from '@trek/shared/roadtrip'
import { isCarrierMode, undatedRides, type CarrierTerminal } from '@trek/shared/roadtrip'
import type { QuietDay, RoadtripDay, RoadtripRoutes, RoadtripStop } from './useRoadtripRoutes'
import type { SpillMark } from './nightSpill'
import { ARRIVING_DRIVE, openOn, type LegAlternatives, type RailDrive } from './useRouteAlternatives'
@@ -2025,6 +2025,42 @@ function QuietDaySection({ day, onMoveStopToDay, drag }: {
)
}
/**
* The rides the drive leaves out because they are on no day (#2461).
*
* The map draws such a booking's arc between its terminals all the same, so without this
* the ferry looked planned while the rail drove round it by road. One line each, with the
* booking a click away, since the fix is a date in the booking itself.
*/
function UndatedRides({ rides, onOpenBooking }: {
rides: readonly Reservation[]
onOpenBooking?: RoadtripSidebarProps['onOpenBooking']
}): React.ReactElement | null {
const { t } = useTranslation()
if (!rides.length) return null
return (
<div role="status" className="mx-3.5 mt-2 rounded-xl bg-warning-soft p-3 text-caption text-content">
<ul className="flex flex-col gap-1.5">
{rides.map(ride => (
<li key={ride.id} className="flex items-start gap-2">
<AlertTriangle size={13} strokeWidth={2} aria-hidden="true" className="mt-0.5 shrink-0 text-warning" />
<span className="min-w-0 flex-1">{t('roadtrip.ride.undated', { title: ride.title })}</span>
{onOpenBooking ? (
<button
type="button"
onClick={() => onOpenBooking(ride.id)}
className="shrink-0 font-semibold text-content underline underline-offset-2 hover:text-content-secondary"
>
{t('roadtrip.ride.open')}
</button>
) : null}
</li>
))}
</ul>
</div>
)
}
/**
* The road trip rail: the whole trip as one chain of stops with the driving distance
* and time between them.
@@ -2057,6 +2093,7 @@ export default function RoadtripSidebar({
const numbers = new Map([...routes.days, ...routes.quietDays].map(d => [d.dayId, d.dayNumber]))
return (dayId: number): number | null => numbers.get(dayId) ?? null
}, [routes.days, routes.quietDays])
const undated = useMemo(() => undatedRides(reservations ?? []), [reservations])
// Nothing to total up, so nothing pretends to: no "0 km" standing above "No route yet".
if (routes.days.length === 0) {
@@ -2091,6 +2128,7 @@ export default function RoadtripSidebar({
{t(`roadtrip.window.${routes.dayWindowIssue}`, { days: MAX_TRIP_DAYS })}
</p>
) : null}
<UndatedRides rides={undated} onOpenBooking={onOpenBooking} />
</div>
<div className="roadtrip-rail-scroll flex min-h-0 flex-1 flex-col gap-2.5 overflow-y-auto pb-3.5">
{routes.days.map(day => (
@@ -20,7 +20,8 @@ import { arrivingReroutable, legReroutable, type StopRow } from '../../../../com
import { ARRIVING_DRIVE, type RailDrive } from '../../../../components/Roadtrip/useRouteAlternatives'
import { dayBookings } from '../../../../components/Roadtrip/stopBookings'
import { getDayOrder } from '../../../../utils/dayOrder'
import type { Reservation } from '../../../../types'
import { undatedRides } from '@trek/shared/roadtrip'
import type { Reservation, TranslationFn } from '../../../../types'
/**
* The road trip tab: one day of the drive, as a chain or on the map.
@@ -102,6 +103,8 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
if (stage && byIndex) for (const [i, list] of byIndex.atStop) atStop.set(stage.stops[i]!.assignmentId, list)
return { atStop, loose: byIndex?.loose ?? [] }
}, [stage, planner.reservations, dayOrder])
// The rides on no day, which the drive leaves out: listed above the stage, whichever it is.
const undated = useMemo(() => undatedRides(planner.reservations), [planner.reservations])
// A chip that may not be opened is not a button in the first place (`bookingOpens`),
// so nothing is turned away silently here.
const canEditBookings = planner.can('reservation_edit', planner.trip)
@@ -169,6 +172,7 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {
searchBar ? 'pt-[calc(var(--m-safe-top,12px)+150px)]' : 'pt-[calc(var(--m-safe-top,12px)+102px)]'
}`}
>
<UndatedRides rides={undated} t={t} onOpen={openBooking} />
{noDayPicked ? (
<PickDay planner={planner} />
) : rt.empty || !stage ? (
@@ -414,6 +418,37 @@ function UpNext({ planner, shell, rt, stageDayId, onOpen }: {
)
}
/**
* The rides the drive leaves out because they are on no day (#2461), each with its
* booking a tap away.
*
* The map half draws such a booking's arc between its terminals all the same, so without
* this the ferry looked planned while the chain went round it by road. Which bookings
* these are is decided once, in @trek/shared (`undatedRides`), for the desktop rail too.
*/
function UndatedRides({ rides, t, onOpen }: {
rides: readonly Reservation[]
t: TranslationFn
onOpen: (res: Reservation) => void
}) {
if (!rides.length) return null
return (
<div role="status" className="mb-2.5 rounded-[18px] bg-[color-mix(in_srgb,var(--m-st-pending)_12%,transparent)] px-3.5 py-2.5">
<ul className="flex flex-col gap-1.5">
{rides.map(ride => (
<li key={ride.id} className="flex items-start gap-2 text-caption font-semibold text-[color:var(--m-st-pending)]">
<AlertTriangle size={13} strokeWidth={2} aria-hidden="true" className="mt-[2px] shrink-0" />
<span className="min-w-0 flex-1">{t('roadtrip.ride.undated', { title: ride.title })}</span>
<button type="button" onClick={() => onOpen(ride)} className="shrink-0 text-m-ink underline underline-offset-2">
{t('roadtrip.ride.open')}
</button>
</li>
))}
</ul>
</div>
)
}
/**
* An empty stage is not a failure.
*
+54 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getTransportRouteEndpoints, getDisplayTimeForDay, getTransportForDay, getAssignmentReservations, getMergedItems, timedSlot } from './dayMerge'
import { parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getTransportRouteEndpoints, getDisplayTimeForDay, getTransportForDay, getAssignmentReservations, getMergedItems, rideSeatKey, timedSlot } from './dayMerge'
describe('parseTimeToMinutes', () => {
it('parses HH:MM string', () => {
@@ -304,6 +304,59 @@ describe('getMergedItems', () => {
})
})
// The crossing from the report behind #2461: Amsterdam and Newcastle on the day, the
// ferry from IJmuiden to the Port of Tyne in the evening. The road trip seats its
// terminals by the same rule (`rideSeatAfter` in @trek/shared), so list and drive agree.
describe('getMergedItems: a ride within one day, seated by where it goes (#2461)', () => {
const place = (id: number, order_index: number, lat: number, lng: number, place_time: string | null = null) =>
({ id, order_index, place: { lat, lng, place_time } })
const amsterdam = (at: string | null = null) => place(1, 0, 52.3731, 4.8926, at)
const newcastle = (at: string | null = null) => place(2, 1, 54.9783, -1.6178, at)
const ferry = (over: Record<string, unknown> = {}) => ({
id: 69, type: 'ferry', title: 'IJmuiden to Newcastle', day_id: 5, end_day_id: 5,
reservation_time: '2026-10-06T17:30', reservation_end_time: '2026-10-06T23:00',
endpoints: [
{ role: 'from', sequence: 0, name: 'IJmuiden', lat: 52.4581, lng: 4.5879 },
{ role: 'to', sequence: 1, name: 'Port of Tyne', lat: 54.9925, lng: -1.4522 },
],
...over,
})
const read = (dayAssignments: unknown[], dayTransports: unknown[], dayNotes: unknown[] = []) =>
getMergedItems({ dayAssignments, dayNotes, dayTransports, dayId: 5 }).map(i => `${i.type}:${i.data.id}`)
it('puts a ferry between the stops on its two shores rather than at the end of the day', () => {
expect(read([amsterdam(), newcastle()], [ferry()])).toEqual(['place:1', 'transport:69', 'place:2'])
})
it('keeps it behind a stop timed before its departure, and leaves a ferry without terminals to the clock', () => {
expect(read([amsterdam(), newcastle('10:00')], [ferry()])).toEqual(['place:1', 'place:2', 'transport:69'])
expect(read([amsterdam(), newcastle()], [ferry({ endpoints: [] })])).toEqual(['place:1', 'place:2', 'transport:69'])
// One that lands tomorrow has no seat of its own on this day either.
expect(read([amsterdam(), newcastle()], [ferry({ end_day_id: 6 })])).toEqual(['place:1', 'place:2', 'transport:69'])
})
it('opens the day with a ride that lands next to its first stop, ahead of a note too', () => {
expect(read([newcastle()], [ferry()], [{ id: 10, sort_order: 0 }])).toEqual(['transport:69', 'place:2', 'note:10'])
})
it('leaves a slot somebody stored where it is', () => {
expect(read([amsterdam(), newcastle()], [ferry({ day_positions: { 5: 1.5 } })])).toEqual(['place:1', 'place:2', 'transport:69'])
})
it('reads a note as nothing and another booking as its clock only', () => {
const rows = [
{ type: 'place' as const, sortKey: 0, data: amsterdam() },
{ type: 'note' as const, sortKey: 0.5, data: { id: 10, time: '20:00' } },
{ type: 'place' as const, sortKey: 1, data: newcastle() },
]
expect(rideSeatKey(ferry(), rows)).toBe(0)
// A bus at 18:00 between the two is a clock after the departure: the ferry stays ahead of it.
const bus = { type: 'transport' as const, sortKey: 0.5, data: { id: 11, type: 'bus', reservation_time: '18:00' } }
expect(rideSeatKey(ferry(), [rows[0], bus, rows[2]])).toBeNull()
expect(rideSeatKey({ ...ferry(), type: 'taxi' }, rows)).toBeNull()
})
})
// A stop with a start is drawn by it, and the road trip drives the stored order, so a
// stop joining a day from elsewhere is stored where the list will draw it.
describe('timedSlot', () => {
+44 -3
View File
@@ -1,4 +1,5 @@
import { chronoOrder } from '@trek/shared'
import { rideSeatAfter, sameDayRide, type CarrierBooking, type SeatItem } from '@trek/shared/roadtrip'
// `orderedEndpoints` is the geometry order's single source of truth, in the module
// that documents the multi-leg model. Sorting endpoints a second time here is how
// the two drift.
@@ -289,6 +290,38 @@ function applyChronoOrder(
})
}
/** A row of the day list as the seat of a ride reads it; a note is none (see rideSeatKey). */
function seatItemsOf(row: MergedItem): SeatItem[] {
if (row.type === 'place') {
const place = row.data?.place
const located = Number.isFinite(place?.lat) && Number.isFinite(place?.lng)
return [{
key: row.sortKey,
minutes: parseTimeToMinutes(place?.place_time),
point: located ? { lat: place.lat, lng: place.lng } : null,
}]
}
if (row.type === 'transport') {
return [{ key: row.sortKey, minutes: parseTimeToMinutes(row.data?.reservation_time), point: null }]
}
return []
}
/**
* Where a booking without a saved slot goes among the day's rows by where it goes: the
* key of the row it goes behind, -Infinity to open the day, or null to leave it to the
* clock. Only a ride that leaves and lands on this day, with both terminals located,
* has a say (`sameDayRide`); the rule itself is `rideSeatAfter` in @trek/shared, which
* the road trip seats its terminals with, so the list and the drive keep one order.
*
* A place counts with its time and its coordinates, another booking with its time, a
* note not at all: the clock rule this refines never read a note's time either.
*/
export function rideSeatKey(r: CarrierBooking, rows: readonly MergedItem[]): number | null {
const ride = sameDayRide(r)
return ride ? rideSeatAfter(rows.flatMap(seatItemsOf), ride) : null
}
/** Merge places, notes, and transports into a single ordered day timeline. */
export function getMergedItems(opts: {
dayAssignments: any[]
@@ -345,11 +378,19 @@ export function getMergedItems(opts: {
if (tm !== null && tm <= minutes) insertAfterKey = item.sortKey
}
}
// A ride that lands today may sit elsewhere between the same clocks, where it adds
// the least road. Without that, a ferry between two untimed stops closed the day and
// the drive went to the far shore overland before the crossing (#2461).
const seat = rideSeatKey(timed.data, result)
if (seat !== null) insertAfterKey = seat
const lastKey = result.length > 0 ? Math.max(...result.map(i => i.sortKey)) : 0
const sortKey = insertAfterKey === -Infinity
? lastKey + 0.5 + ti * 0.01
: insertAfterKey + 0.01 + ti * 0.001
const firstKey = result.length > 0 ? Math.min(...result.map(i => i.sortKey)) : 0
const sortKey = seat === -Infinity
? firstKey - 0.5 - ti * 0.01
: insertAfterKey === -Infinity
? lastKey + 0.5 + ti * 0.01
: insertAfterKey + 0.01 + ti * 0.001
result.push({ type: timed.type, sortKey, data: timed.data })
}