fix(bookings): bookings, transports and stays saved offline wait in the queue and sync once the connection is back

Every booking and stay write went straight to the API, so offline a new
booking failed with "Network Error" and was lost, and a status tick, the
travellers or a moved transport snapped back. Bookings (add, edit, status,
travellers, delete, day order) and stays (add, edit, delete) now go through
reservationRepo and accommodationRepo and the mutation queue like places and
costs: a temporary row offline, held behind an older queued write online,
since neither carries a version token. Desktop, the phone sheets, the day
plan, the road trip nights and the PDF all write and read through them.

The replay reads the booking from `reservation` only, so the travellers
answer ({ travelers, reservation }) lands on the booking it names. A booking
or its stay that names a place or stay created offline is sent with the real
id once that one has synced, inside create_accommodation too, so an imported
hotel reviewed offline can be linked to a place made for it.

What only works online says so instead of failing: an AirTrail import, a
booking file import, the AI retry and an attachment on a saved booking show
that they need a connection, and a save with newly picked files is stopped
with a hint, since an upload cannot wait in the queue.

Refs #2601
This commit is contained in:
Maurice
2026-10-12 19:07:33 +02:00
parent 5dbcc4af40
commit 64ceecefb3
60 changed files with 1011 additions and 82 deletions
@@ -3,9 +3,11 @@ import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router'
import { Loader2, CheckCircle2, AlertCircle, AlertTriangle, X } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
import { addListener, removeListener } from '../../api/websocket'
import { reservationsApi, healthApi } from '../../api/client'
import { saveImportFiles } from '../../db/offlineDb'
import { isEffectivelyOffline } from '../../sync/networkMode'
import { useBackgroundTasksStore, taskFoundSomething, type BackgroundImportTask } from '../../store/backgroundTasksStore'
import type { ReceiptRead } from '@trek/shared'
@@ -33,6 +35,7 @@ function readingKey(task: BackgroundImportTask): string {
*/
export default function BackgroundTasksWidget() {
const { t } = useTranslation()
const toast = useToast()
const navigate = useNavigate()
const tasks = useBackgroundTasksStore((s) => s.tasks)
const setProgress = useBackgroundTasksStore((s) => s.setProgress)
@@ -56,6 +59,8 @@ export default function BackgroundTasksWidget() {
const retryWithAi = async (task: BackgroundImportTask) => {
const files = task.sourceFiles
if (!files || files.length === 0 || retrying === task.id) return
// Offline the card stays as it is, with its button, for a try once the connection is back.
if (isEffectivelyOffline()) { toast.error(t('reservations.needsConnection')); return }
setRetrying(task.id)
try {
const { jobId } = await reservationsApi.importBookingAsync(task.tripId, files, 'force-ai')
+3 -2
View File
@@ -2,7 +2,8 @@
import { createElement } from 'react'
import { getCategoryIcon } from '../shared/categoryIcons'
import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Sailboat, CableCar, Bike, CarTaxiFront, Route, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark, Hotel, LogIn, LogOut, KeyRound, BedDouble, Utensils, Users, ParkingSquare, LucideIcon } from 'lucide-react'
import { accommodationsApi, mapsApi, pluginsApi } from '../../api/client'
import { mapsApi, pluginsApi } from '../../api/client'
import { accommodationRepo } from '../../repo/accommodationRepo'
import type { Trip, Day, Place, Category, AssignmentsMap, DayNote, DistanceUnit, BudgetItem } from '../../types'
import { isDayInAccommodationRange, getDayOrder } from '../../utils/dayOrder'
import { hidesOnMiddleDay, getTransportForDay, getMergedItems, getSpanPhase, getDisplayTimeForDay } from '../../utils/dayMerge'
@@ -254,7 +255,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
const range = longDateRange(sorted, loc)
const coverImg = safeImg(trip?.cover_image)
//retrieve accommodations for the trip to display on the day sections and prefetch their photos if needed
const accommodations = await accommodationsApi.list(trip.id);
const accommodations = await accommodationRepo.list(trip.id);
// The endpoint answers `{ accommodations: [...] }`, not a bare array. Unwrapped once
// here so every reader below gets the list itself — passing the envelope on is what
// cost the route map its hotel legs, and silently (#1736).
@@ -1,4 +1,4 @@
// FE-PLANNER-AIRTRAIL-001 to FE-PLANNER-AIRTRAIL-020
// FE-PLANNER-AIRTRAIL-001 to FE-PLANNER-AIRTRAIL-022
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -8,6 +8,7 @@ import { useTripStore } from '../../store/tripStore';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser, buildTrip, buildReservation } from '../../../tests/helpers/factories';
import type { AirtrailFlight } from '@trek/shared';
import { _resetNetworkMode, setForcedOffline } from '../../sync/networkMode';
import AirTrailImportModal, { detectConnections } from './AirTrailImportModal';
const toasts: Array<[string, string]> = [];
@@ -345,4 +346,16 @@ describe('AirTrailImportModal', () => {
await screen.findByText('Finnair AY1502');
expect(screen.queryByText(/^Imported$/)).not.toBeInTheDocument();
});
it('FE-PLANNER-AIRTRAIL-022: offline the dialog says it needs a connection instead of asking AirTrail (#2601)', async () => {
const flights = vi.fn();
server.use(http.get('/api/integrations/airtrail/flights', () => { flights(); return HttpResponse.json({ flights: [flight()] }); }));
setForcedOffline(true);
try {
render(<AirTrailImportModal {...defaultProps} />);
expect(await screen.findByText('This needs a connection. Try again once TREK is back online.')).toBeInTheDocument();
} finally {
_resetNetworkMode();
}
expect(flights).not.toHaveBeenCalled();
});
});
@@ -5,8 +5,9 @@ import { Plane, X, Check } from 'lucide-react'
import type { AirtrailFlight, AirtrailImportResult } from '@trek/shared'
import { useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
import { airtrailApi, reservationsApi } from '../../api/client'
import { airtrailApi } from '../../api/client'
import { useTripStore } from '../../store/tripStore'
import { isEffectivelyOffline } from '../../sync/networkMode'
import { parseReservationMetadata } from '../../utils/flightLegs'
interface AirTrailImportModalProps {
@@ -71,6 +72,7 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo
const trip = useTripStore(s => s.trip)
const reservations = useTripStore(s => s.reservations)
const loadReservations = useTripStore(s => s.loadReservations)
const deleteReservation = useTripStore(s => s.deleteReservation)
const mouseDownTarget = useRef<EventTarget | null>(null)
const [loading, setLoading] = useState(false)
@@ -117,6 +119,12 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo
setError('')
setSelected(new Set())
setJoinOff(new Set())
// The flights live on the AirTrail server, which only a connection reaches.
if (isEffectivelyOffline()) {
setFlights([])
setError(t('reservations.needsConnection'))
return
}
setLoading(true)
airtrailApi
.flights()
@@ -196,6 +204,7 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo
const handleImport = async () => {
const ids = [...selected].filter(id => !importedIds.has(id))
if (ids.length === 0 || importing) return
if (isEffectivelyOffline()) { setError(t('reservations.needsConnection')); return }
setImporting(true)
setError('')
try {
@@ -209,7 +218,7 @@ export default function AirTrailImportModal({ isOpen, onClose, tripId, pushUndo
const linked = useTripStore.getState().reservations.filter(
r => r.external_source === 'airtrail' && r.external_id && imported.includes(String(r.external_id)),
)
await Promise.all(linked.map(r => reservationsApi.delete(tripId, r.id).catch(() => {})))
await Promise.all(linked.map(r => deleteReservation(tripId, r.id).catch(() => {})))
await loadReservations(tripId)
})
toast.success(t('reservations.airtrail.imported', { count: imported.length }))
@@ -7,6 +7,7 @@ import { llmRepo } from '../../repo/llmRepo'
import { LLM_PHOTO_EXTENSIONS } from '@trek/shared'
import { useBackgroundTasksStore } from '../../store/backgroundTasksStore'
import { saveImportFiles } from '../../db/offlineDb'
import { isEffectivelyOffline } from '../../sync/networkMode'
interface BookingImportModalProps {
isOpen: boolean
@@ -101,6 +102,8 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
// Start the parse in the background and close — the widget takes it from here.
const handleParse = async () => {
if (files.length === 0 || loading) return
// Reading a booking runs on the server: offline there is nothing to send it to.
if (isEffectivelyOffline()) { setError(t('reservations.needsConnection')); return }
setLoading(true)
setError('')
try {
@@ -10,7 +10,7 @@ import { safeHttpUrl } from '../../utils/safeUrl'
import { ChevronDown, ChevronRight, ChevronUp, Compass, RotateCcw, ExternalLink, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Eraser, Route as RouteIcon, RouteOff, Bookmark, StickyNote, TramFront, Zap, MapPin, Globe } from 'lucide-react'
import { type PickedPlace } from './TransitSearchPanel'
import { buildTransitLeg, buildTransitNameIndex } from './transitLeg'
import { reservationsApi, daysApi } from '../../api/client'
import { daysApi } from '../../api/client'
import { optimizeRoute, generateGoogleMapsUrl, generateCoMapsUrl } from '../Map/RouteCalculator'
import { dayViaLookup, routeLeg, type LegEnd, type ViasByDay } from '../Map/dayRouteVias'
import GoogleMapsIcon from '../shared/GoogleMapsIcon'
@@ -522,7 +522,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// day shows an order that only exists in this tab.
// The ids stay marked as initialised: the effect reruns on every reservations
// change, so clearing them here would retry the same failing write in a loop.
reservationsApi.updatePositions(tripId, positions).catch(() => {
tripActions.updateReservationPositions(tripId, positions).catch(() => {
useTripStore.setState(state => ({
reservations: state.reservations.map(r => {
const p = before.find(x => x.id === r.id)
@@ -906,7 +906,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
if (assignmentIds.length) await onReorder(dayId, assignmentIds)
if (transportUpdates.length) {
onRouteRefresh?.()
await reservationsApi.updatePositions(tripId, transportUpdates, dayId)
await tripActions.updateReservationPositions(tripId, transportUpdates, dayId)
for (const tu of transportUpdates) dropRollback(tu.id)
}
for (const n of noteUpdates) {
@@ -26,7 +26,7 @@ import { typeInfo } from './bookings/bookingsModel'
import type { StatusTone } from './bookings/bookingParts'
import { RESERVATION_TYPE_OPTIONS as TYPE_OPTIONS, reservationFieldsFrom, reservationFieldsFromPrefill, selectedDayDate } from './reservationFormModel'
import { useReservationForm } from './useReservationForm'
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, travelersChanged, uploadBookingFiles } from './bookingFormModel'
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, travelersChanged, filesNeedConnection, uploadBookingFiles } from './bookingFormModel'
import { useBookingExpenseIntent } from './useBookingExpenseIntent'
import { useBookingFileAttach } from './useBookingFileAttach'
@@ -126,6 +126,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
e?.preventDefault?.()
if (!form.title.trim()) return
if (isEndBeforeStart) { toast.error(t('reservations.validation.endBeforeStart')); return }
if (filesNeedConnection(pendingFiles, !!onFileUpload)) { toast.error(t('reservations.filesNeedConnection')); return }
setIsSaving(true)
try {
const saveData = buildSaveData({ assignmentId: form.assignment_id, isEdit: !!reservation?.id, withCheckInEnd: true })
@@ -30,7 +30,7 @@ import {
transportDayOptions, type StationWaypointForm, type WaypointForm,
} from './transportEndpoints'
import { useTransportForm } from './useTransportForm'
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, travelersChanged, uploadBookingFiles } from './bookingFormModel'
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, travelersChanged, filesNeedConnection, uploadBookingFiles } from './bookingFormModel'
import { useBookingExpenseIntent } from './useBookingExpenseIntent'
import { useBookingFileAttach } from './useBookingFileAttach'
@@ -130,9 +130,14 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
})
}, [isOpen, reservation, prefill, selectedDayId, budgetItems])
const handleSubmit = async (e?: React.FormEvent) => {
const handleSubmit = (e?: React.FormEvent) => {
e?.preventDefault()
if (!form.title.trim()) return
if (filesNeedConnection(pendingFiles, !!onFileUpload)) { toast.error(t('reservations.filesNeedConnection')); return }
return saveTransport()
}
const saveTransport = async () => {
setIsSaving(true)
try {
const saved = await onSave(payload(days, {
@@ -1,13 +1,15 @@
// FE-PLANNER-BOOKINGFORM-001 to -009: the travellers, picked files, attached files
// FE-PLANNER-BOOKINGFORM-001 to -010: the travellers, picked files, attached files
// and expense requests of the transport and booking forms, desktop and phone alike.
import { typeToCostCategory } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
import { buildBudgetItem, buildDay, buildReservation, buildTripFile } from '../../../tests/helpers/factories';
import { _resetNetworkMode, setForcedOffline } from '../../sync/networkMode';
import type { Reservation } from '../../types';
import {
attachedBookingFiles,
expenseRequestAfterSave,
filesNeedConnection,
pendingImportExpense,
toggledTraveler,
travelerIdsOf,
@@ -113,4 +115,16 @@ describe('bookingFormModel', () => {
expect(attachedBookingFiles(files, null, [3])).toEqual([]);
expect(attachedBookingFiles(files, undefined, [])).toEqual([]);
});
it('FE-PLANNER-BOOKINGFORM-010: only files that would go up while offline hold the save back (#2601)', () => {
const file = new File(['x'], 'ticket.pdf');
expect(filesNeedConnection([file], true)).toBe(false);
setForcedOffline(true);
try {
expect(filesNeedConnection([file], true)).toBe(true);
expect(filesNeedConnection([], true)).toBe(false);
expect(filesNeedConnection([file], false)).toBe(false);
} finally {
_resetNetworkMode();
}
});
});
@@ -1,5 +1,6 @@
import { typeToCostCategory } from '@trek/shared';
import { isEffectivelyOffline } from '../../sync/networkMode';
import type { BudgetItem, Day, Reservation, TripFile } from '../../types';
import type { BookingExpenseRequest } from './BookingCostsSection.types';
import { importedPriceEntry } from './importedPrice';
@@ -53,6 +54,15 @@ export async function uploadBookingFiles(
}
}
/**
* Whether saving now would have to upload picked files while TREK is offline. A
* file cannot wait in the offline queue the way the booking can, so the form asks
* to save without the new files instead of storing a booking that loses them.
*/
export function filesNeedConnection(files: File[], canUpload: boolean): boolean {
return canUpload && files.length > 0 && isEffectivelyOffline();
}
/**
* Which expense the user asked for while saving a booking: a new one or an edit of
* the linked one. The form saves itself first, so the request can name the saved id.
@@ -1,4 +1,4 @@
// FE-PLANNER-BOOKINGFILES-001 to -005: the Files row of the desktop booking and
// FE-PLANNER-BOOKINGFILES-001 to -006: the Files row of the desktop booking and
// transport dialogs.
import { act, renderHook } from '@testing-library/react';
import type React from 'react';
@@ -6,6 +6,7 @@ import { useState } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { buildTripFile } from '../../../tests/helpers/factories';
import { _resetNetworkMode, setForcedOffline } from '../../sync/networkMode';
import type { TripFile } from '../../types';
import { type BookingFileAttachOptions, useBookingFileAttach } from './useBookingFileAttach';
@@ -93,4 +94,21 @@ describe('useBookingFileAttach', () => {
const { result } = setup({ reservation: null }, [buildTripFile({ id: 1, reservation_id: 5 })]);
expect(result.current.attach.attachedFiles).toEqual([]);
});
it('FE-PLANNER-BOOKINGFILES-006: offline a file on a saved booking is not sent and says it needs a connection (#2601)', async () => {
const onFileUpload = vi.fn(async (_fd: FormData) => undefined);
const { result, toast } = setup({ onFileUpload });
const event = changeEvent(new File(['x'], 'ticket.pdf'));
setForcedOffline(true);
try {
await act(async () => {
await result.current.attach.handleFileChange(event);
});
} finally {
_resetNetworkMode();
}
expect(onFileUpload).not.toHaveBeenCalled();
expect(toast.error).toHaveBeenCalledWith('reservations.needsConnection');
expect(event.target.value).toBe('');
expect(result.current.pendingFiles).toEqual([]);
});
});
@@ -1,6 +1,7 @@
import type React from 'react';
import { type Dispatch, type SetStateAction, useState } from 'react';
import { isEffectivelyOffline } from '../../sync/networkMode';
import type { TripFile } from '../../types';
import { attachedBookingFiles } from './bookingFormModel';
@@ -35,7 +36,12 @@ export function useBookingFileAttach({
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
if (reservation?.id) {
if (reservation?.id && isEffectivelyOffline()) {
// A file goes up at once on a saved booking, and an upload cannot wait in
// the offline queue.
toast.error(t('reservations.needsConnection'));
e.target.value = '';
} else if (reservation?.id) {
setUploadingFile(true);
try {
if (onFileUpload) {
@@ -1,6 +1,7 @@
import { useState, useEffect, useRef } from 'react'
import type { WeatherResult } from '@trek/shared'
import { weatherApi, accommodationsApi } from '../../api/client'
import { weatherApi } from '../../api/client'
import { accommodationRepo } from '../../repo/accommodationRepo'
import { isDayInAccommodationRange } from '../../utils/dayOrder'
import { applyStayStops } from '../../store/stayStops'
import { stayCheckoutDay, stayRequestBody } from './stayFormModel'
@@ -29,8 +30,8 @@ const EMPTY_HOTEL_FORM: HotelForm = { check_in: '', check_in_end: '', check_out:
* 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<typeof accommodationsApi.create>[1]) {
const data = accId != null ? await accommodationsApi.update(tripId, accId, body) : await accommodationsApi.create(tripId, body)
export async function writeStay(tripId: number, accId: number | null, body: Parameters<typeof accommodationRepo.create>[1]) {
const data = accId != null ? await accommodationRepo.update(tripId, accId, body) : await accommodationRepo.create(tripId, body)
applyStayStops(data)
return data
}
@@ -109,7 +110,7 @@ export function useDayDetail(day: Day | null, days: Day[], tripId: number, lat:
useEffect(() => {
if (!tripId) return
let cancelled = false
accommodationsApi.list(tripId)
accommodationRepo.list(tripId)
.then(data => {
if (cancelled) return
const all: Accommodation[] = data.accommodations || []
@@ -148,7 +149,7 @@ export function useDayDetail(day: Day | null, days: Day[], tripId: number, lat:
await writeStay(tripId, accommodation.id, stayRequestBody(hotelForm, hotelDayRange))
setShowHotelPicker(false)
setHotelForm(EMPTY_HOTEL_FORM)
const d = await accommodationsApi.list(tripId)
const d = await accommodationRepo.list(tripId)
const all: Accommodation[] = d.accommodations || []
setAccommodations(all)
const forDay = all.filter(isForDay)
@@ -160,7 +161,7 @@ export function useDayDetail(day: Day | null, days: Day[], tripId: number, lat:
const updateAccommodationField = async (field: string, value: string | null) => {
if (!accommodation) return
try {
const data = await accommodationsApi.update(tripId, accommodation.id, { [field]: value || null })
const data = await accommodationRepo.update(tripId, accommodation.id, { [field]: value || null })
applyStayStops(data)
setAccommodation(data.accommodation)
onAccommodationChange?.()
@@ -175,7 +176,7 @@ export function useDayDetail(day: Day | null, days: Day[], tripId: number, lat:
*/
const handleRemoveAccommodation = async (target: Accommodation | null = accommodation) => {
if (!target) return
applyStayStops(await accommodationsApi.delete(tripId, target.id))
applyStayStops(await accommodationRepo.delete(tripId, target.id))
const updated = accommodations.filter(a => a.id !== target.id)
setAccommodations(updated)
setDayAccommodations(updated.filter(isForDay))