From 00ac889139957b1e6ca5bf22dc57dbe3bc5fdd51 Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 29 Oct 2026 15:11:25 +0100 Subject: [PATCH] fix(bookings): add the next imported booking instead of writing over the last one The follow-up kept the booking a save stored until the editor session changed, and on the phone the session was only the open flag. The import review swaps the draft without closing the sheet, so the second booking of the same kind went out as an update of the first and lost its linked cost. The stored booking now lives only as long as a failed try needs it, and the phone sheets name their session the way the desktop dialogs do, by the booking or draft they hold. The sheets also seed their form from that session, so the next draft of the review shows its own fields. The follow-up hook gets its own test, the notes block test passes the saving flag the component now takes, and the swallowed-catch baseline follows the one catch the save merge removed. --- client/scripts/eslint-baseline.json | 2 +- .../Planner/BookingNotesFilesCosts.test.tsx | 10 +- .../Planner/useBookingFollowUp.test.ts | 119 ++++++++++++++++++ .../components/Planner/useBookingFollowUp.ts | 4 + .../screens/trip/sheets/MReservationSheet.tsx | 6 +- .../trip/sheets/MTransportFormSheet.tsx | 6 +- .../mobile/trip/MReservationSheet.test.tsx | 20 ++- .../mobile/trip/MTransportFormSheet.test.tsx | 22 +++- 8 files changed, 179 insertions(+), 10 deletions(-) create mode 100644 client/src/components/Planner/useBookingFollowUp.test.ts diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.json index 7c5e124db..e482eb1fa 100644 --- a/client/scripts/eslint-baseline.json +++ b/client/scripts/eslint-baseline.json @@ -5,7 +5,7 @@ "no-console": 88, "complexity": 219, "@typescript-eslint/no-explicit-any": 146, - "trek/no-swallowed-catch": 130, + "trek/no-swallowed-catch": 129, "max-params": 32, "trek/store-without-selector": 67, "react-hooks/refs": 555, diff --git a/client/src/components/Planner/BookingNotesFilesCosts.test.tsx b/client/src/components/Planner/BookingNotesFilesCosts.test.tsx index 2e17b2c39..37e88f3f5 100644 --- a/client/src/components/Planner/BookingNotesFilesCosts.test.tsx +++ b/client/src/components/Planner/BookingNotesFilesCosts.test.tsx @@ -1,4 +1,4 @@ -// FE-PLANNER-NOTESFILESCOSTS-001 to FE-PLANNER-NOTESFILESCOSTS-003 +// FE-PLANNER-NOTESFILESCOSTS-001 to FE-PLANNER-NOTESFILESCOSTS-004 import { createRef, type ComponentProps } from 'react'; import { describe, expect, it, vi } from 'vitest'; @@ -37,7 +37,6 @@ function setup(overrides: Partial = {}) { pendingFiles: [], fileInputRef: createRef(), attach: { - uploadingFile: false, handleFileChange: vi.fn(), attachedFiles: [], removePending: vi.fn(), @@ -45,6 +44,7 @@ function setup(overrides: Partial = {}) { detachFile: vi.fn(), }, canAttach: true, + saving: false, showCosts: true, pendingExpense: null, expense: { reset: vi.fn(), take: vi.fn(), create: vi.fn(), edit: vi.fn(), remove: vi.fn() }, @@ -99,4 +99,10 @@ describe('BookingNotesFilesCosts', () => { expect(screen.queryByTestId('costs')).toBeNull(); expect(linkAndFiles).toHaveBeenCalledWith(expect.objectContaining({ reservationId: undefined })); }); + + it('FE-PLANNER-NOTESFILESCOSTS-004: shows the files as uploading while the booking saves', () => { + setup({ saving: true }); + + expect(linkAndFiles).toHaveBeenCalledWith(expect.objectContaining({ uploading: true })); + }); }); diff --git a/client/src/components/Planner/useBookingFollowUp.test.ts b/client/src/components/Planner/useBookingFollowUp.test.ts new file mode 100644 index 000000000..53b2af64c --- /dev/null +++ b/client/src/components/Planner/useBookingFollowUp.test.ts @@ -0,0 +1,119 @@ +// FE-PLANNER-BOOKINGFOLLOWUP-001 to -006: what a booking save does after the +// booking itself, shared by the desktop dialogs and the phone sheets. +import { act, renderHook } from '@testing-library/react'; +import { useState } from 'react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { useTripStore } from '../../store/tripStore'; +import type { Reservation } from '../../types'; +import { useBookingFollowUp } from './useBookingFollowUp'; + +const BOOKING = { id: 99 } as Reservation; +const t = (key: string) => key; + +interface Props { + session: unknown; + travelerIds?: Set; + upload?: (fd: FormData) => Promise; +} + +let setTravelers: ReturnType; + +function setup(initial: Props, files: File[] = []) { + return renderHook( + ({ session, travelerIds = new Set([7]), upload }: Props) => { + const [pendingFiles, setPendingFiles] = useState(files); + const followUp = useBookingFollowUp({ + session, + tripId: 5, + original: { travelers: [{ user_id: 7 }] } as Reservation, + travelerIds, + pendingFiles, + setPendingFiles, + upload, + t, + }); + return { followUp, pendingFiles }; + }, + { initialProps: initial } + ); +} + +async function save(result: { current: { followUp: ReturnType } }) { + let outcome: unknown = null; + await act(async () => { + await result.current.followUp + .steps('Hotel') + .afterSave(BOOKING) + .catch((err: unknown) => { + outcome = err; + }); + }); + return outcome; +} + +describe('useBookingFollowUp', () => { + beforeEach(() => { + setTravelers = vi.fn(async () => undefined); + useTripStore.setState({ setReservationTravelers: setTravelers as never }); + }); + + it('FE-PLANNER-BOOKINGFOLLOWUP-001: a save that goes through leaves nothing to retry', async () => { + const upload = vi.fn(async () => undefined); + const { result } = setup({ session: 'new', upload }, [new File(['a'], 'a.pdf')]); + expect(await save(result)).toBeNull(); + expect(result.current.followUp.holdsSaved()).toBe(false); + expect(result.current.followUp.steps('Hotel').saved).toBeUndefined(); + expect(result.current.pendingFiles).toEqual([]); + }); + + it('FE-PLANNER-BOOKINGFOLLOWUP-002: a failed upload keeps the booking and exactly the files still to send', async () => { + const a = new File(['a'], 'a.pdf'); + const b = new File(['b'], 'b.pdf'); + const upload = vi.fn().mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error('413')); + const { result } = setup({ session: 'new', upload }, [a, b]); + const err = await save(result); + expect((err as Error).message).toBe('reservations.toast.filesNotUploaded'); + expect(result.current.followUp.holdsSaved()).toBe(true); + expect(result.current.followUp.steps('Hotel').saved).toBe(BOOKING); + expect(result.current.pendingFiles).toEqual([b]); + const fd = upload.mock.calls[0][0] as FormData; + expect(fd.get('reservation_id')).toBe('99'); + expect(fd.get('description')).toBe('Hotel'); + }); + + it('FE-PLANNER-BOOKINGFOLLOWUP-003: the retry after a failure clears the stored booking once it goes through', async () => { + const upload = vi.fn().mockRejectedValueOnce(new Error('413')).mockResolvedValue(undefined); + const { result } = setup({ session: 'new', upload }, [new File(['a'], 'a.pdf')]); + await save(result); + expect(result.current.followUp.holdsSaved()).toBe(true); + expect(await save(result)).toBeNull(); + expect(result.current.followUp.holdsSaved()).toBe(false); + }); + + it('FE-PLANNER-BOOKINGFOLLOWUP-004: another session starts without the booking a failed try stored', async () => { + const upload = vi.fn().mockRejectedValue(new Error('413')); + const { result, rerender } = setup({ session: 'new', upload }, [new File(['a'], 'a.pdf')]); + await save(result); + expect(result.current.followUp.holdsSaved()).toBe(true); + rerender({ session: { title: 'Next draft' }, upload }); + expect(result.current.followUp.holdsSaved()).toBe(false); + expect(result.current.followUp.steps('Hotel').saved).toBeUndefined(); + }); + + it('FE-PLANNER-BOOKINGFOLLOWUP-005: the travellers are written only when the pick differs from the booking', async () => { + const { result, rerender } = setup({ session: 'new' }); + await save(result); + expect(setTravelers).not.toHaveBeenCalled(); + rerender({ session: 'new', travelerIds: new Set([7, 8]) }); + await save(result); + expect(setTravelers).toHaveBeenCalledWith(5, 99, [7, 8]); + }); + + it('FE-PLANNER-BOOKINGFOLLOWUP-006: a failed traveller write keeps the booking for the retry', async () => { + setTravelers.mockRejectedValueOnce(new Error('offline')); + const { result } = setup({ session: 'new', travelerIds: new Set([8]) }); + expect(await save(result)).toBeInstanceOf(Error); + expect(result.current.followUp.holdsSaved()).toBe(true); + }); +}); diff --git a/client/src/components/Planner/useBookingFollowUp.ts b/client/src/components/Planner/useBookingFollowUp.ts index b2f7065c6..abd8c85c5 100644 --- a/client/src/components/Planner/useBookingFollowUp.ts +++ b/client/src/components/Planner/useBookingFollowUp.ts @@ -62,6 +62,10 @@ export function useBookingFollowUp({ () => false ); if (!uploaded) throw new Error(t('reservations.toast.filesNotUploaded')); + // Only a failed try is retried. The editor can stay open on to the next + // booking without a new session (the import review on the phone), and that + // one must be added, not written over this one. + stored.current = null; }; return { diff --git a/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx b/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx index aca45e822..0afab9d5c 100644 --- a/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx +++ b/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx @@ -63,8 +63,10 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati isEndBeforeStart, endTimeBeforeStartTime, dateBounds, startDate, startTime, setStartDate, setStartTime, takeStopDay, pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, stayPin, saveData: buildSaveData, } = useReservationForm(EMPTY, days, places) + // The import review hands the open sheet its next booking without closing it. + const session = showReservationModal ? (editingReservation ?? reservationPrefill ?? 'new') : null const followUp = useBookingFollowUp({ - session: showReservationModal, + session, tripId, original: editingReservation, travelerIds, pendingFiles, setPendingFiles, upload: canUploadFiles ? fd => planner.tripActions.addFile(tripId, fd) : undefined, t, }) @@ -121,7 +123,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati : EMPTY) } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [showReservationModal]) + }, [session]) const res = snap.res const isHotel = form.type === 'hotel' diff --git a/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx b/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx index e2458f8bb..71c79bbdf 100644 --- a/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx +++ b/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx @@ -66,8 +66,10 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler, isSaving, setIsSaving, seed, payload: buildPayload, writesFlightLegs, writesTrainLegs, } = useTransportForm(EMPTY_TRANSPORT_FIELDS) + // The import review hands the open sheet its next booking without closing it. + const session = showTransportModal ? (editingTransport ?? transportPrefill ?? 'new') : null const followUp = useBookingFollowUp({ - session: showTransportModal, + session, tripId, original: editingTransport, travelerIds, pendingFiles, setPendingFiles, upload: canUploadFiles ? fd => planner.tripActions.addFile(tripId, fd) : undefined, t, }) @@ -98,7 +100,7 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo stopDaysFromEndpoints: true, }) // eslint-disable-next-line react-hooks/exhaustive-deps - }, [showTransportModal]) + }, [session]) const res = snap.res const prefill = snap.prefill diff --git a/client/tests/unit/mobile/trip/MReservationSheet.test.tsx b/client/tests/unit/mobile/trip/MReservationSheet.test.tsx index 42250d874..1bb32708a 100644 --- a/client/tests/unit/mobile/trip/MReservationSheet.test.tsx +++ b/client/tests/unit/mobile/trip/MReservationSheet.test.tsx @@ -14,7 +14,7 @@ import { plannerSave } from '../../../helpers/bookingSave' import { resetAllStores } from '../../../helpers/store' import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render' -// FE-MOB-RESSH-001 to FE-MOB-RESSH-069 (plus 037b) +// FE-MOB-RESSH-001 to FE-MOB-RESSH-070 (plus 037b) // Date/time/select pickers have their own suites — here they only have to be // addressable, so they render as plain controls. @@ -776,6 +776,24 @@ describe('MReservationSheet', () => { expect(fd.get('reservation_id')).toBe('99') }) + it('FE-MOB-RESSH-070: the next booking of an import review is added, not written over the one saved before it', async () => { + // The review keeps the sheet open and only swaps the draft, so the open flag never changes. + const { save } = plannerSave({ id: 99 }) + const review = { importReviewActive: true, handleSaveReservation: save } + const first = makePlanner({ ...review, reservationPrefill: { title: 'First tour', type: 'tour', metadata: null } }) + const { rerender, onOpenExpense } = setup(first) + fireEvent.click(submitBtn()) + await waitFor(() => expect(first.advanceImportReview).toHaveBeenCalledTimes(1)) + + const second = makePlanner({ ...review, reservationPrefill: { title: 'Second tour', type: 'tour', metadata: null } }) + rerender() + expect(titleField()).toHaveValue('Second tour') + fireEvent.click(submitBtn()) + await waitFor(() => expect(second.advanceImportReview).toHaveBeenCalledTimes(1)) + expect(save).toHaveBeenCalledTimes(2) + expect(save.mock.calls[1][1]?.saved).toBeUndefined() + }) + it('FE-MOB-RESSH-038: without upload permission the attachment block is gone', () => { setup(makePlanner({ canUploadFiles: false })) expect(screen.queryByRole('button', { name: 'files.attach' })).not.toBeInTheDocument() diff --git a/client/tests/unit/mobile/trip/MTransportFormSheet.test.tsx b/client/tests/unit/mobile/trip/MTransportFormSheet.test.tsx index 094b90ff4..42c974315 100644 --- a/client/tests/unit/mobile/trip/MTransportFormSheet.test.tsx +++ b/client/tests/unit/mobile/trip/MTransportFormSheet.test.tsx @@ -15,7 +15,7 @@ import { plannerSave } from '../../../helpers/bookingSave' import { resetAllStores, seedStore } from '../../../helpers/store' import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render' -// FE-MOB-TRFRM-001 to FE-MOB-TRFRM-060 +// FE-MOB-TRFRM-001 to FE-MOB-TRFRM-062 // // The sheet's own pickers (airport/location search, day select, time picker) and // the embedded transit panel are replaced by minimal controlled stand-ins so the @@ -1147,7 +1147,7 @@ describe('MTransportFormSheet', () => { expect((fd.get('file') as File).name).toBe('extra.pdf') }) - it('FE-MOB-TRFRM-060: a failed upload keeps the sheet and the file left, and the retry updates the same booking (#2883)', async () => { + it('FE-MOB-TRFRM-061: a failed upload keeps the sheet and the file left, and the retry updates the same booking (#2883)', async () => { const { save, failures } = plannerSave({ id: 99 }) const addFile = vi.fn(async (_tripId: number, _form: FormData) => undefined) .mockResolvedValueOnce(undefined) @@ -1171,6 +1171,24 @@ describe('MTransportFormSheet', () => { expect((addFile.mock.calls[2][1] as FormData).get('reservation_id')).toBe('99') }) + it('FE-MOB-TRFRM-062: the next transport of an import review is added, not written over the one saved before it', async () => { + // The review keeps the sheet open and only swaps the draft, so the open flag never changes. + const { save } = plannerSave({ id: 99 }) + const review = { importReviewActive: true, handleSaveTransport: save } + const first = makePlanner({ ...review, transportPrefill: { type: 'bus', title: 'Shuttle', metadata: {}, endpoints: [] } }) + const { rerender, onOpenExpense } = renderSheet(first) + await submit() + await waitFor(() => expect(first.advanceImportReview).toHaveBeenCalledTimes(1)) + + const second = makePlanner({ ...review, transportPrefill: { type: 'train', title: 'Amtrak', metadata: {}, endpoints: [] } }) + rerender() + expect(screen.getByPlaceholderText('reservations.titlePlaceholder')).toHaveValue('Amtrak') + await submit() + await waitFor(() => expect(second.advanceImportReview).toHaveBeenCalledTimes(1)) + expect(save).toHaveBeenCalledTimes(2) + expect(save.mock.calls[1][1]?.saved).toBeUndefined() + }) + it('FE-MOB-TRFRM-059: a failed transport edit keeps the attached files off the server', async () => { const handleSaveTransport = vi.fn(async (_payload: SavePayload) => undefined) const addFile = vi.fn(async (_tripId: number, _form: FormData) => undefined)