mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +00:00
fix(client): make the new rollbacks roll back only what they wrote
The rollbacks this branch added were snapshot-shaped: capture the whole collection before the write, restore it on any failure. That is wrong in two ways at once. It undoes work the server already accepted when a later step is the one that fails, and it throws away whatever a collaborator's socket event applied while the requests were in flight. The day-plan reorder is the clearest case: five awaits, and a failing day-note write reverted transport positions the server had already stored. It now records only the fields it is about to overwrite, per booking, and drops each one as its request lands - so a note failure reaches the catch with nothing to undo, and a booking that arrived mid-write survives. The notification toggle had the same shape underneath: the rollback was made surgical but the request still shipped the whole matrix built from the pre-toggle render, so two overlapping toggles overwrote each other anyway. It sends the one cell that changed. The test pinned the disagreement as correct; it asserts the payload now. Photo reorder awaits allSettled rather than all, so the UI is not snapped back while the remaining writes are still landing - a partial run really does leave the server holding part of the new order, and only a total refusal justifies restoring the old one. Both the desktop editor and the mobile sheet, which was still swallowing every rejection. Also: the geolocation start guard is a run generation now, because a start issued after a stop re-sets a plain flag while the first run is still parked in the iOS permission prompt; a category rename reports once for the batch and rethrows, so the settings dialog stops closing as if it had worked; and a 404'd import job stops telling the user their file was invalid when it had simply expired. The clipboard fallback for plain-HTTP installs was pasted into three files by this branch. It is one helper now, and the two copy buttons in the members modal that still called navigator.clipboard unguarded use it too. Same for the fourth local-date helper written next to the three that already import the existing one.
This commit is contained in:
@@ -2735,6 +2735,61 @@ describe('DayPlanSidebar', () => {
|
||||
expect(stored.day_positions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-207: a rejected note write leaves the stored booking slot alone', async () => {
|
||||
const updateDayNote = vi.fn().mockRejectedValue(new Error('note write failed'))
|
||||
stubTripActions({ updateDayNote })
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
|
||||
const placeA = buildPlace({ id: 1, name: 'Place A' })
|
||||
const placeB = buildPlace({ id: 2, name: 'Place B' })
|
||||
const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: placeA })
|
||||
const a2 = buildAssignment({ id: 12, day_id: 10, order_index: 1, place: placeB })
|
||||
const note = buildDayNote({ id: 70, day_id: 10, text: 'Pack sunscreen', sort_order: 1.4 })
|
||||
const bus = buildReservation({ id: 430, type: 'bus', title: 'Airport bus', day_id: 10, day_plan_position: 1.5 })
|
||||
mockDayNotesState.dayNotes = { '10': [note] }
|
||||
seedStore(useTripStore, { reservations: [bus] })
|
||||
render(<DayPlanSidebar {...makeDefaultProps({
|
||||
days: [day], places: [placeA, placeB], assignments: { '10': [a1, a2] },
|
||||
reservations: [bus], onReorder: vi.fn(async () => undefined),
|
||||
})} />)
|
||||
fireEvent.dragStart(dragRow(screen.getByText('Place B')), { dataTransfer: emptyDataTransfer })
|
||||
fireEvent.drop(dragRow(screen.getByText('Place A')), { dataTransfer: { getData: vi.fn(() => '') } })
|
||||
|
||||
await waitFor(() => expect(mockToast.error).toHaveBeenCalledWith('note write failed'))
|
||||
// The slot write went through before the note failed, so the day must keep it.
|
||||
const stored = useTripStore.getState().reservations.find(r => r.id === 430)!
|
||||
expect(stored.day_positions).toEqual({ 10: expect.any(Number) })
|
||||
expect(stored.day_plan_position).not.toBe(1.5)
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-208: a booking that arrived mid-write survives the rollback', async () => {
|
||||
const { reservationsApi } = await import('../../api/client')
|
||||
const ferry = buildReservation({ id: 431, type: 'ferry', title: 'Island ferry', day_id: 10 })
|
||||
vi.mocked(reservationsApi.updatePositions).mockImplementationOnce(async () => {
|
||||
// Stands in for a collaborator's reservation:created event landing while the
|
||||
// slot write is still out.
|
||||
useTripStore.setState(state => ({ reservations: [...state.reservations, ferry] }))
|
||||
throw new Error('server said no')
|
||||
})
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
|
||||
const placeA = buildPlace({ id: 1, name: 'Place A' })
|
||||
const placeB = buildPlace({ id: 2, name: 'Place B' })
|
||||
const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: placeA })
|
||||
const a2 = buildAssignment({ id: 12, day_id: 10, order_index: 1, place: placeB })
|
||||
const bus = buildReservation({ id: 430, type: 'bus', title: 'Airport bus', day_id: 10, day_plan_position: 1.5 })
|
||||
seedStore(useTripStore, { reservations: [bus] })
|
||||
render(<DayPlanSidebar {...makeDefaultProps({
|
||||
days: [day], places: [placeA, placeB], assignments: { '10': [a1, a2] },
|
||||
reservations: [bus], onReorder: vi.fn(async () => undefined),
|
||||
})} />)
|
||||
fireEvent.dragStart(dragRow(screen.getByText('Place B')), { dataTransfer: emptyDataTransfer })
|
||||
fireEvent.drop(dragRow(screen.getByText('Place A')), { dataTransfer: { getData: vi.fn(() => '') } })
|
||||
|
||||
await waitFor(() => expect(mockToast.error).toHaveBeenCalledWith('server said no'))
|
||||
const stored = useTripStore.getState().reservations
|
||||
expect(stored.find(r => r.id === 430)!.day_plan_position).toBe(1.5)
|
||||
expect(stored.find(r => r.id === 431)).toBeDefined()
|
||||
})
|
||||
|
||||
it('FE-PLANNER-DAYPLAN-126: reordering around a multi-leg flight writes a position per leg', async () => {
|
||||
const updateReservation = vi.fn(async () => ({} as Reservation))
|
||||
stubTripActions({ updateReservation })
|
||||
|
||||
@@ -689,9 +689,25 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
const applyMergedOrder = async (dayId: number, newOrder: { type: string; data: any }[]) => {
|
||||
// Capture previous place order for undo
|
||||
const prevAssignmentIds = getDayAssignments(dayId).map(a => a.id)
|
||||
// …and the reservations as they stand, so a failed write can put the visible
|
||||
// order back instead of leaving a phantom one behind the error toast.
|
||||
const prevReservations = useTripStore.getState().reservations
|
||||
// …and, per booking, the fields this call is about to overwrite, so a failed write
|
||||
// can put the visible order back instead of leaving a phantom one behind the error
|
||||
// toast. Restoring the whole array instead would also drop what a collaborator's
|
||||
// socket event applied while the requests were in flight.
|
||||
const pendingRollback: (Partial<Reservation> & { id: number })[] = []
|
||||
const dropRollback = (id: number) => {
|
||||
const i = pendingRollback.findIndex(p => p.id === id)
|
||||
if (i >= 0) pendingRollback.splice(i, 1)
|
||||
}
|
||||
const rollBackReservations = () => {
|
||||
if (!pendingRollback.length) return
|
||||
useTripStore.setState(state => ({
|
||||
reservations: state.reservations.map(r => {
|
||||
const p = pendingRollback.find(x => x.id === r.id)
|
||||
return p ? { ...r, ...p } : r
|
||||
})
|
||||
}))
|
||||
setTransportPosVersion(v => v + 1)
|
||||
}
|
||||
|
||||
// Places get sequential integer positions (0, 1, 2, ...)
|
||||
// Non-place items between place N-1 and place N get fractional positions
|
||||
@@ -733,6 +749,10 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
// Update transport positions in store FIRST so the useEffect triggered by
|
||||
// onReorder's optimistic assignment update reads the correct positions.
|
||||
if (transportUpdates.length) {
|
||||
for (const tu of transportUpdates) {
|
||||
const r = useTripStore.getState().reservations.find(x => x.id === tu.id)
|
||||
if (r) pendingRollback.push({ id: r.id, day_plan_position: r.day_plan_position, day_positions: r.day_positions })
|
||||
}
|
||||
useTripStore.setState(state => ({
|
||||
reservations: state.reservations.map(r => {
|
||||
const tu = transportUpdates.find(u => u.id === r.id)
|
||||
@@ -762,8 +782,11 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
// here double-encodes it on the server, which wipes metadata.legs on read
|
||||
// and collapses the flight back to a single span.
|
||||
const newMeta = { ...parsed, legs }
|
||||
pendingRollback.push({ id: rid, metadata: r.metadata })
|
||||
useTripStore.setState(state => ({ reservations: state.reservations.map(x => (x.id === rid ? { ...x, metadata: newMeta } : x)) }))
|
||||
await tripActions.updateReservation(tripId, rid, { metadata: newMeta })
|
||||
// Stored, so a later step failing must not put the old legs back.
|
||||
dropRollback(rid)
|
||||
}
|
||||
setTransportPosVersion(v => v + 1)
|
||||
}
|
||||
@@ -771,6 +794,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
if (transportUpdates.length) {
|
||||
onRouteRefresh?.()
|
||||
await reservationsApi.updatePositions(tripId, transportUpdates, dayId)
|
||||
for (const tu of transportUpdates) dropRollback(tu.id)
|
||||
}
|
||||
for (const n of noteUpdates) {
|
||||
await tripActions.updateDayNote(tripId, dayId, n.id, { sort_order: n.sort_order })
|
||||
@@ -783,8 +807,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
})
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
useTripStore.setState({ reservations: prevReservations })
|
||||
setTransportPosVersion(v => v + 1)
|
||||
rollBackReservations()
|
||||
toast.error(err instanceof Error ? err.message : t('common.unknownError'))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user