feat(trips): shortening a trip says first which days go and what is on them

The trip dialog on the desktop and the trip sheet on a phone now ask before a save whose new dates remove days with something on them. The question names those days the way the day list does and lists what goes with them in the same rows the delete day question uses: planned places stay in the place list, notes and day texts are deleted, bookings stay under Bookings, and a stay that checks in or out on a removed day goes as a whole while its booking and expense remain, shown in the danger tone. A moved start gets both questions in one step, with the booking hint following the chosen shift mode, and a save that only drops empty days asks nothing.

The rule that lays the days out moved into shared as planDayGrid, with resolveDayGridRange deciding whether the rows are rebuilt at all. generateDays on the server now carries that plan out in one transaction, so the warning names exactly the days the save takes, and a seeded fuzz test holds the new rebuild to the old one over 300 random day grids. The update_trip tool says in its description what shortening takes and lists removed_days in its answer.

Alongside, the dialog sends a day count only when it changed, so a stale count no longer trims a day just added, stays are reloaded after every date change including the one made on a phone, and the date shift tip now points to adding a day under Reorder days.
This commit is contained in:
Maurice
2026-09-23 19:54:09 +02:00
parent b56f335978
commit 1b63285ad0
50 changed files with 2122 additions and 231 deletions
@@ -0,0 +1,93 @@
/**
* FE-HOOK-RANGEGUARD-001 to FE-HOOK-RANGEGUARD-005: the question before a trip
* dialog saves new dates. The desktop dialog and the phone sheet both render
* what this answers, so what it reads, when it reads nothing, and what it says
* when it cannot read are pinned here once. The repos are mocked; the layout
* rule is the real planDayGrid from shared, the one the server runs.
*/
import { createElement, type ReactNode } from 'react'
import { act, renderHook } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { TranslationProvider } from '../i18n/TranslationContext'
import { buildAssignment, buildDay, buildPlace } from '../../tests/helpers/factories'
import type { Accommodation, Day, Reservation } from '../types'
import { useTripRangeGuard, type RangeCheck, type RangeRemoval } from './useTripRangeGuard'
const repos = {
days: vi.fn<() => Promise<{ days: Day[] }>>(),
reservations: vi.fn<() => Promise<{ reservations: Reservation[] }>>(),
accommodations: vi.fn<() => Promise<{ accommodations: Accommodation[] }>>(),
}
vi.mock('../repo/dayRepo', () => ({ dayRepo: { list: () => repos.days() } }))
vi.mock('../repo/reservationRepo', () => ({ reservationRepo: { list: () => repos.reservations() } }))
vi.mock('../repo/accommodationRepo', () => ({ accommodationRepo: { list: () => repos.accommodations() } }))
const wrapper = ({ children }: { children: ReactNode }) => createElement(TranslationProvider, null, children)
const trip = { id: 7, start_date: '2026-10-01', end_date: '2026-10-05' }
/** Five dated days; the ones named get a place. */
function fiveDays(planned: number[] = []): Day[] {
return Array.from({ length: 5 }, (_, i) => buildDay({
id: i + 1,
day_number: i + 1,
date: `2026-10-0${i + 1}`,
assignments: planned.includes(i + 1) ? [buildAssignment({ day_id: i + 1, place: buildPlace({ id: 90 + i }) })] : [],
}))
}
async function ask(payload: Parameters<ReturnType<typeof useTripRangeGuard>['check']>[1]): Promise<RangeCheck> {
const { result } = renderHook(() => useTripRangeGuard(), { wrapper })
let answer: RangeCheck = null
await act(async () => { answer = await result.current.check(trip, payload) })
expect(result.current.checking).toBe(false)
return answer
}
beforeEach(() => {
repos.days.mockReset().mockResolvedValue({ days: fiveDays([4, 5]) })
repos.reservations.mockReset().mockResolvedValue({ reservations: [] })
repos.accommodations.mockReset().mockResolvedValue({ accommodations: [] })
})
describe('useTripRangeGuard', () => {
it('FE-HOOK-RANGEGUARD-001: a save that keeps the dates is answered without reading anything', async () => {
const rename = { title: 'Renamed', start_date: trip.start_date, end_date: trip.end_date }
expect(await ask(rename)).toBeNull()
expect(await ask({})).toBeNull()
expect(repos.days).not.toHaveBeenCalled()
expect(repos.reservations).not.toHaveBeenCalled()
expect(repos.accommodations).not.toHaveBeenCalled()
})
it('FE-HOOK-RANGEGUARD-002: an earlier end reads the three repos and names the days it takes, with what is on them', async () => {
const answer = await ask({ start_date: '2026-10-01', end_date: '2026-10-03' }) as RangeRemoval
expect(repos.days).toHaveBeenCalledTimes(1)
expect(repos.reservations).toHaveBeenCalledTimes(1)
expect(repos.accommodations).toHaveBeenCalledTimes(1)
expect(answer.removedDays.map(r => r.day.id)).toEqual([4, 5])
expect(answer.content.places).toBe(2)
expect(answer.startMoved).toBe(false)
// Named the way the day list names them: the date, short.
expect(answer.dayLabels).toEqual(['Sun, Oct 4', 'Mon, Oct 5'])
})
it('FE-HOOK-RANGEGUARD-003: days that go empty ask nothing', async () => {
repos.days.mockResolvedValue({ days: fiveDays([1, 2]) })
expect(await ask({ start_date: '2026-10-01', end_date: '2026-10-03' })).toBeNull()
})
it('FE-HOOK-RANGEGUARD-004: when the days cannot be read the answer is unknown, not silence', async () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
repos.reservations.mockRejectedValue(new Error('500'))
expect(await ask({ start_date: '2026-10-01', end_date: '2026-10-03' })).toBe('unknown')
expect(spy).toHaveBeenCalled()
spy.mockRestore()
})
it('FE-HOOK-RANGEGUARD-005: a later start with the same end takes the last days and says the start moved', async () => {
const answer = await ask({ start_date: '2026-10-03', end_date: '2026-10-05' }) as RangeRemoval
expect(answer.removedDays.map(r => r.day.id)).toEqual([4, 5])
expect(answer.startMoved).toBe(true)
})
})
+87
View File
@@ -0,0 +1,87 @@
import { useCallback, useState } from 'react'
import { planDayGrid, resolveDayGridRange } from '@trek/shared'
import { useTranslation } from '../i18n'
import { dayRepo } from '../repo/dayRepo'
import { reservationRepo } from '../repo/reservationRepo'
import { accommodationRepo } from '../repo/accommodationRepo'
import { dayLabel } from '../utils/dayLabel'
import { hasVisibleContent, tripRangeImpact, type TripRangeImpact } from '../utils/tripRangeImpact'
import type { AssignmentsMap, DayNotesMap, Trip } from '../types'
/** Days a save would remove, with the names the day list gives them. */
export interface RangeRemoval extends TripRangeImpact {
dayLabels: string[]
}
/**
* The answer before a save: the days it removes with something on them, null
* when it removes nothing worth a question, or 'unknown' when the trip's days
* could not be read, so the dialog can still warn in general terms.
*/
export type RangeCheck = RangeRemoval | 'unknown' | null
/** The fields of a trip save that move the day grid. */
export interface RangePayload {
start_date?: string | null
end_date?: string | null
day_count?: number | null
}
/**
* Asks, before a trip dialog saves new dates, which days the save would remove
* and what is on them. It reads the trip's days, bookings and stays through the
* repos and lays the days out with planDayGrid, the rule the server rebuilds
* them by, so the warning names exactly the days the save takes. A save that
* does not rebuild the days is answered without reading anything.
*
* Used by the desktop trip dialog and the phone's trip sheet alike; both only
* render what comes back.
*/
export function useTripRangeGuard(): { checking: boolean; check: (trip: Pick<Trip, 'id' | 'start_date' | 'end_date'>, payload: RangePayload) => Promise<RangeCheck> } {
const { t, locale } = useTranslation()
const [checking, setChecking] = useState(false)
const check = useCallback(async (trip: Pick<Trip, 'id' | 'start_date' | 'end_date'>, payload: RangePayload): Promise<RangeCheck> => {
const range = resolveDayGridRange(trip, payload)
if (!range.regenerate) return null
setChecking(true)
try {
const [{ days }, { reservations }, { accommodations }] = await Promise.all([
dayRepo.list(trip.id),
reservationRepo.list(trip.id),
accommodationRepo.list(trip.id),
])
const plan = planDayGrid({
days: days.map(d => ({
id: d.id,
day_number: d.day_number ?? 0,
date: d.date,
hasPlanItems: (d.assignments?.length ?? 0) > 0 || (d.notes_items?.length ?? 0) > 0,
})),
stays: accommodations,
startDate: range.newStart,
endDate: range.newEnd,
dayCount: range.dayCount,
})
if (plan.removed.length === 0) return null
const assignments: AssignmentsMap = {}
const dayNotes: DayNotesMap = {}
for (const day of days) {
assignments[String(day.id)] = day.assignments ?? []
dayNotes[String(day.id)] = day.notes_items ?? []
}
const startMoved = !!trip.start_date && !!range.newStart && !!range.newEnd && range.newStart !== trip.start_date
const impact = tripRangeImpact(plan, days, { assignments, dayNotes, reservations, accommodations }, { startMoved })
if (!hasVisibleContent(impact)) return null
return { ...impact, dayLabels: impact.removedDays.map(({ day, index }) => dayLabel(day, index, t, locale)) }
} catch (err: unknown) {
console.error('Failed to read the days a new range removes:', err)
return 'unknown'
} finally {
setChecking(false)
}
}, [t, locale])
return { checking, check }
}