From 1b51181930bc518a330cd14096f4a721c7bbe093 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 9 Oct 2026 07:16:39 +0000 Subject: [PATCH] refactor(planner): share the bookings and transports list filters between desktop and phone The bookings model moves from the phone tabs into components/Planner/bookings, so both shells read the same sections, traveller predicate and type colours. The phone bookings and transports tabs had the same traveller filter and folded sections twice; that state now lives once in useReservationListFilter, which only those two tabs use. The desktop panel keeps its own filters in useBookingsView because it remembers them for the session. The status switch and the delete on a booking card stay per shell. The desktop hook renders its ConfirmDialog and awaits the delete, the phone asks in an MConfirmSheet and lets the delete run on its own; sharing them would change when the question closes. --- .../Planner/bookings/bookingParts.tsx | 4 +- .../Planner/bookings/bookingsModel.test.ts | 38 +++++++- .../Planner/bookings/bookingsModel.ts | 60 +++++++++++- .../Planner/bookings/openAttachment.test.ts | 39 ++++++++ .../Planner/bookings/openAttachment.ts | 11 +++ .../Planner/bookings/useBookingActions.tsx | 16 +--- .../bookings/useReservationCard.test.ts | 91 ++++++++++++++++++ .../Planner/bookings/useReservationCard.ts | 55 +++++++++++ .../bookings/useReservationDelete.test.ts | 58 ++++++++++++ .../Planner/bookings/useReservationDelete.ts | 38 ++++++++ .../bookings/useReservationListFilter.test.ts | 66 +++++++++++++ .../bookings/useReservationListFilter.ts | 44 +++++++++ .../mobile/screens/trip/tabs/MBookingsTab.tsx | 68 +++++--------- .../screens/trip/tabs/MTransportsTab.tsx | 73 +++++---------- .../mobile/screens/trip/tabs/bookingsModel.ts | 15 --- .../screens/trip/tabs/transportsModel.ts | 92 ++++++------------- .../unit/mobile/trip/transportsModel.test.ts | 42 +++++++-- 17 files changed, 608 insertions(+), 202 deletions(-) create mode 100644 client/src/components/Planner/bookings/openAttachment.test.ts create mode 100644 client/src/components/Planner/bookings/openAttachment.ts create mode 100644 client/src/components/Planner/bookings/useReservationCard.test.ts create mode 100644 client/src/components/Planner/bookings/useReservationCard.ts create mode 100644 client/src/components/Planner/bookings/useReservationDelete.test.ts create mode 100644 client/src/components/Planner/bookings/useReservationDelete.ts create mode 100644 client/src/components/Planner/bookings/useReservationListFilter.test.ts create mode 100644 client/src/components/Planner/bookings/useReservationListFilter.ts delete mode 100644 client/src/mobile/screens/trip/tabs/bookingsModel.ts diff --git a/client/src/components/Planner/bookings/bookingParts.tsx b/client/src/components/Planner/bookings/bookingParts.tsx index c4b49352a..c37a386ea 100644 --- a/client/src/components/Planner/bookings/bookingParts.tsx +++ b/client/src/components/Planner/bookings/bookingParts.tsx @@ -4,13 +4,13 @@ import type { Reservation, TripFile } from '../../../types' import type { ReservationTraveler } from '@trek/shared' import { useTranslation } from '../../../i18n' import { avatarSrc } from '../../../utils/avatarSrc' -import { openFile } from '../../../utils/fileDownload' import GuestBadge from '../../shared/GuestBadge' import { Tooltip } from '../../shared/Tooltip' import { PILL } from '../../shared/DialogShell' import { useToast } from '../../shared/Toast' import { parseMeta, typeInfo } from './bookingsModel' import type { BookingFacts } from './bookingFacts' +import { openAttachment } from './openAttachment' // The phone's card language on the desktop: small Geist eyebrows, framed value // boxes, count pills. Sizes scale with the user's text size setting. @@ -273,7 +273,7 @@ export function TravelerStack({ travelers, max = 3 }: { travelers: ReservationTr export function useOpenFile() { const { t } = useTranslation() const toast = useToast() - return (f: TripFile) => { openFile(f.url, f.original_name).catch(() => toast.error(t('files.openError'))) } + return (f: TripFile) => openAttachment(f, () => toast.error(t('files.openError'))) } /** The attached files, one framed row each, opening the file. */ diff --git a/client/src/components/Planner/bookings/bookingsModel.test.ts b/client/src/components/Planner/bookings/bookingsModel.test.ts index 42f8df30f..6f1fe220e 100644 --- a/client/src/components/Planner/bookings/bookingsModel.test.ts +++ b/client/src/components/Planner/bookings/bookingsModel.test.ts @@ -1,9 +1,11 @@ -// FE-PLANNER-BKMODEL-001 to FE-PLANNER-BKMODEL-040 +// FE-PLANNER-BKMODEL-001 to FE-PLANNER-BKMODEL-043 import { describe, it, expect } from 'vitest'; import { Plane, TramFront, FileText, Hotel } from 'lucide-react'; import { buildAssignment, buildDay, buildPlace, buildReservation } from '../../../../tests/helpers/factories'; import type { Day, Reservation, ReservationEndpoint } from '../../../types'; import { + BOOKING_TYPE_COLOR, + TRANSPORT_TYPE_COLOR, TYPE_ORDER, applyFilters, buildAssignmentLookup, @@ -11,6 +13,8 @@ import { daySpan, displayTitle, groupReservations, + groupTransports, + onTravelers, parseMeta, phaseOf, searchText, @@ -351,3 +355,35 @@ describe('displayTitle', () => { expect(displayTitle(buildReservation({ title: '' }))).toBe(''); }); }); + +describe('onTravelers and the shared type colours', () => { + it('FE-PLANNER-BKMODEL-041: with nobody chosen every booking passes, otherwise one chosen traveller has to be on it', () => { + const shared = buildReservation({ travelers: [{ user_id: 1, username: 'ann' }, { user_id: 2, username: 'bob' }] } as Partial); + const nobody = buildReservation({ travelers: undefined }); + expect(onTravelers(shared, new Set())).toBe(true); + expect(onTravelers(nobody, new Set())).toBe(true); + expect(onTravelers(shared, new Set([2, 9]))).toBe(true); + expect(onTravelers(shared, new Set([9]))).toBe(false); + expect(onTravelers(nobody, new Set([1]))).toBe(false); + }); + + it('FE-PLANNER-BKMODEL-042: the type colours are the ones the type info and the phone tabs paint with', () => { + expect(BOOKING_TYPE_COLOR.hotel).toBe('#8b5cf6'); + expect(BOOKING_TYPE_COLOR.parking).toBe('#2563eb'); + expect(TRANSPORT_TYPE_COLOR.cable_car).toBe('#dc2626'); + expect(typeInfo('hotel').color).toBe(BOOKING_TYPE_COLOR.hotel); + expect(typeInfo('ferry').color).toBe(TRANSPORT_TYPE_COLOR.ferry); + }); + + it('FE-PLANNER-BKMODEL-043: groupTransports orders like the date sort and splits confirmed, pending and transit', () => { + const transit = buildReservation({ id: 1, type: 'transit', status: 'pending', reservation_time: '2025-06-01T07:00' }); + const later = buildReservation({ id: 2, type: 'train', status: 'confirmed', reservation_time: '2025-06-02T09:00' }); + const sooner = buildReservation({ id: 3, type: 'bus', status: 'confirmed', reservation_time: '2025-06-01T09:00' }); + const open = buildReservation({ id: 4, type: 'car', status: 'pending', reservation_time: null, day_id: null }); + const groups = groupTransports([later, transit, open, sooner], days); + expect(groups.confirmed.map(r => r.id)).toEqual([3, 2]); + expect(groups.pending.map(r => r.id)).toEqual([4]); + expect(groups.transit.map(r => r.id)).toEqual([1]); + expect(sortReservations([later, transit, open, sooner], days, 'date', 'asc', label).map(r => r.id)).toEqual([1, 3, 2, 4]); + }); +}); diff --git a/client/src/components/Planner/bookings/bookingsModel.ts b/client/src/components/Planner/bookings/bookingsModel.ts index bd86b4c9d..659b319fc 100644 --- a/client/src/components/Planner/bookings/bookingsModel.ts +++ b/client/src/components/Planner/bookings/bookingsModel.ts @@ -3,8 +3,6 @@ import { TramFront, Users, ParkingSquare, type LucideIcon, } from 'lucide-react' import type { AssignmentsMap, Day, Reservation } from '../../../types' -import { TRANSPORT_TYPE_COLOR } from '../../../mobile/screens/trip/tabs/transportsModel' -import { BOOKING_TYPE_COLOR } from '../../../mobile/screens/trip/tabs/bookingsModel' import { splitReservationDateTime } from '../../../utils/formatters' import { parseReservationMetadata } from '../../../utils/flightLegs' @@ -23,8 +21,33 @@ export interface ReservationTypeInfo { color: string } -// Icons and label keys for every reservation type. The colours come from the phone's -// models so the two shells can never drift apart on what a flight looks like. +/** Type-chip accent per transport type, the same on the desktop and the phone. */ +export const TRANSPORT_TYPE_COLOR: Record = { + flight: '#3b82f6', + train: '#06b6d4', + bus: '#059669', + car: '#6b7280', + taxi: '#ca8a04', + bicycle: '#84cc16', + cruise: '#0ea5e9', + ferry: '#0d9488', + cable_car: '#dc2626', + transit: '#7c3aed', + transport_other: '#6b7280', +} + +/** Type-chip accent per booking type (hotel, restaurant, event, tour, parking, other). */ +export const BOOKING_TYPE_COLOR: Record = { + hotel: '#8b5cf6', + restaurant: '#ef4444', + event: '#f59e0b', + tour: '#10b981', + parking: '#2563eb', + other: '#6b7280', +} + +// Icons and label keys for every reservation type. The colours above are shared with +// the phone's tabs so the two shells can never drift apart on what a flight looks like. const TYPES: Record = { flight: { Icon: Plane }, train: { Icon: Train }, bus: { Icon: Bus }, car: { Icon: Car }, taxi: { Icon: CarTaxiFront }, bicycle: { Icon: Bike }, cruise: { Icon: Ship }, ferry: { Icon: Sailboat }, cable_car: { Icon: CableCar }, @@ -139,12 +162,17 @@ function matchesStatus(r: Reservation, status: StatusFilter): boolean { return status === 'confirmed' ? r.status === 'confirmed' : r.status !== 'confirmed' } +/** Whether one of the chosen travellers is on the booking; with nobody chosen, every booking passes. */ +export function onTravelers(r: Reservation, travelers: Set): boolean { + return travelers.size === 0 || (r.travelers || []).some(tv => travelers.has(tv.user_id)) +} + export function applyFilters(list: Reservation[], f: BookingFilters, labelOf: (type: string) => string): Reservation[] { const q = f.query.trim().toLowerCase() return list.filter(r => (f.types.size === 0 || f.types.has(r.type)) && matchesStatus(r, f.status) - && (f.travelers.size === 0 || (r.travelers || []).some(tv => f.travelers.has(tv.user_id))) + && onTravelers(r, f.travelers) && (!q || searchText(r, labelOf(r.type)).includes(q)), ) } @@ -182,6 +210,28 @@ export function sortReservations(list: Reservation[], days: Day[], by: SortBy, d .map(x => x.r) } +export interface StatusGroups { + confirmed: Reservation[] + pending: Reservation[] + transit: Reservation[] +} + +/** + * The phone tabs' three sections, each in date order: confirmed and pending, and + * transit (automated public transport, #1065) on its own whatever its status. + * A booking type never matches `transit`, so the split fits the bookings tab too. + */ +export function groupTransports(list: Reservation[], days: Day[]): StatusGroups { + const sorted = sortReservations(list, days, 'date', 'asc', () => '') + const transit = sorted.filter(r => r.type === 'transit') + const nonTransit = sorted.filter(r => r.type !== 'transit') + return { + confirmed: nonTransit.filter(r => r.status === 'confirmed'), + pending: nonTransit.filter(r => r.status !== 'confirmed'), + transit, + } +} + function statusRank(r: Reservation, transitApart: boolean): number { if (r.type === 'transit') return transitApart ? 2 : 0 return r.status === 'confirmed' ? 0 : 1 diff --git a/client/src/components/Planner/bookings/openAttachment.test.ts b/client/src/components/Planner/bookings/openAttachment.test.ts new file mode 100644 index 000000000..847d3dfbb --- /dev/null +++ b/client/src/components/Planner/bookings/openAttachment.test.ts @@ -0,0 +1,39 @@ +// FE-PLANNER-OPENATTACH-001 to -003: opening a booking's attached file. +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { openFile } from '../../../utils/fileDownload'; +import { openAttachment } from './openAttachment'; + +vi.mock('../../../utils/fileDownload', () => ({ openFile: vi.fn(() => Promise.resolve()) })); + +const file = { url: '/uploads/f/1', original_name: 'voucher.pdf' }; + +describe('openAttachment', () => { + // A block body: a hook that returns the mock would have it run again as teardown. + beforeEach(() => { + vi.mocked(openFile).mockReset(); + }); + + it('FE-PLANNER-OPENATTACH-001: opens the file by its url and name', async () => { + vi.mocked(openFile).mockResolvedValue(undefined); + const onError = vi.fn(); + openAttachment(file, onError); + expect(openFile).toHaveBeenCalledWith('/uploads/f/1', 'voucher.pdf'); + await Promise.resolve(); + expect(onError).not.toHaveBeenCalled(); + }); + + it('FE-PLANNER-OPENATTACH-002: a failure reaches onError when one is given', async () => { + vi.mocked(openFile).mockRejectedValue(new Error('offline')); + const onError = vi.fn(); + openAttachment(file, onError); + await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1)); + }); + + it('FE-PLANNER-OPENATTACH-003: without onError it only opens the file', () => { + vi.mocked(openFile).mockResolvedValue(undefined); + expect(openAttachment(file)).toBeUndefined(); + expect(openFile).toHaveBeenCalledTimes(1); + expect(openFile).toHaveBeenCalledWith('/uploads/f/1', 'voucher.pdf'); + }); +}); diff --git a/client/src/components/Planner/bookings/openAttachment.ts b/client/src/components/Planner/bookings/openAttachment.ts new file mode 100644 index 000000000..708917ec2 --- /dev/null +++ b/client/src/components/Planner/bookings/openAttachment.ts @@ -0,0 +1,11 @@ +import { openFile } from '../../../utils/fileDownload'; + +/** + * Opens a file attached to a booking. The desktop panel passes `onError` to say + * so with a toast when the file cannot be opened; the phone's bookings and + * transports cards pass nothing and stay silent, as they always have. + */ +export function openAttachment(f: { url: string; original_name: string }, onError?: () => void): void { + const opening = openFile(f.url, f.original_name); + void (onError ? opening.catch(onError) : opening); +} diff --git a/client/src/components/Planner/bookings/useBookingActions.tsx b/client/src/components/Planner/bookings/useBookingActions.tsx index ccf19dab1..2e8a0c88d 100644 --- a/client/src/components/Planner/bookings/useBookingActions.tsx +++ b/client/src/components/Planner/bookings/useBookingActions.tsx @@ -1,9 +1,9 @@ -import { useState } from 'react' import type { Reservation } from '../../../types' import { useTranslation } from '../../../i18n' import { useTripStore } from '../../../store/tripStore' import { useToast } from '../../shared/Toast' import ConfirmDialog from '../../shared/ConfirmDialog' +import { useReservationDelete } from './useReservationDelete' /** * The two things a booking can have done to it without its editor: switching @@ -17,23 +17,17 @@ export function useBookingActions(tripId: number, onDelete: (id: number) => unkn const { t } = useTranslation() const toast = useToast() const toggleReservationStatus = useTripStore(s => s.toggleReservationStatus) - const [pendingDelete, setPendingDelete] = useState(null) + const { pendingDelete, requestDelete, cancelDelete, confirmDelete } = + useReservationDelete(onDelete, () => toast.error(t('reservations.toast.deleteError')), beforeDelete) const toggleStatus = (r: Reservation) => { toggleReservationStatus(tripId, r.id).catch(() => toast.error(t('reservations.toast.updateError'))) } - const confirmDelete = async () => { - const r = pendingDelete - setPendingDelete(null) - if (!r) return - beforeDelete?.(r) - try { await onDelete(r.id) } catch { toast.error(t('reservations.toast.deleteError')) } - } const confirmDialog = ( setPendingDelete(null)} + onClose={cancelDelete} onConfirm={confirmDelete} title={t('reservations.confirm.deleteTitle')} message={t('reservations.confirm.deleteBody', { name: pendingDelete?.title ?? '' })} @@ -42,5 +36,5 @@ export function useBookingActions(tripId: number, onDelete: (id: number) => unkn /> ) - return { toggleStatus, requestDelete: setPendingDelete, pendingDelete, confirmDialog } + return { toggleStatus, requestDelete, pendingDelete, confirmDialog } } diff --git a/client/src/components/Planner/bookings/useReservationCard.test.ts b/client/src/components/Planner/bookings/useReservationCard.test.ts new file mode 100644 index 000000000..b679e813e --- /dev/null +++ b/client/src/components/Planner/bookings/useReservationCard.test.ts @@ -0,0 +1,91 @@ +// FE-PLANNER-RESLISTFILTER-005 to -008: what one card of the phone's bookings +// and transports tabs does. +import { act, renderHook } from '@testing-library/react'; +import type { KeyboardEvent, MouseEvent } from 'react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { buildReservation } from '../../../../tests/helpers/factories'; +import type { Reservation } from '../../../types'; +import { openFile } from '../../../utils/fileDownload'; +import { useReservationCard } from './useReservationCard'; + +vi.mock('../../../utils/fileDownload', () => ({ openFile: vi.fn(() => Promise.resolve()) })); + +const traveler = (user_id: number) => ({ user_id, username: `u${user_id}` }); +const ann = buildReservation({ + id: 10, + status: 'confirmed', + reservation_time: '2026-03-02T09:00', + travelers: [traveler(1)], +} as Partial); +const bob = buildReservation({ + id: 11, + status: 'pending', + reservation_time: '2026-03-01T09:00', + travelers: [traveler(2)], +} as Partial); + +describe('useReservationCard', () => { + const file = { url: '/uploads/f/1', original_name: 'voucher.pdf' }; + const host = (blur?: boolean, handleDeleteReservation: (id: number) => unknown = vi.fn(() => Promise.resolve())) => ({ + settings: { blur_booking_codes: blur }, + handleDeleteReservation: vi.fn(handleDeleteReservation), + toast: { error: vi.fn() }, + t: (key: string) => key, + }); + + beforeEach(() => vi.mocked(openFile).mockClear()); + + it('FE-PLANNER-RESLISTFILTER-005: with the blur preference on the code is blurred until toggled', () => { + const { result } = renderHook(() => useReservationCard(ann, host(true))); + expect(result.current.codeBlurred).toBe(true); + act(() => result.current.toggleCode?.()); + expect(result.current.codeBlurred).toBe(false); + act(() => result.current.toggleCode?.()); + expect(result.current.codeBlurred).toBe(true); + }); + + it('FE-PLANNER-RESLISTFILTER-006: with the preference off the code is plain and has no toggle', () => { + const { result } = renderHook(() => useReservationCard(ann, host(false))); + expect(result.current.codeBlurred).toBe(false); + expect(result.current.toggleCode).toBeUndefined(); + }); + + it('FE-PLANNER-RESLISTFILTER-007: delete asks first, closes the question and toasts a failure', async () => { + const opts = host(false, () => Promise.reject(new Error('boom'))); + const { result } = renderHook(() => useReservationCard(bob, opts)); + expect(result.current.confirmingDelete).toBe(false); + act(() => result.current.askDelete()); + expect(result.current.confirmingDelete).toBe(true); + act(() => result.current.cancelDelete()); + expect(result.current.confirmingDelete).toBe(false); + expect(opts.handleDeleteReservation).not.toHaveBeenCalled(); + + act(() => result.current.askDelete()); + act(() => result.current.confirmDelete()); + expect(result.current.confirmingDelete).toBe(false); + expect(opts.handleDeleteReservation).toHaveBeenCalledWith(11); + await vi.waitFor(() => expect(opts.toast.error).toHaveBeenCalledWith('reservations.toast.deleteError')); + }); + + it('FE-PLANNER-RESLISTFILTER-008: a file chip opens its file on click, Enter or Space and stops there', () => { + const { result } = renderHook(() => useReservationCard(ann, host())); + const chip = result.current.fileChip(file); + const click = { stopPropagation: vi.fn() } as unknown as MouseEvent; + chip.onClick(click); + expect(click.stopPropagation).toHaveBeenCalled(); + const key = (k: string) => + ({ key: k, preventDefault: vi.fn(), stopPropagation: vi.fn() }) as unknown as KeyboardEvent; + const enter = key('Enter'); + chip.onKeyDown(enter); + chip.onKeyDown(key(' ')); + const tab = key('Tab'); + chip.onKeyDown(tab); + expect(enter.preventDefault).toHaveBeenCalled(); + expect(enter.stopPropagation).toHaveBeenCalled(); + expect(tab.preventDefault).not.toHaveBeenCalled(); + expect(tab.stopPropagation).not.toHaveBeenCalled(); + expect(openFile).toHaveBeenCalledTimes(3); + expect(openFile).toHaveBeenCalledWith('/uploads/f/1', 'voucher.pdf'); + }); +}); diff --git a/client/src/components/Planner/bookings/useReservationCard.ts b/client/src/components/Planner/bookings/useReservationCard.ts new file mode 100644 index 000000000..d9cd7ea6d --- /dev/null +++ b/client/src/components/Planner/bookings/useReservationCard.ts @@ -0,0 +1,55 @@ +import { useState, type KeyboardEvent, type MouseEvent } from 'react'; + +import type { Reservation } from '../../../types'; +import { openAttachment } from './openAttachment'; +import { useReservationDelete } from './useReservationDelete'; + +/** What a phone card needs from the planner it sits in. */ +export interface ReservationCardHost { + settings: { blur_booking_codes?: boolean }; + handleDeleteReservation: (id: number) => unknown; + toast: { error: (message: string) => unknown }; + t: (key: string) => string; +} + +/** + * What a card in the phone's bookings and transports tabs does besides + * opening: its booking code blurred until tapped while the "Blur booking codes" + * preference is on (off, the code is plain and has no toggle), the delete + * behind a question with a toast when it fails, and its attached files, which + * open from a chip inside the card's own button (so a click or Enter/Space on + * the chip stops there). A file that cannot be opened stays silent here; the + * desktop panel toasts it. + */ +export function useReservationCard(res: Reservation, host: ReservationCardHost) { + const blurCodes = host.settings.blur_booking_codes; + const { pendingDelete, requestDelete, cancelDelete, confirmDelete } = useReservationDelete( + host.handleDeleteReservation, + () => host.toast.error(host.t('reservations.toast.deleteError')) + ); + const [codeRevealed, setCodeRevealed] = useState(false); + + return { + codeBlurred: !!blurCodes && !codeRevealed, + toggleCode: blurCodes ? () => setCodeRevealed((v) => !v) : undefined, + confirmingDelete: pendingDelete != null, + askDelete: () => requestDelete(res), + cancelDelete, + confirmDelete: () => { + void confirmDelete(); + }, + fileChip: (f: { url: string; original_name: string }) => ({ + onClick: (e: MouseEvent) => { + e.stopPropagation(); + openAttachment(f); + }, + onKeyDown: (e: KeyboardEvent) => { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + e.stopPropagation(); + openAttachment(f); + } + }, + }), + }; +} diff --git a/client/src/components/Planner/bookings/useReservationDelete.test.ts b/client/src/components/Planner/bookings/useReservationDelete.test.ts new file mode 100644 index 000000000..496e5d3d7 --- /dev/null +++ b/client/src/components/Planner/bookings/useReservationDelete.test.ts @@ -0,0 +1,58 @@ +// FE-PLANNER-RESDELETE-001 to -003: deleting a booking after a question, shared +// by the desktop bookings panel and the phone's booking and transport cards. +import { act, renderHook } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +import { buildReservation } from '../../../../tests/helpers/factories'; +import { useReservationDelete } from './useReservationDelete'; + +const res = buildReservation({ id: 7, title: 'Hotel' }); + +describe('useReservationDelete', () => { + it('FE-PLANNER-RESDELETE-001: nothing is deleted until the question is answered', async () => { + const onDelete = vi.fn(); + const { result } = renderHook(() => useReservationDelete(onDelete, vi.fn())); + act(() => result.current.requestDelete(res)); + expect(result.current.pendingDelete).toBe(res); + act(() => result.current.cancelDelete()); + expect(result.current.pendingDelete).toBeNull(); + await act(() => result.current.confirmDelete()); + expect(onDelete).not.toHaveBeenCalled(); + }); + + it('FE-PLANNER-RESDELETE-002: an answer closes the question, runs beforeDelete, then deletes', async () => { + const calls: string[] = []; + const onDelete = vi.fn(() => { + calls.push('delete'); + }); + const beforeDelete = vi.fn(() => { + calls.push('before'); + }); + const onError = vi.fn(); + const { result } = renderHook(() => useReservationDelete(onDelete, onError, beforeDelete)); + act(() => result.current.requestDelete(res)); + await act(() => result.current.confirmDelete()); + expect(result.current.pendingDelete).toBeNull(); + expect(beforeDelete).toHaveBeenCalledWith(res); + expect(onDelete).toHaveBeenCalledWith(7); + expect(calls).toEqual(['before', 'delete']); + expect(onError).not.toHaveBeenCalled(); + }); + + it('FE-PLANNER-RESDELETE-003: a failed delete, rejected or thrown, goes to onError', async () => { + const onError = vi.fn(); + const rejecting = renderHook(() => useReservationDelete(() => Promise.reject(new Error('offline')), onError)); + act(() => rejecting.result.current.requestDelete(res)); + await act(() => rejecting.result.current.confirmDelete()); + expect(onError).toHaveBeenCalledTimes(1); + + const throwing = renderHook(() => + useReservationDelete(() => { + throw new Error('boom'); + }, onError) + ); + act(() => throwing.result.current.requestDelete(res)); + await act(() => throwing.result.current.confirmDelete()); + expect(onError).toHaveBeenCalledTimes(2); + }); +}); diff --git a/client/src/components/Planner/bookings/useReservationDelete.ts b/client/src/components/Planner/bookings/useReservationDelete.ts new file mode 100644 index 000000000..486c2ebd0 --- /dev/null +++ b/client/src/components/Planner/bookings/useReservationDelete.ts @@ -0,0 +1,38 @@ +import { useState } from 'react'; + +import type { Reservation } from '../../../types'; + +/** + * Deleting a booking after a question, for the desktop bookings panel and the + * cards of the phone's bookings and transports tabs. `requestDelete` asks, + * `cancelDelete` drops the question, `confirmDelete` answers it: the question + * closes first, then `beforeDelete` runs (the desktop closes a detail showing + * that booking) and the delete goes out. A failed delete calls `onError`, so + * each view keeps its own toast. + */ +export function useReservationDelete( + onDelete: (id: number) => unknown, + onError: () => void, + beforeDelete?: (r: Reservation) => void +) { + const [pendingDelete, setPendingDelete] = useState(null); + + const confirmDelete = async () => { + const r = pendingDelete; + setPendingDelete(null); + if (!r) return; + beforeDelete?.(r); + try { + await onDelete(r.id); + } catch { + onError(); + } + }; + + return { + pendingDelete, + requestDelete: setPendingDelete, + cancelDelete: () => setPendingDelete(null), + confirmDelete, + }; +} diff --git a/client/src/components/Planner/bookings/useReservationListFilter.test.ts b/client/src/components/Planner/bookings/useReservationListFilter.test.ts new file mode 100644 index 000000000..bba342930 --- /dev/null +++ b/client/src/components/Planner/bookings/useReservationListFilter.test.ts @@ -0,0 +1,66 @@ +// FE-PLANNER-RESLISTFILTER-001 to -004: the traveller filter and folded sections +// of the phone's bookings and transports tabs. +import { act, renderHook } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import { buildDay, buildReservation } from '../../../../tests/helpers/factories'; +import type { Reservation } from '../../../types'; +import { useReservationListFilter } from './useReservationListFilter'; + +const days = [buildDay({ id: 1, date: '2026-03-01' }), buildDay({ id: 2, date: '2026-03-02' })]; +const traveler = (user_id: number) => ({ user_id, username: `u${user_id}` }); +const ann = buildReservation({ + id: 10, + status: 'confirmed', + reservation_time: '2026-03-02T09:00', + travelers: [traveler(1)], +} as Partial); +const bob = buildReservation({ + id: 11, + status: 'pending', + reservation_time: '2026-03-01T09:00', + travelers: [traveler(2)], +} as Partial); +const ride = buildReservation({ id: 12, type: 'transit', status: 'confirmed', reservation_time: '2026-03-01T07:00' }); +const ALL = [ann, bob, ride]; + +describe('useReservationListFilter', () => { + it('FE-PLANNER-RESLISTFILTER-001: without a filter every booking lands in its status section', () => { + const { result } = renderHook(() => useReservationListFilter(ALL, days, 2)); + expect(result.current.travelerFilter.size).toBe(0); + expect(result.current.groups.confirmed.map((r) => r.id)).toEqual([10]); + expect(result.current.groups.pending.map((r) => r.id)).toEqual([11]); + expect(result.current.groups.transit.map((r) => r.id)).toEqual([12]); + }); + + it('FE-PLANNER-RESLISTFILTER-002: choosing a traveller keeps the bookings they are on, and clearing brings all back', () => { + const { result } = renderHook(() => useReservationListFilter(ALL, days, 2)); + act(() => result.current.toggleTravelerFilter(2)); + expect([...result.current.travelerFilter]).toEqual([2]); + expect(result.current.groups).toEqual({ confirmed: [], pending: [bob], transit: [] }); + + act(() => result.current.toggleTravelerFilter(1)); + expect(result.current.groups.confirmed.map((r) => r.id)).toEqual([10]); + act(() => result.current.toggleTravelerFilter(2)); + expect(result.current.groups.pending).toEqual([]); + + act(() => result.current.clearTravelerFilter()); + expect(result.current.travelerFilter.size).toBe(0); + expect(result.current.groups.transit.map((r) => r.id)).toEqual([12]); + }); + + it('FE-PLANNER-RESLISTFILTER-003: the filter is offered only with company and a booking that names a traveller', () => { + expect(renderHook(() => useReservationListFilter(ALL, days, 2)).result.current.showTravelerFilter).toBe(true); + expect(renderHook(() => useReservationListFilter(ALL, days, 1)).result.current.showTravelerFilter).toBe(false); + expect(renderHook(() => useReservationListFilter([ride], days, 3)).result.current.showTravelerFilter).toBe(false); + }); + + it('FE-PLANNER-RESLISTFILTER-004: a section folds and unfolds on its own', () => { + const { result } = renderHook(() => useReservationListFilter(ALL, days, 2)); + act(() => result.current.toggleSection('pending')); + expect(result.current.collapsed).toEqual({ pending: true }); + act(() => result.current.toggleSection('confirmed')); + act(() => result.current.toggleSection('pending')); + expect(result.current.collapsed).toEqual({ pending: false, confirmed: true }); + }); +}); diff --git a/client/src/components/Planner/bookings/useReservationListFilter.ts b/client/src/components/Planner/bookings/useReservationListFilter.ts new file mode 100644 index 000000000..d32ed8777 --- /dev/null +++ b/client/src/components/Planner/bookings/useReservationListFilter.ts @@ -0,0 +1,44 @@ +import { useState } from 'react'; + +import type { Day, Reservation } from '../../../types'; +import { groupTransports, onTravelers } from './bookingsModel'; + +/** + * The traveller filter and the folded sections of the phone's bookings and + * transports tabs: the bookings someone chosen is on, in their date-ordered status + * sections. The filter is only offered when the trip has company and a booking + * names a traveller at all. + * + * Only those two phone tabs use it. The desktop bookings panel keeps its own + * filters in useBookingsView, remembered for the session, and shares the + * predicates with the phone through bookingsModel. + */ +export function useReservationListFilter(all: Reservation[], days: Day[], memberCount: number) { + const [travelerFilter, setTravelerFilter] = useState>(new Set()); + const groups = groupTransports( + all.filter((r) => onTravelers(r, travelerFilter)), + days + ); + const showTravelerFilter = memberCount > 1 && all.some((r) => (r.travelers || []).length > 0); + const toggleTravelerFilter = (id: number) => + setTravelerFilter((prev) => { + const n = new Set(prev); + if (n.has(id)) n.delete(id); + else n.add(id); + return n; + }); + const clearTravelerFilter = () => setTravelerFilter(new Set()); + + const [collapsed, setCollapsed] = useState>({}); + const toggleSection = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] })); + + return { + travelerFilter, + groups, + showTravelerFilter, + toggleTravelerFilter, + clearTravelerFilter, + collapsed, + toggleSection, + }; +} diff --git a/client/src/mobile/screens/trip/tabs/MBookingsTab.tsx b/client/src/mobile/screens/trip/tabs/MBookingsTab.tsx index 95c2abdd4..6b3fc1243 100644 --- a/client/src/mobile/screens/trip/tabs/MBookingsTab.tsx +++ b/client/src/mobile/screens/trip/tabs/MBookingsTab.tsx @@ -1,16 +1,18 @@ -import { useState } from 'react' import { FileText, MapPin, Pencil, Trash2 } from 'lucide-react' import MDancingTrek from '../../../components/MDancingTrek' import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants' -import { splitReservationDateTime, formatTime, formatPriceText } from '../../../../utils/formatters' -import { openFile } from '../../../../utils/fileDownload' +import { formatTime, formatPriceText } from '../../../../utils/formatters' import { useTranslation } from '../../../../i18n' import type { Reservation } from '../../../../types' import MConfirmSheet from '../../settings/MConfirmSheet' import { ConfirmationCode, Field, ReservationPluginSlots, SectionHeader, StatusDot, TabScroller, TravelerAvatars, TravelerFilterRow } from './tabChrome' import { STATUS_COLOR, type MTabScreenProps } from './tabModel' -import { groupTransports, orderedEndpoints, parseTransportMeta } from './transportsModel' -import { BOOKING_TYPE_COLOR } from './bookingsModel' +import { cardWhen, parseTransportMeta } from './transportsModel' +import { BOOKING_TYPE_COLOR } from '../../../../components/Planner/bookings/bookingsModel' +import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter' +import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard' +import { orderedEndpoints } from '../../../../utils/flightLegs' +import { filesFor } from '../../../../utils/reservationFiles' /** * Tab 2 — Buchungen. Real `planner.reservations` filtered to the non-transport @@ -22,16 +24,11 @@ import { BOOKING_TYPE_COLOR } from './bookingsModel' */ export default function MBookingsTab({ planner, shell }: MTabScreenProps) { const { t, reservations, days } = planner - const [travelerFilter, setTravelerFilter] = useState>(new Set()) const allBookings = reservations.filter(r => !planner.TRANSPORT_TYPES.has(r.type)) - const bookings = travelerFilter.size === 0 ? allBookings : allBookings.filter(r => (r.travelers || []).some(tv => travelerFilter.has(tv.user_id))) - const groups = groupTransports(bookings, days) + const { + travelerFilter, groups, showTravelerFilter, toggleTravelerFilter, clearTravelerFilter, collapsed, toggleSection: toggle, + } = useReservationListFilter(allBookings, days, planner.tripMembers.length) const canEdit = planner.can('reservation_edit', planner.trip) - const showTravelerFilter = planner.tripMembers.length > 1 && allBookings.some(r => (r.travelers || []).length > 0) - const toggleTravelerFilter = (id: number) => setTravelerFilter(prev => { const n = new Set(prev); if (n.has(id)) n.delete(id); else n.add(id); return n }) - - const [collapsed, setCollapsed] = useState>({}) - const toggle = (id: string) => setCollapsed(c => ({ ...c, [id]: !c[id] })) const sections = [ { id: 'confirmed', label: t('reservations.confirmed'), rows: groups.confirmed }, @@ -45,7 +42,7 @@ export default function MBookingsTab({ planner, shell }: MTabScreenProps) { members={planner.tripMembers} active={travelerFilter} onToggle={toggleTravelerFilter} - onClear={() => setTravelerFilter(new Set())} + onClear={clearTravelerFilter} label={t('reservations.travelers.label')} allLabel={t('common.all')} /> @@ -88,9 +85,7 @@ function BookingCard({ res, planner, canEdit, compact }: { const { t, days } = planner const { locale } = useTranslation() const timeFormat = planner.settings.time_format || '24h' - const blurCodes = planner.settings.blur_booking_codes - const [codeRevealed, setCodeRevealed] = useState(false) - const [confirmDelete, setConfirmDelete] = useState(false) + const card = useReservationCard(res, planner) const meta = parseTransportMeta(res) const TypeIcon = RES_ICONS[res.type as keyof typeof RES_ICONS] || RES_ICONS.other @@ -107,12 +102,6 @@ function BookingCard({ res, planner, canEdit, compact }: { ? days.find(d => d.id === res.accommodation_end_day_id) : res.end_day_id != null ? days.find(d => d.id === res.end_day_id) : undefined - const startDt = splitReservationDateTime(res.reservation_time) - const endDt = splitReservationDateTime(res.reservation_end_time) - const fmtDate = (date: string) => - new Date(`${date}T00:00:00Z`).toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) - const dayLabel = (day: NonNullable) => day.title || t('dayplan.dayN', { n: day.day_number }) - const eps = orderedEndpoints(res) const hasEndpoints = eps.some(e => e.role === 'from') && eps.some(e => e.role === 'to') @@ -132,9 +121,7 @@ function BookingCard({ res, planner, canEdit, compact }: { } if (meta.check_out_time) metaCells.push({ label: t('reservations.meta.checkOut'), value: formatTime(meta.check_out_time, locale, timeFormat) }) - const files = (planner.files || []).filter( - f => !f.deleted_at && (f.reservation_id === res.id || (f.linked_reservation_ids || []).includes(res.id)), - ) + const files = filesFor(res, planner.files || []) const openEdit = () => { if (!canEdit) return @@ -142,14 +129,7 @@ function BookingCard({ res, planner, canEdit, compact }: { planner.setShowReservationModal(true) } - const timeValue = startDt.time - ? `${formatTime(startDt.time, locale, timeFormat)}${endDt.time ? ` – ${formatTime(endDt.time, locale, timeFormat)}` : ''}` - : '—' - const dayValue = startDay - ? `${dayLabel(startDay)}${endDay && endDay.id !== startDay.id ? ` – ${dayLabel(endDay)}` : ''}` - : startDt.date - ? fmtDate(startDt.date) - : '—' + const { dayValue, timeValue } = cardWhen(res, startDay, endDay, t, locale, timeFormat) return (
@@ -181,7 +161,7 @@ function BookingCard({ res, planner, canEdit, compact }: { {canEdit && (
) diff --git a/client/src/mobile/screens/trip/tabs/MTransportsTab.tsx b/client/src/mobile/screens/trip/tabs/MTransportsTab.tsx index fb2d1a62c..0a7ebaf46 100644 --- a/client/src/mobile/screens/trip/tabs/MTransportsTab.tsx +++ b/client/src/mobile/screens/trip/tabs/MTransportsTab.tsx @@ -1,20 +1,18 @@ -import { useState } from 'react' import { FileText, Pencil, Trash2 } from 'lucide-react' import MDancingTrek from '../../../components/MDancingTrek' import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants' -import { splitReservationDateTime, formatTime, formatPriceText } from '../../../../utils/formatters' -import { openFile } from '../../../../utils/fileDownload' +import { formatPriceText } from '../../../../utils/formatters' import { useTranslation } from '../../../../i18n' import type { Reservation } from '../../../../types' import MConfirmSheet from '../../settings/MConfirmSheet' import { ConfirmationCode, Field, ReservationPluginSlots, SectionHeader, StatusDot, TabScroller, TravelerAvatars, TravelerFilterRow } from './tabChrome' import { STATUS_COLOR, type MTabScreenProps } from './tabModel' -import { - TRANSPORT_TYPE_COLOR, - groupTransports, - orderedEndpoints, - parseTransportMeta, -} from './transportsModel' +import { cardWhen, parseTransportMeta } from './transportsModel' +import { TRANSPORT_TYPE_COLOR } from '../../../../components/Planner/bookings/bookingsModel' +import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter' +import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard' +import { orderedEndpoints } from '../../../../utils/flightLegs' +import { filesFor } from '../../../../utils/reservationFiles' /** * Tab 1 — Transporte. Real `planner.reservations` filtered to the 10 transport @@ -26,16 +24,11 @@ import { */ export default function MTransportsTab({ planner, shell }: MTabScreenProps) { const { t, reservations, days } = planner - const [travelerFilter, setTravelerFilter] = useState>(new Set()) const allTransports = reservations.filter(r => planner.TRANSPORT_TYPES.has(r.type)) - const transports = travelerFilter.size === 0 ? allTransports : allTransports.filter(r => (r.travelers || []).some(tv => travelerFilter.has(tv.user_id))) - const groups = groupTransports(transports, days) + const { + travelerFilter, groups, showTravelerFilter, toggleTravelerFilter, clearTravelerFilter, collapsed, toggleSection: toggle, + } = useReservationListFilter(allTransports, days, planner.tripMembers.length) const canEdit = planner.can('day_edit', planner.trip) - const showTravelerFilter = planner.tripMembers.length > 1 && allTransports.some(r => (r.travelers || []).length > 0) - const toggleTravelerFilter = (id: number) => setTravelerFilter(prev => { const n = new Set(prev); if (n.has(id)) n.delete(id); else n.add(id); return n }) - - const [collapsed, setCollapsed] = useState>({}) - const toggle = (id: string) => setCollapsed(c => ({ ...c, [id]: !c[id] })) const sections = [ { id: 'confirmed', label: t('reservations.confirmed'), rows: groups.confirmed }, @@ -50,7 +43,7 @@ export default function MTransportsTab({ planner, shell }: MTabScreenProps) { members={planner.tripMembers} active={travelerFilter} onToggle={toggleTravelerFilter} - onClear={() => setTravelerFilter(new Set())} + onClear={clearTravelerFilter} label={t('reservations.travelers.label')} allLabel={t('common.all')} /> @@ -95,9 +88,7 @@ function TransportCard({ res, planner, shell, canEdit, compact }: { const { t, days } = planner const { locale } = useTranslation() const timeFormat = planner.settings.time_format || '24h' - const blurCodes = planner.settings.blur_booking_codes - const [codeRevealed, setCodeRevealed] = useState(false) - const [confirmDelete, setConfirmDelete] = useState(false) + const card = useReservationCard(res, planner) const meta = parseTransportMeta(res) const TypeIcon = RES_ICONS[res.type as keyof typeof RES_ICONS] || RES_ICONS.other @@ -109,13 +100,6 @@ function TransportCard({ res, planner, shell, canEdit, compact }: { const startDay = res.day_id != null ? days.find(d => d.id === res.day_id) : undefined const endDay = res.end_day_id != null ? days.find(d => d.id === res.end_day_id) : undefined - const startDt = splitReservationDateTime(res.reservation_time) - const endDt = splitReservationDateTime(res.reservation_end_time) - - const fmtDate = (date: string) => - new Date(`${date}T00:00:00Z`).toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) - const dayLabel = (day: NonNullable) => day.title || t('dayplan.dayN', { n: day.day_number }) - const eps = orderedEndpoints(res) const hasEndpoints = eps.some(e => e.role === 'from') && eps.some(e => e.role === 'to') @@ -131,9 +115,7 @@ function TransportCard({ res, planner, shell, canEdit, compact }: { metaCells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, planner.trip?.currency, locale) }) } - const files = (planner.files || []).filter( - f => !f.deleted_at && (f.reservation_id === res.id || (f.linked_reservation_ids || []).includes(res.id)), - ) + const files = filesFor(res, planner.files || []) const openDetail = () => shell.openSheet('transport', { reservationId: res.id }) const toggleStatus = async () => { @@ -149,14 +131,7 @@ function TransportCard({ res, planner, shell, canEdit, compact }: { planner.setShowTransportModal(true) } - const timeValue = startDt.time - ? `${formatTime(startDt.time, locale, timeFormat)}${endDt.time ? ` – ${formatTime(endDt.time, locale, timeFormat)}` : ''}` - : '—' - const dayValue = startDay - ? `${dayLabel(startDay)}${endDay && endDay.id !== startDay.id ? ` – ${dayLabel(endDay)}` : ''}` - : startDt.date - ? fmtDate(startDt.date) - : '—' + const { dayValue, timeValue } = cardWhen(res, startDay, endDay, t, locale, timeFormat) return (
@@ -203,7 +178,7 @@ function TransportCard({ res, planner, shell, canEdit, compact }: { {canEdit && (
) diff --git a/client/src/mobile/screens/trip/tabs/bookingsModel.ts b/client/src/mobile/screens/trip/tabs/bookingsModel.ts deleted file mode 100644 index 79e5ac960..000000000 --- a/client/src/mobile/screens/trip/tabs/bookingsModel.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Booking (non-transport reservation) accents — hotel / restaurant / event / - * tour / other, from the desktop ReservationsPanel TYPE_OPTIONS. Grouping, - * metadata parsing and endpoint ordering are shared with the transports tab - * (see transportsModel: groupTransports splits off `transit`, which never - * matches a booking type, so its `confirmed` / `pending` split fits bookings). - */ -export const BOOKING_TYPE_COLOR: Record = { - hotel: '#8b5cf6', - restaurant: '#ef4444', - event: '#f59e0b', - tour: '#10b981', - parking: '#2563eb', - other: '#6b7280', -} diff --git a/client/src/mobile/screens/trip/tabs/transportsModel.ts b/client/src/mobile/screens/trip/tabs/transportsModel.ts index c6d4aa1dd..7eda53673 100644 --- a/client/src/mobile/screens/trip/tabs/transportsModel.ts +++ b/client/src/mobile/screens/trip/tabs/transportsModel.ts @@ -1,28 +1,13 @@ -import { splitReservationDateTime } from '../../../../utils/formatters' -import type { Day, Reservation } from '../../../../types' +import { formatTime, splitReservationDateTime } from '../../../../utils/formatters' +import type { Day, Reservation, TranslationFn } from '../../../../types' /** * Transport view-model — the real-data counterpart to the demo's `trsSecs` - * (spec 03 §1.4). Grouping and chronological order mirror the desktop - * ReservationsPanel (Confirmed / Pending / Automated-Transit) so both surfaces - * agree. + * (spec 03 §1.4). The sections, their order and the type colours come from the + * desktop bookings model (groupTransports, TRANSPORT_TYPE_COLOR) so both surfaces + * agree; what is left here is the phone cards' own reading of a booking. */ -/** Type-chip accent per transport type (from ReservationsPanel TYPE_OPTIONS). */ -export const TRANSPORT_TYPE_COLOR: Record = { - flight: '#3b82f6', - train: '#06b6d4', - bus: '#059669', - car: '#6b7280', - taxi: '#ca8a04', - bicycle: '#84cc16', - cruise: '#0ea5e9', - ferry: '#0d9488', - cable_car: '#dc2626', - transit: '#7c3aed', - transport_other: '#6b7280', -} - export interface TransitLeg { mode?: string line?: string | null @@ -58,48 +43,31 @@ export function parseTransportMeta(res: Reservation): TransportMeta { } } -/** Waypoints in travel order (from · stops · to). */ -export function orderedEndpoints(res: Reservation) { - return (res.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)) -} - -export interface TransportGroups { - confirmed: Reservation[] - pending: Reservation[] - transit: Reservation[] -} - /** - * Chronological sort + split into the three demo sections. Undated entries sink - * to the bottom; `transit` (automated public transport, #1065) is peeled off - * into its own group regardless of status. Mirrors ReservationsPanel:683-711. + * The date and time cells of a phone booking or transport card: the day (or day + * range) the booking sits on, else its own date, and its time or time range. A + * dash stands in for whichever is missing. */ -export function groupTransports(list: Reservation[], days: Day[]): TransportGroups { - const dayDates = new Map(days.map(d => [d.id, d.date])) - const sortKey = (r: Reservation): string | null => { - const { date, time } = splitReservationDateTime(r.reservation_time) - const dayId = r.type === 'hotel' ? r.accommodation_start_day_id ?? r.day_id : r.day_id - const effectiveDate = date ?? (dayId != null ? dayDates.get(dayId) ?? null : null) - if (!effectiveDate) return null - return `${effectiveDate}T${time ?? '00:00'}` - } - const sorted = list - .map(r => ({ r, key: sortKey(r) })) - .sort((a, b) => { - if (a.key !== b.key) { - if (a.key === null) return 1 - if (b.key === null) return -1 - return a.key < b.key ? -1 : 1 - } - return (a.r.created_at ?? '').localeCompare(b.r.created_at ?? '') - }) - .map(({ r }) => r) - - const transit = sorted.filter(r => r.type === 'transit') - const nonTransit = sorted.filter(r => r.type !== 'transit') - return { - confirmed: nonTransit.filter(r => r.status === 'confirmed'), - pending: nonTransit.filter(r => r.status !== 'confirmed'), - transit, - } +export function cardWhen( + res: Reservation, + startDay: Day | undefined, + endDay: Day | undefined, + t: TranslationFn, + locale: string, + timeFormat: string, +): { dayValue: string; timeValue: string } { + const startDt = splitReservationDateTime(res.reservation_time) + const endDt = splitReservationDateTime(res.reservation_end_time) + const fmtDate = (date: string) => + new Date(`${date}T00:00:00Z`).toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) + const dayLabel = (day: Day) => day.title || t('dayplan.dayN', { n: day.day_number }) + const timeValue = startDt.time + ? `${formatTime(startDt.time, locale, timeFormat)}${endDt.time ? ` – ${formatTime(endDt.time, locale, timeFormat)}` : ''}` + : '—' + const dayValue = startDay + ? `${dayLabel(startDay)}${endDay && endDay.id !== startDay.id ? ` – ${dayLabel(endDay)}` : ''}` + : startDt.date + ? fmtDate(startDt.date) + : '—' + return { dayValue, timeValue } } diff --git a/client/tests/unit/mobile/trip/transportsModel.test.ts b/client/tests/unit/mobile/trip/transportsModel.test.ts index 94f4c5127..5af33495b 100644 --- a/client/tests/unit/mobile/trip/transportsModel.test.ts +++ b/client/tests/unit/mobile/trip/transportsModel.test.ts @@ -1,14 +1,11 @@ import { describe, it, expect } from 'vitest'; -import { - TRANSPORT_TYPE_COLOR, - groupTransports, - orderedEndpoints, - parseTransportMeta, -} from '../../../../src/mobile/screens/trip/tabs/transportsModel'; +import { cardWhen, parseTransportMeta } from '../../../../src/mobile/screens/trip/tabs/transportsModel'; +import { TRANSPORT_TYPE_COLOR, groupTransports } from '../../../../src/components/Planner/bookings/bookingsModel'; +import { orderedEndpoints } from '../../../../src/utils/flightLegs'; import { buildDay, buildReservation } from '../../../helpers/factories'; import type { Day, Reservation } from '../../../../src/types'; -// FE-MOB-TRPM-001 to FE-MOB-TRPM-014 +// FE-MOB-TRPM-001 to FE-MOB-TRPM-017 function res(overrides: Partial = {}): Reservation { return buildReservation({ type: 'flight', status: 'confirmed', ...overrides }); @@ -155,3 +152,34 @@ describe('transportsModel — groupTransports', () => { expect(groupTransports([a, b], days).confirmed.map(r => r.id)).toEqual([1, 2]); }); }); + +describe('transportsModel — cardWhen', () => { + const t = (key: string, params?: Record) => `${key}:${params?.n}`; + const day1 = buildDay({ id: 100, day_number: 1, title: null, date: '2026-07-01' }); + const day3 = buildDay({ id: 102, day_number: 3, title: 'Coast', date: '2026-07-03' }); + + it('FE-MOB-TRPM-015: names the day or the day range and the time or time range', () => { + const r = res({ reservation_time: '2026-07-01T09:05', reservation_end_time: '2026-07-03T18:30' }); + expect(cardWhen(r, day1, day3, t, 'en-US', '24h')).toEqual({ + dayValue: 'dayplan.dayN:1 – Coast', + timeValue: '09:05 – 18:30', + }); + expect(cardWhen(r, day1, day1, t, 'en-US', '24h').dayValue).toBe('dayplan.dayN:1'); + }); + + it('FE-MOB-TRPM-016: without a day the booking date stands in, then a dash', () => { + expect(cardWhen(res({ reservation_time: '2026-07-04' }), undefined, undefined, t, 'en-US', '24h')).toEqual({ + dayValue: 'Jul 4', + timeValue: '—', + }); + expect(cardWhen(res({ reservation_time: null }), undefined, undefined, t, 'en-US', '24h')).toEqual({ + dayValue: '—', + timeValue: '—', + }); + }); + + it('FE-MOB-TRPM-017: a start time alone shows on its own, in the chosen clock', () => { + const r = res({ reservation_time: '2026-07-01T14:00', reservation_end_time: null }); + expect(cardWhen(r, day1, undefined, t, 'en-US', '12h').timeValue).toBe('2:00 PM'); + }); +});