fix(roadtrip): keep the stay on each visit, not on the place (#3092)

A nullable day_assignments.stay_minutes holds the stay of one visit; a visit without one keeps reading the place's duration, so existing trips drive as before. REST PUT /trips/:tripId/assignments/:id/stay and the MCP tool set_assignment_stay write it with day_edit.
This commit is contained in:
Maurice
2026-11-14 17:48:57 +01:00
parent 535761dbd5
commit bac4599d64
40 changed files with 510 additions and 96 deletions
+8
View File
@@ -0,0 +1,8 @@
import { assignmentSchema, type AssignmentStayRequest } from '@trek/shared';
import { apiClient } from './client';
/** How long the drive stands at one visit (#3092); null hands it back to the place's stay. */
export async function saveAssignmentStay(tripId: number | string, id: number, body: AssignmentStayRequest) {
const saved = await apiClient.put(`/trips/${tripId}/assignments/${id}/stay`, body);
return assignmentSchema.parse(saved.data.assignment);
}
@@ -60,7 +60,7 @@ export function stopSpan(assignment: Assignment): DaySpan | null {
if (start === null) return null;
const end = clockMinutes(assignment.assignment_end_time ?? assignment.place.end_time);
if (end !== null && end > start) return { start, end };
const duration = assignment.place.duration_minutes ?? 0;
const duration = assignment.stay_minutes ?? assignment.place.duration_minutes ?? 0;
return { start, end: duration > 0 ? Math.min(start + duration, MINUTES_PER_DAY) : null };
}
@@ -3,6 +3,7 @@ import type { AssistantChangeEffect } from '@trek/shared';
import { dayPoints, type LatLng } from '../../store/assistantMapModel';
import type { Assignment, AssignmentsMap, Place } from '../../types';
import { haversineKm } from '../../utils/geo';
import { stayOf } from '../Roadtrip/stayReading';
/**
* A day as it would read once the waiting changes of a card ran: the stops it
@@ -91,7 +92,7 @@ function draftOf(visit: Assignment, status: StopStatus, toolCallId: string | nul
const time = visit.assignment_time ?? place?.place_time ?? null;
const start = minutesOf(time);
const explicitEnd = minutesOf(visit.assignment_end_time ?? place?.end_time ?? null);
const duration = place?.duration_minutes;
const duration = stayOf(visit);
const end = explicitEnd ?? (start !== null && typeof duration === 'number' && duration > 0 ? start + duration : null);
return {
stop: { key, name: place?.name ?? '', status, toolCallId, time: start === null ? null : time },
@@ -105,7 +105,7 @@ describe('RoadtripStayModal', () => {
fireEvent.change(slider(), { target: { value: '45' } })
fireEvent.click(screen.getByRole('button', { name: /^save$/i }))
await waitFor(() => expect(onSave).toHaveBeenCalledWith(9, 45))
await waitFor(() => expect(onSave).toHaveBeenCalledWith(9, 45, undefined))
await waitFor(() => expect(onClose).toHaveBeenCalled())
})
@@ -116,7 +116,7 @@ describe('RoadtripStayModal', () => {
fireEvent.click(screen.getByRole('button', { name: /no stay|none/i }))
await waitFor(() => expect(onSave).toHaveBeenCalledWith(9, 0))
await waitFor(() => expect(onSave).toHaveBeenCalledWith(9, 0, undefined))
expect(onSave.mock.calls[0][1]).not.toBeNull()
})
@@ -29,8 +29,11 @@ export interface StayDraft {
interface RoadtripStayModalProps {
stop: StayDraft | null
onClose: () => void
/** Zero clears it: the rail reads "no stay" and "nothing planned" as the same thing. */
onSave: (placeId: number, minutes: number) => Promise<void> | void
/**
* Zero clears it: the rail reads "no stay" and "nothing planned" as the same thing.
* The visit rides along, so the stay lands on it and not on every visit of the place.
*/
onSave: (placeId: number, minutes: number, assignmentId?: number) => Promise<void> | void
}
/** The round minus and plus beside the number. */
@@ -59,10 +62,11 @@ const SLIDER = [
* question the number is actually being chosen for: given when the drive arrives, when
* does it leave again. Typing minutes into a box could never show that.
*
* The value is `places.duration_minutes`, which the schedule has read for years and
* nothing has ever been able to write. Cleared as a zero rather than a null, because the
* update statement folds a null into "leave it alone" — a null could give a stop a stay
* but never take one away.
* The value is the visit's own stay (`day_assignments.stay_minutes`, #3092), so two
* visits of one place can last differently; a stop without a saved visit writes the
* place's `duration_minutes`, which a visit without a stay of its own reads. Cleared as a
* zero rather than a null, because a null would hand the visit back to the place's stay
* instead of taking the stay away.
*/
export default function RoadtripStayModal({ stop, onClose, onSave }: RoadtripStayModalProps): React.ReactElement | null {
const { t } = useTranslation()
@@ -86,7 +90,7 @@ export default function RoadtripStayModal({ stop, onClose, onSave }: RoadtripSta
if (saving) return
setSaving(true)
try {
await onSave(stop.placeId, value)
await onSave(stop.placeId, value, stop.assignmentId)
onClose()
} finally {
setSaving(false)
@@ -29,7 +29,8 @@ import type { RoadtripStopType } from '@trek/shared'
// from the one table in stopKinds.ts.
export interface RoadtripStopDraft {
editing?: { placeId: number; dwellMinutes: number; stopType: RoadtripStopType | null; accommodationId?: number; checkIn?: string; checkOut?: string }
/** `assignmentId` is the visit being edited: its stay is its own, not every visit's of the place (#3092). */
editing?: { placeId: number; assignmentId?: number; dwellMinutes: number; stopType: RoadtripStopType | null; accommodationId?: number; checkIn?: string; checkOut?: string }
arrivalTime?: string | null
poi: CorridorPoi
dayId: number
+16 -4
View File
@@ -2,15 +2,27 @@ import { formatClock, parseClock, type ScheduleEntry } from './roadtripModel'
import type { RoadtripDay, RoadtripStop } from '@trek/shared/roadtrip'
import type { StayDraft } from './RoadtripStayModal'
import type { RoadtripStayControl } from './VisitControls'
import type { Assignment } from '../../types'
/**
* How long the drive stands at one visit: its own stay (#3092), else the one its place
* carries. A place planned twice can be stopped at once and only driven past the other
* time, and a visit nobody gave a length keeps reading the place, as every visit did
* before the stay moved onto it.
*/
export function stayOf(a: Pick<Assignment, 'stay_minutes' | 'place'>): number | null {
if (typeof a.stay_minutes === 'number') return a.stay_minutes
return typeof a.place?.duration_minutes === 'number' ? a.place.duration_minutes : null
}
/**
* How long a stop is stood at, the way a stay badge shows it.
*
* For most stops that is the stay the place carries. A stop with a time set to leave it
* is stood at from whenever the drive gets there until that time, so its stay is what
* For most stops that is the stay of the visit (`stayOf`). A stop with a time set to leave
* it is stood at from whenever the drive gets there until that time, so its stay is what
* the schedule made of it and `until` says when it ends. The number is read here and
* never written back to the place: the stay belongs to the place, the end time to one
* visit of it, and a stored copy would be wrong the moment the arrival moved.
* never written back: the end time decides it, and a stored copy would be wrong the
* moment the arrival moved.
*/
export interface StayReading {
minutes: number | null
@@ -5,6 +5,7 @@ import { avoidedClasses, calculateRouteWithLegs, routeEngineFor, RoutingRefusedE
import { resolveLegMode } from '../Planner/legMode'
import { splitIntoRuns, parseAvoid, type DriveLimits } from './roadtripModel'
import { spillChains } from './nightSpill'
import { stayOf } from './stayReading'
import { useSettingsStore } from '../../store/settingsStore'
import { useTripStore } from '../../store/tripStore'
import { useVehicleRange } from './useVehicleRange'
@@ -201,7 +202,7 @@ const asStop = (a: Assignment, ownerDayId: number, ownerIndex: number, accommoda
checkInTime: stay?.check_in ?? null,
night: stay !== undefined,
bookedNightId: a.accommodation_id ?? null,
dwellMinutes: typeof p.duration_minutes === 'number' ? p.duration_minutes : null,
dwellMinutes: stayOf(a),
endDay: a.end_day === true,
legMode: a.leg_transport_mode ?? null,
incomingLegMode: a.incoming_leg_transport_mode ?? null,
@@ -31,10 +31,10 @@ interface RtStaySheetPayload {
* How long the traveller stays at one stop, on the phone ('rtstay', payload
* { placeId, minutes, name }).
*
* Writes `places.duration_minutes` through `planner.setRoadtripStay`, which is the same
* single write the desktop dialog makes. Zero rather than null clears it: the update
* statement folds a null into "leave it alone", so a null could give a stop a stay but
* never take one away.
* Writes the stay of the visit it was opened on through `planner.setRoadtripStay`, which
* is the same single write the desktop dialog makes, so two visits of one place keep
* their own lengths (#3092). Zero rather than null clears it: a null would hand the visit
* back to the place's stay instead of taking the stay away.
*
* Two things this sheet deliberately does not do:
*
@@ -51,7 +51,9 @@ export default function MRtStaySheet({ planner, shell }: MTripSheetsProps) {
const open = shell.sheet?.id === 'rtstay'
const payload = (shell.sheet?.payload ?? {}) as RtStaySheetPayload
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
const canEdit = planner.can('place_edit', planner.trip)
// A visit's stay is part of the day plan; only a stop with no saved visit writes the place.
const onVisit = typeof payload.assignmentId === 'number' && payload.assignmentId > 0
const canEdit = planner.can(onVisit ? 'day_edit' : 'place_edit', planner.trip)
// Hold the last payload so the name and the number survive the exit animation
// instead of blinking out while the sheet slides away.
@@ -124,7 +126,7 @@ export default function MRtStaySheet({ planner, shell }: MTripSheetsProps) {
const value = minutes
setSaving(true)
try {
await planner.setRoadtripStay(placeId, value)
await planner.setRoadtripStay(placeId, value, stop?.assignmentId)
// 'rtstop' is located by day and assignment, not by place: spreading this sheet's own
// payload into it opened a sheet that resolved to nothing, drew nothing, and still
// counted as open, which blocks the day swipe until something else closes it.
+6 -1
View File
@@ -87,6 +87,8 @@ export interface PlaceVisit {
endTime: string | null;
notes: string | null;
endDay: boolean;
/** The visit's own stay (#3092), or null where it read the place's. */
stayMinutes: number | null;
routeExcluded: boolean;
legMode: string | null;
incomingLegMode: string | null;
@@ -103,6 +105,7 @@ export function visitOf(dayId: number, a: Assignment): PlaceVisit {
endTime: a.assignment_end_time ?? null,
notes: a.notes ?? null,
endDay: a.end_day === true,
stayMinutes: a.stay_minutes ?? null,
routeExcluded: a.route_excluded === true,
legMode: a.leg_transport_mode ?? null,
incomingLegMode: a.incoming_leg_transport_mode ?? null,
@@ -123,6 +126,7 @@ export type RestoreActions = Pick<
| 'setAssignmentTimes'
| 'setAssignmentNotes'
| 'setAssignmentEndDay'
| 'setAssignmentStay'
| 'setAssignmentRouteExcluded'
| 'setAssignmentParticipants'
| 'setAssignmentLegMode'
@@ -153,7 +157,7 @@ export async function restorePlace(
return restored;
}
/** Gives a visit planned again the times, note, end of day, travellers and legs it had. */
/** Gives a visit planned again the times, note, end of day, stay, travellers and legs it had. */
export async function restoreVisit(
tripId: number | string,
actions: Omit<RestoreActions, 'addPlace' | 'assignPlaceToDay' | 'ratePlace'>,
@@ -166,6 +170,7 @@ export async function restoreVisit(
}
if (visit.notes) await actions.setAssignmentNotes(tripId, dayId, assignmentId, visit.notes);
if (visit.endDay) await actions.setAssignmentEndDay(tripId, dayId, assignmentId, true);
if (visit.stayMinutes !== null) await actions.setAssignmentStay(tripId, dayId, assignmentId, visit.stayMinutes);
if (visit.routeExcluded) await actions.setAssignmentRouteExcluded(tripId, dayId, assignmentId, true);
if (visit.participantIds.length > 0)
await actions.setAssignmentParticipants(tripId, dayId, assignmentId, visit.participantIds);
@@ -306,7 +306,7 @@ export function usePlaceFormOpeners(options: PlaceFormOpenersOptions) {
setStopDraft({
poi: { osm_id: place.osm_id ?? '', name: place.name, lat: place.lat, lng: place.lng, category, poi_type: category, address: place.address ?? null, website: place.website ?? null, phone: place.phone ?? null, opening_hours: null, cuisine: null, source: 'trek', offRouteKm: 0, alongKm: 0 },
arrivalTime, dayId, dayNumber: days.find(day => day.id === dayId)?.day_number ?? 0, position: visit.order_index ?? 0,
editing: { placeId: place.id, stopType: place.stop_type ?? (stay ? 'hotel' : null), dwellMinutes: place.duration_minutes ?? 30, accommodationId: stay?.id, checkIn: stay?.check_in ?? '', checkOut: stay?.check_out ?? '' },
editing: { placeId: place.id, assignmentId: visit.id, stopType: place.stop_type ?? (stay ? 'hotel' : null), dwellMinutes: visit.stay_minutes ?? place.duration_minutes ?? 30, accommodationId: stay?.id, checkIn: stay?.check_in ?? '', checkOut: stay?.check_out ?? '' },
...(isOvernightCategory(category) ? { overnight: { ...overnightOptions(dayId), ...(stay ? { defaultEndDayId: stay.end_day_id } : {}) } } : {}),
})
return
@@ -1,4 +1,4 @@
// FE-TP-STOPEDITS-001 to FE-TP-STOPEDITS-016
// FE-TP-STOPEDITS-001 to FE-TP-STOPEDITS-018
//
// Edits to one stop on the drive, driven straight through useRoadtripStopEdits. The
// stop popup's draft and the stay release question are real state in the harness, so
@@ -8,6 +8,7 @@ import { act, renderHook } from '@testing-library/react'
import { accommodationsApi } from '../../api/client'
import type { RoadtripStopDraft } from '../../components/Roadtrip/RoadtripStopPopup'
import { reanchorAfterInsert, reanchorAfterRemove, reanchorAfterReorder } from '../../components/Roadtrip/roadtripModel'
import { stayOf } from '../../components/Roadtrip/stayReading'
import type { CorridorPoi } from '../../components/Roadtrip/useCorridorPois'
import type { RoadtripStop } from '../../components/Roadtrip/useRoadtripRoutes'
import { useTripStore, type TripStoreState } from '../../store/tripStore'
@@ -17,6 +18,7 @@ import type { Accommodation, AssignmentsMap } from '../../types'
import type { Can, Translate } from './plannerTypes'
import type { PlannerDialogs } from './usePlannerDialogs'
import type { RoadtripFeed } from './useRoadtripFeed'
import { assignmentRepo } from '../../repo/assignmentRepo'
import { useRoadtripStopEdits } from './useRoadtripStopEdits'
type Options = Parameters<typeof useRoadtripStopEdits>[0]
@@ -485,4 +487,47 @@ describe('useRoadtripStopEdits', () => {
'common.unknownError', 'common.unknownError',
])
})
// #3092: the same place planned twice on a day, once to stop and once only to steer the
// route past it. The stay belongs to the visit, so changing one leaves the other alone.
describe('a stay per visit', () => {
const viewpoint = buildPlace({ id: 70, lat: 50, lng: 13, duration_minutes: 45 })
const twice: AssignmentsMap = {
5: [
buildAssignment({ id: 51, day_id: 5, place: viewpoint, place_id: 70, order_index: 0 }),
buildAssignment({ id: 52, day_id: 5, place: viewpoint, place_id: 70, order_index: 1 }),
],
}
const seed = () => {
useTripStore.setState({ assignments: twice })
vi.spyOn(assignmentRepo, 'setStay').mockImplementation(async (_tripId, visit, minutes) => ({ ...visit, stay_minutes: minutes }))
return { ...useTripStore.getState(), ...actions, setAssignmentStay: useTripStore.getState().setAssignmentStay } as unknown as TripStoreState
}
it('FE-TP-STOPEDITS-017: the stay dialog changes one visit of a place and leaves the other visit of it alone', async () => {
const tripActions = seed()
const { result } = renderEdits(null, { tripActions, assignments: twice })
await act(async () => { await result.current.setRoadtripStay(70, 0, 52) })
expect(actions.updatePlace).not.toHaveBeenCalled()
expect(assignmentRepo.setStay).toHaveBeenCalledWith(42, expect.objectContaining({ id: 52 }), 0)
const [first, second] = useTripStore.getState().assignments['5']
expect(stayOf(first)).toBe(45)
expect(stayOf(second)).toBe(0)
})
it('FE-TP-STOPEDITS-018: the stop popup writes the kind on the place and the stay on the visit it was opened on', async () => {
const tripActions = seed()
const editing = { placeId: 70, assignmentId: 51, dwellMinutes: 45, stopType: null }
const { result } = renderEdits({ poi: hit(), dayId: 5, position: 0, dayNumber: 5, editing }, { tripActions, assignments: twice })
await act(async () => { await result.current.saveStopDraft({ stopType: 'rest_area', dwellMinutes: 90 }) })
expect(actions.updatePlace).toHaveBeenCalledWith(42, 70, { stop_type: 'rest_area' })
const [first, second] = useTripStore.getState().assignments['5']
expect(stayOf(first)).toBe(90)
expect(stayOf(second)).toBe(45)
})
})
})
@@ -24,6 +24,40 @@ interface RoadtripStopEditsOptions
updateRouteForDay: ReturnType<typeof useRouteCalculation>['updateRouteForDay']
}
/**
* The day a saved visit is stored on, or null for none: no visit named, the optimistic
* row of one still being saved (a negative id the server never issued), or one no longer
* planned. A stay is written onto such a visit (#3092); without one it falls back to the
* place.
*/
function savedVisitDayOf(assignments: TripStoreState['assignments'], assignmentId: number | undefined): number | null {
if (assignmentId == null || assignmentId <= 0) return null
const day = Object.entries(assignments).find(([, visits]) => visits.some(visit => visit.id === assignmentId))
return day ? Number(day[0]) : null
}
/**
* Saves the stop popup over a stop already on the drive. The kind is the place's, the stay
* the visit's (#3092): a place planned twice keeps a stay per visit, so the popup on one
* of them leaves the other one's alone. A stop with no saved visit writes both onto the
* place, as before.
*/
async function writeEditedStop(
tripActions: TripStoreState,
tripId: PlannerBase['tripId'],
assignments: TripStoreState['assignments'],
{ placeId, assignmentId }: { placeId: number; assignmentId?: number },
{ stopType, dwellMinutes }: { stopType: RoadtripStopType | null; dwellMinutes: number },
): Promise<void> {
const visitDayId = savedVisitDayOf(assignments, assignmentId)
if (assignmentId == null || visitDayId === null) {
await tripActions.updatePlace(tripId, placeId, { stop_type: stopType, duration_minutes: dwellMinutes })
return
}
await tripActions.updatePlace(tripId, placeId, { stop_type: stopType })
await tripActions.setAssignmentStay(tripId, visitDayId, assignmentId, dwellMinutes)
}
/**
* Edits to one stop on the drive: saving the stop popup as a pause or as a night,
* releasing a booked night, the kind, fill and stay of a stop, moving it within its day
@@ -63,7 +97,7 @@ export function useRoadtripStopEdits(options: RoadtripStopEditsOptions) {
}
try {
if (stopDraft.editing) {
await tripActions.updatePlace(tripId, stopDraft.editing.placeId, { stop_type: stopType, duration_minutes: dwellMinutes })
await writeEditedStop(tripActions, tripId, assignments, stopDraft.editing, { stopType, dwellMinutes })
if (accommodationId) {
// The night is what was switched off, not the stop: it stays where it is
// in the drive and becomes an ordinary pause.
@@ -106,7 +140,7 @@ export function useRoadtripStopEdits(options: RoadtripStopEditsOptions) {
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : t('common.unknownError'))
}
}, [stopDraft, tripId, tripActions, updateRouteForDay, toast, t, roadtripVias, viaLiesBefore, loadAccommodations, tripAccommodations, reservations, setStayRelease, setStopDraft])
}, [stopDraft, tripId, tripActions, updateRouteForDay, toast, t, roadtripVias, viaLiesBefore, loadAccommodations, tripAccommodations, reservations, setStayRelease, setStopDraft, assignments])
/** The yes to the question above: the same save, this time allowed to drop the night. */
const confirmStayRelease = useCallback(async () => {
@@ -315,22 +349,32 @@ export function useRoadtripStopEdits(options: RoadtripStopEditsOptions) {
/**
* How long the traveller stays at one stop.
*
* Writes `places.duration_minutes`, which the schedule has read since it was written
* and which nothing in TREK has ever been able to set: the road trip is the only place
* the value means anything, so it is the only place that edits it.
* The stay belongs to the visit (#3092): the same place planned twice on a day can be
* stopped at once and only driven past the other time, so a stop the rail names by its
* assignment writes `day_assignments.stay_minutes` and leaves the place and its other
* visits alone. Only a stop without a saved visit of its own (no assignment, or the
* optimistic row of one still on its way) falls back to the place's
* `duration_minutes`, which every visit without a stay of its own reads.
*
* Zero rather than null to clear: the update statement folds a null into "leave it
* alone" (`COALESCE(?, duration_minutes)`), so a null could give a stop a stay but
* never take one away. The rail reads zero and absent as the same thing.
* Zero rather than null to clear: on the place the update statement folds a null into
* "leave it alone" (`COALESCE(?, duration_minutes)`), and on a visit a null would hand
* it back to the place's stay instead of taking the stay away. The rail reads zero and
* absent as the same thing.
*/
const setRoadtripStay = useCallback(async (placeId: number, minutes: number) => {
if (!can('place_edit', trip)) return
const setRoadtripStay = useCallback(async (placeId: number, minutes: number, assignmentId?: number) => {
const visitDayId = savedVisitDayOf(assignments, assignmentId)
try {
if (assignmentId != null && visitDayId !== null) {
if (!can('day_edit', trip)) return
await tripActions.setAssignmentStay(tripId, visitDayId, assignmentId, minutes)
return
}
if (!can('place_edit', trip)) return
await tripActions.updatePlace(tripId, placeId, { duration_minutes: minutes })
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : t('common.unknownError'))
}
}, [tripId, tripActions, toast, t, can, trip])
}, [assignments, tripId, tripActions, toast, t, can, trip])
/**
* Moves a stop onto another day, from the road trip rail.
+20
View File
@@ -3,12 +3,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { assignmentRepo } from './assignmentRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { saveAssignmentEndDay } from '../api/assignmentEndDay'
import { saveAssignmentStay } from '../api/assignmentStay'
import { isEffectivelyOffline } from '../sync/networkMode'
import { mutationQueue } from '../sync/mutationQueue'
import { apiClient, assignmentsApi } from '../api/client'
import type { Assignment, Day } from '../types'
vi.mock('../api/assignmentEndDay', () => ({ saveAssignmentEndDay: vi.fn() }))
vi.mock('../api/assignmentStay', () => ({ saveAssignmentStay: vi.fn() }))
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => true) }))
vi.mock('../sync/authGate', () => ({ isAuthed: () => true }))
vi.mock('../api/client', () => ({ apiClient: { request: vi.fn() }, assignmentsApi: { updateTime: vi.fn(), updateNotes: vi.fn(), clearDay: vi.fn() } }))
@@ -51,6 +53,24 @@ describe('assignment day-end persistence', () => {
})
})
describe('assignment stay persistence (#3092)', () => {
it('stores the stay on the one visit offline with a replayable write', async () => {
await assignmentRepo.setStay(9, assignment, 0)
expect((await offlineDb.days.get(1))?.assignments?.[0]).toMatchObject({ id: 7, stay_minutes: 0 })
expect(await offlineDb.mutationQueue.toArray()).toEqual([expect.objectContaining({
url: '/trips/9/assignments/7/stay', method: 'PUT', body: { stay_minutes: 0 }, resource: 'assignments', entityId: 7,
})])
})
it('saves through the online API and caches what came back', async () => {
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
vi.mocked(saveAssignmentStay).mockResolvedValue({ ...assignment, stay_minutes: 20 })
await assignmentRepo.setStay(9, assignment, 20)
expect(saveAssignmentStay).toHaveBeenCalledWith(9, 7, { stay_minutes: 20 })
expect((await offlineDb.days.get(1))?.assignments?.[0].stay_minutes).toBe(20)
})
})
describe('assignment time persistence', () => {
const times = { place_time: '07:00', end_time: null }
+46 -30
View File
@@ -1,5 +1,6 @@
import { assignmentSchema } from '@trek/shared'
import { saveAssignmentEndDay } from '../api/assignmentEndDay'
import { saveAssignmentStay } from '../api/assignmentStay'
import { assignmentsApi } from '../api/client'
import { offlineDb } from '../db/offlineDb'
import { cacheAssignment } from '../db/cacheAssignment'
@@ -32,6 +33,34 @@ async function cacheVisitFields(tripId: number, id: number, fields: Partial<Assi
}
/** The day's visits in the order given; the ones not named keep their place behind them. */
/**
* One field of a saved visit, written through its own route: sent straight away when
* nothing older to the visit waits in the queue, otherwise queued behind it with the
* cached row patched, so the planner shows the change offline as well.
*/
async function writeVisitField(
tripId: number | string,
assignment: Assignment,
write: { suffix: string; body: Record<string, unknown>; fields: Partial<Assignment>; send: () => Promise<Assignment> },
): Promise<Assignment> {
if (!(await mutationQueue.mustQueue('assignments', assignment.id))) {
const saved = await write.send()
await cacheAssignment(saved)
return saved
}
const updated = { ...assignment, ...write.fields }
await offlineDb.transaction('rw', offlineDb.days, offlineDb.mutationQueue, async () => {
await mutationQueue.enqueue({
id: generateUUID(), tripId: Number(tripId), method: 'PUT',
url: `/trips/${tripId}/assignments/${assignment.id}/${write.suffix}`,
body: write.body, resource: 'assignments', entityId: assignment.id,
})
await cacheAssignment(updated)
})
mutationQueue.sendSoon()
return updated
}
function inOrder(items: Assignment[], orderedIds: number[]): Assignment[] {
const rank = new Map(orderedIds.map((id, index) => [id, index]))
return items
@@ -237,42 +266,29 @@ export const assignmentRepo = {
},
async setEndDay(tripId: number | string, assignment: Assignment, endDay: boolean): Promise<Assignment> {
if (!(await mutationQueue.mustQueue('assignments', assignment.id))) {
const saved = await saveAssignmentEndDay(tripId, assignment.id, { end_day: endDay })
await cacheAssignment(saved)
return saved
}
const updated = { ...assignment, end_day: endDay }
await offlineDb.transaction('rw', offlineDb.days, offlineDb.mutationQueue, async () => {
await mutationQueue.enqueue({
id: generateUUID(), tripId: Number(tripId), method: 'PUT',
url: `/trips/${tripId}/assignments/${assignment.id}/end-day`,
body: { end_day: endDay }, resource: 'assignments', entityId: assignment.id,
})
await cacheAssignment(updated)
return await writeVisitField(tripId, assignment, {
suffix: 'end-day', body: { end_day: endDay }, fields: { end_day: endDay },
send: () => saveAssignmentEndDay(tripId, assignment.id, { end_day: endDay }),
})
},
/**
* How long the drive stands at this one visit (#3092), offline too. Null hands the
* visit back to the stay its place carries.
*/
async setStay(tripId: number | string, assignment: Assignment, stayMinutes: number | null): Promise<Assignment> {
return await writeVisitField(tripId, assignment, {
suffix: 'stay', body: { stay_minutes: stayMinutes }, fields: { stay_minutes: stayMinutes },
send: () => saveAssignmentStay(tripId, assignment.id, { stay_minutes: stayMinutes }),
})
mutationQueue.sendSoon()
return updated
},
/** Takes a stop out of the day's route or puts it back (#2532), offline too. */
async setRouteExcluded(tripId: number | string, assignment: Assignment, excluded: boolean): Promise<Assignment> {
if (!(await mutationQueue.mustQueue('assignments', assignment.id))) {
const saved = assignmentSchema.parse((await assignmentsApi.setRouteExcluded(tripId, assignment.id, excluded)).assignment)
await cacheAssignment(saved)
return saved
}
const updated = { ...assignment, route_excluded: excluded }
await offlineDb.transaction('rw', offlineDb.days, offlineDb.mutationQueue, async () => {
await mutationQueue.enqueue({
id: generateUUID(), tripId: Number(tripId), method: 'PUT',
url: `/trips/${tripId}/assignments/${assignment.id}/route`,
body: { excluded }, resource: 'assignments', entityId: assignment.id,
})
await cacheAssignment(updated)
return await writeVisitField(tripId, assignment, {
suffix: 'route', body: { excluded }, fields: { route_excluded: excluded },
send: async () => assignmentSchema.parse((await assignmentsApi.setRouteExcluded(tripId, assignment.id, excluded)).assignment),
})
mutationQueue.sendSoon()
return updated
},
/**
+42 -15
View File
@@ -11,6 +11,8 @@ type GetState = StoreApi<TripStoreState>['getState']
export interface AssignmentsSlice {
setAssignmentEndDay: (tripId: number | string, dayId: number, assignmentId: number, endDay: boolean) => Promise<void>
/** The stay of one visit (#3092); null reads the place's duration_minutes again. */
setAssignmentStay: (tripId: number | string, dayId: number, assignmentId: number, stayMinutes: number | null) => Promise<void>
setAssignmentRouteExcluded: (tripId: number | string, dayId: number, assignmentId: number, excluded: boolean) => Promise<void>
setAssignmentTimes: (tripId: number | string, dayId: number, assignmentId: number, times: AssignmentTimes) => Promise<void>
setAssignmentNotes: (tripId: number | string, dayId: number, assignmentId: number, notes: string | null) => Promise<void>
@@ -25,6 +27,38 @@ export interface AssignmentsSlice {
setAssignments: (assignments: AssignmentsMap) => void
}
/**
* One field of a saved visit on its day, written optimistically: shown at once, settled
* on what the save answers, and put back when the save is refused. `read` is how the
* field is read off a row, so an absent value settles the same way every time.
*/
async function writeVisitField<K extends keyof Assignment>(
set: SetState,
get: GetState,
{ dayId, assignmentId, field, value, read, save }: {
dayId: number
assignmentId: number
field: K
value: Assignment[K]
read: (a: Assignment) => Assignment[K]
save: (assignment: Assignment) => Promise<Assignment>
},
): Promise<void> {
const key = String(dayId)
const assignment = get().assignments[key]?.find(a => a.id === assignmentId)
if (!assignment || assignmentId < 0) return
const apply = (next: Assignment[K]) => set(state => ({
assignments: { ...state.assignments, [key]: (state.assignments[key] || []).map(a => a.id === assignmentId ? { ...a, [field]: next } : a) },
}))
apply(value)
try {
apply(read(await save(assignment)))
} catch (err: unknown) {
apply(read(assignment))
throw err
}
}
export const createAssignmentsSlice = (set: SetState, get: GetState): AssignmentsSlice => ({
setAssignmentEndDay: async (tripId, dayId, assignmentId, endDay) => {
const assignment = get().assignments[String(dayId)]?.find(a => a.id === assignmentId)
@@ -43,21 +77,14 @@ export const createAssignmentsSlice = (set: SetState, get: GetState): Assignment
throw err
}
},
setAssignmentRouteExcluded: async (tripId, dayId, assignmentId, excluded) => {
const assignment = get().assignments[String(dayId)]?.find(a => a.id === assignmentId)
if (!assignment || assignmentId < 0) return
const apply = (value: boolean) => set(state => ({
assignments: { ...state.assignments, [String(dayId)]: (state.assignments[String(dayId)] || []).map(a => a.id === assignmentId ? { ...a, route_excluded: value } : a) },
}))
apply(excluded)
try {
const saved = await assignmentRepo.setRouteExcluded(tripId, assignment, excluded)
apply(saved.route_excluded === true)
} catch (err: unknown) {
apply(assignment.route_excluded === true)
throw err
}
},
setAssignmentStay: (tripId, dayId, assignmentId, stayMinutes) => writeVisitField(set, get, {
dayId, assignmentId, field: 'stay_minutes', value: stayMinutes, read: a => a.stay_minutes ?? null,
save: assignment => assignmentRepo.setStay(tripId, assignment, stayMinutes),
}),
setAssignmentRouteExcluded: (tripId, dayId, assignmentId, excluded) => writeVisitField(set, get, {
dayId, assignmentId, field: 'route_excluded', value: excluded, read: a => a.route_excluded === true,
save: assignment => assignmentRepo.setRouteExcluded(tripId, assignment, excluded),
}),
setAssignmentTimes: async (tripId, dayId, assignmentId, times) => {
const assignment = get().assignments[String(dayId)]?.find(a => a.id === assignmentId)
if (!assignment || assignmentId < 0) return