mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
fix(bookings): keep the editor open until a booking's files are uploaded
Saving a booking or a transport closed the editor and reported success before the travellers and picked files were written. A failed upload left a booking without some of its PDFs, no list to retry from, and a create form that would add a duplicate when saved again. On desktop a file picked on an existing booking went up at once and vanished when that failed. The planner's save now takes the editor's follow-up as a step it waits for: it stores the booking, runs the traveller write and the uploads, and only then says so and closes. Each file that lands leaves the list, so a failure leaves exactly the files still to send, and the editor keeps the stored booking so the retry updates it instead of creating another one, without a second linked cost or stay. All four editors (desktop booking and transport dialogs, both phone sheets) share this through useBookingFollowUp, an import review only moves on once an item's files are up, and desktop files picked on a saved booking wait for Update like on the phone. Closes #2883
This commit is contained in:
@@ -23,6 +23,7 @@ export function BookingNotesFilesCosts({
|
||||
fileInputRef,
|
||||
attach,
|
||||
canAttach,
|
||||
saving,
|
||||
showCosts,
|
||||
pendingExpense,
|
||||
expense,
|
||||
@@ -38,6 +39,8 @@ export function BookingNotesFilesCosts({
|
||||
fileInputRef: RefObject<HTMLInputElement | null>;
|
||||
attach: ReturnType<typeof useBookingFileAttach>;
|
||||
canAttach: boolean;
|
||||
/** While the save runs the picked files are on their way, so no more can join them. */
|
||||
saving: boolean;
|
||||
showCosts: boolean;
|
||||
pendingExpense: { total_price: number; currency?: string | null; category: string } | null;
|
||||
expense: ReturnType<typeof useBookingExpenseIntent>;
|
||||
@@ -68,7 +71,7 @@ export function BookingNotesFilesCosts({
|
||||
fileInputRef={fileInputRef}
|
||||
onFileChange={attach.handleFileChange}
|
||||
canAttach={canAttach}
|
||||
uploading={attach.uploadingFile}
|
||||
uploading={saving}
|
||||
onLinked={attach.linkFile}
|
||||
onDetached={attach.detachFile}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-RESMODAL-001 to FE-PLANNER-RESMODAL-107
|
||||
// FE-PLANNER-RESMODAL-001 to FE-PLANNER-RESMODAL-109
|
||||
import { render, screen, waitFor, fireEvent, within, act } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -9,6 +9,8 @@ import { useAddonStore } from '../../store/addonStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { isBlurred } from '../../../tests/helpers/bookingCodeBlur';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { plannerSave } from '../../../tests/helpers/bookingSave';
|
||||
import { _resetNetworkMode, setForcedOffline } from '../../sync/networkMode';
|
||||
import {
|
||||
buildUser,
|
||||
buildTrip,
|
||||
@@ -259,7 +261,8 @@ describe('ReservationModal', () => {
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: 'Le Jules Verne', type: 'restaurant' })
|
||||
expect.objectContaining({ title: 'Le Jules Verne', type: 'restaurant' }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -280,7 +283,8 @@ describe('ReservationModal', () => {
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ status: 'confirmed' })
|
||||
expect.objectContaining({ status: 'confirmed' }),
|
||||
expect.anything(),
|
||||
);
|
||||
unmount();
|
||||
});
|
||||
@@ -392,7 +396,7 @@ describe('ReservationModal', () => {
|
||||
await userEvent.click(screen.getByRole('button', { name: /Create expense/i }));
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).not.toHaveBeenCalledWith(expect.objectContaining({ create_budget_entry: expect.anything() }));
|
||||
expect(onSave.mock.calls[0][0].create_budget_entry).toBeUndefined();
|
||||
await waitFor(() =>
|
||||
expect(onOpenExpense).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ prefill: expect.objectContaining({ reservationId: 55 }) })
|
||||
@@ -452,7 +456,8 @@ describe('ReservationModal', () => {
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: 'Grand Hotel', type: 'hotel' })
|
||||
expect.objectContaining({ title: 'Grand Hotel', type: 'hotel' }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -466,7 +471,8 @@ describe('ReservationModal', () => {
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: 'Louvre Museum', type: 'event' })
|
||||
expect.objectContaining({ title: 'Louvre Museum', type: 'event' }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -480,7 +486,8 @@ describe('ReservationModal', () => {
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: 'Airport Parking P1', type: 'parking' })
|
||||
expect.objectContaining({ title: 'Airport Parking P1', type: 'parking' }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -502,13 +509,15 @@ describe('ReservationModal', () => {
|
||||
expect(screen.getByPlaceholderText(/e\.g\. ABC12345/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESMODAL-036: file upload to existing reservation calls onFileUpload', async () => {
|
||||
it('FE-PLANNER-RESMODAL-036: a file picked on an existing reservation waits in the list and goes up on Update', async () => {
|
||||
const onFileUpload = vi.fn().mockResolvedValue(undefined);
|
||||
const res = buildReservation({ id: 10, title: 'My Trip', type: 'other' });
|
||||
const { save: onSave } = plannerSave(res);
|
||||
render(
|
||||
<ReservationModal
|
||||
{...defaultProps}
|
||||
reservation={res}
|
||||
onSave={onSave}
|
||||
onFileUpload={onFileUpload}
|
||||
/>
|
||||
);
|
||||
@@ -516,7 +525,10 @@ describe('ReservationModal', () => {
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const testFile = new File(['content'], 'boarding-pass.pdf', { type: 'application/pdf' });
|
||||
fireEvent.change(fileInput, { target: { files: [testFile] } });
|
||||
expect(screen.getByText('boarding-pass.pdf')).toBeInTheDocument();
|
||||
expect(onFileUpload).not.toHaveBeenCalled();
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
await waitFor(() => expect(onFileUpload).toHaveBeenCalled());
|
||||
const [fd] = onFileUpload.mock.calls[0] as [FormData];
|
||||
expect(fd.get('file')).toBeTruthy();
|
||||
@@ -646,7 +658,8 @@ describe('ReservationModal', () => {
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ title: 'Grand Hotel', type: 'hotel' })
|
||||
expect.objectContaining({ title: 'Grand Hotel', type: 'hotel' }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -707,7 +720,7 @@ describe('ReservationModal', () => {
|
||||
await pickType(/^Other$/i);
|
||||
await userEvent.type(screen.getByPlaceholderText(/e\.g\. Lufthansa/i), 'Misc item');
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ type: 'other' })));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ type: 'other' }), expect.anything()));
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESMODAL-048: clicking attach file button triggers file input', async () => {
|
||||
@@ -774,7 +787,8 @@ describe('ReservationModal', () => {
|
||||
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ type: 'hotel' })
|
||||
expect.objectContaining({ type: 'hotel' }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1064,7 +1078,7 @@ describe('ReservationModal', () => {
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESMODAL-062: the parsed source document is seeded as a pending file and uploaded after save', async () => {
|
||||
const onSave = vi.fn().mockResolvedValue({ id: 81 });
|
||||
const { save: onSave } = plannerSave({ id: 81 });
|
||||
const onFileUpload = vi.fn().mockResolvedValue(undefined);
|
||||
const sourceFile = new File(['x'], 'booking.pdf', { type: 'application/pdf' });
|
||||
const prefill = hotelPrefill({ _sourceFiles: [sourceFile] });
|
||||
@@ -1241,6 +1255,7 @@ describe('ReservationModal', () => {
|
||||
notes: 'Bring sunscreen',
|
||||
url: 'https://boats.example',
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1252,7 +1267,7 @@ describe('ReservationModal', () => {
|
||||
];
|
||||
|
||||
it('FE-PLANNER-RESMODAL-072: toggling travelers persists them once the booking has an id', async () => {
|
||||
const onSave = vi.fn().mockResolvedValue({ id: 90 });
|
||||
const { save: onSave } = plannerSave({ id: 90 });
|
||||
let body: { user_ids: number[] } | null = null;
|
||||
server.use(
|
||||
http.put('/api/trips/1/reservations/90/travelers', async ({ request }) => {
|
||||
@@ -1292,10 +1307,8 @@ describe('ReservationModal', () => {
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESMODAL-074: a failing traveler write surfaces an error toast', async () => {
|
||||
const addToast = vi.fn();
|
||||
window.__addToast = addToast;
|
||||
const onSave = vi.fn().mockResolvedValue({ id: 92 });
|
||||
it('FE-PLANNER-RESMODAL-074: a failing traveler write fails the save, so the planner keeps the dialog open', async () => {
|
||||
const { save: onSave, failures } = plannerSave({ id: 92 });
|
||||
server.use(
|
||||
http.put('/api/trips/1/reservations/92/travelers', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
@@ -1305,8 +1318,8 @@ describe('ReservationModal', () => {
|
||||
await userEvent.click(within(await openTravelers()).getByText('alice'));
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith(expect.any(String), 'error', undefined));
|
||||
delete window.__addToast;
|
||||
await waitFor(() => expect(failures).toHaveLength(1));
|
||||
expect(screen.getByRole('button', { name: /^Add$/i })).toBeEnabled();
|
||||
});
|
||||
|
||||
// ── Linked cost actions ─────────────────────────────────────────────────────
|
||||
@@ -1466,18 +1479,70 @@ describe('ReservationModal', () => {
|
||||
expect(screen.getByRole('button', { name: /Attach file/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESMODAL-078: a failing upload to an existing booking shows the upload error', async () => {
|
||||
const addToast = vi.fn();
|
||||
window.__addToast = addToast;
|
||||
it('FE-PLANNER-RESMODAL-078: a failing upload on Update keeps the file listed and says the booking is saved', async () => {
|
||||
const onFileUpload = vi.fn().mockRejectedValue(new Error('disk full'));
|
||||
const res = buildReservation({ id: 12, title: 'My Trip', type: 'other' });
|
||||
const { save: onSave, failures } = plannerSave(res);
|
||||
|
||||
render(<ReservationModal {...defaultProps} reservation={res} onFileUpload={onFileUpload} />);
|
||||
render(<ReservationModal {...defaultProps} reservation={res} onSave={onSave} onFileUpload={onFileUpload} />);
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(fileInput, { target: { files: [new File(['x'], 'fail.pdf', { type: 'application/pdf' })] } });
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to upload', 'error', undefined));
|
||||
delete window.__addToast;
|
||||
await waitFor(() => expect(failures).toHaveLength(1));
|
||||
expect(failures[0].message).toBe('The booking is saved, but some files did not upload. Save again to send them.');
|
||||
expect(screen.getByText('fail.pdf')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESMODAL-108: a new booking whose second file fails retries as an update with only that file (#2883)', async () => {
|
||||
const onFileUpload = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockRejectedValueOnce(new Error('413'))
|
||||
.mockResolvedValue(undefined);
|
||||
const { save: onSave, failures } = plannerSave({ id: 95 });
|
||||
|
||||
render(<ReservationModal {...defaultProps} onSave={onSave} onFileUpload={onFileUpload} />);
|
||||
await userEvent.type(screen.getByPlaceholderText(/e\.g\. Lufthansa/i), 'Ferry');
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(fileInput, { target: { files: [new File(['a'], 'ok.pdf', { type: 'application/pdf' })] } });
|
||||
fireEvent.change(fileInput, { target: { files: [new File(['b'], 'fail.pdf', { type: 'application/pdf' })] } });
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(failures).toHaveLength(1));
|
||||
expect(onSave.mock.calls[0][1]?.saved).toBeUndefined();
|
||||
expect(screen.queryByText('ok.pdf')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('fail.pdf')).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(onFileUpload).toHaveBeenCalledTimes(3));
|
||||
expect(onSave).toHaveBeenCalledTimes(2);
|
||||
expect(onSave.mock.calls[1][1]?.saved).toEqual({ id: 95 });
|
||||
const [fd] = onFileUpload.mock.calls[2] as [FormData];
|
||||
expect((fd.get('file') as File).name).toBe('fail.pdf');
|
||||
expect(fd.get('reservation_id')).toBe('95');
|
||||
expect(failures).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESMODAL-109: offline a file picked on an existing booking holds the save back (#2601)', async () => {
|
||||
const addToast = vi.fn();
|
||||
window.__addToast = addToast;
|
||||
const onSave = vi.fn().mockResolvedValue(undefined);
|
||||
const res = buildReservation({ id: 14, title: 'My Trip', type: 'other' });
|
||||
render(<ReservationModal {...defaultProps} reservation={res} onSave={onSave} />);
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(fileInput, { target: { files: [new File(['x'], 'ticket.pdf', { type: 'application/pdf' })] } });
|
||||
|
||||
setForcedOffline(true);
|
||||
try {
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith(expect.stringMatching(/need a connection/), 'error', undefined));
|
||||
} finally {
|
||||
_resetNetworkMode();
|
||||
delete window.__addToast;
|
||||
}
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
expect(screen.getByText('ticket.pdf')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-RESMODAL-079: a failing unlink reports the update error but still drops the row', async () => {
|
||||
@@ -1642,6 +1707,7 @@ describe('ReservationModal', () => {
|
||||
// carries a clock, and a bare date is what makes it an all-day event.
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ reservation_time: '2026-05-02', reservation_end_time: '2026-05-02' }),
|
||||
expect.anything(),
|
||||
));
|
||||
});
|
||||
|
||||
|
||||
@@ -26,9 +26,10 @@ 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, filesNeedConnection, uploadBookingFiles } from './bookingFormModel'
|
||||
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, filesNeedConnection, type BookingSaveSteps } from './bookingFormModel'
|
||||
import { useBookingExpenseIntent } from './useBookingExpenseIntent'
|
||||
import { useBookingFileAttach } from './useBookingFileAttach'
|
||||
import { useBookingFollowUp } from './useBookingFollowUp'
|
||||
import StayPinStatus from './StayPinStatus'
|
||||
|
||||
const EMPTY_FORM = {
|
||||
@@ -44,7 +45,7 @@ const EMPTY_FORM = {
|
||||
interface ReservationModalProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onSave: (data: Record<string, string | number | null> & { title: string }) => Promise<Reservation | undefined>
|
||||
onSave: (data: Record<string, string | number | null> & { title: string }, steps?: BookingSaveSteps) => Promise<Reservation | undefined>
|
||||
reservation: Reservation | null
|
||||
days: Day[]
|
||||
places: Place[]
|
||||
@@ -65,7 +66,6 @@ interface ReservationModalProps {
|
||||
|
||||
export function ReservationModal({ isOpen, onClose, onSave, reservation, days, places, assignments, selectedDayId, files = [], onFileUpload, onFileDelete, accommodations = [], defaultAssignmentId = null, onOpenExpense, prefill = null, tripMembers = [] }: ReservationModalProps) {
|
||||
const { id: tripId } = useParams<{ id: string }>()
|
||||
const setReservationTravelers = useTripStore(s => s.setReservationTravelers)
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
const fileInputRef = useRef(null)
|
||||
@@ -84,7 +84,11 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
||||
isEndBeforeStart, endTimeBeforeStartTime, dateBounds: tripDateRange, startDate, startTime, setStartDate, setStartTime, takeStopDay,
|
||||
pickPlace, pickHotelPlace, pickHotelStart, pickHotelEnd, stayPin, saveData: buildSaveData,
|
||||
} = useReservationForm(EMPTY_FORM, days, places)
|
||||
const attach = useBookingFileAttach({ reservation, files, onFileUpload, setPendingFiles, toast, t })
|
||||
const attach = useBookingFileAttach({ reservation, files, setPendingFiles })
|
||||
const followUp = useBookingFollowUp({
|
||||
session: isOpen ? (reservation ?? prefill ?? 'new') : null,
|
||||
tripId, original: reservation, travelerIds, pendingFiles, setPendingFiles, upload: onFileUpload, t,
|
||||
})
|
||||
|
||||
const assignmentOptions = useMemo(
|
||||
() => buildAssignmentOptions(days, assignments, t, locale),
|
||||
@@ -92,6 +96,9 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
// A try that stored the booking and failed on its files keeps the form as the
|
||||
// user left it; the places and stays that save refreshed must not reseed it.
|
||||
if (followUp.holdsSaved()) return
|
||||
// Match an existing place by name (exact, then loose contains) for hotels.
|
||||
const matchPlaceId = (name: string | undefined): string | number => {
|
||||
const n = (name || '').trim().toLowerCase()
|
||||
@@ -142,19 +149,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
||||
const entry = importedPriceEntry(prefill.metadata, form.type)
|
||||
if (entry) saveData.create_budget_entry = entry
|
||||
}
|
||||
const saved = await onSave(saveData as Record<string, string | number | null> & { title: string })
|
||||
// Persist the traveler assignment once we have the reservation id (create → save
|
||||
// result, edit → existing reservation), and only when it actually changed (#1517).
|
||||
const savedId = saved?.id ?? reservation?.id
|
||||
if (savedId && tripId) {
|
||||
const { changed, nextIds } = travelersChanged(reservation, travelerIds)
|
||||
if (changed) {
|
||||
try { await setReservationTravelers(tripId, savedId, nextIds) } catch { toast.error(t('common.unknownError')) }
|
||||
}
|
||||
}
|
||||
if (!reservation?.id && saved?.id && pendingFiles.length > 0) {
|
||||
await uploadBookingFiles(onFileUpload, saved.id, pendingFiles, form.title)
|
||||
}
|
||||
const saved = await onSave(saveData as Record<string, string | number | null> & { title: string }, followUp.steps(form.title))
|
||||
// Open the Costs editor for the saved booking when the user asked to
|
||||
// create/edit its linked expense (gated on saved?.id).
|
||||
const expenseRequest = expenseRequestAfterSave(expense.take(), saved, form, days)
|
||||
@@ -401,6 +396,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
|
||||
fileInputRef={fileInputRef}
|
||||
attach={attach}
|
||||
canAttach={!!onFileUpload}
|
||||
saving={isSaving}
|
||||
showCosts={isBudgetEnabled}
|
||||
pendingExpense={pendingExpense}
|
||||
expense={expense}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-TRANSMODAL-001 to FE-PLANNER-TRANSMODAL-082
|
||||
// FE-PLANNER-TRANSMODAL-001 to FE-PLANNER-TRANSMODAL-083
|
||||
import { render, screen, waitFor, fireEvent, within, act } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -9,6 +9,7 @@ import { useAddonStore } from '../../store/addonStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { isBlurred } from '../../../tests/helpers/bookingCodeBlur';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { plannerSave } from '../../../tests/helpers/bookingSave';
|
||||
import {
|
||||
buildUser,
|
||||
buildTrip,
|
||||
@@ -189,7 +190,7 @@ describe('TransportModal', () => {
|
||||
await userEvent.type(screen.getByPlaceholderText(/e\.g\. Lufthansa/i), 'LH456');
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ title: 'LH456', type: 'flight' }));
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ title: 'LH456', type: 'flight' }), expect.anything());
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-010: switching to train type calls onSave with train type', async () => {
|
||||
@@ -199,7 +200,7 @@ describe('TransportModal', () => {
|
||||
await userEvent.type(screen.getByPlaceholderText(/e\.g\. Lufthansa/i), 'Eurostar');
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ type: 'train' }));
|
||||
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ type: 'train' }), expect.anything());
|
||||
});
|
||||
|
||||
// ── Budget addon ─────────────────────────────────────────────────────────────
|
||||
@@ -230,7 +231,7 @@ describe('TransportModal', () => {
|
||||
await userEvent.click(screen.getByRole('button', { name: /Create expense/i }));
|
||||
await waitFor(() => expect(onSave).toHaveBeenCalled());
|
||||
// The legacy auto-budget mechanism is gone; the expense is created via the editor instead.
|
||||
expect(onSave).not.toHaveBeenCalledWith(expect.objectContaining({ create_budget_entry: expect.anything() }));
|
||||
expect(onSave.mock.calls[0][0].create_budget_entry).toBeUndefined();
|
||||
await waitFor(() =>
|
||||
expect(onOpenExpense).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ prefill: expect.objectContaining({ reservationId: 42 }) })
|
||||
@@ -269,16 +270,20 @@ describe('TransportModal', () => {
|
||||
await waitFor(() => expect(screen.getByText('itinerary.pdf')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-018: file upload to existing transport calls onFileUpload with correct FormData', async () => {
|
||||
it('FE-PLANNER-TRANSMODAL-018: a file picked on an existing transport waits and goes up on Update with correct FormData', async () => {
|
||||
const onFileUpload = vi.fn().mockResolvedValue(undefined);
|
||||
const res = buildReservation({ id: 10, type: 'train', title: 'Eurostar' });
|
||||
const { save: onSave } = plannerSave(res);
|
||||
|
||||
render(<TransportModal {...defaultProps} reservation={res} onFileUpload={onFileUpload} />);
|
||||
render(<TransportModal {...defaultProps} reservation={res} onSave={onSave} onFileUpload={onFileUpload} />);
|
||||
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
const testFile = new File(['content'], 'ticket.pdf', { type: 'application/pdf' });
|
||||
fireEvent.change(fileInput, { target: { files: [testFile] } });
|
||||
expect(screen.getByText('ticket.pdf')).toBeInTheDocument();
|
||||
expect(onFileUpload).not.toHaveBeenCalled();
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
await waitFor(() => expect(onFileUpload).toHaveBeenCalled());
|
||||
const [fd] = onFileUpload.mock.calls[0] as [FormData];
|
||||
expect(fd.get('file')).toBeTruthy();
|
||||
@@ -407,8 +412,7 @@ describe('TransportModal', () => {
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-025: pending files flushed after saving new transport', async () => {
|
||||
const savedReservation = buildReservation({ id: 99, type: 'flight' });
|
||||
const onSave = vi.fn().mockResolvedValue(savedReservation);
|
||||
const { save: onSave } = plannerSave(buildReservation({ id: 99, type: 'flight' }));
|
||||
const onFileUpload = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
render(<TransportModal {...defaultProps} onSave={onSave} onFileUpload={onFileUpload} reservation={null} />);
|
||||
@@ -1078,7 +1082,7 @@ describe('TransportModal', () => {
|
||||
];
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-044: assigned travelers are written back after the save resolves', async () => {
|
||||
const onSave = vi.fn().mockResolvedValue({ id: 60 });
|
||||
const { save: onSave } = plannerSave({ id: 60 });
|
||||
let body: { user_ids: number[] } | null = null;
|
||||
server.use(
|
||||
http.put('/api/trips/1/reservations/60/travelers', async ({ request }) => {
|
||||
@@ -1096,10 +1100,8 @@ describe('TransportModal', () => {
|
||||
expect(body!.user_ids).toEqual([2]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-045: a failing traveler write surfaces an error toast', async () => {
|
||||
const addToast = vi.fn();
|
||||
window.__addToast = addToast;
|
||||
const onSave = vi.fn().mockResolvedValue({ id: 61 });
|
||||
it('FE-PLANNER-TRANSMODAL-045: a failing traveler write fails the save, so the planner keeps the dialog open', async () => {
|
||||
const { save: onSave, failures } = plannerSave({ id: 61 });
|
||||
server.use(
|
||||
http.put('/api/trips/1/reservations/61/travelers', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
|
||||
);
|
||||
@@ -1109,8 +1111,37 @@ describe('TransportModal', () => {
|
||||
await userEvent.click(within(await openTravelers()).getByText('alice'));
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith(expect.any(String), 'error', undefined));
|
||||
delete window.__addToast;
|
||||
await waitFor(() => expect(failures).toHaveLength(1));
|
||||
expect(screen.getByRole('button', { name: /^Add$/i })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-083: a new transport whose upload fails retries as an update with only that file (#2883)', async () => {
|
||||
const onFileUpload = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockRejectedValueOnce(new Error('413'))
|
||||
.mockResolvedValue(undefined);
|
||||
const { save: onSave, failures } = plannerSave({ id: 64 });
|
||||
|
||||
render(<TransportModal {...defaultProps} onSave={onSave} onFileUpload={onFileUpload} />);
|
||||
await userEvent.type(screen.getByPlaceholderText(/e\.g\. Lufthansa/i), 'LH 400');
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(fileInput, { target: { files: [new File(['a'], 'ok.pdf', { type: 'application/pdf' })] } });
|
||||
fireEvent.change(fileInput, { target: { files: [new File(['b'], 'fail.pdf', { type: 'application/pdf' })] } });
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(failures).toHaveLength(1));
|
||||
expect(screen.queryByText('ok.pdf')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('fail.pdf')).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
|
||||
await waitFor(() => expect(onFileUpload).toHaveBeenCalledTimes(3));
|
||||
expect(onSave.mock.calls[0][1]?.saved).toBeUndefined();
|
||||
expect(onSave.mock.calls[1][1]?.saved).toEqual({ id: 64 });
|
||||
const [fd] = onFileUpload.mock.calls[2] as [FormData];
|
||||
expect((fd.get('file') as File).name).toBe('fail.pdf');
|
||||
expect(fd.get('reservation_id')).toBe('64');
|
||||
expect(failures).toHaveLength(1);
|
||||
});
|
||||
|
||||
// ── Linked cost actions ─────────────────────────────────────────────────────
|
||||
@@ -1192,18 +1223,19 @@ describe('TransportModal', () => {
|
||||
expect(screen.getByRole('button', { name: /Attach file/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-050: a failing upload to an existing booking shows the upload error', async () => {
|
||||
const addToast = vi.fn();
|
||||
window.__addToast = addToast;
|
||||
it('FE-PLANNER-TRANSMODAL-050: a failing upload on Update keeps the file listed and says the booking is saved', async () => {
|
||||
const onFileUpload = vi.fn().mockRejectedValue(new Error('disk full'));
|
||||
const res = buildReservation({ id: 20, type: 'train', title: 'Eurostar' });
|
||||
const { save: onSave, failures } = plannerSave(res);
|
||||
|
||||
render(<TransportModal {...defaultProps} reservation={res} onFileUpload={onFileUpload} />);
|
||||
render(<TransportModal {...defaultProps} reservation={res} onSave={onSave} onFileUpload={onFileUpload} />);
|
||||
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
|
||||
fireEvent.change(fileInput, { target: { files: [new File(['x'], 'fail.pdf', { type: 'application/pdf' })] } });
|
||||
await userEvent.click(screen.getByRole('button', { name: /^Update$/i }));
|
||||
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Failed to upload', 'error', undefined));
|
||||
delete window.__addToast;
|
||||
await waitFor(() => expect(failures).toHaveLength(1));
|
||||
expect(failures[0].message).toBe('The booking is saved, but some files did not upload. Save again to send them.');
|
||||
expect(screen.getByText('fail.pdf')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-051: a failing unlink reports the update error', async () => {
|
||||
@@ -1271,7 +1303,7 @@ describe('TransportModal', () => {
|
||||
});
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-055: an existing traveler list is toggled off and written back empty', async () => {
|
||||
const onSave = vi.fn().mockResolvedValue({ id: 63 });
|
||||
const { save: onSave } = plannerSave({ id: 63 });
|
||||
let body: { user_ids: number[] } | null = null;
|
||||
server.use(
|
||||
http.put('/api/trips/1/reservations/63/travelers', async ({ request }) => {
|
||||
|
||||
@@ -31,9 +31,10 @@ import {
|
||||
transportDayOptions, type StationWaypointForm, type WaypointForm,
|
||||
} from './transportEndpoints'
|
||||
import { useTransportForm } from './useTransportForm'
|
||||
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, travelersChanged, filesNeedConnection, uploadBookingFiles } from './bookingFormModel'
|
||||
import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, filesNeedConnection, type BookingSaveSteps } from './bookingFormModel'
|
||||
import { useBookingExpenseIntent } from './useBookingExpenseIntent'
|
||||
import { useBookingFileAttach } from './useBookingFileAttach'
|
||||
import { useBookingFollowUp } from './useBookingFollowUp'
|
||||
|
||||
const defaultForm = {
|
||||
...EMPTY_TRANSPORT_FIELDS,
|
||||
@@ -48,7 +49,7 @@ const defaultForm = {
|
||||
interface TransportModalProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onSave: (data: Record<string, any> & { title: string }) => Promise<Reservation | undefined>
|
||||
onSave: (data: Record<string, any> & { title: string }, steps?: BookingSaveSteps) => Promise<Reservation | undefined>
|
||||
reservation: Reservation | null
|
||||
days: Day[]
|
||||
selectedDayId: number | null
|
||||
@@ -84,7 +85,6 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
|
||||
const budgetItems = useTripStore(s => s.budgetItems)
|
||||
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
|
||||
const setReservationTravelers = useTripStore(s => s.setReservationTravelers)
|
||||
const { id: tripId } = useParams<{ id: string }>()
|
||||
// Set right before submitting when the user clicked "create/edit expense", so
|
||||
// the post-save handler knows to open the Costs editor for the saved booking.
|
||||
@@ -99,11 +99,17 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
seed, payload, writesFlightLegs, writesTrainLegs,
|
||||
} = useTransportForm(defaultForm)
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
||||
const attach = useBookingFileAttach({ reservation, files, onFileUpload, setPendingFiles, toast, t })
|
||||
const attach = useBookingFileAttach({ reservation, files, setPendingFiles })
|
||||
const followUp = useBookingFollowUp({
|
||||
session: isOpen ? (reservation ?? prefill ?? 'new') : null,
|
||||
tripId, original: reservation, travelerIds, pendingFiles, setPendingFiles, upload: onFileUpload, t,
|
||||
})
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
// A try that stored the booking and failed on its files keeps the form as the
|
||||
// user left it; the costs that save reloaded must not reseed it.
|
||||
if (!isOpen || followUp.holdsSaved()) return
|
||||
setTravelerIds(travelerIdsOf(reservation))
|
||||
// Edit uses the saved `reservation`; a review-import populates from `prefill`.
|
||||
// Either way the init reads the same fields — `reservation` still decides
|
||||
@@ -143,19 +149,7 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
try {
|
||||
const saved = await onSave(payload(days, {
|
||||
reservation, prefill, budgetEnabled: isBudgetEnabled, anchorOnStations: false, url: form.url,
|
||||
}))
|
||||
// Persist the traveler assignment once we have the reservation id (create → save
|
||||
// result, edit → existing reservation), and only when it actually changed (#1517).
|
||||
const savedId = saved?.id ?? reservation?.id
|
||||
if (savedId && tripId) {
|
||||
const { changed, nextIds } = travelersChanged(reservation, travelerIds)
|
||||
if (changed) {
|
||||
try { await setReservationTravelers(tripId, savedId, nextIds) } catch { toast.error(t('common.unknownError')) }
|
||||
}
|
||||
}
|
||||
if (!reservation?.id && saved?.id && pendingFiles.length > 0 && onFileUpload) {
|
||||
await uploadBookingFiles(onFileUpload, saved.id, pendingFiles, form.title)
|
||||
}
|
||||
}), followUp.steps(form.title))
|
||||
// The user asked to create/edit the linked expense — open the Costs editor
|
||||
// for the now-saved booking. Gated on saved?.id so a failed save doesn't.
|
||||
const expenseRequest = expenseRequestAfterSave(expense.take(), saved, form, days)
|
||||
@@ -556,6 +550,7 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
fileInputRef={fileInputRef}
|
||||
attach={attach}
|
||||
canAttach={!!onFileUpload}
|
||||
saving={isSaving}
|
||||
showCosts={isBudgetEnabled}
|
||||
pendingExpense={pendingExpense}
|
||||
expense={expense}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PLANNER-BOOKINGFORM-001 to -010: the travellers, picked files, attached files
|
||||
// FE-PLANNER-BOOKINGFORM-001 to -012: 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';
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
expenseRequestAfterSave,
|
||||
filesNeedConnection,
|
||||
pendingImportExpense,
|
||||
retriedSave,
|
||||
toggledTraveler,
|
||||
travelerIdsOf,
|
||||
travelersChanged,
|
||||
@@ -62,6 +63,40 @@ describe('bookingFormModel', () => {
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BOOKINGFORM-011: each landed file is reported, and the first failure stops the rest (#2883)', async () => {
|
||||
const files = [new File(['a'], 'a.pdf'), new File(['b'], 'fail.pdf'), new File(['c'], 'c.pdf')];
|
||||
const upload = vi.fn(async (fd: FormData) => {
|
||||
if ((fd.get('file') as File).name === 'fail.pdf') throw new Error('413');
|
||||
});
|
||||
const onUploaded = vi.fn();
|
||||
await expect(uploadBookingFiles(upload, 42, files, 'Hotel stay', onUploaded)).rejects.toThrow('413');
|
||||
expect(onUploaded.mock.calls).toEqual([[files[0]]]);
|
||||
expect(upload).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BOOKINGFORM-012: a retried save creates no second cost and keeps the stay it already made', () => {
|
||||
const stored = buildReservation({ id: 6, accommodation_id: 31 } as Partial<Reservation>);
|
||||
expect(
|
||||
retriedSave(
|
||||
{ title: 'Ryokan', type: 'hotel', accommodation_id: null, create_budget_entry: { total_price: 90 } },
|
||||
stored
|
||||
)
|
||||
).toEqual({
|
||||
title: 'Ryokan',
|
||||
type: 'hotel',
|
||||
accommodation_id: 31,
|
||||
});
|
||||
expect(retriedSave({ title: 'Ryokan', type: 'hotel', accommodation_id: 12 }, stored)).toEqual({
|
||||
title: 'Ryokan',
|
||||
type: 'hotel',
|
||||
accommodation_id: 12,
|
||||
});
|
||||
expect(retriedSave({ title: 'ICE', type: 'train', create_budget_entry: true }, stored)).toEqual({
|
||||
title: 'ICE',
|
||||
type: 'train',
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BOOKINGFORM-008: without an upload handler the picked files are skipped and the save is not rejected', async () => {
|
||||
await expect(uploadBookingFiles(undefined, 42, [new File(['a'], 'a.pdf')], 'Hotel stay')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -37,12 +37,17 @@ export function travelersChanged(reservation: Pick<Reservation, 'travelers'> | n
|
||||
* uploaded twice, and skipping the edit dropped them without a word (#2534).
|
||||
* Without an upload handler (a dialog opened with no file support) there is
|
||||
* nowhere to send them, so nothing is uploaded and the save carries on.
|
||||
*
|
||||
* Each file that lands is reported before the next one starts, and the first one
|
||||
* that fails stops the rest, so the form can keep exactly the files still to send
|
||||
* and a second save picks up where this one stopped (#2883).
|
||||
*/
|
||||
export async function uploadBookingFiles(
|
||||
upload: ((fd: FormData) => Promise<unknown>) | undefined,
|
||||
savedId: number,
|
||||
files: File[],
|
||||
description: string
|
||||
description: string,
|
||||
onUploaded?: (file: File) => void
|
||||
): Promise<void> {
|
||||
if (!upload) return;
|
||||
for (const file of files) {
|
||||
@@ -51,9 +56,39 @@ export async function uploadBookingFiles(
|
||||
fd.append('reservation_id', String(savedId));
|
||||
fd.append('description', description);
|
||||
await upload(fd);
|
||||
onUploaded?.(file);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How a booking editor hands its save to the planner. The planner stores the
|
||||
* booking, waits for `afterSave` (the travellers and files that hang on it) and
|
||||
* only then reports success and closes the editor. When that part fails the
|
||||
* editor stays open with the booking stored, and passes it back as `saved` on
|
||||
* the next try, so the retry updates it instead of creating a second one.
|
||||
*/
|
||||
export interface BookingSaveSteps {
|
||||
saved?: Reservation;
|
||||
afterSave?: (saved: Reservation) => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The update a retry sends for a booking the first try already created: the cost
|
||||
* that try linked is not created again, and a hotel keeps the stay it was given
|
||||
* rather than gaining a second one beside it.
|
||||
*/
|
||||
export function retriedSave<T extends Record<string, unknown>>(
|
||||
data: T,
|
||||
stored: Pick<Reservation, 'accommodation_id'>
|
||||
): T {
|
||||
const { create_budget_entry: _linkedCost, ...rest } = data;
|
||||
const update = rest as Record<string, unknown>;
|
||||
if (update.type === 'hotel' && !update.accommodation_id && stored.accommodation_id) {
|
||||
update.accommodation_id = stored.accommodation_id;
|
||||
}
|
||||
return update as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
// FE-PLANNER-BOOKINGFILES-001 to -006: the Files row of the desktop booking and
|
||||
// FE-PLANNER-BOOKINGFILES-001 to -005: the Files row of the desktop booking and
|
||||
// transport dialogs.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import type React from 'react';
|
||||
import { useState } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { describe, expect, it } 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';
|
||||
|
||||
@@ -18,69 +17,36 @@ function changeEvent(file?: File): FileEvent {
|
||||
}
|
||||
|
||||
function setup(overrides: Partial<BookingFileAttachOptions> = {}, files: TripFile[] = []) {
|
||||
const toast = { success: vi.fn(), error: vi.fn() };
|
||||
const t = (key: string) => key;
|
||||
const view = renderHook(() => {
|
||||
return renderHook(() => {
|
||||
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
|
||||
const attach = useBookingFileAttach({
|
||||
reservation: { id: 5, title: 'Hotel' },
|
||||
files,
|
||||
setPendingFiles,
|
||||
toast,
|
||||
t,
|
||||
...overrides,
|
||||
});
|
||||
const attach = useBookingFileAttach({ reservation: { id: 5 }, files, setPendingFiles, ...overrides });
|
||||
return { attach, pendingFiles };
|
||||
});
|
||||
return { ...view, toast };
|
||||
}
|
||||
|
||||
describe('useBookingFileAttach', () => {
|
||||
it('FE-PLANNER-BOOKINGFILES-001: a file on a saved booking goes up at once and the input clears', async () => {
|
||||
const onFileUpload = vi.fn(async (_fd: FormData) => undefined);
|
||||
const { result, toast } = setup({ onFileUpload });
|
||||
const e = changeEvent(new File(['a'], 'a.pdf'));
|
||||
await act(() => result.current.attach.handleFileChange(e));
|
||||
const fd = onFileUpload.mock.calls[0][0];
|
||||
expect(fd.get('reservation_id')).toBe('5');
|
||||
expect(fd.get('description')).toBe('Hotel');
|
||||
expect(toast.success).toHaveBeenCalledWith('reservations.toast.fileUploaded');
|
||||
it('FE-PLANNER-BOOKINGFILES-001: a file picked on a saved booking waits for the save like on a new one (#2883)', () => {
|
||||
const { result } = setup();
|
||||
const a = new File(['a'], 'a.pdf');
|
||||
const e = changeEvent(a);
|
||||
act(() => result.current.attach.handleFileChange(e));
|
||||
expect(result.current.pendingFiles).toEqual([a]);
|
||||
expect(e.target.value).toBe('');
|
||||
expect(result.current.attach.uploadingFile).toBe(false);
|
||||
expect(result.current.pendingFiles).toEqual([]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BOOKINGFILES-002: a failed upload, or a dialog without one, says so', async () => {
|
||||
const onFileUpload = vi.fn(async () => {
|
||||
throw new Error('boom');
|
||||
});
|
||||
const failing = setup({ onFileUpload });
|
||||
await act(() => failing.result.current.attach.handleFileChange(changeEvent(new File(['a'], 'a.pdf'))));
|
||||
expect(failing.toast.error).toHaveBeenCalledWith('reservations.toast.uploadError');
|
||||
|
||||
const without = setup({ onFileUpload: undefined });
|
||||
await act(() => without.result.current.attach.handleFileChange(changeEvent(new File(['a'], 'a.pdf'))));
|
||||
expect(without.toast.error).toHaveBeenCalledWith('reservations.toast.uploadError');
|
||||
expect(without.toast.success).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BOOKINGFILES-003: on a new booking the file waits for the save and can be taken back', async () => {
|
||||
const onFileUpload = vi.fn(async () => undefined);
|
||||
const { result } = setup({ reservation: null, onFileUpload });
|
||||
it('FE-PLANNER-BOOKINGFILES-002: on a new booking the files gather and can be taken back', () => {
|
||||
const { result } = setup({ reservation: null });
|
||||
const a = new File(['a'], 'a.pdf');
|
||||
const b = new File(['b'], 'b.pdf');
|
||||
const e = changeEvent(a);
|
||||
await act(() => result.current.attach.handleFileChange(e));
|
||||
await act(() => result.current.attach.handleFileChange(changeEvent(b)));
|
||||
await act(() => result.current.attach.handleFileChange(changeEvent()));
|
||||
expect(onFileUpload).not.toHaveBeenCalled();
|
||||
expect(e.target.value).toBe('');
|
||||
act(() => result.current.attach.handleFileChange(changeEvent(a)));
|
||||
act(() => result.current.attach.handleFileChange(changeEvent(b)));
|
||||
act(() => result.current.attach.handleFileChange(changeEvent()));
|
||||
expect(result.current.pendingFiles).toEqual([a, b]);
|
||||
act(() => result.current.attach.removePending(0));
|
||||
expect(result.current.pendingFiles).toEqual([b]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BOOKINGFILES-004: files linked and detached in the dialog show on the booking', () => {
|
||||
it('FE-PLANNER-BOOKINGFILES-003: files linked and detached in the dialog show on the booking', () => {
|
||||
const files = [buildTripFile({ id: 1, reservation_id: 5 }), buildTripFile({ id: 2, reservation_id: null })];
|
||||
const { result } = setup({}, files);
|
||||
expect(result.current.attach.attachedFiles.map((f) => f.id)).toEqual([1]);
|
||||
@@ -90,25 +56,8 @@ describe('useBookingFileAttach', () => {
|
||||
expect(result.current.attach.attachedFiles.map((f) => f.id)).toEqual([1]);
|
||||
});
|
||||
|
||||
it('FE-PLANNER-BOOKINGFILES-005: a new booking lists no attached files', () => {
|
||||
it('FE-PLANNER-BOOKINGFILES-004: a new booking lists no attached files', () => {
|
||||
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,74 +1,34 @@
|
||||
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';
|
||||
|
||||
export interface BookingFileAttachOptions {
|
||||
/** The booking being edited; files picked before it is saved wait in `pendingFiles`. */
|
||||
reservation: { id: number; title: string } | null | undefined;
|
||||
/** The booking being edited; unset while it is being created. */
|
||||
reservation: { id: number } | null | undefined;
|
||||
/** The trip's files. */
|
||||
files: TripFile[];
|
||||
onFileUpload?: (fd: FormData) => Promise<unknown>;
|
||||
setPendingFiles: Dispatch<SetStateAction<File[]>>;
|
||||
/** The toast and translate the dialog already holds. */
|
||||
toast: { success: (message: string) => void; error: (message: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Files row of the desktop booking and transport dialogs: a file picked on a
|
||||
* saved booking goes up at once, one picked on a new booking waits for the save,
|
||||
* and the files linked or detached in the dialog show on the booking right away.
|
||||
* The Files row of the desktop booking and transport dialogs. A picked file waits
|
||||
* in `pendingFiles` and goes up with the save, on a new booking and a saved one
|
||||
* alike, as on the phone (#2534): one that fails stays in the list to try again
|
||||
* instead of vanishing with its toast (#2883). The files linked or detached in the
|
||||
* dialog show on the booking right away.
|
||||
*/
|
||||
export function useBookingFileAttach({
|
||||
reservation,
|
||||
files,
|
||||
onFileUpload,
|
||||
setPendingFiles,
|
||||
toast,
|
||||
t,
|
||||
}: BookingFileAttachOptions) {
|
||||
const [uploadingFile, setUploadingFile] = useState(false);
|
||||
export function useBookingFileAttach({ reservation, files, setPendingFiles }: BookingFileAttachOptions) {
|
||||
const [linkedFileIds, setLinkedFileIds] = useState<number[]>([]);
|
||||
|
||||
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
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) {
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
fd.append('reservation_id', String(reservation.id));
|
||||
fd.append('description', reservation.title);
|
||||
await onFileUpload(fd);
|
||||
toast.success(t('reservations.toast.fileUploaded'));
|
||||
} else {
|
||||
// A dialog without an upload reports a failed upload, as it always did.
|
||||
toast.error(t('reservations.toast.uploadError'));
|
||||
}
|
||||
} catch {
|
||||
toast.error(t('reservations.toast.uploadError'));
|
||||
} finally {
|
||||
setUploadingFile(false);
|
||||
e.target.value = '';
|
||||
}
|
||||
} else {
|
||||
setPendingFiles((prev) => [...prev, file]);
|
||||
e.target.value = '';
|
||||
}
|
||||
if (file) setPendingFiles((prev) => [...prev, file]);
|
||||
e.target.value = '';
|
||||
};
|
||||
|
||||
return {
|
||||
uploadingFile,
|
||||
handleFileChange,
|
||||
attachedFiles: attachedBookingFiles(files, reservation?.id, linkedFileIds),
|
||||
removePending: (index: number) => setPendingFiles((prev) => prev.filter((_, j) => j !== index)),
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { type Dispatch, type SetStateAction, useEffect, useRef } from 'react';
|
||||
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Reservation } from '../../types';
|
||||
import { type BookingSaveSteps, travelersChanged, uploadBookingFiles } from './bookingFormModel';
|
||||
|
||||
interface BookingFollowUpOptions {
|
||||
/**
|
||||
* Which booking the editor is open on. A new value starts over: the booking a
|
||||
* failed try stored belongs to the editor session it was saved in.
|
||||
*/
|
||||
session: unknown;
|
||||
tripId: number | string | undefined;
|
||||
/** The booking being edited, whose travellers the picked ones are compared with. */
|
||||
original: Pick<Reservation, 'travelers'> | null | undefined;
|
||||
travelerIds: Set<number>;
|
||||
pendingFiles: File[];
|
||||
setPendingFiles: Dispatch<SetStateAction<File[]>>;
|
||||
/** Where picked files go; without it they stay with the form. */
|
||||
upload: ((fd: FormData) => Promise<unknown>) | undefined;
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The part of a booking save that comes after the booking itself, shared by the
|
||||
* desktop dialogs and the phone sheets: the travellers picked for it (#1517) and
|
||||
* the files picked in the form. The planner waits for it before it closes the
|
||||
* editor, so a failure leaves the editor open (#2883). Each file that lands
|
||||
* leaves the list at once, so what is left after a failure is exactly what still
|
||||
* has to go up, and the booking the failed try stored is kept so that saving
|
||||
* again updates it instead of adding a second one.
|
||||
*/
|
||||
export function useBookingFollowUp({
|
||||
session,
|
||||
tripId,
|
||||
original,
|
||||
travelerIds,
|
||||
pendingFiles,
|
||||
setPendingFiles,
|
||||
upload,
|
||||
t,
|
||||
}: BookingFollowUpOptions) {
|
||||
const setReservationTravelers = useTripStore((s) => s.setReservationTravelers);
|
||||
const stored = useRef<Reservation | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
stored.current = null;
|
||||
}, [session]);
|
||||
|
||||
const afterSave = async (saved: Reservation, description: string) => {
|
||||
stored.current = saved;
|
||||
if (tripId) {
|
||||
const { changed, nextIds } = travelersChanged(original, travelerIds);
|
||||
if (changed) await setReservationTravelers(tripId, saved.id, nextIds);
|
||||
}
|
||||
// The server's reason for one file says less than what the editor shows: the
|
||||
// booking is there, and the files still listed are the ones to try again.
|
||||
const uploaded = await uploadBookingFiles(upload, saved.id, pendingFiles, description, (file) =>
|
||||
setPendingFiles((prev) => prev.filter((f) => f !== file))
|
||||
).then(
|
||||
() => true,
|
||||
() => false
|
||||
);
|
||||
if (!uploaded) throw new Error(t('reservations.toast.filesNotUploaded'));
|
||||
};
|
||||
|
||||
return {
|
||||
/** Whether a try in this session already stored the booking, so the form holds a retry. */
|
||||
holdsSaved: () => stored.current !== null,
|
||||
/** What the save hands the planner, for a booking whose files are described by `description`. */
|
||||
steps: (description: string): BookingSaveSteps => ({
|
||||
saved: stored.current ?? undefined,
|
||||
afterSave: (saved) => afterSave(saved, description),
|
||||
}),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user