diff --git a/client/src/components/Planner/DayDetailPanel.tsx b/client/src/components/Planner/DayDetailPanel.tsx index e788f8100..300f213b6 100644 --- a/client/src/components/Planner/DayDetailPanel.tsx +++ b/client/src/components/Planner/DayDetailPanel.tsx @@ -19,7 +19,7 @@ import type { Day, Place, Category, Reservation, AssignmentsMap, Accommodation } import { formatClockTime, splitReservationDateTime } from '../../utils/formatters' import { useDayDetail, useDayRename, type HotelDayRange, type HotelForm, type HotelPickerMode } from './useDayDetail' import { dayBookings, stayDayLabel, toDisplayTemp } from './dayDetailModel' -import { stayPlaces } from '../../utils/stayPlaces' +import { stayDayOptions, stayFormFrom, stayPlaceChoices, stayRangeFromEnd, stayRangeFromStart } from './stayFormModel' import { DialogShell, DialogHeader, DialogSection, DialogFooter, DialogButton, FooterSpacer, NEUTRAL_TINT, PILL, fs } from '../shared/DialogShell' import { INPUT, PANEL, EditorField, AddRowButton, PillSelect } from '../shared/dialogParts' import { BOX, Eyebrow, Field, RoundAction, TypeTile, toneOf, toneColor, toneTint } from './bookings/bookingParts' @@ -155,7 +155,7 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri } const editAccommodation = (acc: Accommodation) => { setAccommodation(acc) - setHotelForm({ check_in: acc.check_in || '', check_in_end: acc.check_in_end || '', check_out: acc.check_out || '', confirmation: acc.confirmation || '', place_id: acc.place_id ?? null }) + setHotelForm(stayFormFrom(acc, null)) setHotelDayRange({ start: acc.start_day_id, end: acc.end_day_id }) setShowHotelPicker('edit') } @@ -537,17 +537,10 @@ function HotelPickerModal({ mode, onClose, onSave, days, categories, places, hot if (!mode) return null const dayLabel = (d: Day, i: number) => d.title || t('planner.dayN', { n: i + 1 }) - const dayOptions = days.map((d, i) => ({ - value: d.id, - label: dayLabel(d, i), - badge: d.date - ? new Date(d.date + 'T00:00:00Z').toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) - : (d.title ? t('planner.dayN', { n: i + 1 }) : undefined), - })) + const dayOptions = stayDayOptions(days, t, locale) const position = (id: number | undefined) => days.findIndex(d => d.id === id) const allDays = hotelDayRange.start === days[0]?.id && hotelDayRange.end === days[days.length - 1]?.id - const offered = stayPlaces(places, hotelForm.place_id) - const filtered = hotelCategoryFilter ? offered.filter(p => p.category_id === hotelCategoryFilter) : offered + const filtered = stayPlaceChoices(places, hotelForm.place_id, hotelCategoryFilter || null) const setTime = (field: 'check_in' | 'check_in_end' | 'check_out') => (v: string) => setHotelForm(f => ({ ...f, [field]: v })) const picked = places.find(p => p.id === hotelForm.place_id) ?? null const startAt = position(hotelDayRange.start) @@ -609,7 +602,7 @@ function HotelPickerModal({ mode, onClose, onSave, days, categories, places, hot { const id = Number(v); setHotelDayRange(prev => ({ start: id, end: position(id) > position(prev.end) ? id : prev.end })) }} + onChange={v => { const id = Number(v); setHotelDayRange(prev => stayRangeFromStart(days, prev, id)) }} options={dayOptions} size="sm" /> @@ -619,7 +612,7 @@ function HotelPickerModal({ mode, onClose, onSave, days, categories, places, hot { const id = Number(v); setHotelDayRange(prev => ({ start: position(id) < position(prev.start) ? id : prev.start, end: id })) }} + onChange={v => { const id = Number(v); setHotelDayRange(prev => stayRangeFromEnd(days, prev, id)) }} options={dayOptions} size="sm" /> diff --git a/client/src/components/Planner/stayFormModel.test.ts b/client/src/components/Planner/stayFormModel.test.ts new file mode 100644 index 000000000..46a692448 --- /dev/null +++ b/client/src/components/Planner/stayFormModel.test.ts @@ -0,0 +1,110 @@ +// FE-PLANNER-STAYFORM-001 to -008: the stay editor rules the desktop hotel picker +// and the phone accommodation sheet share. +import { describe, expect, it } from 'vitest'; + +import { buildDay, buildPlace } from '../../../tests/helpers/factories'; +import type { Accommodation } from '../../types'; +import { + stayCheckoutDay, + stayDayOptions, + stayFormFrom, + stayPlaceChoices, + stayRangeFromEnd, + stayRangeFromStart, + stayRequestBody, +} from './stayFormModel'; + +const t = (key: string, params?: Record) => (params ? `${key}:${params.n}` : key); +const DAYS = [{ id: 10 }, { id: 20 }, { id: 30 }]; + +describe('stayDayOptions', () => { + it('FE-PLANNER-STAYFORM-001: a titled day keeps its number as the badge, a dated one its date', () => { + const days = [ + buildDay({ id: 1, title: null, date: '2026-07-04' }), + buildDay({ id: 2, title: 'Beach', date: null }), + buildDay({ id: 3, title: null, date: null }), + ]; + expect(stayDayOptions(days, t, 'en-US')).toEqual([ + { value: 1, label: 'planner.dayN:1', badge: 'Jul 4' }, + { value: 2, label: 'Beach', badge: 'planner.dayN:2' }, + { value: 3, label: 'planner.dayN:3', badge: undefined }, + ]); + }); +}); + +describe('stay ranges', () => { + it('FE-PLANNER-STAYFORM-002: a later first day pulls the end along, an earlier one leaves it', () => { + expect(stayRangeFromStart(DAYS, { start: 10, end: 20 }, 30)).toEqual({ start: 30, end: 30 }); + expect(stayRangeFromStart(DAYS, { start: 20, end: 30 }, 10)).toEqual({ start: 10, end: 30 }); + expect(stayRangeFromStart(DAYS, { start: undefined, end: undefined }, 20)).toEqual({ start: 20, end: 20 }); + }); + + it('FE-PLANNER-STAYFORM-003: an earlier last day pulls the start back, a later one leaves it', () => { + expect(stayRangeFromEnd(DAYS, { start: 20, end: 30 }, 10)).toEqual({ start: 10, end: 10 }); + expect(stayRangeFromEnd(DAYS, { start: 10, end: 20 }, 30)).toEqual({ start: 10, end: 30 }); + }); + + it('FE-PLANNER-STAYFORM-004: a new stay checks out the next day, if the trip has one', () => { + expect(stayCheckoutDay(DAYS, 10)).toBe(20); + expect(stayCheckoutDay(DAYS, 30)).toBeUndefined(); + expect(stayCheckoutDay(DAYS, 99)).toBeUndefined(); + expect(stayCheckoutDay(DAYS, undefined)).toBeUndefined(); + }); +}); + +describe('stayFormFrom and stayRequestBody', () => { + const acc = { + check_in: '15:00', + check_in_end: null, + check_out: '10:00', + confirmation: 'ABC', + place_id: 7, + } as Pick; + + it('FE-PLANNER-STAYFORM-005: an existing stay fills the editor, empty fields as blanks', () => { + expect(stayFormFrom(acc, null)).toEqual({ + check_in: '15:00', + check_in_end: '', + check_out: '10:00', + confirmation: 'ABC', + place_id: 7, + }); + expect(stayFormFrom({ ...acc, place_id: null }, '').place_id).toBe(''); + expect(stayFormFrom({ ...acc, place_id: undefined }, null).place_id).toBeNull(); + }); + + it('FE-PLANNER-STAYFORM-006: the request sends the range and blank times and codes as null', () => { + expect( + stayRequestBody( + { check_in: '', check_in_end: '22:00', check_out: '', confirmation: '', place_id: 7 }, + { + start: 10, + end: 20, + } + ) + ).toEqual({ + place_id: 7, + start_day_id: 10, + end_day_id: 20, + check_in: null, + check_in_end: '22:00', + check_out: null, + confirmation: null, + }); + }); +}); + +describe('stayPlaceChoices', () => { + const hotel = buildPlace({ id: 1, category_id: 2 }); + const museum = buildPlace({ id: 2, category_id: 3 }); + const track = buildPlace({ id: 3, category_id: 2, route_geometry: 'abc' }); + + it('FE-PLANNER-STAYFORM-007: a track is never a place to stay, unless it is the one already picked', () => { + expect(stayPlaceChoices([hotel, museum, track], null, null).map((p) => p.id)).toEqual([1, 2]); + expect(stayPlaceChoices([hotel, museum, track], 3, null).map((p) => p.id)).toEqual([1, 2, 3]); + }); + + it('FE-PLANNER-STAYFORM-008: a chosen category narrows the choice', () => { + expect(stayPlaceChoices([hotel, museum, track], 3, 2).map((p) => p.id)).toEqual([1, 3]); + }); +}); diff --git a/client/src/components/Planner/stayFormModel.ts b/client/src/components/Planner/stayFormModel.ts new file mode 100644 index 000000000..3e7399b3f --- /dev/null +++ b/client/src/components/Planner/stayFormModel.ts @@ -0,0 +1,109 @@ +import type { Accommodation, Day } from '../../types'; +import { stayPlaces } from '../../utils/stayPlaces'; + +type Translate = (key: string, params?: Record) => string; + +/** + * The stay editor both shells show over the same rules: the desktop day panel's + * hotel picker and the phone's accommodation sheet. Each keeps its own state; the + * shape of a range, the day options, the places on offer and the request body are + * worked out here. + */ + +/** The days a stay spans; `N` is how a shell writes "no day yet". */ +export interface StayRange { + start: N; + end: N; +} + +/** The stay's own fields as the editor holds them; `P` is how a shell writes "no place picked". */ +export interface StayFormFields

{ + check_in: string; + check_in_end: string; + check_out: string; + confirmation: string; + place_id: P; +} + +/** The day options of the range pickers: the day's title, its date as the badge, or its number when titled. */ +export function stayDayOptions(days: Day[], t: Translate, locale: string) { + return days.map((d, i) => ({ + value: d.id, + label: d.title || t('planner.dayN', { n: i + 1 }), + badge: d.date + ? new Date(d.date + 'T00:00:00Z').toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) + : d.title + ? t('planner.dayN', { n: i + 1 }) + : undefined, + })); +} + +const position = (days: { id: number }[], id: number | undefined) => days.findIndex((d) => d.id === id); + +/** A new first day; a range that would end before it is pulled along to it. */ +export function stayRangeFromStart( + days: { id: number }[], + prev: StayRange, + id: number +): StayRange { + return { start: id, end: position(days, id) > position(days, prev.end) ? id : prev.end }; +} + +/** A new last day; a range that would start after it is pulled back to it. */ +export function stayRangeFromEnd( + days: { id: number }[], + prev: StayRange, + id: number +): StayRange { + return { start: position(days, id) < position(days, prev.start) ? id : prev.start, end: id }; +} + +/** + * The day after the given one, which is where a new stay checks out by default: a + * stay virtually never checks out the day it checks in. Undefined on the trip's + * last day or for a day the trip does not have. + */ +export function stayCheckoutDay(days: { id: number }[], dayId: number | undefined): number | undefined { + const idx = position(days, dayId); + return (idx >= 0 && days[idx + 1]?.id) || undefined; +} + +/** The editor's fields for an existing stay; `emptyPlace` stands in for a stay without a place. */ +export function stayFormFrom

( + acc: Pick, + emptyPlace: P +): StayFormFields { + return { + check_in: acc.check_in || '', + check_in_end: acc.check_in_end || '', + check_out: acc.check_out || '', + confirmation: acc.confirmation || '', + place_id: acc.place_id ?? emptyPlace, + }; +} + +/** + * The places a stay can be at (no GPX tracks, but always the one already picked), + * narrowed to a category when one is chosen. + */ +export function stayPlaceChoices

( + places: P[], + placeId: number | string | null | undefined, + categoryId: number | null +): P[] { + const offered = stayPlaces

(places, placeId); + return categoryId != null ? offered.filter((p) => p.category_id === categoryId) : offered; +} + +/** The request body for creating or updating a stay; empty times and codes are sent as null. */ +export function stayRequestBody(form: StayFormFields

, range: StayRange) { + return { + place_id: form.place_id, + start_day_id: range.start, + end_day_id: range.end, + check_in: form.check_in || null, + check_in_end: form.check_in_end || null, + check_out: form.check_out || null, + confirmation: form.confirmation || null, + }; +} diff --git a/client/src/components/Planner/useDayDetail.test.ts b/client/src/components/Planner/useDayDetail.test.ts index 90abecc9a..812116285 100644 --- a/client/src/components/Planner/useDayDetail.test.ts +++ b/client/src/components/Planner/useDayDetail.test.ts @@ -1,11 +1,13 @@ -// FE-PLANNER-USEDAYDETAIL-001 to -007: the forecast and the in-place rename the -// desktop day panel and the phone day sheet share. +// FE-PLANNER-USEDAYDETAIL-001 to -009: the forecast, the in-place rename and the +// stay write the desktop day panel and the phone day and stay sheets share. import { act, renderHook, waitFor } from '@testing-library/react'; import type { WeatherResult } from '@trek/shared'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { weatherApi } from '../../api/client'; -import { useDayForecast, useDayRename } from './useDayDetail'; +import { resetAllStores } from '../../../tests/helpers/store'; +import { accommodationsApi, weatherApi } from '../../api/client'; +import { useTripStore } from '../../store/tripStore'; +import { useDayForecast, useDayRename, writeStay } from './useDayDetail'; const SUNNY = { temp: 21, main: 'Clear', description: 'clear sky' } as WeatherResult; @@ -16,7 +18,10 @@ function deferred() { return { promise, resolve }; } -afterEach(() => vi.restoreAllMocks()); +afterEach(() => { + vi.restoreAllMocks(); + resetAllStores(); +}); describe('useDayForecast', () => { it('FE-PLANNER-USEDAYDETAIL-001: asks for nothing while not ready', () => { @@ -107,3 +112,29 @@ describe('useDayRename', () => { expect(onCommit).not.toHaveBeenCalled(); }); }); + +describe('writeStay', () => { + const body = { place_id: 7, start_day_id: 1, end_day_id: 2, check_in: null }; + + it('FE-PLANNER-USEDAYDETAIL-008: creates a new stay and applies the stop the server added for it', async () => { + const handleRemoteEvent = vi.fn(); + useTripStore.setState({ handleRemoteEvent } as never); + const assignment = { id: 5, day_id: 1 }; + const create = vi.spyOn(accommodationsApi, 'create').mockResolvedValue({ accommodation: { id: 9 }, assignment }); + const update = vi.spyOn(accommodationsApi, 'update'); + + await expect(writeStay(3, null, body)).resolves.toEqual({ accommodation: { id: 9 }, assignment }); + expect(create).toHaveBeenCalledWith(3, body); + expect(update).not.toHaveBeenCalled(); + expect(handleRemoteEvent).toHaveBeenCalledWith({ type: 'assignment:created', assignment }); + }); + + it('FE-PLANNER-USEDAYDETAIL-009: updates the given stay, and a refused write throws', async () => { + const update = vi.spyOn(accommodationsApi, 'update').mockResolvedValueOnce({ accommodation: { id: 4 } }); + await writeStay(3, 4, body); + expect(update).toHaveBeenCalledWith(3, 4, body); + + update.mockRejectedValueOnce(new Error('overlap')); + await expect(writeStay(3, 4, body)).rejects.toThrow('overlap'); + }); +}); diff --git a/client/src/components/Planner/useDayDetail.ts b/client/src/components/Planner/useDayDetail.ts index 31588d93d..1cf61c9ed 100644 --- a/client/src/components/Planner/useDayDetail.ts +++ b/client/src/components/Planner/useDayDetail.ts @@ -3,6 +3,7 @@ import type { WeatherResult } from '@trek/shared' import { weatherApi, accommodationsApi } from '../../api/client' import { isDayInAccommodationRange } from '../../utils/dayOrder' import { applyStayStops } from '../../store/stayStops' +import { stayCheckoutDay, stayRequestBody } from './stayFormModel' import type { Accommodation, Day } from '../../types' export interface HotelForm { @@ -23,6 +24,17 @@ export type HotelPickerMode = boolean | 'edit' const EMPTY_HOTEL_FORM: HotelForm = { check_in: '', check_in_end: '', check_out: '', confirmation: '', place_id: null } +/** + * Creates a stay, or updates the one with `accId`, and applies the stops the + * server moved for it, for the desktop day panel and the phone accommodation + * sheet alike. Throws when the server refuses the write. + */ +export async function writeStay(tripId: number, accId: number | null, body: Parameters[1]) { + const data = accId != null ? await accommodationsApi.update(tripId, accId, body) : await accommodationsApi.create(tripId, body) + applyStayStops(data) + return data +} + /** * A day's detailed forecast (Open-Meteo through the weather service, climate * fallback), shared by the desktop day panel and the phone day sheet. `ready` says @@ -81,8 +93,7 @@ export function useDayDetail(day: Day | null, days: Day[], tripId: number, lat: // A stay virtually never checks out the day it checks in — default the range // to check-out on the next day, unless the trip ends here. const defaultHotelDayRange = (d: Day | null): HotelDayRange => { - const idx = (days || []).findIndex(x => x.id === d?.id) - return { start: d?.id, end: (idx >= 0 && days[idx + 1]?.id) || d?.id } + return { start: d?.id, end: stayCheckoutDay(days || [], d?.id) || d?.id } } const [hotelDayRange, setHotelDayRange] = useState(() => defaultHotelDayRange(day)) const [hotelCategoryFilter, setHotelCategoryFilter] = useState('') @@ -120,16 +131,7 @@ export function useDayDetail(day: Day | null, days: Day[], tripId: number, lat: /** Creates the stay the picker describes. Throws when the server refuses it. */ const handleSaveAccommodation = async () => { if (!hotelForm.place_id || hotelDayRange.start == null || hotelDayRange.end == null) return - const data = await accommodationsApi.create(tripId, { - place_id: hotelForm.place_id, - start_day_id: hotelDayRange.start, - end_day_id: hotelDayRange.end, - check_in: hotelForm.check_in || null, - check_in_end: hotelForm.check_in_end || null, - check_out: hotelForm.check_out || null, - confirmation: hotelForm.confirmation || null, - }) - applyStayStops(data) + const data = await writeStay(tripId, null, stayRequestBody(hotelForm, hotelDayRange)) const newAcc: Accommodation = data.accommodation const updated = [...accommodations, newAcc] setAccommodations(updated) @@ -143,15 +145,7 @@ export function useDayDetail(day: Day | null, days: Day[], tripId: number, lat: /** Saves the picker over the stay in `accommodation`, then reloads the list. Throws when the server refuses it. */ const handleUpdateAccommodation = async () => { if (!accommodation) return - applyStayStops(await accommodationsApi.update(tripId, accommodation.id, { - place_id: hotelForm.place_id, - start_day_id: hotelDayRange.start, - end_day_id: hotelDayRange.end, - check_in: hotelForm.check_in || null, - check_in_end: hotelForm.check_in_end || null, - check_out: hotelForm.check_out || null, - confirmation: hotelForm.confirmation || null, - })) + await writeStay(tripId, accommodation.id, stayRequestBody(hotelForm, hotelDayRange)) setShowHotelPicker(false) setHotelForm(EMPTY_HOTEL_FORM) const d = await accommodationsApi.list(tripId) diff --git a/client/src/mobile/screens/trip/sheets/MAccommodationSheet.tsx b/client/src/mobile/screens/trip/sheets/MAccommodationSheet.tsx index d33dca706..3587e560e 100644 --- a/client/src/mobile/screens/trip/sheets/MAccommodationSheet.tsx +++ b/client/src/mobile/screens/trip/sheets/MAccommodationSheet.tsx @@ -5,12 +5,13 @@ import MIconBtn from '../../../components/MIconBtn' import CustomSelect from '../../../../components/shared/CustomSelect' import CustomTimePicker from '../../../../components/shared/CustomTimePicker' import { BookingCodeInput } from '../../../../components/shared/BookingCode' -import { accommodationsApi } from '../../../../api/client' -import { applyStayStops } from '../../../../store/stayStops' +import { writeStay } from '../../../../components/Planner/useDayDetail' +import { + stayCheckoutDay, stayDayOptions, stayFormFrom, stayPlaceChoices, stayRangeFromEnd, stayRangeFromStart, stayRequestBody, +} from '../../../../components/Planner/stayFormModel' import { useTranslation } from '../../../../i18n' import { Eyebrow } from './MTripSheetUi' import type { MTripSheetsProps } from '../MTripShell' -import { stayPlaces } from '../../../../utils/stayPlaces' interface AccommodationPayload { dayId?: number @@ -61,16 +62,9 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps if (!open) return if (editing) { setRange({ start: editing.start_day_id, end: editing.end_day_id }) - setForm({ - check_in: editing.check_in || '', - check_in_end: editing.check_in_end || '', - check_out: editing.check_out || '', - confirmation: editing.confirmation || '', - place_id: editing.place_id ?? '', - }) + setForm(stayFormFrom(editing, '')) } else { - const idx = days.findIndex(d => d.id === payload.dayId) - setRange({ start: payload.dayId ?? 0, end: (idx >= 0 && days[idx + 1]?.id) || payload.dayId || 0 }) + setRange({ start: payload.dayId ?? 0, end: stayCheckoutDay(days, payload.dayId) || payload.dayId || 0 }) setForm(EMPTY_FORM) } setCategoryFilter(null) @@ -90,34 +84,17 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps const lastId = days[days.length - 1]?.id const allDays = days.length > 0 && range.start === firstId && range.end === lastId - const dayOptions = days.map((d, i) => ({ - value: d.id, - label: d.title || t('planner.dayN', { n: i + 1 }), - badge: d.date - ? new Date(d.date + 'T00:00:00Z').toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' }) - : (d.title ? t('planner.dayN', { n: i + 1 }) : undefined), - })) + const dayOptions = stayDayOptions(days, t, locale) - const offeredPlaces = stayPlaces(places, form.place_id) - const filteredPlaces = categoryFilter != null ? offeredPlaces.filter(p => p.category_id === categoryFilter) : offeredPlaces + const filteredPlaces = stayPlaceChoices(places, form.place_id, categoryFilter) const save = async () => { setSaving(true) - const body = { - place_id: form.place_id, - start_day_id: range.start, - end_day_id: range.end, - check_in: form.check_in || null, - check_in_end: form.check_in_end || null, - check_out: form.check_out || null, - confirmation: form.confirmation || null, - } + const body = stayRequestBody(form, range) // Only the write itself decides whether the save failed — a refresh that // trips afterwards must not be reported as a failed save. try { - applyStayStops(editing - ? await accommodationsApi.update(tripId, editing.id, body) - : await accommodationsApi.create(tripId, body)) + await writeStay(tripId, editing ? editing.id : null, body) } catch { planner.toast.error(t('common.error')) return @@ -158,10 +135,7 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps

setRange(prev => { - const id = Number(v) - return { start: id, end: days.findIndex(d => d.id === id) > days.findIndex(d => d.id === prev.end) ? id : prev.end } - })} + onChange={v => setRange(prev => stayRangeFromStart(days, prev, Number(v)))} options={dayOptions} size="sm" /> @@ -170,10 +144,7 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps
setRange(prev => { - const id = Number(v) - return { start: days.findIndex(d => d.id === id) < days.findIndex(d => d.id === prev.start) ? id : prev.start, end: id } - })} + onChange={v => setRange(prev => stayRangeFromEnd(days, prev, Number(v)))} options={dayOptions} size="sm" />