fix(planner): scope transit picks by day and rank other stays by date

This commit is contained in:
Raz Erlich
2026-11-16 22:34:01 +02:00
committed by Maurice
parent 0834d4f8fe
commit 9a7bce6fd8
8 changed files with 881 additions and 61 deletions
@@ -357,7 +357,7 @@ describe('TransitSearchPanel', () => {
await user.click(fromInput)
const picks = (await screen.findAllByRole('button', { name: /Hotel Adlon|Stop \d|Hostel/ })).map(b => b.textContent)
expect(picks[0]).toBe('Hotel Adlon')
expect(picks.slice(1)).toEqual(['Stop 1', 'Stop 2', 'Stop 3', 'Stop 4', 'Stop 5', 'Stop 6', 'Stop 7', 'Stop 8'])
expect(picks.slice(1)).toEqual([...places.map(p => p.name), 'Later Hostel'])
await user.click(screen.getByRole('button', { name: 'Hotel Adlon' }))
expect(fromInput).toHaveValue('Hotel Adlon')
@@ -744,7 +744,7 @@ describe('quick picks from the bookings of the day (#1506)', () => {
const places = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 100 + i, name: `P${i}`, lat: 52 + i / 100, lng: 13 }))
const picks = buildQuickPicks(day, [day], places as any, [], dayBookingStops(day, [flight] as any))
expect(picks.slice(0, 2).map(p => p.name)).toEqual(['FRA', 'BER Airport'])
expect(picks).toHaveLength(2 + 8)
expect(picks).toHaveLength(2 + places.length)
})
})
@@ -8,7 +8,8 @@ import { transitApi } from '../../api/client'
import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { getDayBookendHotels } from '../../utils/dayOrder'
import { getDayBookendHotels, isDayInAccommodationRange } from '../../utils/dayOrder'
import { orderTransitStaysByDate } from './transitStayOrder'
import type { Day, Place, Accommodation, Reservation } from '../../types'
import { useTripStore } from '../../store/tripStore'
import { isCarrierTransport } from '../../utils/dayMerge'
@@ -110,7 +111,11 @@ function fmtDuration(seconds: number, t: (k: string, p?: Record<string, string |
// ── quick picks ──────────────────────────────────────────────────────────────
const MAX_QUICK_PICKS = 8
const MAX_OTHER_DAY_STAYS = 8
function pickedPlaceKey(p: PickedPlace): string {
return JSON.stringify([p.name.trim().toLowerCase(), p.lat, p.lng])
}
function stayPick(a: Accommodation): PickedPlace | null {
return a.place_lat != null && a.place_lng != null && a.place_name ? { name: a.place_name, lat: a.place_lat, lng: a.place_lng } : null
@@ -143,28 +148,30 @@ export function dayBookingStops(day: Pick<Day, 'id' | 'date'>, reservations: Res
* starts in and the one it ends in come first and are never cut, since most
* connections of a day begin or end there (#2538); the day's airports and
* stations follow and are not cut either (#1506); then the day's own located
* places and the trip's other stays, up to MAX_QUICK_PICKS.
* places and remaining stays covering the day, without a limit. Only stays
* outside the selected day's range are capped, nearest in nights first.
*/
export function buildQuickPicks(day: Day, days: Day[], places: Place[], accommodations: Accommodation[], bookingStops: PickedPlace[] = []): PickedPlace[] {
const { morning, evening } = getDayBookendHotels(day, days, accommodations)
const dayStays = [morning, evening].filter((a): a is Accommodation => a != null)
const bookendStays = [morning, evening].filter((a): a is Accommodation => a != null)
const dayStays = accommodations.filter(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days))
const seen = new Set<string>()
const unique = (p: PickedPlace | null): p is PickedPlace => {
if (!p) return false
const k = `${p.name}:${p.lat}`
const k = pickedPlaceKey(p)
if (seen.has(k)) return false
seen.add(k)
return true
}
const stays = dayStays.map(stayPick).filter(unique)
const stays = bookendStays.map(stayPick).filter(unique)
const stations = bookingStops.filter(unique)
const rest = [
...places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)),
...accommodations.filter(a => !dayStays.includes(a)).map(stayPick),
].filter(unique)
return [...stays, ...stations, ...rest.slice(0, MAX_QUICK_PICKS)]
const dayPlaces = places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)).filter(unique)
const remainingDayStays = dayStays.map(stayPick).filter(unique)
const otherStays = orderTransitStaysByDate(day, days, accommodations.filter(a => !dayStays.includes(a)))
.map(stayPick).filter(unique).slice(0, MAX_OTHER_DAY_STAYS)
return [...stays, ...stations, ...dayPlaces, ...remainingDayStays, ...otherStays]
}
// ── from/to stop picker ──────────────────────────────────────────────────────
@@ -221,6 +228,8 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
const [results, setResults] = useState<TransitPlaceResult[]>([])
const [open, setOpen] = useState(false)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
// Ignore lookups superseded by another query, a saved pick, or leaving this day.
const requestId = useRef(0)
const rootRef = useRef<HTMLDivElement>(null)
const fieldRef = useRef<HTMLDivElement>(null)
const listRef = useRef<HTMLDivElement>(null)
@@ -235,21 +244,45 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
return () => document.removeEventListener('mousedown', close)
}, [])
useEffect(() => () => { if (debounceRef.current) clearTimeout(debounceRef.current) }, [])
useEffect(() => () => {
requestId.current += 1
if (debounceRef.current) clearTimeout(debounceRef.current)
}, [])
const search = (q: string) => {
const id = ++requestId.current
setText(q)
setResults([])
onPick(null)
if (debounceRef.current) clearTimeout(debounceRef.current)
if (q.trim().length < 2) { setResults([]); return }
if (q.trim().length < 2) return
debounceRef.current = setTimeout(() => {
transitApi.geocode(q, { lang: language, near: near || undefined })
.then((d: { results: TransitPlaceResult[] }) => setResults(d.results || []))
.catch(() => setResults([]))
.then((d: { results: TransitPlaceResult[] }) => { if (id === requestId.current) setResults(d.results || []) })
.catch(() => { if (id === requestId.current) setResults([]) })
}, 300)
}
const display = value ? value.name : text
const query = text.trim().toLowerCase()
const saved = quickPicks.filter(p => p.name.toLowerCase().includes(query))
const seen = new Set(saved.map(pickedPlaceKey))
const external = results.filter(p => {
const key = pickedPlaceKey(p)
if (seen.has(key)) return false
seen.add(key)
return true
})
const suggestions: (PickedPlace & { area?: string | null })[] = value ? [] : [...saved, ...external]
const pick = (p: PickedPlace) => {
requestId.current += 1
if (debounceRef.current) clearTimeout(debounceRef.current)
onPick({ name: p.name, lat: p.lat, lng: p.lng })
setText('')
setResults([])
setOpen(false)
}
return (
<div ref={rootRef} style={{ position: 'relative', flex: 1, minWidth: 0 }}>
@@ -267,34 +300,23 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }}
/>
</div>
{open && listPos && (results.length > 0 || (!value && text.trim().length < 2 && quickPicks.length > 0)) && createPortal(
{open && listPos && suggestions.length > 0 && createPortal(
// On the page rather than inside the dialog, so a dialog that scrolls or clips
// its content cannot cut the list off before anything is typed.
<div ref={listRef} className="bg-surface-card border border-edge z-[var(--z-toast)]" style={{ position: 'fixed', left: listPos.left, width: listPos.width, ...(listPos.above ? { bottom: listPos.bottom } : { top: listPos.top }), borderRadius: 10, boxShadow: 'var(--shadow-dropdown)', overflow: 'hidden', maxHeight: listPos.maxHeight, overflowY: 'auto' }}>
{results.length > 0
? results.map((r, i) => (
<button type="button" key={i} onClick={() => { onPick({ name: r.name, lat: r.lat, lng: r.lng }); setText(''); setResults([]); setOpen(false) }}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{r.name}
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
</span>
</button>
))
: quickPicks.map((p, i) => (
<button type="button" key={i} onClick={() => { onPick(p); setText(''); setOpen(false) }}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
</button>
))}
{suggestions.map(r => (
<button type="button" key={pickedPlaceKey(r)} onClick={() => pick(r)}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{r.name}
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
</span>
</button>
))}
</div>,
document.body,
)}
@@ -0,0 +1,664 @@
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAssignment, buildDay, buildPlace, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { buildPlanner } from '../../../tests/helpers/mobileTrip';
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n';
import MTransportFormSheet from '../../mobile/screens/trip/sheets/MTransportFormSheet';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import type { Accommodation, AssignmentsMap, Day, Place } from '../../types';
import type { TransitPrefill } from './transitLeg';
import { TransportModal } from './TransportModal';
// Keep the real day selectors, wrappers and shared stop picker. Only the external
// geocoder is controlled: a saved private place need not exist in that service.
const { geocode, plan } = vi.hoisted(() => ({ geocode: vi.fn(), plan: vi.fn() }));
vi.mock('../../api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('../../api/client')>()),
transitApi: { geocode, plan },
}));
type Surface = 'desktop' | 'phone';
interface Fixture {
days: Day[];
places: Place[];
assignments: AssignmentsMap;
accommodations: Accommodation[];
transitPrefill?: TransitPrefill;
selectedDayId?: number;
}
function fixture(): Fixture {
const days = [
buildDay({ id: 101, trip_id: 1, day_number: 1, date: '2027-06-01', title: 'First day' }),
buildDay({ id: 205, trip_id: 1, day_number: 2, date: '2027-06-02', title: 'Second day' }),
buildDay({ id: 309, trip_id: 1, day_number: 3, date: '2027-06-03', title: 'Empty day' }),
];
const places = ['First private stop', 'Second private stop', 'Shared private stop'].map((name, i) =>
buildPlace({ id: 11 + i, trip_id: 1, name, lat: 52.5 + i / 100, lng: 13.4 })
);
const visit = (dayId: number, p: Place, order: number) =>
buildAssignment({ day_id: dayId, place_id: p.id, place: p, order_index: order });
return {
days,
places,
assignments: {
'101': [visit(101, places[0], 0), visit(101, places[2], 1)],
'205': [visit(205, places[1], 0), visit(205, places[2], 1)],
'309': [],
},
accommodations: [],
};
}
function buildStay(id: number, name: string, start: number, end: number): Accommodation {
return {
id,
trip_id: 1,
place_id: 1000 + id,
start_day_id: start,
end_day_id: end,
place_name: name,
place_lat: 52 + id / 1000,
place_lng: 13,
} as Accommodation;
}
function longTripFixture(): Fixture {
const days = Array.from({ length: 30 }, (_, i) =>
buildDay({
id: 5000 - i * 97,
trip_id: 1,
day_number: i + 1,
date: new Date(Date.UTC(2027, 2, i + 1)).toISOString().slice(0, 10),
title: `Day ${i + 1}`,
})
);
days[28] = { ...days[28], date: null };
const stay = (id: number, name: string, start: number, end: number) =>
buildStay(id, name, days[start - 1].id, days[end - 1].id);
const nearby = Array.from({ length: 4 }, (_, i) => [
stay(10 + i * 2, `Nearby before ${i + 1}`, 18 - i, 20 - i),
stay(11 + i * 2, `Nearby after ${i + 1}`, 22 + i, 24 + i),
]).flat();
return {
days,
places: [],
assignments: {},
selectedDayId: days[20].id,
accommodations: [
stay(1, 'First-week hotel created first', 1, 7),
stay(2, 'Undated hotel', 29, 30),
...nearby.slice().reverse(),
{ ...nearby[0], id: 99 },
stay(100, 'Morning hotel', 20, 21),
stay(101, 'Evening hotel', 21, 22),
...Array.from({ length: 10 }, (_, i) => stay(200 + i, `Current stay ${i + 1}`, 19, 23)),
],
};
}
function Harness({ surface, data }: { surface: Surface; data: Fixture }) {
const { t } = useTranslation();
if (surface === 'phone') {
const planner = buildPlanner({
t,
trip: buildTrip({ id: 1 }),
days: data.days,
places: data.places,
assignments: data.assignments,
storedAssignments: data.assignments,
tripAccommodations: data.accommodations,
showTransportModal: true,
transportModalDayId: data.selectedDayId ?? 101,
transportModalAutomated: true,
transitPrefill: data.transitPrefill ?? null,
});
return <MTransportFormSheet planner={planner} onOpenExpense={vi.fn()} />;
}
return (
<TransportModal
isOpen
onClose={vi.fn()}
onSave={vi.fn()}
reservation={null}
days={data.days}
selectedDayId={data.selectedDayId ?? 101}
initialAutomated
places={data.places}
assignments={data.assignments}
accommodations={data.accommodations}
transitPrefill={data.transitPrefill}
/>
);
}
const inputs = () => screen.getAllByPlaceholderText('Search stop or station…');
async function switchDay(user: ReturnType<typeof userEvent.setup>, current: string, next: string) {
await user.click(screen.getByText(current));
await user.click(screen.getByRole('button', { name: new RegExp(`^${next}`) }));
}
const pickNames = () => screen.queryAllByRole('button', { name: /private stop/ }).map((b) => b.textContent);
beforeEach(() => {
resetAllStores();
geocode.mockReset().mockResolvedValue({ results: [] });
plan.mockReset();
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), reservations: [] });
});
describe.each<Surface>(['desktop', 'phone'])('Automated transport day selection: %s', (surface) => {
beforeEach(() => {
Object.defineProperty(window, 'innerWidth', { configurable: true, value: surface === 'phone' ? 390 : 1440 });
fireEvent(window, new Event('resize'));
});
it('scopes both pickers by day id and keeps a shared place when switching back and forth', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[1]);
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
await switchDay(user, 'Second day', 'First day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
});
it('keeps all nine eligible day places available in the dropdown', async () => {
const user = userEvent.setup();
const data = fixture();
const stops = Array.from({ length: 9 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
data.places.push(...stops);
data.assignments['101'] = stops.map((p, i) =>
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
);
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.queryAllByRole('button', { name: /^Day stop/ }).map((b) => b.textContent)).toEqual(
stops.map((p) => p.name)
);
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
});
it('finds an assigned private place when the geocoder has no result', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await user.click(inputs()[0]);
await user.type(inputs()[0], 'First private');
await waitFor(() => expect(geocode).toHaveBeenCalled());
await act(async () => {
await Promise.resolve();
});
expect(screen.queryByRole('button', { name: 'First private stop' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
});
it('ranks matching saved places before external matches and deduplicates by name and both coordinates', async () => {
const user = userEvent.setup();
const data = fixture();
const saved = data.places[0];
const other = { name: 'External private stop', lat: 52.8, lng: 13.8, area: 'Berlin' };
geocode.mockResolvedValue({
results: [
other,
{ name: saved.name.toUpperCase(), lat: saved.lat, lng: saved.lng, area: 'Duplicate' },
{ ...other },
{ name: saved.name, lat: saved.lat, lng: 13.9, area: 'Other longitude' },
],
});
render(<Harness surface={surface} data={data} />);
await user.type(inputs()[0], 'private');
await screen.findByRole('button', { name: /External private stop/ });
const rows = screen.getAllByRole('button', { name: /private stop/i });
expect(rows.map((row) => row.textContent)).toEqual([
'First private stop',
'Shared private stop',
'External private stopBerlin',
'First private stopOther longitude',
]);
expect(geocode).toHaveBeenCalledTimes(1);
await user.click(rows[0]);
expect(inputs()[0]).toHaveValue(saved.name);
});
it('limits only other-day stays, keeping current hotels, terminals and every selected-day place first', async () => {
const user = userEvent.setup();
const data = fixture();
const stops = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
// A same-name stop at a different longitude must not be dropped as a duplicate.
stops.push(buildPlace({ id: 62, name: stops[0].name, lat: stops[0].lat, lng: 10 }));
data.places.push(...stops);
data.assignments['101'] = stops.map((p, i) =>
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
);
data.accommodations = Array.from(
{ length: 12 },
(_, i) =>
({
id: 70 + i,
trip_id: 1,
place_id: 70 + i,
start_day_id: i === 0 ? 101 : 205,
end_day_id: i === 0 ? 101 : 205,
place_name: i === 0 ? 'Current hotel' : `Other hotel ${i}`,
place_lat: 52 + i / 100,
place_lng: 13,
}) as Accommodation
);
// Duplicate stays must not consume another slot of the other-day allowance.
data.accommodations.splice(2, 0, { ...data.accommodations[1], id: 90 });
seedStore(useTripStore, {
reservations: [
{
id: 81,
trip_id: 1,
type: 'train',
day_id: 101,
end_day_id: 101,
endpoints: [{ role: 'from', name: 'Current terminal', lat: 52, lng: 13, local_date: '2027-06-01' }],
},
] as ReturnType<typeof useTripStore.getState>['reservations'],
});
render(<Harness surface={surface} data={data} />);
for (const input of inputs()) {
await user.click(input);
const rows = screen.getAllByRole('button', { name: /Current hotel|Current terminal|Day stop|Other hotel/ });
expect(rows.map((row) => row.textContent)).toEqual([
'Current hotel',
'Current terminal',
...stops.map((p) => p.name),
...Array.from({ length: 8 }, (_, i) => `Other hotel ${i + 1}`),
]);
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
}
});
it('keeps more than eight current-day hotels selectable and searchable despite earlier other-day stays', async () => {
const user = userEvent.setup();
const data = fixture();
const current = Array.from({ length: 12 }, (_, i) => buildStay(200 + i, `Current day hotel ${i + 1}`, 101, 101));
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Other day hotel ${i + 1}`, 205, 205));
data.accommodations = [
...other,
...current,
{ ...current[8], id: 999 },
{ ...buildStay(300, 'Unlocated current hotel', 101, 101), place_lat: null },
];
render(<Harness surface={surface} data={data} />);
for (const input of inputs()) {
await user.click(input);
expect(screen.getAllByRole('button', { name: /^Current day hotel/ }).map((b) => b.textContent)).toEqual(
current.map((a) => a.place_name)
);
expect(screen.getAllByRole('button', { name: /^Other day hotel/ }).map((b) => b.textContent)).toEqual(
other.slice(0, 8).map((a) => a.place_name)
);
expect(screen.queryByRole('button', { name: 'Unlocated current hotel' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
}
await user.type(inputs()[1], 'current day hotel 12');
await user.click(screen.getByRole('button', { name: 'Current day hotel 12' }));
expect(inputs()[1]).toHaveValue('Current day hotel 12');
});
it('offers Hotel 09 on Day 3 for the manual-review booking pattern without using mirrored day places', async () => {
const user = userEvent.setup();
const data = fixture();
const a = buildStay(1, 'Hotel A — first night', 101, 205);
const b = buildStay(2, 'Hotel B — second night', 205, 309);
const sameDay = Array.from({ length: 9 }, (_, i) =>
buildStay(3 + i, `Other night hotel ${String(i + 1).padStart(2, '0')}`, 309, 309)
);
data.accommodations = [a, b, ...sameDay];
// Days hides accommodation-owned mirror assignments: hotels must come from the stays themselves.
data.assignments['309'] = [];
render(<Harness surface={surface} data={data} />);
await switchDay(user, 'First day', 'Empty day');
for (const input of inputs()) {
await user.click(input);
expect(
screen.getAllByRole('button', { name: /Hotel A|Hotel B|Other night hotel/ }).map((row) => row.textContent)
).toEqual([b.place_name, ...sameDay.map((stay) => stay.place_name), a.place_name]);
}
await user.click(screen.getByRole('button', { name: 'Other night hotel 09' }));
expect(inputs()[1]).toHaveValue('Other night hotel 09');
});
it('keeps multi-night stays and checkout-day stays uncapped, with bookends before the other current stays', async () => {
const user = userEvent.setup();
const data = fixture();
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Future hotel ${i + 1}`, 309, 309));
const spanning = Array.from({ length: 10 }, (_, i) => buildStay(200 + i, `Multi-night hotel ${i + 1}`, 101, 309));
const checkout = buildStay(300, 'Checks out today', 101, 205);
const checkin = buildStay(301, 'Checks in today', 205, 309);
data.accommodations = [...other, ...spanning, checkout, checkin];
render(<Harness surface={surface} data={data} />);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(
screen
.getAllByRole('button', { name: /Multi-night hotel|Checks (in|out) today|Future hotel/ })
.map((row) => row.textContent)
).toEqual([
spanning[0].place_name,
checkin.place_name,
...spanning.slice(1).map((stay) => stay.place_name),
checkout.place_name,
...other.slice(0, 8).map((stay) => stay.place_name),
]);
expect(screen.queryByRole('button', { name: 'Future hotel 9' })).not.toBeInTheDocument();
});
it('does not let a first-week hotel take a Day 21 slot from eight closer stays on a 30-day trip', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={longTripFixture()} />);
for (const input of inputs()) {
await user.click(input);
expect(screen.queryByRole('button', { name: 'First-week hotel created first' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Undated hotel' })).not.toBeInTheDocument();
expect(
screen
.getAllByRole('button', { name: /Morning hotel|Evening hotel|Current stay|Nearby/ })
.map((row) => row.textContent)
).toEqual([
'Morning hotel',
'Evening hotel',
...Array.from({ length: 10 }, (_, i) => `Current stay ${i + 1}`),
...Array.from({ length: 4 }, (_, i) => [`Nearby before ${i + 1}`, `Nearby after ${i + 1}`]).flat(),
]);
}
});
it('puts undated stays last and orders identical dated intervals by stay id independently of input order', async () => {
const user = userEvent.setup();
const data = longTripFixture();
const dated = data.accommodations.find((stay) => stay.place_name === 'Nearby after 1');
if (!dated) throw new Error('Missing dated fixture');
const undated = data.accommodations.find((stay) => stay.place_name === 'Undated hotel');
if (!undated) throw new Error('Missing undated fixture');
data.accommodations = [
undated,
{ ...dated, id: 90, place_name: 'Same dates higher id', place_lng: 14 },
{ ...dated, id: 80, place_name: 'Same dates lower id', place_lng: 15 },
];
const view = render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
const names = () =>
screen.getAllByRole('button', { name: /Same dates|Undated hotel/ }).map((row) => row.textContent);
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
view.rerender(
<Harness surface={surface} data={{ ...data, accommodations: data.accommodations.slice().reverse() }} />
);
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
});
it('refreshes an open dropdown after places are added, removed and reordered', async () => {
const user = userEvent.setup();
const data = fixture();
const view = render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
const added = buildPlace({ id: 99, name: 'Added private stop' });
const next = {
...data,
places: [...data.places, added],
assignments: {
...data.assignments,
'101': [
{ ...data.assignments['101'][1], order_index: 2 },
buildAssignment({ day_id: 101, place_id: added.id, place: added, order_index: 0 }),
],
},
};
view.rerender(<Harness surface={surface} data={next} />);
expect(pickNames()).toEqual(['Added private stop', 'Shared private stop']);
});
it('keeps place membership tied to ids when days and their dates are reordered', async () => {
const user = userEvent.setup();
const data = fixture();
const view = render(<Harness surface={surface} data={data} />);
const reordered = {
...data,
days: [
{ ...data.days[1], day_number: 1, date: data.days[0].date },
{ ...data.days[0], day_number: 2, date: data.days[1].date },
data.days[2],
],
};
view.rerender(<Harness surface={surface} data={reordered} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
});
it('does not retain endpoints from an unrelated day after selecting from and to', async () => {
const user = userEvent.setup();
const data = fixture();
// Make the first day's two endpoints exclusive to that day.
data.assignments['205'] = [data.assignments['205'][0]];
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
await user.click(screen.getByRole('button', { name: 'First private stop' }));
await user.click(inputs()[1]);
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
await switchDay(user, 'First day', 'Second day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('clears search state when changing days so the next day offers its own places', async () => {
const user = userEvent.setup();
geocode.mockResolvedValue({ results: [{ name: 'Old external station', lat: 52, lng: 13, area: null }] });
render(<Harness surface={surface} data={fixture()} />);
await user.type(inputs()[0], 'Old station');
await screen.findByRole('button', { name: 'Old external station' });
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(screen.queryByRole('button', { name: 'Old external station' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('scopes day-plan endpoint, time and walk prefills to the opening day', async () => {
const user = userEvent.setup();
const data = fixture();
data.transitPrefill = {
from: { name: 'Walk end', lat: 52.5, lng: 13.4 },
to: { name: 'Next walk start', lat: 52.6, lng: 13.5 },
time: '12:15',
walk: {
dayId: 101,
fromWalk: 'Old town',
toWalk: 'Harbour',
ends: '12:15',
endsNextDay: false,
endsAtLeast: false,
nextStarts: '13:00',
},
};
render(<Harness surface={surface} data={data} />);
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
expect(screen.getByDisplayValue('12:15')).toBeInTheDocument();
await switchDay(user, 'First day', 'Second day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
expect(screen.queryByTestId('transit-walk-end')).not.toBeInTheDocument();
expect(screen.queryByDisplayValue('12:15')).not.toBeInTheDocument();
await switchDay(user, 'Second day', 'First day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
});
it('drops old itineraries when changing the day', async () => {
const user = userEvent.setup();
const data = fixture();
const stop = (name: string, time: string) => ({
name,
lat: 52.5,
lng: 13.4,
time,
scheduledTime: null,
track: null,
});
plan.mockResolvedValue({
itineraries: [
{
startTime: '2027-06-01T07:00:00Z',
endTime: '2027-06-01T07:30:00Z',
duration: 1800,
transfers: 0,
walkSeconds: 0,
legs: [
{
mode: 'SUBWAY',
from: stop('A', '2027-06-01T07:00:00Z'),
to: stop('B', '2027-06-01T07:30:00Z'),
duration: 1800,
distance: null,
headsign: null,
line: 'U88',
lineColor: null,
lineTextColor: null,
agency: null,
intermediateStops: 0,
},
],
},
],
});
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
await user.click(screen.getByRole('button', { name: 'First private stop' }));
await user.click(inputs()[1]);
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
await user.click(screen.getByRole('button', { name: /^Search$/ }));
await screen.findByText('U88');
await switchDay(user, 'First day', 'Second day');
expect(screen.queryByText('U88')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Add to day' })).not.toBeInTheDocument();
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('ignores an old geocoder response after the day changes', async () => {
const user = userEvent.setup();
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
throw new Error('lookup not started');
};
geocode.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
})
);
render(<Harness surface={surface} data={fixture()} />);
await user.type(inputs()[0], 'Old station');
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
await act(async () => {
finish({ results: [{ name: 'Late old station', lat: 52, lng: 13, area: null }] });
});
expect(screen.queryByRole('button', { name: 'Late old station' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
expect(inputs()[0]).toHaveValue('');
});
it('ignores a superseded geocoder response after a saved place is picked', async () => {
const user = userEvent.setup();
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
throw new Error('lookup not started');
};
geocode.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
})
);
render(<Harness surface={surface} data={fixture()} />);
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
fireEvent.change(inputs()[0], { target: { value: 'First private' } });
fireEvent.focus(inputs()[0]);
fireEvent.click(screen.getByRole('button', { name: 'First private stop' }));
await act(async () => {
finish({ results: [{ name: 'Superseded station', lat: 52, lng: 13, area: null }] });
});
await user.clear(inputs()[0]);
expect(screen.queryByRole('button', { name: 'Superseded station' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
expect(geocode).toHaveBeenCalledTimes(1);
});
it('offers no unrelated regular places on an empty day', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await switchDay(user, 'First day', 'Empty day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual([]);
});
it('offers the active stay and other trip stays intentionally, even on a booking-only day', async () => {
const user = userEvent.setup();
const data = fixture();
data.assignments['101'] = [];
const stay = (id: number, name: string, dayId: number): Accommodation =>
({
id,
trip_id: 1,
place_id: id,
start_day_id: dayId,
end_day_id: dayId,
place_name: name,
place_lat: 52 + id / 100,
place_lng: 13,
}) as Accommodation;
data.accommodations = [stay(70, 'Current hotel', 101), stay(71, 'Later hotel', 205)];
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'Current hotel' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Later hotel' })).toBeInTheDocument();
expect(pickNames()).toEqual([]);
});
it('offers only the selected day transport terminals on a transport-only day', async () => {
const user = userEvent.setup();
const data = fixture();
data.assignments['101'] = [];
const endpoint = (role: 'from' | 'to', name: string, date: string) => ({
role,
name,
lat: 52,
lng: 13,
local_date: date,
});
seedStore(useTripStore, {
reservations: [
{
id: 81,
trip_id: 1,
type: 'train',
day_id: 101,
end_day_id: 205,
endpoints: [
endpoint('from', 'First terminal', '2027-06-01'),
endpoint('to', 'Second terminal', '2027-06-02'),
],
},
] as ReturnType<typeof useTripStore.getState>['reservations'],
});
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'First terminal' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second terminal' })).not.toBeInTheDocument();
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'Second terminal' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'First terminal' })).not.toBeInTheDocument();
});
});
@@ -20,6 +20,7 @@ import type { TripMember } from '../Budget/BudgetPanelMemberChips'
import type { BookingExpenseRequest } from './BookingCostsSection.types'
import type { BookingReviewDraft } from './parsedItemToDraft'
import TransitSearchPanel from './TransitSearchPanel'
import { getTransitDayPlaces } from './transitDayPlaces'
import type { TransitPrefill } from './transitLeg'
import { BookingDialogHeader, StatusPill } from './bookings/BookingDialogShell'
import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton } from '../shared/DialogShell'
@@ -287,22 +288,20 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
const transitSearch = () => {
const transitDay = days.find(d => d.id === Number(form.start_day_id))
if (!transitDay) return <p className="m-0 text-content-faint" style={fs(13, 'body')}>{t('transit.pickDay')}</p>
// Quick picks offer the chosen day's itinerary, not the whole trip (#1460).
const dayPlaces = (assignments[String(transitDay.id)] || [])
.slice().sort((a, b) => a.order_index - b.order_index)
.map(a => places.find(p => p.id === a.place_id))
.filter((p): p is Place => p != null)
const dayPlaces = getTransitDayPlaces(transitDay.id, assignments, places)
const dayPrefill = transitDay.id === selectedDayId ? transitPrefill : null
return (
<TransitSearchPanel
key={transitDay.id}
day={transitDay}
days={days}
places={dayPlaces}
accommodations={accommodations}
onAdd={(payload) => onSave(payload as Record<string, any> & { title: string })}
initialFrom={transitPrefill?.from ?? null}
initialTo={transitPrefill?.to ?? null}
initialTime={transitPrefill?.time ?? null}
walk={transitPrefill?.walk ?? null}
initialFrom={dayPrefill?.from ?? null}
initialTo={dayPrefill?.to ?? null}
initialTime={dayPrefill?.time ?? null}
walk={dayPrefill?.walk ?? null}
/>
)
}
@@ -0,0 +1,10 @@
import type { AssignmentsMap, Place } from '../../types';
/** Resolve the chosen day's places by day id, in itinerary order (#1460). */
export function getTransitDayPlaces(dayId: number, assignments: AssignmentsMap, places: Place[]): Place[] {
return (assignments[String(dayId)] ?? [])
.slice()
.sort((a, b) => a.order_index - b.order_index)
.map((a) => places.find((p) => p.id === a.place_id))
.filter((p): p is Place => p != null);
}
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest';
import { buildDay } from '../../../tests/helpers/factories';
import type { Accommodation } from '../../types';
import { orderTransitStaysByDate } from './transitStayOrder';
const day = buildDay({ id: 500, date: '2027-03-21', day_number: 21 });
const stay = (id: number, start: number, end = start) =>
({ id, start_day_id: start, end_day_id: end }) as Accommodation;
const refs = [
buildDay({ id: 900, date: '2027-03-01', day_number: 1 }),
buildDay({ id: 700, date: '2027-03-19', day_number: 19 }),
buildDay({ id: 600, date: '2027-03-20', day_number: 20 }),
day,
buildDay({ id: 400, date: '2027-03-22', day_number: 22 }),
buildDay({ id: 300, date: '2027-03-23', day_number: 23 }),
];
const ids = (stays: Accommodation[]) => stays.map((a) => a.id);
describe('orderTransitStaysByDate', () => {
it('uses the whole interval: an early check-in with a nearby checkout is close', () => {
const spanning = stay(1, 900, 600);
const future = stay(2, 400, 300);
const farther = stay(3, 700);
expect(ids(orderTransitStaysByDate(day, refs, [farther, future, spanning]))).toEqual([1, 2, 3]);
});
it('puts the earlier interval first at equal distance, then earlier checkout and stable stay id', () => {
const list = [stay(90, 400, 300), stay(2, 600), stay(80, 400, 300), stay(100, 400)];
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 100, 80, 90]);
expect(ids(orderTransitStaysByDate(day, refs, list.slice().reverse()))).toEqual([2, 100, 80, 90]);
});
it('places missing, incomplete and invalid calendar dates after dated stays', () => {
const dates = [
...refs,
buildDay({ id: 10, date: null }),
buildDay({ id: 11, date: '2027-02-30' }),
buildDay({ id: 12, date: 'not-a-date' }),
];
const list = [stay(4, 10), stay(3, 11), stay(2, 12), stay(5, 600, 10), stay(6, 99999), stay(9, 900)];
expect(ids(orderTransitStaysByDate(day, dates, list))).toEqual([9, 2, 3, 4, 5, 6]);
});
it('handles leap days without accepting a normalized invalid date', () => {
const selected = buildDay({ id: 1, date: '2028-03-01' });
const dates = [selected, buildDay({ id: 2, date: '2028-02-29' }), buildDay({ id: 3, date: '2027-02-29' })];
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
});
it('uses updated calendar dates after days are reordered, regardless of array order or numeric ids', () => {
const before = stay(1, 600);
const after = stay(2, 400);
const reordered = refs
.map((d) =>
d.id === 600
? { ...d, date: '2027-03-22', day_number: 22 }
: d.id === 400
? { ...d, date: '2027-03-20', day_number: 20 }
: d
)
.reverse();
expect(ids(orderTransitStaysByDate(day, refs, [after, before]))).toEqual([1, 2]);
expect(ids(orderTransitStaysByDate(day, reordered, [before, after]))).toEqual([2, 1]);
});
it('counts calendar nights equally across the spring DST boundary', () => {
const selected = buildDay({ id: 1, date: '2027-03-29' });
const dates = [selected, buildDay({ id: 2, date: '2027-03-28' }), buildDay({ id: 3, date: '2027-03-30' })];
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
});
it('normalizes reversed interval endpoints consistently with day-range membership', () => {
expect(ids(orderTransitStaysByDate(day, refs, [stay(1, 700), stay(2, 300, 600)]))).toEqual([2, 1]);
});
it('keeps dated stays ahead of undated ones when the selected day has no usable date', () => {
const selected = { ...day, date: null };
expect(ids(orderTransitStaysByDate(selected, refs, [stay(1, 99999), stay(3, 300), stay(2, 900)]))).toEqual([
2, 3, 1,
]);
});
it('does not mutate the caller list', () => {
const list = Object.freeze([stay(1, 300), stay(2, 600)]);
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 1]);
expect(ids([...list])).toEqual([1, 2]);
});
});
@@ -0,0 +1,37 @@
import type { Accommodation, Day } from '../../types';
/** A strict calendar date as a UTC day number, so DST never changes the number of nights. */
function nightNumber(value: string | null | undefined): number | null {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const time = Date.parse(`${value}T00:00:00Z`);
if (!Number.isFinite(time) || new Date(time).toISOString().slice(0, 10) !== value) return null;
return time / 86_400_000;
}
/** Rank other-day stays by the closest boundary of their complete booking interval. */
export function orderTransitStaysByDate(
day: Pick<Day, 'date'>,
days: readonly Pick<Day, 'id' | 'date'>[],
stays: readonly Accommodation[]
): Accommodation[] {
const selected = nightNumber(day.date);
const dates = new Map(days.map((d) => [d.id, nightNumber(d.date)]));
return stays
.map((stay) => {
const start = dates.get(stay.start_day_id);
const end = dates.get(stay.end_day_id);
// A partial or invalid interval has no usable proximity and follows every dated stay.
const lo = start != null && end != null ? Math.min(start, end) : Infinity;
const hi = start != null && end != null ? Math.max(start, end) : Infinity;
const distance = selected != null && lo !== Infinity ? Math.max(lo - selected, selected - hi, 0) : Infinity;
// Earlier check-in, then earlier check-out, then stable booking identity break ties.
return { stay, rank: [distance, lo, hi, stay.id] };
})
.sort((a, b) => {
for (let i = 0; i < a.rank.length; i++) {
if (a.rank[i] !== b.rank[i]) return a.rank[i] < b.rank[i] ? -1 : 1;
}
return 0;
})
.map((row) => row.stay);
}
@@ -11,6 +11,7 @@ import AirportSelect from '../../../../components/Planner/AirportSelect'
import LocationSelect from '../../../../components/Planner/LocationSelect'
import { toLocationPicks } from '../../../../components/Planner/locationPicks'
import TransitSearchPanel from '../../../../components/Planner/TransitSearchPanel'
import { getTransitDayPlaces } from '../../../../components/Planner/transitDayPlaces'
import {
EMPTY_TRANSPORT_FIELDS, TRANSPORT_TYPE_OPTIONS as TYPE_OPTIONS, emptyCarStop, emptyStationWaypoint, emptyWaypoint,
transportDayOptions, type StationWaypointForm, type WaypointForm,
@@ -21,7 +22,7 @@ import { useBookingFollowUp } from '../../../../components/Planner/useBookingFol
import { useBookingExpenseIntent } from '../../../../components/Planner/useBookingExpenseIntent'
import { Eyebrow, FIELD_CLS, FormSheetBody, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
import MBookingFilesCosts from './MBookingFilesCosts'
import type { Place, Reservation } from '../../../../types'
import type { Reservation } from '../../../../types'
import type { BookingReviewDraft } from '../../../../components/Planner/parsedItemToDraft'
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
import type { TripPlanner } from '../MTripShell'
@@ -226,23 +227,21 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo
if (!transitDay) {
return <div className="mt-3 font-geist text-[0.78125rem] text-m-faint">{t('transit.pickDay')}</div>
}
// Quick picks offer the chosen day's itinerary, not the whole trip.
const dayPlaces = (assignments[String(transitDay.id)] || [])
.slice().sort((a, b) => a.order_index - b.order_index)
.map(a => places.find(p => p.id === a.place_id))
.filter((p): p is Place => p != null)
const dayPlaces = getTransitDayPlaces(transitDay.id, assignments, places)
const dayPrefill = transitDay.id === transportModalDayId ? transitPrefill : null
return (
<div className="mt-4">
<TransitSearchPanel
key={transitDay.id}
day={transitDay}
days={days}
places={dayPlaces}
accommodations={tripAccommodations}
onAdd={(p) => saveTransport(p as Record<string, unknown> & { title: string })}
initialFrom={transitPrefill?.from ?? null}
initialTo={transitPrefill?.to ?? null}
initialTime={transitPrefill?.time ?? null}
walk={transitPrefill?.walk ?? null}
initialFrom={dayPrefill?.from ?? null}
initialTo={dayPrefill?.to ?? null}
initialTime={dayPrefill?.time ?? null}
walk={dayPrefill?.walk ?? null}
/>
</div>
)