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.
This commit is contained in:
Maurice
2026-10-29 15:11:25 +01:00
parent 9ab2fc30ff
commit 00ac889139
8 changed files with 179 additions and 10 deletions
+1 -1
View File
@@ -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,
@@ -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<Props> = {}) {
pendingFiles: [],
fileInputRef: createRef<HTMLInputElement>(),
attach: {
uploadingFile: false,
handleFileChange: vi.fn(),
attachedFiles: [],
removePending: vi.fn(),
@@ -45,6 +44,7 @@ function setup(overrides: Partial<Props> = {}) {
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 }));
});
});
@@ -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<number>;
upload?: (fd: FormData) => Promise<unknown>;
}
let setTravelers: ReturnType<typeof vi.fn>;
function setup(initial: Props, files: File[] = []) {
return renderHook(
({ session, travelerIds = new Set([7]), upload }: Props) => {
const [pendingFiles, setPendingFiles] = useState<File[]>(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<typeof useBookingFollowUp> } }) {
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);
});
});
@@ -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 {
@@ -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'
@@ -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
@@ -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(<MReservationSheet planner={second} onOpenExpense={onOpenExpense} />)
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()
@@ -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(<MTransportFormSheet planner={second} onOpenExpense={onOpenExpense} />)
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)