feat(roadtrip): share trip preferences and improve service stops

This commit is contained in:
Maurice
2026-09-12 00:24:45 +02:00
parent dd6ad31ab9
commit b773faff70
72 changed files with 1136 additions and 375 deletions
@@ -1,24 +1,33 @@
import { act, renderHook } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { useRoadtripPreferencesSync } from './useRoadtripPreferencesSync'
import { useSettingsStore } from '../store/settingsStore'
import { useRoadtripSettings } from './useRoadtripSettings'
import { useRoadtripPreferencesStore } from '../store/roadtripPreferencesStore'
import { useAuthStore } from '../store/authStore'
import { addListener, removeListener } from '../api/websocket'
vi.mock('../api/websocket', () => ({ addListener: vi.fn(), removeListener: vi.fn() }))
vi.mock('../repo/roadtripPreferencesRepo', () => ({ cachedRoadtripPreferences: vi.fn(async () => ({})) }))
vi.mock('../db/offlineDb', () => ({ offlineDb: { roadtripPreferences: { put: vi.fn(async () => {}) } } }))
describe('Roadtrip settings from MCP', () => {
it('merges valid user events, refuses unrelated settings and unsubscribes', () => {
const before = useSettingsStore.getState().settings
const hook = renderHook(() => useRoadtripPreferencesSync())
const calls = vi.mocked(addListener).mock.calls
const listener = calls[calls.length - 1][0]
act(() => listener({ type: 'roadtripPreferences:changed', preferences: { roadtrip_day_start: '07:00' } }))
expect(useSettingsStore.getState().settings.roadtrip_day_start).toBe('07:00')
expect(useSettingsStore.getState().settings.distance_unit).toBe(before.distance_unit)
act(() => listener({ type: 'roadtripPreferences:changed', preferences: { roadtrip_day_start: '99:00' } }))
expect(useSettingsStore.getState().settings.roadtrip_day_start).toBe('07:00')
describe('shared Roadtrip settings', () => {
it('scopes events and reads by trip and signed-in account', () => {
useAuthStore.setState({ user: { id: 1 } as never })
useRoadtripPreferencesStore.setState({ byTrip: {} })
const hook = renderHook(() => {
useRoadtripPreferencesSync()
return useRoadtripSettings(s => s.roadtrip_day_start, 10)
})
const listener = vi.mocked(addListener).mock.calls[vi.mocked(addListener).mock.calls.length - 1][0]
act(() => listener({ type: 'roadtripPreferences:changed', tripId: '10', preferences: { roadtrip_day_start: '07:00' } }))
expect(hook.result.current).toBe('07:00')
act(() => listener({ type: 'roadtripPreferences:changed', tripId: '11', preferences: { roadtrip_day_start: '09:00' } }))
expect(hook.result.current).toBe('07:00')
act(() => listener({ type: 'roadtripPreferences:changed', tripId: '10', preferences: { roadtrip_day_start: '99:00' } }))
expect(hook.result.current).toBe('07:00')
act(() => useAuthStore.setState({ user: { id: 2 } as never }))
expect(hook.result.current).toBeUndefined()
hook.unmount()
expect(removeListener).toHaveBeenCalledWith(listener)
useSettingsStore.setState({ settings: before })
})
})
+15 -4
View File
@@ -1,16 +1,27 @@
import { useEffect } from 'react'
import { roadtripPreferencesSchema } from '@trek/shared'
import { addListener, removeListener } from '../api/websocket'
import { useSettingsStore } from '../store/settingsStore'
import { useAuthStore } from '../store/authStore'
import { publishRoadtripPreferences } from '../store/roadtripPreferencesStore'
import { offlineDb } from '../db/offlineDb'
import { cachedRoadtripPreferences } from '../repo/roadtripPreferencesRepo'
export function useRoadtripPreferencesSync() {
const userId = useAuthStore(s => s.user?.id)
useEffect(() => {
if (!userId) return
let disposed = false
const listener = (event: Record<string, unknown>) => {
if (event.type !== 'roadtripPreferences:changed') return
const tripId = Number(event.tripId)
const parsed = roadtripPreferencesSchema.safeParse(event.preferences)
if (parsed.success) useSettingsStore.setState(state => ({ settings: { ...state.settings, ...parsed.data } }))
if (!parsed.success || !Number.isSafeInteger(tripId) || tripId < 1) return
publishRoadtripPreferences(userId, tripId, parsed.data)
void offlineDb.roadtripPreferences.put({ tripId, preferences: parsed.data }).then(() => cachedRoadtripPreferences(tripId)).then(preferences => {
if (!disposed) publishRoadtripPreferences(userId, tripId, preferences)
}).catch(() => {})
}
addListener(listener)
return () => removeListener(listener)
}, [])
return () => { disposed = true; removeListener(listener) }
}, [userId])
}
+42
View File
@@ -0,0 +1,42 @@
import { liveQuery } from 'dexie'
import { onNetworkModeChange } from '../sync/networkMode'
import { useEffect, useState } from 'react'
import type { RoadtripPreferences } from '@trek/shared'
import { useAuthStore } from '../store/authStore'
import { useTripStore } from '../store/tripStore'
import { EMPTY_ROADTRIP_PREFERENCES, publishRoadtripPreferences, useRoadtripPreferencesStore } from '../store/roadtripPreferencesStore'
import { cachedRoadtripPreferences, roadtripPreferencesRepo } from '../repo/roadtripPreferencesRepo'
export function useRoadtripSettings<T>(select: (settings: RoadtripPreferences) => T, requestedTripId?: number | string | null): T {
const activeTripId = useTripStore(s => s.trip?.id)
const userId = useAuthStore(s => s.user?.id)
const key = `${userId}:${requestedTripId ?? activeTripId}`
return useRoadtripPreferencesStore(s => select(s.byTrip[key] ?? EMPTY_ROADTRIP_PREFERENCES))
}
export function useLoadRoadtripSettings(tripId: number, enabled: boolean) {
const userId = useAuthStore(s => s.user?.id)
const [loadedKey, setLoadedKey] = useState('')
const [failedKey, setFailedKey] = useState('')
const key = `${userId}:${tripId}`
useEffect(() => {
if (!enabled || !userId || !Number.isFinite(tripId)) return
let cancelled = false
const load = () => {
roadtripPreferencesRepo.read(tripId).then(preferences => {
if (cancelled) return
publishRoadtripPreferences(userId, tripId, preferences)
setLoadedKey(key)
setFailedKey('')
}).catch(() => { if (!cancelled) setFailedKey(key) })
}
const cacheSubscription = liveQuery(() => cachedRoadtripPreferences(tripId).catch(() => null)).subscribe(preferences => {
if (!cancelled && preferences) publishRoadtripPreferences(userId, tripId, preferences)
})
load()
const unsubscribe = onNetworkModeChange(load)
window.addEventListener('online', load)
return () => { cancelled = true; cacheSubscription.unsubscribe(); unsubscribe(); window.removeEventListener('online', load) }
}, [tripId, userId, enabled, key])
return { ready: loadedKey === key, failed: failedKey === key }
}
+6 -3
View File
@@ -1,3 +1,5 @@
import { useRoadtripSettings } from './useRoadtripSettings'
import { isServiceStopType } from '../components/Roadtrip/roadtripModel'
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
import { useTripStore } from '../store/tripStore'
import { useSettingsStore } from '../store/settingsStore'
@@ -24,6 +26,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
const [routeSegments, setRouteSegments] = useState<RouteSegment[]>([])
// Charging stops / rest areas a plugin route places on the drawn line.
const [routeVias, setRouteVias] = useState<RouteVia[]>([])
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
const routeAbortRef = useRef<AbortController | null>(null)
const reservationsForSignature = useTripStore((s) => s.reservations)
// Recompute when the selected day's whole-day default mode changes (#1281) —
@@ -45,7 +48,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
// Read directly from store (not a render-phase ref) so callers after optimistic
// updates or non-optimistic deletes always see the latest assignments.
const currentAssignments = useTripStore.getState().assignments || {}
const da = (currentAssignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)
const da = (currentAssignments[String(dayId)] || []).filter(a => mirrorServiceStops || !isServiceStopType(a.place?.stop_type)).slice().sort((a, b) => a.order_index - b.order_index)
const allReservations = useTripStore.getState().reservations || []
const allDays = useTripStore.getState().days || []
const dayOrder = (id: number | null | undefined): number | null => {
@@ -275,7 +278,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
// Aborted (day changed) — newer call owns the state. Anything else: keep straight lines.
if (!(err instanceof Error) || err.name !== 'AbortError') { setRouteSegments([]); setRouteVias([]) }
}
}, [enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode])
}, [enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode, mirrorServiceStops])
// Stable signature for transport reservations on the selected day — changes when a transport
// is added, removed, or repositioned, ensuring route recalc fires even on transport-only reorders.
@@ -299,7 +302,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
if (!selectedDayId) { setRoute(null); setRouteSegments([]); setRouteVias([]); return }
updateRouteForDay(selectedDayId)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedDayId, selectedDayAssignments, transportSignature, enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode])
}, [selectedDayId, selectedDayAssignments, transportSignature, enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit, selectedDayDefaultMode, mirrorServiceStops])
return { route, routeSegments, routeVias, routeInfo, setRoute, setRouteInfo, updateRouteForDay }
}