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.

refactor(planner): the day header's stay order lives in its own module and its tests in their own file

Mauricecc94bc69537f
diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.json
index 005f789fd..40fb14cc5 100644
--- a/client/scripts/size-baseline.json
+++ b/client/scripts/size-baseline.json
@@ -11,8 +11,8 @@
"src/components/Map/RouteCalculator.ts": 1195,
"src/components/PDF/TripPDF.tsx": 1097,
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
- "src/components/Planner/DayPlanSidebar.test.tsx": 5403,
- "src/components/Planner/DayPlanSidebar.tsx": 3060,
+ "src/components/Planner/DayPlanSidebar.test.tsx": 5381,
+ "src/components/Planner/DayPlanSidebar.tsx": 3052,
"src/components/Planner/PlaceFormModal.test.tsx": 2864,
"src/components/Planner/PlaceFormModal.tsx": 1250,
"src/components/Planner/PlaceInspector.tsx": 1308,
diff --git a/client/src/components/Planner/DayPlanSidebar.dayHead.test.tsx b/client/src/components/Planner/DayPlanSidebar.dayHead.test.tsx
new file mode 100644
index 000000000..d2b8cac7e
--- /dev/null
+++ b/client/src/components/Planner/DayPlanSidebar.dayHead.test.tsx
@@ -0,0 +1,222 @@
+// FE-PLANNER-DAYPLAN-236: the drag data a booking drop leaves behind. The mocks
+// are the ones DayPlanSidebar.test.tsx renders the sidebar with.
+import userEvent from '@testing-library/user-event';
+import { http, HttpResponse } from 'msw';
+import { buildDay, buildTrip, buildUser } from '../../../tests/helpers/factories';
+import { server } from '../../../tests/helpers/msw/server';
+import { render, screen } from '../../../tests/helpers/render';
+import { resetAllStores, seedStore } from '../../../tests/helpers/store';
+import { clearExchangeRateCache } from '../../hooks/useExchangeRates';
+import { useAuthStore } from '../../store/authStore';
+import { useSettingsStore } from '../../store/settingsStore';
+import { useTripStore } from '../../store/tripStore';
+import type { Accommodation } from '../../types';
+import DayPlanSidebar from './DayPlanSidebar';
+
+// ── Hoisted mock state (accessible in vi.mock factories) ────────────────────
+const mockDayNotesState = vi.hoisted(() => ({
+ noteUi: {} as Record<string, unknown>,
+ dayNotes: {} as Record<string, unknown[]>,
+ setNoteUi: vi.fn(),
+ noteInputRef: { current: null } as { current: null },
+ openAddNote: vi.fn(),
+ openEditNote: vi.fn(),
+ cancelNote: vi.fn(),
+ saveNote: vi.fn(),
+ deleteNote: vi.fn(),
+ moveNote: vi.fn(),
+}));
+
+// ── Module mocks ────────────────────────────────────────────────────────────
+
+vi.mock('../../api/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../api/client')>();
+ return {
+ ...actual,
+ assignmentsApi: {
+ reorder: vi.fn().mockResolvedValue({}),
+ remove: vi.fn().mockResolvedValue({}),
+ updateTime: vi.fn().mockResolvedValue({}),
+ updateTransport: vi.fn().mockResolvedValue({}),
+ },
+ reservationsApi: {
+ list: vi.fn().mockResolvedValue({ reservations: [] }),
+ updatePositions: vi.fn().mockResolvedValue({}),
+ },
+ daysApi: {
+ ...actual.daysApi,
+ updateTransport: vi.fn().mockResolvedValue({}),
+ },
+ };
+});
+
+vi.mock('../PDF/TripPDF', () => ({ downloadTripPDF: vi.fn().mockResolvedValue(undefined) }));
+
+vi.mock('../Map/RouteCalculator', () => ({
+ calculateRoute: vi.fn().mockResolvedValue({ distanceText: '5 km', durationText: '1h', coordinates: [] }),
+ generateGoogleMapsUrl: vi.fn().mockReturnValue('https://maps.google.com/...'),
+ generateCoMapsUrl: vi.fn().mockReturnValue('https://comaps.at/...'),
+ optimizeRoute: vi.fn().mockImplementation((places) => places),
+ // One leg per waypoint gap; the connector between two stops reads distanceText.
+ calculateRouteWithLegs: vi.fn().mockImplementation((waypoints) =>
+ Promise.resolve({
+ distanceText: '2 km',
+ durationText: '10 min',
+ legs: Array.from({ length: Math.max(0, (waypoints?.length ?? 0) - 1) }, () => ({
+ distanceText: '2 km',
+ durationText: '10 min',
+ drivingText: '10 min',
+ walkingText: '25 min',
+ })),
+ })
+ ),
+}));
+
+// PlaceAvatar needs IntersectionObserver
+class MockIO {
+ observe = vi.fn();
+ disconnect = vi.fn();
+ unobserve = vi.fn();
+}
+beforeAll(() => {
+ (globalThis as unknown as { IntersectionObserver: unknown }).IntersectionObserver = MockIO;
+});
+
+vi.mock('../../services/photoService', () => ({
+ getCached: vi.fn(() => null),
+ isLoading: vi.fn(() => false),
+ fetchPhoto: vi.fn(),
+ onThumbReady: vi.fn(() => () => {}),
+}));
+
+vi.mock('../../hooks/useDayNotes', () => ({
+ useDayNotes: () => mockDayNotesState,
+}));
+
+vi.mock('../Weather/WeatherWidget', () => ({
+ default: (props: { locationName?: string | null }) => (
+ <span data-testid="weather-widget" data-location={props.locationName ?? ''} />
+ ),
+}));
+
+// A stable toast object so tests can assert on the messages the sidebar raises.
+const mockToast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn() }));
+
+vi.mock('../shared/Toast', () => ({
+ useToast: () => mockToast,
+}));
+
+vi.mock('../../store/permissionsStore', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../store/permissionsStore')>()),
+ useCanDo: () => () => true,
+}));
+
+const trip = buildTrip({ id: 1, currency: 'EUR' });
+
+function makeDefaultProps(overrides = {}) {
+ return {
+ tripId: 1,
+ trip,
+ days: [],
+ places: [],
+ categories: [],
+ assignments: {},
+ selectedDayId: null,
+ selectedPlaceId: null,
+ selectedAssignmentId: null,
+ onSelectDay: vi.fn(),
+ onPlaceClick: vi.fn(),
+ onDayDetail: vi.fn(),
+ accommodations: [],
+ onReorder: vi.fn(),
+ onUpdateDayTitle: vi.fn(),
+ onRouteCalculated: vi.fn(),
+ onAssignToDay: vi.fn(),
+ onRemoveAssignment: vi.fn(),
+ onEditPlace: vi.fn(),
+ onDeletePlace: vi.fn(),
+ reservations: [],
+ onAddReservation: vi.fn(),
+ onNavigateToFiles: vi.fn(),
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ resetAllStores();
+ vi.clearAllMocks();
+ Element.prototype.scrollTo = vi.fn();
+ clearExchangeRateCache();
+ server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([])));
+ seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
+ seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
+ seedStore(useSettingsStore, { settings: { time_format: '24h', temperature_unit: 'celsius' } } as never);
+});
+
+function dayHeader(title: string) {
+ return screen.getByText(title).closest('[style*="cursor: pointer"]') as HTMLElement;
+}
+
+describe('DayPlanSidebar day header', () => {
+ it('FE-PLANNER-DAYPLAN-176: a transfer day lists the check-out hotel before the check-in one', async () => {
+ const user = userEvent.setup();
+ const days = [
+ buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
+ buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
+ buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
+ ];
+ const accommodations: Accommodation[] = [
+ {
+ id: 1,
+ trip_id: 1,
+ start_day_id: 11,
+ end_day_id: 12,
+ place_id: 9,
+ place_lat: 51.5,
+ place_lng: -0.12,
+ place_name: 'Check-in Hotel',
+ },
+ {
+ id: 2,
+ trip_id: 1,
+ start_day_id: 10,
+ end_day_id: 11,
+ place_id: 8,
+ place_lat: 48.85,
+ place_lng: 2.35,
+ place_name: 'Check-out Hotel',
+ },
+ ];
+ const onPlaceClick = vi.fn();
+ render(<DayPlanSidebar {...makeDefaultProps({ days, accommodations, onPlaceClick })} />);
+ const badges = dayHeader('Day 2').querySelectorAll('[data-dp="day-pill"]');
+ expect(badges[0].textContent).toBe('Check-out Hotel');
+ expect(badges[1].textContent).toBe('Check-in Hotel');
+ await user.click(badges[0]);
+ expect(onPlaceClick).toHaveBeenCalledWith(8);
+ });
+
+ it('FE-PLANNER-DAYPLAN-176c: a day without a stay centres its name on the badge, a day with one keeps it at the top', () => {
+ const days = [
+ buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
+ buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
+ buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
+ ];
+ const accommodations: Accommodation[] = [
+ {
+ id: 1,
+ trip_id: 1,
+ start_day_id: 11,
+ end_day_id: 12,
+ place_id: 9,
+ place_lat: 51.5,
+ place_lng: -0.12,
+ place_name: 'Hotel',
+ },
+ ];
+ render(<DayPlanSidebar {...makeDefaultProps({ days, accommodations })} />);
+ expect(dayHeader('Day 1').style.alignItems).toBe('center');
+ expect(dayHeader('Day 1').querySelector('[data-dp="day-pill"]')).toBeNull();
+ expect(dayHeader('Day 2').style.alignItems).toBe('flex-start');
+ });
+});
diff --git a/client/src/components/Planner/DayPlanSidebar.test.tsx b/client/src/components/Planner/DayPlanSidebar.test.tsx
index 00dad0da6..16d2d05fd 100644
--- a/client/src/components/Planner/DayPlanSidebar.test.tsx
+++ b/client/src/components/Planner/DayPlanSidebar.test.tsx
@@ -4444,41 +4444,6 @@ describe('DayPlanSidebar', () => {
// ── Day header details ───────────────────────────────────────────────────
- it('FE-PLANNER-DAYPLAN-176: a transfer day lists the check-out hotel before the check-in one', async () => {
- const user = userEvent.setup()
- const days = [
- buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
- buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
- buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
- ]
- const accommodations: Accommodation[] = [
- { id: 1, trip_id: 1, start_day_id: 11, end_day_id: 12, place_id: 9, place_lat: 51.5, place_lng: -0.12, place_name: 'Check-in Hotel' },
- { id: 2, trip_id: 1, start_day_id: 10, end_day_id: 11, place_id: 8, place_lat: 48.85, place_lng: 2.35, place_name: 'Check-out Hotel' },
- ]
- const onPlaceClick = vi.fn()
- render(<DayPlanSidebar {...makeDefaultProps({ days, accommodations, onPlaceClick })} />)
- const badges = dayHeader('Day 2').querySelectorAll('[data-dp="day-pill"]')
- expect(badges[0].textContent).toBe('Check-out Hotel')
- expect(badges[1].textContent).toBe('Check-in Hotel')
- await user.click(badges[0])
- expect(onPlaceClick).toHaveBeenCalledWith(8)
- })
-
- it('FE-PLANNER-DAYPLAN-176c: a day without a stay centres its name on the badge, a day with one keeps it at the top', () => {
- const days = [
- buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
- buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
- buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
- ]
- const accommodations: Accommodation[] = [
- { id: 1, trip_id: 1, start_day_id: 11, end_day_id: 12, place_id: 9, place_lat: 51.5, place_lng: -0.12, place_name: 'Hotel' },
- ]
- render(<DayPlanSidebar {...makeDefaultProps({ days, accommodations })} />)
- expect(dayHeader('Day 1').style.alignItems).toBe('center')
- expect(dayHeader('Day 1').querySelector('[data-dp="day-pill"]')).toBeNull()
- expect(dayHeader('Day 2').style.alignItems).toBe('flex-start')
- })
-
it('FE-PLANNER-DAYPLAN-176b: a booked stay opens its booking from the pill, the name still opens the place (#2363)', async () => {
const user = userEvent.setup()
const days = [
diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsx
index 3bd91f19c..f6cde7f6f 100644
--- a/client/src/components/Planner/DayPlanSidebar.tsx
+++ b/client/src/components/Planner/DayPlanSidebar.tsx
@@ -40,7 +40,8 @@ const ROW_ROUND = 'grid flex-none place-items-center rounded-full bg-surface-car
const ROUTE_TOOL = 'bg-surface-card shadow-sm ring-1 ring-edge-faint'
import { TypeTile } from './bookings/bookingParts'
import { typeInfo } from './bookings/bookingsModel'
-import { isDayInAccommodationRange, getAccommodationAnchors, getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg, type CarrierEdge } from '../../utils/dayOrder'
+import { dayHeadStays } from './dayHeadStays'
+import { getAccommodationAnchors, getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg, type CarrierEdge } from '../../utils/dayOrder'
import {
TRANSPORT_TYPES, parseTimeToMinutes, getSpanPhase, hidesOnMiddleDay, getDisplayTimeForDay, getTransportRouteEndpoints,
getTransportForDay as _getTransportForDay, getMergedItems as _getMergedItems, isCarrierTransport, hasCarrierEndpointOnDay,
@@ -1600,19 +1601,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
// silently showed another city's weather with nothing naming the place.
const { lat: wLat, lng: wLng, name: weatherName } = dayWeatherAnchor(da, () => dayBookends.morning)
const hasWeather = !!(day.date && wLat != null && wLng != null)
- const dayAccs = accommodations.filter(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days))
- // Sort: check-out first, then ongoing stays, then check-in last
- .sort((a, b) => {
- const aIsOut = a.end_day_id === day.id && a.start_day_id !== day.id
- const bIsOut = b.end_day_id === day.id && b.start_day_id !== day.id
- const aIsIn = a.start_day_id === day.id
- const bIsIn = b.start_day_id === day.id
- if (aIsOut && !bIsOut) return -1
- if (!aIsOut && bIsOut) return 1
- if (aIsIn && !bIsIn) return 1
- if (!aIsIn && bIsIn) return -1
- return 0
- })
+ const dayAccs = dayHeadStays(accommodations, day, days)
const activeRentals = getActiveRentalsForDay(day.id)
// A day with pills under its name keeps the name at the badge's top edge; a day
// with only its name centres it on the badge instead of leaving it hanging high.
diff --git a/client/src/components/Planner/dayHeadStays.test.ts b/client/src/components/Planner/dayHeadStays.test.ts
new file mode 100644
index 000000000..7bc519276
--- /dev/null
+++ b/client/src/components/Planner/dayHeadStays.test.ts
@@ -0,0 +1,22 @@
+import { buildDay } from '../../../tests/helpers/factories';
+import type { Accommodation } from '../../types';
+import { dayHeadStays } from './dayHeadStays';
+
+const days = [
+ buildDay({ id: 10, day_number: 1, date: '2025-06-01' }),
+ buildDay({ id: 11, day_number: 2, date: '2025-06-02' }),
+ buildDay({ id: 12, day_number: 3, date: '2025-06-03' }),
+];
+const stay = (id: number, start: number, end: number) =>
+ ({ id, trip_id: 1, start_day_id: start, end_day_id: end, place_id: id, place_name: `Stay ${id}` }) as Accommodation;
+
+describe('dayHeadStays', () => {
+ it('orders a day check-out first, the stays running through next, check-in last', () => {
+ const accommodations = [stay(1, 11, 12), stay(2, 10, 12), stay(3, 10, 11)];
+ expect(dayHeadStays(accommodations, days[1], days).map((a) => a.id)).toEqual([3, 2, 1]);
+ });
+
+ it('leaves out the stays that do not cover the day', () => {
+ expect(dayHeadStays([stay(1, 11, 12)], days[0], days)).toEqual([]);
+ });
+});
diff --git a/client/src/components/Planner/dayHeadStays.ts b/client/src/components/Planner/dayHeadStays.ts
new file mode 100644
index 000000000..774eb6db9
--- /dev/null
+++ b/client/src/components/Planner/dayHeadStays.ts
@@ -0,0 +1,18 @@
+import type { Accommodation, Day } from '../../types';
+import { isDayInAccommodationRange } from '../../utils/dayOrder';
+
+/**
+ * The stays a day's header names, in the order a traveller meets them that day:
+ * the one checked out of first, then the ones running through, the one checked
+ * into last.
+ */
+export function dayHeadStays(accommodations: Accommodation[], day: Day, days: Day[]): Accommodation[] {
+ const rank = (a: Accommodation) => {
+ if (a.end_day_id === day.id && a.start_day_id !== day.id) return 0;
+ if (a.start_day_id === day.id) return 2;
+ return 1;
+ };
+ return accommodations
+ .filter((a) => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days))
+ .sort((a, b) => rank(a) - rank(b));
+}