The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
feat(client): follow and switch a trip's own addons
Maurice9956c58dd55b
diff --git a/client/scripts/eslint-baseline.json b/client/scripts/eslint-baseline.jsonindex 74be1f03f..57a40c386 100644--- a/client/scripts/eslint-baseline.json+++ b/client/scripts/eslint-baseline.json@@ -5,7 +5,7 @@"no-console": 88,"complexity": 217,"@typescript-eslint/no-explicit-any": 143,- "trek/no-swallowed-catch": 127,+ "trek/no-swallowed-catch": 126,"max-params": 31,"trek/store-without-selector": 66,"react-hooks/refs": 534,diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.jsonindex 2fc9d10a0..db6d44f70 100644--- a/client/scripts/feature-pairs.json+++ b/client/scripts/feature-pairs.json@@ -1113,8 +1113,8 @@"mobile": ["src/mobile/screens/admin/MAdminSchoolHolidayCatalog.tsx"]},{- "feature": "Trip settings: members, guests, public and invite link",- "hooks": ["src/components/Trips/useTripShare.ts"],+ "feature": "Trip settings: members, guests, public and invite link, the trip's own addons",+ "hooks": ["src/components/Trips/useTripShare.ts", "src/components/Trips/useTripAddonRows.ts"],"desktop": ["src/components/Trips/TripShareDialog.tsx"],"mobile": ["src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx"]}diff --git a/client/scripts/size-baseline.json b/client/scripts/size-baseline.jsonindex 9ba37f583..2e3d01696 100644--- a/client/scripts/size-baseline.json+++ b/client/scripts/size-baseline.json@@ -22,6 +22,6 @@"src/pages/TripPlannerPage.tsx": 1128,"src/pages/atlas/useAtlas.ts": 1207,"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,- "src/pages/tripPlanner/useTripPlanner.test.tsx": 3269,+ "src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,"src/styles/studio.css": 1918}diff --git a/client/src/App.tsx b/client/src/App.tsxindex 59baf4af5..b18fff2a5 100644--- a/client/src/App.tsx+++ b/client/src/App.tsx@@ -30,6 +30,7 @@ import { takeResumeRoute, useRememberRoute } from './utils/resumeRoute'import { usePermissionsStore, PermissionLevel } from './store/permissionsStore'import { useInAppNotificationListener } from './hooks/useInAppNotificationListener.ts'import { useRoadtripPreferencesSync } from './hooks/useRoadtripPreferencesSync'+import { useTripAddonsSync } from './hooks/useTripAddonsSync'import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTriggers'import OfflineBanner from './components/Layout/OfflineBanner'import NewVersionNotice from './components/Layout/NewVersionNotice'@@ -379,6 +380,7 @@ export default function App() {useInAppNotificationListener()useRoadtripPreferencesSync()+ useTripAddonsSync()useEffect(() => {if (isAuthenticated) {diff --git a/client/src/api/tripAddons.ts b/client/src/api/tripAddons.tsnew file mode 100644index 000000000..2a12ab327--- /dev/null+++ b/client/src/api/tripAddons.ts@@ -0,0 +1,10 @@+import type { TripAddonsResponse, TripAddonUpdateRequest } from '@trek/shared';+import apiClient from './client';++/** The trip addons of one trip, each on or off for it: every member reads them, only the owner switches one. */+export const tripAddonsApi = {+ list: (tripId: number): Promise<TripAddonsResponse> => apiClient.get(`/trips/${tripId}/addons`).then((r) => r.data),+ /** `enabled: null` drops the trip's own choice, so the instance setting applies again. */+ update: (tripId: number, addonId: string, body: TripAddonUpdateRequest): Promise<TripAddonsResponse> =>+ apiClient.put(`/trips/${tripId}/addons/${encodeURIComponent(addonId)}`, body).then((r) => r.data),+};diff --git a/client/src/api/wsEventPolicy.ts b/client/src/api/wsEventPolicy.tsindex 2095dd56c..ac3f2a308 100644--- a/client/src/api/wsEventPolicy.ts+++ b/client/src/api/wsEventPolicy.ts@@ -46,6 +46,10 @@ export const HANDLED_OUTSIDE_TRIP_STORE = ['roadtripVia:changed','roadtripTrack:changed','roadtripPreferences:changed',+ // Per-trip addons: store/tripAddonsStore (watchTripAddons, mounted by App through+ // hooks/useTripAddonsSync) puts the trip's list into the store and the device's copy, so the+ // tabs and panels a trip switched off disappear for every member at once.+ 'tripAddons:changed',// components/Roadtrip/useDayBoundaries reloads the shared boundaries.'roadtripBoundary:changed',// In-app notifications: hooks/useInAppNotificationListener, which also keepsdiff --git a/client/src/components/Assistant/useAssistantShare.ts b/client/src/components/Assistant/useAssistantShare.tsindex ae76c318c..3ec21ad53 100644--- a/client/src/components/Assistant/useAssistantShare.ts+++ b/client/src/components/Assistant/useAssistantShare.ts@@ -8,6 +8,7 @@ import { OnlineOnlyError } from '../../repo/onlineOnly';import { useAddonStore } from '../../store/addonStore';import { chatOf, useAssistantStore } from '../../store/assistantStore';import { useCanDo } from '../../store/permissionsStore';+import { useTripAddonEnabled } from '../../store/tripAddonsStore';import { useTripStore } from '../../store/tripStore';import { useToast } from '../shared/Toast';import { chatTextOf } from './assistantShare';@@ -35,7 +36,10 @@ export function useAssistantShare(tripId: number, message: AssistantMessage, wriconst { offline } = useNetworkMode();const can = useCanDo();const trip = useTripStore((s) => (s.trip?.id === tripId ? s.trip : null));- const chatOn = useAddonStore((s) => s.collabChat && s.addons.some((a) => a.id === 'collab' && a.enabled));+ // The chat is an instance-wide part of Collab, which this trip may have on or off.+ const chatFeatureOn = useAddonStore((s) => s.collabChat);+ const collabOn = useTripAddonEnabled(tripId, 'collab');+ const chatOn = chatFeatureOn && collabOn;const threadId = useAssistantStore((s) => chatOf(s, tripId).threadId);const [previewing, setPreviewing] = useState(false);const [includeChanges, setIncludeChanges] = useState(true);diff --git a/client/src/components/Layout/NativeWidgetsSync.test.tsx b/client/src/components/Layout/NativeWidgetsSync.test.tsxindex c876a334b..8078e1c5b 100644--- a/client/src/components/Layout/NativeWidgetsSync.test.tsx+++ b/client/src/components/Layout/NativeWidgetsSync.test.tsx@@ -34,6 +34,7 @@ vi.mock('../../native/widgets', async (importOriginal) => {};});+import { collabSummary, packingDetail } from '../../native/widgetOnline';import NativeWidgetsSync from './NativeWidgetsSync';const trip = {@@ -69,6 +70,8 @@ describe('NativeWidgetsSync', () => {vi.useRealTimers();await offlineDb.trips.clear();await offlineDb.days.clear();+ await offlineDb.todoItems.clear();+ await offlineDb.tripAddons.clear();});it('FE-NATIVE-WSYNC-001: writes today and every day ahead, so the widgets turn the day without the app', async () => {@@ -84,4 +87,29 @@ describe('NativeWidgetsSync', () => {['2026-11-08', 'Market'],]);});++ it('FE-NATIVE-WSYNC-002: a trip with Lists and Collab switched off shows neither its todos nor its chat', async () => {+ await offlineDb.todoItems.put({ id: 70, trip_id: 7, name: 'Book ferry', checked: 0 } as never);+ const off = (id: string) => ({ id, name: id, icon: null, enabled: false, instanceEnabled: true, overridden: true });+ await offlineDb.tripAddons.put({ tripId: 7, addons: [off('packing'), off('collab')] });+ vi.mocked(packingDetail).mockClear();+ vi.mocked(collabSummary).mockClear();++ render(<NativeWidgetsSync />);+ await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));+ const snapshot = published.calls[0][0] as { todos?: unknown; collab?: unknown };+ expect(snapshot.todos).toBeUndefined();+ expect(snapshot.collab).toBeUndefined();+ expect(vi.mocked(packingDetail)).not.toHaveBeenCalled();+ expect(vi.mocked(collabSummary)).not.toHaveBeenCalled();+ });++ it('FE-NATIVE-WSYNC-003: a trip the device never read the addons of shows its todos, as before', async () => {+ await offlineDb.todoItems.put({ id: 71, trip_id: 7, name: 'Book ferry', checked: 0 } as never);++ render(<NativeWidgetsSync />);+ await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));+ const snapshot = published.calls[0][0] as { todos?: { items?: unknown[] } };+ expect(snapshot.todos).toBeDefined();+ });});diff --git a/client/src/components/Layout/NativeWidgetsSync.tsx b/client/src/components/Layout/NativeWidgetsSync.tsxindex 0b741a2e8..406e27015 100644--- a/client/src/components/Layout/NativeWidgetsSync.tsx+++ b/client/src/components/Layout/NativeWidgetsSync.tsx@@ -32,12 +32,15 @@ import {type TripWidgetSnapshot,type WidgetLabels,} from '../../native/widgets';+import { cachedTripAddons } from '../../repo/tripAddonsRepo';+import { instanceAddonOn, useAddonStore } from '../../store/addonStore';import { useAuthStore } from '../../store/authStore';import { useFlightLiveStore } from '../../store/flightLiveStore';import { useSettingsStore } from '../../store/settingsStore';import { useTripStore } from '../../store/tripStore';import type { Day, Place, Reservation, TranslationFn, Trip } from '../../types';import { formatTime } from '../../utils/formatters';+import { tripAddonEnabled } from '../../utils/tripAddons';import { localDateStr } from '../../vacay/monthGrid';const REFRESH_MS = 15 * 60 * 1000;@@ -120,15 +123,31 @@ async function flightOf(trip: Trip, reservations: Reservation[], path: string, creturn widgetFlight(legs, Date.now(), path, { locale: context.language, timeFormat: context.timeFormat });}+/**+ * Whether the trip has Lists and Collab on, from the list the device kept for it+ * (the sync reads it with the trip). A trip it never read follows the instance,+ * and while that is not known either the widgets show both, as they always did.+ */+async function tripSections(tripId: number): Promise<{ lists: boolean; collab: boolean }> {+ const own = await cachedTripAddons(tripId);+ const instance = useAddonStore.getState();+ const on = (id: string) => tripAddonEnabled(own, id, instanceAddonOn(instance, id, true));+ return { lists: on('packing'), collab: on('collab') };+}+async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {const { today, language, unit, time } = context;- const [places, reservations, todos, packing, memberRows] = await Promise.all([+ const [places, reservations, todoRows, packingRows, memberRows, sections] = await Promise.all([offlineDb.places.where('trip_id').equals(trip.id).toArray(),offlineDb.reservations.where('trip_id').equals(trip.id).toArray(),offlineDb.todoItems.where('trip_id').equals(trip.id).toArray(),offlineDb.packingItems.where('trip_id').equals(trip.id).toArray(),offlineDb.tripMembers.where('tripId').equals(trip.id).toArray(),+ tripSections(trip.id),]);+ // A trip with Lists off shows no todos or packing, on the widgets and the watch alike.+ const todos = sections.lists ? todoRows : [];+ const packing = sections.lists ? packingRows : [];const members = memberRows.length;const names = [trip.owner_username, ...memberRows.map((m) => m.username)].filter((n): n is string => !!n);const path = `/trips/${trip.id}`;@@ -144,13 +163,15 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {const [weather, cover, bags, collab, flight] = await Promise.all([spot && inRange ? widgetWeather(spot, { date: weatherDate, lang: language, unit, place }) : Promise.resolve(null),widgetCover(trip.cover_image),- packingDetail(trip.id, packing),- collabSummary(- trip.id,- `/trips/${trip.id}?tab=collab`,- [...new Set(names)],- useAuthStore.getState().user?.id ?? null- ),+ sections.lists ? packingDetail(trip.id, packing) : Promise.resolve(null),+ sections.collab+ ? collabSummary(+ trip.id,+ `/trips/${trip.id}?tab=collab`,+ [...new Set(names)],+ useAuthStore.getState().user?.id ?? null+ )+ : Promise.resolve(null),flightOf(trip, reservations, path, context),]);const packed = packingSummary(packing, `/trips/${trip.id}?tab=listen`);@@ -166,7 +187,7 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {memberCount: members > 0 ? members + 1 : 0,weather,bookings: bookingsAhead(reservations, { dayDates, today, tripPath: path, formatTime: time }),- todos: todosSummary(todos, `${path}?tab=listen`),+ todos: sections.lists ? todosSummary(todos, `${path}?tab=listen`) : undefined,packing: packed && bags ? { ...packed, ...bags } : packed,collab,flight,diff --git a/client/src/components/Map/useTripRouteOverview.ts b/client/src/components/Map/useTripRouteOverview.tsindex c5c442069..1fc317075 100644--- a/client/src/components/Map/useTripRouteOverview.ts+++ b/client/src/components/Map/useTripRouteOverview.ts@@ -5,7 +5,7 @@ import {type TripRouteAnswers, type TripRouteSummary,} from './tripRouteGeometry'import { useSettingsStore } from '../../store/settingsStore'-import { useAddonStore } from '../../store/addonStore'+import { useTripAddonEnabled } from '../../store/tripAddonsStore'import type { RoadtripVia } from '@trek/shared'import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'import type { TourStageStops } from './dayTourProjection'@@ -51,7 +51,7 @@ export function useTripRouteOverview(tourStageStops?: TourStageStops,): TripRouteOverview {const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)- const toursEnabled = useAddonStore(s => s.isEnabled('tours'))+ const toursEnabled = useTripAddonEnabled(tripId, 'tours')// Leg text is formatted at compute time, so a km↔mi switch has to re-run (#1300).const distanceUnit = useSettingsStore(s => s.settings.distance_unit)const [result, setResult] = useState<TripRouteOverview>(EMPTY)diff --git a/client/src/components/PDF/TripPDF.tsx b/client/src/components/PDF/TripPDF.tsxindex 861ee9a41..ea4b2d0aa 100644--- a/client/src/components/PDF/TripPDF.tsx+++ b/client/src/components/PDF/TripPDF.tsx@@ -14,7 +14,7 @@ import { renderIconMarkup } from '../../utils/iconMarkup'import { formatMoney, formatMoneySum, formatClockTime, splitReservationDateTime, type MoneyEntry } from '../../utils/formatters'import { useSettingsStore } from '../../store/settingsStore'import { useTripStore } from '../../store/tripStore'-import { useAddonStore } from '../../store/addonStore'+import { tripAddonEnabledNow } from '../../store/tripAddonsStore'import { projectDayItinerary } from '../Map/dayTourProjection'import { planCosts } from '../Planner/planCosts'import { routeDistanceLabel } from '../Map/tripRouteLabels'@@ -180,8 +180,10 @@ interface downloadTripPDFProps {showServiceStops?: boolean/** The trip's expenses, which the cost figures add up with Costs on (#2551). Read from the trip store when left out. */budgetItems?: BudgetItem[]- /** Whether the Costs addon is on. Read from the addon store when left out. */+ /** Whether the Costs addon is on for this trip. Read from the trip's addons when left out. */costsEnabled?: boolean+ /** Whether the Tours addon is on for this trip. Read from the trip's addons when left out. */+ toursEnabled?: boolean/** Prints only this member's plan (#2168): the stops and bookings that name them, and the ones that name nobody. */onlyUserId?: number/** The planner's road trip vias and tour stages, and the routing progress and stop (#2876). */@@ -192,7 +194,7 @@ interface downloadTripPDFProps {// `assignments` is normalised here once, to the plan's own list; every read below// (and fetchPlacePhotos) relies on it being an object.-export async function downloadTripPDF({ trip, days, places, assignments: allStored = {}, categories, dayNotes, reservations: allReservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled, onlyUserId, route, signal }: downloadTripPDFProps) {+export async function downloadTripPDF({ trip, days, places, assignments: allStored = {}, categories, dayNotes, reservations: allReservations = [], t: _t, locale: _locale, timeFormat: _timeFormat, distanceUnit: _distanceUnit, showServiceStops = true, budgetItems, costsEnabled, toursEnabled: toursOn, onlyUserId, route, signal }: downloadTripPDFProps) {const { assignments: stored, reservations } = onlyUserId != null? onlyMyPlan(allStored, allReservations, onlyUserId): { assignments: allStored, reservations: allReservations }@@ -226,7 +228,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStorconst unit: DistanceUnit = (_distanceUnit || useSettingsStore.getState().settings.distance_unit) === 'imperial'? 'imperial' : 'metric'- const toursEnabled = useAddonStore.getState().isEnabled('tours')+ const toursEnabled = toursOn ?? tripAddonEnabledNow(trip.id, 'tours')const hasInvalidTour = toursEnabled && Object.values(assignments).some(list =>projectDayItinerary(list || [], true, places).some(item => item.kind === 'tour' && !item.valid))const { route: tripRoute, mapSvg: tripMapSvg } = await drawTripRoute({@@ -289,7 +291,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor// The same figures the plan shows (#2551): the expenses with Costs on, each once,// else each planned place's own price once. An expense linked to a place finds its// day through every stop, the booked night's included.- const withCosts = costsEnabled ?? useAddonStore.getState().isEnabled('budget')+ const withCosts = costsEnabled ?? tripAddonEnabledNow(trip.id, 'budget')const costs = planCosts({days: sorted,assignments: withCosts ? stored : assignments,diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsxindex 9fe3b7e03..1afa6b61d 100644--- a/client/src/components/Planner/DayPlanSidebar.tsx+++ b/client/src/components/Planner/DayPlanSidebar.tsx@@ -33,6 +33,7 @@ import { useTripStore } from '../../store/tripStore'import { useCanDo } from '../../store/permissionsStore'import { useSettingsStore } from '../../store/settingsStore'import { useAddonStore } from '../../store/addonStore'+import { useTripAddonEnabled } from '../../store/tripAddonsStore'import { openSaveToCollection } from '../Collections/saveTarget'import { computeMultiDayMove as computeMultiDayMoveIn, getDayOrder as getDayOrderIn, type SpanPhase } from './DayPlanSidebar.multiDayMove'import { useTranslation } from '../../i18n'@@ -41,7 +42,6 @@ import { Tooltip } from '../shared/Tooltip'import { NEUTRAL_TINT, fs } from '../shared/DialogShell'import { BarButton, MoreButton, SoftPill, TimePill, tintOf } from './planParts'import './dayPlanRows.css'-import { TypeTile } from './bookings/bookingParts'import { typeInfo } from './bookings/bookingsModel'import { transportSubtitle } from './transportDetailModel'@@ -218,7 +218,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {const toast = useToast()const { t, locale } = useTranslation()const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)- const toursEnabled = useAddonStore(s => s.isEnabled('tours'))+ const toursEnabled = useTripAddonEnabled(tripId, 'tours')const tripActions = useRef(useTripStore.getState()).currentconst { noteUi, setNoteUi, noteInputRef, dayNotes, openAddNote: _openAddNote, openEditNote: _openEditNote, cancelNote, saveNote, deleteNote: _deleteNote, moveNote: _moveNote } = useDayNotes(tripId)@@ -1098,7 +1098,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {// Total Cost reads the expenses in Costs when it is on (#2551).const budgetItems = useTripStore(s => s.budgetItems)- const costsEnabled = useAddonStore(s => s.isEnabled('budget'))+ const costsEnabled = useTripAddonEnabled(tripId, 'budget')const totalCostLabel = useMemo(() => {return formatMoneySum(planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency, displayCurrency: costBase }).total, costBase, locale, fxRates)}, [days, assignments, reservations, budgetItems, costsEnabled, currency, costBase, locale, fxRates])@@ -1276,7 +1276,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarPconst optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)const dateFirst = useSettingsStore(s => s.settings.day_date_first === true)const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))- const toursEnabled = useAddonStore(s => s.isEnabled('tours'))+ const toursEnabled = useTripAddonEnabled(tripId, 'tours')// Plugin time contributions in the day plan (dayScheduleProvider hook).const daySchedule = usePluginDaySchedule(tripId)// Per-day colours from the dayTintProvider hook — e.g. which leg of the trip adiff --git a/client/src/components/Planner/PlaceFormModal.tsx b/client/src/components/Planner/PlaceFormModal.tsxindex 8acbaa716..83987e5d0 100644--- a/client/src/components/Planner/PlaceFormModal.tsx+++ b/client/src/components/Planner/PlaceFormModal.tsx@@ -2,6 +2,7 @@ import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNodimport type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'import { useAuthStore } from '../../store/authStore'import { useAddonStore } from '../../store/addonStore'+import { useTripAddonEnabled } from '../../store/tripAddonsStore'import { useCanDo } from '../../store/permissionsStore'import { useTripStore } from '../../store/tripStore'import { useSettingsStore } from '../../store/settingsStore'@@ -120,7 +121,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {const tripObj = useTripStore((s) => s.trip)const canUploadFiles = can('file_upload', tripObj)const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))- const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))+ const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)const {form, setForm, autoFilledRef, pendingFiles, addFilesFromInput, removeFile, handlePaste, isSaving, setIsSaving,diff --git a/client/src/components/Planner/ReservationModal.tsx b/client/src/components/Planner/ReservationModal.tsxindex f70448c96..87e0811b8 100644--- a/client/src/components/Planner/ReservationModal.tsx+++ b/client/src/components/Planner/ReservationModal.tsx@@ -1,7 +1,7 @@import { useEffect, useRef, useMemo, useId } from 'react'import { useParams } from 'react-router'import { useTripStore } from '../../store/tripStore'-import { useAddonStore } from '../../store/addonStore'+import { useTripAddonEnabled } from '../../store/tripAddonsStore'import CustomSelect from '../shared/CustomSelect'import { BookingCodeInput } from '../shared/BookingCode'import { buildAssignmentOptions } from './assignmentOptions'@@ -71,7 +71,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, pconst fileInputRef = useRef(null)const titleId = useId()- const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))+ const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)// Set right before submit when the user clicked create/edit expense.const expense = useBookingExpenseIntent(() => handleSubmit(), {diff --git a/client/src/components/Planner/TransportModal.tsx b/client/src/components/Planner/TransportModal.tsxindex 1e321eeff..52205895c 100644--- a/client/src/components/Planner/TransportModal.tsx+++ b/client/src/components/Planner/TransportModal.tsx@@ -12,7 +12,7 @@ import { toLocationPicks } from './locationPicks'import { useTranslation } from '../../i18n'import { useToast } from '../shared/Toast'import { useTripStore } from '../../store/tripStore'-import { useAddonStore } from '../../store/addonStore'+import { useTripAddonEnabled } from '../../store/tripAddonsStore'import type { Day, Place, Accommodation, Reservation, TripFile, AssignmentsMap } from '../../types'import { BookingNotesFilesCosts } from './BookingNotesFilesCosts'import { TravelerPicker } from './TravelerPicker'@@ -83,10 +83,10 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, selconst toast = useToast()// The trip's places, offered by every location field of the manual tab (#2468).const locationPicks = useMemo(() => toLocationPicks(places), [places])- const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))const budgetItems = useTripStore(s => s.budgetItems)const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)const { id: tripId } = useParams<{ id: string }>()+ const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')// 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.const expense = useBookingExpenseIntent(() => handleSubmit(), {diff --git a/client/src/components/Planner/useTripExport.test.ts b/client/src/components/Planner/useTripExport.test.tsindex 0bce77df7..1fdd9148b 100644--- a/client/src/components/Planner/useTripExport.test.ts+++ b/client/src/components/Planner/useTripExport.test.ts@@ -1,11 +1,12 @@-// FE-PLANNER-TRIPEXPORT-001 to -014: the trip exports behind the desktop export+// FE-PLANNER-TRIPEXPORT-001 to -015: the trip exports behind the desktop export// dialog and the phone's export sheet.import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';import { buildAssignment, buildReservation, buildTrip, buildUser } from '../../../tests/helpers/factories';-import { resetAllStores, seedStore } from '../../../tests/helpers/store';+import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';import { useAuthStore } from '../../store/authStore';+import { useTripAddonsStore } from '../../store/tripAddonsStore';import type { DayNote } from '../../types';import { downloadTripPDF } from '../PDF/TripPDF';import { flatDayNotes, saveBlob, useTripExport, type TripExportOptions } from './useTripExport';@@ -133,6 +134,17 @@ describe('useTripExport', () => {expect(vi.mocked(downloadTripPDF).mock.calls[1][0]).toMatchObject({ onlyUserId: 9 });});+ it('FE-PLANNER-TRIPEXPORT-015: the PDF prints costs and tours as the trip has them, not the instance', async () => {+ seedInstanceAddons(['budget']);+ useTripAddonsStore.getState().publish(3, [+ { id: 'budget', name: 'Costs', icon: null, enabled: false, instanceEnabled: true, overridden: true },+ { id: 'tours', name: 'Tours', icon: null, enabled: true, instanceEnabled: false, overridden: true },+ ]);+ const { result } = renderHook(() => useTripExport(options()));+ await act(() => result.current.exportPdf());+ expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({ costsEnabled: false, toursEnabled: true });+ });+it('FE-PLANNER-TRIPEXPORT-005: the phone stays open after the PDF and prints nothing without a trip', async () => {const opts = options(PHONE);const { result } = renderHook(() => useTripExport(opts));diff --git a/client/src/components/Planner/useTripExport.ts b/client/src/components/Planner/useTripExport.tsindex 4de48d9b3..76e672e00 100644--- a/client/src/components/Planner/useTripExport.ts+++ b/client/src/components/Planner/useTripExport.ts@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { useRoadtripSettings } from '../../hooks/useRoadtripSettings';import { useAuthStore } from '../../store/authStore';import { useSettingsStore } from '../../store/settingsStore';+import { useTripAddonEnabled } from '../../store/tripAddonsStore';import type { AssignmentsMap, Category, Day, DayNote, Place, Reservation, Trip } from '../../types';import { importChunk } from '../../utils/chunkReload';import type { ViasByDay } from '../../utils/dayRouteVias';@@ -144,6 +145,9 @@ export function useTripExport({// them, so it needs the same switch the plan reads.const showServiceStops = useRoadtripSettings((s) => s.roadtrip_service_stops_in_days !== false, tripId);const myId = useAuthStore((s) => s.user?.id);+ // The sections the trip has on, as the plan shows them: costs in the figures, tours on the route.+ const costsEnabled = useTripAddonEnabled(tripId, 'budget');+ const toursEnabled = useTripAddonEnabled(tripId, 'tours');const offerMine = myId != null && hasPersonalPlan(data.assignments, data.reservations);const fileBase = data.trip?.title || 'trip';@@ -185,6 +189,8 @@ export function useTripExport({timeFormat,distanceUnit,showServiceStops,+ costsEnabled,+ toursEnabled,onlyUserId: mine ? myId : undefined,route: { viasByDay: data.viasByDay, tourStageStops: data.tourStageStops, ...routing },signal: givenUp,diff --git a/client/src/components/Tours/collection/collectionTours.test.tsx b/client/src/components/Tours/collection/collectionTours.test.tsxindex 9f200d18a..856e0bb82 100644--- a/client/src/components/Tours/collection/collectionTours.test.tsx+++ b/client/src/components/Tours/collection/collectionTours.test.tsx@@ -447,7 +447,28 @@ describe('CollectionToursSection', () => {expect(await screen.findByTestId('kept-tour-preview')).toBeInTheDocument();unmount();useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });+ const off = { response: { status: 404, data: { error: 'Tours addon is not enabled' } } };+ list.mockRejectedValue(off);render(<CollectionToursSection collectionId={3} canRemove />);+ await waitFor(() => expect(list).toHaveBeenLastCalledWith(3));+ expect(screen.queryByTestId('collection-tours')).toBeNull();+ expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();+ });++ it('FE-COLLECTION-TOURS-021: with Tours off for the instance, the tours show once the server hands them over', async () => {+ useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });+ // A trip of the user switched Tours on for itself, so the server answers.+ vi.spyOn(collectionToursRepo, 'list').mockResolvedValue({ tours: [kept()] });+ render(<CollectionToursSection collectionId={3} canRemove />);+ expect(await screen.findByTestId('kept-tour-4')).toHaveTextContent('Ridge');+ });++ it('FE-COLLECTION-TOURS-022: with Tours off for the instance, a failed read shows nothing, as it always did', async () => {+ useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });+ const list = vi.spyOn(collectionToursRepo, 'list').mockRejectedValue(new Error('500'));+ render(<CollectionToursSection collectionId={3} canRemove />);+ await waitFor(() => expect(list).toHaveBeenCalled());+ expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();expect(screen.queryByTestId('collection-tours')).toBeNull();});diff --git a/client/src/components/Tours/collection/useCollectionTours.ts b/client/src/components/Tours/collection/useCollectionTours.tsindex 6354bf12f..c4ebdebea 100644--- a/client/src/components/Tours/collection/useCollectionTours.ts+++ b/client/src/components/Tours/collection/useCollectionTours.ts@@ -13,23 +13,26 @@ import { useToast } from '../../shared/Toast';/*** LIB-03: the tours a collection keeps, for the collection's page. Read when* the collection opens and kept current while its members keep or remove one;- * nothing at all while the Tours addon is off. Removing asks first and says+ * nothing at all while the Tours addon is off. Tours counts as on while the+ * instance has it on or any of the user's trips switched it on for itself;+ * only the server knows the second, so with the instance off the tours are+ * read all the same and its refusal hides them. Removing asks first and says* how it went.*/export function useCollectionTours(collectionId: number) {const { t } = useTranslation();const toast = useToast();- const enabled = useAddonStore((state) => state.isEnabled('tours'));+ const instanceOn = useAddonStore((state) => state.isEnabled('tours'));const { tours, status, shownFor } = useCollectionTourStore(useShallow((state) => ({ tours: state.tours, status: state.status, shownFor: state.collectionId })));const [removing, setRemoving] = useState<CollectionTourItem | null>(null);+ // Read again when the instance switch flips, since the answer may change with it.useEffect(() => {- if (!enabled) return undefined;void useCollectionTourStore.getState().load(collectionId);return watchCollectionTours();- }, [collectionId, enabled]);+ }, [collectionId, instanceOn]);const confirmRemove = async () => {const tour = removing;@@ -44,6 +47,9 @@ export function useCollectionTours(collectionId: number) {};const current = shownFor === collectionId;+ // With the instance on nothing changes; with it off only tours the server handed over show,+ // so an install without a trip of its own choice shows nothing, as it always did.+ const enabled = instanceOn ? !(current && status === 'off') : current && status === 'ready';return {enabled,tours: enabled && current ? tours : [],diff --git a/client/src/components/Tours/packing/useTourPackingLink.ts b/client/src/components/Tours/packing/useTourPackingLink.tsindex 476a17173..59787e8f1 100644--- a/client/src/components/Tours/packing/useTourPackingLink.ts+++ b/client/src/components/Tours/packing/useTourPackingLink.ts@@ -9,7 +9,7 @@ import {import { useCallback, useEffect, useMemo, useState } from 'react';import { translateApiError, useTranslation } from '../../../i18n';import { tourPackingLinkRepo } from '../../../repo/tourPackingLinkRepo';-import { useAddonStore } from '../../../store/addonStore';+import { useTripAddonEnabled } from '../../../store/tripAddonsStore';import { useTripStore } from '../../../store/tripStore';import type { PackingItem } from '../../../types';import { packingCategoryOrder, packingViewItems } from '../../Packing/packingListModel';@@ -42,7 +42,7 @@ interface TourPackingCategory extends PackingCategoryChoice {export function useTourPackingLink({ tripId, tour }: { tripId: number; tour: TourListItem }) {const { t } = useTranslation();const toast = useToast();- const packingEnabled = useAddonStore((state) => state.isEnabled('packing'));+ const packingEnabled = useTripAddonEnabled(tripId, 'packing');const items = useTripStore((state) => state.packingItems);const placeId = tour.place_id;const key = `${tripId}:${placeId}`;diff --git a/client/src/components/Trips/TripMembersModal.test.tsx b/client/src/components/Trips/TripMembersModal.test.tsxindex ff05c4ed5..3d1bcfe0e 100644--- a/client/src/components/Trips/TripMembersModal.test.tsx+++ b/client/src/components/Trips/TripMembersModal.test.tsx@@ -7,7 +7,7 @@ import { server } from '../../../tests/helpers/msw/server';import { useAuthStore } from '../../store/authStore';import { useTripStore } from '../../store/tripStore';import { usePermissionsStore } from '../../store/permissionsStore';-import { resetAllStores, seedStore } from '../../../tests/helpers/store';+import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';import { buildUser, buildTrip } from '../../../tests/helpers/factories';import TripMembersModal from './TripMembersModal';@@ -101,6 +101,8 @@ beforeEach(() => {);seedStore(useAuthStore, { user: ownerUser, isAuthenticated: true });seedStore(useTripStore, { trip: buildTrip({ id: 1, title: 'Test Trip' }) });+ // The instance has the three addons a link section belongs to; the trip names none of its own.+ seedInstanceAddons(['packing', 'budget', 'collab']);addToast = vi.fn<AddToast>(() => 0);window.__addToast = addToast;});@@ -1131,4 +1133,34 @@ describe('TripMembersModal', () => {expect(await screen.findByText('owner')).toBeInTheDocument();expect(screen.queryByRole('button', { name: 'Edit Trip' })).toBeNull();});++ it('FE-COMP-MEMBERS-064: the owner switches the trip addons in an area of their own', async () => {+ const user = userEvent.setup();+ const bodies: unknown[] = [];+ const list = [+ { id: 'budget', name: 'Budget', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true },+ ];+ server.use(+ http.get('/api/trips/1/addons', () => HttpResponse.json({ tripId: 1, addons: list })),+ http.put('/api/trips/1/addons/:addonId', async ({ request }) => {+ bodies.push(await request.json());+ return HttpResponse.json({ tripId: 1, addons: list });+ }),+ );+ render(<TripMembersModal {...defaultProps} />);++ const nav = await screen.findByRole('navigation', { name: 'Trip settings' });+ await user.click(await within(nav).findByRole('button', { name: 'Addons' }));+ expect(await screen.findByText('This trip only')).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Costs' }));+ await waitFor(() => expect(bodies).toEqual([{ enabled: null }]));+ });++ it('FE-COMP-MEMBERS-065: a member who is not the owner gets no Addons area', async () => {+ seedStore(useAuthStore, { user: memberUser, isAuthenticated: true });+ render(<TripMembersModal {...defaultProps} />);++ expect(await screen.findByText('owner')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Addons' })).toBeNull();+ });});diff --git a/client/src/components/Trips/TripShareDialog.tsx b/client/src/components/Trips/TripShareDialog.tsxindex 7671aff10..004338aff 100644--- a/client/src/components/Trips/TripShareDialog.tsx+++ b/client/src/components/Trips/TripShareDialog.tsx@@ -1,8 +1,9 @@import { useId, useState, type ComponentProps, type ReactNode } from 'react'-import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'+import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Puzzle, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'import { useTranslation } from '../../i18n'import CustomSelect from '../shared/CustomSelect'import ConfirmDialog from '../shared/ConfirmDialog'+import ToggleSwitch from '../Settings/ToggleSwitch'import { Tooltip } from '../shared/Tooltip'import { DialogButton, DialogHeader, DialogSection, DialogShell, DialogTile, NEUTRAL_TINT, PILL, fs } from '../shared/DialogShell'import { AddRowButton, CardHead, INPUT, LABEL, PANEL } from '../shared/dialogParts'@@ -12,7 +13,8 @@ import TripFormModal from './TripFormModal'import { TripJournalLinkSection } from './TripJournalLinkSection'import { TripMemberAvatar } from './TripMemberAvatar'import { useTripJournalSectionVisible } from './useTripJournalLink'-import { SHARE_OPTIONS, SHARE_SECTIONS, useShareLink, useTripInviteLink, useTripMembers, type TripMembersState } from './useTripShare'+import { useTripAddonRows } from './useTripAddonRows'+import { SHARE_OPTIONS, useShareLink, useTripInviteLink, useTripMembers, type TripMembersState } from './useTripShare'interface TripShareDialogProps {isOpen: boolean@@ -57,19 +59,21 @@ const NAV_ENTRY_OFF = 'text-content-muted hover:bg-surface-hover hover:text-cont/*** The trip's Settings on the desktop: who is on the trip, its guests, the two- * links that let others in, and the journal the trip shows.+ * links that let others in, the journal the trip shows, and for the owner+ * which addons the trip uses.*/export default function TripShareDialog(props: TripShareDialogProps) {return props.isOpen ? <OpenDialog {...props} /> : null}-type Area = 'people' | 'sharing' | 'journal' | 'trip'+type Area = 'people' | 'sharing' | 'journal' | 'addons' | 'trip'/** The areas of the dialog, each with its icon, its name and the line under the name. */const AREAS: { id: Area; icon: (on: boolean) => ReactNode; labelKey: string; hintKey: string }[] = [{ id: 'people', icon: () => <Users size={16} strokeWidth={2} />, labelKey: 'trip.settings.people', hintKey: 'trip.settings.peopleHint' },{ id: 'sharing', icon: () => <Link2 size={16} strokeWidth={2} />, labelKey: 'trip.settings.sharing', hintKey: 'trip.settings.sharingHint' },{ id: 'journal', icon: () => <LinkedJournalIcon size={16} />, labelKey: 'trip.journal.title', hintKey: 'trip.journal.hint' },+ { id: 'addons', icon: () => <Puzzle size={16} strokeWidth={2} />, labelKey: 'trip.settings.addons', hintKey: 'trip.settings.addonsHint' },{ id: 'trip', icon: () => <Pencil size={16} strokeWidth={2} />, labelKey: 'dashboard.editTrip', hintKey: 'trip.settings.editTripHint' },]@@ -81,7 +85,7 @@ function OpenDialog({ onClose, tripId, tripTitle, onMembersChanged, editTrip }:const [area, setArea] = useState<Area>('people')const [tripReviewing, setTripReviewing] = useState(false)const journalSection = useTripJournalSectionVisible(tripId)- const shows: Record<Area, boolean> = { people: true, sharing: m.canManageShare, journal: journalSection, trip: !!editTrip }+ const shows: Record<Area, boolean> = { people: true, sharing: m.canManageShare, journal: journalSection, addons: m.isCurrentOwner, trip: !!editTrip }const areas = AREAS.filter(a => shows[a.id])const current = areas.find(a => a.id === area) ?? areas[0]const panelOf = (id: Area) => areas.find(a => a.id === id)@@ -132,6 +136,11 @@ function OpenDialog({ onClose, tripId, tripTitle, onMembersChanged, editTrip }:<TripJournalLinkSection tripId={tripId} framed={false} /></AreaPanel>)}+ {m.isCurrentOwner && (+ <AreaPanel area={panelOf('addons')} shown={current.id === 'addons'} titled>+ <TripAddonsList tripId={tripId} />+ </AreaPanel>+ )}{editTrip && (<AreaPanel area={panelOf('trip')} shown={current.id === 'trip'} titled><TripFormModal embedded isOpen onClose={onClose} onReviewChange={setTripReviewing} {...editTrip} />@@ -418,6 +427,32 @@ function PermChip({ on, disabled, label, hint, onToggle }: { on: boolean; disablreturn hint ? <Tooltip label={hint}>{chip}</Tooltip> : chip}+/** The trip addons, each with its switch; a badge marks the ones the owner set apart from the instance. */+function TripAddonsList({ tripId }: { tripId: number }) {+ const { t } = useTranslation()+ const { rows, loading } = useTripAddonRows(tripId)+ if (loading) return <div className="h-[120px] animate-pulse rounded-[14px] bg-surface-secondary" />+ return (+ <div className={ROWS}>+ {rows.map(row => (+ <div key={row.id} className={ROW}>+ <span className={`flex h-8 w-8 flex-none items-center justify-center rounded-[10px] bg-surface-tertiary ${row.enabled ? 'text-content' : 'text-content-faint'}`}>+ <row.Icon size={16} strokeWidth={2} />+ </span>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ <span className="truncate font-semibold text-content" style={fs(13.5, 'body')}>{row.name}</span>+ {row.ownChoice && <span className={`${BADGE} bg-surface-tertiary text-content-muted`} style={fs(10.5, 'caption')}>{t('trip.addons.thisTripOnly')}</span>}+ </div>+ {row.description && <p className="m-0 truncate text-content-muted" style={fs(12, 'caption')}>{row.description}</p>}+ </div>+ <ToggleSwitch on={row.enabled} onToggle={row.toggle} label={row.name} disabled={row.busy} />+ </div>+ ))}+ </div>+ )+}+/** The read-only public link, and which parts of the trip it shows. */function PublicLink({ tripId }: { tripId: number }) {const { t } = useTranslation()@@ -429,7 +464,7 @@ function PublicLink({ tripId }: { tripId: number }) {<div><span className={LABEL}>{t('share.options')}</span><div className="flex flex-wrap gap-1.5">- {SHARE_SECTIONS.map(opt => (+ {link.sections.map(opt => (<PermChip key={opt.key} on={link.perms[opt.key]} disabled={opt.always} label={t(opt.label)}onToggle={() => void link.setPerm(opt.key, !link.perms[opt.key])} />))}diff --git a/client/src/components/Trips/useTripAddonRows.test.tsx b/client/src/components/Trips/useTripAddonRows.test.tsxnew file mode 100644index 000000000..735d4ebfc--- /dev/null+++ b/client/src/components/Trips/useTripAddonRows.test.tsx@@ -0,0 +1,84 @@+// FE-TRIPADDONROWS-001 to FE-TRIPADDONROWS-003: the rows of the trip settings' Addons area,+// shared by the desktop dialog and the phone sheet.+import { act, renderHook, waitFor } from '@testing-library/react';+import type { TripAddon } from '@trek/shared';+import 'fake-indexeddb/auto';+import { CarFront, ListChecks, Puzzle } from 'lucide-react';+import { http, HttpResponse } from 'msw';+import type { ReactNode } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { buildUser } from '../../../tests/helpers/factories';+import { server } from '../../../tests/helpers/msw/server';+import { resetAllStores, seedStore } from '../../../tests/helpers/store';+import { clearAll } from '../../db/offlineDb';+import { TranslationProvider } from '../../i18n/TranslationContext';+import { useAuthStore } from '../../store/authStore';+import { useTripAddonRows } from './useTripAddonRows';++const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));+vi.mock('../shared/Toast', () => ({ useToast: () => toast }));++const LIST: TripAddon[] = [+ { id: 'packing', name: 'Packing', icon: 'ListChecks', enabled: true, instanceEnabled: true, overridden: false },+ { id: 'roadtrip', name: 'Road trip', icon: 'Route', enabled: false, instanceEnabled: true, overridden: true },+ { id: 'someplugin', name: 'Some plugin', icon: 'Unknown', enabled: true, instanceEnabled: false, overridden: true },+];++function wrapper({ children }: { children: ReactNode }) {+ return <TranslationProvider>{children}</TranslationProvider>;+}++let bodies: unknown[] = [];++beforeEach(async () => {+ await clearAll();+ resetAllStores();+ bodies = [];+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });+ server.use(+ http.get('/api/trips/4/addons', () => HttpResponse.json({ tripId: 4, addons: LIST })),+ http.put('/api/trips/4/addons/:addonId', async ({ request }) => {+ bodies.push(await request.json());+ return HttpResponse.json({ tripId: 4, addons: LIST });+ })+ );+});++describe('useTripAddonRows', () => {+ it('FE-TRIPADDONROWS-001: names each addon from the catalog, with its icon and whether the trip chose it', async () => {+ const { result } = renderHook(() => useTripAddonRows(4), { wrapper });+ expect(result.current.loading).toBe(true);+ await waitFor(() => expect(result.current.rows).toHaveLength(3));++ const [packing, roadtrip, plugin] = result.current.rows;+ expect(packing).toMatchObject({ name: 'Lists', Icon: ListChecks, enabled: true, ownChoice: false });+ expect(packing.description).not.toBe('');+ expect(roadtrip).toMatchObject({ Icon: CarFront, enabled: false, ownChoice: true });+ // An addon the catalog does not know keeps the server's name, no description and the fallback icon.+ expect(plugin).toMatchObject({ name: 'Some plugin', description: '', Icon: Puzzle });+ expect(result.current.loading).toBe(false);+ });++ it('FE-TRIPADDONROWS-002: a switch away from the instance stores the choice, back to it drops the choice', async () => {+ const { result } = renderHook(() => useTripAddonRows(4), { wrapper });+ await waitFor(() => expect(result.current.rows).toHaveLength(3));++ act(() => result.current.rows[0].toggle());+ await waitFor(() => expect(bodies).toEqual([{ enabled: false }]));+ await waitFor(() => expect(result.current.rows[0].busy).toBe(false));++ act(() => result.current.rows[1].toggle());+ await waitFor(() => expect(bodies).toEqual([{ enabled: false }, { enabled: null }]));+ });++ it('FE-TRIPADDONROWS-003: a second switch while one is saving is ignored', async () => {+ const { result } = renderHook(() => useTripAddonRows(4), { wrapper });+ await waitFor(() => expect(result.current.rows).toHaveLength(3));++ act(() => result.current.rows[0].toggle());+ expect(result.current.rows[0].busy).toBe(true);+ act(() => result.current.rows[2].toggle());+ await waitFor(() => expect(result.current.rows[0].busy).toBe(false));+ expect(bodies).toEqual([{ enabled: false }]);+ });+});diff --git a/client/src/components/Trips/useTripAddonRows.ts b/client/src/components/Trips/useTripAddonRows.tsnew file mode 100644index 000000000..7200f2055--- /dev/null+++ b/client/src/components/Trips/useTripAddonRows.ts@@ -0,0 +1,74 @@+import {+ CarFront,+ Compass,+ FileText,+ ListChecks,+ Mountain,+ Puzzle,+ Users,+ Wallet,+ type LucideIcon,+} from 'lucide-react';+import { useState } from 'react';++import { useTranslation } from '../../i18n';+import { useTripAddons } from './useTripAddons';++/** The addons table's `icon` names of the trip addons; road trip was seeded as `Route`, the car says it better. */+const ICONS: Readonly<Record<string, LucideIcon>> = {+ ListChecks,+ Wallet,+ FileText,+ Users,+ Route: CarFront,+ Mountain,+ Compass,+};++/** One trip addon as the trip settings list it. */+export interface TripAddonRow {+ id: string;+ name: string;+ description: string;+ Icon: LucideIcon;+ enabled: boolean;+ /** The owner chose this for the trip, so it differs from the instance. */+ ownChoice: boolean;+ busy: boolean;+ toggle: () => void;+}++/**+ * The rows of the trip settings' Addons area, the same on the desktop dialog and+ * the phone sheet. Flipping a switch back to what the instance says drops the+ * trip's own choice instead of storing a copy of it, so a later change by the+ * admin reaches the trip again and no reset button is needed.+ */+export function useTripAddonRows(tripId: number) {+ const { t } = useTranslation();+ const trip = useTripAddons(tripId);+ const [busy, setBusy] = useState<string | null>(null);++ const rows: TripAddonRow[] = trip.addons.map((addon) => {+ // Spelled out inside t() so the key check sees which catalog keys this reaches.+ const name = t(`admin.addons.catalog.${addon.id}.name`);+ const description = t(`admin.addons.catalog.${addon.id}.description`);+ return {+ id: addon.id,+ name: name === `admin.addons.catalog.${addon.id}.name` ? addon.name : name,+ description: description === `admin.addons.catalog.${addon.id}.description` ? '' : description,+ Icon: (addon.icon && ICONS[addon.icon]) || Puzzle,+ enabled: addon.enabled,+ ownChoice: addon.overridden,+ busy: busy === addon.id,+ toggle: () => {+ if (busy) return;+ const next = !addon.enabled;+ setBusy(addon.id);+ void trip.setOverride(addon.id, next === addon.instanceEnabled ? null : next).finally(() => setBusy(null));+ },+ };+ });++ return { rows, loading: trip.loading && rows.length === 0 };+}diff --git a/client/src/components/Trips/useTripAddons.test.tsx b/client/src/components/Trips/useTripAddons.test.tsxnew file mode 100644index 000000000..42a87658f--- /dev/null+++ b/client/src/components/Trips/useTripAddons.test.tsx@@ -0,0 +1,182 @@+// FE-TRIPADDONS-HOOK-001 to FE-TRIPADDONS-HOOK-006: the trip addons of one trip for the+// planner and the trip settings: read, refreshed when the connection returns, switched+// by the owner online only.+import { act, renderHook, waitFor } from '@testing-library/react';+import type { TripAddon } from '@trek/shared';+import 'fake-indexeddb/auto';+import { http, HttpResponse } from 'msw';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { buildUser } from '../../../tests/helpers/factories';+import { server } from '../../../tests/helpers/msw/server';+import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';+import { clearAll } from '../../db/offlineDb';+import { TranslationProvider } from '../../i18n/TranslationContext';+import { useAuthStore } from '../../store/authStore';+import { useTripAddons } from './useTripAddons';++const env = vi.hoisted(() => ({+ offline: false,+ modeListeners: [] as Array<() => void>,+ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() },+}));++vi.mock('../../sync/networkMode', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../../sync/networkMode')>();+ return {+ ...actual,+ isEffectivelyOffline: () => env.offline,+ onNetworkModeChange: (fn: () => void) => {+ env.modeListeners.push(fn);+ return () => {+ env.modeListeners = env.modeListeners.filter((l) => l !== fn);+ };+ },+ };+});++vi.mock('../shared/Toast', () => ({ useToast: () => env.toast }));++const addon = (id: string, enabled: boolean, instanceEnabled: boolean): TripAddon => ({+ id,+ name: id,+ icon: null,+ enabled,+ instanceEnabled,+ overridden: enabled !== instanceEnabled,+});++function wrapper({ children }: { children: ReactNode }) {+ return <TranslationProvider>{children}</TranslationProvider>;+}++function tripHas(addons: TripAddon[]) {+ server.use(http.get('/api/trips/4/addons', () => HttpResponse.json({ tripId: 4, addons })));+}++beforeEach(async () => {+ await clearAll();+ resetAllStores();+ vi.clearAllMocks();+ env.offline = false;+ env.modeListeners = [];+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('useTripAddons', () => {+ it('FE-TRIPADDONS-HOOK-001: reads the trip’s list, and until then answers with the instance switches', async () => {+ seedInstanceAddons(['budget']);+ tripHas([addon('budget', false, true), addon('tours', true, false)]);++ const { result } = renderHook(() => useTripAddons(4), { wrapper });++ expect(result.current.loading).toBe(true);+ expect(result.current.loaded).toBe(false);+ expect(result.current.isEnabled('budget')).toBe(true);++ await waitFor(() => expect(result.current.loaded).toBe(true));+ expect(result.current.loading).toBe(false);+ expect(result.current.addons.map((a) => a.id)).toEqual(['budget', 'tours']);+ expect(result.current.isEnabled('budget')).toBe(false);+ expect(result.current.isEnabled('tours')).toBe(true);+ // Not a trip addon: the instance decides.+ expect(result.current.isEnabled('dawarich')).toBe(false);+ });++ it('FE-TRIPADDONS-HOOK-002: reads again when the connection comes back, and no trip reads nothing', async () => {+ let asked = 0;+ server.use(+ http.get('/api/trips/4/addons', () => {+ asked++;+ return HttpResponse.json({ tripId: 4, addons: [addon('budget', asked > 1, true)] });+ })+ );+ const { result } = renderHook(() => useTripAddons(4), { wrapper });+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.isEnabled('budget')).toBe(false);++ expect(env.modeListeners).toHaveLength(1);+ act(() => env.modeListeners.forEach((listener) => listener()));++ await waitFor(() => expect(result.current.isEnabled('budget')).toBe(true));+ expect(asked).toBe(2);++ const none = renderHook(() => useTripAddons(null), { wrapper });+ expect(none.result.current).toMatchObject({ addons: [], loading: false, loaded: false });+ });++ it('FE-TRIPADDONS-HOOK-003: the owner switches an addon, and the trip follows the answer', async () => {+ let sent: unknown = null;+ server.use(+ http.put('/api/trips/4/addons/budget', async ({ request }) => {+ sent = await request.json();+ return HttpResponse.json({ tripId: 4, addons: [addon('budget', true, false)] });+ })+ );+ const { result } = renderHook(() => useTripAddons(4), { wrapper });+ await waitFor(() => expect(result.current.loaded).toBe(true));++ let ok = false;+ await act(async () => {+ ok = await result.current.setOverride('budget', true);+ });++ expect(ok).toBe(true);+ expect(sent).toEqual({ enabled: true });+ expect(result.current.isEnabled('budget')).toBe(true);+ expect(env.toast.error).not.toHaveBeenCalled();+ });++ it('FE-TRIPADDONS-HOOK-004: offline the switch is refused with a word why, and nothing is sent', async () => {+ let sent = false;+ server.use(+ http.put('/api/trips/4/addons/:addonId', () => {+ sent = true;+ return HttpResponse.json({ tripId: 4, addons: [] });+ })+ );+ const { result } = renderHook(() => useTripAddons(4), { wrapper });+ env.offline = true;++ let ok = true;+ await act(async () => {+ ok = await result.current.setOverride('budget', false);+ });++ expect(ok).toBe(false);+ expect(sent).toBe(false);+ expect(env.toast.error).toHaveBeenCalledWith(expect.stringMatching(/connection/i));+ });++ it('FE-TRIPADDONS-HOOK-005: a refusal from the server is said in its own words', async () => {+ server.use(+ http.put('/api/trips/4/addons/budget', () =>+ HttpResponse.json({ error: 'Only the owner can change the addons of this trip' }, { status: 403 })+ )+ );+ const { result } = renderHook(() => useTripAddons(4), { wrapper });++ let ok = true;+ await act(async () => {+ ok = await result.current.setOverride('budget', null);+ });++ expect(ok).toBe(false);+ expect(env.toast.error).toHaveBeenCalledWith('Only the owner can change the addons of this trip');+ });++ it('FE-TRIPADDONS-HOOK-006: a failure without the server’s words falls back to the localized one', async () => {+ server.use(http.put('/api/trips/4/addons/budget', () => HttpResponse.json({}, { status: 500 })));+ const { result } = renderHook(() => useTripAddons(4), { wrapper });++ await act(async () => {+ await result.current.setOverride('budget', true);+ });++ expect(env.toast.error).toHaveBeenCalledWith('The addons of this trip could not be changed.');+ });+});diff --git a/client/src/components/Trips/useTripAddons.ts b/client/src/components/Trips/useTripAddons.tsnew file mode 100644index 000000000..87dc9765e--- /dev/null+++ b/client/src/components/Trips/useTripAddons.ts@@ -0,0 +1,79 @@+import type { TripAddon } from '@trek/shared';+import { useCallback, useEffect, useMemo } from 'react';++import { useTranslation } from '../../i18n';+import { useAddonStore } from '../../store/addonStore';+import { tripAddonsEntry, useTripAddonsStore } from '../../store/tripAddonsStore';+import { onNetworkModeChange } from '../../sync/networkMode';+import { getApiErrorMessage } from '../../types';+import { refusedOffline } from '../../utils/needsConnection';+import { tripAddonEnabled } from '../../utils/tripAddons';+import { useToast } from '../shared/Toast';++const NONE: TripAddon[] = [];++/**+ * The trip addons of one trip, each on or off for it, for the trip planner and+ * the trip's settings. Reads the trip's list when the trip changes and again+ * when the connection comes back; a change another member's owner made arrives+ * live through useTripAddonsSync.+ *+ * - `addons`: every trip addon as the trip sees it, in the admin's order; empty+ * until the first read answered (or offline with nothing kept).+ * - `isEnabled(id)`: whether an addon applies here; before the list is known,+ * and for an addon it does not name, the instance switch.+ * - `setOverride(id, enabled)`: the owner switches one addon for the trip,+ * `null` going back to the instance setting. Online only: offline it says so+ * and answers false. Answers whether the server took the change.+ */+export function useTripAddons(tripId: number | null | undefined) {+ const toast = useToast();+ const { t } = useTranslation();+ const validId = tripId != null && Number.isSafeInteger(tripId) && tripId > 0 ? tripId : null;+ const entry = useTripAddonsStore((state) => tripAddonsEntry(state, validId));+ // The instance list, so isEnabled answers anew once it is read.+ const instanceAddons = useAddonStore((state) => state.addons);++ useEffect(() => {+ if (validId == null) return;+ const load = () => void useTripAddonsStore.getState().load(validId);+ load();+ return onNetworkModeChange(load);+ }, [validId]);++ const isEnabled = useCallback(+ (addonId: string) =>+ tripAddonEnabled(+ entry?.addons,+ addonId,+ instanceAddons.some((addon) => addon.id === addonId && addon.enabled)+ ),+ [entry?.addons, instanceAddons]+ );++ const setOverride = useCallback(+ async (addonId: string, enabled: boolean | null): Promise<boolean> => {+ if (validId == null || refusedOffline(toast, t)) return false;+ try {+ await useTripAddonsStore.getState().setOverride(validId, addonId, enabled);+ return true;+ } catch (err) {+ toast.error(getApiErrorMessage(err, t('trip.addons.saveFailed')));+ return false;+ }+ },+ [validId, toast, t]+ );++ return useMemo(+ () => ({+ addons: entry?.addons ?? NONE,+ loading: validId != null && (!entry || entry.status === 'loading'),+ /** A list is held, or the first read failed; until then isEnabled is the instance switch. */+ loaded: !!entry && (entry.addons != null || entry.status !== 'loading'),+ isEnabled,+ setOverride,+ }),+ [entry, validId, isEnabled, setOverride]+ );+}diff --git a/client/src/components/Trips/useTripShare.ts b/client/src/components/Trips/useTripShare.tsindex 8f4ae05fa..7788f0258 100644--- a/client/src/components/Trips/useTripShare.ts+++ b/client/src/components/Trips/useTripShare.ts@@ -9,6 +9,7 @@ import { useTranslation } from '../../i18n'import { getApiErrorMessage } from '../../types'import { useCopied } from '../../hooks/useCopied'import { refusedOffline } from '../../utils/needsConnection'+import { useTripAddons } from './useTripAddons'// The state behind the share dialog, shared by the desktop dialog and the one the// phone opens from its More sheet. The questions ("Remove this member?") are the@@ -22,13 +23,13 @@ const DEFAULT_PERMS: SharePerms = {share_travel_only: false, share_hide_images: false,}-/** What the link shows, one tab each. */-export const SHARE_SECTIONS: { key: SharePerm; label: string; always?: boolean }[] = [+/** What the link shows, one tab each; a tab of an addon only while the trip has that addon on. */+const SHARE_SECTIONS: { key: SharePerm; label: string; always?: boolean; addon?: string }[] = [{ key: 'share_map', label: 'share.permMap', always: true },{ key: 'share_bookings', label: 'share.permBookings' },- { key: 'share_packing', label: 'share.permPacking' },- { key: 'share_budget', label: 'share.permBudget' },- { key: 'share_collab', label: 'share.permCollab' },+ { key: 'share_packing', label: 'share.permPacking', addon: 'packing' },+ { key: 'share_budget', label: 'share.permBudget', addon: 'budget' },+ { key: 'share_collab', label: 'share.permCollab', addon: 'collab' },]/** How the plan it shows is narrowed (#1712). */@@ -45,6 +46,10 @@ export function useShareLink(tripId: number) {const { copied, copy } = useCopied()const toast = useToast()const { t } = useTranslation()+ // A section of an addon the trip has off is not offered: the link would not show it+ // anyway. Its stored choice stays and counts again once the addon is back on.+ const tripAddons = useTripAddons(tripId)+ const sections = SHARE_SECTIONS.filter(section => !section.addon || tripAddons.isEnabled(section.addon))useEffect(() => {shareApi.getLink(tripId).then(d => {@@ -85,7 +90,7 @@ export function useShareLink(tripId: number) {} catch { toast.error(t('common.error')) }}- return { loading, url, perms, copied, create, setPerm, remove, copy: () => copy(url) }+ return { loading, url, perms, sections, copied, create, setPerm, remove, copy: () => copy(url) }}/** The rotating link an existing user opens to join the trip (#1143). */diff --git a/client/src/db/offlineDb.ts b/client/src/db/offlineDb.tsindex b2ab4ec90..929c91505 100644--- a/client/src/db/offlineDb.ts+++ b/client/src/db/offlineDb.ts@@ -1,4 +1,4 @@-import type { Ferrata, RoadtripPreferences, TourActivity, TourDraft, TourListItem, TourObstacleCheck, TourPackingLink, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';+import type { Ferrata, RoadtripPreferences, TripAddon, TourActivity, TourDraft, TourListItem, TourObstacleCheck, TourPackingLink, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';import Dexie, { type Table } from 'dexie';import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember, Tag, Category } from '../types';@@ -80,6 +80,15 @@ interface CachedTripTags {tags: Tag[];}+/**+ * The trip addons of one trip as the server last listed them, each on or off for+ * that trip: one row per trip, so a trip opened offline shows the tabs it had.+ */+interface CachedTripAddons {+ tripId: number;+ addons: TripAddon[];+}+/*** A road route as the router answered it, kept on the device so a trip opens* with its roads drawn instead of asking the router for every leg again (#2794).@@ -304,6 +313,7 @@ export class TrekOfflineDb extends Dexie {tourDrafts!: Table<CachedTourDraft, number>;routeCache!: Table<CachedRoute, string>;tripTags!: Table<CachedTripTags, number>;+ tripAddons!: Table<CachedTripAddons, number>;constructor(name: string = ANON_DB_NAME) {super(name);@@ -400,6 +410,10 @@ export class TrekOfflineDb extends Dexie {// v15: the tags a trip owns, one list per trip, so they are offered offline// and go with the trip.this.version(15).stores({ tripTags: 'tripId' });++ // v16: the trip addons of each trip, on or off for that trip, one list per+ // trip, so the tabs a trip switched off stay hidden offline too.+ this.version(16).stores({ tripAddons: 'tripId' });}}@@ -702,11 +716,13 @@ export async function clearTripData(tripId: number): Promise<void> {offlineDb.tourStationVisits,offlineDb.tourDrafts,offlineDb.tripTags,+ offlineDb.tripAddons,],async () => {await offlineDb.roadtripPreferences.delete(tripId);await offlineDb.tourDrafts.delete(tripId);await offlineDb.tripTags.delete(tripId);+ await offlineDb.tripAddons.delete(tripId);await offlineDb.budgetSettlements.delete(tripId);await offlineDb.days.where('trip_id').equals(tripId).delete();await offlineDb.places.where('trip_id').equals(tripId).delete();diff --git a/client/src/hooks/useRouteCalculation.ts b/client/src/hooks/useRouteCalculation.tsindex eef92c23d..7c92ef138 100644--- a/client/src/hooks/useRouteCalculation.ts+++ b/client/src/hooks/useRouteCalculation.ts@@ -3,7 +3,7 @@ import { isServiceStopType } from '../components/Roadtrip/roadtripModel'import { useState, useCallback, useRef, useEffect, useMemo } from 'react'import { useTripStore } from '../store/tripStore'import { useSettingsStore } from '../store/settingsStore'-import { useAddonStore } from '../store/addonStore'+import { useTripAddonEnabled } from '../store/tripAddonsStore'import { calculateRouteWithRetries, type RouteProfileKey } from '../components/Map/routeRetry'import { buildDayRouteRuns, hotelBookendOf, TRANSPORT_TYPES, type DayRouteInputs } from '../components/Map/dayRoutePlan'import { dayViaLookup, foldViaLegs, threadVias, viaKeyOf, viasOnDayLeg } from '../utils/dayRouteVias'@@ -36,7 +36,8 @@ export function useRouteCalculation(tripStore: Pick<TripStoreState, 'assignments// 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 toursEnabled = useAddonStore(s => s.isEnabled('tours'))+ const activeTripId = useTripStore(s => s.trip?.id)+ const toursEnabled = useTripAddonEnabled(activeTripId, 'tours')const places = useTripStore(s => s.places)const routeAbortRef = useRef<AbortController | null>(null)const reservationsForSignature = useTripStore((s) => s.reservations)diff --git a/client/src/hooks/useTripAddonsSync.ts b/client/src/hooks/useTripAddonsSync.tsnew file mode 100644index 000000000..b80230d2c--- /dev/null+++ b/client/src/hooks/useTripAddonsSync.ts@@ -0,0 +1,14 @@+import { useEffect } from 'react';++import { useAuthStore } from '../store/authStore';+import { watchTripAddons } from '../store/tripAddonsStore';++/**+ * Keeps the trip addons of every trip the app looks at live while someone is+ * signed in: the trip owner switching an addon reaches every member at once.+ * Mounted once, by App.+ */+export function useTripAddonsSync(): void {+ const userId = useAuthStore((s) => s.user?.id);+ useEffect(() => (userId ? watchTripAddons() : undefined), [userId]);+}diff --git a/client/src/mobile/components/NativeImportSheet.test.tsx b/client/src/mobile/components/NativeImportSheet.test.tsxindex ec5f6da4c..a7e0fa7ea 100644--- a/client/src/mobile/components/NativeImportSheet.test.tsx+++ b/client/src/mobile/components/NativeImportSheet.test.tsx@@ -1,8 +1,11 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';+import { ToastContainer } from '../../components/shared/Toast';import { saveSharedLink, useSharedImportStore } from '../../native/sharedFiles';+import { tripAddonsRepo } from '../../repo/tripAddonsRepo';import { tripRepo } from '../../repo/tripRepo';import { useAddonStore } from '../../store/addonStore';+import { useTripAddonsStore } from '../../store/tripAddonsStore';import NativeImportSheet from './NativeImportSheet';const navigate = vi.hoisted(() => vi.fn());@@ -21,6 +24,9 @@ beforeEach(() => {navigate.mockReset();useSharedImportStore.setState({ file: null, tripId: null, link: null });useAddonStore.setState({ addons: [{ id: 'collab', enabled: true }] as never, loaded: true });+ useTripAddonsStore.setState({ trips: {} });+ // Every trip follows the instance switch unless a test says otherwise; answered at once, so no read outlives its test.+ vi.spyOn(tripAddonsRepo, 'list').mockResolvedValue([]);vi.mocked(saveSharedLink).mockReset().mockResolvedValue();vi.spyOn(tripRepo, 'list').mockResolvedValue({trips: [@@ -33,6 +39,15 @@ beforeEach(() => {const page = () => new File(['<html></html>'], 'hotel.html', { type: 'text/html' });const bareLink = () => new File(['https://hotel.example/stay'], 'link.url', { type: 'text/uri-list' });+/** Trip 2's own Collab choice; trip 1 follows the instance. */+const collabOnlyFor2 = (enabled: boolean) =>+ vi+ .spyOn(tripAddonsRepo, 'list')+ .mockImplementation(async (tripId: number) =>+ tripId === 2+ ? [{ id: 'collab', name: 'Collab', icon: null, enabled, instanceEnabled: !enabled, overridden: true }]+ : []+ );const link = (presetTripId: number | null = null) => ({url: 'https://hotel.example/stay',title: 'Hotel Kanra',@@ -116,6 +131,33 @@ describe('NativeImportSheet', () => {expect(useSharedImportStore.getState().file).not.toBeNull();});+ it('keeps a link in a trip that switched Collab on while the instance has it off, offering only that trip', async () => {+ useAddonStore.setState({ addons: [], loaded: true });+ collabOnlyFor2(true);+ render(<NativeImportSheet />);+ act(() => useSharedImportStore.getState().setFile(page(), link()));++ fireEvent.click(await screen.findByRole('button', { name: /Save to the trip's links/ }));+ expect(await screen.findByRole('button', { name: /Japan/ })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Past trip/ })).not.toBeInTheDocument();+ });++ it('leaves out a trip that switched Collab off, and shows why when the server refuses the link', async () => {+ collabOnlyFor2(false);+ vi.mocked(saveSharedLink).mockRejectedValue({ response: { data: { error: 'Collab addon is not enabled' } } });+ render(+ <>+ <ToastContainer />+ <NativeImportSheet />+ </>+ );+ act(() => useSharedImportStore.getState().setFile(bareLink(), link(2)));++ expect(await screen.findByText('Collab addon is not enabled')).toBeInTheDocument();+ expect(await screen.findByRole('button', { name: /Past trip/ })).toBeInTheDocument();+ await waitFor(() => expect(screen.queryByRole('button', { name: /Japan/ })).not.toBeInTheDocument());+ });+it('stays closed with nothing shared', () => {render(<NativeImportSheet />);expect(screen.queryByRole('dialog')).not.toBeInTheDocument();diff --git a/client/src/mobile/components/NativeImportSheet.tsx b/client/src/mobile/components/NativeImportSheet.tsxindex 4643756a2..4321270f6 100644--- a/client/src/mobile/components/NativeImportSheet.tsx+++ b/client/src/mobile/components/NativeImportSheet.tsx@@ -6,16 +6,21 @@* A web page or a link is asked about first: kept among the trip's links* (Collaboration, Links), or read as a booking. A bare link, whose page the phone* could not read, can only be kept; with Collaboration off, a page can only be read.+ * Collaboration counts per trip: a link goes only to a trip that has it on.*/import { ChevronRight, FileText, Link2, ScanText } from 'lucide-react';import React, { useEffect, useEffectEvent, useRef, useState } from 'react';import { useLocation, useNavigate } from 'react-router';+import { useShallow } from 'zustand/react/shallow';import { useToast } from '../../components/shared/Toast';import { useTranslation } from '../../i18n';import { saveSharedLink, useSharedImportStore, type SharedLink } from '../../native/sharedFiles';import { tripRepo } from '../../repo/tripRepo';import { useAddonStore } from '../../store/addonStore';+import { tripAddonsEntry, useTripAddonsStore } from '../../store/tripAddonsStore';+import { getApiErrorMessage } from '../../utils/apiError';import { offlineOr } from '../../utils/needsConnection';+import { tripAddonEnabled } from '../../utils/tripAddons';import { TileHeader } from '../screens/trip/sheets/MTripSheetUi';import MSheet from './MSheet';@@ -83,6 +88,27 @@ function useTripRows(open: boolean): TripRow[] {return trips;}+/**+ * The trips a shared link may go to: those with Collaboration on, each by its+ * own list (the owner's choice, else the instance switch). The lists are read+ * once the sheet opens for a link, so a trip that switched Collaboration on is+ * offered while the instance has it off, and one that switched it off is not.+ */+function useCollabTrips(trips: TripRow[], active: boolean): TripRow[] {+ const instanceOn = useAddonStore((s) => s.isEnabled('collab'));+ const load = useTripAddonsStore((s) => s.load);+ useEffect(() => {+ if (!active) return;+ trips.forEach((trip) => void load(trip.id));+ }, [active, trips, load]);+ const on = useTripAddonsStore(+ useShallow((state) =>+ trips.map((trip) => tripAddonEnabled(tripAddonsEntry(state, trip.id)?.addons, 'collab', instanceOn))+ )+ );+ return trips.filter((_trip, i) => on[i]);+}+export default function NativeImportSheet(): React.ReactElement | null {const { t } = useTranslation();const toast = useToast();@@ -93,7 +119,12 @@ export default function NativeImportSheet(): React.ReactElement | null {const link = useSharedImportStore((s) => s.link);const chooseTrip = useSharedImportStore((s) => s.chooseTrip);const setFile = useSharedImportStore((s) => s.setFile);- const collabOn = useAddonStore((s) => s.isEnabled('collab'));+ const instanceCollab = useAddonStore((s) => s.isEnabled('collab'));+ const open = !!file && tripId == null;+ const trips = useTripRows(open);+ const collabTrips = useCollabTrips(trips, open && !!link);+ // Before the trips are known the instance switch decides, as it always did.+ const collabOn = trips.length === 0 ? instanceCollab : collabTrips.length > 0;// Both belong to the item they were made for, so a newly shared one starts afresh.const [pick, setPick] = useState<{ file: File; choice: LinkChoice } | null>(null);const [failedFile, setFailedFile] = useState<File | null>(null);@@ -107,8 +138,6 @@ export default function NativeImportSheet(): React.ReactElement | null {picked,presetFailed: failedFile != null && failedFile === file,});- const open = !!file && tripId == null;- const trips = useTripRows(open);// Once a trip is picked (here, or in the share sheet before the app opened), go to// it; its planner opens the booking import with the file (MTripShell).@@ -126,8 +155,9 @@ export default function NativeImportSheet(): React.ReactElement | null {setFile(null);void navigate(`/trips/${id}?tab=collab`);},- () => {- toast.error(offlineOr(t, t('common.error')));+ (err: unknown) => {+ // The server says why, such as a trip that has Collaboration off.+ toast.error(offlineOr(t, getApiErrorMessage(err, t('common.error'))));savingRef.current = null;setFailedFile(file);}@@ -164,7 +194,7 @@ export default function NativeImportSheet(): React.ReactElement | null {{t('native.share.linkUnsupported')}</p>)}- {showTrips && <TripPicker trips={trips} onPick={pickTrip} />}+ {showTrips && <TripPicker trips={choice === 'link' ? collabTrips : trips} onPick={pickTrip} />}</div></MSheet>);diff --git a/client/src/mobile/screens/trip/places/MPlacesBrowser.tsx b/client/src/mobile/screens/trip/places/MPlacesBrowser.tsxindex 8d6b866d8..24d50aa14 100644--- a/client/src/mobile/screens/trip/places/MPlacesBrowser.tsx+++ b/client/src/mobile/screens/trip/places/MPlacesBrowser.tsx@@ -6,6 +6,7 @@ import {import MDancingTrek from '../../../components/MDancingTrek'import MChipStrip from '../../../components/MChipStrip'import { useAddonStore } from '../../../../store/addonStore'+import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'import PlaceAvatar from '../../../../components/shared/PlaceAvatar'import MarkdownText from '../../../../components/shared/MarkdownText'import { getCategoryIcon } from '../../../../components/shared/categoryIcons'@@ -45,7 +46,7 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)const { locale } = useTranslation()const canEditPlaces = planner.can('place_edit', trip)const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))- const toursEnabled = useAddonStore(s => s.isEnabled('tours'))+ const toursEnabled = useTripAddonEnabled(tripId, 'tours')// Top level of the places browser, mirroring the desktop right add-panel's// Places <-> Tours switch placement.const [toursMode, setToursMode] = useState(false)diff --git a/client/src/mobile/screens/trip/sheets/MImportSheet.tsx b/client/src/mobile/screens/trip/sheets/MImportSheet.tsxindex e0e5b4ca3..85a10d4c9 100644--- a/client/src/mobile/screens/trip/sheets/MImportSheet.tsx+++ b/client/src/mobile/screens/trip/sheets/MImportSheet.tsx@@ -6,9 +6,9 @@ import MIconBtn from '../../../components/MIconBtn'import { FormSheetHeader } from './PlSheetChrome'import ImpFileStep from './ImpFileStep'import ImpListStep from './ImpListStep'-import { useAddonStore } from '../../../../store/addonStore'import { usePlacesColumnFileImport } from '../../../../components/Planner/usePlacesColumnFileImport'import TourGpxPreviewDialog from '../../../../components/Tours/TourGpxPreviewDialog'+import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'import type { TripPlanner } from '../MTripShell'export interface MImportSheetProps {@@ -32,7 +32,7 @@ type ImportStep = 'menu' | 'file' | 'list'export default function MImportSheet({ planner, open, onClose }: MImportSheetProps) {const { t, tripId, trip, can } = plannerconst [step, setStep] = useState<ImportStep>('menu')- const toursEnabled = useAddonStore(s => s.isEnabled('tours'))+ const toursEnabled = useTripAddonEnabled(tripId, 'tours')const fileImport = usePlacesColumnFileImport({tripId,toursEnabled,diff --git a/client/src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx b/client/src/mobile/screens/trip/sheets/MPlaceEditSheet.tsxindex 6c48c70dd..97dad1b99 100644--- a/client/src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx+++ b/client/src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx@@ -16,7 +16,7 @@ import { usePlaceForm } from '../../../../components/Planner/usePlaceForm'import { usePlaceTags } from '../../../../components/Planner/usePlaceTags'import { addressWithoutCoordinates } from '../../../../components/Planner/placeCoordinates'import { AMOUNT_FIELD_CLS, Eyebrow, FIELD_CLS, FormSheetBody, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'-import { useAddonStore } from '../../../../store/addonStore'+import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'import PlPlaceSearch, { type PlSearchPick } from './PlPlaceSearch'import PlCategoryPicker from './PlCategoryPicker'@@ -90,7 +90,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditShconst [resolvingPick, setResolvingPick] = useState(false)// The hours the details looked up, offered to the hours editor as on the desktop.const [detailsHours, setDetailsHours] = useState<PlaceOpeningHours | null>(null)- const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))+ const isBudgetEnabled = useTripAddonEnabled(planner.tripId, 'budget')// Set right before submit: the place has to exist before an expense can point// at it, exactly like MReservationSheet does it.const expenseIntentRef = useRef(false)diff --git a/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx b/client/src/mobile/screens/trip/sheets/MReservationSheet.tsxindex f73b0143f..93576f054 100644--- a/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx+++ b/client/src/mobile/screens/trip/sheets/MReservationSheet.tsx@@ -3,7 +3,7 @@ import { Link2, Ticket } from 'lucide-react'import MSheet from '../../../components/MSheet'import MWalletButton from '../../../components/MWalletButton'import { MBookingCodeStatus, MBookingNotes, MBookingTravelers } from './MBookingFields'-import { useAddonStore } from '../../../../store/addonStore'+import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'import { useTranslation } from '../../../../i18n'import CustomSelect from '../../../../components/shared/CustomSelect'import CustomTimePicker from '../../../../components/shared/CustomTimePicker'@@ -59,7 +59,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati} = plannerconst { locale } = useTranslation()- const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))+ const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')const {form, setForm, set, isSaving, setIsSaving, pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler,diff --git a/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx b/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsxindex fd1f138e8..c713bf028 100644--- a/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx+++ b/client/src/mobile/screens/trip/sheets/MTransportFormSheet.tsx@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react'import { ChevronDown, ChevronUp, Plus, TrainFront, TramFront, X } from 'lucide-react'import MSheet from '../../../components/MSheet'import { MBookingCodeStatus, MBookingNotes, MBookingTravelers, MRouteStopCard } from './MBookingFields'-import { useAddonStore } from '../../../../store/addonStore'+import { useTripAddonEnabled } from '../../../../store/tripAddonsStore'import { useTranslation } from '../../../../i18n'import CustomSelect from '../../../../components/shared/CustomSelect'import CustomTimePicker from '../../../../components/shared/CustomTimePicker'@@ -56,7 +56,7 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo} = plannerconst { locale } = useTranslation()- const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))+ const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')const tripHasDates = Boolean(trip?.start_date && trip?.end_date)// The trip's places, offered by every location field of the manual tab (#2468).const locationPicks = useMemo(() => toLocationPicks(places), [places])diff --git a/client/src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx b/client/src/mobile/screens/trip/sheets/MTripSettingsSheet.tsxindex 4b172f056..338a61b05 100644--- a/client/src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx+++ b/client/src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx@@ -7,6 +7,7 @@ import {LogOut,Pencil,Plus,+ Puzzle,RefreshCw,Settings2,Trash2,@@ -20,10 +21,10 @@ import CustomSelect from '../../../../components/shared/CustomSelect';import { LinkedJournalIcon } from '../../../../components/Trips/LinkedJournalIcon';import { TripJournalLinkSection } from '../../../../components/Trips/TripJournalLinkSection';import { TripMemberAvatar } from '../../../../components/Trips/TripMemberAvatar';+import { useTripAddonRows } from '../../../../components/Trips/useTripAddonRows';import { useTripJournalSectionVisible } from '../../../../components/Trips/useTripJournalLink';import {SHARE_OPTIONS,- SHARE_SECTIONS,useShareLink,useTripInviteLink,useTripMembers,@@ -33,6 +34,7 @@ import { useTranslation } from '../../../../i18n';import MChip from '../../../components/MChip';import MLinkField from '../../../components/MLinkField';import MSheet from '../../../components/MSheet';+import MToggle from '../../../components/MToggle';import MConfirmSheet from '../../settings/MConfirmSheet';import {SHEET_FIELD as FIELD,@@ -91,7 +93,7 @@ function ShareLinkSection({ tripId }: { tripId: number }) {return (<Section title={t('share.linkTitle')} hint={t('share.linkHint')}><div className="flex flex-wrap gap-1.5">- {[...SHARE_SECTIONS, ...SHARE_OPTIONS].map((option) => {+ {[...link.sections, ...SHARE_OPTIONS].map((option) => {const always = 'always' in option && !!option.always;const on = !!link.perms[option.key];return (@@ -396,8 +398,40 @@ function GuestsSection({ m, ask }: { m: Members; ask: Ask }) {);}+/** The trip addons with their switches, for the owner; a pill marks the ones set apart from the instance. */+function AddonsSection({ tripId }: { tripId: number }) {+ const { t } = useTranslation();+ const { rows, loading } = useTripAddonRows(tripId);+ return (+ <Section hint={t('trip.settings.addonsHint')}>+ {loading ? (+ <div className="h-[44px] animate-pulse rounded-full bg-[color:var(--m-ic)]" />+ ) : (+ rows.map((row) => (+ <div key={row.id} className="flex min-h-[44px] items-center gap-[10px]">+ <span+ className={`flex h-8 w-8 flex-none items-center justify-center rounded-[10px] bg-[color:var(--m-ic)] ${row.enabled ? 'text-m-ink' : 'text-m-faint'}`}+ >+ <row.Icon size={16} strokeWidth={2} />+ </span>+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">+ <span className="min-w-0 truncate text-[length:calc(13.5px*var(--fs-scale-body,1))] font-semibold text-m-ink">+ {row.name}+ </span>+ {row.ownChoice && (+ <span className={`${PILL} bg-[color:var(--m-ic)] text-m-muted`}>{t('trip.addons.thisTripOnly')}</span>+ )}+ </div>+ <MToggle checked={row.enabled} onChange={row.toggle} ariaLabel={row.name} disabled={row.busy} />+ </div>+ ))+ )}+ </Section>+ );+}+/** The areas the sheet opens into, each a page of its own. */-type Page = 'people' | 'sharing' | 'journal';+type Page = 'people' | 'sharing' | 'journal' | 'addons';/** One row of the sheet's first page: an icon tile, the area's name, what it holds, a chevron. */function AreaRow({@@ -427,9 +461,10 @@ function AreaRow({* The trip's settings on the phone (the Mehr sheet's "Trip settings"). The* first page lists the areas, like the phone's own settings, and each opens as* a page of its own with a way back: who is on the trip and its guests, the two- * links, and the linked journal. One list rather than every card at once, so- * the sheet stays calm as areas are added. The state is useTripShare's, the same- * the desktop dialog runs on; only the markup and the questions are the phone's.+ * links, the linked journal, and for the owner the trip's own addons. One list+ * rather than every card at once, so the sheet stays calm as areas are added.+ * The state is useTripShare's and useTripAddonRows', the same the desktop+ * dialog runs on; only the markup and the questions are the phone's.*/export default function MTripSettingsSheet({open,@@ -463,6 +498,7 @@ export default function MTripSettingsSheet({people: t('trip.settings.people'),sharing: t('trip.settings.sharing'),journal: t('trip.journal.title'),+ addons: t('trip.settings.addons'),};const people = m.realMembers.length + m.guests.length;@@ -518,6 +554,13 @@ export default function MTripSettingsSheet({onOpen={() => setPage('journal')}/>)}+ {m.isCurrentOwner && (+ <AreaRow+ icon={<Puzzle size={16} strokeWidth={2} />}+ label={pageTitle.addons}+ onOpen={() => setPage('addons')}+ />+ )}</nav>)}{page === 'people' && (@@ -533,6 +576,7 @@ export default function MTripSettingsSheet({</>)}{page === 'journal' && <TripJournalLinkSection tripId={tripId} />}+ {page === 'addons' && m.isCurrentOwner && <AddonsSection tripId={tripId} />}</div></MSheet>diff --git a/client/src/pages/TripPlannerPage.test.tsx b/client/src/pages/TripPlannerPage.test.tsxindex abd3cd129..f8469b425 100644--- a/client/src/pages/TripPlannerPage.test.tsx+++ b/client/src/pages/TripPlannerPage.test.tsx@@ -456,7 +456,7 @@ describe('TripPlannerPage', () => {it('shows PackingListPanel after clicking the Lists tab with packing addon enabled', async () => {server.use(http.get('/api/addons', () =>- HttpResponse.json({ addons: [{ id: 'packing', type: 'packing' }] })+ HttpResponse.json({ addons: [{ id: 'packing', type: 'trip', enabled: true }] })));@@ -483,7 +483,7 @@ describe('TripPlannerPage', () => {it('shows CostsPanel after clicking the Costs tab with budget addon enabled', async () => {server.use(http.get('/api/addons', () =>- HttpResponse.json({ addons: [{ id: 'budget', type: 'budget' }] })+ HttpResponse.json({ addons: [{ id: 'budget', type: 'trip', enabled: true }] })));@@ -510,7 +510,7 @@ describe('TripPlannerPage', () => {it('shows FileManager after clicking the Files tab with documents addon enabled', async () => {server.use(http.get('/api/addons', () =>- HttpResponse.json({ addons: [{ id: 'documents', type: 'documents' }] })+ HttpResponse.json({ addons: [{ id: 'documents', type: 'trip', enabled: true }] })));@@ -537,7 +537,7 @@ describe('TripPlannerPage', () => {it('shows CollabPanel after clicking the Collab tab with collab addon enabled', async () => {server.use(http.get('/api/addons', () =>- HttpResponse.json({ addons: [{ id: 'collab', type: 'collab' }] })+ HttpResponse.json({ addons: [{ id: 'collab', type: 'trip', enabled: true }] })));@@ -665,7 +665,7 @@ describe('TripPlannerPage', () => {it('shows TodoListPanel after switching to the Todo subtab inside Lists', async () => {server.use(http.get('/api/addons', () =>- HttpResponse.json({ addons: [{ id: 'packing', type: 'packing' }] })+ HttpResponse.json({ addons: [{ id: 'packing', type: 'trip', enabled: true }] })));@@ -1393,7 +1393,7 @@ describe('TripPlannerPage', () => {it('calls FileManager onUpload/onDelete/onUpdate to cover inline lambda bodies', async () => {server.use(http.get('/api/addons', () =>- HttpResponse.json({ addons: [{ id: 'documents', type: 'documents' }] })+ HttpResponse.json({ addons: [{ id: 'documents', type: 'trip', enabled: true }] })));@@ -1838,7 +1838,7 @@ describe('TripPlannerPage', () => {// road-trip hooks then read their own endpoints, answered empty here.const enterRoadtrip = () => {server.use(- http.get('/api/addons', () => HttpResponse.json({ addons: [{ id: 'roadtrip', type: 'roadtrip' }] })),+ http.get('/api/addons', () => HttpResponse.json({ addons: [{ id: 'roadtrip', type: 'trip', enabled: true }] })),http.get('/api/trips/42/roadtrip/vias', () => HttpResponse.json({ vias: [], tracks: [] })),http.get('/api/trips/42/roadtrip/preferences', () => HttpResponse.json({ tripId: 42, preferences: {} })),);diff --git a/client/src/pages/tripPlanner/usePlannerAddons.ts b/client/src/pages/tripPlanner/usePlannerAddons.tsnew file mode 100644index 000000000..267036ee7--- /dev/null+++ b/client/src/pages/tripPlanner/usePlannerAddons.ts@@ -0,0 +1,54 @@+import { useEffect, useMemo } from 'react';+import { useShallow } from 'zustand/react/shallow';++import { useTripAddons } from '../../components/Trips/useTripAddons';+import { useAddonStore } from '../../store/addonStore';+import { tripAddonEnabled } from '../../utils/tripAddons';++/**+ * What the planner shows while neither the trip's list nor the instance's is+ * known (offline on a trip the device never read the addons of): the core+ * sections on, the rest off, as the planner always guessed.+ */+const WHEN_UNKNOWN: Readonly<Record<string, boolean>> = {+ packing: true,+ budget: true,+ documents: true,+ collab: false,+ roadtrip: false,+ tours: false,+ dawarich: false,+};++/**+ * The addons the trip planner shows for one trip, in both shells: the trip+ * addons as the trip has them (the owner's choice or the instance switch),+ * Dawarich (an integration) and the collab sub-features from the instance.+ * Follows a change of the trip's addons live, so tabs, dock, rail and More+ * sheet appear and go as the owner switches.+ */+export function usePlannerAddons(tripId: number) {+ const tripAddons = useTripAddons(Number.isFinite(tripId) ? tripId : null);+ const instance = useAddonStore(+ useShallow((s) => ({ addons: s.addons, known: (s.loaded && !s.failed) || s.addons.length > 0, loaded: s.loaded }))+ );+ const collabFeatures = useAddonStore((s) => s.collabFeatures);++ // The app reads the instance list once signed in; a planner opened before that answered asks itself.+ useEffect(() => {+ if (!useAddonStore.getState().loaded) void useAddonStore.getState().loadAddons();+ }, []);++ const enabledAddons = useMemo(() => {+ const instanceOn = (id: string) =>+ instance.known ? instance.addons.some((a) => a.id === id && a.enabled) : WHEN_UNKNOWN[id];+ return Object.fromEntries(+ Object.keys(WHEN_UNKNOWN).map((id) => [id, tripAddonEnabled(tripAddons.addons, id, instanceOn(id))])+ ) as Record<string, boolean>;+ }, [tripAddons.addons, instance]);++ // Until then enabledAddons is a guess, and the tab guard must not evict a tab on it.+ const addonsLoaded = tripAddons.loaded && (tripAddons.addons.length > 0 || instance.loaded);++ return { enabledAddons, addonsLoaded, collabFeatures, toursEnabled: !!enabledAddons.tours };+}diff --git a/client/src/pages/tripPlanner/useTourStageLayers.test.ts b/client/src/pages/tripPlanner/useTourStageLayers.test.tsindex eba42f9ac..ba2c01374 100644--- a/client/src/pages/tripPlanner/useTourStageLayers.test.ts+++ b/client/src/pages/tripPlanner/useTourStageLayers.test.ts@@ -29,7 +29,7 @@ const basesOf = (p: Planner, zoom: number | null = null) =>renderHook(() => useTourStageLayers(p, ferrata, zoom)).result.current;describe('useTourStageLayers: OpenHikingMap (MAP-01)', () => {- beforeEach(() => useAddonStore.setState({ toursHikingMap: true, toursCycleMap: true }));+ beforeEach(() => useAddonStore.setState({ toursOptions: { wanderer: false, hikingMap: true, cycleMap: true } }));it('offers it while a hike is open: planned as a draft, a saved tour in the editor, or an import viewed as it came in', () => {const viewed = { type: 'view-gpx', placeId: 9, tour: { place_id: 9, tour_type: 'hike' } as TourListItem } as const;@@ -54,7 +54,7 @@ describe('useTourStageLayers: OpenHikingMap (MAP-01)', () => {});it('not where the admin withdrew it', () => {- useAddonStore.setState({ toursHikingMap: false });+ useAddonStore.setState({ toursOptions: { wanderer: false, hikingMap: false, cycleMap: true } });expect(basesOf(planner({ type: 'new-draft' })).tourLayers.bases).not.toContain('hiking');});@@ -67,7 +67,7 @@ describe('useTourStageLayers: OpenHikingMap (MAP-01)', () => {expect(layers.tourLayers.baseHealth).toMatchObject({ base: 'cycle', down: false });}expect(basesOf(planner({ type: 'new-draft' }, 'hike', 'cycle')).baseLayer).toBe('default');- useAddonStore.setState({ toursCycleMap: false });+ useAddonStore.setState({ toursOptions: { wanderer: false, hikingMap: true, cycleMap: false } });expect(basesOf(planner({ type: 'new-draft' }, 'bike', 'cycle')).tourLayers.bases).not.toContain('cycle');});});diff --git a/client/src/pages/tripPlanner/useTourStageLayers.ts b/client/src/pages/tripPlanner/useTourStageLayers.tsindex 7509c54b6..50a635095 100644--- a/client/src/pages/tripPlanner/useTourStageLayers.ts+++ b/client/src/pages/tripPlanner/useTourStageLayers.ts@@ -36,9 +36,10 @@ export function useTourStageLayers(const { mode } = tourPlanner;// MAP-01, BIK-06: a type's own map (OpenHikingMap for a hike, CyclOSM for a bike tour) while a// tour of that type is open, planned or viewed as it came in, never with no tour open, and only- // while the admin offers it.- const hikingMapAllowed = useAddonStore((state) => state.toursHikingMap);- const cycleMapAllowed = useAddonStore((state) => state.toursCycleMap);+ // while the admin offers it. The options apply wherever Tours is on, the instance switch or the+ // trip's own, and this stage only shows where it is.+ const hikingMapAllowed = useAddonStore((state) => state.toursOptions.hikingMap);+ const cycleMapAllowed = useAddonStore((state) => state.toursOptions.cycleMap);const tourOpen = mode.type !== 'neutral';const openType = mode.type === 'view-gpx' ? mode.tour.tour_type : tourPlanner.tourType;const layerSet = tourMapLayersFor(openType, {diff --git a/client/src/pages/tripPlanner/useTourWorkspace.ts b/client/src/pages/tripPlanner/useTourWorkspace.tsindex 654d957c5..014b187af 100644--- a/client/src/pages/tripPlanner/useTourWorkspace.ts+++ b/client/src/pages/tripPlanner/useTourWorkspace.ts@@ -70,8 +70,9 @@ export function useTourWorkspace(planner: TripPlanner, canPlaceEdit: boolean, catripMembers,upsertTour,} = planner;- // wanderer only while the admin allows it under Tours (the store reads Tours being on into it too).- const wandererAllowed = useAddonStore((state) => state.toursWanderer);+ // wanderer only while the admin allows it under Tours, and Tours is on for this trip (the+ // instance switch or the trip's own).+ const wandererAllowed = useAddonStore((state) => state.toursOptions.wanderer) && !!enabledAddons.tours;// The workspace is up where its tab is: on a desktop, and in the touch shell on a// large screen (an iPad, an unfolded foldable). The app counts as a phone shell on// every device, so the phone test alone left the tablet's editor switched off.diff --git a/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsxindex b41c09009..f0ec1dd41 100644--- a/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx+++ b/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx@@ -10,10 +10,10 @@ import { usePluginStore } from '../../store/pluginStore'import { usePermissionsStore } from '../../store/permissionsStore'import { useSettingsStore } from '../../store/settingsStore'import { useBackgroundTasksStore } from '../../store/backgroundTasksStore'-import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { resetAllStores, seedStore, seedInstanceAddons } from '../../../tests/helpers/store'import { buildUser, buildTrip, buildDay, buildPlace, buildAssignment, buildReservation } from '../../../tests/helpers/factories'import {- addonsApi, accommodationsApi, authApi, tripsApi, healthApi, airtrailApi, mapsApi,+ accommodationsApi, authApi, tripsApi, healthApi, airtrailApi, mapsApi,} from '../../api/client'import { accommodationRepo } from '../../repo/accommodationRepo'import { dayColor } from '../../components/Roadtrip/dayColors'@@ -358,7 +358,7 @@ beforeEach(() => {// away instead of leaving a settings fetch behind that lands in the next test.sessionStorage.setItem('trip-roadtrip-42', '1')useSettingsStore.setState(s => ({ isLoaded: true, settings: { ...s.settings, planner_trip_views: { '42': { roadtrip: true } } } }))- vi.spyOn(addonsApi, 'enabled').mockResolvedValue({ addons: [{ id: 'roadtrip' }] } as never)+ seedInstanceAddons(['roadtrip'])vi.spyOn(authApi, 'getAppConfig').mockResolvedValue({})vi.spyOn(healthApi, 'features').mockResolvedValue({ bookingImport: false, aiParsing: false })diff --git a/client/src/pages/tripPlanner/useTripPlanner.tabLink.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.tabLink.test.tsxindex 21cb131e7..26e1a93e3 100644--- a/client/src/pages/tripPlanner/useTripPlanner.tabLink.test.tsx+++ b/client/src/pages/tripPlanner/useTripPlanner.tabLink.test.tsx@@ -4,8 +4,8 @@ import type { ReactNode } from 'react';import { buildTrip, buildUser } from '../../../tests/helpers/factories';import { makeActions } from '../../../tests/helpers/plannerActions';-import { resetAllStores, seedStore } from '../../../tests/helpers/store';-import { addonsApi, airtrailApi, authApi, healthApi, tripsApi } from '../../api/client';+import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';+import { airtrailApi, authApi, healthApi, tripsApi } from '../../api/client';import { TranslationProvider } from '../../i18n/TranslationContext';import { useAuthStore } from '../../store/authStore';import { useBackgroundTasksStore } from '../../store/backgroundTasksStore';@@ -80,7 +80,7 @@ beforeEach(() => {...(makeActions() as unknown as Partial<TripStoreState>),} as Partial<TripStoreState>);- vi.spyOn(addonsApi, 'enabled').mockResolvedValue({ addons: [{ id: 'collab' }] });+ seedInstanceAddons(['collab']);vi.spyOn(authApi, 'getAppConfig').mockResolvedValue({});vi.spyOn(healthApi, 'features').mockResolvedValue({ bookingImport: false, aiParsing: false });vi.spyOn(tripsApi, 'getMembers').mockResolvedValue({ owner: null, members: [] });diff --git a/client/src/pages/tripPlanner/useTripPlanner.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.test.tsxindex e2a0e0a3e..f2a8aefbb 100644--- a/client/src/pages/tripPlanner/useTripPlanner.test.tsx+++ b/client/src/pages/tripPlanner/useTripPlanner.test.tsx@@ -11,10 +11,10 @@ import { usePermissionsStore } from '../../store/permissionsStore'import { usePluginStore } from '../../store/pluginStore'import { useBackgroundTasksStore } from '../../store/backgroundTasksStore'import { useAddonStore } from '../../store/addonStore'-import { resetAllStores, seedStore } from '../../../tests/helpers/store'+import { resetAllStores, seedStore, seedInstanceAddons } from '../../../tests/helpers/store'import { buildUser, buildTrip, buildDay, buildPlace, buildAssignment, buildReservation, buildBudgetItem } from '../../../tests/helpers/factories'import {- addonsApi, authApi, tripsApi, assignmentsApi,+ authApi, tripsApi, assignmentsApi,healthApi, airtrailApi, mapsApi, toursApi,} from '../../api/client'import { accommodationRepo } from '../../repo/accommodationRepo'@@ -143,7 +143,8 @@ beforeEach(() => {}) as unknown as typeof window.__addToastseedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true, placesPhotosEnabled: false })- vi.spyOn(addonsApi, 'enabled').mockResolvedValue({ addons: [] })+ // The instance's addon list has answered with none on, and the trip names none of its own.+ seedInstanceAddons([])vi.spyOn(authApi, 'getAppConfig').mockResolvedValue({})vi.spyOn(healthApi, 'features').mockResolvedValue({ bookingImport: false, aiParsing: false })vi.spyOn(tripsApi, 'getMembers').mockResolvedValue({ owner: null, members: [] })@@ -228,10 +229,7 @@ describe('useTripPlanner — bootstrap', () => {})it('FE-TP-HOOK-006: enabled addons and collab feature flags reach the returned state', async () => {- vi.mocked(addonsApi.enabled).mockResolvedValue({- addons: [{ id: 'packing' }, { id: 'budget' }, { id: 'collab' }],- collabFeatures: { chat: true, notes: false, polls: false, whatsnext: true },- })+ seedInstanceAddons(['packing', 'budget', 'collab'], { chat: true, notes: false, polls: false, whatsnext: true })seedTrip()const { result } = await renderPlanner()@@ -336,7 +334,7 @@ describe('useTripPlanner — bootstrap', () => {describe('useTripPlanner — tabs', () => {it('FE-TP-HOOK-015: addon tabs appear only for enabled addons', async () => {- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'packing' }, { id: 'documents' }] })+ seedInstanceAddons(['packing', 'documents'])seedTrip()const { result } = await renderPlanner()@@ -349,7 +347,7 @@ describe('useTripPlanner — tabs', () => {})it('FE-TP-HOOK-016: switching to the Costs tab loads the budget items and persists the tab', async () => {- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'budget' }] })+ seedInstanceAddons(['budget'])seedTrip()const { result } = await renderPlanner()await waitFor(() => expect(result.current.TRIP_TABS.map(t => t.id)).toContain('finanzplan'))@@ -458,7 +456,7 @@ describe('useTripPlanner — tabs', () => {// ── ?tab= deep link (startup destination, shortcuts, wrapper apps) ──────────it('FE-TP-HOOK-104: ?tab= opens that tab on the very first render and clears the param', async () => {- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'budget' }] })+ seedInstanceAddons(['budget'])searchParams = new URLSearchParams('tab=finanzplan')seedTrip()@@ -491,7 +489,7 @@ describe('useTripPlanner — tabs', () => {// The lazy loads live in handleTabChange, which a deep link never goes through.it('FE-TP-HOOK-107: starting on Costs still loads the budget items', async () => {- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'budget' }] })+ seedInstanceAddons(['budget'])searchParams = new URLSearchParams('tab=finanzplan')seedTrip()@@ -501,7 +499,7 @@ describe('useTripPlanner — tabs', () => {})it('FE-TP-HOOK-108: starting on Files still loads the files', async () => {- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'documents' }] })+ seedInstanceAddons(['documents'])searchParams = new URLSearchParams('tab=dateien')seedTrip()@@ -513,7 +511,7 @@ describe('useTripPlanner — tabs', () => {// enabledAddons is an optimistic guess until the feed answers, and 'collab'// is guessed off — evicting on that guess would drop a requested tab.it('FE-TP-HOOK-109: a requested collab tab survives until the addon feed answers', async () => {- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'collab' }] })+ seedInstanceAddons(['collab'])searchParams = new URLSearchParams('tab=collab')seedTrip()@@ -525,7 +523,7 @@ describe('useTripPlanner — tabs', () => {})it('FE-TP-HOOK-110: but a tab whose addon really is off still falls back to plan', async () => {- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [] })+ seedInstanceAddons([])searchParams = new URLSearchParams('tab=finanzplan')seedTrip()@@ -616,7 +614,7 @@ describe('useTripPlanner — map derivations', () => {max_hiking_difficulty: 2, planned: false, caution: false,}useAddonStore.setState({ addons: [{ id: 'tours', enabled: true } as never], loaded: true })- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'tours' }] })+ seedInstanceAddons(['tours'])vi.spyOn(toursApi, 'list').mockResolvedValue({ tours: [tour] })seedTrip({places: [@@ -1587,7 +1585,7 @@ describe('useTripPlanner — day plan CRUD', () => {const tourPlace = buildPlace({ id: 1, name: 'Ridge walk', tour_place_id: 1 })const ordinaryPlace = buildPlace({ id: 2, name: 'Ordinary place' })useAddonStore.setState({ addons: [{ id: 'tours', enabled: true } as never], loaded: true })- vi.mocked(addonsApi.enabled).mockResolvedValue({ addons: [{ id: 'tours' }] })+ seedInstanceAddons(['tours'])vi.spyOn(toursApi, 'list').mockResolvedValue({ tours: [tour] })seedTrip({places: [tourPlace, ordinaryPlace],diff --git a/client/src/pages/tripPlanner/useTripPlanner.tripAddons.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.tripAddons.test.tsxnew file mode 100644index 000000000..a49deae55--- /dev/null+++ b/client/src/pages/tripPlanner/useTripPlanner.tripAddons.test.tsx@@ -0,0 +1,186 @@+// FE-TP-TRIPADDONS-001 to FE-TP-TRIPADDONS-005+import { act, renderHook, waitFor } from '@testing-library/react';+import type { TripAddon } from '@trek/shared';+import { http, HttpResponse } from 'msw';+import type { ReactNode } from 'react';++import { buildTrip, buildUser } from '../../../tests/helpers/factories';+import { server } from '../../../tests/helpers/msw/server';+import { makeActions } from '../../../tests/helpers/plannerActions';+import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';+import { airtrailApi, authApi, healthApi, tripsApi } from '../../api/client';+import { TranslationProvider } from '../../i18n/TranslationContext';+import { useAuthStore } from '../../store/authStore';+import { useBackgroundTasksStore } from '../../store/backgroundTasksStore';+import { usePluginStore } from '../../store/pluginStore';+import { useTripAddonsStore } from '../../store/tripAddonsStore';+import { type TripStoreState, useTripStore } from '../../store/tripStore';+import { useTripPlanner } from './useTripPlanner';++/**+ * The trip owner switches addons for one trip, both ways: the planner's tabs,+ * dock, rail and More sheet all come from TRIP_TABS, so they follow the trip's+ * own list, at once when the owner switches while the trip is open.+ */++let searchParams = new URLSearchParams();++vi.mock('react-router', () => ({+ useParams: () => ({ id: '42' }),+ useNavigate: () => vi.fn(),+ useSearchParams: () => [searchParams, vi.fn()],+}));++vi.mock('../../hooks/useTripWebSocket', () => ({ useTripWebSocket: vi.fn() }));++vi.mock('../../hooks/useRouteCalculation', () => ({+ useRouteCalculation: () => ({+ route: null,+ routeSegments: [],+ routeVias: [],+ routeInfo: null,+ setRoute: vi.fn(),+ setRouteInfo: vi.fn(),+ updateRouteForDay: vi.fn(async () => {}),+ }),+}));++vi.mock('../../hooks/useAirtrailConnection', () => ({+ useAirtrailConnection: () => ({ airtrailEnabled: false, connected: false, available: false, loading: false }),+}));++vi.mock('../../repo/accommodationRepo', async (importOriginal) => {+ const real = await importOriginal<typeof import('../../repo/accommodationRepo')>();+ return { accommodationRepo: { ...real.accommodationRepo, list: vi.fn(async () => ({ accommodations: [] })) } };+});++vi.mock('../../services/photoService', () => ({+ getCached: vi.fn(() => undefined),+ fetchPhoto: vi.fn(),+}));++function wrapper({ children }: { children: ReactNode }) {+ return <TranslationProvider>{children}</TranslationProvider>;+}++const addon = (id: string, enabled: boolean, instanceEnabled: boolean): TripAddon => ({+ id,+ name: id,+ icon: null,+ enabled,+ instanceEnabled,+ overridden: enabled !== instanceEnabled,+});++/** GET /api/trips/42/addons answers this list. */+function tripHas(addons: TripAddon[]) {+ server.use(http.get('/api/trips/42/addons', () => HttpResponse.json({ tripId: 42, addons })));+}++async function renderPlanner() {+ const rendered = renderHook(() => useTripPlanner(), { wrapper });+ await act(async () => {+ await Promise.resolve();+ });+ return rendered;+}++const tabIds = (result: { current: ReturnType<typeof useTripPlanner> }) => result.current.TRIP_TABS.map((t) => t.id);++beforeEach(() => {+ vi.clearAllMocks();+ resetAllStores();+ searchParams = new URLSearchParams();+ usePluginStore.setState({ plugins: [], loaded: true });+ useBackgroundTasksStore.setState({ tasks: [] });+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true, placesPhotosEnabled: false });+ useTripStore.setState({+ trip: buildTrip({ id: 42, title: 'Kyoto' }),+ isLoading: false,+ days: [],+ places: [],+ assignments: {},+ reservations: [],+ ...(makeActions() as unknown as Partial<TripStoreState>),+ } as Partial<TripStoreState>);+ vi.spyOn(authApi, 'getAppConfig').mockResolvedValue({});+ vi.spyOn(healthApi, 'features').mockResolvedValue({ bookingImport: false, aiParsing: false });+ vi.spyOn(tripsApi, 'getMembers').mockResolvedValue({ owner: null, members: [] });+ vi.spyOn(airtrailApi, 'sync').mockResolvedValue({ changed: 0 });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('useTripPlanner — the trip’s own addons', () => {+ it('FE-TP-TRIPADDONS-001: a trip switches Costs on while the instance has it off', async () => {+ seedInstanceAddons(['packing']);+ tripHas([addon('packing', true, true), addon('budget', true, false)]);++ const { result } = await renderPlanner();++ await waitFor(() => expect(tabIds(result)).toContain('finanzplan'));+ expect(result.current.enabledAddons.budget).toBe(true);+ });++ it('FE-TP-TRIPADDONS-002: a trip switches Lists off while the instance has it on, and its open tab falls back to the plan', async () => {+ seedInstanceAddons(['packing', 'budget']);+ sessionStorage.setItem('trip-tab-42', 'listen');+ tripHas([addon('packing', false, true), addon('budget', true, true)]);++ const { result } = await renderPlanner();++ await waitFor(() => expect(result.current.activeTab).toBe('plan'));+ expect(tabIds(result)).not.toContain('listen');+ expect(tabIds(result)).toContain('finanzplan');+ });++ it('FE-TP-TRIPADDONS-003: the owner switching Tours on while the trip is open turns the tours on at once', async () => {+ seedInstanceAddons([]);+ tripHas([addon('tours', false, false)]);+ const { result } = await renderPlanner();+ await waitFor(() => expect(useTripAddonsStore.getState().trips['1:42']?.status).toBe('ready'));+ expect(result.current.toursEnabled).toBe(false);++ act(() => useTripAddonsStore.getState().publish(42, [addon('tours', true, false)]));++ expect(result.current.toursEnabled).toBe(true);+ expect(tabIds(result)).toContain('tour-planner');+ });++ it('FE-TP-TRIPADDONS-004: a plugin page that replaces Costs follows the Costs addon of the trip', async () => {+ seedInstanceAddons(['budget']);+ usePluginStore.setState({+ plugins: [+ { id: 'ledger', name: 'Ledger', type: 'trip-page', tripPage: { replaces: ['finanzplan'] } },+ { id: 'notes', name: 'Notes', type: 'trip-page' },+ ] as never,+ loaded: true,+ });+ tripHas([addon('budget', false, true)]);++ const { result } = await renderPlanner();++ await waitFor(() => expect(tabIds(result)).not.toContain('plugin:ledger'));+ expect(tabIds(result)).toContain('plugin:notes');+ expect(tabIds(result)).not.toContain('finanzplan');+ });++ it('FE-TP-TRIPADDONS-005: a list that cannot be read leaves the instance switches in charge', async () => {+ seedInstanceAddons(['documents']);+ server.use(http.get('/api/trips/42/addons', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));++ const { result } = await renderPlanner();++ await waitFor(() => expect(useTripAddonsStore.getState().trips['1:42']?.status).toBe('failed'));+ expect(tabIds(result)).toContain('dateien');+ expect(result.current.collabFeatures).toEqual({+ chat: true,+ notes: true,+ links: true,+ polls: true,+ whatsnext: true,+ });+ });+});diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.tsindex 8c913dd32..bd7ec9760 100644--- a/client/src/pages/tripPlanner/useTripPlanner.ts+++ b/client/src/pages/tripPlanner/useTripPlanner.ts@@ -10,7 +10,7 @@ import { useToast } from '../../components/shared/Toast'import { Map, Ticket, PackageCheck, Wallet, FolderOpen, Users, Train, Mountain, Route } from 'lucide-react'import { resolvePluginIcon } from '../../components/shared/PluginIcon'import { useTranslation } from '../../i18n'-import { addonsApi, authApi, tripsApi, healthApi, placesApi } from '../../api/client'+import { authApi, tripsApi, healthApi, placesApi } from '../../api/client'import { TRANSPORT_TYPES } from '../../utils/dayMerge'import { offlineDb } from '../../db/offlineDb'import { isEffectivelyOffline } from '../../sync/networkMode'@@ -27,7 +27,6 @@ import { usePlaceSelection } from '../../hooks/usePlaceSelection'import { useTourPlaceIds } from '../../hooks/useTourPlaceIds'import { LinkedJournalIcon } from '../../components/Trips/LinkedJournalIcon'import { useTripJournal } from '../../components/Trips/useTripJournalLink'-import { useAddonStore } from '../../store/addonStore'import { usePlannerHistory } from '../../hooks/usePlannerHistory'import { useIsTouch } from '../../hooks/useIsTouch'import { usePluginStore } from '../../store/pluginStore'@@ -71,6 +70,8 @@ import { useRoadtripVias } from '../../components/Roadtrip/useRoadtripVias'import { TRIP_SPLASH_AFTER_MS } from '../../components/shared/useTripSplashBeats'import { useFlightLiveSync } from '../../components/Planner/flightLive/useFlightLiveSync'import { useMailPrefillLink } from '../../components/MailIngest/useMailPrefillLink'+import { usePlannerAddons } from './usePlannerAddons'+import { pluginPageShown } from '../../utils/tripAddons'/*** The trip's roster from the server: the owner and the members. Null offline@@ -142,11 +143,10 @@ export function useTripPlanner() {else if (undone) toast.info(t('undo.done', { action: label ?? '' }))}, [undo, lastActionLabel, toast])- const [enabledAddons, setEnabledAddons] = useState<Record<string, boolean>>({ packing: true, budget: true, documents: true, collab: false, roadtrip: false, tours: false, dawarich: false })- // The values above are an optimistic guess until the addon feed answers. The- // tab guard below waits for this before evicting anything, so a tab we were- // asked to open ('collab' in particular, guessed off) survives the gap.- const [addonsLoaded, setAddonsLoaded] = useState<boolean>(false)+ // The trip's addons, as its owner switched them or as the instance has them, live.+ // The tab guard below waits for addonsLoaded before evicting anything, so a tab we+ // were asked to open survives until the trip's list answered.+ const { enabledAddons, addonsLoaded, collabFeatures, toursEnabled } = usePlannerAddons(tripId)// Road trip mode swaps the plan view's left rail (and later its map layer) for the// drive-first reading of the same trip. Remembered per trip on the account (#2639):// someone planning a road trip finds it again in another browser without it@@ -185,7 +185,6 @@ export function useTripPlanner() {Object.entries(storedAssignments).map(([dayId, visits]) => [dayId, visits.filter(v => !hidden(v))]),)}, [roadtripMode, roadtripSettings.roadtrip_service_stops_in_days, storedAssignments])- const [collabFeatures, setCollabFeatures] = useState<{ chat: boolean; notes: boolean; links: boolean; polls: boolean; whatsnext: boolean }>({ chat: true, notes: true, links: true, polls: true, whatsnext: true })// Stays live in page-local state rather than the store, so store-level// refreshes (a stay booked or changed elsewhere, a remote trip date change,// reconnect hydration) nudge them, one read per burst (#1288).@@ -209,19 +208,14 @@ export function useTripPlanner() {useTripRosterSync(tripId, refreshMembers)useEffect(() => {- addonsApi.enabled().then(data => {- const map: Record<string, boolean> = {}- data.addons.forEach(a => { map[a.id] = true })- setEnabledAddons({ packing: !!map.packing, budget: !!map.budget, documents: !!map.documents, collab: !!map.collab, roadtrip: !!map.roadtrip, tours: !!map.tours, dawarich: !!map.dawarich })- if (data.collabFeatures) setCollabFeatures(data.collabFeatures)- }).catch(() => {}).finally(() => setAddonsLoaded(true))authApi.getAppConfig().then(config => {if (config.allowed_file_types) setAllowedFileTypes(config.allowed_file_types)}).catch(() => {})}, [])- const tripPagePlugins = allPlugins.filter(p => p.type === 'trip-page')+ // A plugin page that replaces a core tab follows that tab's addon on this trip.+ const tripPagePlugins = allPlugins.filter(p => p.type === 'trip-page' && pluginPageShown(p.tripPage?.replaces, id => !!enabledAddons[id]))const tripPluginIds = tripPagePlugins.map(p => p.id).join(',')// A trip-page plugin may replace core tabs while it's active (its manifest names@@ -313,7 +307,6 @@ export function useTripPlanner() {startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight,} = useResizablePanels()const { selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment } = usePlaceSelection()- const toursEnabled = useAddonStore(state => state.isEnabled('tours'))const [toursMode, setToursMode] = useState(false)const previousToursModeRef = useRef(false)const { tours, toursLoading, tourDataReady, tourPlaceIds, reloadTourPlaceIds, invalidateTourPlaceIds, upsertTour } = useTourPlaceIds(tripId, toursEnabled)diff --git a/client/src/repo/tripAddonsRepo.test.ts b/client/src/repo/tripAddonsRepo.test.tsnew file mode 100644index 000000000..96cd0dc58--- /dev/null+++ b/client/src/repo/tripAddonsRepo.test.ts@@ -0,0 +1,89 @@+// FE-REPO-TRIPADDONS-001 to FE-REPO-TRIPADDONS-006: the trip addons of one trip, read+// through to the server and kept on this device, read from there without a connection,+// and switched online only.+import type { TripAddon } from '@trek/shared';+import 'fake-indexeddb/auto';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { clearAll, clearTripData, offlineDb } from '../db/offlineDb';+import { isEffectivelyOffline } from '../sync/networkMode';+import { OnlineOnlyError } from './onlineOnly';+import { cachedTripAddons, tripAddonsRepo } from './tripAddonsRepo';++const { client } = vi.hoisted(() => ({ client: { get: vi.fn(), put: vi.fn() } }));++vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) }));+vi.mock('../api/client', () => ({ default: client, apiClient: client }));++const costs = (enabled: boolean): TripAddon => ({+ id: 'budget',+ name: 'Costs',+ icon: 'Wallet',+ enabled,+ instanceEnabled: true,+ overridden: !enabled,+});+/** An axios failure that never reached the server. */+const networkError = () => Object.assign(new Error('Network Error'), { isAxiosError: true });++beforeEach(async () => {+ await clearAll();+ vi.clearAllMocks();+ vi.mocked(isEffectivelyOffline).mockReturnValue(false);+});++describe('tripAddonsRepo', () => {+ it('FE-REPO-TRIPADDONS-001: reads the addons of the trip and keeps them on this device', async () => {+ client.get.mockResolvedValue({ data: { tripId: 4, addons: [costs(false)] } });++ expect(await tripAddonsRepo.list(4)).toEqual([costs(false)]);++ expect(client.get).toHaveBeenCalledWith('/trips/4/addons');+ expect(await cachedTripAddons(4)).toEqual([costs(false)]);+ });++ it('FE-REPO-TRIPADDONS-002: without a connection answers what the device last read, and refuses a trip it never read', async () => {+ await offlineDb.tripAddons.put({ tripId: 4, addons: [costs(true)] });+ vi.mocked(isEffectivelyOffline).mockReturnValue(true);++ expect(await tripAddonsRepo.list(4)).toEqual([costs(true)]);+ await expect(tripAddonsRepo.list(5)).rejects.toThrow('not available offline');+ expect(client.get).not.toHaveBeenCalled();+ });++ it('FE-REPO-TRIPADDONS-003: a request that never reached the server falls back to the device, a refusal does not', async () => {+ await offlineDb.tripAddons.put({ tripId: 4, addons: [costs(true)] });+ client.get.mockRejectedValueOnce(networkError());+ expect(await tripAddonsRepo.list(4)).toEqual([costs(true)]);++ const refused = Object.assign(new Error('Not found'), { isAxiosError: true, response: { status: 404 } });+ client.get.mockRejectedValueOnce(refused);+ await expect(tripAddonsRepo.list(4)).rejects.toBe(refused);+ });++ it('FE-REPO-TRIPADDONS-004: an answer the contract does not describe is refused and nothing is kept', async () => {+ client.get.mockResolvedValue({ data: { tripId: 4, addons: [{ id: 'budget' }] } });++ await expect(tripAddonsRepo.list(4)).rejects.toThrow();+ expect(await cachedTripAddons(4)).toBeNull();+ });++ it('FE-REPO-TRIPADDONS-005: the owner switches an addon online, and the answer is kept; offline nothing is sent', async () => {+ client.put.mockResolvedValue({ data: { tripId: 4, addons: [costs(false)] } });++ expect(await tripAddonsRepo.setOverride(4, 'budget', false)).toEqual([costs(false)]);+ expect(client.put).toHaveBeenCalledWith('/trips/4/addons/budget', { enabled: false });+ expect(await cachedTripAddons(4)).toEqual([costs(false)]);++ vi.mocked(isEffectivelyOffline).mockReturnValue(true);+ await expect(tripAddonsRepo.setOverride(4, 'budget', null)).rejects.toBeInstanceOf(OnlineOnlyError);+ expect(client.put).toHaveBeenCalledTimes(1);+ });++ it('FE-REPO-TRIPADDONS-006: a pushed list is kept, and the trip leaving the cache takes it along', async () => {+ await tripAddonsRepo.remember(4, [costs(true)]);+ expect(await cachedTripAddons(4)).toEqual([costs(true)]);++ await clearTripData(4);+ expect(await cachedTripAddons(4)).toBeNull();+ });+});diff --git a/client/src/repo/tripAddonsRepo.ts b/client/src/repo/tripAddonsRepo.tsnew file mode 100644index 000000000..4ee59424f--- /dev/null+++ b/client/src/repo/tripAddonsRepo.ts@@ -0,0 +1,60 @@+import { tripAddonsResponseSchema, type TripAddon } from '@trek/shared';++import { tripAddonsApi } from '../api/tripAddons';+import { offlineDb } from '../db/offlineDb';+import { requireOnline } from './onlineOnly';+import { onlineThenCache } from './withOfflineFallback';++/** The trip's addons as the device last read them, or null while it never did. */+export async function cachedTripAddons(tripId: number): Promise<TripAddon[] | null> {+ return (await offlineDb.tripAddons.get(tripId))?.addons ?? null;+}++/**+ * Keeps the list the server sent, unless the signed-in account changed while it+ * was on its way: the database is the account's own, and the list belongs to the+ * one that asked.+ */+async function keep(tripId: number, addons: TripAddon[], cacheName: string): Promise<void> {+ if (offlineDb.name !== cacheName) throw new Error('Account changed.');+ await offlineDb.tripAddons.put({ tripId, addons });+}++/**+ * The trip addons of one trip, each on or off for it. Reading works offline,+ * from the list the device last read. Switching one is online only, on purpose:+ * only the owner may do it, the server says whether they may, and a change+ * queued offline could switch a section on or off for every member long after+ * the owner forgot about it.+ */+export const tripAddonsRepo = {+ async list(tripId: number): Promise<TripAddon[]> {+ const cacheName = offlineDb.name;+ return onlineThenCache(+ async () => {+ const { addons } = tripAddonsResponseSchema.parse(await tripAddonsApi.list(tripId));+ await keep(tripId, addons, cacheName);+ return addons;+ },+ async () => {+ const cached = await cachedTripAddons(tripId);+ if (!cached) throw new Error('The addons of this trip are not available offline.');+ return cached;+ }+ );+ },++ /** `enabled: null` goes back to the instance setting. Answers the trip's whole list after the change. */+ async setOverride(tripId: number, addonId: string, enabled: boolean | null): Promise<TripAddon[]> {+ requireOnline();+ const cacheName = offlineDb.name;+ const { addons } = tripAddonsResponseSchema.parse(await tripAddonsApi.update(tripId, addonId, { enabled }));+ await keep(tripId, addons, cacheName);+ return addons;+ },++ /** A list another member's change sent along (`tripAddons:changed`), kept like a read. */+ async remember(tripId: number, addons: TripAddon[]): Promise<void> {+ await keep(tripId, addons, offlineDb.name);+ },+};diff --git a/client/src/store/addonStore.ts b/client/src/store/addonStore.tsindex 7ff504d4a..bc3b02992 100644--- a/client/src/store/addonStore.ts+++ b/client/src/store/addonStore.ts@@ -22,6 +22,27 @@ interface Addon {}>}+/** The parts of the collab addon the admin can switch off inside it, instance-wide. */+export interface CollabFeatures {+ chat: boolean+ notes: boolean+ links: boolean+ polls: boolean+ whatsnext: boolean+}++const ALL_COLLAB_FEATURES: CollabFeatures = { chat: true, notes: true, links: true, polls: true, whatsnext: true }++/**+ * The Tours options the admin chose, whatever the instance Tours switch says: a+ * trip may switch Tours on for itself, and its planner offers them there.+ */+interface ToursOptions {+ wanderer: boolean+ hikingMap: boolean+ cycleMap: boolean+}+interface AddonState {addons: Addon[]bagTracking: boolean@@ -31,9 +52,13 @@ interface AddonState {toursHikingMap: boolean/** Tours is on and the admin offers CyclOSM in its planner (BIK-06). */toursCycleMap: boolean+ toursOptions: ToursOptions/** The collab chat is on: the admin can switch it off inside the collab addon. */collabChat: boolean+ collabFeatures: CollabFeaturesloaded: boolean+ /** No read of the addons has answered yet but one failed (offline, say), so `addons` says nothing about the instance. */+ failed: booleanloadAddons: () => Promise<void>isEnabled: (id: string) => boolean}@@ -44,21 +69,36 @@ export const useAddonStore = create<AddonState>((set, get) => ({toursWanderer: false,toursHikingMap: false,toursCycleMap: false,+ toursOptions: { wanderer: false, hikingMap: false, cycleMap: false },collabChat: true,+ collabFeatures: ALL_COLLAB_FEATURES,loaded: false,+ failed: false,loadAddons: async () => {try {const data = await addonsApi.enabled()+ const toursWanderer = !!data.toursWanderer+ const toursHikingMap = !!data.toursHikingMap+ const toursCycleMap = !!data.toursCycleMapset({ addons: data.addons || [], bagTracking: !!data.bagTracking,- toursWanderer: !!data.toursWanderer,- toursHikingMap: !!data.toursHikingMap,- toursCycleMap: !!data.toursCycleMap,+ toursWanderer,+ toursHikingMap,+ toursCycleMap,+ // A server from before the options were listed apart only sends the combined flags.+ toursOptions: {+ wanderer: data.toursOptions?.wanderer ?? toursWanderer,+ hikingMap: data.toursOptions?.hikingMap ?? toursHikingMap,+ cycleMap: data.toursOptions?.cycleMap ?? toursCycleMap,+ },collabChat: data.collabFeatures?.chat !== false,+ collabFeatures: { ...ALL_COLLAB_FEATURES, ...data.collabFeatures },loaded: true,+ failed: false,})} catch {- set({ loaded: true })+ // A failed refresh after a good read keeps that read: it still says what the instance has.+ set(state => ({ loaded: true, failed: state.failed || !state.loaded }))}},@@ -69,3 +109,16 @@ export const useAddonStore = create<AddonState>((set, get) => ({return get().addons.some(a => a.id === id && a.enabled)},}))++/**+ * The instance switch of an addon when the instance list is known (a read+ * answered, or the list holds addons), else `whenUnknown`: offline, or before+ * the first read answered, the empty list would otherwise read as every addon off.+ */+export function instanceAddonOn(+ state: Pick<AddonState, 'addons' | 'loaded' | 'failed' | 'isEnabled'>,+ id: string,+ whenUnknown: boolean,+): boolean {+ return (state.loaded && !state.failed) || state.addons.length > 0 ? state.isEnabled(id) : whenUnknown+}diff --git a/client/src/store/collectionTourStore.test.ts b/client/src/store/collectionTourStore.test.tsindex 60960fcb6..395134ed2 100644--- a/client/src/store/collectionTourStore.test.ts+++ b/client/src/store/collectionTourStore.test.ts@@ -58,6 +58,14 @@ describe('collectionTourStore', () => {expect(useCollectionTourStore.getState().status).toBe('error');});+ it('FE-STORE-COLLECTION-TOURS-008: the refusal while Tours is off for the user everywhere is no failure', async () => {+ vi.spyOn(collectionToursRepo, 'list').mockRejectedValueOnce({+ response: { status: 404, data: { error: 'Tours addon is not enabled' } },+ });+ await useCollectionTourStore.getState().load(3);+ expect(useCollectionTourStore.getState()).toMatchObject({ status: 'off', tours: [] });+ });+it('FE-STORE-COLLECTION-TOURS-004: removing takes the tour off at once and puts it back on a refusal', async () => {vi.spyOn(collectionToursRepo, 'list').mockResolvedValue({ tours: [tour(1, 'Ridge'), tour(2, 'Lake')] });await useCollectionTourStore.getState().load(3);diff --git a/client/src/store/collectionTourStore.ts b/client/src/store/collectionTourStore.tsindex 43fc22fe8..7224147b1 100644--- a/client/src/store/collectionTourStore.ts+++ b/client/src/store/collectionTourStore.ts@@ -4,9 +4,21 @@ import { addListener, removeListener } from '../api/websocket';import { collectionToursRepo } from '../repo/collectionToursRepo';import { OnlineOnlyError } from '../repo/onlineOnly';import type { WebSocketEvent } from '../types';+import { getApiErrorMessage } from '../utils/apiError';-/** How far the open collection's tours are: asked for, there, or not to be had right now. */-type CollectionTourStatus = 'idle' | 'loading' | 'ready' | 'error' | 'offline';+/**+ * How far the open collection's tours are: asked for, there, or not to be had+ * right now; `off` while Tours is off for the user in every trip.+ */+type CollectionTourStatus = 'idle' | 'loading' | 'ready' | 'error' | 'offline' | 'off';++/** The answer the server gives while Tours is on neither for the instance nor in any of the user's trips. */+const TOURS_OFF = 'Tours addon is not enabled';++function failureOf(err: unknown): CollectionTourStatus {+ if (err instanceof OnlineOnlyError) return 'offline';+ return getApiErrorMessage(err, '') === TOURS_OFF ? 'off' : 'error';+}interface CollectionTourState {/** The collection the tours are read for. */@@ -52,7 +64,7 @@ export const useCollectionTourStore = create<CollectionTourState>((set, get) =>const { tours } = await collectionToursRepo.list(collectionId);if (current()) set({ tours, status: 'ready' });} catch (err: unknown) {- if (current()) set({ status: err instanceof OnlineOnlyError ? 'offline' : 'error' });+ if (current()) set({ status: failureOf(err) });}},remove: async (collectionId, tourId) => {diff --git a/client/src/store/tourVisitStore.ts b/client/src/store/tourVisitStore.tsindex d103b3483..b7280e1d7 100644--- a/client/src/store/tourVisitStore.ts+++ b/client/src/store/tourVisitStore.ts@@ -3,7 +3,7 @@ import { create } from 'zustand';import { addListener, removeListener } from '../api/websocket';import { tourVisitRepo } from '../repo/tourVisitRepo';import type { WebSocketEvent } from '../types';-import { useAddonStore } from './addonStore';+import { tripAddonEnabledNow } from './tripAddonsStore';/** A station's status on one day of its walk; a station not listed is planned. */export type VisitsByStation = Readonly<Record<string, TourVisitStatus>>;@@ -94,7 +94,7 @@ export const useTourVisitStore = create<TourVisitState>((set, get) => ({*/export function reloadTourVisits(tripId: number | string): void {const key = String(tripId);- if (useTourVisitStore.getState().tripId !== key || !useAddonStore.getState().isEnabled('tours')) return;+ if (useTourVisitStore.getState().tripId !== key || !tripAddonEnabledNow(Number(tripId), 'tours')) return;useTourVisitStore.getState().load(tripId)diff --git a/client/src/store/tripAddonsStore.test.ts b/client/src/store/tripAddonsStore.test.tsnew file mode 100644index 000000000..c777f56f9--- /dev/null+++ b/client/src/store/tripAddonsStore.test.ts@@ -0,0 +1,154 @@+// FE-STORE-TRIPADDONS-001 to FE-STORE-TRIPADDONS-008: the trip addons per trip, read,+// pushed and switched, and the readers that fall back to the instance switches.+import { act, renderHook, waitFor } from '@testing-library/react';+import type { TripAddon } from '@trek/shared';+import 'fake-indexeddb/auto';+import { http, HttpResponse } from 'msw';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { buildUser } from '../../tests/helpers/factories';+import { server } from '../../tests/helpers/msw/server';+import { resetAllStores, seedInstanceAddons, seedStore } from '../../tests/helpers/store';+import { addListener, removeListener } from '../api/websocket';+import { clearAll } from '../db/offlineDb';+import { cachedTripAddons } from '../repo/tripAddonsRepo';+import { useAuthStore } from './authStore';+import {+ tripAddonEnabledNow,+ tripAddonsEntry,+ useTripAddonEnabled,+ useTripAddonsStore,+ watchTripAddons,+} from './tripAddonsStore';++const addon = (id: string, enabled: boolean, instanceEnabled = !enabled): TripAddon => ({+ id,+ name: id,+ icon: null,+ enabled,+ instanceEnabled,+ overridden: enabled !== instanceEnabled,+});++const entry = (tripId: number) => tripAddonsEntry(useTripAddonsStore.getState(), tripId);++function tripHas(tripId: number, addons: TripAddon[]) {+ server.use(http.get(`/api/trips/${tripId}/addons`, () => HttpResponse.json({ tripId, addons })));+}++beforeEach(async () => {+ await clearAll();+ resetAllStores();+ vi.mocked(addListener).mockClear();+ seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('tripAddonsStore', () => {+ it('FE-STORE-TRIPADDONS-001: reads the trip’s list for the signed-in account', async () => {+ tripHas(4, [addon('budget', false)]);++ await useTripAddonsStore.getState().load(4);++ expect(entry(4)).toMatchObject({ status: 'ready', addons: [addon('budget', false)] });+ expect(useTripAddonsStore.getState().trips['1:4']).toBeDefined();+ // Another account on the same tab does not see it.+ seedStore(useAuthStore, { user: buildUser({ id: 2 }) });+ expect(entry(4)).toBeUndefined();+ });++ it('FE-STORE-TRIPADDONS-002: a read that fails keeps what was held and says so; an invalid id reads nothing', async () => {+ tripHas(4, [addon('tours', true)]);+ await useTripAddonsStore.getState().load(4);+ server.use(http.get('/api/trips/4/addons', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));++ await useTripAddonsStore.getState().load(4);++ expect(entry(4)).toMatchObject({ status: 'failed', addons: [addon('tours', true)] });+ await useTripAddonsStore.getState().load(0);+ await useTripAddonsStore.getState().load(Number.NaN);+ expect(Object.keys(useTripAddonsStore.getState().trips)).toEqual(['1:4']);+ });++ it('FE-STORE-TRIPADDONS-003: one read per trip at a time, and a push during it outlives its older answer', async () => {+ let release: () => void = () => {};+ let asked = 0;+ server.use(+ http.get('/api/trips/4/addons', async () => {+ asked++;+ await new Promise<void>((resolve) => {+ release = resolve;+ });+ return HttpResponse.json({ tripId: 4, addons: [addon('budget', true, true)] });+ })+ );++ const first = useTripAddonsStore.getState().load(4);+ const second = useTripAddonsStore.getState().load(4);+ await second;+ await waitFor(() => expect(asked).toBe(1));+ useTripAddonsStore.getState().publish(4, [addon('budget', false, true)]);+ release();+ await first;++ expect(asked).toBe(1);+ expect(entry(4)).toMatchObject({ status: 'ready', addons: [addon('budget', false, true)] });+ });++ it('FE-STORE-TRIPADDONS-004: the owner’s switch puts the server’s answer in place', async () => {+ const addons = await useTripAddonsStore.getState().setOverride(4, 'collab', false);++ expect(addons[0]).toMatchObject({ id: 'collab', enabled: false, overridden: true });+ expect(entry(4)?.addons).toEqual(addons);+ });++ it('FE-STORE-TRIPADDONS-005: a push for a trip goes into the store and the device’s copy; anything malformed is dropped', async () => {+ const stop = watchTripAddons();+ const listener = vi.mocked(addListener).mock.calls[0][0] as (event: Record<string, unknown>) => void;++ listener({ type: 'tripAddons:changed', tripId: 4, addons: [addon('tours', true)] });+ listener({ type: 'tripAddons:changed', tripId: 'x', addons: [addon('tours', false)] });+ listener({ type: 'tripAddons:changed', tripId: 5, addons: [{ id: 'tours' }] });+ listener({ type: 'roadtripPreferences:changed', tripId: 6, addons: [] });++ expect(entry(4)?.addons).toEqual([addon('tours', true)]);+ expect(entry(5)).toBeUndefined();+ expect(entry(6)).toBeUndefined();+ await waitFor(async () => expect(await cachedTripAddons(4)).toEqual([addon('tours', true)]));++ stop();+ expect(vi.mocked(removeListener)).toHaveBeenCalledWith(listener);+ });++ it('FE-STORE-TRIPADDONS-006: read once outside React, the trip’s list first, then the instance, then the guess', () => {+ expect(tripAddonEnabledNow(4, 'packing', true)).toBe(true);+ expect(tripAddonEnabledNow(4, 'packing')).toBe(false);++ seedInstanceAddons(['packing']);+ expect(tripAddonEnabledNow(4, 'packing')).toBe(true);+ expect(tripAddonEnabledNow(null, 'packing')).toBe(true);++ useTripAddonsStore.getState().publish(4, [addon('packing', false, true)]);+ expect(tripAddonEnabledNow(4, 'packing', true)).toBe(false);+ });++ it('FE-STORE-TRIPADDONS-007: a trip view follows the trip’s list as it changes', () => {+ seedInstanceAddons(['budget']);+ const { result } = renderHook(() => useTripAddonEnabled(4, 'budget'));+ expect(result.current).toBe(true);++ act(() => useTripAddonsStore.getState().publish(4, [addon('budget', false, true)]));+ expect(result.current).toBe(false);++ act(() => useTripAddonsStore.getState().publish(4, [addon('budget', true, true)]));+ expect(result.current).toBe(true);+ });++ it('FE-STORE-TRIPADDONS-008: without a trip, the instance switch alone answers', () => {+ seedInstanceAddons(['tours']);+ const { result } = renderHook(() => useTripAddonEnabled(undefined, 'tours'));+ expect(result.current).toBe(true);+ });+});diff --git a/client/src/store/tripAddonsStore.ts b/client/src/store/tripAddonsStore.tsnew file mode 100644index 000000000..613418a8f--- /dev/null+++ b/client/src/store/tripAddonsStore.ts@@ -0,0 +1,135 @@+import { tripAddonListSchema, type TripAddon } from '@trek/shared';+import { create } from 'zustand';++import { addListener, removeListener } from '../api/websocket';+import { tripAddonsRepo } from '../repo/tripAddonsRepo';+import { tripAddonEnabled } from '../utils/tripAddons';+import { instanceAddonOn, useAddonStore } from './addonStore';+import { useAuthStore } from './authStore';++/**+ * The trip addons of each trip the app looked at, each on or off for that trip+ * (GET /trips/:id/addons, then the `tripAddons:changed` pushes). Kept apart from+ * the trip store because readers outside the open trip need it too: the share+ * dialog on the dashboard, the offline sync, the widgets.+ *+ * Keyed by account and trip, like the driving settings, so a list read for one+ * account is never shown to the next one signed in on the same tab.+ */++type Status = 'loading' | 'ready' | 'failed';++interface TripAddonsEntry {+ /** The trip's list, or null while none was read (still loading, or offline with nothing kept). */+ addons: TripAddon[] | null;+ status: Status;+ /** Counts the lists put in, so a read that started before a newer list arrived does not lay its older answer over it. */+ rev: number;+}++interface TripAddonsState {+ trips: Record<string, TripAddonsEntry>;+ /** Reads the trip's list into the store; one read per trip at a time. Never throws. */+ load: (tripId: number) => Promise<void>;+ /** Puts a list the server sent (an answer or a push) in place. */+ publish: (tripId: number, addons: TripAddon[]) => void;+ /** The owner switches one addon for the trip (null: back to the instance setting). Online only; throws on refusal. */+ setOverride: (tripId: number, addonId: string, enabled: boolean | null) => Promise<TripAddon[]>;+}++function keyOf(tripId: number): string {+ return `${useAuthStore.getState().user?.id ?? 'anon'}:${tripId}`;+}++export const useTripAddonsStore = create<TripAddonsState>((set, get) => ({+ trips: {},++ load: async (tripId) => {+ if (!Number.isSafeInteger(tripId) || tripId < 1) return;+ const key = keyOf(tripId);+ const before = get().trips[key];+ if (before?.status === 'loading') return;+ const rev = (before?.rev ?? 0) + 1;+ set((state) => ({ trips: { ...state.trips, [key]: { addons: before?.addons ?? null, status: 'loading', rev } } }));+ let addons: TripAddon[] | null = null;+ try {+ addons = await tripAddonsRepo.list(tripId);+ } catch {+ // Offline with nothing kept, or the server refused: the readers fall back to the instance switches.+ }+ set((state) => {+ const current = state.trips[key];+ // A push that landed meanwhile is newer than this answer and stays.+ if (current && current.rev !== rev) return state;+ const entry: TripAddonsEntry = addons+ ? { addons, status: 'ready', rev }+ : { addons: current?.addons ?? null, status: 'failed', rev };+ return { trips: { ...state.trips, [key]: entry } };+ });+ },++ publish: (tripId, addons) => {+ const key = keyOf(tripId);+ set((state) => ({+ trips: { ...state.trips, [key]: { addons, status: 'ready', rev: (state.trips[key]?.rev ?? 0) + 1 } },+ }));+ },++ setOverride: async (tripId, addonId, enabled) => {+ const addons = await tripAddonsRepo.setOverride(tripId, addonId, enabled);+ get().publish(tripId, addons);+ return addons;+ },+}));++/**+ * Applies `tripAddons:changed`: the trip owner switched an addon on or off, or+ * back to the instance setting, and the push carries the trip's whole list,+ * which goes into the store and the device's copy alike. Returns the function+ * that stops listening.+ */+export function watchTripAddons(): () => void {+ const onEvent = (event: Record<string, unknown>) => {+ if (event?.type !== 'tripAddons:changed') return;+ const tripId = Number(event.tripId);+ const parsed = tripAddonListSchema.safeParse(event.addons);+ if (!parsed.success || !Number.isSafeInteger(tripId) || tripId < 1) return;+ useTripAddonsStore.getState().publish(tripId, parsed.data);+ // The screen already follows. Should the copy for offline use not take the list,+ // it is read again, which writes that copy on its way.+ void tripAddonsRepo.remember(tripId, parsed.data).catch(() => useTripAddonsStore.getState().load(tripId));+ };+ addListener(onEvent);+ return () => removeListener(onEvent);+}++/** The trip's entry for the signed-in account, if the store holds one. */+export function tripAddonsEntry(+ state: TripAddonsState,+ tripId: number | null | undefined+): TripAddonsEntry | undefined {+ return tripId == null ? undefined : state.trips[keyOf(tripId)];+}++/**+ * Whether an addon applies to the trip, read once, outside React: the trip's own+ * list when the store holds it, else the instance switch (`whenUnknown` while+ * that is not known either).+ */+export function tripAddonEnabledNow(tripId: number | null | undefined, addonId: string, whenUnknown = false): boolean {+ const own = tripAddonsEntry(useTripAddonsStore.getState(), tripId)?.addons;+ return tripAddonEnabled(own, addonId, instanceAddonOn(useAddonStore.getState(), addonId, whenUnknown));+}++/**+ * Whether an addon applies to the trip, for a component inside a trip view: the+ * trip's own list once read, the instance switch before. Reads only; the trip+ * planner (useTripAddons) loads the list and the live sync keeps it current.+ */+export function useTripAddonEnabled(tripId: number | null | undefined, addonId: string): boolean {+ const own = useTripAddonsStore(+ (state) => tripAddonsEntry(state, tripId)?.addons?.find((a) => a.id === addonId)?.enabled+ );+ const instance = useAddonStore((state) => state.isEnabled(addonId));+ return own ?? instance;+}diff --git a/client/src/store/tripStore.test.ts b/client/src/store/tripStore.test.tsindex 34452bcca..68620f484 100644--- a/client/src/store/tripStore.test.ts+++ b/client/src/store/tripStore.test.ts@@ -204,6 +204,32 @@ describe('tripStore', () => {expect(state.error).toBeNull();});+ it('FE-TSTORE-005b: a trip with Lists switched off opens without its packing and todos', async () => {+ server.use(+ http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })),+ http.get('/api/trips/1/packing', () => HttpResponse.json({ error: 'Lists addon is not enabled' }, { status: 404 })),+ http.get('/api/trips/1/todo', () => HttpResponse.json({ error: 'Lists addon is not enabled' }, { status: 404 })),+ );++ await useTripStore.getState().loadTrip(1);++ const state = useTripStore.getState();+ expect(state.trip?.id).toBe(1);+ expect(state.packingItems).toEqual([]);+ expect(state.todoItems).toEqual([]);+ expect(state.error).toBeNull();+ });++ it('FE-TSTORE-005c: any other packing failure still fails the load, as before', async () => {+ server.use(+ http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })),+ http.get('/api/trips/1/packing', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),+ );++ await expect(useTripStore.getState().loadTrip(1)).rejects.toThrow();+ expect(useTripStore.getState().trip).toBeNull();+ });+it('FE-TSTORE-006: falls back to the cached tags and categories when their endpoints fail', async () => {await offlineDb.tags.put(buildTag({ id: 31, name: 'Cached tag' }));await offlineDb.categories.put(buildCategory({ id: 32, name: 'Cached category' }));diff --git a/client/src/store/tripStore.ts b/client/src/store/tripStore.tsindex 2ce87b045..8323bbab8 100644--- a/client/src/store/tripStore.ts+++ b/client/src/store/tripStore.ts@@ -123,6 +123,16 @@ export interface TripStoreStateclearTripGone: () => void}+/**+ * What a section reads as when the trip has its addon switched off: the server+ * answers 404 ("Lists addon is not enabled") for it, which is no reason to fail+ * the whole trip. Any other failure is rethrown as before.+ */+function emptyWhenAddonOff<T>(err: unknown, empty: T): T {+ if ((err as { response?: { status?: number } } | null)?.response?.status === 404) return empty+ throw err+}+export const useTripStore = create<TripStoreState>((set, get) => ({trip: null,days: [],@@ -188,8 +198,9 @@ export const useTripStore = create<TripStoreState>((set, get) => ({tripRepo.get(tripId),dayRepo.list(tripId),placeRepo.list(tripId),- packingRepo.list(tripId),- todoRepo.list(tripId),+ // A trip with Lists switched off answers 404 for both; the trip still opens, without them.+ packingRepo.list(tripId).catch(err => emptyWhenAddonOff(err, { items: [] as PackingItem[] })),+ todoRepo.list(tripId).catch(err => emptyWhenAddonOff(err, { items: [] as TodoItem[] })),// Budget / reservations / files are hydrated here too so the offline// path is uniform (no separate tab-gated effects). Non-fatal: a failure// in any of these must not blank the whole trip.diff --git a/client/src/sync/tripSyncManager.ts b/client/src/sync/tripSyncManager.tsindex 6ed327632..f78545f63 100644--- a/client/src/sync/tripSyncManager.ts+++ b/client/src/sync/tripSyncManager.ts@@ -1,6 +1,7 @@import { roadtripPreferencesRepo } from '../repo/roadtripPreferencesRepo'import { tourRepo } from '../repo/tourRepo'import { tripTagRepo } from '../repo/tripTagRepo'+import { tripAddonsRepo } from '../repo/tripAddonsRepo'/*** Trip sync manager — seeds Dexie with trip data for offline use.*@@ -35,6 +36,9 @@ import { isEffectivelyOffline } from './networkMode'import { getOfflinePrefs, isTripOfflineEnabled, isTripPinned } from './offlinePrefs'import { useSettingsStore } from '../store/settingsStore'import { useAddonStore } from '../store/addonStore'+import { useTripAddonsStore } from '../store/tripAddonsStore'+import { tripAddonEnabled } from '../utils/tripAddons'+import type { TripAddon } from '@trek/shared'import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember } from '../types'// ── Types ─────────────────────────────────────────────────────────────────────@@ -144,6 +148,12 @@ async function syncTrip(tripId: number): Promise<void> {filesCachedCount: 0,})+ // Which addons the trip has on, kept for offline use and decided before the+ // optional caches below. Never fatal: without the list each addon follows the+ // instance switch, as it did before a trip could switch its own.+ const tripAddons = await readTripAddons(tripId)+ const addonOn = (id: string) => tripAddonEnabled(tripAddons, id, useAddonStore.getState().isEnabled(id))+// Last, and never fatal. Driving settings belong to an optional addon: the// route answers 404 when it is off, and the repo's own offline fallback throws// a bare Error when there is no cached row yet, which is exactly the state a@@ -152,7 +162,7 @@ async function syncTrip(tripId: number): Promise<void> {// reported it stored, so Settings said "N trips ready" over an empty database.// Asked only while the addon is on, like the tours below: with it off, every// trip of a dashboard load spent a request on a 404.- if (useAddonStore.getState().isEnabled('roadtrip')) {+ if (addonOn('roadtrip')) {await roadtripPreferencesRepo.read(tripId).catch(() => { /* optional cache */ })}@@ -167,7 +177,7 @@ async function syncTrip(tripId: number): Promise<void> {// Tours, the same way: optional, and never fatal. Without them every Tour// reads as a plain place offline. Asked only while the addon is on, so a// sync of many trips does not spend a refused request on each.- if (useAddonStore.getState().isEnabled('tours')) {+ if (addonOn('tours')) {try {await cacheTripTours(tripId)} catch (err) {@@ -176,6 +186,19 @@ async function syncTrip(tripId: number): Promise<void> {}}+/** The trip's addons, read and kept for offline use, and put in the store for the open views; null when unreadable. */+async function readTripAddons(tripId: number): Promise<TripAddon[] | null> {+ try {+ const addons = await tripAddonsRepo.list(tripId)+ useTripAddonsStore.getState().publish(tripId, addons)+ return addons+ } catch {+ // An optional cache like the ones after it: a trip opened offline then shows+ // the instance switches, until the next sync reads its own.+ return null+ }+}+/*** A trip's tours and, for its city walks, the stops checked off on their days* (CW-03), so a walk still shows how far it got offline. A walk whose stopsdiff --git a/client/src/utils/tripAddons.test.ts b/client/src/utils/tripAddons.test.tsnew file mode 100644index 000000000..8abe608eb--- /dev/null+++ b/client/src/utils/tripAddons.test.ts@@ -0,0 +1,41 @@+// FE-UTIL-TRIPADDONS-001 to FE-UTIL-TRIPADDONS-003+import type { TripAddon } from '@trek/shared';+import { describe, expect, it } from 'vitest';+import { pluginPageShown, tripAddonEnabled } from './tripAddons';++const addon = (id: string, enabled: boolean): TripAddon => ({+ id,+ name: id,+ icon: null,+ enabled,+ instanceEnabled: !enabled,+ overridden: true,+});++describe('tripAddonEnabled', () => {+ it('FE-UTIL-TRIPADDONS-001: the trip’s own list decides, both ways', () => {+ expect(tripAddonEnabled([addon('budget', true)], 'budget', false)).toBe(true);+ expect(tripAddonEnabled([addon('budget', false)], 'budget', true)).toBe(false);+ });++ it('FE-UTIL-TRIPADDONS-002: an addon the list does not name, or no list at all, follows the instance', () => {+ expect(tripAddonEnabled([addon('budget', false)], 'dawarich', true)).toBe(true);+ expect(tripAddonEnabled(null, 'tours', true)).toBe(true);+ expect(tripAddonEnabled(undefined, 'tours', false)).toBe(false);+ expect(tripAddonEnabled([], 'packing', false)).toBe(false);+ });+});++describe('pluginPageShown', () => {+ it('FE-UTIL-TRIPADDONS-003: a page that replaces core tabs shows while one of their addons is on', () => {+ const on = (ids: string[]) => (id: string) => ids.includes(id);+ expect(pluginPageShown(undefined, on([]))).toBe(true);+ expect(pluginPageShown([], on([]))).toBe(true);+ expect(pluginPageShown(['finanzplan'], on(['budget']))).toBe(true);+ expect(pluginPageShown(['finanzplan'], on(['packing']))).toBe(false);+ expect(pluginPageShown(['finanzplan', 'listen'], on(['packing']))).toBe(true);+ expect(pluginPageShown(['dateien', 'collab'], on([]))).toBe(false);+ // A tab no addon owns does not hide the page.+ expect(pluginPageShown(['plan'], on([]))).toBe(true);+ });+});diff --git a/client/src/utils/tripAddons.ts b/client/src/utils/tripAddons.tsnew file mode 100644index 000000000..f812bdcf1--- /dev/null+++ b/client/src/utils/tripAddons.ts@@ -0,0 +1,41 @@+import type { TripAddon } from '@trek/shared';++/**+ * Whether an addon applies to one trip.+ *+ * The trip's own list says it for every trip addon (lists, costs, files, collab,+ * road trip, tours), the owner's choice or the instance switch, whichever the+ * server worked out. An addon the list does not name (an integration such as+ * Dawarich, or any addon while the list is not known yet) follows the+ * instance switch the caller passes in.+ */+export function tripAddonEnabled(+ tripAddons: readonly TripAddon[] | null | undefined,+ addonId: string,+ instanceEnabled: boolean+): boolean {+ const own = tripAddons?.find((addon) => addon.id === addonId);+ return own ? own.enabled : instanceEnabled;+}++/** The trip addon a core trip tab belongs to; a plugin page that replaces the tab follows it. */+const TRIP_TAB_ADDON: Readonly<Record<string, string>> = {+ listen: 'packing',+ finanzplan: 'budget',+ dateien: 'documents',+ collab: 'collab',+};++/**+ * Whether a plugin's trip page shows on a trip. A page that replaces core tabs+ * stands in for them, so it shows while the addon of at least one of those tabs+ * is on for the trip; a page that replaces none (or only tabs no addon owns)+ * always shows.+ */+export function pluginPageShown(+ replaces: readonly string[] | undefined,+ addonOn: (addonId: string) => boolean+): boolean {+ const owned = (replaces ?? []).flatMap((tab) => (TRIP_TAB_ADDON[tab] ? [TRIP_TAB_ADDON[tab]] : []));+ return owned.length === 0 || owned.some(addonOn);+}diff --git a/client/tests/helpers/msw/handlers/addons.ts b/client/tests/helpers/msw/handlers/addons.tsindex aa970bbcc..bfe8973f0 100644--- a/client/tests/helpers/msw/handlers/addons.ts+++ b/client/tests/helpers/msw/handlers/addons.ts@@ -1,4 +1,6 @@+import { tripAddonsResponseSchema, tripAddonUpdateRequestSchema } from '@trek/shared';import { http, HttpResponse } from 'msw';+import { contractHandler } from '../contract';export const addonHandlers = [// Whose AI model reads images: off unless a test says otherwise, so no photo picker shows by default.@@ -12,4 +14,27 @@ export const addonHandlers = [],});}),+ // A trip that names no addon of its own: every addon follows the instance switch, as before per-trip addons.+ contractHandler('get', '/api/trips/:tripId/addons', { response: tripAddonsResponseSchema }, ({ params }) => ({+ tripId: Number(params.tripId),+ addons: [],+ })),+ contractHandler(+ 'put',+ '/api/trips/:tripId/addons/:addonId',+ { request: tripAddonUpdateRequestSchema, response: tripAddonsResponseSchema },+ ({ params, body }) => ({+ tripId: Number(params.tripId),+ addons: [+ {+ id: String(params.addonId),+ name: String(params.addonId),+ icon: null,+ enabled: body.enabled ?? true,+ instanceEnabled: true,+ overridden: body.enabled !== null,+ },+ ],+ })+ ),];diff --git a/client/tests/helpers/store.ts b/client/tests/helpers/store.tsindex 9a043255f..6c7923250 100644--- a/client/tests/helpers/store.ts+++ b/client/tests/helpers/store.ts@@ -1,4 +1,5 @@import type { StoreApi } from 'zustand';+import { useAddonStore, type CollabFeatures } from '../../src/store/addonStore';import { RESET_STORES } from './storeRegistry';// The state of each store in the registry when this module was first imported,@@ -26,3 +27,17 @@ type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]> }export function seedStore<T extends object>(store: Pick<StoreApi<T>, 'setState'>, state: DeepPartial<T>): void {store.setState(state as Partial<T>);}++/**+ * The instance's addons as the app read them from GET /api/addons: these on,+ * every other off. A trip that names no addon of its own (the default MSW+ * answer of GET /api/trips/:id/addons) then shows exactly these.+ */+export function seedInstanceAddons(ids: string[], collabFeatures?: Partial<CollabFeatures>): void {+ useAddonStore.setState((state) => ({+ addons: ids.map((id) => ({ id, name: id, type: 'trip', icon: '', enabled: true })),+ loaded: true,+ failed: false,+ collabFeatures: { ...state.collabFeatures, ...collabFeatures },+ }));+}diff --git a/client/tests/helpers/storeRegistry.ts b/client/tests/helpers/storeRegistry.tsindex e66af459c..3520f5bdb 100644--- a/client/tests/helpers/storeRegistry.ts+++ b/client/tests/helpers/storeRegistry.ts@@ -13,6 +13,7 @@ import { useSettingsStore } from '../../src/store/settingsStore';import { useTourMapViewportStore } from '../../src/store/tourMapViewportStore';import { useTourMapVisibilityStore } from '../../src/store/tourMapVisibilityStore';import { useTrackMarkToolStore } from '../../src/store/trackMarkToolStore';+import { useTripAddonsStore } from '../../src/store/tripAddonsStore';import { useTripStore } from '../../src/store/tripStore';import { useVacayStore } from '../../src/store/vacayStore';@@ -54,6 +55,8 @@ export const RESET_STORES: Record<string, ResettableStore> = {useFlightLiveStore,// The mail inbox and its pending count, which the menus of every shell read.useMailIngestStore,+ // The trip addons per trip, which every trip view reads: a list one test loaded must not decide the next one's tabs.+ useTripAddonsStore,};/** Not reset so far; moving one into RESET_STORES changes what every file that resets starts from. */diff --git a/client/tests/unit/db/offlineDb.upgrade.test.ts b/client/tests/unit/db/offlineDb.upgrade.test.tsindex f46b1b4a9..a13502472 100644--- a/client/tests/unit/db/offlineDb.upgrade.test.ts+++ b/client/tests/unit/db/offlineDb.upgrade.test.ts@@ -58,6 +58,7 @@ const HISTORY: Record<number, StoreSpec> = {13: { tourDrafts: 'tripId' },14: { routeCache: 'key, savedAt' },15: { tripTags: 'tripId' },+ 16: { tripAddons: 'tripId' },};const HISTORY_VERSIONS = Object.keys(HISTORY)@@ -140,6 +141,12 @@ function rowsAt(version: number): Record<string, Record<string, unknown>> {tourDrafts: { tripId: 1, draft: { payload: '{"version":11}', updated_at: '2026-10-22 09:00:00' } },routeCache: { key: 'driving:km:11.5,48.1;11.6,48.2', route: { coordinates: [], legs: [] }, savedAt: 13 },tripTags: { tripId: 1, tags: [{ id: 91, trip_id: 1, name: 'Viewpoint', color: '#10b981' }] },+ tripAddons: {+ tripId: 1,+ addons: [+ { id: 'budget', name: 'Costs', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true },+ ],+ },};const tables = schemaAt(version);return Object.fromEntries(Object.entries(all).filter(([table]) => table in tables));@@ -388,6 +395,28 @@ const UPGRADE_CASES: Record<number, UpgradeCase> = {expect(await db.tags.count()).toBe(1);},},+ 16: {+ intent: 'adds the trip addons of each trip, one list per trip, and keeps the tags a trip owns',+ check: async (db) => {+ expect((await db.tripTags.get(1))?.tags.map((tag) => tag.name)).toEqual(['Viewpoint']);+ const costsOff = {+ id: 'budget',+ name: 'Costs',+ icon: 'Wallet',+ enabled: false,+ instanceEnabled: true,+ overridden: true,+ };+ await db.table('tripAddons').bulkPut([+ { tripId: 1, addons: [costsOff] },+ { tripId: 2, addons: [] },+ ]);+ // One row per trip: the list read again replaces the one kept before.+ await db.table('tripAddons').put({ tripId: 1, addons: [{ ...costsOff, enabled: true, overridden: false }] });+ expect(await db.tripAddons.count()).toBe(2);+ expect((await db.tripAddons.get(1))?.addons[0]).toMatchObject({ id: 'budget', enabled: true, overridden: false });+ },+ },};describe('offlineDb upgrades', () => {diff --git a/client/tests/unit/mobile/trip/MTripSettingsSheet.test.tsx b/client/tests/unit/mobile/trip/MTripSettingsSheet.test.tsxindex 7cd4f849a..1f8fc18f0 100644--- a/client/tests/unit/mobile/trip/MTripSettingsSheet.test.tsx+++ b/client/tests/unit/mobile/trip/MTripSettingsSheet.test.tsx@@ -8,9 +8,9 @@ import { useTripStore } from '../../../../src/store/tripStore';import { buildTrip, buildUser } from '../../../helpers/factories';import { server } from '../../../helpers/msw/server';import { fireEvent, render, screen, waitFor, within } from '../../../helpers/render';-import { resetAllStores, seedStore } from '../../../helpers/store';+import { resetAllStores, seedInstanceAddons, seedStore } from '../../../helpers/store';-// FE-MOB-TSET-001 to FE-MOB-TSET-008: the phone's trip settings, on useTripShare.+// FE-MOB-TSET-001 to FE-MOB-TSET-010: the phone's trip settings, on useTripShare and useTripAddonRows.const owner = buildUser({ id: 1, username: 'owner' });const alice = buildUser({ id: 2, username: 'alice' });@@ -59,6 +59,8 @@ beforeEach(() => {resetAllStores();seedStore(useAuthStore, { user: owner, isAuthenticated: true });seedStore(useTripStore, { trip: buildTrip({ id: 1, title: 'Japan 2026', user_id: owner.id }) });+ // The instance has the three addons a link section belongs to; the trip names none of its own.+ seedInstanceAddons(['packing', 'budget', 'collab']);roster([]);server.use(http.get('/api/trips/1/share-link', () => HttpResponse.json({ token: null })),@@ -209,6 +211,26 @@ describe('MTripSettingsSheet', () => {expect(await screen.findByDisplayValue(/\/shared\/fresh$/)).toBeInTheDocument();});+ it('FE-MOB-TSET-006b: a section of an addon the trip switched off is not offered for the link', async () => {+ seedStore(usePermissionsStore, { permissions: { share_manage: 'trip_owner' } });+ server.use(+ http.get('/api/trips/1/addons', () =>+ HttpResponse.json({+ tripId: 1,+ addons: [+ { id: 'budget', name: 'Costs', icon: null, enabled: false, instanceEnabled: true, overridden: true },+ ],+ })+ )+ );+ renderSheet();+ await openArea('Sharing');++ expect(await screen.findByRole('button', { name: 'Packing' })).toBeInTheDocument();+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Costs' })).not.toBeInTheDocument());+ expect(screen.getByRole('button', { name: 'Chat' })).toBeInTheDocument();+ });+it('FE-MOB-TSET-007: the invite link is created and switched off again', async () => {const user = userEvent.setup();seedStore(usePermissionsStore, { permissions: { share_manage: 'trip_owner' } });@@ -246,4 +268,37 @@ describe('MTripSettingsSheet', () => {);expect(onClose).toHaveBeenCalled();});++ it('FE-MOB-TSET-009: the owner switches the trip addons, and back to the instance setting', async () => {+ const user = userEvent.setup();+ const bodies: unknown[] = [];+ const list = [+ { id: 'packing', name: 'Packing', icon: 'ListChecks', enabled: true, instanceEnabled: true, overridden: false },+ { id: 'tours', name: 'Tours', icon: 'Mountain', enabled: true, instanceEnabled: false, overridden: true },+ ];+ server.use(+ http.get('/api/trips/1/addons', () => HttpResponse.json({ tripId: 1, addons: list })),+ http.put('/api/trips/1/addons/:addonId', async ({ request }) => {+ bodies.push(await request.json());+ return HttpResponse.json({ tripId: 1, addons: list });+ })+ );+ renderSheet();+ fireEvent.click(await screen.findByRole('button', { name: /^Addons/ }));++ expect(await screen.findByText('Lists')).toBeInTheDocument();+ expect(screen.getByText('This trip only')).toBeInTheDocument();+ await user.click(screen.getByRole('switch', { name: 'Lists' }));+ await waitFor(() => expect(bodies).toEqual([{ enabled: false }]));+ await waitFor(() => expect(screen.getByRole('switch', { name: 'Tours' })).toBeEnabled());+ await user.click(screen.getByRole('switch', { name: 'Tours' }));+ await waitFor(() => expect(bodies).toEqual([{ enabled: false }, { enabled: null }]));+ });++ it('FE-MOB-TSET-010: a member who is not the owner gets no Addons area', async () => {+ seedStore(useAuthStore, { user: alice, isAuthenticated: true });+ renderSheet();+ expect(await screen.findByRole('button', { name: /^People/ })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /^Addons/ })).not.toBeInTheDocument();+ });});diff --git a/client/tests/unit/stores/addonStore.test.ts b/client/tests/unit/stores/addonStore.test.tsindex f4c71d34b..6f97fbdc7 100644--- a/client/tests/unit/stores/addonStore.test.ts+++ b/client/tests/unit/stores/addonStore.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, beforeEach } from 'vitest';import { http, HttpResponse } from 'msw';import { server } from '../../helpers/msw/server';-import { useAddonStore } from '../../../src/store/addonStore';+import { instanceAddonOn, useAddonStore } from '../../../src/store/addonStore';import { resetAllStores } from '../../helpers/store';beforeEach(() => {@@ -86,6 +86,62 @@ describe('addonStore', () => {expect(state.loaded).toBe(true);expect(state.addons).toEqual([]);+ expect(state.failed).toBe(true);+ // The empty list says nothing, so the caller's guess stands.+ expect(instanceAddonOn(state, 'packing', true)).toBe(true);+ });++ it('a failed refresh after a good read keeps that read as what the instance has', async () => {+ server.use(http.get('/api/addons', () => HttpResponse.json({ addons: [{ id: 'packing', enabled: true }] })));+ await useAddonStore.getState().loadAddons();+ server.use(http.get('/api/addons', () => HttpResponse.json({ error: 'down' }, { status: 500 })));+ await useAddonStore.getState().loadAddons();++ const state = useAddonStore.getState();+ expect(state.failed).toBe(false);+ expect(instanceAddonOn(state, 'packing', false)).toBe(true);+ expect(instanceAddonOn(state, 'budget', true)).toBe(false);+ });+ });++ describe('FE-ADDON-005: the Tours options and the collab features', () => {+ it('keeps the Tours options apart from the combined flags', async () => {+ server.use(+ http.get('/api/addons', () =>+ HttpResponse.json({+ toursWanderer: false,+ toursHikingMap: false,+ toursCycleMap: false,+ toursOptions: { wanderer: true, hikingMap: true, cycleMap: false },+ addons: [],+ })+ )+ );+ await useAddonStore.getState().loadAddons();+ expect(useAddonStore.getState().toursOptions).toEqual({ wanderer: true, hikingMap: true, cycleMap: false });+ expect(useAddonStore.getState().toursWanderer).toBe(false);+ });++ it('reads the options from the combined flags of a server that does not list them apart', async () => {+ server.use(+ http.get('/api/addons', () => HttpResponse.json({ toursWanderer: true, toursCycleMap: true, addons: [] }))+ );+ await useAddonStore.getState().loadAddons();+ expect(useAddonStore.getState().toursOptions).toEqual({ wanderer: true, hikingMap: false, cycleMap: true });+ });++ it('keeps every collab feature, on unless the response turns it off', async () => {+ server.use(+ http.get('/api/addons', () => HttpResponse.json({ addons: [], collabFeatures: { polls: false } }))+ );+ await useAddonStore.getState().loadAddons();+ expect(useAddonStore.getState().collabFeatures).toEqual({+ chat: true,+ notes: true,+ links: true,+ polls: false,+ whatsnext: true,+ });});});});diff --git a/client/tests/unit/sync/tripSyncManager.test.ts b/client/tests/unit/sync/tripSyncManager.test.tsindex a6adc2f44..88dee0aa1 100644--- a/client/tests/unit/sync/tripSyncManager.test.ts+++ b/client/tests/unit/sync/tripSyncManager.test.ts@@ -365,6 +365,48 @@ describe('tripSyncManager.syncAll — tours', () => {expect(await offlineDb.syncMeta.get(312)).toBeDefined();});+ describe("the trip's own addons", () => {+ const toursAddon = (enabled: boolean, instanceEnabled: boolean) => ({+ id: 'tours', name: 'Tours', icon: 'Mountain', enabled, instanceEnabled, overridden: enabled !== instanceEnabled,+ });+ const serveAddons = (tripId: number, addons: unknown[]) =>+ server.use(http.get(`/api/trips/${tripId}/addons`, () => HttpResponse.json({ tripId, addons })));++ it('keeps the list for offline use and caches tours for a trip that switched them on', async () => {+ // Off for the instance, on for this trip.+ serveAddons(314, [toursAddon(true, false)]);+ serve(314, () => HttpResponse.json({ tours: [tour] }));++ await tripSyncManager.syncAll();++ expect((await offlineDb.tripAddons.get(314))?.addons).toEqual([toursAddon(true, false)]);+ expect(await offlineDb.tours.get(900)).toMatchObject({ trip_id: 314 });+ });++ it('does not ask for the tours of a trip that switched them off', async () => {+ useAddonStore.setState({ addons: [{ id: 'tours', enabled: true }] as never });+ serveAddons(315, [toursAddon(false, true)]);+ const asked = serve(315, () => HttpResponse.json({ tours: [tour] }));++ await tripSyncManager.syncAll();++ expect(asked()).toBe(0);+ expect(await offlineDb.tours.count()).toBe(0);+ });++ it('follows the instance switch when the list cannot be read, and still stores the trip', async () => {+ useAddonStore.setState({ addons: [{ id: 'tours', enabled: true }] as never });+ server.use(http.get('/api/trips/316/addons', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));+ serve(316, () => HttpResponse.json({ tours: [tour] }));++ await tripSyncManager.syncAll();++ expect(await offlineDb.tripAddons.get(316)).toBeUndefined();+ expect(await offlineDb.tours.get(900)).toMatchObject({ trip_id: 316 });+ expect(await offlineDb.syncMeta.get(316)).toBeDefined();+ });+ });+// CW-03: a city walk shows how far it got offline, and its stops can be checked off there.describe('city walks', () => {const walk = (place_id: number) => ({ ...tour, place_id, name: `Walk ${place_id}`, tour_type: 'walk', max_hiking_difficulty: null, station_count: 1 });diff --git a/shared/src/i18n/ar/trip.ts b/shared/src/i18n/ar/trip.tsindex e96cc016a..018cf2534 100644--- a/shared/src/i18n/ar/trip.ts+++ b/shared/src/i18n/ar/trip.ts@@ -128,6 +128,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'المشاركة','trip.settings.sharingHint': 'رابط للقراءة فقط لأي شخص، ورابط دعوة للانضمام.','trip.settings.editTripHint': 'العنوان والتواريخ والغلاف والوصف والعملة.',+ 'trip.addons.saveFailed': 'تعذّر تغيير إضافات هذه الرحلة.',+ 'trip.settings.addons': 'الإضافات',+ 'trip.settings.addonsHint': 'شغّل الميزات أو أوقفها لهذه الرحلة فقط. ينطبق ذلك على كل من في الرحلة.',+ 'trip.addons.thisTripOnly': 'لهذه الرحلة فقط','trip.form.coverTitle': 'صورة الغلاف','trip.form.coverHint': 'تظهر على بطاقة الرحلة وفي أعلى المخطط.','trip.form.aboutTitle': 'الاسم والوصف',diff --git a/shared/src/i18n/az/trip.ts b/shared/src/i18n/az/trip.tsindex 45eb980b4..f765eab71 100644--- a/shared/src/i18n/az/trip.ts+++ b/shared/src/i18n/az/trip.ts@@ -119,6 +119,11 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Paylaşma','trip.settings.sharingHint': 'Hər kəs üçün yalnız oxunan keçid və qoşulmaq üçün dəvət keçidi.','trip.settings.editTripHint': 'Ad, tarixlər, üz qabığı, təsvir və valyuta.',+ 'trip.addons.saveFailed': 'Bu səyahətin əlavələrini dəyişmək mümkün olmadı.',+ 'trip.settings.addons': 'Əlavələr',+ 'trip.settings.addonsHint':+ 'Funksiyaları yalnız bu səyahət üçün açın və ya bağlayın. Bu, səyahətdəki hər kəsə aiddir.',+ 'trip.addons.thisTripOnly': 'Yalnız bu səyahət','trip.form.coverTitle': 'Örtük şəkli','trip.form.coverHint': 'Səfərin kartında və planlayıcının yuxarısında göstərilir.','trip.form.aboutTitle': 'Ad və təsvir',diff --git a/shared/src/i18n/br/trip.ts b/shared/src/i18n/br/trip.tsindex 255f3f5ef..cf02b2d8d 100644--- a/shared/src/i18n/br/trip.ts+++ b/shared/src/i18n/br/trip.ts@@ -108,6 +108,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Compartilhar','trip.settings.sharingHint': 'Um link somente leitura para qualquer pessoa e um link de convite para entrar.','trip.settings.editTripHint': 'Título, datas, capa, descrição e moeda.',+ 'trip.addons.saveFailed': 'Não foi possível alterar os complementos desta viagem.',+ 'trip.settings.addons': 'Complementos',+ 'trip.settings.addonsHint': 'Ative ou desative recursos só para esta viagem. Vale para todos na viagem.',+ 'trip.addons.thisTripOnly': 'Só esta viagem','trip.form.coverTitle': 'Imagem de capa','trip.form.coverHint': 'Aparece no cartão da viagem e no topo do planejador.','trip.form.aboutTitle': 'Nome e descrição',diff --git a/shared/src/i18n/ca/trip.ts b/shared/src/i18n/ca/trip.tsindex dcff7d9ac..904992b43 100644--- a/shared/src/i18n/ca/trip.ts+++ b/shared/src/i18n/ca/trip.ts@@ -108,6 +108,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Compartir','trip.settings.sharingHint': "Un enllaç de només lectura per a tothom i un enllaç d'invitació per unir-se.",'trip.settings.editTripHint': 'Títol, dates, portada, descripció i moneda.',+ 'trip.addons.saveFailed': "No s'han pogut canviar els complements d'aquest viatge.",+ 'trip.settings.addons': 'Complements',+ 'trip.settings.addonsHint': "Activa o desactiva funcions només per a aquest viatge. S'aplica a tothom del viatge.",+ 'trip.addons.thisTripOnly': 'Només aquest viatge','trip.form.coverTitle': 'Imatge de portada','trip.form.coverHint': 'Apareix a la targeta del viatge i a dalt del planificador.','trip.form.aboutTitle': 'Nom i descripció',diff --git a/shared/src/i18n/cs/trip.ts b/shared/src/i18n/cs/trip.tsindex c8b2bbc9b..2a1baa710 100644--- a/shared/src/i18n/cs/trip.ts+++ b/shared/src/i18n/cs/trip.ts@@ -113,6 +113,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Sdílení','trip.settings.sharingHint': 'Odkaz jen pro čtení pro kohokoli a pozvánka k připojení.','trip.settings.editTripHint': 'Název, termíny, obálka, popis a měna.',+ 'trip.addons.saveFailed': 'Doplňky tohoto výletu se nepodařilo změnit.',+ 'trip.settings.addons': 'Doplňky',+ 'trip.settings.addonsHint': 'Zapněte nebo vypněte funkce jen pro tento výlet. Platí to pro všechny účastníky výletu.',+ 'trip.addons.thisTripOnly': 'Jen tento výlet','trip.form.coverTitle': 'Titulní obrázek','trip.form.coverHint': 'Zobrazí se na kartě cesty a nahoře v plánovači.','trip.form.aboutTitle': 'Název a popis',diff --git a/shared/src/i18n/de/trip.ts b/shared/src/i18n/de/trip.tsindex bf3c1763d..813b025ed 100644--- a/shared/src/i18n/de/trip.ts+++ b/shared/src/i18n/de/trip.ts@@ -109,6 +109,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Teilen','trip.settings.sharingHint': 'Ein Nur-Lesen-Link für alle und ein Einladungslink zum Beitreten.','trip.settings.editTripHint': 'Titel, Daten, Titelbild, Beschreibung und Währung.',+ 'trip.addons.saveFailed': 'Die Addons dieser Reise konnten nicht geändert werden.',+ 'trip.settings.addons': 'Addons', // same-as-en+ 'trip.settings.addonsHint': 'Funktionen nur für diese Reise ein- oder ausschalten. Das gilt für alle auf der Reise.',+ 'trip.addons.thisTripOnly': 'Nur diese Reise','trip.form.coverTitle': 'Titelbild','trip.form.coverHint': 'Erscheint auf der Karte der Reise und oben im Planer.','trip.form.aboutTitle': 'Name und Beschreibung',diff --git a/shared/src/i18n/en/trip.ts b/shared/src/i18n/en/trip.tsindex dcf8f939b..2675ea700 100644--- a/shared/src/i18n/en/trip.ts+++ b/shared/src/i18n/en/trip.ts@@ -108,6 +108,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Sharing','trip.settings.sharingHint': 'A read-only link for anyone, and an invite link to join.','trip.settings.editTripHint': 'Title, dates, cover, description and currency.',+ 'trip.addons.saveFailed': 'The addons of this trip could not be changed.',+ 'trip.settings.addons': 'Addons',+ 'trip.settings.addonsHint': 'Switch features on or off for this trip only. It applies to everyone on the trip.',+ 'trip.addons.thisTripOnly': 'This trip only','trip.form.coverTitle': 'Cover image','trip.form.coverHint': "Shown on the trip's card and at the top of the planner.",'trip.form.aboutTitle': 'Name and description',diff --git a/shared/src/i18n/es/trip.ts b/shared/src/i18n/es/trip.tsindex 4f8820b47..fc889c0d8 100644--- a/shared/src/i18n/es/trip.ts+++ b/shared/src/i18n/es/trip.ts@@ -108,6 +108,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Compartir','trip.settings.sharingHint': 'Un enlace de solo lectura para cualquiera y un enlace de invitación para unirse.','trip.settings.editTripHint': 'Título, fechas, portada, descripción y moneda.',+ 'trip.addons.saveFailed': 'No se pudieron cambiar los complementos de este viaje.',+ 'trip.settings.addons': 'Complementos',+ 'trip.settings.addonsHint': 'Activa o desactiva funciones solo para este viaje. Se aplica a todos los del viaje.',+ 'trip.addons.thisTripOnly': 'Solo este viaje','trip.form.coverTitle': 'Imagen de portada','trip.form.coverHint': 'Aparece en la tarjeta del viaje y arriba en el planificador.','trip.form.aboutTitle': 'Nombre y descripción',diff --git a/shared/src/i18n/et/trip.ts b/shared/src/i18n/et/trip.tsindex f3b36052d..bc92350e1 100644--- a/shared/src/i18n/et/trip.ts+++ b/shared/src/i18n/et/trip.ts@@ -108,6 +108,11 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Jagamine','trip.settings.sharingHint': 'Kirjutuskaitstud link kõigile ja kutselink liitumiseks.','trip.settings.editTripHint': 'Pealkiri, kuupäevad, kaanepilt, kirjeldus ja valuuta.',+ 'trip.addons.saveFailed': 'Selle reisi lisasid ei õnnestunud muuta.',+ 'trip.settings.addons': 'Lisad',+ 'trip.settings.addonsHint':+ 'Lülita funktsioone sisse või välja ainult selle reisi jaoks. See kehtib kõigile reisil osalejatele.',+ 'trip.addons.thisTripOnly': 'Ainult see reis','trip.form.coverTitle': 'Kaanepilt','trip.form.coverHint': 'Kuvatakse reisi kaardil ja planeerija ülaosas.','trip.form.aboutTitle': 'Nimi ja kirjeldus',diff --git a/shared/src/i18n/fr/trip.ts b/shared/src/i18n/fr/trip.tsindex 569841692..f01289292 100644--- a/shared/src/i18n/fr/trip.ts+++ b/shared/src/i18n/fr/trip.ts@@ -109,6 +109,11 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Partage','trip.settings.sharingHint': "Un lien en lecture seule pour tous, et un lien d'invitation pour rejoindre.",'trip.settings.editTripHint': 'Titre, dates, couverture, description et devise.',+ 'trip.addons.saveFailed': 'Impossible de modifier les modules de ce voyage.',+ 'trip.settings.addons': 'Modules',+ 'trip.settings.addonsHint':+ 'Activez ou désactivez des fonctions pour ce voyage uniquement. Cela vaut pour tous les participants.',+ 'trip.addons.thisTripOnly': 'Ce voyage uniquement','trip.form.coverTitle': 'Image de couverture','trip.form.coverHint': 'Affichée sur la carte du voyage et en haut du planificateur.','trip.form.aboutTitle': 'Nom et description',diff --git a/shared/src/i18n/gr/trip.ts b/shared/src/i18n/gr/trip.tsindex 1f863425b..082a4ecbb 100644--- a/shared/src/i18n/gr/trip.ts+++ b/shared/src/i18n/gr/trip.ts@@ -111,6 +111,11 @@ const trip: TranslationStrings = {'trip.settings.sharingHint':'Ένας σύνδεσμος μόνο για ανάγνωση για όλους και ένας σύνδεσμος πρόσκλησης για συμμετοχή.','trip.settings.editTripHint': 'Τίτλος, ημερομηνίες, εξώφυλλο, περιγραφή και νόμισμα.',+ 'trip.addons.saveFailed': 'Δεν ήταν δυνατή η αλλαγή των πρόσθετων αυτού του ταξιδιού.',+ 'trip.settings.addons': 'Πρόσθετα',+ 'trip.settings.addonsHint':+ 'Ενεργοποιήστε ή απενεργοποιήστε λειτουργίες μόνο για αυτό το ταξίδι. Ισχύει για όλους στο ταξίδι.',+ 'trip.addons.thisTripOnly': 'Μόνο αυτό το ταξίδι','trip.form.coverTitle': 'Εικόνα εξωφύλλου','trip.form.coverHint': 'Εμφανίζεται στην κάρτα του ταξιδιού και στην κορυφή του σχεδιαστή.','trip.form.aboutTitle': 'Όνομα και περιγραφή',diff --git a/shared/src/i18n/he/trip.ts b/shared/src/i18n/he/trip.tsindex 3365aa8d5..7ec0e25d2 100644--- a/shared/src/i18n/he/trip.ts+++ b/shared/src/i18n/he/trip.ts@@ -112,6 +112,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'שיתוף','trip.settings.sharingHint': 'קישור לקריאה בלבד לכל אחד, וקישור הזמנה להצטרפות.','trip.settings.editTripHint': 'כותרת, תאריכים, תמונת שער, תיאור ומטבע.',+ 'trip.addons.saveFailed': 'לא ניתן היה לשנות את התוספים של הטיול הזה.',+ 'trip.settings.addons': 'תוספים',+ 'trip.settings.addonsHint': 'הפעלה או כיבוי של תכונות לטיול הזה בלבד. זה חל על כל מי שבטיול.',+ 'trip.addons.thisTripOnly': 'לטיול הזה בלבד','trip.form.coverTitle': 'תמונת שער','trip.form.coverHint': 'מוצגת בכרטיס הטיול ובראש המתכנן.','trip.form.aboutTitle': 'שם ותיאור',diff --git a/shared/src/i18n/hu/trip.ts b/shared/src/i18n/hu/trip.tsindex d7dbd6263..ea3e55425 100644--- a/shared/src/i18n/hu/trip.ts+++ b/shared/src/i18n/hu/trip.ts@@ -111,6 +111,11 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Megosztás','trip.settings.sharingHint': 'Csak olvasható link bárkinek, és meghívó link a csatlakozáshoz.','trip.settings.editTripHint': 'Cím, dátumok, borítókép, leírás és pénznem.',+ 'trip.addons.saveFailed': 'Az utazás bővítményeit nem sikerült módosítani.',+ 'trip.settings.addons': 'Bővítmények',+ 'trip.settings.addonsHint':+ 'Funkciók be- vagy kikapcsolása csak ehhez az utazáshoz. Ez az utazás minden résztvevőjére vonatkozik.',+ 'trip.addons.thisTripOnly': 'Csak ez az utazás','trip.form.coverTitle': 'Borítókép','trip.form.coverHint': 'Az utazás kártyáján és a tervező tetején jelenik meg.','trip.form.aboutTitle': 'Név és leírás',diff --git a/shared/src/i18n/id/trip.ts b/shared/src/i18n/id/trip.tsindex 90024d941..4ec12cf72 100644--- a/shared/src/i18n/id/trip.ts+++ b/shared/src/i18n/id/trip.ts@@ -104,6 +104,11 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Berbagi','trip.settings.sharingHint': 'Tautan hanya-baca untuk siapa saja, dan tautan undangan untuk bergabung.','trip.settings.editTripHint': 'Judul, tanggal, sampul, deskripsi, dan mata uang.',+ 'trip.addons.saveFailed': 'Add-on perjalanan ini tidak dapat diubah.',+ 'trip.settings.addons': 'Add-on',+ 'trip.settings.addonsHint':+ 'Aktifkan atau nonaktifkan fitur hanya untuk perjalanan ini. Berlaku untuk semua orang di perjalanan.',+ 'trip.addons.thisTripOnly': 'Hanya perjalanan ini','trip.form.coverTitle': 'Gambar sampul','trip.form.coverHint': 'Tampil di kartu perjalanan dan di bagian atas perencana.','trip.form.aboutTitle': 'Nama dan deskripsi',diff --git a/shared/src/i18n/it/trip.ts b/shared/src/i18n/it/trip.tsindex da77fb283..0f76c5f39 100644--- a/shared/src/i18n/it/trip.ts+++ b/shared/src/i18n/it/trip.ts@@ -108,6 +108,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Condivisione','trip.settings.sharingHint': 'Un link di sola lettura per tutti e un link di invito per unirsi.','trip.settings.editTripHint': 'Titolo, date, copertina, descrizione e valuta.',+ 'trip.addons.saveFailed': 'Impossibile modificare i componenti aggiuntivi di questo viaggio.',+ 'trip.settings.addons': 'Componenti aggiuntivi',+ 'trip.settings.addonsHint': 'Attiva o disattiva funzioni solo per questo viaggio. Vale per tutti i partecipanti.',+ 'trip.addons.thisTripOnly': 'Solo questo viaggio','trip.form.coverTitle': 'Immagine di copertina','trip.form.coverHint': 'Appare sulla scheda del viaggio e in alto nel planner.','trip.form.aboutTitle': 'Nome e descrizione',diff --git a/shared/src/i18n/ja/trip.ts b/shared/src/i18n/ja/trip.tsindex 61bc6560b..5d7ef4693 100644--- a/shared/src/i18n/ja/trip.ts+++ b/shared/src/i18n/ja/trip.ts@@ -101,6 +101,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': '共有','trip.settings.sharingHint': '誰でも見られる閲覧専用リンクと、参加用の招待リンク。','trip.settings.editTripHint': 'タイトル、日程、カバー画像、説明、通貨。',+ 'trip.addons.saveFailed': 'この旅行のアドオンを変更できませんでした。',+ 'trip.settings.addons': 'アドオン',+ 'trip.settings.addonsHint': 'この旅行だけで機能をオンまたはオフにします。旅行の全員に適用されます。',+ 'trip.addons.thisTripOnly': 'この旅行のみ','trip.form.coverTitle': 'カバー画像','trip.form.coverHint': '旅行のカードとプランナーの上部に表示されます。','trip.form.aboutTitle': '名前と説明',diff --git a/shared/src/i18n/ko/trip.ts b/shared/src/i18n/ko/trip.tsindex 38830b5ab..2264f556c 100644--- a/shared/src/i18n/ko/trip.ts+++ b/shared/src/i18n/ko/trip.ts@@ -101,6 +101,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': '공유','trip.settings.sharingHint': '누구나 볼 수 있는 읽기 전용 링크와 참여용 초대 링크.','trip.settings.editTripHint': '제목, 날짜, 커버 이미지, 설명, 통화.',+ 'trip.addons.saveFailed': '이 여행의 애드온을 변경할 수 없습니다.',+ 'trip.settings.addons': '애드온',+ 'trip.settings.addonsHint': '이 여행에서만 기능을 켜거나 끕니다. 여행의 모든 사람에게 적용됩니다.',+ 'trip.addons.thisTripOnly': '이 여행만','trip.form.coverTitle': '커버 이미지','trip.form.coverHint': '여행 카드와 플래너 상단에 표시됩니다.','trip.form.aboutTitle': '이름과 설명',diff --git a/shared/src/i18n/nl/trip.ts b/shared/src/i18n/nl/trip.tsindex 8da14caed..306666c0b 100644--- a/shared/src/i18n/nl/trip.ts+++ b/shared/src/i18n/nl/trip.ts@@ -108,6 +108,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Delen','trip.settings.sharingHint': 'Een alleen-lezen-link voor iedereen en een uitnodigingslink om mee te doen.','trip.settings.editTripHint': 'Titel, data, omslagfoto, beschrijving en valuta.',+ 'trip.addons.saveFailed': 'De add-ons van deze reis konden niet worden gewijzigd.',+ 'trip.settings.addons': 'Add-ons',+ 'trip.settings.addonsHint': 'Zet functies alleen voor deze reis aan of uit. Dit geldt voor iedereen op de reis.',+ 'trip.addons.thisTripOnly': 'Alleen deze reis','trip.form.coverTitle': 'Omslagfoto','trip.form.coverHint': 'Staat op de kaart van de reis en bovenaan de planner.','trip.form.aboutTitle': 'Naam en beschrijving',diff --git a/shared/src/i18n/pl/trip.ts b/shared/src/i18n/pl/trip.tsindex 93e3fb113..32b38a9e8 100644--- a/shared/src/i18n/pl/trip.ts+++ b/shared/src/i18n/pl/trip.ts@@ -118,6 +118,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Udostępnianie','trip.settings.sharingHint': 'Link tylko do odczytu dla każdego i link z zaproszeniem do dołączenia.','trip.settings.editTripHint': 'Tytuł, daty, okładka, opis i waluta.',+ 'trip.addons.saveFailed': 'Nie udało się zmienić dodatków tej podróży.',+ 'trip.settings.addons': 'Dodatki',+ 'trip.settings.addonsHint': 'Włącz lub wyłącz funkcje tylko dla tej podróży. Dotyczy to wszystkich uczestników.',+ 'trip.addons.thisTripOnly': 'Tylko ta podróż','trip.form.coverTitle': 'Zdjęcie okładki','trip.form.coverHint': 'Widoczne na karcie podróży i na górze planera.','trip.form.aboutTitle': 'Nazwa i opis',diff --git a/shared/src/i18n/ru/trip.ts b/shared/src/i18n/ru/trip.tsindex 275c7391e..e40027744 100644--- a/shared/src/i18n/ru/trip.ts+++ b/shared/src/i18n/ru/trip.ts@@ -118,6 +118,11 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Доступ по ссылке','trip.settings.sharingHint': 'Ссылка только для чтения для всех и ссылка-приглашение для участия.','trip.settings.editTripHint': 'Название, даты, обложка, описание и валюта.',+ 'trip.addons.saveFailed': 'Не удалось изменить дополнения этой поездки.',+ 'trip.settings.addons': 'Дополнения',+ 'trip.settings.addonsHint':+ 'Включайте и выключайте функции только для этой поездки. Это действует для всех участников.',+ 'trip.addons.thisTripOnly': 'Только эта поездка','trip.form.coverTitle': 'Обложка','trip.form.coverHint': 'Показывается на карточке поездки и вверху планировщика.','trip.form.aboutTitle': 'Название и описание',diff --git a/shared/src/i18n/sk/trip.ts b/shared/src/i18n/sk/trip.tsindex 2dd6407ab..03b3879a3 100644--- a/shared/src/i18n/sk/trip.ts+++ b/shared/src/i18n/sk/trip.ts@@ -113,6 +113,11 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Zdieľanie','trip.settings.sharingHint': 'Odkaz len na čítanie pre kohokoľvek a pozvánka na pripojenie.','trip.settings.editTripHint': 'Názov, termíny, obálka, popis a mena.',+ 'trip.addons.saveFailed': 'Doplnky tohto výletu sa nepodarilo zmeniť.',+ 'trip.settings.addons': 'Doplnky',+ 'trip.settings.addonsHint':+ 'Zapnite alebo vypnite funkcie len pre tento výlet. Platí to pre všetkých účastníkov výletu.',+ 'trip.addons.thisTripOnly': 'Len tento výlet','trip.form.coverTitle': 'Titulný obrázok','trip.form.coverHint': 'Zobrazí sa na karte cesty a hore v plánovači.','trip.form.aboutTitle': 'Názov a popis',diff --git a/shared/src/i18n/sv/trip.ts b/shared/src/i18n/sv/trip.tsindex a511dd39b..02d8f98bc 100644--- a/shared/src/i18n/sv/trip.ts+++ b/shared/src/i18n/sv/trip.ts@@ -108,6 +108,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Dela','trip.settings.sharingHint': 'En skrivskyddad länk för alla och en inbjudningslänk för att gå med.','trip.settings.editTripHint': 'Titel, datum, omslagsbild, beskrivning och valuta.',+ 'trip.addons.saveFailed': 'Tilläggen för den här resan kunde inte ändras.',+ 'trip.settings.addons': 'Tillägg',+ 'trip.settings.addonsHint': 'Slå på eller av funktioner bara för den här resan. Det gäller alla på resan.',+ 'trip.addons.thisTripOnly': 'Bara den här resan','trip.form.coverTitle': 'Omslagsbild','trip.form.coverHint': 'Visas på resans kort och högst upp i planeraren.','trip.form.aboutTitle': 'Namn och beskrivning',diff --git a/shared/src/i18n/th/trip.ts b/shared/src/i18n/th/trip.tsindex bbaf12795..fefc2b589 100644--- a/shared/src/i18n/th/trip.ts+++ b/shared/src/i18n/th/trip.ts@@ -100,6 +100,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'การแชร์','trip.settings.sharingHint': 'ลิงก์อ่านอย่างเดียวสำหรับทุกคน และลิงก์เชิญเพื่อเข้าร่วม','trip.settings.editTripHint': 'ชื่อ วันที่ ภาพปก คำอธิบาย และสกุลเงิน',+ 'trip.addons.saveFailed': 'ไม่สามารถเปลี่ยนส่วนเสริมของทริปนี้ได้',+ 'trip.settings.addons': 'ส่วนเสริม',+ 'trip.settings.addonsHint': 'เปิดหรือปิดฟีเจอร์สำหรับทริปนี้เท่านั้น มีผลกับทุกคนในทริป',+ 'trip.addons.thisTripOnly': 'เฉพาะทริปนี้','trip.form.coverTitle': 'ภาพปก','trip.form.coverHint': 'แสดงบนการ์ดทริปและด้านบนของตัววางแผน','trip.form.aboutTitle': 'ชื่อและคำอธิบาย',diff --git a/shared/src/i18n/tr/trip.ts b/shared/src/i18n/tr/trip.tsindex bfcd1d1eb..fea5dead1 100644--- a/shared/src/i18n/tr/trip.ts+++ b/shared/src/i18n/tr/trip.ts@@ -109,6 +109,11 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Paylaşım','trip.settings.sharingHint': 'Herkes için salt okunur bir bağlantı ve katılmak için davet bağlantısı.','trip.settings.editTripHint': 'Başlık, tarihler, kapak, açıklama ve para birimi.',+ 'trip.addons.saveFailed': 'Bu seyahatin eklentileri değiştirilemedi.',+ 'trip.settings.addons': 'Eklentiler',+ 'trip.settings.addonsHint':+ 'Özellikleri yalnızca bu seyahat için açın veya kapatın. Seyahatteki herkes için geçerlidir.',+ 'trip.addons.thisTripOnly': 'Yalnızca bu seyahat','trip.form.coverTitle': 'Kapak görseli','trip.form.coverHint': 'Seyahat kartında ve planlayıcının üstünde görünür.','trip.form.aboutTitle': 'Ad ve açıklama',diff --git a/shared/src/i18n/uk/trip.ts b/shared/src/i18n/uk/trip.tsindex 2c9dc025b..beafe4589 100644--- a/shared/src/i18n/uk/trip.ts+++ b/shared/src/i18n/uk/trip.ts@@ -118,6 +118,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Поширення','trip.settings.sharingHint': 'Посилання лише для читання для всіх і посилання-запрошення, щоб приєднатися.','trip.settings.editTripHint': 'Назва, дати, обкладинка, опис і валюта.',+ 'trip.addons.saveFailed': 'Не вдалося змінити доповнення цієї подорожі.',+ 'trip.settings.addons': 'Доповнення',+ 'trip.settings.addonsHint': 'Вмикайте або вимикайте функції лише для цієї подорожі. Це діє для всіх учасників.',+ 'trip.addons.thisTripOnly': 'Лише ця подорож','trip.form.coverTitle': 'Обкладинка','trip.form.coverHint': 'Показується на картці подорожі та вгорі планувальника.','trip.form.aboutTitle': 'Назва й опис',diff --git a/shared/src/i18n/vi/trip.ts b/shared/src/i18n/vi/trip.tsindex 718decff2..9f5c22a97 100644--- a/shared/src/i18n/vi/trip.ts+++ b/shared/src/i18n/vi/trip.ts@@ -103,6 +103,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': 'Chia sẻ','trip.settings.sharingHint': 'Liên kết chỉ đọc cho mọi người và liên kết mời để tham gia.','trip.settings.editTripHint': 'Tiêu đề, ngày, ảnh bìa, mô tả và tiền tệ.',+ 'trip.addons.saveFailed': 'Không thể thay đổi các tiện ích bổ sung của chuyến đi này.',+ 'trip.settings.addons': 'Tiện ích bổ sung',+ 'trip.settings.addonsHint': 'Bật hoặc tắt tính năng chỉ cho chuyến đi này. Áp dụng cho mọi người trong chuyến đi.',+ 'trip.addons.thisTripOnly': 'Chỉ chuyến đi này','trip.form.coverTitle': 'Ảnh bìa','trip.form.coverHint': 'Hiển thị trên thẻ chuyến đi và ở đầu trình lập kế hoạch.','trip.form.aboutTitle': 'Tên và mô tả',diff --git a/shared/src/i18n/zh-TW/trip.ts b/shared/src/i18n/zh-TW/trip.tsindex c4464761f..9be961c29 100644--- a/shared/src/i18n/zh-TW/trip.ts+++ b/shared/src/i18n/zh-TW/trip.ts@@ -100,6 +100,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': '分享','trip.settings.sharingHint': '任何人可用的唯讀連結,以及用於加入的邀請連結。','trip.settings.editTripHint': '標題、日期、封面、描述和貨幣。',+ 'trip.addons.saveFailed': '無法變更此旅程的附加元件。',+ 'trip.settings.addons': '附加元件',+ 'trip.settings.addonsHint': '僅為此旅程開啟或關閉功能。對旅程中的所有人生效。',+ 'trip.addons.thisTripOnly': '僅此旅程','trip.form.coverTitle': '封面圖片','trip.form.coverHint': '顯示在旅行卡片與規劃器頂部。','trip.form.aboutTitle': '名稱與描述',diff --git a/shared/src/i18n/zh/trip.ts b/shared/src/i18n/zh/trip.tsindex 66ea2bb70..ef989ea8c 100644--- a/shared/src/i18n/zh/trip.ts+++ b/shared/src/i18n/zh/trip.ts@@ -100,6 +100,10 @@ const trip: TranslationStrings = {'trip.settings.sharing': '分享','trip.settings.sharingHint': '任何人可用的只读链接,以及用于加入的邀请链接。','trip.settings.editTripHint': '标题、日期、封面、描述和货币。',+ 'trip.addons.saveFailed': '无法更改此旅程的附加组件。',+ 'trip.settings.addons': '附加组件',+ 'trip.settings.addonsHint': '仅为此旅程开启或关闭功能。对旅程中的所有人生效。',+ 'trip.addons.thisTripOnly': '仅此旅程','trip.form.coverTitle': '封面图片','trip.form.coverHint': '显示在旅行卡片和规划器顶部。','trip.form.aboutTitle': '名称和描述',