diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index 3a7d5cd10..ab783e713 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -130,6 +130,15 @@ "src/mobile/screens/trip/sheets/MTransportFormSheet.tsx" ] }, + { + "feature": "Booking save follow-up: travellers and files before the editor closes", + "hooks": ["src/components/Planner/useBookingFollowUp.ts"], + "desktop": ["src/components/Planner/ReservationModal.tsx", "src/components/Planner/TransportModal.tsx"], + "mobile": [ + "src/mobile/screens/trip/sheets/MReservationSheet.tsx", + "src/mobile/screens/trip/sheets/MTransportFormSheet.tsx" + ] + }, { "feature": "Bookings and transports lists", "hooks": ["src/components/Planner/bookings/bookingsModel.ts"], diff --git a/client/src/components/Planner/BookingNotesFilesCosts.tsx b/client/src/components/Planner/BookingNotesFilesCosts.tsx index 4ce102205..fe7584f9a 100644 --- a/client/src/components/Planner/BookingNotesFilesCosts.tsx +++ b/client/src/components/Planner/BookingNotesFilesCosts.tsx @@ -23,6 +23,7 @@ export function BookingNotesFilesCosts({ fileInputRef, attach, canAttach, + saving, showCosts, pendingExpense, expense, @@ -38,6 +39,8 @@ export function BookingNotesFilesCosts({ fileInputRef: RefObject; attach: ReturnType; 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; @@ -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} /> diff --git a/client/src/components/Planner/ReservationModal.test.tsx b/client/src/components/Planner/ReservationModal.test.tsx index f11bfc782..7497faea3 100644 --- a/client/src/components/Planner/ReservationModal.test.tsx +++ b/client/src/components/Planner/ReservationModal.test.tsx @@ -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( ); @@ -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(); + render(); 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(); + 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(); + 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(), )); }); diff --git a/client/src/components/Planner/ReservationModal.tsx b/client/src/components/Planner/ReservationModal.tsx index 19d863329..6548f9c47 100644 --- a/client/src/components/Planner/ReservationModal.tsx +++ b/client/src/components/Planner/ReservationModal.tsx @@ -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 & { title: string }) => Promise + onSave: (data: Record & { title: string }, steps?: BookingSaveSteps) => Promise 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 & { 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 & { 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} diff --git a/client/src/components/Planner/TransportModal.test.tsx b/client/src/components/Planner/TransportModal.test.tsx index 07457aec5..c6ca7d0c6 100644 --- a/client/src/components/Planner/TransportModal.test.tsx +++ b/client/src/components/Planner/TransportModal.test.tsx @@ -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(); + render(); 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(); @@ -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(); + 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(); + render(); 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 }) => { diff --git a/client/src/components/Planner/TransportModal.tsx b/client/src/components/Planner/TransportModal.tsx index 5fb966c43..6220d41c3 100644 --- a/client/src/components/Planner/TransportModal.tsx +++ b/client/src/components/Planner/TransportModal.tsx @@ -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 & { title: string }) => Promise + onSave: (data: Record & { title: string }, steps?: BookingSaveSteps) => Promise 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(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} diff --git a/client/src/components/Planner/bookingFormModel.test.ts b/client/src/components/Planner/bookingFormModel.test.ts index 92eef146f..f2abd61c2 100644 --- a/client/src/components/Planner/bookingFormModel.test.ts +++ b/client/src/components/Planner/bookingFormModel.test.ts @@ -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); + 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(); }); diff --git a/client/src/components/Planner/bookingFormModel.ts b/client/src/components/Planner/bookingFormModel.ts index 34f571d1e..1ce0aa0ee 100644 --- a/client/src/components/Planner/bookingFormModel.ts +++ b/client/src/components/Planner/bookingFormModel.ts @@ -37,12 +37,17 @@ export function travelersChanged(reservation: Pick | 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) | undefined, savedId: number, files: File[], - description: string + description: string, + onUploaded?: (file: File) => void ): Promise { 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; +} + +/** + * 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>( + data: T, + stored: Pick +): T { + const { create_budget_entry: _linkedCost, ...rest } = data; + const update = rest as Record; + 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 diff --git a/client/src/components/Planner/useBookingFileAttach.test.ts b/client/src/components/Planner/useBookingFileAttach.test.ts index a506ab9e7..cbe5223f2 100644 --- a/client/src/components/Planner/useBookingFileAttach.test.ts +++ b/client/src/components/Planner/useBookingFileAttach.test.ts @@ -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 = {}, files: TripFile[] = []) { - const toast = { success: vi.fn(), error: vi.fn() }; - const t = (key: string) => key; - const view = renderHook(() => { + return renderHook(() => { const [pendingFiles, setPendingFiles] = useState([]); - 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([]); - }); }); diff --git a/client/src/components/Planner/useBookingFileAttach.ts b/client/src/components/Planner/useBookingFileAttach.ts index 25cb9fa47..45bd2a0af 100644 --- a/client/src/components/Planner/useBookingFileAttach.ts +++ b/client/src/components/Planner/useBookingFileAttach.ts @@ -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; setPendingFiles: Dispatch>; - /** 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([]); - const handleFileChange = async (e: React.ChangeEvent) => { + const handleFileChange = (e: React.ChangeEvent) => { 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)), diff --git a/client/src/components/Planner/useBookingFollowUp.ts b/client/src/components/Planner/useBookingFollowUp.ts new file mode 100644 index 000000000..b2f7065c6 --- /dev/null +++ b/client/src/components/Planner/useBookingFollowUp.ts @@ -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 | null | undefined; + travelerIds: Set; + pendingFiles: File[]; + setPendingFiles: Dispatch>; + /** Where picked files go; without it they stay with the form. */ + upload: ((fd: FormData) => Promise) | 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(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), + }), + }; +} diff --git a/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx b/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx index 9feaf366e..aca45e822 100644 --- a/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx +++ b/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx @@ -9,7 +9,8 @@ import CustomTimePicker from '../../../../components/shared/CustomTimePicker' import { CustomDatePicker } from '../../../../components/shared/CustomDateTimePicker' import { Eyebrow, FIELD_CLS, FormSheetFooter, FormSheetHeader } from './PlSheetChrome' import MBookingFilesCosts from './MBookingFilesCosts' -import { expenseRequestAfterSave, travelerIdsOf, travelersChanged, filesNeedConnection, uploadBookingFiles } from '../../../../components/Planner/bookingFormModel' +import { expenseRequestAfterSave, travelerIdsOf, filesNeedConnection } from '../../../../components/Planner/bookingFormModel' +import { useBookingFollowUp } from '../../../../components/Planner/useBookingFollowUp' import { useBookingExpenseIntent } from '../../../../components/Planner/useBookingExpenseIntent' import { RESERVATION_TYPE_OPTIONS as TYPE_OPTIONS, reservationFieldsFrom, reservationFieldsFromPrefill, selectedDayDate, @@ -17,7 +18,6 @@ import { import { useReservationForm } from '../../../../components/Planner/useReservationForm' import StayPinStatus from '../../../../components/Planner/StayPinStatus' import { buildAssignmentOptions } from '../../../../components/Planner/assignmentOptions' -import { useTripStore } from '../../../../store/tripStore' import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types' import type { TripPlanner } from '../MTripShell' import { stayPlaces } from '../../../../utils/stayPlaces' @@ -41,7 +41,8 @@ const EMPTY = { * driven by the planner's own editor flags (showReservationModal / editingReservation / * reservationPrefill / bookingForAssignmentId) so every entry point (bookings tab, day * sheet, timeline, import review) opens it unchanged. Saving reuses - * planner.handleSaveReservation, which owns the accommodation split, file upload and undo. + * planner.handleSaveReservation, which owns the accommodation split and closes the sheet + * once the travellers and files that hang on the booking are written. */ export default function MReservationSheet({ planner, onOpenExpense }: MReservationSheetProps) { const { @@ -54,7 +55,6 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati handleSaveReservation, canUploadFiles, } = planner const { locale } = useTranslation() - const setReservationTravelers = useTripStore(s => s.setReservationTravelers) const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget')) @@ -63,6 +63,11 @@ 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) + const followUp = useBookingFollowUp({ + session: showReservationModal, + tripId, original: editingReservation, travelerIds, pendingFiles, setPendingFiles, + upload: canUploadFiles ? fd => planner.tripActions.addFile(tripId, fd) : undefined, t, + }) const assignmentOptions = useMemo( () => buildAssignmentOptions(days, assignments, t, locale), [days, assignments, t, locale], @@ -153,17 +158,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati setIsSaving(true) try { const saveData = buildSaveData({ assignmentId, isEdit: !!snap.res?.id, withCheckInEnd: false }) - const saved = await handleSaveReservation(saveData as never) - // Persist the traveler assignment once we have the reservation id (from the - // save result on create, or the edited reservation) — only when it changed. - const savedId = saved?.id ?? res?.id - if (savedId) { - const { changed, nextIds } = travelersChanged(res, travelerIds) - if (changed) await setReservationTravelers(tripId, savedId, nextIds) - } - if (saved?.id && canUploadFiles) { - await uploadBookingFiles(fd => planner.tripActions.addFile(tripId, fd), saved.id, pendingFiles, form.title) - } + const saved = await handleSaveReservation(saveData as never, followUp.steps(form.title)) const expenseRequest = expenseRequestAfterSave(withExpense, saved, form, days) if (expenseRequest) onOpenExpense(expenseRequest) if (importReviewActive && saved) advanceImportReview() diff --git a/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx b/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx index 7caa6ec00..e2458f8bb 100644 --- a/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx +++ b/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx @@ -16,11 +16,11 @@ import { transportDayOptions, type StationWaypointForm, type WaypointForm, } from '../../../../components/Planner/transportEndpoints' import { useTransportForm } from '../../../../components/Planner/useTransportForm' -import { expenseRequestAfterSave, travelerIdsOf, travelersChanged, filesNeedConnection, uploadBookingFiles } from '../../../../components/Planner/bookingFormModel' +import { expenseRequestAfterSave, travelerIdsOf, filesNeedConnection, type BookingSaveSteps } from '../../../../components/Planner/bookingFormModel' +import { useBookingFollowUp } from '../../../../components/Planner/useBookingFollowUp' import { useBookingExpenseIntent } from '../../../../components/Planner/useBookingExpenseIntent' import { Eyebrow, FIELD_CLS, FormSheetFooter, FormSheetHeader } from './PlSheetChrome' import MBookingFilesCosts from './MBookingFilesCosts' -import { useTripStore } from '../../../../store/tripStore' import type { Place, Reservation } from '../../../../types' import type { BookingReviewDraft } from '../../../../components/Planner/parsedItemToDraft' import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types' @@ -54,7 +54,6 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo canUploadFiles, } = planner const { locale } = useTranslation() - const setReservationTravelers = useTripStore(s => s.setReservationTravelers) const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget')) const tripHasDates = Boolean(trip?.start_date && trip?.end_date) @@ -67,6 +66,11 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler, isSaving, setIsSaving, seed, payload: buildPayload, writesFlightLegs, writesTrainLegs, } = useTransportForm(EMPTY_TRANSPORT_FIELDS) + const followUp = useBookingFollowUp({ + session: showTransportModal, + tripId, original: editingTransport, travelerIds, pendingFiles, setPendingFiles, + upload: canUploadFiles ? fd => planner.tripActions.addFile(tripId, fd) : undefined, t, + }) // Ref (not state) so handleSubmit reads the intent set by the same click — a // state value would be stale in that render's closure and never open the editor. const expense = useBookingExpenseIntent(() => handleSubmit()) @@ -113,10 +117,11 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo } // The single save path shared by the manual submit and the automated panel — - // handleSaveTransport closes the sheet on success; on an import review it also - // advances to the next parsed item (mirrors the desktop MTripSheets wrapper). - const saveTransport = async (data: Record & { title: string }) => { - const r = await handleSaveTransport(data as never) + // handleSaveTransport closes the sheet once the booking and what hangs on it are + // written; on an import review it also advances to the next parsed item then, + // and not while the item's files are still going up (mirrors the desktop wrapper). + const saveTransport = async (data: Record & { title: string }, steps?: BookingSaveSteps) => { + const r = await handleSaveTransport(data as never, steps) if (importReviewActive && r) advanceImportReview() return r } @@ -129,20 +134,7 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo try { const saved = await saveTransport(buildPayload(days, { reservation: res, prefill, budgetEnabled: isBudgetEnabled, anchorOnStations: true, - })) - // Persist the traveler assignment once we have the reservation id (from the - // save result on create, or the edited reservation) — only when it changed. - const savedId = saved?.id ?? res?.id - if (savedId) { - const { changed, nextIds } = travelersChanged(res, travelerIds) - if (changed) await setReservationTravelers(tripId, savedId, nextIds) - } - // Runs after both a create and an edit: the sheet only holds files the user just - // picked, so nothing is uploaded twice, and skipping the edit dropped them without - // a word (#2534). A save that did not come back with a record uploads nothing. - if (saved?.id && canUploadFiles) { - await uploadBookingFiles(fd => planner.tripActions.addFile(tripId, fd), saved.id, pendingFiles, form.title) - } + }), followUp.steps(form.title)) const expenseRequest = expenseRequestAfterSave(withExpense, saved, form, days) if (expenseRequest) onOpenExpense(expenseRequest) } catch (err: unknown) { diff --git a/client/src/pages/TripPlannerPage.tsx b/client/src/pages/TripPlannerPage.tsx index ebad87bdd..5190042d6 100644 --- a/client/src/pages/TripPlannerPage.tsx +++ b/client/src/pages/TripPlannerPage.tsx @@ -831,11 +831,11 @@ function TripPlannerPageDesktop(): React.ReactElement | null { onCoverUpdate={applyTripCoverUpdate} /> setShowMembersModal(false)} tripId={tripId} tripTitle={trip?.title} onMembersChanged={refreshMembers} /> - { if (importReviewActive) { advanceImportReview() } else { setShowReservationModal(false); setEditingReservation(null); setBookingForAssignmentId(null) } }} onSave={async (data) => { const r = await handleSaveReservation(data); if (importReviewActive && r) advanceImportReview(); return r }} reservation={editingReservation} prefill={reservationPrefill} days={days} places={places} assignments={assignments} selectedDayId={selectedDayId} files={files} onFileUpload={canUploadFiles ? (fd) => tripActions.addFile(tripId, fd) : undefined} onFileDelete={(id) => tripActions.deleteFile(tripId, id)} accommodations={tripAccommodations} defaultAssignmentId={bookingForAssignmentId} onOpenExpense={openBookingExpense} tripMembers={tripMembers} /> + { if (importReviewActive) { advanceImportReview() } else { setShowReservationModal(false); setEditingReservation(null); setBookingForAssignmentId(null) } }} onSave={async (data, steps) => { const r = await handleSaveReservation(data, steps); if (importReviewActive && r) advanceImportReview(); return r }} reservation={editingReservation} prefill={reservationPrefill} days={days} places={places} assignments={assignments} selectedDayId={selectedDayId} files={files} onFileUpload={canUploadFiles ? (fd) => tripActions.addFile(tripId, fd) : undefined} onFileDelete={(id) => tripActions.deleteFile(tripId, id)} accommodations={tripAccommodations} defaultAssignmentId={bookingForAssignmentId} onOpenExpense={openBookingExpense} tripMembers={tripMembers} /> {showTransportModal && ( - { if (importReviewActive) { advanceImportReview() } else { setShowTransportModal(false); setEditingTransport(null); setTransportModalDayId(null); setTransportModalAutomated(false); setTransitPrefill(null) } }} onSave={async (data) => { const r = await handleSaveTransport(data); if (importReviewActive && r) advanceImportReview(); return r }} reservation={editingTransport} prefill={transportPrefill} days={days} selectedDayId={transportModalDayId} files={files} onFileUpload={canUploadFiles ? (fd) => tripActions.addFile(tripId, fd) : undefined} onFileDelete={(id) => tripActions.deleteFile(tripId, id)} onDelete={can('reservation_edit', trip) && editingTransport ? () => handleDeleteReservation(editingTransport.id) : undefined} onOpenExpense={openBookingExpense} places={places} assignments={assignments} accommodations={tripAccommodations} initialAutomated={transportModalAutomated} transitPrefill={transitPrefill} tripHasDates={tripHasDates} tripMembers={tripMembers} /> + { if (importReviewActive) { advanceImportReview() } else { setShowTransportModal(false); setEditingTransport(null); setTransportModalDayId(null); setTransportModalAutomated(false); setTransitPrefill(null) } }} onSave={async (data, steps) => { const r = await handleSaveTransport(data, steps); if (importReviewActive && r) advanceImportReview(); return r }} reservation={editingTransport} prefill={transportPrefill} days={days} selectedDayId={transportModalDayId} files={files} onFileUpload={canUploadFiles ? (fd) => tripActions.addFile(tripId, fd) : undefined} onFileDelete={(id) => tripActions.deleteFile(tripId, id)} onDelete={can('reservation_edit', trip) && editingTransport ? () => handleDeleteReservation(editingTransport.id) : undefined} onOpenExpense={openBookingExpense} places={places} assignments={assignments} accommodations={tripAccommodations} initialAutomated={transportModalAutomated} transitPrefill={transitPrefill} tripHasDates={tripHasDates} tripMembers={tripMembers} /> )} diff --git a/client/src/pages/TripPlannerPage.wiring.test.tsx b/client/src/pages/TripPlannerPage.wiring.test.tsx index db7ed74d8..a07238bca 100644 --- a/client/src/pages/TripPlannerPage.wiring.test.tsx +++ b/client/src/pages/TripPlannerPage.wiring.test.tsx @@ -1573,8 +1573,9 @@ describe('TripPlannerPage — modals', () => { act(() => { props('reservationModal').onClose() }) expect(hookState.advanceImportReview).toHaveBeenCalledTimes(1) - await act(async () => { await props('reservationModal').onSave({ title: 'Ryokan' }) }) - expect(hookState.handleSaveReservation).toHaveBeenCalledWith({ title: 'Ryokan' }) + const steps = { afterSave: vi.fn() } + await act(async () => { await props('reservationModal').onSave({ title: 'Ryokan' }, steps) }) + expect(hookState.handleSaveReservation).toHaveBeenCalledWith({ title: 'Ryokan' }, steps) expect(hookState.advanceImportReview).toHaveBeenCalledTimes(2) }) @@ -1595,8 +1596,9 @@ describe('TripPlannerPage — modals', () => { // carries tz-lookup. expect(await screen.findByTestId('transport-modal')).toBeInTheDocument() - await act(async () => { await props('transportModal').onSave({ title: 'ICE' }) }) - expect(hookState.handleSaveTransport).toHaveBeenCalledWith({ title: 'ICE' }) + const steps = { afterSave: vi.fn() } + await act(async () => { await props('transportModal').onSave({ title: 'ICE' }, steps) }) + expect(hookState.handleSaveTransport).toHaveBeenCalledWith({ title: 'ICE' }, steps) act(() => { props('transportModal').onClose() }) expect(hookState.setShowTransportModal).toHaveBeenCalledWith(false) diff --git a/client/src/pages/tripPlanner/useBookingEdits.test.ts b/client/src/pages/tripPlanner/useBookingEdits.test.ts index 8c336af9b..3c6b05889 100644 --- a/client/src/pages/tripPlanner/useBookingEdits.test.ts +++ b/client/src/pages/tripPlanner/useBookingEdits.test.ts @@ -1,4 +1,4 @@ -// FE-TP-BOOKING-001 to FE-TP-BOOKING-013 +// FE-TP-BOOKING-001 to FE-TP-BOOKING-016 // // Booking writes and the review before an import is saved, driven straight through // useBookingEdits. Every write goes to a recorded stand-in for the store's actions and @@ -407,4 +407,76 @@ describe('useBookingEdits', () => { await waitFor(() => expect(useBackgroundTasksStore.getState().tasks).toHaveLength(0)) expect(result.current.receiptExpense).toBeNull() }) + it('FE-TP-BOOKING-014: the editor stays open until what hangs on the booking is written (#2883)', async () => { + const { result } = renderEdits() + let finish!: () => void + const afterSave = vi.fn(() => new Promise(resolve => { finish = resolve })) + + let pending!: Promise + act(() => { pending = result.current.handleSaveReservation({ title: 'Dinner', type: 'restaurant' }, { afterSave }) }) + await waitFor(() => expect(afterSave).toHaveBeenCalledWith({ id: 6 })) + expect(toast.success).not.toHaveBeenCalled() + expect(fixed.setShowReservationModal).not.toHaveBeenCalled() + + let saved: unknown + await act(async () => { finish(); saved = await pending }) + expect(saved).toEqual({ id: 6 }) + expect(toast.success).toHaveBeenCalledWith('trip.toast.reservationAdded') + expect(fixed.setShowReservationModal).toHaveBeenCalledWith(false) + }) + + it('FE-TP-BOOKING-015: a failed follow-up keeps the editor open, and the retry updates the stored booking', async () => { + const { result } = renderEdits() + const afterSave = vi.fn().mockRejectedValueOnce(new Error('reservations.toast.filesNotUploaded')).mockResolvedValue(undefined) + + let saved: unknown = 'unset' + await act(async () => { + saved = await result.current.handleSaveReservation({ title: 'Ryokan', type: 'hotel', create_budget_entry: 1 }, { afterSave }) + }) + expect(saved).toBeUndefined() + expect(toast.error).toHaveBeenCalledWith('reservations.toast.filesNotUploaded') + expect(toast.success).not.toHaveBeenCalled() + expect(fixed.setShowReservationModal).not.toHaveBeenCalled() + expect(actions.addReservation).toHaveBeenCalledTimes(1) + expect(actions.loadBudgetItems).toHaveBeenCalledTimes(1) + + // The retry names the stored booking: it is updated, its cost and stay are not made twice. + const stored = buildReservation({ id: 6, type: 'hotel', accommodation_id: 31 }) + await act(async () => { + saved = await result.current.handleSaveReservation( + { title: 'Ryokan', type: 'hotel', create_budget_entry: 1, accommodation_id: null }, + { saved: stored, afterSave }, + ) + }) + expect(actions.addReservation).toHaveBeenCalledTimes(1) + expect(actions.updateReservation).toHaveBeenCalledWith(42, 6, { title: 'Ryokan', type: 'hotel', accommodation_id: 31 }) + expect(actions.loadBudgetItems).toHaveBeenCalledTimes(1) + expect(afterSave).toHaveBeenLastCalledWith({ id: 5 }) + expect(saved).toEqual({ id: 5 }) + expect(toast.success).toHaveBeenCalledWith('trip.toast.reservationAdded') + expect(fixed.setShowReservationModal).toHaveBeenCalledWith(false) + }) + + it('FE-TP-BOOKING-016: a transport waits for its follow-up the same way, and retries as an update', async () => { + const { result } = renderEdits() + const afterSave = vi.fn().mockRejectedValueOnce(new Error('reservations.toast.filesNotUploaded')).mockResolvedValue(undefined) + + let saved: unknown = 'unset' + await act(async () => { saved = await result.current.handleSaveTransport({ title: 'ICE', create_budget_entry: true }, { afterSave }) }) + expect(saved).toBeUndefined() + expect(toast.error).toHaveBeenCalledWith('reservations.toast.filesNotUploaded') + expect(fixed.setShowTransportModal).not.toHaveBeenCalled() + + await act(async () => { + saved = await result.current.handleSaveTransport( + { title: 'ICE', create_budget_entry: true }, + { saved: buildReservation({ id: 6, type: 'train' }), afterSave }, + ) + }) + expect(actions.addReservation).toHaveBeenCalledTimes(1) + expect(actions.updateReservation).toHaveBeenCalledWith(42, 6, { title: 'ICE' }) + expect(saved).toEqual({ id: 5 }) + expect(toast.success).toHaveBeenCalledWith('trip.toast.reservationAdded') + expect(fixed.setShowTransportModal).toHaveBeenCalledWith(false) + }) }) diff --git a/client/src/pages/tripPlanner/useBookingEdits.ts b/client/src/pages/tripPlanner/useBookingEdits.ts index 819435874..f3f35a90c 100644 --- a/client/src/pages/tripPlanner/useBookingEdits.ts +++ b/client/src/pages/tripPlanner/useBookingEdits.ts @@ -3,13 +3,14 @@ import type { BookingImportPreviewItem } from '@trek/shared' import { receiptToPrefill } from '../../components/Budget/CostsPanel.helpers' import type { ExpensePrefill } from '../../components/Budget/CostsPanel' import { parsedItemToDraft, isTransportItem, isUnplaceableItem, type BookingReviewDraft } from '../../components/Planner/parsedItemToDraft' +import { retriedSave, type BookingSaveSteps } from '../../components/Planner/bookingFormModel' import { getImportFiles, deleteImportFiles } from '../../db/offlineDb' import { accommodationRepo } from '../../repo/accommodationRepo' import { findOnMap, stayQueries } from '../../repo/mapMatchRepo' import { useBackgroundTasksStore } from '../../store/backgroundTasksStore' import type { TripStoreState } from '../../store/tripStore' import { isEffectivelyOffline } from '../../sync/networkMode' -import type { Accommodation, Place } from '../../types' +import type { Accommodation, Place, Reservation } from '../../types' import type { Can, PlannerBase } from './plannerTypes' import type { PlannerDialogs } from './usePlannerDialogs' @@ -57,7 +58,14 @@ export function useBookingEdits(options: BookingEditsOptions) { // The value comes off the persisted job (#2076). const importKindRef = useRef<'transports' | 'bookings'>('bookings') - const handleSaveReservation = async (data: Record & { title: string }) => { + // A save is done once the editor's own part (travellers, files) is done too: + // only then does it say so and close. Until then the editor stays open, so a + // failed upload leaves the files to try again instead of a closed dialog and a + // booking that silently lacks them (#2883). Undefined means not done. + const handleSaveReservation = async ( + data: Record & { title: string }, + { saved: earlier, afterSave }: BookingSaveSteps = {}, + ): Promise => { try { // Imported hotel with a reviewed address but no existing place picked: match // an existing place by name, else geocode the address and create one, then link it. @@ -81,55 +89,54 @@ export function useBookingEdits(options: BookingEditsOptions) { } delete acc.address } + let r: Reservation if (editingReservation) { // Don't force a day here. The old code pinned it to the (often empty) // selected day, which dropped the booking out of the Plan; preserving the // old day_id instead left it stale when the date changed. Omitting it lets // the server derive the day from the booking's date, or keep the current // one when there is no date. - const r = await tripActions.updateReservation(tripId, editingReservation.id, data) - toast.success(t('trip.toast.reservationUpdated')) - setShowReservationModal(false) - setEditingReservation(null) - if (data.type === 'hotel') { - accommodationRepo.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {}) - } - return r + r = await tripActions.updateReservation(tripId, editingReservation.id, data) + } else if (earlier) { + r = await tripActions.updateReservation(tripId, earlier.id, retriedSave(data, earlier)) } else { - const r = await tripActions.addReservation(tripId, { ...data, day_id: selectedDayId || null }) - toast.success(t('trip.toast.reservationAdded')) - setShowReservationModal(false) + r = await tripActions.addReservation(tripId, { ...data, day_id: selectedDayId || null }) // An imported booking auto-creates a linked cost server-side; the saving client gets // no budget:created echo, so refresh the budget items here to surface it without a reload. if ((data as Record).create_budget_entry) await tripActions.loadBudgetItems?.(tripId) - // Refresh accommodations if hotel was created - if (data.type === 'hotel') { - accommodationRepo.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {}) - } - return r } + if (data.type === 'hotel') { + accommodationRepo.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {}) + } + await afterSave?.(r) + toast.success(t(editingReservation ? 'trip.toast.reservationUpdated' : 'trip.toast.reservationAdded')) + setShowReservationModal(false) + if (editingReservation) setEditingReservation(null) + return r } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } } - const handleSaveTransport = async (data: Record & { title: string }) => { + const handleSaveTransport = async ( + data: Record & { title: string }, + { saved: earlier, afterSave }: BookingSaveSteps = {}, + ): Promise => { try { + let r: Reservation if (editingTransport) { - const r = await tripActions.updateReservation(tripId, editingTransport.id, data) - toast.success(t('trip.toast.reservationUpdated')) - setShowTransportModal(false) - setEditingTransport(null) - setTransportModalDayId(null) - return r + r = await tripActions.updateReservation(tripId, editingTransport.id, data) + } else if (earlier) { + r = await tripActions.updateReservation(tripId, earlier.id, retriedSave(data, earlier)) } else { - const r = await tripActions.addReservation(tripId, data) - toast.success(t('trip.toast.reservationAdded')) - setShowTransportModal(false) - setEditingTransport(null) - setTransportModalDayId(null) + r = await tripActions.addReservation(tripId, data) // Surface the auto-created linked cost without a reload (no budget:created echo to us). if (data.create_budget_entry) await tripActions.loadBudgetItems?.(tripId) - return r } + await afterSave?.(r) + toast.success(t(editingTransport ? 'trip.toast.reservationUpdated' : 'trip.toast.reservationAdded')) + setShowTransportModal(false) + setEditingTransport(null) + setTransportModalDayId(null) + return r } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } } diff --git a/client/tests/helpers/bookingSave.ts b/client/tests/helpers/bookingSave.ts new file mode 100644 index 000000000..25e25146b --- /dev/null +++ b/client/tests/helpers/bookingSave.ts @@ -0,0 +1,25 @@ +import { vi } from 'vitest'; + +import type { BookingSaveSteps } from '../../src/components/Planner/bookingFormModel'; +import type { Reservation } from '../../src/types'; + +/** + * A booking save that does what the planner does (useBookingEdits): it stores the + * booking as `record`, runs the editor's follow-up (travellers, files) and answers + * nothing when that fails, keeping the failure for the test to read. The desktop + * dialogs take it as `onSave`, the phone sheets as `handleSaveReservation` or + * `handleSaveTransport`. + */ +export function plannerSave(record: { id: number }) { + const failures: Error[] = []; + const save = vi.fn(async (_data: unknown, steps?: BookingSaveSteps) => { + try { + await steps?.afterSave?.(record as Reservation); + return record; + } catch (err) { + failures.push(err as Error); + return undefined; + } + }); + return { save, failures }; +} diff --git a/client/tests/unit/mobile/trip/MReservationSheet.test.tsx b/client/tests/unit/mobile/trip/MReservationSheet.test.tsx index 05fa12ec3..42250d874 100644 --- a/client/tests/unit/mobile/trip/MReservationSheet.test.tsx +++ b/client/tests/unit/mobile/trip/MReservationSheet.test.tsx @@ -10,10 +10,11 @@ import { useSettingsStore } from '../../../../src/store/settingsStore' import { isBlurred } from '../../../helpers/bookingCodeBlur' import type { Accommodation, Assignment, Day, Place, Reservation, TripMember } from '../../../../src/types' import { buildPlanner } from '../../../helpers/mobileTrip' +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-068 (plus 037b) +// FE-MOB-RESSH-001 to FE-MOB-RESSH-069 (plus 037b) // Date/time/select pickers have their own suites — here they only have to be // addressable, so they render as plain controls. @@ -118,7 +119,7 @@ function makePlanner(overrides: Record = {}) { selectedDayId: 12, showReservationModal: true, canUploadFiles: true, - handleSaveReservation: vi.fn(async () => ({ id: 99 })), + handleSaveReservation: plannerSave({ id: 99 }).save, ...overrides, } as never) } @@ -694,11 +695,11 @@ describe('MReservationSheet', () => { expect(setTravelers).not.toHaveBeenCalled() }) - it('FE-MOB-RESSH-035: removing a traveler falls back to the edited booking id', async () => { + it('FE-MOB-RESSH-035: removing a traveler writes the empty list to the edited booking', async () => { const planner = makePlanner({ tripMembers: MEMBERS, editingReservation: DINNER, - handleSaveReservation: vi.fn(async () => undefined), + handleSaveReservation: plannerSave(DINNER).save, }) setup(planner) fireEvent.click(screen.getByText('Ana')) @@ -725,7 +726,7 @@ describe('MReservationSheet', () => { }) it('FE-MOB-RESSH-037: files attached while editing a booking are uploaded against it (#2534)', async () => { - const { planner } = setup(makePlanner({ editingReservation: DINNER, handleSaveReservation: vi.fn(async () => DINNER) })) + const { planner } = setup(makePlanner({ editingReservation: DINNER, handleSaveReservation: plannerSave(DINNER).save })) const input = document.querySelector('input[type="file"]') as HTMLInputElement fireEvent.change(input, { target: { files: [new File(['a'], 'a.pdf'), new File(['b'], 'b.pdf')] } }) fireEvent.click(submitBtn()) @@ -747,6 +748,34 @@ describe('MReservationSheet', () => { expect(planner.tripActions.addFile).not.toHaveBeenCalled() }) + it('FE-MOB-RESSH-069: a failed upload keeps the sheet and the files left, and the retry updates the same booking (#2883)', async () => { + const { save, failures } = plannerSave({ id: 99 }) + const planner = makePlanner({ importReviewActive: true, handleSaveReservation: save }) + vi.mocked(planner.tripActions.addFile) + .mockResolvedValueOnce(undefined as never) + .mockRejectedValueOnce(new Error('413')) + .mockResolvedValue(undefined as never) + setup(planner) + type(titleField(), 'Flight docs') + const input = document.querySelector('input[type="file"]') as HTMLInputElement + fireEvent.change(input, { target: { files: [new File(['a'], 'ok.pdf'), new File(['b'], 'fail.pdf')] } }) + fireEvent.click(submitBtn()) + + await waitFor(() => expect(failures).toHaveLength(1)) + expect(planner.advanceImportReview).not.toHaveBeenCalled() + expect(screen.queryByText('ok.pdf')).not.toBeInTheDocument() + expect(screen.getByText('fail.pdf')).toBeInTheDocument() + expect(save.mock.calls[0][1]?.saved).toBeUndefined() + + fireEvent.click(submitBtn()) + await waitFor(() => expect(planner.advanceImportReview).toHaveBeenCalledTimes(1)) + expect(save.mock.calls[1][1]?.saved).toEqual({ id: 99 }) + expect(planner.tripActions.addFile).toHaveBeenCalledTimes(3) + const [, fd] = vi.mocked(planner.tripActions.addFile).mock.calls[2] as [number, FormData] + expect((fd.get('file') as File).name).toBe('fail.pdf') + expect(fd.get('reservation_id')).toBe('99') + }) + 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 14229182d..094b90ff4 100644 --- a/client/tests/unit/mobile/trip/MTransportFormSheet.test.tsx +++ b/client/tests/unit/mobile/trip/MTransportFormSheet.test.tsx @@ -11,10 +11,11 @@ import { useSettingsStore } from '../../../../src/store/settingsStore' import { isBlurred } from '../../../helpers/bookingCodeBlur' import type { Day, Reservation, TripMember } from '../../../../src/types' import { buildPlanner } from '../../../helpers/mobileTrip' +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-059 +// FE-MOB-TRFRM-001 to FE-MOB-TRFRM-060 // // 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 @@ -135,8 +136,9 @@ const MEMBERS = [ type SavePayload = Record & { title: string } -function makeSave(result: unknown = { id: 99 } as unknown) { - return vi.fn(async (_payload: SavePayload) => result) +/** A save that stores `result` and runs the sheet's follow-up, as the planner does; null stores nothing. */ +function makeSave(result: { id: number } | null = { id: 99 }) { + return result ? plannerSave(result).save : vi.fn(async (_payload: SavePayload) => undefined) } function makePlanner(overrides: Record = {}): TripPlanner { @@ -983,7 +985,7 @@ describe('MTransportFormSheet', () => { const handleSaveTransport = makeSave() renderSheet(makePlanner({ transportModalAutomated: true, transportModalDayId: 12, handleSaveTransport })) await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'add-itinerary' })) }) - expect(handleSaveTransport).toHaveBeenCalledWith({ title: 'U4 to Prater', type: 'transit' }) + expect(handleSaveTransport).toHaveBeenCalledWith({ title: 'U4 to Prater', type: 'transit' }, undefined) }) it('FE-MOB-TRFRM-041: switching between manual and automated swaps the form', () => { @@ -1145,6 +1147,30 @@ 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 () => { + const { save, failures } = plannerSave({ id: 99 }) + const addFile = vi.fn(async (_tripId: number, _form: FormData) => undefined) + .mockResolvedValueOnce(undefined) + .mockRejectedValueOnce(new Error('413')) + const planner = makePlanner({ importReviewActive: true, handleSaveTransport: save, tripActions: { addFile } }) + renderSheet(planner) + typeTitle('Flight with docs') + fireEvent.click(screen.getByRole('button', { name: 'attach-file' })) + fireEvent.click(screen.getByRole('button', { name: 'attach-file' })) + + await submit() + await waitFor(() => expect(failures).toHaveLength(1)) + expect(planner.advanceImportReview).not.toHaveBeenCalled() + expect(screen.getAllByRole('button', { name: 'drop-extra.pdf' })).toHaveLength(1) + expect(save.mock.calls[0][1]?.saved).toBeUndefined() + + await submit() + await waitFor(() => expect(planner.advanceImportReview).toHaveBeenCalledTimes(1)) + expect(save.mock.calls[1][1]?.saved).toEqual({ id: 99 }) + expect(addFile).toHaveBeenCalledTimes(3) + expect((addFile.mock.calls[2][1] as FormData).get('reservation_id')).toBe('99') + }) + 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) diff --git a/shared/src/i18n/ar/reservations.ts b/shared/src/i18n/ar/reservations.ts index bce45b582..2bb74ecd3 100644 --- a/shared/src/i18n/ar/reservations.ts +++ b/shared/src/i18n/ar/reservations.ts @@ -77,8 +77,7 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': 'سيتم حذف "{name}" نهائيًا، مع التكاليف المرتبطة به.', 'reservations.toast.updated': 'تم تحديث الحجز', 'reservations.toast.removed': 'تم حذف الحجز', - 'reservations.toast.fileUploaded': 'تم رفع الملف', - 'reservations.toast.uploadError': 'فشل الرفع', + 'reservations.toast.filesNotUploaded': 'تم حفظ الحجز، لكن تعذّر رفع بعض الملفات. احفظ مرة أخرى لإرسالها.', 'reservations.newTitle': 'حجز جديد', 'reservations.bookingType': 'نوع الحجز', 'reservations.titleLabel': 'العنوان', diff --git a/shared/src/i18n/az/reservations.ts b/shared/src/i18n/az/reservations.ts index 0bae5d913..e2c0ec8f0 100644 --- a/shared/src/i18n/az/reservations.ts +++ b/shared/src/i18n/az/reservations.ts @@ -91,8 +91,8 @@ const reservations: TranslationStrings = { 'reservations.toast.updated': 'Rezervasiya yeniləndi', 'reservations.toast.removed': 'Rezervasiya silindi', - 'reservations.toast.fileUploaded': 'Fayl yükləndi', - 'reservations.toast.uploadError': 'Faylı yükləmək mümkün olmadı', + 'reservations.toast.filesNotUploaded': + 'Rezervasiya yadda saxlanıldı, lakin bəzi fayllar yüklənmədi. Onları göndərmək üçün yenidən yadda saxlayın.', 'reservations.newTitle': 'Yeni rezervasiya', 'reservations.bookingType': 'Rezervasiya növü', diff --git a/shared/src/i18n/br/reservations.ts b/shared/src/i18n/br/reservations.ts index 1343be629..eb2819b76 100644 --- a/shared/src/i18n/br/reservations.ts +++ b/shared/src/i18n/br/reservations.ts @@ -77,8 +77,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" e os custos vinculados serão excluídos permanentemente.', 'reservations.toast.updated': 'Reserva atualizada', 'reservations.toast.removed': 'Reserva excluída', - 'reservations.toast.fileUploaded': 'Arquivo enviado', - 'reservations.toast.uploadError': 'Falha no envio', + 'reservations.toast.filesNotUploaded': + 'A reserva foi salva, mas alguns arquivos não foram enviados. Salve novamente para enviá-los.', 'reservations.newTitle': 'Nova reserva', 'reservations.bookingType': 'Tipo de reserva', 'reservations.titleLabel': 'Título', diff --git a/shared/src/i18n/ca/reservations.ts b/shared/src/i18n/ca/reservations.ts index 959908bef..cd915ba25 100644 --- a/shared/src/i18n/ca/reservations.ts +++ b/shared/src/i18n/ca/reservations.ts @@ -46,8 +46,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': "« {name} » i els costos vinculats s'eliminaran permanentment.", 'reservations.toast.updated': 'Reserva actualitzada', 'reservations.toast.removed': 'Reserva eliminada', - 'reservations.toast.fileUploaded': 'Fitxer pujat', - 'reservations.toast.uploadError': "No s'ha pogut pujar", + 'reservations.toast.filesNotUploaded': + "La reserva s'ha desat, però alguns fitxers no s'han pujat. Desa de nou per enviar-los.", 'reservations.newTitle': 'Reserva nova', 'reservations.bookingType': 'Tipus de reserva', 'reservations.titleLabel': 'Títol', diff --git a/shared/src/i18n/cs/reservations.ts b/shared/src/i18n/cs/reservations.ts index 39b689883..e7bd32c7f 100644 --- a/shared/src/i18n/cs/reservations.ts +++ b/shared/src/i18n/cs/reservations.ts @@ -77,8 +77,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '„{name}” bude trvale smazána i s propojenými náklady.', 'reservations.toast.updated': 'Rezervace aktualizována', 'reservations.toast.removed': 'Rezervace smazána', - 'reservations.toast.fileUploaded': 'Soubor byl nahrán', - 'reservations.toast.uploadError': 'Nahrávání se nezdařilo', + 'reservations.toast.filesNotUploaded': + 'Rezervace je uložená, ale některé soubory se nenahrály. Ulož znovu a odešli je.', 'reservations.newTitle': 'Nová rezervace', 'reservations.bookingType': 'Typ rezervace', 'reservations.titleLabel': 'Název', diff --git a/shared/src/i18n/de/reservations.ts b/shared/src/i18n/de/reservations.ts index f1802e593..7419f17e5 100644 --- a/shared/src/i18n/de/reservations.ts +++ b/shared/src/i18n/de/reservations.ts @@ -85,8 +85,8 @@ const reservations: TranslationStrings = { 'reservations.toast.updateError': 'Fehler beim Aktualisieren', 'reservations.toast.deleteError': 'Fehler beim Löschen', 'reservations.confirm.remove': 'Reservierung für "{name}" entfernen?', - 'reservations.toast.fileUploaded': 'Datei hochgeladen', - 'reservations.toast.uploadError': 'Fehler beim Hochladen', + 'reservations.toast.filesNotUploaded': + 'Die Buchung ist gespeichert, aber einige Dateien wurden nicht hochgeladen. Speichere erneut, um sie zu senden.', 'reservations.newTitle': 'Neue Buchung', 'reservations.bookingType': 'Art der Buchung', 'reservations.titleLabel': 'Titel', diff --git a/shared/src/i18n/en/reservations.ts b/shared/src/i18n/en/reservations.ts index 626cb8b0b..0986c92ce 100644 --- a/shared/src/i18n/en/reservations.ts +++ b/shared/src/i18n/en/reservations.ts @@ -79,8 +79,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" will be permanently deleted, along with its linked costs.', 'reservations.toast.updated': 'Reservation updated', 'reservations.toast.removed': 'Reservation deleted', - 'reservations.toast.fileUploaded': 'File uploaded', - 'reservations.toast.uploadError': 'Failed to upload', + 'reservations.toast.filesNotUploaded': + 'The booking is saved, but some files did not upload. Save again to send them.', 'reservations.newTitle': 'New Reservation', 'reservations.bookingType': 'Booking Type', 'reservations.titleLabel': 'Title', diff --git a/shared/src/i18n/es/reservations.ts b/shared/src/i18n/es/reservations.ts index e912ef006..0cf73d9cf 100644 --- a/shared/src/i18n/es/reservations.ts +++ b/shared/src/i18n/es/reservations.ts @@ -46,8 +46,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '« {name} » y sus costes vinculados se eliminarán permanentemente.', 'reservations.toast.updated': 'Reserva actualizada', 'reservations.toast.removed': 'Reserva eliminada', - 'reservations.toast.fileUploaded': 'Archivo subido', - 'reservations.toast.uploadError': 'No se pudo subir', + 'reservations.toast.filesNotUploaded': + 'La reserva se ha guardado, pero algunos archivos no se subieron. Guarda de nuevo para enviarlos.', 'reservations.newTitle': 'Nueva reserva', 'reservations.bookingType': 'Tipo de reserva', 'reservations.titleLabel': 'Título', diff --git a/shared/src/i18n/et/reservations.ts b/shared/src/i18n/et/reservations.ts index 1c74edabf..301507a3a 100644 --- a/shared/src/i18n/et/reservations.ts +++ b/shared/src/i18n/et/reservations.ts @@ -79,8 +79,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" kustutatakse jäädavalt koos sellega seotud kuludega.', 'reservations.toast.updated': 'Broneering uuendatud', 'reservations.toast.removed': 'Broneering kustutatud', - 'reservations.toast.fileUploaded': 'Fail üles laaditud', - 'reservations.toast.uploadError': 'Üleslaadimine ebaõnnestus', + 'reservations.toast.filesNotUploaded': + 'Broneering on salvestatud, kuid mõned failid jäid üles laadimata. Salvesta uuesti, et need saata.', 'reservations.newTitle': 'Uus broneering', 'reservations.bookingType': 'Broneeringu tüüp', 'reservations.titleLabel': 'Pealkiri', diff --git a/shared/src/i18n/fr/reservations.ts b/shared/src/i18n/fr/reservations.ts index 7bf2506c7..1d40af716 100644 --- a/shared/src/i18n/fr/reservations.ts +++ b/shared/src/i18n/fr/reservations.ts @@ -79,8 +79,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '« {name} » et ses coûts liés seront définitivement supprimés.', 'reservations.toast.updated': 'Réservation mise à jour', 'reservations.toast.removed': 'Réservation supprimée', - 'reservations.toast.fileUploaded': 'Fichier importé', - 'reservations.toast.uploadError': "Échec de l'import", + 'reservations.toast.filesNotUploaded': + "La réservation est enregistrée, mais certains fichiers n'ont pas été importés. Enregistre à nouveau pour les envoyer.", 'reservations.newTitle': 'Nouvelle réservation', 'reservations.bookingType': 'Type de réservation', 'reservations.titleLabel': 'Titre', diff --git a/shared/src/i18n/gr/reservations.ts b/shared/src/i18n/gr/reservations.ts index 1ddd20ed2..befea3d53 100644 --- a/shared/src/i18n/gr/reservations.ts +++ b/shared/src/i18n/gr/reservations.ts @@ -80,8 +80,8 @@ const reservations: TranslationStrings = { 'Η κράτηση "{name}" θα διαγραφεί οριστικά μαζί με τα συνδεδεμένα έξοδα.', 'reservations.toast.updated': 'Η κράτηση ενημερώθηκε', 'reservations.toast.removed': 'Η κράτηση διαγράφηκε', - 'reservations.toast.fileUploaded': 'Το αρχείο μεταφορτώθηκε', - 'reservations.toast.uploadError': 'Η μεταφόρτωση απέτυχε', + 'reservations.toast.filesNotUploaded': + 'Η κράτηση αποθηκεύτηκε, αλλά ορισμένα αρχεία δεν μεταφορτώθηκαν. Αποθήκευσε ξανά για να σταλούν.', 'reservations.newTitle': 'Νέα Κράτηση', 'reservations.bookingType': 'Τύπος Κράτησης', 'reservations.titleLabel': 'Τίτλος', diff --git a/shared/src/i18n/hu/reservations.ts b/shared/src/i18n/hu/reservations.ts index e09fda8b4..552d273e7 100644 --- a/shared/src/i18n/hu/reservations.ts +++ b/shared/src/i18n/hu/reservations.ts @@ -79,8 +79,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" a hozzá kapcsolt költségekkel együtt véglegesen törlődik.', 'reservations.toast.updated': 'Foglalás frissítve', 'reservations.toast.removed': 'Foglalás törölve', - 'reservations.toast.fileUploaded': 'Fájl feltöltve', - 'reservations.toast.uploadError': 'Feltöltés sikertelen', + 'reservations.toast.filesNotUploaded': + 'A foglalás mentve, de néhány fájlt nem sikerült feltölteni. Mentsd újra, hogy elküldd őket.', 'reservations.newTitle': 'Új foglalás', 'reservations.bookingType': 'Foglalás típusa', 'reservations.titleLabel': 'Cím', diff --git a/shared/src/i18n/id/reservations.ts b/shared/src/i18n/id/reservations.ts index 729b8e875..2533bb552 100644 --- a/shared/src/i18n/id/reservations.ts +++ b/shared/src/i18n/id/reservations.ts @@ -78,8 +78,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" beserta biaya yang terkait akan dihapus permanen.', 'reservations.toast.updated': 'Reservasi diperbarui', 'reservations.toast.removed': 'Reservasi dihapus', - 'reservations.toast.fileUploaded': 'File diunggah', - 'reservations.toast.uploadError': 'Gagal mengunggah', + 'reservations.toast.filesNotUploaded': + 'Pemesanan sudah tersimpan, tetapi beberapa file gagal diunggah. Simpan lagi untuk mengirimnya.', 'reservations.newTitle': 'Reservasi Baru', 'reservations.bookingType': 'Jenis Pemesanan', 'reservations.titleLabel': 'Judul', diff --git a/shared/src/i18n/it/reservations.ts b/shared/src/i18n/it/reservations.ts index 4decac05f..bae652cfa 100644 --- a/shared/src/i18n/it/reservations.ts +++ b/shared/src/i18n/it/reservations.ts @@ -78,8 +78,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" e i costi collegati verranno eliminati in modo permanente.', 'reservations.toast.updated': 'Prenotazione aggiornata', 'reservations.toast.removed': 'Prenotazione eliminata', - 'reservations.toast.fileUploaded': 'File caricato', - 'reservations.toast.uploadError': 'Impossibile caricare', + 'reservations.toast.filesNotUploaded': + 'La prenotazione è salvata, ma alcuni file non sono stati caricati. Salva di nuovo per inviarli.', 'reservations.newTitle': 'Nuova prenotazione', 'reservations.bookingType': 'Tipo di prenotazione', 'reservations.titleLabel': 'Titolo', diff --git a/shared/src/i18n/ja/reservations.ts b/shared/src/i18n/ja/reservations.ts index 1fa19a6ea..89bbf1ab7 100644 --- a/shared/src/i18n/ja/reservations.ts +++ b/shared/src/i18n/ja/reservations.ts @@ -77,8 +77,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '「{name}」と紐づいた費用は完全に削除されます。', 'reservations.toast.updated': '予約を更新しました', 'reservations.toast.removed': '予約を削除しました', - 'reservations.toast.fileUploaded': 'ファイルをアップロードしました', - 'reservations.toast.uploadError': 'アップロードに失敗しました', + 'reservations.toast.filesNotUploaded': + '予約は保存されましたが、一部のファイルをアップロードできませんでした。もう一度保存すると送信されます。', 'reservations.newTitle': '新しい予約', 'reservations.bookingType': '予約タイプ', 'reservations.titleLabel': 'タイトル', diff --git a/shared/src/i18n/ko/reservations.ts b/shared/src/i18n/ko/reservations.ts index 45741652a..058d98f9f 100644 --- a/shared/src/i18n/ko/reservations.ts +++ b/shared/src/i18n/ko/reservations.ts @@ -77,8 +77,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}"과(와) 연결된 비용이 영구 삭제됩니다.', 'reservations.toast.updated': '예약이 업데이트되었습니다', 'reservations.toast.removed': '예약이 삭제되었습니다', - 'reservations.toast.fileUploaded': '파일이 업로드되었습니다', - 'reservations.toast.uploadError': '업로드 실패', + 'reservations.toast.filesNotUploaded': + '예약은 저장되었지만 일부 파일이 업로드되지 않았습니다. 다시 저장하면 전송됩니다.', 'reservations.newTitle': '새 예약', 'reservations.bookingType': '예약 유형', 'reservations.titleLabel': '제목', diff --git a/shared/src/i18n/nl/reservations.ts b/shared/src/i18n/nl/reservations.ts index b9d77dd7a..21745208f 100644 --- a/shared/src/i18n/nl/reservations.ts +++ b/shared/src/i18n/nl/reservations.ts @@ -78,8 +78,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" en de gekoppelde kosten worden permanent verwijderd.', 'reservations.toast.updated': 'Reservering bijgewerkt', 'reservations.toast.removed': 'Reservering verwijderd', - 'reservations.toast.fileUploaded': 'Bestand geüpload', - 'reservations.toast.uploadError': 'Uploaden mislukt', + 'reservations.toast.filesNotUploaded': + 'De boeking is opgeslagen, maar sommige bestanden zijn niet geüpload. Sla opnieuw op om ze te versturen.', 'reservations.newTitle': 'Nieuwe reservering', 'reservations.bookingType': 'Boekingstype', 'reservations.titleLabel': 'Titel', diff --git a/shared/src/i18n/pl/reservations.ts b/shared/src/i18n/pl/reservations.ts index a65d5ebb1..012cf297b 100644 --- a/shared/src/i18n/pl/reservations.ts +++ b/shared/src/i18n/pl/reservations.ts @@ -79,8 +79,8 @@ const reservations: TranslationStrings = { 'Rezerwacja "{name}" zostanie trwale usunięta wraz z powiązanymi kosztami.', 'reservations.toast.updated': 'Rezerwacja została zaktualizowana', 'reservations.toast.removed': 'Rezerwacja została usunięta', - 'reservations.toast.fileUploaded': 'Plik został przesłany', - 'reservations.toast.uploadError': 'Nie udało się przesłać pliku', + 'reservations.toast.filesNotUploaded': + 'Rezerwacja została zapisana, ale niektóre pliki nie zostały przesłane. Zapisz ponownie, aby je wysłać.', 'reservations.newTitle': 'Nowa rezerwacja', 'reservations.bookingType': 'Rodzaj rezerwacji', 'reservations.titleLabel': 'Tytuł', diff --git a/shared/src/i18n/ru/reservations.ts b/shared/src/i18n/ru/reservations.ts index e7008c00d..71ef11ef5 100644 --- a/shared/src/i18n/ru/reservations.ts +++ b/shared/src/i18n/ru/reservations.ts @@ -77,8 +77,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '«{name}» и связанные с ним расходы будут удалены навсегда.', 'reservations.toast.updated': 'Бронирование обновлено', 'reservations.toast.removed': 'Бронирование удалено', - 'reservations.toast.fileUploaded': 'Файл загружен', - 'reservations.toast.uploadError': 'Ошибка загрузки', + 'reservations.toast.filesNotUploaded': + 'Бронирование сохранено, но некоторые файлы не загрузились. Сохраните ещё раз, чтобы отправить их.', 'reservations.newTitle': 'Новое бронирование', 'reservations.bookingType': 'Тип бронирования', 'reservations.titleLabel': 'Название', diff --git a/shared/src/i18n/sk/reservations.ts b/shared/src/i18n/sk/reservations.ts index fe7d20980..f3156a01e 100644 --- a/shared/src/i18n/sk/reservations.ts +++ b/shared/src/i18n/sk/reservations.ts @@ -80,8 +80,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '„{name}“ bude natrvalo odstránená spolu s prepojenými nákladmi.', 'reservations.toast.updated': 'Rezervácia aktualizovaná', 'reservations.toast.removed': 'Rezervácia odstránená', - 'reservations.toast.fileUploaded': 'Súbor bol nahraný', - 'reservations.toast.uploadError': 'Nahrávanie zlyhalo', + 'reservations.toast.filesNotUploaded': + 'Rezervácia je uložená, ale niektoré súbory sa nenahrali. Ulož znova a odošli ich.', 'reservations.newTitle': 'Nová rezervácia', 'reservations.bookingType': 'Typ rezervácie', 'reservations.titleLabel': 'Názov', diff --git a/shared/src/i18n/sv/reservations.ts b/shared/src/i18n/sv/reservations.ts index 0007742b2..699dc4133 100644 --- a/shared/src/i18n/sv/reservations.ts +++ b/shared/src/i18n/sv/reservations.ts @@ -78,8 +78,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" och de kopplade kostnaderna kommer att raderas permanent.', 'reservations.toast.updated': 'Bokning uppdaterad', 'reservations.toast.removed': 'Bokning borttagen', - 'reservations.toast.fileUploaded': 'Fil uppladdad', - 'reservations.toast.uploadError': 'Det gick inte att ladda upp', + 'reservations.toast.filesNotUploaded': + 'Bokningen är sparad, men vissa filer laddades inte upp. Spara igen för att skicka dem.', 'reservations.newTitle': 'Ny bokning', 'reservations.bookingType': 'Bokningstyp', 'reservations.titleLabel': 'Titel', diff --git a/shared/src/i18n/th/reservations.ts b/shared/src/i18n/th/reservations.ts index 70f98a6b0..2a94b023e 100644 --- a/shared/src/i18n/th/reservations.ts +++ b/shared/src/i18n/th/reservations.ts @@ -79,8 +79,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" และค่าใช้จ่ายที่เชื่อมโยงไว้จะถูกลบอย่างถาวร', 'reservations.toast.updated': 'อัพเดตการจองแล้ว', 'reservations.toast.removed': 'ลบการจองแล้ว', - 'reservations.toast.fileUploaded': 'อัปโหลดไฟล์แล้ว', - 'reservations.toast.uploadError': 'ล้มเหลวในการอัปโหลด', + 'reservations.toast.filesNotUploaded': + 'บันทึกการจองแล้ว แต่บางไฟล์อัปโหลดไม่สำเร็จ บันทึกอีกครั้งเพื่อส่งไฟล์เหล่านั้น', 'reservations.newTitle': 'การจองใหม่', 'reservations.bookingType': 'ประเภทการจอง', 'reservations.titleLabel': 'ชื่อเรื่อง', diff --git a/shared/src/i18n/tr/reservations.ts b/shared/src/i18n/tr/reservations.ts index e32f1054a..dc3c581fb 100644 --- a/shared/src/i18n/tr/reservations.ts +++ b/shared/src/i18n/tr/reservations.ts @@ -78,8 +78,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" ve bağlı maliyetleri kalıcı olarak silinecek.', 'reservations.toast.updated': 'Rezervasyon güncellendi', 'reservations.toast.removed': 'Rezervasyon silindi', - 'reservations.toast.fileUploaded': 'Dosya yüklendi', - 'reservations.toast.uploadError': 'Yükleme başarısız oldu', + 'reservations.toast.filesNotUploaded': + 'Rezervasyon kaydedildi ancak bazı dosyalar yüklenemedi. Göndermek için yeniden kaydet.', 'reservations.newTitle': 'Yeni Rezervasyon', 'reservations.bookingType': 'Rezervasyon Türü', 'reservations.titleLabel': 'Başlık', diff --git a/shared/src/i18n/uk/reservations.ts b/shared/src/i18n/uk/reservations.ts index 4e80e4693..6f7ac13c5 100644 --- a/shared/src/i18n/uk/reservations.ts +++ b/shared/src/i18n/uk/reservations.ts @@ -77,8 +77,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '«{name}» і пов’язані з ним витрати буде видалено назавжди.', 'reservations.toast.updated': 'Бронювання оновлено', 'reservations.toast.removed': 'Бронювання видалено', - 'reservations.toast.fileUploaded': 'Файл завантажено', - 'reservations.toast.uploadError': 'Помилка завантаження', + 'reservations.toast.filesNotUploaded': + 'Бронювання збережено, але деякі файли не завантажилися. Збережіть ще раз, щоб надіслати їх.', 'reservations.newTitle': 'Нове бронювання', 'reservations.bookingType': 'Тип бронювання', 'reservations.titleLabel': 'Назва', diff --git a/shared/src/i18n/vi/reservations.ts b/shared/src/i18n/vi/reservations.ts index ea84f7bae..40f3ce3b7 100644 --- a/shared/src/i18n/vi/reservations.ts +++ b/shared/src/i18n/vi/reservations.ts @@ -78,8 +78,8 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" và các chi phí liên kết sẽ bị xóa vĩnh viễn.', 'reservations.toast.updated': 'Đã cập nhật đặt chỗ', 'reservations.toast.removed': 'Đã xóa đặt chỗ', - 'reservations.toast.fileUploaded': 'Tệp đã được tải lên', - 'reservations.toast.uploadError': 'Không thể tải lên', + 'reservations.toast.filesNotUploaded': + 'Đã lưu đặt chỗ, nhưng một số tệp chưa tải lên được. Hãy lưu lại để gửi chúng.', 'reservations.newTitle': 'Đặt chỗ mới', 'reservations.bookingType': 'Loại đặt chỗ', 'reservations.titleLabel': 'Tiêu đề', diff --git a/shared/src/i18n/zh-TW/reservations.ts b/shared/src/i18n/zh-TW/reservations.ts index 1059da3bc..066b055b7 100644 --- a/shared/src/i18n/zh-TW/reservations.ts +++ b/shared/src/i18n/zh-TW/reservations.ts @@ -77,8 +77,7 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" 及其關聯的費用將被永久刪除。', 'reservations.toast.updated': '預訂已更新', 'reservations.toast.removed': '預訂已刪除', - 'reservations.toast.fileUploaded': '檔案已上傳', - 'reservations.toast.uploadError': '上傳失敗', + 'reservations.toast.filesNotUploaded': '預訂已儲存,但部分檔案未能上傳。請再次儲存以傳送。', 'reservations.newTitle': '新建預訂', 'reservations.bookingType': '預訂型別', 'reservations.titleLabel': '標題', diff --git a/shared/src/i18n/zh/reservations.ts b/shared/src/i18n/zh/reservations.ts index 50ce0ecc2..4413030f4 100644 --- a/shared/src/i18n/zh/reservations.ts +++ b/shared/src/i18n/zh/reservations.ts @@ -77,8 +77,7 @@ const reservations: TranslationStrings = { 'reservations.confirm.deleteBodyWithExpense': '"{name}" 及其关联的费用将被永久删除。', 'reservations.toast.updated': '预订已更新', 'reservations.toast.removed': '预订已删除', - 'reservations.toast.fileUploaded': '文件已上传', - 'reservations.toast.uploadError': '上传失败', + 'reservations.toast.filesNotUploaded': '预订已保存,但部分文件未能上传。请再次保存以发送。', 'reservations.newTitle': '新建预订', 'reservations.bookingType': '预订类型', 'reservations.titleLabel': '标题',