Skip to content

armgit / TREK

Public Imported from GitHub
0

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.

Managed mode: hand place search, routing, plugins and docs to the operator

Maurice86513fda0d39
diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx
index 566d1b4e2..14db721e2 100644
--- a/client/src/App.test.tsx
+++ b/client/src/App.test.tsx
@@ -436,6 +436,28 @@ describe('App — on-mount effects', () => {
await waitFor(() => expect(setManaged).toHaveBeenCalledWith(false))
})
+ it('FE-COMP-APP-018c: app-config is asked again after a failed answer, so managed is not lost', async () => {
+ // A page opened while the server restarts got a 502 here and kept every
+ // default for the session, which brought back the operator's settings.
+ let calls = 0
+ server.use(
+ http.get('/api/auth/app-config', () => {
+ calls += 1
+ return calls === 1 ? new HttpResponse(null, { status: 502 }) : HttpResponse.json({ managed: true })
+ })
+ )
+ const setManaged = vi.fn()
+ useAuthStore.setState({
+ isLoading: false,
+ isAuthenticated: false,
+ loadUser: vi.fn().mockResolvedValue(undefined),
+ setManaged,
+ })
+ renderApp('/')
+ await waitFor(() => expect(setManaged).toHaveBeenCalledWith(true), { timeout: 4000 })
+ expect(calls).toBe(2)
+ })
+
it('FE-COMP-APP-019: loadSettings is called once the user is authenticated', async () => {
const loadSettings = vi.fn().mockResolvedValue(undefined)
seedAuth({ isAuthenticated: true, user: buildUser() })
diff --git a/client/src/App.tsx b/client/src/App.tsx
index 61bd92380..6419e2018 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -323,7 +323,21 @@ export default function App() {
loadUser()
}
}
- authApi.getAppConfig().then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record<string, PermissionLevel> }) => {
+ // Asked again until it answers: a page opened while the server restarts got a
+ // 502 here and kept the defaults for the whole session, which on a managed
+ // install put back every setting the operator owns.
+ let cancelled = false
+ let retryTimer: ReturnType<typeof setTimeout> | undefined
+ type AppConfigAnswer = Awaited<ReturnType<typeof authApi.getAppConfig>>
+ const fetchAppConfig = (attempt: number): Promise<AppConfigAnswer> => authApi.getAppConfig().catch((err: unknown) => {
+ if (cancelled) throw err
+ return new Promise<AppConfigAnswer>((resolve, reject) => {
+ retryTimer = setTimeout(() => {
+ fetchAppConfig(attempt + 1).then(resolve, reject)
+ }, Math.min(30_000, 1_000 * 2 ** attempt))
+ })
+ })
+ fetchAppConfig(0).then(async (config: { managed?: boolean; demo_mode?: boolean; dev_mode?: boolean; is_prerelease?: boolean; has_maps_key?: boolean; has_amap_key?: boolean; places_provider?: string; version?: string; timezone?: string; require_mfa?: boolean; trip_reminders_enabled?: boolean; places_photos_enabled?: boolean; places_autocomplete_enabled?: boolean; places_details_enabled?: boolean; places_enrich_enabled?: boolean; place_shadow_enabled?: boolean; max_upload_mb?: number; permissions?: Record<string, PermissionLevel> }) => {
setManaged(!!config?.managed)
setDemoMode(!!config?.demo_mode)
if (config?.dev_mode) setDevMode(true)
@@ -347,6 +361,10 @@ export default function App() {
// Last, since a new release reloads the page from here.
await reconcileAppVersion(config?.version)
}).catch(() => {})
+ return () => {
+ cancelled = true
+ clearTimeout(retryTimer)
+ }
}, [])
const { settings } = useSettingsStore()
@@ -402,6 +420,10 @@ export default function App() {
// interceptor's covers all of /public/. A route that is public to one and not
// to the other is exactly the seam that puts a 401 back.
const hideAuthedWidgets = isAuthPage || isAuthPublicPath(location.pathname)
+ // The Help & Docs page is the wiki, written for somebody who runs TREK
+ // themselves: keys, backups, updates, the server behind it. A managed install
+ // does not offer it; the in-app help center stays.
+ const managed = useAuthStore(s => s.managed)
return (
<TranslationProvider>
@@ -456,7 +478,7 @@ export default function App() {
path="/help"
element={
<ProtectedRoute>
- <HelpPage />
+ {managed ? <Navigate to="/dashboard" replace /> : <HelpPage />}
</ProtectedRoute>
}
/>
@@ -464,7 +486,7 @@ export default function App() {
path="/help/:slug"
element={
<ProtectedRoute>
- <HelpPage />
+ {managed ? <Navigate to="/dashboard" replace /> : <HelpPage />}
</ProtectedRoute>
}
/>
diff --git a/client/src/components/Admin/AddonManager.test.tsx b/client/src/components/Admin/AddonManager.test.tsx
index 77b5d6d34..8338b5a63 100644
--- a/client/src/components/Admin/AddonManager.test.tsx
+++ b/client/src/components/Admin/AddonManager.test.tsx
@@ -3,6 +3,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
+import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useAddonStore } from '../../store/addonStore';
import { ToastContainer } from '../shared/Toast';
@@ -679,6 +680,16 @@ describe('AddonManager', () => {
expect(isOn(screen.getByRole('button', { name: 'wanderer' }))).toBe(true);
});
+ it('FE-ADMIN-ADDON-042b: a managed install has no wanderer switch under Tours', async () => {
+ seedStore(useAuthStore, { managed: true });
+ server.use(addonsRoute([buildAddon({ id: 'tours', name: 'Tours', icon: 'Mountain', enabled: true })]));
+ render(<AddonManager />);
+
+ await screen.findByRole('button', { name: /\d+ options?/, expanded: false });
+ await unfoldShelves();
+ expect(screen.queryByRole('button', { name: 'wanderer' })).not.toBeInTheDocument();
+ });
+
it('FE-ADMIN-ADDON-043: a failed wanderer save puts the switch back', async () => {
server.use(
addonsRoute([buildAddon({ id: 'tours', name: 'Tours', icon: 'Mountain', enabled: true })]),
diff --git a/client/src/components/Admin/AddonManager.tsx b/client/src/components/Admin/AddonManager.tsx
index 99d96ca3c..a5939fb5b 100644
--- a/client/src/components/Admin/AddonManager.tsx
+++ b/client/src/components/Admin/AddonManager.tsx
@@ -73,6 +73,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
const {
addons, loading, handleToggle, tripAddons, globalAddons, integrationAddons, aiAddons, providerOptions, documentProviderOptions,
toursWanderer,
+ wandererOffered,
toggleToursWanderer,
mapSwitches,
} = useAddonManager()
@@ -157,14 +158,18 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
// "N options" bar the way Collab's and Documents' are.
if (addon.id === 'tours' && addon.enabled) {
return [
- <AddonSubRow
- key="wanderer"
- icon={<WandererMark size={14} />}
- title={t('admin.toursWanderer.title')}
- description={t('admin.toursWanderer.subtitle')}
- enabled={toursWanderer}
- onToggle={() => void toggleToursWanderer()}
- />,
+ ...(wandererOffered
+ ? [
+ <AddonSubRow
+ key="wanderer"
+ icon={<WandererMark size={14} />}
+ title={t('admin.toursWanderer.title')}
+ description={t('admin.toursWanderer.subtitle')}
+ enabled={toursWanderer}
+ onToggle={() => void toggleToursWanderer()}
+ />,
+ ]
+ : []),
...mapSwitches.map(({ key, Icon, titleKey, subtitleKey, enabled, toggle }) => (
<AddonSubRow
key={key}
diff --git a/client/src/components/Admin/DefaultUserSettingsTab.tsx b/client/src/components/Admin/DefaultUserSettingsTab.tsx
index c4038d99d..08461a390 100644
--- a/client/src/components/Admin/DefaultUserSettingsTab.tsx
+++ b/client/src/components/Admin/DefaultUserSettingsTab.tsx
@@ -12,7 +12,7 @@ import type { DistanceUnit, WeekStart } from '../../types'
import { weekStartOptions } from '../../utils/calendarWeek'
import { withTileApiKey } from '../../utils/tileUrl'
import { defaultStyleForProvider } from '../Map/glProviders'
-import { MAP_PRESETS, type MapProvider } from '../Settings/mapSettingsModel'
+import type { MapProvider } from '../Settings/mapSettingsModel'
import RoutingInstanceFields from './RoutingInstanceFields'
import { useDefaultUserSettings, type Defaults } from './useDefaultUserSettings'
@@ -69,7 +69,7 @@ function errorText(err: unknown, fallback: string): string {
export default function DefaultUserSettingsTab(): React.ReactElement {
const { t, locale } = useTranslation()
const {
- defaults, loaded, managed, isSet, save, reset, mapTileUrl, setMapTileUrl, mapboxToken, setMapboxToken,
+ defaults, loaded, managed, presets, canMapbox, isSet, save, reset, mapTileUrl, setMapTileUrl, mapboxToken, setMapboxToken,
cartoKey, setCartoKey, mapboxStyle, setMapboxStyle, mapPreviewPlaces, mapProvider, glStylePresets, styleKey,
saveMapProvider, pickTilePreset, pickStylePreset, commitStyle,
} = useDefaultUserSettings({ errorMessage: errorText, previewCreatedAt: () => String(new Date()) })
@@ -217,7 +217,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
value={mapTileUrl}
onChange={pickTilePreset}
placeholder={t('settings.mapTemplatePlaceholder.select')}
- options={MAP_PRESETS.map(p => ({ value: p.url, label: p.name }))}
+ options={presets.map(p => ({ value: p.url, label: p.name }))}
/>
<input
type="text"
@@ -283,7 +283,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
onChange={saveMapProvider}
options={[
{ value: 'leaflet', label: t('admin.defaultSettings.providerLeaflet') },
- { value: 'mapbox-gl', label: t('admin.defaultSettings.providerMapbox') },
+ ...(canMapbox ? [{ value: 'mapbox-gl' as const, label: t('admin.defaultSettings.providerMapbox') }] : []),
{ value: 'maplibre-gl', label: t('admin.defaultSettings.providerMapLibre') },
]}
/>
diff --git a/client/src/components/Admin/PlaceContribPanel.test.tsx b/client/src/components/Admin/PlaceContribPanel.test.tsx
index a29b83ab9..fa241820d 100644
--- a/client/src/components/Admin/PlaceContribPanel.test.tsx
+++ b/client/src/components/Admin/PlaceContribPanel.test.tsx
@@ -1,4 +1,4 @@
-// FE-ADMIN-CONTRIB-001 to FE-ADMIN-CONTRIB-011
+// FE-ADMIN-CONTRIB-001 to FE-ADMIN-CONTRIB-013
import userEvent from '@testing-library/user-event';
import type { PlaceContribDecisionRequest, PlaceContribState } from '@trek/shared';
import { http, HttpResponse } from 'msw';
@@ -201,4 +201,23 @@ describe('PlaceContribPanel', () => {
vi.useRealTimers();
}
});
+
+ it('FE-ADMIN-CONTRIB-012: standing alone, a card the operator switched off is not shown', async () => {
+ const asked = vi.fn();
+ server.use(
+ http.get('/api/admin/places-contribute', () => {
+ asked();
+ return HttpResponse.json({ ...UNDECIDED, eligible: false, ineligibleReason: 'env_off', showPrompt: false });
+ })
+ );
+ const { container } = render(<PlaceContribPanel hideWhenSwitchedOff />);
+ await waitFor(() => expect(asked).toHaveBeenCalled());
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('FE-ADMIN-CONTRIB-013: standing alone, any other reason is still explained', async () => {
+ serve({ ...UNDECIDED, eligible: false, ineligibleReason: 'not_production', showPrompt: false });
+ render(<PlaceContribPanel hideWhenSwitchedOff />);
+ expect(await screen.findByText('admin.contribute.ineligible.not_production')).toBeInTheDocument();
+ });
});
diff --git a/client/src/components/Admin/PlaceContribPanel.tsx b/client/src/components/Admin/PlaceContribPanel.tsx
index 0fbaa7c9b..645e76eb2 100644
--- a/client/src/components/Admin/PlaceContribPanel.tsx
+++ b/client/src/components/Admin/PlaceContribPanel.tsx
@@ -61,7 +61,7 @@ function Figures({ state, t }: { state: PlaceContribState; t: TranslationFn }) {
* way to take everything back. Turning it on for the first time opens the same
* prompt an admin gets on the first visit, so an agreement always comes from it.
*/
-export default function PlaceContribPanel() {
+export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean } = {}) {
const { t } = useTranslation();
const toast = useToast();
const contrib = usePlaceContrib();
@@ -70,6 +70,9 @@ export default function PlaceContribPanel() {
const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);
if (!state) return null;
+ // Standing alone (managed settings), a card that can only say "not available"
+ // because the operator switched sharing off is a dead end.
+ if (hideWhenSwitchedOff && state.ineligibleReason === 'env_off') return null;
const status = contribStatus(state);
const agreed = state.consent.decision === 'agreed' && state.consent.termsVersion === state.termsVersion;
// The prompt opens by itself once per visit while the server asks for it.
diff --git a/client/src/components/Admin/addons/useAddonManager.ts b/client/src/components/Admin/addons/useAddonManager.ts
index b2080ac4b..0bdf72307 100644
--- a/client/src/components/Admin/addons/useAddonManager.ts
+++ b/client/src/components/Admin/addons/useAddonManager.ts
@@ -7,6 +7,7 @@ import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../.
import { wandererAdminApi } from '../../../api/wanderer';
import { useTranslation } from '../../../i18n';
import { useAddonStore } from '../../../store/addonStore';
+import { useAuthStore } from '../../../store/authStore';
import { useToast } from '../../shared/Toast';
import { type Addon, type ProviderOption, isPhotosAddon } from './addonModel';
import { aiAddonsOf, isAiAddon } from './aiAddons';
@@ -36,6 +37,9 @@ export function useAddonManager() {
const [addons, setAddons] = useState<Addon[]>([]);
const [loading, setLoading] = useState(true);
const [toursWanderer, setToursWanderer] = useState(false);
+ // wanderer sends a user's searches to a server of their choosing, which a
+ // managed install's terms do not cover; the operator decides, not the admin.
+ const wandererOffered = !useAuthStore((s) => s.managed);
const [toursHikingMap, setToursHikingMap] = useState(false);
const [toursCycleMap, setToursCycleMap] = useState(false);
const [toursSkiRouting, setToursSkiRouting] = useState(false);
@@ -160,6 +164,7 @@ export function useAddonManager() {
providerOptions,
documentProviderOptions,
toursWanderer,
+ wandererOffered,
toggleToursWanderer,
mapSwitches,
};
diff --git a/client/src/components/Admin/useDefaultUserSettings.ts b/client/src/components/Admin/useDefaultUserSettings.ts
index 25099ce50..2f0d33630 100644
--- a/client/src/components/Admin/useDefaultUserSettings.ts
+++ b/client/src/components/Admin/useDefaultUserSettings.ts
@@ -3,6 +3,7 @@ import { useEffect, useState } from 'react';
import { adminApi } from '../../api/client';
import { useTranslation } from '../../i18n';
import { useAuthStore } from '../../store/authStore';
+import { useSettingsStore } from '../../store/settingsStore';
import type { DistanceUnit, Place, WeekStart } from '../../types';
import { normalizeTileUrl } from '../../utils/tileUrl';
import {
@@ -11,7 +12,13 @@ import {
normalizeStyleForProvider,
styleSettingKey,
} from '../Map/glProviders';
-import { type MapProvider, normalizeProvider, styleForProvider } from '../Settings/mapSettingsModel';
+import {
+ type MapProvider,
+ mapboxOffered,
+ mapPresetsFor,
+ normalizeProvider,
+ styleForProvider,
+} from '../Settings/mapSettingsModel';
import { useToast } from '../shared/Toast';
import type { RoutingDefaults } from './RoutingInstanceFields';
@@ -53,6 +60,9 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
const [loaded, setLoaded] = useState(false);
const [mapTileUrl, setMapTileUrl] = useState('');
const managed = useAuthStore((s) => s.managed);
+ const hasAmapKey = useAuthStore((s) => s.hasAmapKey);
+ // The operator's token reaches the admin's own settings the same way it reaches everybody's.
+ const operatorMapboxToken = useSettingsStore((s) => s.settings.mapbox_access_token);
const [mapboxToken, setMapboxToken] = useState('');
const [cartoKey, setCartoKey] = useState('');
const [mapboxStyle, setMapboxStyle] = useState('');
@@ -153,6 +163,8 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
defaults,
loaded,
managed,
+ presets: mapPresetsFor(managed, hasAmapKey),
+ canMapbox: mapboxOffered(managed, operatorMapboxToken),
isSet,
save,
reset,
diff --git a/client/src/components/Help/HelpGuideView.tsx b/client/src/components/Help/HelpGuideView.tsx
index 152246648..e290a0a07 100644
--- a/client/src/components/Help/HelpGuideView.tsx
+++ b/client/src/components/Help/HelpGuideView.tsx
@@ -8,6 +8,7 @@ import type { HelpGuide } from '../../help/types'
import { helpIcon } from './helpIcons'
import HelpBadge from './HelpBadge'
import HelpDocLink from './HelpDocLink'
+import { useAuthStore } from '../../store/authStore'
import HelpSizeChip from './HelpSizeChip'
import { useScreenRoute } from './useScreenRoute'
@@ -27,6 +28,8 @@ export default function HelpGuideView({ guide }: { guide: HelpGuide }): React.Re
const openLightbox = useHelpStore(s => s.openLightbox)
const closeHelp = useHelpStore(s => s.closeHelp)
const docIndex = useHelpStore(s => s.docIndex)
+ // No Help & Docs page on a managed install (App.tsx), so no link into it.
+ const docs = useAuthStore(s => s.managed) ? undefined : guide.docs
const openGuide = useHelpStore(s => s.openGuide)
const title = t(guideKey(guide.id, 'title'))
const screen = getHelpContext(guide.context)
@@ -180,9 +183,9 @@ export default function HelpGuideView({ guide }: { guide: HelpGuide }): React.Re
)}
{/* Go there / docs / related */}
- {(guide.link || guide.docs || related.length > 0) && (
+ {(guide.link || docs || related.length > 0) && (
<section className="grid grid-cols-1 md:grid-cols-2 gap-3">
- {(guide.link || guide.docs) && (
+ {(guide.link || docs) && (
<div className="rounded-2xl border border-edge bg-surface-card p-4 flex flex-col gap-3">
<HelpBadge tone="neutral" icon={Link2} uppercase className="self-start">{t('help.center.docsSection')}</HelpBadge>
{guide.link && (
@@ -195,8 +198,8 @@ export default function HelpGuideView({ guide }: { guide: HelpGuide }): React.Re
<ArrowUpRight className="w-4 h-4" />
</Link>
)}
- {guide.docs && (
- <HelpDocLink to={docsRoute(guide.docs)} title={t('help.center.openDocs')} subtitle={docTitle(docIndex, guide.docs.slug)} />
+ {docs && (
+ <HelpDocLink to={docsRoute(docs)} title={t('help.center.openDocs')} subtitle={docTitle(docIndex, docs.slug)} />
)}
</div>
)}
diff --git a/client/src/components/Help/HelpHome.tsx b/client/src/components/Help/HelpHome.tsx
index 34f234127..c7e9a9987 100644
--- a/client/src/components/Help/HelpHome.tsx
+++ b/client/src/components/Help/HelpHome.tsx
@@ -8,6 +8,7 @@ import type { HelpContext, HelpDocLink as HelpDocTarget, HelpGuide } from '../..
import { helpIcon } from './helpIcons'
import HelpBadge from './HelpBadge'
import HelpDocLink from './HelpDocLink'
+import { useAuthStore } from '../../store/authStore'
import HelpSizeChip from './HelpSizeChip'
import { useScreenRoute } from './useScreenRoute'
@@ -19,6 +20,8 @@ import { useScreenRoute } from './useScreenRoute'
export default function HelpHome({ context }: { context: HelpContext | null }): React.ReactElement {
const { t } = useTranslation()
const docIndex = useHelpStore(s => s.docIndex)
+ // No Help & Docs page on a managed install (App.tsx), so no links into it.
+ const managed = useAuthStore(s => s.managed)
const closeHelp = useHelpStore(s => s.closeHelp)
const screenRoute = useScreenRoute(context?.route)
@@ -35,7 +38,7 @@ export default function HelpHome({ context }: { context: HelpContext | null }):
const guides = guidesFor(context)
const bullets = Array.from({ length: context.bullets }, (_, i) => t(ctxBulletKey(context.id, i + 1)))
const children = childHelpContexts(context.id)
- const docs = onePerPage(context.docs)
+ const docs = managed ? [] : onePerPage(context.docs)
const trail = helpContextTrail(context).slice(0, -1)
const Icon = helpIcon(context.icon)
diff --git a/client/src/components/Help/HelpSearchResults.tsx b/client/src/components/Help/HelpSearchResults.tsx
index 45815412e..2bf4661ae 100644
--- a/client/src/components/Help/HelpSearchResults.tsx
+++ b/client/src/components/Help/HelpSearchResults.tsx
@@ -6,6 +6,7 @@ import { allHelpGuides, guideKey, guideStepKey, guideTipKey, ctxKey } from '../.
import type { HelpGuide } from '../../help/types'
import { GuideCard, SectionLabel } from './HelpHome'
import HelpDocLink from './HelpDocLink'
+import { useAuthStore } from '../../store/authStore'
/** Guides shown for a query, at most. The docs list is capped by the server. */
const MAX_GUIDES = 8
@@ -62,6 +63,8 @@ export default function HelpSearchResults(): React.ReactElement {
const { t } = useTranslation()
const query = useHelpStore(s => s.query)
const status = useHelpStore(s => s.searchStatus)
+ // No Help & Docs page on a managed install (App.tsx): guides only.
+ const managed = useAuthStore(s => s.managed)
const docHits = useHelpStore(s => s.docHits)
const q = query.trim()
@@ -75,7 +78,7 @@ export default function HelpSearchResults(): React.ReactElement {
.map(x => x.g)
}, [q, t])
- const nothing = guides.length === 0 && status === 'done' && docHits.length === 0
+ const nothing = guides.length === 0 && (managed || (status === 'done' && docHits.length === 0))
return (
<div className="trek-help-view flex flex-col gap-8">
@@ -93,6 +96,7 @@ export default function HelpSearchResults(): React.ReactElement {
</section>
)}
+ {!managed && (
<section className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<SectionLabel>{t('help.center.searchDocs')}</SectionLabel>
@@ -113,6 +117,7 @@ export default function HelpSearchResults(): React.ReactElement {
</ul>
)}
</section>
+ )}
{nothing && (
<div className="flex flex-col items-center text-center gap-2 py-10">
diff --git a/client/src/components/Journey/JourneyDetailPageEntryEditor.test.tsx b/client/src/components/Journey/JourneyDetailPageEntryEditor.test.tsx
index c28463e14..443f07f56 100644
--- a/client/src/components/Journey/JourneyDetailPageEntryEditor.test.tsx
+++ b/client/src/components/Journey/JourneyDetailPageEntryEditor.test.tsx
@@ -8,6 +8,7 @@ import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpe
import { seedStore } from '../../../tests/helpers/store'
import { buildSettings } from '../../../tests/helpers/factories'
import { useSettingsStore } from '../../store/settingsStore'
+import { useAddonStore } from '../../store/addonStore'
import { server } from '../../../tests/helpers/msw/server'
import type { GalleryPhoto, JourneyEntry, JourneyPhoto, JourneyTrip } from '../../store/journeyStore'
import type { ResilientResult, UploadProgress } from '../../utils/uploadQueue'
@@ -102,6 +103,8 @@ beforeEach(() => {
// The time field reads time_format, so pin it: without this the cases that
// assert a 24h string depend on whichever test ran before them (#2067).
seedStore(useSettingsStore, { settings: buildSettings({ time_format: '24h' }) })
+ // A photo provider switched on for the install, so the External photos source is offered.
+ seedStore(useAddonStore, { addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', enabled: true } as never] })
window.__addToast = toastSpy
Object.defineProperty(URL, 'createObjectURL', {
configurable: true, writable: true, value: vi.fn(() => 'blob:preview'),
@@ -430,6 +433,14 @@ describe('EntryEditor', () => {
expect(screen.getByText('Roma Termini')).toBeInTheDocument()
})
+ it('FE-JRN-EDITOR-018b: offers no External photos source where no photo provider is on', () => {
+ seedStore(useAddonStore, { addons: [] })
+ mountEditor(buildEntry({ id: 10 }))
+
+ expect(screen.queryByRole('button', { name: 'External photos' })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /Upload photos/ })).toBeInTheDocument()
+ })
+
it('FE-JRN-EDITOR-019: reports that no external provider is connected', async () => {
server.use(http.get('/api/addons', () => HttpResponse.json({})))
const user = userEvent.setup()
diff --git a/client/src/components/Journey/JourneyDetailPageEntryEditor.tsx b/client/src/components/Journey/JourneyDetailPageEntryEditor.tsx
index a7a54f720..760d8cc03 100644
--- a/client/src/components/Journey/JourneyDetailPageEntryEditor.tsx
+++ b/client/src/components/Journey/JourneyDetailPageEntryEditor.tsx
@@ -17,6 +17,7 @@ import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, D
import { AddRowButton, EditorField, INPUT } from '../shared/dialogParts'
import { Tooltip } from '../shared/Tooltip'
import { useJourneyEntryForm, type PendingProviderGroup } from './useJourneyEntryForm'
+import { useAddonStore } from '../../store/addonStore'
/** A chip of the mood and weather rows, as in the collection dialogs' category row. */
const CHIP = 'inline-flex items-center gap-1.5 rounded-full border px-3 py-1 font-semibold transition-colors'
@@ -139,6 +140,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
onDone: () => void
}) {
const { t } = useTranslation()
+ const photoProvidersOn = useAddonStore(s => s.isEnabled('memories'))
const {
title, setTitle, story, setStory, entryDate, setEntryDate, entryTime, setEntryTime,
locationName,
@@ -273,14 +275,19 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
<Camera size={14} />
</button>
</Tooltip>
- <button type="button"
- onClick={() => { setPhotoTab('external'); setShowGalleryPick(false) }}
- disabled={saving}
- aria-pressed={photoTab === 'external'}
- className={`${SOURCE} flex-1 ${photoTab === 'external' ? SOURCE_ON : SOURCE_OFF}`}
- >
- <Image size={13} /> {t('journey.editor.externalPhotos') || 'External photos'}
- </button>
+ {/* Only where the install has a photo provider (Immich, Synology) switched
+ on, as on the phone: a source that can only say "nothing connected"
+ is not worth its width, and the other two share the row instead. */}
+ {photoProvidersOn && (
+ <button type="button"
+ onClick={() => { setPhotoTab('external'); setShowGalleryPick(false) }}
+ disabled={saving}
+ aria-pressed={photoTab === 'external'}
+ className={`${SOURCE} flex-1 ${photoTab === 'external' ? SOURCE_ON : SOURCE_OFF}`}
+ >
+ <Image size={13} /> {t('journey.editor.externalPhotos') || 'External photos'}
+ </button>
+ )}
</div>
{/* The gallery picker, directly below the buttons. Safari collapses
@@ -312,7 +319,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, trips,
</div>
</div>
)}
- {photoTab === 'external' && (
+ {photoTab === 'external' && photoProvidersOn && (
<div className={`${PHOTO_PANEL} flex flex-col overflow-hidden`} style={{ height: 'min(56vh, 520px)' }}>
<div className="flex items-center justify-between gap-2 border-b border-edge-faint px-3 py-2">
<div className="min-w-0">
diff --git a/client/src/components/Layout/Navbar.test.tsx b/client/src/components/Layout/Navbar.test.tsx
index 93c09c2c7..4557bfdb2 100644
--- a/client/src/components/Layout/Navbar.test.tsx
+++ b/client/src/components/Layout/Navbar.test.tsx
@@ -87,6 +87,16 @@ describe('Navbar', () => {
expect(screen.getByText('Admin')).toBeInTheDocument();
});
+ it('FE-COMP-NAVBAR-009b: a managed install keeps the help center but has no Help & Docs entry', async () => {
+ const user = userEvent.setup();
+ seedStore(useAuthStore, { user: buildUser({ username: 'testuser' }), isAuthenticated: true, managed: true });
+ render(<Navbar />);
+ expect(document.querySelector('[data-help-button]')).not.toBeNull();
+ await user.click(screen.getByText('testuser'));
+ expect(screen.queryByText('Help')).not.toBeInTheDocument();
+ expect(screen.getByText('Settings')).toBeInTheDocument();
+ });
+
it('FE-COMP-NAVBAR-010: regular user does not see Admin option', async () => {
const user = userEvent.setup();
render(<Navbar />);
diff --git a/client/src/components/Layout/Navbar.tsx b/client/src/components/Layout/Navbar.tsx
index d74cf6c12..69781dce2 100644
--- a/client/src/components/Layout/Navbar.tsx
+++ b/client/src/components/Layout/Navbar.tsx
@@ -35,7 +35,7 @@ interface Addon {
}
export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings }: NavbarProps): React.ReactElement {
- const { user, logout, isPrerelease, appVersion } = useAuthStore()
+ const { user, logout, isPrerelease, appVersion, managed } = useAuthStore()
const { settings, updateSetting } = useSettingsStore()
const { addons: allAddons, loadAddons } = useAddonStore()
const { t, locale } = useTranslation()
@@ -326,6 +326,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
{t('nav.settings')}
</Link>
+ {!managed && (
<Link to="/help" onClick={() => setUserMenuOpen(false)}
className="flex items-center gap-2 px-4 py-2 text-sm transition-colors text-content-secondary"
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
@@ -333,6 +334,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
<BookOpen className="w-4 h-4" />
{t('nav.help')}
</Link>
+ )}
{user.role === 'admin' && (
<Link to="/admin" onClick={() => setUserMenuOpen(false)}
diff --git a/client/src/components/Settings/MapSettingsTab.test.tsx b/client/src/components/Settings/MapSettingsTab.test.tsx
index 31c8fb055..fe8a43446 100644
--- a/client/src/components/Settings/MapSettingsTab.test.tsx
+++ b/client/src/components/Settings/MapSettingsTab.test.tsx
@@ -386,6 +386,27 @@ describe('MapSettingsTab – CARTO key', () => {
expect(screen.queryByText('CARTO API key')).not.toBeInTheDocument();
});
+ it('FE-COMP-MAP-032b: a managed instance without an operator token offers no Mapbox and no Amap tiles', async () => {
+ const user = userEvent.setup();
+ seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true, managed: true, hasAmapKey: false });
+ seedStore(useSettingsStore, { settings: buildSettings({ map_provider: 'leaflet', mapbox_access_token: '', map_tile_url: '' }) });
+ render(<MapSettingsTab />);
+
+ expect(screen.queryByText('Mapbox GL')).not.toBeInTheDocument();
+ expect(screen.getByText('MapLibre GL')).toBeInTheDocument();
+ await user.click(screen.getByText('Select template...'));
+ expect(screen.queryByText('高德地图 (Amap)')).not.toBeInTheDocument();
+ expect(screen.getByText('OpenStreetMap')).toBeInTheDocument();
+ });
+
+ it('FE-COMP-MAP-032c: the operator token brings Mapbox back on a managed instance', () => {
+ seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true, managed: true });
+ seedStore(useSettingsStore, { settings: buildSettings({ map_provider: 'leaflet', mapbox_access_token: 'pk.operator' }) });
+ render(<MapSettingsTab />);
+
+ expect(screen.getByText('Mapbox GL')).toBeInTheDocument();
+ });
+
it('FE-COMP-MAP-033: the typed key is part of the save patch', async () => {
const user = userEvent.setup();
const updateSettings = vi.fn().mockResolvedValue(undefined);
diff --git a/client/src/components/Settings/MapSettingsTab.tsx b/client/src/components/Settings/MapSettingsTab.tsx
index ad688a66b..63304042c 100644
--- a/client/src/components/Settings/MapSettingsTab.tsx
+++ b/client/src/components/Settings/MapSettingsTab.tsx
@@ -15,7 +15,7 @@ import ToggleSwitch from './ToggleSwitch'
import { SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill } from './settingsKit'
import { withTileApiKey } from '../../utils/tileUrl'
import { defaultStyleForProvider, getStylePresets, type GlMapProvider } from '../Map/glProviders'
-import { MAP_PRESETS, PREVIEW_CENTER, PREVIEW_ZOOM } from './mapSettingsModel'
+import { PREVIEW_CENTER, PREVIEW_ZOOM } from './mapSettingsModel'
import { useMapSettingsForm } from './useMapSettingsForm'
/** A field holding a URL, token or key: the box look in Geist, so the characters read apart. */
@@ -130,7 +130,7 @@ function ProviderTile({ active, onClick, icon: Icon, name, subtitle, badge }: {
export default function MapSettingsTab(): React.ReactElement {
const { t } = useTranslation()
const {
- managed, saving, provider, changeProvider, mapTileUrl, setMapTileUrl, mapboxToken, setMapboxToken,
+ managed, presets, canMapbox, saving, provider, changeProvider, mapTileUrl, setMapTileUrl, mapboxToken, setMapboxToken,
cartoKey, setCartoKey, cartoNeedsKey, mapboxStyle, setMapboxStyle, mapbox3d, setMapbox3d,
mapboxQuality, setMapboxQuality, previewPlaces, glPreview, webgl2Missing, save: saveMapSettings,
} = useMapSettingsForm()
@@ -149,7 +149,7 @@ export default function MapSettingsTab(): React.ReactElement {
{/* Provider picker — big tiles so the choice is obvious */}
<SettingRows>
<SettingRow label={t('settings.mapProvider')} hint={t('settings.mapProviderHint')} stacked>
- <div className="grid grid-cols-1 gap-2 sm:grid-cols-3">
+ <div className={`grid grid-cols-1 gap-2 ${canMapbox ? 'sm:grid-cols-3' : 'sm:grid-cols-2'}`}>
<ProviderTile
active={provider === 'leaflet'}
onClick={() => changeProvider('leaflet')}
@@ -157,15 +157,17 @@ export default function MapSettingsTab(): React.ReactElement {
name="Leaflet"
subtitle={t('settings.mapLeafletSubtitle')}
/>
- <ProviderTile
- active={provider === 'mapbox-gl'}
- onClick={() => changeProvider('mapbox-gl')}
- icon={Box}
- name={<><span className="sm:hidden">Mapbox</span><span className="hidden sm:inline">Mapbox GL</span></>}
- subtitle={t('settings.mapMapboxSubtitle')}
- // Only on ≥sm; on a narrow window there's no room next to the title.
- badge={<span className="hidden sm:inline-flex"><StatusPill tone="warning">{t('settings.mapExperimental')}</StatusPill></span>}
- />
+ {canMapbox && (
+ <ProviderTile
+ active={provider === 'mapbox-gl'}
+ onClick={() => changeProvider('mapbox-gl')}
+ icon={Box}
+ name={<><span className="sm:hidden">Mapbox</span><span className="hidden sm:inline">Mapbox GL</span></>}
+ subtitle={t('settings.mapMapboxSubtitle')}
+ // Only on ≥sm; on a narrow window there's no room next to the title.
+ badge={<span className="hidden sm:inline-flex"><StatusPill tone="warning">{t('settings.mapExperimental')}</StatusPill></span>}
+ />
+ )}
<ProviderTile
active={provider === 'maplibre-gl'}
onClick={() => changeProvider('maplibre-gl')}
@@ -185,7 +187,7 @@ export default function MapSettingsTab(): React.ReactElement {
value={mapTileUrl}
onChange={(value: string) => { if (value) setMapTileUrl(value) }}
placeholder={t('settings.mapTemplatePlaceholder.select')}
- options={MAP_PRESETS.map(p => ({ value: p.url, label: p.name }))}
+ options={presets.map(p => ({ value: p.url, label: p.name }))}
/>
<input
id={`${fieldId}-tile`}
diff --git a/client/src/components/Settings/mapSettingsModel.test.ts b/client/src/components/Settings/mapSettingsModel.test.ts
new file mode 100644
index 000000000..3183e97d7
--- /dev/null
+++ b/client/src/components/Settings/mapSettingsModel.test.ts
@@ -0,0 +1,33 @@
+// FE-MAP-MODEL-001 to FE-MAP-MODEL-004
+import { describe, expect, it } from 'vitest';
+import { AMAP_ROAD, AMAP_SATELLITE } from '../../constants/mapDefaults';
+import { MAP_PRESETS, mapboxOffered, mapPresetsFor } from './mapSettingsModel';
+
+const urls = (list: { url: string }[]) => list.map((p) => p.url);
+
+describe('mapPresetsFor', () => {
+ it('FE-MAP-MODEL-001: a self-hosted install offers every preset, Amap included', () => {
+ expect(mapPresetsFor(false, false)).toEqual(MAP_PRESETS);
+ });
+
+ it('FE-MAP-MODEL-002: a managed install offers Amap only where the operator set it up', () => {
+ const without = urls(mapPresetsFor(true, false));
+ expect(without).not.toContain(AMAP_ROAD);
+ expect(without).not.toContain(AMAP_SATELLITE);
+ expect(without).toHaveLength(MAP_PRESETS.length - 2);
+ expect(mapPresetsFor(true, true)).toEqual(MAP_PRESETS);
+ });
+});
+
+describe('mapboxOffered', () => {
+ it('FE-MAP-MODEL-003: a self-hosted install always offers Mapbox, the token field follows', () => {
+ expect(mapboxOffered(false, null)).toBe(true);
+ expect(mapboxOffered(false, '')).toBe(true);
+ });
+
+ it('FE-MAP-MODEL-004: a managed install offers Mapbox only with the operator token', () => {
+ expect(mapboxOffered(true, undefined)).toBe(false);
+ expect(mapboxOffered(true, '')).toBe(false);
+ expect(mapboxOffered(true, 'pk.operator')).toBe(true);
+ });
+});
diff --git a/client/src/components/Settings/mapSettingsModel.ts b/client/src/components/Settings/mapSettingsModel.ts
index b75cf2a43..74cfb1053 100644
--- a/client/src/components/Settings/mapSettingsModel.ts
+++ b/client/src/components/Settings/mapSettingsModel.ts
@@ -41,6 +41,26 @@ export const MAP_PRESETS: MapPreset[] = [
{ name: '高德卫星 (Amap Satellite)', url: AMAP_SATELLITE },
];
+/**
+ * The presets this install offers. On a managed install Amap is the operator's
+ * service like every other keyed one: its tiles are offered only where the
+ * operator set Amap up (has_amap_key), so a hosted user is never pointed at a
+ * provider the instance does not use.
+ */
+export function mapPresetsFor(managed: boolean, hasAmapKey: boolean): MapPreset[] {
+ if (!managed || hasAmapKey) return MAP_PRESETS;
+ return MAP_PRESETS.filter((p) => p.url !== AMAP_ROAD && p.url !== AMAP_SATELLITE);
+}
+
+/**
+ * Whether Mapbox GL can be picked. A managed install brings the token with the
+ * instance and offers no field for one, so without an operator token the
+ * choice would only lead to a map that never loads.
+ */
+export function mapboxOffered(managed: boolean, token: string | null | undefined): boolean {
+ return !managed || !!token;
+}
+
export type MapProvider = 'leaflet' | GlMapProvider;
export function normalizeProvider(value: unknown): MapProvider {
diff --git a/client/src/components/Settings/useMapSettingsForm.ts b/client/src/components/Settings/useMapSettingsForm.ts
index 00a5877f1..0029d7c9d 100644
--- a/client/src/components/Settings/useMapSettingsForm.ts
+++ b/client/src/components/Settings/useMapSettingsForm.ts
@@ -7,7 +7,15 @@ import type { Place } from '../../types';
import { normalizeStyleForProvider } from '../Map/glProviders';
import { useWebGL2 } from '../Map/glSupport';
import { useToast } from '../shared/Toast';
-import { type MapProvider, normalizeProvider, previewPlace, slotStyle, styleForProvider } from './mapSettingsModel';
+import {
+ type MapProvider,
+ mapboxOffered,
+ mapPresetsFor,
+ normalizeProvider,
+ previewPlace,
+ slotStyle,
+ styleForProvider,
+} from './mapSettingsModel';
export interface MapSettingsFormOptions {
/**
@@ -32,6 +40,7 @@ export function useMapSettingsForm({ mirrorStyleBeforeSave = false }: MapSetting
const [provider, setProvider] = useState<MapProvider>(initialProvider);
const [mapTileUrl, setMapTileUrl] = useState<string>(settings.map_tile_url || '');
const managed = useAuthStore((s) => s.managed);
+ const hasAmapKey = useAuthStore((s) => s.hasAmapKey);
const [mapboxToken, setMapboxToken] = useState<string>(settings.mapbox_access_token || '');
const [cartoKey, setCartoKey] = useState<string>(settings.carto_api_key || '');
const [mapboxStyle, setMapboxStyle] = useState<string>(
@@ -94,6 +103,8 @@ export function useMapSettingsForm({ mirrorStyleBeforeSave = false }: MapSetting
return {
managed,
+ presets: mapPresetsFor(managed, hasAmapKey),
+ canMapbox: mapboxOffered(managed, settings.mapbox_access_token),
saving,
provider,
changeProvider,
diff --git a/client/src/help/registry.test.ts b/client/src/help/registry.test.ts
index 15917626d..552976ff5 100644
--- a/client/src/help/registry.test.ts
+++ b/client/src/help/registry.test.ts
@@ -232,3 +232,30 @@ describe('help registry: helpers', () => {
expect(docsRoute({ slug: 'Creating-a-Trip', anchor: 'fields' })).toBe('/help/Creating-a-Trip#fields')
})
})
+
+describe('help on a managed install', () => {
+ it('leaves out the guides and screens about what the operator runs', async () => {
+ const { useAuthStore } = await import('../store/authStore')
+ const { useAddonStore } = await import('../store/addonStore')
+ const reg = await import('./registry')
+ useAuthStore.setState({ managed: true })
+ try {
+ expect(reg.getHelpGuide('create-backup')).toBeNull()
+ expect(reg.getHelpGuide('instance-keys')).toBeNull()
+ expect(reg.getHelpContext('admin-backup')).toBeNull()
+ expect(reg.allHelpGuides().some(g => g.context === 'admin-storage')).toBe(false)
+ expect(reg.getHelpGuide('files-sync')).toBeNull()
+ // Integrations follow whether the instance has them on.
+ useAddonStore.setState({ addons: [] })
+ expect(reg.getHelpGuide('connect-dawarich')).toBeNull()
+ useAddonStore.setState({ addons: [{ id: 'dawarich', enabled: true } as never] })
+ expect(reg.getHelpGuide('connect-dawarich')).not.toBeNull()
+ // What a hosted admin can still do keeps its guide.
+ expect(reg.getHelpGuide('create-user')).not.toBeNull()
+ } finally {
+ useAuthStore.setState({ managed: false })
+ useAddonStore.setState({ addons: [] })
+ }
+ expect(reg.getHelpGuide('create-backup')).not.toBeNull()
+ })
+})
diff --git a/client/src/help/registry.ts b/client/src/help/registry.ts
index 4b4c60899..30426177a 100644
--- a/client/src/help/registry.ts
+++ b/client/src/help/registry.ts
@@ -1,4 +1,6 @@
import type { HelpContext, HelpGuide } from './types'
+import { useAddonStore } from '../store/addonStore'
+import { useAuthStore } from '../store/authStore'
import { dashboardContext, dashboardGuides } from './contexts/dashboard'
import { vacayContext, vacayGuides } from './contexts/vacay'
import { atlasContext, atlasGuides } from './contexts/atlas'
@@ -74,36 +76,87 @@ const GUIDE_LIST: HelpGuide[] = [
export const HELP_CONTEXTS: ReadonlyMap<string, HelpContext> = new Map(CONTEXT_LIST.map(c => [c.id, c]))
export const HELP_GUIDES: ReadonlyMap<string, HelpGuide> = new Map(GUIDE_LIST.map(g => [g.id, g]))
+/**
+ * What a managed install leaves out: the admin screens it hides (AdminPage) and
+ * the guides about what the operator runs there, such as keys, OIDC, place
+ * search, routing, backups, storage, releases and plugins. A guide that walks
+ * somebody through a panel they cannot open is worse than none.
+ */
+const MANAGED_HIDDEN_CONTEXTS: ReadonlySet<string> = new Set([
+ 'admin-plugins', 'admin-storage', 'admin-github', 'admin-backup', 'settings-plugins',
+])
+const MANAGED_HIDDEN_GUIDES: ReadonlySet<string> = new Set([
+ 'oidc', 'instance-keys', 'places-transit', 'rotate-jwt-secret', 'own-routing-engine',
+ 'install-plugin', 'storage-backends', 'release-history', 'create-backup', 'auto-backup',
+ 'plugin-settings', 'files-sync', 'files-sync-settings', 'document-providers',
+])
+
+/**
+ * Guides about an integration, shown on a managed install only while it is on
+ * there: the operator decides which integrations the instance has, and a guide
+ * to connect one it does not offer leads nowhere.
+ */
+const addonOn = (id: string) => (): boolean => useAddonStore.getState().isEnabled(id)
+const MANAGED_FEATURE_GUIDES: Readonly<Record<string, () => boolean>> = {
+ 'connect-dawarich': addonOn('dawarich'),
+ 'dawarich-countries': addonOn('dawarich'),
+ 'dawarich-wishes': addonOn('dawarich'),
+ 'dawarich-stays': addonOn('dawarich'),
+ 'journey-day-stays': addonOn('dawarich'),
+ 'map-dawarich-trail': addonOn('dawarich'),
+ 'connect-airtrail': addonOn('airtrail'),
+ 'airtrail-import': addonOn('airtrail'),
+ 'photo-providers': addonOn('memories'),
+ 'mcp-oauth': addonOn('mcp'),
+ 'api-keys': addonOn('mcp'),
+ 'mcp-tokens-admin': addonOn('mcp'),
+ 'tour-connect-wanderer': () => useAddonStore.getState().toursWanderer,
+ 'tour-wanderer-watch': () => useAddonStore.getState().toursWanderer,
+ 'tour-import-wanderer': () => useAddonStore.getState().toursWanderer,
+}
+
+/** Read at call time: `managed` arrives with app-config, after the registry loaded. */
+const isManaged = (): boolean => useAuthStore.getState().managed
+const shownContext = (c: HelpContext): boolean => !(isManaged() && MANAGED_HIDDEN_CONTEXTS.has(c.id))
+const shownGuide = (g: HelpGuide): boolean => {
+ if (!isManaged()) return true
+ if (MANAGED_HIDDEN_GUIDES.has(g.id) || MANAGED_HIDDEN_CONTEXTS.has(g.context)) return false
+ const feature = MANAGED_FEATURE_GUIDES[g.id]
+ return feature ? feature() : true
+}
+
export function getHelpContext(id: string | null | undefined): HelpContext | null {
- return id ? (HELP_CONTEXTS.get(id) ?? null) : null
+ const context = id ? HELP_CONTEXTS.get(id) : undefined
+ return context && shownContext(context) ? context : null
}
export function getHelpGuide(id: string | null | undefined): HelpGuide | null {
- return id ? (HELP_GUIDES.get(id) ?? null) : null
+ const guide = id ? HELP_GUIDES.get(id) : undefined
+ return guide && shownGuide(guide) ? guide : null
}
/** The guides of a context, in the order the context lists them. */
export function guidesFor(context: HelpContext): HelpGuide[] {
- return context.guides.map(id => HELP_GUIDES.get(id)).filter((g): g is HelpGuide => g !== undefined)
+ return context.guides.map(id => HELP_GUIDES.get(id)).filter((g): g is HelpGuide => g !== undefined && shownGuide(g))
}
export function allHelpGuides(): HelpGuide[] {
- return GUIDE_LIST
+ return isManaged() ? GUIDE_LIST.filter(shownGuide) : GUIDE_LIST
}
/** Every screen that has help, in registration order, for the screen switcher. */
export function allHelpContexts(): HelpContext[] {
- return CONTEXT_LIST
+ return isManaged() ? CONTEXT_LIST.filter(shownContext) : CONTEXT_LIST
}
/** The screens that stand on their own; their sub-screens hang under them in the switcher. */
export function topLevelHelpContexts(): HelpContext[] {
- return CONTEXT_LIST.filter(c => !c.parent)
+ return CONTEXT_LIST.filter(c => !c.parent && shownContext(c))
}
/** The sub-screens of a screen, in registration order. */
export function childHelpContexts(parentId: string): HelpContext[] {
- return CONTEXT_LIST.filter(c => c.parent === parentId)
+ return CONTEXT_LIST.filter(c => c.parent === parentId && shownContext(c))
}
/** The screen and the screens above it, outermost first, for a breadcrumb. */
diff --git a/client/src/mobile/screens/admin/MAdmin.tsx b/client/src/mobile/screens/admin/MAdmin.tsx
index c04f3c13d..309a1a7b2 100644
--- a/client/src/mobile/screens/admin/MAdmin.tsx
+++ b/client/src/mobile/screens/admin/MAdmin.tsx
@@ -88,7 +88,7 @@ export default function MAdmin() {
{ id: 'config', label: t('admin.tabs.config'), icon: SlidersHorizontal },
{ id: 'settings', label: t('admin.tabs.settings'), icon: SettingsIcon },
{ id: 'addons', label: t('admin.tabs.addons'), icon: Blocks },
- { id: 'plugins', label: t('admin.tabs.plugins'), icon: Puzzle },
+ ...(managed ? [] : [{ id: 'plugins', label: t('admin.tabs.plugins'), icon: Puzzle }]),
...(managed ? [] : [{ id: 'storage', label: t('admin.tabs.storage'), icon: HardDrive }]),
{ id: 'notifications', label: t('admin.tabs.notifications'), icon: Bell },
...(mcpEnabled ? [{ id: 'mcp-tokens', label: t('admin.tabs.mcpTokens'), icon: Plug }] : []),
diff --git a/client/src/mobile/screens/admin/MAdminAddonManager.tsx b/client/src/mobile/screens/admin/MAdminAddonManager.tsx
index 74f224e5e..0f498bbcc 100644
--- a/client/src/mobile/screens/admin/MAdminAddonManager.tsx
+++ b/client/src/mobile/screens/admin/MAdminAddonManager.tsx
@@ -63,6 +63,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
const {
addons, loading, handleToggle, tripAddons, globalAddons, integrationAddons, aiAddons, providerOptions, documentProviderOptions,
toursWanderer,
+ wandererOffered,
toggleToursWanderer,
mapSwitches,
} = useAddonManager()
@@ -115,13 +116,15 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
{addon.id === 'documents' && addon.enabled && <MProviderShelf options={documentProviderOptions} />}
{addon.id === 'tours' && addon.enabled && (
<>
- <MSubRow
- providerIcon={WandererMark}
- title={t('admin.toursWanderer.title')}
- subtitle={t('admin.toursWanderer.subtitle')}
- enabled={toursWanderer}
- onToggle={() => void toggleToursWanderer()}
- />
+ {wandererOffered && (
+ <MSubRow
+ providerIcon={WandererMark}
+ title={t('admin.toursWanderer.title')}
+ subtitle={t('admin.toursWanderer.subtitle')}
+ enabled={toursWanderer}
+ onToggle={() => void toggleToursWanderer()}
+ />
+ )}
{mapSwitches.map(({ key, Icon, titleKey, subtitleKey, enabled, toggle }) => (
<MSubRow
key={key}
diff --git a/client/src/mobile/screens/admin/MAdminDefaultUserSettings.tsx b/client/src/mobile/screens/admin/MAdminDefaultUserSettings.tsx
index 0bd99367f..0eb021be0 100644
--- a/client/src/mobile/screens/admin/MAdminDefaultUserSettings.tsx
+++ b/client/src/mobile/screens/admin/MAdminDefaultUserSettings.tsx
@@ -7,7 +7,7 @@ import { getApiErrorMessage, type DistanceUnit, type WeekStart } from '../../../
import { weekStartOptions } from '../../../utils/calendarWeek'
import { withTileApiKey } from '../../../utils/tileUrl'
import { defaultStyleForProvider } from '../../../components/Map/glProviders'
-import { MAP_PRESETS, type MapProvider } from '../../../components/Settings/mapSettingsModel'
+import type { MapProvider } from '../../../components/Settings/mapSettingsModel'
import { useDefaultUserSettings, type Defaults } from '../../../components/Admin/useDefaultUserSettings'
import MToggle from '../../components/MToggle'
import MSegmented from '../../components/MSegmented'
@@ -22,7 +22,7 @@ import RoutingInstanceFields from '../../../components/Admin/RoutingInstanceFiel
export default function MAdminDefaultUserSettings(): React.ReactElement {
const { t, locale } = useTranslation()
const {
- defaults, loaded, managed, isSet, save, reset, mapTileUrl, setMapTileUrl, mapboxToken, setMapboxToken,
+ defaults, loaded, managed, presets, canMapbox, isSet, save, reset, mapTileUrl, setMapTileUrl, mapboxToken, setMapboxToken,
cartoKey, setCartoKey, mapboxStyle, setMapboxStyle, mapPreviewPlaces, mapProvider, glStylePresets, styleKey,
saveMapProvider, pickTilePreset, pickStylePreset, commitStyle,
} = useDefaultUserSettings({ errorMessage: getApiErrorMessage, previewCreatedAt: () => new Date().toISOString() })
@@ -80,14 +80,14 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
]
const providerOptions: { value: string; label: React.ReactNode }[] = [
{ value: 'leaflet', label: t('admin.defaultSettings.providerLeaflet') },
- { value: 'mapbox-gl', label: t('admin.defaultSettings.providerMapbox') },
+ ...(canMapbox ? [{ value: 'mapbox-gl' as const, label: t('admin.defaultSettings.providerMapbox') }] : []),
{ value: 'maplibre-gl', label: t('admin.defaultSettings.providerMapLibre') },
]
const currencyLabel = defaults.default_currency
? (SYMBOLS[defaults.default_currency] ? `${defaults.default_currency} ${SYMBOLS[defaults.default_currency]}` : defaults.default_currency)
: t('settings.currency')
- const tilePresetLabel = MAP_PRESETS.find((p) => p.url === mapTileUrl)?.name || t('settings.mapTemplatePlaceholder.select')
+ const tilePresetLabel = presets.find((p) => p.url === mapTileUrl)?.name || t('settings.mapTemplatePlaceholder.select')
const stylePresetLabel = glStylePresets.find((p) => p.url === mapboxStyle)?.name || t('admin.defaultSettings.mapboxStylePlaceholder')
const chevron = <ChevronDown size={13} strokeWidth={2} className="flex-none text-m-faint" />
@@ -302,7 +302,7 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
title={t('settings.mapTemplate')}
value={mapTileUrl}
onSelect={pickTilePreset}
- options={MAP_PRESETS.map((p) => ({ value: p.url, label: p.name }))}
+ options={presets.map((p) => ({ value: p.url, label: p.name }))}
/>
<MSetPickerSheet
diff --git a/client/src/mobile/screens/admin/MAdminSettingsSection.tsx b/client/src/mobile/screens/admin/MAdminSettingsSection.tsx
index 1a8858f42..ba835e4de 100644
--- a/client/src/mobile/screens/admin/MAdminSettingsSection.tsx
+++ b/client/src/mobile/screens/admin/MAdminSettingsSection.tsx
@@ -134,6 +134,9 @@ export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectio
{t('admin.passkey.notConfigured')}
</p>
)}
+ {/* The relying party is the instance's address, which the operator owns on a
+ managed install (server managed.ts), same as the desktop tab. */}
+ {!managed && (
<div className="space-y-3">
<MAdminField label={t('admin.passkey.rpId')} hint={t('admin.passkey.rpIdHint')}>
<MAdminInput
@@ -155,6 +158,7 @@ export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectio
{t('common.save')}
</MAdminButton>
</div>
+ )}
</MAdminCard>
{/* Require 2FA */}
@@ -187,7 +191,9 @@ export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectio
</div>
</MAdminCard>
- {/* API keys */}
+ {/* API keys, place search and routing: the operator's on a managed install,
+ same as the desktop tab. Share place details has its own section there. */}
+ {!managed && (
<MAdminCard>
<MAdminCardHead title={t('admin.apiKeys')} hint={t('admin.apiKeysHint')} />
<div className="space-y-3">
@@ -379,8 +385,10 @@ export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectio
)}
</div>
</MAdminCard>
+ )}
- {/* OIDC / SSO */}
+ {/* OIDC / SSO: the operator's on a managed install, as on the desktop tab. */}
+ {!managed && (
<MAdminCard>
<MAdminCardHead title={t('admin.oidcTitle')} hint={t('admin.oidcSubtitle')} />
<div className="space-y-3">
@@ -428,6 +436,7 @@ export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectio
</MAdminButton>
</div>
</MAdminCard>
+ )}
{/* Danger zone */}
<MAdminCard className="border-[color:color-mix(in_srgb,var(--m-st-danger)_28%,transparent)]">
diff --git a/client/src/mobile/screens/settings/MSettings.tsx b/client/src/mobile/screens/settings/MSettings.tsx
index a2c396802..9c92075d1 100644
--- a/client/src/mobile/screens/settings/MSettings.tsx
+++ b/client/src/mobile/screens/settings/MSettings.tsx
@@ -51,7 +51,7 @@ export default function MSettings() {
{ id: 'map', label: t('settings.tabs.map'), icon: Map },
{ id: 'notifications', label: t('settings.tabs.notifications'), icon: Bell },
...(hasIntegrations ? [{ id: 'integrations', label: t('settings.tabs.integrations'), icon: Plug }] : []),
- ...(hasPlugins ? [{ id: 'plugins', label: t('settings.tabs.plugins'), icon: Puzzle }] : []),
+ ...(hasPlugins && !managed ? [{ id: 'plugins', label: t('settings.tabs.plugins'), icon: Puzzle }] : []),
{ id: 'offline', label: t('settings.tabs.offline'), icon: CloudOff },
{ id: 'account', label: t('settings.tabs.account'), icon: User },
// Same call as the desktop page: About is about the project — what TREK is,
@@ -116,7 +116,7 @@ export default function MSettings() {
{active.id === 'notifications' && <MSettingsNotifications />}
{active.id === 'integrations' && hasIntegrations && <MSettingsIntegrations />}
{/* Per-plugin settings still reuse the existing responsive tab. */}
- {active.id === 'plugins' && hasPlugins && <MSettingsPlugins />}
+ {active.id === 'plugins' && hasPlugins && !managed && <MSettingsPlugins />}
{active.id === 'offline' && <MSettingsOffline />}
{active.id === 'account' && <MSettingsAccount />}
{active.id === 'about' && appVersion && <MSettingsAbout appVersion={appVersion} />}
diff --git a/client/src/mobile/screens/settings/MSettingsMap.tsx b/client/src/mobile/screens/settings/MSettingsMap.tsx
index bee77fad4..aebd12e8e 100644
--- a/client/src/mobile/screens/settings/MSettingsMap.tsx
+++ b/client/src/mobile/screens/settings/MSettingsMap.tsx
@@ -6,7 +6,7 @@ import { MapView } from '../../../components/Map/MapView'
import ErrorBoundary from '../../../components/shared/ErrorBoundary'
import { GlMapPreviewMapbox, GlMapPreviewMaplibre } from '../../../components/Map/glLazy'
import { defaultStyleForProvider, getStylePresets } from '../../../components/Map/glProviders'
-import { MAP_PRESETS, PREVIEW_CENTER, PREVIEW_ZOOM, type MapProvider } from '../../../components/Settings/mapSettingsModel'
+import { PREVIEW_CENTER, PREVIEW_ZOOM, type MapProvider } from '../../../components/Settings/mapSettingsModel'
import { useMapSettingsForm } from '../../../components/Settings/useMapSettingsForm'
import { withTileApiKey } from '../../../utils/tileUrl'
import MToggle from '../../components/MToggle'
@@ -20,7 +20,7 @@ import MSetPickerSheet from './MSetPickerSheet'
export default function MSettingsMap() {
const { t } = useTranslation()
const {
- managed, saving, provider, changeProvider, mapTileUrl, setMapTileUrl, mapboxToken, setMapboxToken,
+ managed, presets: tilePresets, canMapbox, saving, provider, changeProvider, mapTileUrl, setMapTileUrl, mapboxToken, setMapboxToken,
cartoKey, setCartoKey, cartoNeedsKey, mapboxStyle, setMapboxStyle, mapbox3d, setMapbox3d,
mapboxQuality, setMapboxQuality, previewPlaces, glPreview, webgl2Missing, save,
} = useMapSettingsForm({ mirrorStyleBeforeSave: true })
@@ -29,7 +29,7 @@ export default function MSettingsMap() {
const providers: { id: MapProvider; name: string; sub: string; icon: typeof Layers }[] = [
{ id: 'leaflet', name: 'Leaflet', sub: t('settings.mapLeafletSubtitle'), icon: Layers },
- { id: 'mapbox-gl', name: 'Mapbox GL', sub: t('settings.mapMapboxSubtitle'), icon: Box },
+ ...(canMapbox ? [{ id: 'mapbox-gl' as const, name: 'Mapbox GL', sub: t('settings.mapMapboxSubtitle'), icon: Box }] : []),
{ id: 'maplibre-gl', name: 'MapLibre GL', sub: t('settings.mapMapLibreSubtitle'), icon: Globe2 },
]
@@ -73,7 +73,7 @@ export default function MSettingsMap() {
<>
<MSetEyebrow className="mb-[5px] mt-[14px]">{t('settings.mapTemplate')}</MSetEyebrow>
<MSetSelectRow
- label={MAP_PRESETS.find((p) => p.url === mapTileUrl)?.name || t('settings.mapTemplatePlaceholder.select')}
+ label={tilePresets.find((p) => p.url === mapTileUrl)?.name || t('settings.mapTemplatePlaceholder.select')}
trailing={chevron}
onClick={() => setPresetOpen(true)}
/>
@@ -221,7 +221,7 @@ export default function MSettingsMap() {
title={t('settings.mapTemplate')}
value={mapTileUrl}
onSelect={setMapTileUrl}
- options={MAP_PRESETS.map((p) => ({ value: p.url, label: p.name }))}
+ options={tilePresets.map((p) => ({ value: p.url, label: p.name }))}
/>
<MSetPickerSheet
diff --git a/client/src/pages/AdminPage.test.tsx b/client/src/pages/AdminPage.test.tsx
index e19de8aa7..dc04fa8ff 100644
--- a/client/src/pages/AdminPage.test.tsx
+++ b/client/src/pages/AdminPage.test.tsx
@@ -1837,4 +1837,12 @@ describe('AdminPage', () => {
await screen.findByRole('button', { name: /^users$/i });
expect(screen.queryByRole('button', { name: /^storage$/i })).not.toBeInTheDocument();
});
+
+ it('FE-PAGE-ADMIN-STOR-003: managed mode hides the Plugins tab, and ?tab=plugins falls back to Users', async () => {
+ seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), managed: true });
+ render(<AdminPage />, { initialEntries: ['/admin?tab=plugins'] });
+ await screen.findByRole('button', { name: /^users$/i });
+ expect(screen.queryByRole('button', { name: /^plugins$/i })).not.toBeInTheDocument();
+ await waitFor(() => expect(screen.queryByRole('heading', { name: /plugins/i })).not.toBeInTheDocument());
+ });
});
diff --git a/client/src/pages/AdminPage.tsx b/client/src/pages/AdminPage.tsx
index 6857d38ab..f0e8125c9 100644
--- a/client/src/pages/AdminPage.tsx
+++ b/client/src/pages/AdminPage.tsx
@@ -60,7 +60,9 @@ function AdminPageDesktop(): React.ReactElement {
{ id: 'config', label: t('admin.tabs.config'), icon: SlidersHorizontal, group: gConfig },
{ id: 'settings', label: t('admin.tabs.settings'), icon: SettingsIcon, group: gConfig },
{ id: 'addons', label: t('admin.tabs.addons'), icon: Puzzle, group: gConfig },
- { id: 'plugins', label: t('admin.tabs.plugins'), icon: Blocks, group: gConfig },
+ // Plugins run third-party code that can send data anywhere; a hosted instance
+ // offers none, so there is nothing to manage here (TREK_PLUGINS_ENABLED is off).
+ ...(managed ? [] : [{ id: 'plugins', label: t('admin.tabs.plugins'), icon: Blocks, group: gConfig }]),
// Storage backends and their credentials are hoster-level configuration —
// the server refuses the whole surface in managed mode (MANAGED_FORBIDDEN).
...(managed ? [] : [{ id: 'storage', label: t('admin.tabs.storage'), icon: HardDrive, group: gConfig }]),
diff --git a/client/src/pages/JourneyDetailPage.test.tsx b/client/src/pages/JourneyDetailPage.test.tsx
index 3a203256a..ac89ba936 100644
--- a/client/src/pages/JourneyDetailPage.test.tsx
+++ b/client/src/pages/JourneyDetailPage.test.tsx
@@ -5,6 +5,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../tests/helpers/store';
+import { useAddonStore } from '../store/addonStore';
import { buildUser } from '../../tests/helpers/factories';
import { useAuthStore } from '../store/authStore';
import { usePermissionsStore } from '../store/permissionsStore';
@@ -240,6 +241,8 @@ beforeEach(() => {
useJourneyStore.setState(useJourneyStore.getState(), true);
seedStore(useAuthStore, { isAuthenticated: true, user: ownerUser });
seedStore(usePermissionsStore, { level: 'owner' } as any);
+ // A photo provider on for the install, so the entry editor offers External photos.
+ seedStore(useAddonStore, { addons: [{ id: 'immich', name: 'Immich', type: 'photo_provider', enabled: true } as never] });
setupDefaultHandlers();
});
diff --git a/client/src/pages/SettingsPage.tsx b/client/src/pages/SettingsPage.tsx
index 397aafc60..d3ff5632b 100644
--- a/client/src/pages/SettingsPage.tsx
+++ b/client/src/pages/SettingsPage.tsx
@@ -38,7 +38,7 @@ function SettingsPageDesktop(): React.ReactElement {
// Always there: API keys sit in this tab and need no addon. The addon backed
// sections inside it gate themselves.
{ id: 'integrations', label: t('settings.tabs.integrations'), icon: Plug },
- ...(hasPlugins
+ ...(hasPlugins && !managed
? [{ id: 'plugins', label: t('settings.tabs.plugins'), icon: Blocks }]
: []),
{ id: 'offline', label: t('settings.tabs.offline'), icon: CloudOff },
@@ -87,7 +87,7 @@ function SettingsPageDesktop(): React.ReactElement {
{activeTab === 'map' && <MapSettingsTab />}
{activeTab === 'notifications' && <NotificationsTab />}
{activeTab === 'integrations' && <IntegrationsTab />}
- {activeTab === 'plugins' && hasPlugins && <PluginSettingsTab />}
+ {activeTab === 'plugins' && hasPlugins && !managed && <PluginSettingsTab />}
{activeTab === 'offline' && <OfflineTab />}
{activeTab === 'account' && <AccountTab />}
{activeTab === 'about' && appVersion && <AboutTab appVersion={appVersion} />}
diff --git a/client/src/pages/admin/AdminNotificationsTab.tsx b/client/src/pages/admin/AdminNotificationsTab.tsx
index 0540763d4..08bdce19e 100644
--- a/client/src/pages/admin/AdminNotificationsTab.tsx
+++ b/client/src/pages/admin/AdminNotificationsTab.tsx
@@ -78,6 +78,21 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
</EditorField>
)
+ const tripRemindersCard = (
+ <SettingsCard
+ icon={CalendarClock}
+ title={t('admin.notifications.tripReminders.title')}
+ hint={t('admin.notifications.tripReminders.hint')}
+ action={
+ <ToggleSwitch
+ on={tripRemindersActive}
+ label={t('admin.notifications.tripReminders.title')}
+ onToggle={toggleTripReminders}
+ />
+ }
+ />
+ )
+
return (<>
{/* Two columns from xl up, the same shape as the Settings tab. Most of these
cards are a title with a switch on the far right, so on a wide screen the
@@ -168,19 +183,7 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
action={<LockedSwitch />}
/>
- {/* Trip Reminders Toggle */}
- <SettingsCard
- icon={CalendarClock}
- title={t('admin.notifications.tripReminders.title')}
- hint={t('admin.notifications.tripReminders.hint')}
- action={
- <ToggleSwitch
- on={tripRemindersActive}
- label={t('admin.notifications.tripReminders.title')}
- onToggle={toggleTripReminders}
- />
- }
- />
+ {!managed && tripRemindersCard}
</div>
<div className="min-w-0">
@@ -284,6 +287,9 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
over, so it belongs under the targets it routes to rather than across the
full width below both columns. */}
<AdminNotificationsPanel t={t} toast={toast} />
+ {/* Without the admin alert cards the right column is short, so the
+ reminder switch moves over on a managed install. */}
+ {managed && tripRemindersCard}
</div>
</div>
diff --git a/client/src/pages/admin/AdminSettingsTab.test.tsx b/client/src/pages/admin/AdminSettingsTab.test.tsx
index 745698efc..89d7a4097 100644
--- a/client/src/pages/admin/AdminSettingsTab.test.tsx
+++ b/client/src/pages/admin/AdminSettingsTab.test.tsx
@@ -320,24 +320,24 @@ describe('AdminSettingsTab', () => {
expect(admin.handleSavePlacesProvider).toHaveBeenCalledWith('amap');
});
- it('FE-ADMSET-022e: a managed install hides the keys but keeps the provider choice', () => {
- // The operator owns the credentials; which of them answers place search is
- // still the admin's call (server managed.ts lists places_provider as theirs).
+ it('FE-ADMSET-022e: a managed install hides place search, routing and the keys', () => {
+ // All of it is the operator's there (server managed.ts locks places_provider);
+ // Share place details has a tab of its own on AdminPage.
renderTab({ managed: true, placesProvider: 'auto' });
expect(screen.queryByRole('heading', { name: 'API Keys' })).not.toBeInTheDocument();
expect(screen.queryByLabelText('Google Maps API Key')).not.toBeInTheDocument();
- expect(within(card(SERVICES)).getByRole('button', { name: 'Automatic' })).toBeInTheDocument();
+ expect(screen.queryByRole('heading', { name: SERVICES })).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Automatic' })).not.toBeInTheDocument();
});
- it('FE-ADMSET-022f: an operator key keeps the managed install quiet', () => {
- // The key fields are not on the page here, and an operator key set through
- // the environment would not show up in them anyway. app-config knows.
- renderTab({ managed: true, placesProvider: 'google', mapsKey: '', hasMapsKey: true });
+ it('FE-ADMSET-022f: a managed install moves file types to the right column', () => {
+ // With place search and the keys gone the right column would stand empty.
+ renderTab({ managed: true });
- expect(
- within(card(SERVICES)).queryByText(/falls back to OpenStreetMap/i),
- ).not.toBeInTheDocument();
+ const right = screen.getByRole('heading', { name: 'Allowed File Types' }).closest('.min-w-0');
+ expect(right).not.toBeNull();
+ expect(within(right as HTMLElement).queryByRole('heading', { name: /two-factor/i })).not.toBeInTheDocument();
});
it('FE-ADMSET-023: the maps Test button is disabled without a key', () => {
diff --git a/client/src/pages/admin/AdminSettingsTab.tsx b/client/src/pages/admin/AdminSettingsTab.tsx
index 10b309873..2e3c2c2fa 100644
--- a/client/src/pages/admin/AdminSettingsTab.tsx
+++ b/client/src/pages/admin/AdminSettingsTab.tsx
@@ -16,6 +16,7 @@ import GoogleOptions from './GoogleOptions'
import GoogleDailyLimitRow from '../../components/Admin/GoogleDailyLimitRow'
import ProviderBlock from './ProviderBlock'
import TrekApiCard from './TrekApiCard'
+import PlaceContribPanel from '../../components/Admin/PlaceContribPanel'
import { useAdminSettingsActions } from '../../components/Admin/useAdminSettingsActions'
import { placesGoogleOnlyHint } from '../../utils/placeSource'
import type { TranslationFn } from '../../types'
@@ -140,6 +141,29 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
const passwordLoginLocked = !passwordLogin && !oidcLogin
const oidcLoginLocked = !passwordLogin && oidcLogin
+ // On a managed install the right column loses place search, routing and the
+ // keys to the operator, so file types move over and the columns stay even.
+ const fileTypesCard = (
+ <SettingsCard icon={FileType} title={t('admin.fileTypes')} hint={t('admin.fileTypesHint')}>
+ <div>
+ <input
+ type="text"
+ aria-label={t('admin.fileTypes')}
+ value={allowedFileTypes}
+ onChange={e => setAllowedFileTypes(e.target.value)}
+ placeholder="jpg,png,pdf,doc,docx,xls,xlsx,txt,csv"
+ className={`${INPUT} font-geist`}
+ />
+ <SettingsHint className="mt-1.5">{t('admin.fileTypesFormat')}</SettingsHint>
+ </div>
+ <SaveBar
+ label={t('common.save')}
+ saving={savingFileTypes}
+ onClick={saveFileTypes}
+ />
+ </SettingsCard>
+ )
+
return (
<div>
{/* Two columns from xl up. Nearly every card here is "label left,
@@ -351,33 +375,24 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
</SettingsCard>
)}
- {/* Allowed File Types */}
- <SettingsCard icon={FileType} title={t('admin.fileTypes')} hint={t('admin.fileTypesHint')}>
- <div>
- <input
- type="text"
- aria-label={t('admin.fileTypes')}
- value={allowedFileTypes}
- onChange={e => setAllowedFileTypes(e.target.value)}
- placeholder="jpg,png,pdf,doc,docx,xls,xlsx,txt,csv"
- className={`${INPUT} font-geist`}
- />
- <SettingsHint className="mt-1.5">{t('admin.fileTypesFormat')}</SettingsHint>
- </div>
- <SaveBar
- label={t('common.save')}
- saving={savingFileTypes}
- onClick={saveFileTypes}
- />
- </SettingsCard>
+ {!managed && fileTypesCard}
</div>
<div className="min-w-0">
+ {managed && fileTypesCard}
+ {/* Inside the place search card elsewhere; that card is the operator's here,
+ sharing place details is still the admin's decision. */}
+ {managed && <PlaceContribPanel hideWhenSwitchedOff />}
{/* Place search and routing: TREK's own services first, then which provider
answers search and transit, and the search log. Apart from the keys, so a
keyless install reads its whole setup in one card. Everything here saves
as it is changed. */}
+ {/* On a managed install place search and routing are the operator's: the
+ services, their allowance and the providers behind them come with the
+ instance. Share place details stays the admin's call and has a tab of
+ its own there (AdminPage). */}
+ {!managed && (
<SettingsCard icon={Compass} title={t('admin.servicesCard.title')} hint={t('admin.servicesCard.hint')}>
<TrekApiCard t={t} managed={managed} />
{!managed && (<>
@@ -486,6 +501,7 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
</SettingRows>
</SettingsCard>
+ )}
{/* API Keys: only the keyed providers, Google, Unsplash and Amap. They are
the operator's on a managed install, so the card is not shown there;
diff --git a/client/src/pages/admin/useAdmin.ts b/client/src/pages/admin/useAdmin.ts
index e9b29f136..295e236ae 100644
--- a/client/src/pages/admin/useAdmin.ts
+++ b/client/src/pages/admin/useAdmin.ts
@@ -33,7 +33,7 @@ const ADMIN_TAB_IDS = [
* hosted instance. Checked in an effect rather than in the initial state
* because `managed` arrives with /app-config, after the first render.
*/
-const MANAGED_HIDDEN = ['storage', 'github', 'backup']
+const MANAGED_HIDDEN = ['storage', 'github', 'backup', 'plugins']
/** How often the open users list asks again who is online and active. */
const USERS_REFRESH_MS = 30_000
diff --git a/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx b/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx
index 1eeac7c46..f67393b45 100644
--- a/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx
+++ b/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx
@@ -281,16 +281,16 @@ describe('MAdminSettingsSection', () => {
expect(admin.handleSaveApiKeys).toHaveBeenCalled();
});
- it('FE-MOB-ASET-016b: a managed install hides the keys but keeps the provider choice', () => {
- // The operator owns the credentials; which of them answers place search is
- // still the admin's call, the same split the desktop tab makes.
+ it('FE-MOB-ASET-016b: a managed install hides the keys, place search, OIDC and the relying party', () => {
+ // All of it is the operator's there, the same split the desktop tab makes.
renderSettings({ managed: true });
expect(screen.queryByLabelText('Google Maps API Key')).not.toBeInTheDocument();
expect(screen.queryByLabelText(/Amap/)).not.toBeInTheDocument();
expect(screen.queryByLabelText('Unsplash API Key')).not.toBeInTheDocument();
- // The native select became TREK's own picker: a button carrying the choice.
- expect(screen.getByRole('button', { name: 'Automatic' })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Automatic' })).not.toBeInTheDocument();
+ expect(screen.queryByPlaceholderText('trek.example.org')).not.toBeInTheDocument();
+ expect(screen.queryByPlaceholderText(/Authentik/)).not.toBeInTheDocument();
});
it('FE-MOB-ASET-016c: the missing-key notice follows app-config, not the fields', () => {
@@ -301,7 +301,7 @@ describe('MAdminSettingsSection', () => {
expect(screen.getByText(/TREK index and OpenStreetMap alone/i)).toBeInTheDocument();
unmount();
- renderSettings({ managed: true, placesProvider: 'google', mapsKey: '', hasMapsKey: true });
+ renderSettings({ placesProvider: 'google', mapsKey: '', hasMapsKey: true });
expect(screen.queryByText(/TREK index and OpenStreetMap alone/i)).not.toBeInTheDocument();
});
diff --git a/server/src/nest/addons/addons.service.ts b/server/src/nest/addons/addons.service.ts
index db4af1ace..75fea8379 100644
--- a/server/src/nest/addons/addons.service.ts
+++ b/server/src/nest/addons/addons.service.ts
@@ -114,6 +114,12 @@ export class AddonsService {
return this.writeFlag('ski_routing_enabled', enabled);
}
+ /** The photo providers users can connect: none while the journey addon is off. */
+ async enabledPhotoProviderIds(): Promise<string[]> {
+ if (!(await this.isAddonEnabled(ADDON_IDS.JOURNEY))) return [];
+ return (await this.photoProviders.listEnabled()).map((row) => row.id);
+ }
+
/** wanderer may be used: Tours is on and the admin allowed it under Tours. */
async isWandererAvailable(): Promise<boolean> {
return (await this.isAddonEnabled(ADDON_IDS.TOURS)) && (await this.getToursWanderer()).enabled;
diff --git a/server/src/nest/admin/admin.controller.ts b/server/src/nest/admin/admin.controller.ts
index 79ea435f3..ab5aa0969 100644
--- a/server/src/nest/admin/admin.controller.ts
+++ b/server/src/nest/admin/admin.controller.ts
@@ -293,6 +293,7 @@ export class AdminController {
@Put('tours-wanderer')
@ResponseContract(adminFeatureToggleResponseSchema)
+ @ManagedForbidden('wanderer sends searches to a server the user picks, which the operator has not agreed to')
async updateToursWanderer(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = await this.addons.updateToursWanderer(body.enabled);
await this.audit.writeAudit({
@@ -418,6 +419,7 @@ export class AdminController {
}
@Put('place-shadow')
+ @ManagedForbidden('place search belongs to the operator on a managed install')
async updatePlaceShadow(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = await this.addons.updatePlaceShadow(body.enabled);
await this.audit.writeAudit({
@@ -491,6 +493,7 @@ export class AdminController {
}
@Put('transit-provider')
+ @ManagedForbidden('routing belongs to the operator on a managed install')
async updateTransitProvider(@CurrentUser() user: User, @Body() body: AdminTransitProviderDto, @Req() req: Request) {
const result = await this.addons.updateTransitProvider(body.provider, user.id);
await this.audit.writeAudit({
diff --git a/server/src/nest/common/app-settings.registry.ts b/server/src/nest/common/app-settings.registry.ts
index f7362d6ab..74ad8de30 100644
--- a/server/src/nest/common/app-settings.registry.ts
+++ b/server/src/nest/common/app-settings.registry.ts
@@ -89,7 +89,7 @@ export const APP_SETTINGS = {
webauthn_origins: { schema: text, default: null, adminForm: true, managedLocked: true },
// 'auto' (what every install had before Amap existed), 'google', 'amap' or
// 'openstreetmap'; the maps domain validates it (isPlacesProviderChoice).
- places_provider: { schema: text, default: 'auto', adminForm: true, publicConfig: true },
+ places_provider: { schema: text, default: 'auto', adminForm: true, publicConfig: true, managedLocked: true },
// Read by name elsewhere.
oidc_issuer: { schema: text, default: null, env: (e) => e.oidc.issuer, publicConfig: true },
diff --git a/server/src/nest/common/managed.ts b/server/src/nest/common/managed.ts
index d7cfb95b7..3b29d8628 100644
--- a/server/src/nest/common/managed.ts
+++ b/server/src/nest/common/managed.ts
@@ -91,6 +91,9 @@ export const MANAGED_LOCKED_SETTING_KEYS = [
'oidc_login',
'oidc_registration',
'openweather_api_key',
+ // Place search and routing are the operator's on a managed install: the
+ // services, their allowance and who answers come with the instance.
+ 'places_provider',
'routing_base_url',
'routing_valhalla_provider',
// The operator issues a managed install its key through TREK_SERVICES_KEY.
@@ -149,10 +152,6 @@ export const MANAGED_CUSTOMER_KEYS = [
'passkey_login',
'password_login',
'password_registration',
- // WHICH provider answers place search stays the admin's call even when the
- // operator owns both credentials: it decides what their users see, not what
- // the operator is billed for — the keys above cover that.
- 'places_provider',
'require_mfa',
'temperature_unit',
'time_format',
diff --git a/server/src/nest/common/validate-managed-routes.ts b/server/src/nest/common/validate-managed-routes.ts
index a2b0ce0b4..db92d21eb 100644
--- a/server/src/nest/common/validate-managed-routes.ts
+++ b/server/src/nest/common/validate-managed-routes.ts
@@ -64,6 +64,9 @@ export function collectManagedRoutes(app: INestApplication): ManagedRouteEntry[]
*/
export const MANAGED_ROUTE_ALLOW_LIST: string[] = [
'AdminController.rotateJwtSecret',
+ 'AdminController.updatePlaceShadow',
+ 'AdminController.updateToursWanderer',
+ 'AdminController.updateTransitProvider',
'AdminOidcController.get',
'AdminOidcController.update',
'AiAdminController.connection',
diff --git a/server/src/nest/notifications/notification-preferences.service.ts b/server/src/nest/notifications/notification-preferences.service.ts
index b4028a4e3..e58fce9e2 100644
--- a/server/src/nest/notifications/notification-preferences.service.ts
+++ b/server/src/nest/notifications/notification-preferences.service.ts
@@ -1,7 +1,10 @@
+import { ADDON_IDS } from '../../addons';
+import { readEnv } from '../../app-config';
import { AppSettings } from '../../db/entities/AppSettings.entity';
import { NotificationChannelPreferences } from '../../db/entities/NotificationChannelPreferences.entity';
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
import type { NotificationChannelPreferencesRepository } from '../../db/repositories/NotificationChannelPreferences.repository';
+import { AddonsService } from '../addons/addons.service';
import { readAppSetting } from '../common/app-settings.registry';
import { UnitOfWork } from '../database/unit-of-work';
import { listChannels } from './channel-registry';
@@ -60,6 +63,21 @@ const DEFAULT_KEY = (event: string, channel: string) => `notif_default_${event}_
* 3-column composite primary key (`user`, `event_type`, `channel`) via
* `em.upsert({ onConflictFields: [...] })`, per Task 0's R5 pin.
*/
+
+/**
+ * The events this install can actually raise, for the preference matrices.
+ * Plugin notifications need the plugin runtime; on a managed install the
+ * release check and the storage replicas are the operator's, so their alerts
+ * would be rows nobody there can act on.
+ */
+export function offeredEventTypes(): NotifEventType[] {
+ const env = readEnv();
+ return ALL_EVENT_TYPES.filter((e) => {
+ if (e === 'plugin_notification') return env.plugins.enabled;
+ if (e === 'version_available' || e === 'replica_failure') return !env.managed.enabled;
+ return true;
+ });
+}
@Injectable()
export class NotificationPreferencesService {
constructor(
@@ -68,8 +86,57 @@ export class NotificationPreferencesService {
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
@InjectRepository(NotificationChannelPreferences)
private readonly channelPrefs: NotificationChannelPreferencesRepository,
+ private readonly addons: AddonsService,
) {}
+ /**
+ * The events the matrices list: what the install can raise at all
+ * (offeredEventTypes), narrowed to the features that are switched on. A row
+ * for vacation sharing on an install without Vacay, or for Synology without
+ * the provider, is a switch that never does anything.
+ */
+ private async listedEventTypes(): Promise<NotifEventType[]> {
+ const photoProviders = await this.addons.enabledPhotoProviderIds();
+ const addonOn = new Map<string, boolean>();
+ const on = async (id: string) => {
+ if (!addonOn.has(id)) addonOn.set(id, await this.addons.isAddonEnabled(id));
+ return addonOn.get(id) === true;
+ };
+ const listed: NotifEventType[] = [];
+ for (const event of offeredEventTypes()) {
+ if (await this.featureOn(event, on, photoProviders)) listed.push(event);
+ }
+ return listed;
+ }
+
+ private async featureOn(
+ event: NotifEventType,
+ on: (addonId: string) => Promise<boolean>,
+ photoProviders: string[],
+ ): Promise<boolean> {
+ switch (event) {
+ case 'vacay_invite':
+ case 'vacay_share':
+ return on(ADDON_IDS.VACAY);
+ case 'collection_invite':
+ return on(ADDON_IDS.COLLECTIONS);
+ case 'collab_message':
+ return on(ADDON_IDS.COLLAB);
+ case 'packing_tagged':
+ return on(ADDON_IDS.PACKING);
+ case 'paddle_region_requested':
+ return on(ADDON_IDS.TOURS);
+ case 'photos_shared':
+ return photoProviders.length > 0;
+ case 'synology_session_cleared':
+ return photoProviders.includes('synologyphotos');
+ case 'wanderer_source_hint':
+ return this.addons.isWandererAvailable();
+ default:
+ return true;
+ }
+ }
+
/**
* Channels implemented for an event. In-app takes everything; external channels
* decide for themselves (today: everything except `synology_session_cleared`).
@@ -151,12 +218,12 @@ export class NotificationPreferencesService {
return (NOTIFICATION_DEFAULTS as readonly string[]).includes(raw ?? '') ? (raw as NotificationDefault) : 'on';
}
- private userEventTypes(): NotifEventType[] {
- return ALL_EVENT_TYPES.filter((e) => !ADMIN_SCOPED_EVENTS.has(e));
+ private async userEventTypes(): Promise<NotifEventType[]> {
+ return (await this.listedEventTypes()).filter((e) => !ADMIN_SCOPED_EVENTS.has(e));
}
async getInstanceDefaults(adminId: number): Promise<InstanceDefaultsMatrix> {
- const event_types = this.userEventTypes();
+ const event_types = await this.userEventTypes();
const implemented_combos = await this.allCombos();
const defaults: InstanceDefaultsMatrix['defaults'] = {};
for (const event of event_types) {
@@ -171,7 +238,9 @@ export class NotificationPreferencesService {
async setInstanceDefaults(
defaults: Partial<Record<string, Partial<Record<string, NotificationDefault>>>>,
): Promise<void> {
- const userEvents = new Set<string>(this.userEventTypes());
+ // Every user event, not only the listed ones: a default set while an addon is
+ // off is still the right default once it is switched on.
+ const userEvents = new Set<string>(ALL_EVENT_TYPES.filter((e) => !ADMIN_SCOPED_EVENTS.has(e)));
// The channel set is read before the transaction opens: listChannels() may
// ask the plugin runtime, which is no work to hold the connection for.
const combos = await this.allCombos();
@@ -298,8 +367,8 @@ export class NotificationPreferencesService {
// Filter event types by scope
const event_types =
scope === 'admin'
- ? ALL_EVENT_TYPES.filter((e) => ADMIN_SCOPED_EVENTS.has(e))
- : ALL_EVENT_TYPES.filter((e) => !ADMIN_SCOPED_EVENTS.has(e));
+ ? (await this.listedEventTypes()).filter((e) => ADMIN_SCOPED_EVENTS.has(e))
+ : (await this.listedEventTypes()).filter((e) => !ADMIN_SCOPED_EVENTS.has(e));
return {
preferences,
diff --git a/server/src/nest/notifications/notifications.module.ts b/server/src/nest/notifications/notifications.module.ts
index 0e0fb1e72..ba91452ac 100644
--- a/server/src/nest/notifications/notifications.module.ts
+++ b/server/src/nest/notifications/notifications.module.ts
@@ -5,6 +5,7 @@ import { PushSubscriptions } from '../../db/entities/PushSubscriptions.entity';
import { Settings } from '../../db/entities/Settings.entity';
import { TodoItems } from '../../db/entities/TodoItems.entity';
import { Trips } from '../../db/entities/Trips.entity';
+import { AddonsModule } from '../addons/addons.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { StorageModule } from '../storage/storage.module';
import { MailerModule } from './mailer/mailer.module';
@@ -63,6 +64,7 @@ import { Module } from '@nestjs/common';
PushSubscriptions,
]),
+ AddonsModule,
MailerModule,
SchedulingModule,
StorageModule,
diff --git a/server/tests/helpers/notifications.ts b/server/tests/helpers/notifications.ts
index 28a695656..f7b6ce307 100644
--- a/server/tests/helpers/notifications.ts
+++ b/server/tests/helpers/notifications.ts
@@ -1,3 +1,4 @@
+import type { AddonsService } from '../../src/nest/addons/addons.service';
import { MailerService } from '../../src/nest/notifications/mailer/mailer.service';
import { NotificationPreferencesService } from '../../src/nest/notifications/notification-preferences.service';
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
@@ -62,7 +63,7 @@ export async function makeNotificationsService(
mailer,
new WebhookService(settingsRepo, appSettings),
new NtfyService(settingsRepo, appSettings),
- new NotificationPreferencesService(mailer, uow, appSettings, channelPrefsRepo),
+ new NotificationPreferencesService(mailer, uow, appSettings, channelPrefsRepo, everyFeatureOn()),
uow,
notificationsRepo,
await makeWebPushService(db),
@@ -98,9 +99,25 @@ export async function makeNotificationPreferencesService(
await createTestUnitOfWork(db),
appSettings,
channelPrefsRepo,
+ everyFeatureOn(),
);
}
+/**
+ * The addon answers for the preference matrices with every feature on, so a
+ * suite sees every event row unless it is about the narrowing itself.
+ */
+export function everyFeatureOn(
+ overrides: Partial<Pick<AddonsService, 'isAddonEnabled' | 'isWandererAvailable' | 'enabledPhotoProviderIds'>> = {},
+): AddonsService {
+ return {
+ isAddonEnabled: async () => true,
+ isWandererAvailable: async () => true,
+ enabledPhotoProviderIds: async () => ['immich', 'synologyphotos'],
+ ...overrides,
+ } as unknown as AddonsService;
+}
+
/**
* A send that records instead of delivering.
*
diff --git a/server/tests/unit/nest/admin.controller.test.ts b/server/tests/unit/nest/admin.controller.test.ts
index a383e9454..a8804d74d 100644
--- a/server/tests/unit/nest/admin.controller.test.ts
+++ b/server/tests/unit/nest/admin.controller.test.ts
@@ -5,6 +5,7 @@ import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { RegistrationInvitesService } from '../../../src/nest/auth/registration-invites.service';
import { KitineraryExtractorService } from '../../../src/nest/booking-import/kitinerary-extractor.service';
import { DomainError } from '../../../src/nest/common/domain-error';
+import { MANAGED_FORBIDDEN } from '../../../src/nest/common/managed';
import type { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import type { OauthService } from '../../../src/nest/oauth/oauth.service';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
@@ -607,3 +608,17 @@ describe('AdminController feature toggles', () => {
expect(noopInvalidate).not.toHaveBeenCalled();
});
});
+
+describe('AdminController on a managed install', () => {
+ it('ADMIN-CTRL-MANAGED-001: the transit provider and the place search log are operator-owned', () => {
+ // Place search and routing come with a managed instance; the admin UI hides
+ // both, and the routes refuse them so a direct call cannot set them either.
+ for (const name of ['updateTransitProvider', 'updatePlaceShadow', 'updateToursWanderer'] as const) {
+ const handler = AdminController.prototype[name];
+ expect(Reflect.getMetadata(MANAGED_FORBIDDEN, handler)?.reason, name).toBeTruthy();
+ }
+ // Reading stays open: the search still needs to know what it runs on.
+ expect(Reflect.getMetadata(MANAGED_FORBIDDEN, AdminController.prototype.getTransitProvider)).toBeUndefined();
+ expect(Reflect.getMetadata(MANAGED_FORBIDDEN, AdminController.prototype.getPlaceShadow)).toBeUndefined();
+ });
+});
diff --git a/server/tests/unit/nest/channel-override.test.ts b/server/tests/unit/nest/channel-override.test.ts
index 259e8ad03..1fcea85b2 100644
--- a/server/tests/unit/nest/channel-override.test.ts
+++ b/server/tests/unit/nest/channel-override.test.ts
@@ -27,7 +27,7 @@ import { NtfyService } from '../../../src/nest/notifications/transports/ntfy.ser
import { WebhookService } from '../../../src/nest/notifications/transports/webhook.service';
import { createUser, createAdmin, setAppSetting, setNotificationChannels } from '../../helpers/factories';
import { makePlugin } from '../../helpers/factories/plugins';
-import { makeNotificationsService } from '../../helpers/notifications';
+import { everyFeatureOn, makeNotificationsService } from '../../helpers/notifications';
import { createTestNotificationChannelPreferencesRepo } from '../../helpers/notifications-repos';
import { createPluginRuntime } from '../../helpers/plugin-host';
import { resetTestDb } from '../../helpers/test-db';
@@ -114,6 +114,7 @@ beforeAll(async () => {
await createTestUnitOfWork(testDb),
await createTestAppSettingsRepo(testDb),
await createTestNotificationChannelPreferencesRepo(testDb),
+ everyFeatureOn(),
);
notifications = await makeNotificationsService(testDb);
});
diff --git a/server/tests/unit/nest/managed-keys.test.ts b/server/tests/unit/nest/managed-keys.test.ts
index 08d0a1096..01002495b 100644
--- a/server/tests/unit/nest/managed-keys.test.ts
+++ b/server/tests/unit/nest/managed-keys.test.ts
@@ -68,6 +68,7 @@ describe('managed key assignment', () => {
'oidc_login',
'oidc_registration',
'openweather_api_key',
+ 'places_provider',
'routing_base_url',
'routing_valhalla_provider',
'service_key',
diff --git a/server/tests/unit/nest/notification-offered-events.test.ts b/server/tests/unit/nest/notification-offered-events.test.ts
new file mode 100644
index 000000000..b8be644af
--- /dev/null
+++ b/server/tests/unit/nest/notification-offered-events.test.ts
@@ -0,0 +1,46 @@
+/**
+ * Which events the preference matrices offer. A row for an event the install
+ * can never raise is a switch that does nothing: plugin notifications without
+ * the plugin runtime, and on a managed install the release check and the
+ * storage replicas, which belong to the operator there.
+ */
+import { ALL_EVENT_TYPES } from '../../../src/nest/notifications/notification-events';
+import { offeredEventTypes } from '../../../src/nest/notifications/notification-preferences.service';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+const saved = { managed: process.env.TREK_MANAGED, plugins: process.env.TREK_PLUGINS_ENABLED };
+
+afterEach(() => {
+ if (saved.managed === undefined) delete process.env.TREK_MANAGED;
+ else process.env.TREK_MANAGED = saved.managed;
+ if (saved.plugins === undefined) delete process.env.TREK_PLUGINS_ENABLED;
+ else process.env.TREK_PLUGINS_ENABLED = saved.plugins;
+});
+
+describe('offeredEventTypes', () => {
+ it('NOTIF-OFFERED-001: a self-hosted install with plugins offers every event', () => {
+ delete process.env.TREK_MANAGED;
+ delete process.env.TREK_PLUGINS_ENABLED;
+ expect(offeredEventTypes()).toEqual(ALL_EVENT_TYPES);
+ });
+
+ it('NOTIF-OFFERED-002: without the plugin runtime there is no plugin row', () => {
+ delete process.env.TREK_MANAGED;
+ process.env.TREK_PLUGINS_ENABLED = 'false';
+ expect(offeredEventTypes()).not.toContain('plugin_notification');
+ expect(offeredEventTypes()).toContain('version_available');
+ });
+
+ it('NOTIF-OFFERED-003: a managed install drops the operator alerts and keeps the rest in order', () => {
+ process.env.TREK_MANAGED = '1';
+ process.env.TREK_PLUGINS_ENABLED = 'false';
+ const offered = offeredEventTypes();
+ expect(offered).not.toContain('version_available');
+ expect(offered).not.toContain('replica_failure');
+ expect(offered).toContain('paddle_region_requested');
+ expect(offered).toEqual(
+ ALL_EVENT_TYPES.filter((e) => !['version_available', 'replica_failure', 'plugin_notification'].includes(e)),
+ );
+ });
+});
diff --git a/server/tests/unit/nest/notification-preferences.service.test.ts b/server/tests/unit/nest/notification-preferences.service.test.ts
index 5be317c6b..b7c9f74a7 100644
--- a/server/tests/unit/nest/notification-preferences.service.test.ts
+++ b/server/tests/unit/nest/notification-preferences.service.test.ts
@@ -19,7 +19,7 @@ import {
disableNotificationPref,
} from '../../helpers/factories';
import { countRows, findRow, insertRow } from '../../helpers/factories/rows';
-import { makeWebPushService } from '../../helpers/notifications';
+import { everyFeatureOn, makeWebPushService } from '../../helpers/notifications';
import { createTestNotificationChannelPreferencesRepo } from '../../helpers/notifications-repos';
import { resetTestDb } from '../../helpers/test-db';
import {
@@ -102,6 +102,7 @@ beforeAll(async () => {
await createTestUnitOfWork(testDb),
await createTestAppSettingsRepo(testDb),
await createTestNotificationChannelPreferencesRepo(testDb),
+ everyFeatureOn(),
);
});
@@ -450,3 +451,36 @@ describe('instance defaults', () => {
expect(await countRows(await sharedTestOrm(testDb), AppSettings, { key: { $like: 'notif_default_%' } })).toBe(0);
});
});
+
+describe('listed events follow the features that are on', () => {
+ it('NPREF-LIST-001: rows for switched-off addons and providers are not listed', async () => {
+ const narrow = new NotificationPreferencesService(
+ new MailerService(
+ await createTestUsersRepo(testDb),
+ await createTestSettingsRepo(testDb),
+ await createTestAppSettingsRepo(testDb),
+ ),
+ await createTestUnitOfWork(testDb),
+ await createTestAppSettingsRepo(testDb),
+ await createTestNotificationChannelPreferencesRepo(testDb),
+ everyFeatureOn({
+ isAddonEnabled: async (id: string) => id !== 'vacay' && id !== 'collections',
+ isWandererAvailable: async () => false,
+ enabledPhotoProviderIds: async () => ['immich'],
+ }),
+ );
+ const { user } = createUser(testDb);
+ const { event_types } = await narrow.getPreferencesMatrix(user.id, 'user');
+ for (const hidden of [
+ 'vacay_invite',
+ 'vacay_share',
+ 'collection_invite',
+ 'wanderer_source_hint',
+ 'synology_session_cleared',
+ ]) {
+ expect(event_types).not.toContain(hidden);
+ }
+ expect(event_types).toContain('photos_shared');
+ expect(event_types).toContain('trip_invite');
+ });
+});