The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
feat(mobile): the admin services section gets what the desktop tab has
Mauricea3620f9e051e
diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.jsonindex 25d1e3c21..c17d67368 100644--- a/client/scripts/feature-pairs.json+++ b/client/scripts/feature-pairs.json@@ -57,6 +57,30 @@"desktop": ["src/pages/admin/AdminSettingsTab.tsx"],"mobile": ["src/mobile/screens/admin/MAdminSettingsSection.tsx"]},+ {+ "feature": "Admin Google daily limit",+ "hooks": ["src/components/Admin/useGoogleQuota.ts"],+ "desktop": ["src/components/Admin/GoogleDailyLimitRow.tsx"],+ "mobile": ["src/mobile/screens/admin/MAdminGoogleDailyLimit.tsx"]+ },+ {+ "feature": "Admin share place details",+ "hooks": [+ "src/components/Admin/usePlaceContribPanel.ts",+ "src/components/Admin/placeContribModel.ts"+ ],+ "desktop": ["src/components/Admin/PlaceContribPanel.tsx"],+ "mobile": ["src/mobile/screens/admin/MAdminPlaceContrib.tsx"]+ },+ {+ "feature": "Admin TREK services allowance",+ "hooks": [+ "src/components/Admin/useServiceIdentity.ts",+ "src/components/Admin/serviceIdentityModel.ts"+ ],+ "desktop": ["src/components/Admin/ServiceIdentityPanel.tsx"],+ "mobile": ["src/mobile/screens/admin/MAdminServiceQuota.tsx"]+ },{"feature": "Admin users invite status","hooks": ["src/pages/admin/adminModel.ts"],diff --git a/client/scripts/theme-baseline.json b/client/scripts/theme-baseline.jsonindex 456d3fc64..5d2a44be9 100644--- a/client/scripts/theme-baseline.json+++ b/client/scripts/theme-baseline.json@@ -160,7 +160,7 @@"mobile/screens/admin/MAdminPackingTemplateManager.tsx": 8,"mobile/screens/admin/MAdminPermissionsPanel.tsx": 1,"mobile/screens/admin/MAdminPluginsPanel.tsx": 128,- "mobile/screens/admin/MAdminSettingsSection.tsx": 9,+ "mobile/screens/admin/MAdminSettingsSection.tsx": 2,"mobile/screens/admin/MAdminSheets.tsx": 11,"mobile/screens/admin/MAdminStoragePanel.tsx": 42,"mobile/screens/admin/MAdminUi.tsx": 7,diff --git a/client/src/components/Admin/PlaceContribPanel.tsx b/client/src/components/Admin/PlaceContribPanel.tsxindex e8ddf91f6..975325335 100644--- a/client/src/components/Admin/PlaceContribPanel.tsx+++ b/client/src/components/Admin/PlaceContribPanel.tsx@@ -1,26 +1,16 @@-import type { PlaceContribField, PlaceContribState } from '@trek/shared';+import type { PlaceContribState } from '@trek/shared';import { HeartHandshake, Undo2 } from 'lucide-react';-import { useState } from 'react';import { useTranslation } from '../../i18n';import type { TranslationFn } from '../../types';-import { getApiErrorMessage } from '../../utils/apiError';import { SettingsCard, StatusPill } from '../Settings/settingsKit';import ToggleSwitch from '../Settings/ToggleSwitch';import ConfirmDialog from '../shared/ConfirmDialog';import { fs } from '../shared/DialogShell';-import { useToast } from '../shared/Toast';import { FigureBadge } from '../Tours/paddle/FigureBadge';import PlaceContribLog from './PlaceContribLog';-import {- contribNote,- contribStatus,- fieldEntries,- fieldLabel,- refusalReason,- type ContribStatus,-} from './placeContribModel';+import { contribNote, fieldEntries, fieldLabel, type ContribStatus } from './placeContribModel';import PlaceContribPrompt from './PlaceContribPrompt';-import { usePlaceContrib } from './usePlaceContrib';+import { usePlaceContribPanel } from './usePlaceContribPanel';const PILL_TONE: Record<ContribStatus, 'success' | 'warning' | 'neutral'> = {active: 'success',@@ -61,54 +51,12 @@ 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.*/-/**- * Standing alone (managed settings), a card that can only say "not available"- * because the operator switched sharing off is a dead end.- */-function hiddenAlone(state: PlaceContribState, alone: boolean): boolean {- return alone && state.ineligibleReason === 'env_off';-}-export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean } = {}) {const { t } = useTranslation();- const toast = useToast();- const contrib = usePlaceContrib();- const { state } = contrib;- const [prompting, setPrompting] = useState<boolean | null>(null);- const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);+ const panel = usePlaceContribPanel({ hideWhenSwitchedOff });+ const { contrib, state, status, on, confirm, setConfirm, toggleField, withdraw } = panel;- if (!state) return null;- if (hiddenAlone(state, hideWhenSwitchedOff)) 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.- const showPrompt = prompting ?? state.showPrompt;-- const fail = (err: unknown) => {- const reason = refusalReason(err);- toast.error(- reason === 'terms_outdated' || reason === 'no_field'- ? t(`admin.contribute.refused.${reason}`)- : getApiErrorMessage(err, t('common.error'))- );- };-- const toggleField = (field: PlaceContribField) => {- const fields = { ...state.consent.fields, [field]: !state.consent.fields[field] };- if (!Object.values(fields).some(Boolean)) {- setConfirm('off');- return;- }- contrib.decide({ action: 'fields', fields }).catch(fail);- };-- const withdraw = () => {- setConfirm(null);- contrib.withdraw().then((r) => {- const total = Object.values(r.withdrawn).reduce((a, b) => a + b, 0);- toast.success(t('admin.contribute.withdrawn', { total }));- }, fail);- };+ if (panel.hidden || !state || !status) return null;return (<SettingsCard@@ -119,15 +67,15 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hidhint={contribNote(t, state)}action={<ToggleSwitch- on={agreed && state.consent.enabled}+ on={on}label={t('admin.contribute.title')}disabled={!state.eligible || contrib.busy}- onToggle={() => (agreed && state.consent.enabled ? setConfirm('off') : setPrompting(true))}+ onToggle={panel.toggleMain}/>}bodyClassName="flex flex-col gap-3 p-4">- {agreed && state.consent.enabled && (+ {on && (<><Figures state={state} t={t} /><ul className="m-0 grid list-none grid-cols-2 gap-1.5 p-0 max-sm:grid-cols-1">@@ -151,7 +99,7 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hid</>)}- {(agreed || state.consent.decision === 'off') && (+ {panel.showLog && (<div className="overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card">{/* A plain section head: the settings fold nothing away. */}<div className="flex items-center gap-2.5 px-3.5 py-2.5">@@ -175,16 +123,11 @@ export default function PlaceContribPanel({ hideWhenSwitchedOff = false }: { hid</div>)}- {showPrompt && state.eligible && (- <PlaceContribPrompt state={state} contrib={contrib} onClose={() => setPrompting(false)} />- )}+ {panel.showPrompt && <PlaceContribPrompt state={state} contrib={contrib} onClose={panel.closePrompt} />}<ConfirmDialogisOpen={confirm === 'off'}onClose={() => setConfirm(null)}- onConfirm={() => {- setConfirm(null);- contrib.decide({ action: 'off' }).catch(fail);- }}+ onConfirm={panel.switchOff}title={t('admin.contribute.offTitle')}message={t('admin.contribute.offMessage')}confirmLabel={t('admin.contribute.offConfirm')}diff --git a/client/src/components/Admin/ServiceIdentityPanel.tsx b/client/src/components/Admin/ServiceIdentityPanel.tsxindex ce448f2d5..39989a37b 100644--- a/client/src/components/Admin/ServiceIdentityPanel.tsx+++ b/client/src/components/Admin/ServiceIdentityPanel.tsx@@ -1,15 +1,22 @@-import type { ServiceAllowance, ServiceIdentityState, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';+import type { ServiceAllowance, ServiceIdentityState } from '@trek/shared';import { MapPin, RefreshCw, Route, Search, Signal, type LucideIcon } from 'lucide-react';import { useRef, useState } from 'react';import { useTranslation } from '../../i18n';import { useSettingsStore } from '../../store/settingsStore';-import type { TranslationFn } from '../../types';import { getApiErrorMessage } from '../../utils/apiError';-import { formatClockTime } from '../../utils/formatters';import { SettingsCard } from '../Settings/settingsKit';import ConfirmDialog from '../shared/ConfirmDialog';import { useToast } from '../shared/Toast';import { FigureBadge } from '../Tours/paddle/FigureBadge';+import {+ allowanceNote,+ canRegenerateKey,+ identityHint,+ quotaLevel,+ quotaResetClock,+ quotaShare,+ type QuotaLevel,+} from './serviceIdentityModel';import { useServiceIdentity } from './useServiceIdentity';const STATE_DOT: Record<ServiceIdentityState, string> = {@@ -23,32 +30,8 @@ const STATE_DOT: Record<ServiceIdentityState, string> = {const SERVICE_ICON: Record<string, LucideIcon> = { places: MapPin, photon: Search, valhalla: Route };/** Below a tenth of the day left the bar turns amber, at nothing left red. */-function barTone(quota: ServiceQuotaView): string {- if (quota.remaining === 0) return 'bg-danger';- return quota.remaining < quota.limit / 10 ? 'bg-warning' : 'bg-accent';-}--function figureTone(quota: ServiceQuotaView): string {- if (quota.remaining === 0) return 'text-danger';- return quota.remaining < quota.limit / 10 ? 'text-warning' : 'text-content';-}--/** The clock time the counts start again, in the user's format; one for all services, which share the day. */-function useResetTime(status: ServiceIdentityStatus | null): string | null {- const is12h = useSettingsStore((s) => s.settings.time_format === '12h');- const at = status?.services.find((s) => s.quota)?.quota?.resetAt;- if (!at) return null;- const reset = new Date(at);- return formatClockTime(- `${String(reset.getHours()).padStart(2, '0')}:${String(reset.getMinutes()).padStart(2, '0')}`,- is12h- );-}--function tileNote(t: TranslationFn, allowance: ServiceAllowance): string | null {- if (!allowance.inUse) return t('admin.trekApi.quota.notInUse');- return allowance.quota ? null : t('admin.trekApi.quota.unavailable');-}+const BAR_TONE: Record<QuotaLevel, string> = { ok: 'bg-accent', low: 'bg-warning', out: 'bg-danger' };+const FIGURE_TONE: Record<QuotaLevel, string> = { ok: 'text-content', low: 'text-warning', out: 'text-danger' };/*** One service under the key, as a tile: what is left today as the figure that@@ -59,10 +42,10 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {const { t, locale } = useTranslation();const number = new Intl.NumberFormat(locale);const name = t(`admin.trekApi.quota.service.${allowance.service}`);- const note = tileNote(t, allowance);+ const note = allowanceNote(t, allowance);const quota = allowance.quota;const Icon = SERVICE_ICON[allowance.service] ?? MapPin;- const share = quota && quota.limit > 0 ? Math.min(100, (quota.used / quota.limit) * 100) : 100;+ const share = quota ? quotaShare(quota) : 100;// One row per service: its name, the day's use as a bar, used of the limit.return (@@ -83,7 +66,7 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-surface-tertiary"><div- className={`h-full rounded-full transition-[width] duration-500 ${barTone(quota)}`}+ className={`h-full rounded-full transition-[width] duration-500 ${BAR_TONE[quotaLevel(quota)]}`}style={{ width: `${share}%` }}/></div>@@ -91,7 +74,7 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {className="flex-none text-caption tabular-nums text-content-faint"title={`${t('admin.trekApi.quota.remaining')}: ${number.format(quota.remaining)}`}>- <span className={`font-semibold ${figureTone(quota)}`}>{number.format(quota.used)}</span>+ <span className={`font-semibold ${FIGURE_TONE[quotaLevel(quota)]}`}>{number.format(quota.used)}</span>{' / '}{number.format(quota.limit)}</span>@@ -103,11 +86,6 @@ function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {);}-function stateHint(t: TranslationFn, status: ServiceIdentityStatus | null, failed: boolean): string | null {- if (!status) return failed ? t('admin.trekApi.quota.unavailable') : null;- return status.state === 'connected' ? null : t(`admin.trekApi.quota.hint.${status.state}`);-}-/*** How this installation stands with the TREK services: whether it has its key,* and for place search, address search and routing today's allowance against@@ -121,7 +99,8 @@ export default function ServiceIdentityPanel({ managed = false }: { managed?: boconst panel = useRef<HTMLDivElement>(null);const { status, failed, regenerating, regenerate } = useServiceIdentity(panel);const [confirming, setConfirming] = useState(false);- const resetAt = useResetTime(status);+ const is12h = useSettingsStore((s) => s.settings.time_format === '12h');+ const resetAt = quotaResetClock(status, is12h);const confirmRegenerate = async () => {setConfirming(false);@@ -133,8 +112,8 @@ export default function ServiceIdentityPanel({ managed = false }: { managed?: bo}};- const hint = stateHint(t, status, failed);- const canRegenerate = !managed && status !== null && status.keySource !== 'env' && status.state !== 'off';+ const hint = identityHint(t, status, failed);+ const canRegenerate = canRegenerateKey(status, managed);return (<div ref={panel}>diff --git a/client/src/components/Admin/serviceIdentityModel.test.ts b/client/src/components/Admin/serviceIdentityModel.test.tsnew file mode 100644index 000000000..b2045908e--- /dev/null+++ b/client/src/components/Admin/serviceIdentityModel.test.ts@@ -0,0 +1,71 @@+// FE-ADMIN-SVCMODEL-001 to FE-ADMIN-SVCMODEL-006+import type { ServiceIdentityStatus } from '@trek/shared';+import { describe, expect, it } from 'vitest';+import {+ allowanceNote,+ canRegenerateKey,+ identityHint,+ quotaLevel,+ quotaResetClock,+ quotaShare,+} from './serviceIdentityModel';++const t = (key: string) => key;+const quota = (used: number, limit: number) => ({+ used,+ limit,+ remaining: limit - used,+ resetAt: '2026-11-15T01:30:00',+});+const STATUS: ServiceIdentityStatus = {+ state: 'connected',+ tier: 'std',+ keySource: 'registered',+ services: [+ { service: 'places', inUse: true, quota: quota(10, 100) },+ { service: 'photon', inUse: false, quota: null },+ ],+ lastSeenAt: null,+} as ServiceIdentityStatus;++describe('serviceIdentityModel', () => {+ it('FE-ADMIN-SVCMODEL-001: a day is ok, low below a tenth left, out at nothing left', () => {+ expect(quotaLevel(quota(10, 100))).toBe('ok');+ expect(quotaLevel(quota(95, 100))).toBe('low');+ expect(quotaLevel(quota(100, 100))).toBe('out');+ });++ it('FE-ADMIN-SVCMODEL-002: the bar share is capped at the whole and full without a limit', () => {+ expect(quotaShare(quota(25, 100))).toBe(25);+ expect(quotaShare({ used: 150, limit: 100, remaining: 0, resetAt: '' })).toBe(100);+ expect(quotaShare({ used: 0, limit: 0, remaining: 0, resetAt: '' })).toBe(100);+ });++ it('FE-ADMIN-SVCMODEL-003: the reset reads from the first counted service, in the user format', () => {+ expect(quotaResetClock(STATUS, false)).toBe('01:30');+ expect(quotaResetClock(STATUS, true)).toMatch(/1:30/);+ expect(quotaResetClock(null, false)).toBeNull();+ expect(quotaResetClock({ ...STATUS, services: [] }, false)).toBeNull();+ });++ it('FE-ADMIN-SVCMODEL-004: a service out of use, or without a count, says so', () => {+ expect(allowanceNote(t, STATUS.services[1])).toBe('admin.trekApi.quota.notInUse');+ expect(allowanceNote(t, { service: 'places', inUse: true, quota: null })).toBe('admin.trekApi.quota.unavailable');+ expect(allowanceNote(t, STATUS.services[0])).toBeNull();+ });++ it('FE-ADMIN-SVCMODEL-005: the identity line is quiet when connected', () => {+ expect(identityHint(t, STATUS, false)).toBeNull();+ expect(identityHint(t, { ...STATUS, state: 'revoked' }, false)).toBe('admin.trekApi.quota.hint.revoked');+ expect(identityHint(t, null, true)).toBe('admin.trekApi.quota.unavailable');+ expect(identityHint(t, null, false)).toBeNull();+ });++ it('FE-ADMIN-SVCMODEL-006: a new key only where the admin holds the key', () => {+ expect(canRegenerateKey(STATUS, false)).toBe(true);+ expect(canRegenerateKey(STATUS, true)).toBe(false);+ expect(canRegenerateKey({ ...STATUS, keySource: 'env' }, false)).toBe(false);+ expect(canRegenerateKey({ ...STATUS, state: 'off' }, false)).toBe(false);+ expect(canRegenerateKey(null, false)).toBe(false);+ });+});diff --git a/client/src/components/Admin/serviceIdentityModel.ts b/client/src/components/Admin/serviceIdentityModel.tsnew file mode 100644index 000000000..9acc30b2e--- /dev/null+++ b/client/src/components/Admin/serviceIdentityModel.ts@@ -0,0 +1,49 @@+import type { ServiceAllowance, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';+import type { TranslationFn } from '../../types';+import { formatClockTime } from '../../utils/formatters';++/**+ * What the allowance panels (desktop ServiceIdentityPanel, phone MAdminServiceQuota)+ * read from the service identity status. Pure, so both views show the same thing.+ */++/** How much of a service's day is left: plenty, below a tenth, or nothing. */+export type QuotaLevel = 'ok' | 'low' | 'out';++export function quotaLevel(quota: ServiceQuotaView): QuotaLevel {+ if (quota.remaining === 0) return 'out';+ return quota.remaining < quota.limit / 10 ? 'low' : 'ok';+}++/** The share of the day used, for the bar; a quota without a limit reads as full. */+export function quotaShare(quota: ServiceQuotaView): number {+ return quota.limit > 0 ? Math.min(100, (quota.used / quota.limit) * 100) : 100;+}++/** The clock time the counts start again, in the user's format; one for all services, which share the day. */+export function quotaResetClock(status: ServiceIdentityStatus | null, is12h: boolean): string | null {+ const at = status?.services.find((s) => s.quota)?.quota?.resetAt;+ if (!at) return null;+ const reset = new Date(at);+ return formatClockTime(+ `${String(reset.getHours()).padStart(2, '0')}:${String(reset.getMinutes()).padStart(2, '0')}`,+ is12h+ );+}++/** A service that is not in use, or whose count the service did not report, says so under its row. */+export function allowanceNote(t: TranslationFn, allowance: ServiceAllowance): string | null {+ if (!allowance.inUse) return t('admin.trekApi.quota.notInUse');+ return allowance.quota ? null : t('admin.trekApi.quota.unavailable');+}++/** A line about the identity itself, when it is not simply connected (or could not be read). */+export function identityHint(t: TranslationFn, status: ServiceIdentityStatus | null, failed: boolean): string | null {+ if (!status) return failed ? t('admin.trekApi.quota.unavailable') : null;+ return status.state === 'connected' ? null : t(`admin.trekApi.quota.hint.${status.state}`);+}++/** A new key can be asked for unless the operator holds it (managed, environment) or the services are off. */+export function canRegenerateKey(status: ServiceIdentityStatus | null, managed: boolean): boolean {+ return !managed && status !== null && status.keySource !== 'env' && status.state !== 'off';+}diff --git a/client/src/components/Admin/useAdminSettingsActions.test.ts b/client/src/components/Admin/useAdminSettingsActions.test.tsindex acc2a74f2..b582ad764 100644--- a/client/src/components/Admin/useAdminSettingsActions.test.ts+++ b/client/src/components/Admin/useAdminSettingsActions.test.ts@@ -13,6 +13,7 @@ const api = vi.hoisted(() => ({updatePlacesDetails: vi.fn(),updatePlacesEnrich: vi.fn(),updatePlaceShadow: vi.fn(),+ updateTransitProvider: vi.fn(),}));vi.mock('../../api/client', () => ({adminApi: {@@ -22,6 +23,7 @@ vi.mock('../../api/client', () => ({updatePlacesDetails: api.updatePlacesDetails,updatePlacesEnrich: api.updatePlacesEnrich,updatePlaceShadow: api.updatePlaceShadow,+ updateTransitProvider: api.updateTransitProvider,},authApi: { updateAppSettings: api.updateAppSettings },}));@@ -51,6 +53,9 @@ function host(over: Record<string, unknown> = {}) {setPlacesEnrichEnabled: vi.fn(),setPlaceShadowEnabledState: vi.fn(),setPlaceShadowEnabled: vi.fn(),+ transitProvider: 'transitous' as const,+ setTransitProviderState: vi.fn(),+ setTransitGoogleKeySource: vi.fn(),...over,};}@@ -140,4 +145,30 @@ describe('useAdminSettingsActions', () => {expect(admin.setPlacesDetailsEnabledState).toHaveBeenCalledWith(false);expect(admin.setPlacesEnrichEnabled).toHaveBeenCalledWith(false);});++ it('FE-HOOK-ADMSETACT-T01: switching the transit backend shows it at once and keeps the key source the server reports', async () => {+ api.updateTransitProvider.mockResolvedValueOnce({ provider: 'google', googleKeySource: 'instance' });+ const { admin, actions } = mount();+ await act(() => actions.changeTransitProvider('google'));+ expect(admin.setTransitProviderState).toHaveBeenCalledWith('google');+ expect(api.updateTransitProvider).toHaveBeenCalledWith('google');+ expect(admin.setTransitGoogleKeySource).toHaveBeenCalledWith('instance');+ });++ it('FE-HOOK-ADMSETACT-T02: picking the backend already set writes nothing', async () => {+ api.updateTransitProvider.mockClear();+ const { admin, actions } = mount();+ await act(() => actions.changeTransitProvider('transitous'));+ expect(api.updateTransitProvider).not.toHaveBeenCalled();+ expect(admin.setTransitProviderState).not.toHaveBeenCalled();+ });++ it('FE-HOOK-ADMSETACT-T03: a failed save puts the previous backend back and says why', async () => {+ api.updateTransitProvider.mockRejectedValueOnce(new Error('down'));+ const { admin, actions } = mount();+ await act(() => actions.changeTransitProvider('google'));+ expect(admin.setTransitProviderState).toHaveBeenNthCalledWith(1, 'google');+ expect(admin.setTransitProviderState).toHaveBeenNthCalledWith(2, 'transitous');+ expect(admin.toast.error).toHaveBeenCalled();+ });});diff --git a/client/src/components/Admin/useAdminSettingsActions.ts b/client/src/components/Admin/useAdminSettingsActions.tsindex 15259b474..b7fa7cfc3 100644--- a/client/src/components/Admin/useAdminSettingsActions.ts+++ b/client/src/components/Admin/useAdminSettingsActions.ts@@ -1,3 +1,4 @@+import type { TransitKeySource, TransitProvider } from '@trek/shared';import { adminApi, authApi } from '../../api/client';import type { TranslationFn } from '../../types';import { getApiErrorMessage } from '../../types';@@ -28,6 +29,9 @@ interface SettingsActionsHost {setPlacesEnrichEnabled: Flag;setPlaceShadowEnabledState: Flag;setPlaceShadowEnabled: Flag;+ transitProvider: TransitProvider;+ setTransitProviderState: (provider: TransitProvider) => void;+ setTransitGoogleKeySource: (source: TransitKeySource) => void;}/**@@ -86,9 +90,29 @@ export function useAdminSettingsActions(admin: SettingsActionsHost, t: Translati};};+ /**+ * The transit backend (#1699): shown at once, and back to the previous one with a+ * word when the save fails, so a select that springs back does not read as broken.+ * A pick of the provider already selected writes nothing: the route is audited.+ */+ const changeTransitProvider = async (value: string) => {+ if (value === admin.transitProvider) return;+ const next: TransitProvider = value === 'google' ? 'google' : 'transitous';+ const previous = admin.transitProvider;+ admin.setTransitProviderState(next);+ try {+ const saved = await adminApi.updateTransitProvider(next);+ admin.setTransitGoogleKeySource(saved.googleKeySource);+ } catch (err: unknown) {+ admin.setTransitProviderState(previous);+ toast.error(getApiErrorMessage(err, t('common.error')));+ }+ };+return {saveOidc,saveFileTypes,+ changeTransitProvider,togglePlacesPhotos: placeSwitch(admin.setPlacesPhotosEnabledState, admin.setPlacesPhotosEnabled, (enabled) =>adminApi.updatePlacesPhotos(enabled)),diff --git a/client/src/components/Admin/usePlaceContribPanel.ts b/client/src/components/Admin/usePlaceContribPanel.tsnew file mode 100644index 000000000..3b98a8eec--- /dev/null+++ b/client/src/components/Admin/usePlaceContribPanel.ts@@ -0,0 +1,79 @@+import type { PlaceContribField } from '@trek/shared';+import { useState } from 'react';+import { useTranslation } from '../../i18n';+import { getApiErrorMessage } from '../../utils/apiError';+import { useToast } from '../shared/Toast';+import { contribStatus, refusalReason } from './placeContribModel';+import { usePlaceContrib } from './usePlaceContrib';++/**+ * What the share-place-details panels (desktop PlaceContribPanel, phone+ * MAdminPlaceContrib) do: the main switch (on asks for consent first, off asks+ * to confirm), one switch per field (switching the last one off is switching the+ * whole thing off), withdrawing what was shared, and the words for a refusal.+ */+export function usePlaceContribPanel({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean } = {}) {+ const { t } = useTranslation();+ const toast = useToast();+ const contrib = usePlaceContrib();+ const { state } = contrib;+ const [prompting, setPrompting] = useState<boolean | null>(null);+ const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);++ const fail = (err: unknown) => {+ const reason = refusalReason(err);+ toast.error(+ reason === 'terms_outdated' || reason === 'no_field'+ ? t(`admin.contribute.refused.${reason}`)+ : getApiErrorMessage(err, t('common.error'))+ );+ };++ // Shown on its own (a managed install), a switch the environment turned off is+ // no decision of the admin's, so the panel stays away.+ const hidden = !state || (hideWhenSwitchedOff && state.ineligibleReason === 'env_off');+ const agreed = !!state && state.consent.decision === 'agreed' && state.consent.termsVersion === state.termsVersion;+ const on = agreed && !!state?.consent.enabled;++ const toggleField = (field: PlaceContribField) => {+ if (!state) return;+ const fields = { ...state.consent.fields, [field]: !state.consent.fields[field] };+ if (!Object.values(fields).some(Boolean)) {+ setConfirm('off');+ return;+ }+ contrib.decide({ action: 'fields', fields }).catch(fail);+ };++ const switchOff = () => {+ setConfirm(null);+ contrib.decide({ action: 'off' }).catch(fail);+ };++ const withdraw = () => {+ setConfirm(null);+ contrib.withdraw().then((r) => {+ const total = Object.values(r.withdrawn).reduce((a, b) => a + b, 0);+ toast.success(t('admin.contribute.withdrawn', { total }));+ }, fail);+ };++ return {+ contrib,+ state,+ hidden,+ status: state ? contribStatus(state) : null,+ agreed,+ on,+ /** The log and the withdraw action: once agreed, and still after switching off. */+ showLog: agreed || state?.consent.decision === 'off',+ showPrompt: !!state && (prompting ?? state.showPrompt) && state.eligible,+ toggleMain: () => (on ? setConfirm('off') : setPrompting(true)),+ closePrompt: () => setPrompting(false),+ confirm,+ setConfirm,+ toggleField,+ switchOff,+ withdraw,+ };+}diff --git a/client/src/mobile/screens/admin/MAdminGoogleDailyLimit.tsx b/client/src/mobile/screens/admin/MAdminGoogleDailyLimit.tsxnew file mode 100644index 000000000..3ab18550e--- /dev/null+++ b/client/src/mobile/screens/admin/MAdminGoogleDailyLimit.tsx@@ -0,0 +1,63 @@+import { Check } from 'lucide-react';+import { useGoogleQuota } from '../../../components/Admin/useGoogleQuota';+import { NumericInput } from '../../../components/shared/NumericInput';+import { useTranslation } from '../../../i18n';+import MHintLabel from '../../components/MHintLabel';+import { MAdminButton } from './MAdminUi';++/**+ * The daily cap on Google requests, the phone's form of the desktop+ * GoogleDailyLimitRow: today's count under the name (in the warning colour once+ * the day is used up), the cap in a small field, and a save while it differs.+ */+export default function MAdminGoogleDailyLimit() {+ const { t } = useTranslation();+ const { status, draft, setDraft, dirty, saving, save } = useGoogleQuota();++ let today: string | null = null;+ if (status) {+ if (status.exhausted) today = t('admin.googleQuota.reached', { used: status.used_today });+ else if (status.daily_limit == null) today = t('admin.googleQuota.usedToday', { used: status.used_today });+ else today = t('admin.googleQuota.usedOfLimit', { used: status.used_today, limit: status.daily_limit });+ }++ return (+ <div+ className={`flex items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[11px] ${saving ? 'opacity-60' : ''}`}+ >+ <div className="min-w-0 flex-1">+ <MHintLabel label={t('admin.googleQuota.title')} hint={t('admin.googleQuota.subtitle')} />+ {today && (+ <p+ className={`mt-[1px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] tabular-nums ${+ status?.exhausted ? 'text-[color:var(--m-st-pending)]' : 'text-m-muted'+ }`}+ >+ {today}+ </p>+ )}+ </div>+ <NumericInput+ aria-label={t('admin.googleQuota.title')}+ mode="integer"+ value={draft}+ onValueChange={setDraft}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ void save();+ }+ }}+ placeholder={t('admin.googleQuota.placeholder')}+ disabled={status === null || saving}+ className="h-[34px] w-[88px] flex-none rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-end font-geist text-[length:calc(12.5px*var(--fs-scale-body,1))] tabular-nums text-m-ink outline-none placeholder:text-m-faint"+ />+ {dirty && (+ <MAdminButton busy={saving} onClick={() => void save()}>+ {!saving && <Check size={12} strokeWidth={2.4} />}+ {t('common.save')}+ </MAdminButton>+ )}+ </div>+ );+}diff --git a/client/src/mobile/screens/admin/MAdminPlaceContrib.tsx b/client/src/mobile/screens/admin/MAdminPlaceContrib.tsxnew file mode 100644index 000000000..ae5ee2ad2--- /dev/null+++ b/client/src/mobile/screens/admin/MAdminPlaceContrib.tsx@@ -0,0 +1,124 @@+import { Undo2 } from 'lucide-react';+import PlaceContribLog from '../../../components/Admin/PlaceContribLog';+import PlaceContribPrompt from '../../../components/Admin/PlaceContribPrompt';+import { contribNote, fieldEntries, fieldLabel, type ContribStatus } from '../../../components/Admin/placeContribModel';+import { usePlaceContribPanel } from '../../../components/Admin/usePlaceContribPanel';+import { useTranslation } from '../../../i18n';+import MToggle from '../../components/MToggle';+import MConfirmSheet from '../settings/MConfirmSheet';+import { MAdminButton, MAdminNote, MAdminRow } from './MAdminUi';++const STATUS_TONE: Record<ContribStatus, string> = {+ active: 'text-[color:var(--m-st-confirmed)]',+ paused: 'text-[color:var(--m-st-pending)]',+ off: 'text-m-muted',+ unavailable: 'text-m-muted',+};++/**+ * Sharing place details with the TREK Places API, the phone's form of the+ * desktop PlaceContribPanel: one switch for the installation (on asks for+ * consent first), one per field, the figures, the transmission log and the way+ * to take everything back. The logic is usePlaceContribPanel, shared with it.+ */+export default function MAdminPlaceContrib({ hideWhenSwitchedOff = false }: { hideWhenSwitchedOff?: boolean }) {+ const { t, locale } = useTranslation();+ const panel = usePlaceContribPanel({ hideWhenSwitchedOff });+ const { contrib, state, status, on, confirm, setConfirm } = panel;+ if (panel.hidden || !state || !status) return null;++ const number = new Intl.NumberFormat(locale);+ const last = state.lastSuccessDay+ ? new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(+ new Date(`${state.lastSuccessDay}T12:00:00`)+ )+ : t('admin.contribute.never');++ return (+ <div className="rounded-[16px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[14px] py-1">+ <MAdminRow+ first+ title={+ <span className="inline-flex max-w-full items-center gap-[6px]">+ <span className="min-w-0">{t('admin.contribute.title')}</span>+ <span+ className={`flex-none font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold ${STATUS_TONE[status]}`}+ >+ {t(`admin.contribute.status.${status}`)}+ </span>+ </span>+ }+ hint={contribNote(t, state)}+ trailing={+ <MToggle+ checked={on}+ ariaLabel={t('admin.contribute.title')}+ disabled={!state.eligible || contrib.busy}+ onChange={panel.toggleMain}+ />+ }+ />++ {on && (+ <>+ <MAdminNote>+ {[+ `${t('admin.contribute.figure.accepted')} ${number.format(state.counts.accepted)}`,+ `${t('admin.contribute.figure.queue')} ${number.format(state.queue.size)}`,+ `${t('admin.contribute.figure.last')} ${last}`,+ ].join(', ')}+ </MAdminNote>+ {state.queue.full && <MAdminNote warn>{t('admin.contribute.figure.queueFull')}</MAdminNote>}+ {fieldEntries(state.consent.fields).map(([field, fieldOn]) => (+ <MAdminRow+ key={field}+ title={fieldLabel(t, field)}+ trailing={+ <MToggle+ checked={fieldOn}+ ariaLabel={fieldLabel(t, field)}+ disabled={contrib.busy}+ onChange={() => panel.toggleField(field)}+ />+ }+ />+ ))}+ </>+ )}++ {panel.showLog && (+ <div className="space-y-2 border-t border-[color:var(--m-rowbr)] py-[11px]">+ <div className="text-[length:calc(12.5px*var(--fs-scale-body,1))] font-bold text-m-ink">+ {t('admin.contribute.log.title')}+ </div>+ <PlaceContribLog />+ <MAdminButton variant="ghost" disabled={contrib.busy} onClick={() => setConfirm('withdraw')}>+ <Undo2 size={12} strokeWidth={2.2} />+ {t('admin.contribute.withdraw')}+ </MAdminButton>+ </div>+ )}++ {panel.showPrompt && <PlaceContribPrompt state={state} contrib={contrib} onClose={panel.closePrompt} />}+ <MConfirmSheet+ open={confirm === 'off'}+ onClose={() => setConfirm(null)}+ title={t('admin.contribute.offTitle')}+ message={t('admin.contribute.offMessage')}+ confirmLabel={t('admin.contribute.offConfirm')}+ cancelLabel={t('common.cancel')}+ onConfirm={panel.switchOff}+ />+ <MConfirmSheet+ open={confirm === 'withdraw'}+ onClose={() => setConfirm(null)}+ title={t('admin.contribute.withdrawTitle')}+ message={t('admin.contribute.withdrawMessage')}+ confirmLabel={t('admin.contribute.withdraw')}+ cancelLabel={t('common.cancel')}+ danger+ onConfirm={panel.withdraw}+ />+ </div>+ );+}diff --git a/client/src/mobile/screens/admin/MAdminServiceQuota.tsx b/client/src/mobile/screens/admin/MAdminServiceQuota.tsxnew file mode 100644index 000000000..58098362c--- /dev/null+++ b/client/src/mobile/screens/admin/MAdminServiceQuota.tsx@@ -0,0 +1,170 @@+import type { ServiceAllowance, ServiceIdentityState, ServiceIdentityStatus } from '@trek/shared';+import { MapPin, RefreshCw, Route, Search, type LucideIcon } from 'lucide-react';+import { useRef, useState } from 'react';+import {+ allowanceNote,+ canRegenerateKey,+ identityHint,+ quotaLevel,+ quotaResetClock,+ quotaShare,+ type QuotaLevel,+} from '../../../components/Admin/serviceIdentityModel';+import { useServiceIdentity } from '../../../components/Admin/useServiceIdentity';+import { useToast } from '../../../components/shared/Toast';+import { useTranslation } from '../../../i18n';+import { useSettingsStore } from '../../../store/settingsStore';+import type { TranslationFn } from '../../../types';+import { getApiErrorMessage } from '../../../utils/apiError';+import MConfirmSheet from '../settings/MConfirmSheet';+import { MAdminButton } from './MAdminUi';++const STATE_DOT: Record<ServiceIdentityState, string> = {+ connected: 'bg-[color:var(--m-st-confirmed)]',+ registering: 'bg-[color:var(--m-st-pending)] motion-safe:animate-pulse',+ legacy: 'bg-[color:var(--m-faint)]',+ off: 'bg-[color:var(--m-faint)]',+ revoked: 'bg-[color:var(--m-st-danger)]',+};+const BAR: Record<QuotaLevel, string> = {+ ok: 'bg-m-act',+ low: 'bg-[color:var(--m-st-pending)]',+ out: 'bg-[color:var(--m-st-danger)]',+};+const FIGURE: Record<QuotaLevel, string> = {+ ok: 'text-m-ink',+ low: 'text-[color:var(--m-st-pending)]',+ out: 'text-[color:var(--m-st-danger)]',+};+const SERVICE_ICON: Record<string, LucideIcon> = { places: MapPin, photon: Search, valhalla: Route };++/** The tier, an operator key from the environment and the reset, as one quiet line (the desktop's badges). */+function quotaMeta(t: TranslationFn, status: ServiceIdentityStatus | null, resetAt: string | null): string {+ if (!status) return '';+ const parts = [+ status.tier ? t(`admin.trekApi.quota.tier.${status.tier}`) : null,+ status.keySource === 'env' ? `${t('admin.trekApi.quota.key')}: TREK_SERVICES_KEY` : null,+ resetAt ? `${t('admin.trekApi.quota.resets')} ${resetAt}` : null,+ ];+ return parts.filter(Boolean).join(', ');+}++function MQuotaRow({ allowance }: { allowance: ServiceAllowance }) {+ const { t, locale } = useTranslation();+ const number = new Intl.NumberFormat(locale);+ const name = t(`admin.trekApi.quota.service.${allowance.service}`);+ const note = allowanceNote(t, allowance);+ const quota = allowance.quota;+ const Icon = SERVICE_ICON[allowance.service] ?? MapPin;+ return (+ <li className={`py-[9px] ${allowance.inUse ? '' : 'opacity-60'}`}>+ <div className="flex items-center gap-2">+ <Icon size={13} strokeWidth={2} aria-hidden className="flex-none text-m-faint" />+ <span className="min-w-0 flex-1 truncate text-[length:calc(12px*var(--fs-scale-body,1))] font-bold text-m-ink">+ {name}+ </span>+ {quota && (+ <span className="flex-none font-geist text-[length:calc(10.5px*var(--fs-scale-caption,1))] tabular-nums text-m-faint">+ <span className={`font-bold ${FIGURE[quotaLevel(quota)]}`}>{number.format(quota.used)}</span>+ {' / '}+ {number.format(quota.limit)}+ </span>+ )}+ </div>+ {quota && (+ <div+ role="progressbar"+ aria-label={name}+ aria-valuemin={0}+ aria-valuemax={quota.limit}+ aria-valuenow={quota.used}+ className="mt-[6px] h-[5px] overflow-hidden rounded-full bg-[color:var(--m-rowbr)]"+ >+ <div className={`h-full rounded-full ${BAR[quotaLevel(quota)]}`} style={{ width: `${quotaShare(quota)}%` }} />+ </div>+ )}+ {note && (+ <p className="mt-[3px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-snug text-m-muted">+ {note}+ </p>+ )}+ </li>+ );+}++/**+ * How this installation stands with the TREK services, the phone's form of the+ * desktop ServiceIdentityPanel: its state, today's use per service against the+ * allowance, when the count starts again, and a new key when the old one leaked.+ * Read while in view and refreshed every 30 seconds (useServiceIdentity).+ */+export default function MAdminServiceQuota({ managed = false }: { managed?: boolean }) {+ const { t } = useTranslation();+ const toast = useToast();+ const panel = useRef<HTMLDivElement>(null);+ const { status, failed, regenerating, regenerate } = useServiceIdentity(panel);+ const [confirming, setConfirming] = useState(false);+ const is12h = useSettingsStore((s) => s.settings.time_format === '12h');+ const resetAt = quotaResetClock(status, is12h);+ const hint = identityHint(t, status, failed);+ const meta = quotaMeta(t, status, resetAt);++ const confirmRegenerate = async () => {+ setConfirming(false);+ try {+ await regenerate();+ toast.success(t('admin.trekApi.quota.regenerated'));+ } catch (err) {+ toast.error(getApiErrorMessage(err, t('common.error')));+ }+ };++ return (+ <div+ ref={panel}+ className="rounded-[16px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[14px] py-3"+ >+ <div className="flex items-center gap-2">+ <span className="min-w-0 flex-1 truncate text-[length:calc(13px*var(--fs-scale-body,1))] font-bold text-m-ink">+ {t('admin.trekApi.quota.title')}+ </span>+ <span className="inline-flex flex-none items-center gap-[5px] rounded-full bg-[color:var(--m-sheetop)] px-2 py-[2px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold text-m-ink">+ <span aria-hidden className={`h-[7px] w-[7px] rounded-full ${STATE_DOT[status?.state ?? 'off']}`} />+ {status ? t(`admin.trekApi.quota.state.${status.state}`) : '…'}+ </span>+ </div>+ {meta && (+ <p className="mt-[3px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] text-m-muted">{meta}</p>+ )}+ {status && status.services.length > 0 && (+ <ul aria-label={t('admin.trekApi.quota.title')} className="mt-1 divide-y divide-[color:var(--m-rowbr)]">+ {status.services.map((allowance) => (+ <MQuotaRow key={allowance.service} allowance={allowance} />+ ))}+ </ul>+ )}+ {hint && (+ <p className="mt-1 font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-snug text-m-muted">+ {hint}+ </p>+ )}+ {canRegenerateKey(status, managed) && (+ <div className="mt-2 flex justify-end">+ <MAdminButton variant="ghost" busy={regenerating} onClick={() => setConfirming(true)}>+ {!regenerating && <RefreshCw size={12} strokeWidth={2.2} />}+ {t('admin.trekApi.quota.regenerate')}+ </MAdminButton>+ </div>+ )}+ <MConfirmSheet+ open={confirming}+ onClose={() => setConfirming(false)}+ title={t('admin.trekApi.quota.regenerateTitle')}+ message={t('admin.trekApi.quota.regenerateBody')}+ confirmLabel={t('admin.trekApi.quota.regenerate')}+ cancelLabel={t('common.cancel')}+ onConfirm={() => void confirmRegenerate()}+ />+ </div>+ );+}diff --git a/client/src/mobile/screens/admin/MAdminSettingsSection.tsx b/client/src/mobile/screens/admin/MAdminSettingsSection.tsxindex 01abc962c..ecec506d7 100644--- a/client/src/mobile/screens/admin/MAdminSettingsSection.tsx+++ b/client/src/mobile/screens/admin/MAdminSettingsSection.tsx@@ -1,5 +1,4 @@-import { useState } from 'react'-import { AlertTriangle, ChevronDown, RefreshCw } from 'lucide-react'+import { AlertTriangle, RefreshCw } from 'lucide-react'import { useAdminSettingsActions } from '../../../components/Admin/useAdminSettingsActions'import { placesGoogleOnlyHint } from '../../../utils/placeSource'import type { TranslationFn } from '../../../types'@@ -8,15 +7,19 @@ import MToggle from '../../components/MToggle'import { MBlockDisclosure, MProviderBlock, MTrekApiBlock } from './MApiProviderBlocks'import MAdminOidcCard from './MAdminOidcCard'import MMailIngestAdminCard from './MMailIngestAdminCard'-import MSetPickerSheet from '../settings/MSetPickerSheet'+import MAdminGoogleDailyLimit from './MAdminGoogleDailyLimit'+import MAdminPlaceContrib from './MAdminPlaceContrib'+import MAdminServiceQuota from './MAdminServiceQuota'import {MAdminButton,MAdminCard,MAdminCardHead,MAdminField,MAdminInput,+ MAdminNote,MAdminRow,MAdminSecretInput,+ MAdminSelect,} from './MAdminUi'interface MAdminSettingsSectionProps {@@ -30,52 +33,50 @@ interface MAdminSettingsSectionProps {part: 'security' | 'services' | 'features'}-// The admin's security, services and feature setup sections as phone cards.-// All state and mutations come from useAdmin.+type PartProps = Omit<MAdminSettingsSectionProps, 'part'>++// The admin's security, services and feature setup sections as phone cards,+// one function each. All state and mutations come from useAdmin.export default function MAdminSettingsSection({ admin, t, part }: MAdminSettingsSectionProps) {- const [providerPickerOpen, setProviderPickerOpen] = useState(false)+ if (part === 'features') return <FeaturesPart admin={admin} t={t} />+ if (part === 'security') return <SecurityPart admin={admin} t={t} />+ return <ServicesPart admin={admin} t={t} />+}++/** Live flights and booking mails: how the integrations of the addons tab reach the world. */+function FeaturesPart({ admin, t }: PartProps) {+ const { managed, flightLive, setFlightLive, flightLiveLocked, handleToggleAuthSetting } = admin+ return (+ <div className="space-y-3">+ {/* Live flight status: open ADS-B data, no key, on by default (desktop parity). */}+ <FlightLiveCard+ t={t}+ managed={!!managed}+ on={flightLive}+ locked={flightLiveLocked}+ onChange={(v) => void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)}+ />+ {/* Booking mail import: self-hosted only, the operator runs the TREK Cloud relay (desktop parity). */}+ {!managed && <MMailIngestAdminCard />}+ </div>+ )+}++/** Who may sign in and what it takes, with the one destructive action last. */+function SecurityPart({ admin, t }: PartProps) {const {- placesPhotosEnabled, placesAutocompleteEnabled, placesDetailsEnabled, placesEnrichEnabled,- placesGoogleOnly, handleTogglePlacesGoogleOnly,- placeShadowEnabled,passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration, oidcAutoRedirect, setOidcAutoRedirect,- flightLive, setFlightLive, flightLiveLocked,envOverrideOidcOnly, oidcConfigured, requireMfa,passkeyLogin, setPasskeyLogin, passkeyConfigured,webauthnRpId, setWebauthnRpId, webauthnOrigins, setWebauthnOrigins, savingWebauthn, handleSaveWebauthn,- allowedFileTypes, setAllowedFileTypes, savingFileTypes,- mapsKey, setMapsKey, unsplashKey, setUnsplashKey, amapKey, setAmapKey, hasMapsKey, hasAmapKey, keyInputProps, mapsKeyTestable, savingKeys, validating, validation,- placesProvider, savingPlacesProvider, handleSavePlacesProvider,managed,setShowRotateJwtModal,handleToggleAuthSetting, handleToggleRequireMfa,- handleSaveApiKeys, handleValidateKey,} = admin+ const { saveOidc } = useAdminSettingsActions(admin, t)- const {- saveOidc, saveFileTypes, togglePlacesPhotos, togglePlacesAutocomplete, togglePlacesDetails, togglePlacesEnrich,- togglePlaceShadow,- } = useAdminSettingsActions(admin, t)-- if (part === 'features') {- return (- <div className="space-y-3">- {/* Live flight status: open ADS-B data, no key, on by default (desktop parity). */}- <FlightLiveCard- t={t}- managed={!!managed}- on={flightLive}- locked={flightLiveLocked}- onChange={(v) => void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)}- />- {/* Booking mail import: self-hosted only, the operator runs the TREK Cloud relay (desktop parity). */}- {!managed && <MMailIngestAdminCard />}- </div>- )- }-- if (part === 'security') return (+ return (<div className="space-y-3">{/* Authentication methods, with the passkey switch and the 2FA rule: they are ways in too. */}<MAdminCard>@@ -230,30 +231,117 @@ export default function MAdminSettingsSection({ admin, t, part }: MAdminSettings)}</div>)+}- // Services: what the install talks to outside, and the file types it takes.+/** What the install talks to outside: place search and routing, the keys, the file types. */+function ServicesPart({ admin, t }: PartProps) {+ const {+ placesPhotosEnabled, placesAutocompleteEnabled, placesDetailsEnabled, placesEnrichEnabled,+ placesGoogleOnly, handleTogglePlacesGoogleOnly,+ placeShadowEnabled,+ transitProvider, transitGoogleKeySource,+ allowedFileTypes, setAllowedFileTypes, savingFileTypes,+ mapsKey, setMapsKey, unsplashKey, setUnsplashKey, amapKey, setAmapKey, hasMapsKey, hasAmapKey, keyInputProps, mapsKeyTestable, savingKeys, validating, validation,+ placesProvider, savingPlacesProvider, handleSavePlacesProvider,+ managed,+ handleSaveApiKeys, handleValidateKey,+ } = admin+ const {+ saveFileTypes, togglePlacesPhotos, togglePlacesAutocomplete, togglePlacesDetails, togglePlacesEnrich,+ togglePlaceShadow, changeTransitProvider,+ } = useAdminSettingsActions(admin, t)++ // Services, cut like the desktop tab: place search and routing (TREK's own+ // services, which provider answers what, the search log), then the keys for+ // the keyed providers, then the file types.+ const providerMissingKey = (placesProvider === 'google' && !hasMapsKey) || (placesProvider === 'amap' && !hasAmapKey)return (<div className="space-y-3">- {/* API keys, place search and routing: the operator's on a managed install,- same as the desktop tab, so the whole card is left out. Unlike the desktop- tab, the phone has no share place details section for a managed install. */}+ {/* On a managed install place search and routing are the operator's, but+ sharing place details stays the admin's decision, as on the desktop. */}+ {managed && <MAdminPlaceContrib hideWhenSwitchedOff />}+{!managed && (<MAdminCard>- <MAdminCardHead title={t('admin.apiKeys')} hint={t('admin.apiKeysHint')} />+ <MAdminCardHead title={t('admin.servicesCard.title')} hint={t('admin.servicesCard.hint')} /><div className="space-y-3">- {/* Comparable blocks in the order we would have somebody choose them,- matching the desktop tab: the free source first, the keys after it.- The recommendation used to sit on the Google field here, which told- a phone admin the opposite of what the same setting says on a- laptop. */}<MTrekApiBlock />+ <MAdminServiceQuota />+ <MAdminPlaceContrib />+ {/* Transit backend (#1699): Transitous has no GTFS for much of Asia, so an+ install can send transit search to Google on the same key. */}+ <MAdminField label={t('admin.transitProvider.title')} hint={t('admin.transitProvider.subtitle')}>+ <MAdminSelect+ title={t('admin.transitProvider.title')}+ value={transitProvider}+ onChange={(value) => void changeTransitProvider(value)}+ options={[+ { value: 'transitous', label: t('admin.transitProvider.transitous') },+ { value: 'google', label: t('admin.transitProvider.google') },+ ]}+ />+ <MAdminNote>+ {transitProvider === 'google' ? t('admin.transitProvider.googleHint') : t('admin.transitProvider.transitousHint')}+ </MAdminNote>+ {/* Google without a key that resolves changes nothing, and a personal key+ serves this admin alone: the request-time fallback is silent, so here+ is the only place to say it. */}+ {transitProvider === 'google' && transitGoogleKeySource === null && (+ <MAdminNote warn>{t('admin.transitProvider.noKeyWarning')}</MAdminNote>+ )}+ {transitProvider === 'google' && transitGoogleKeySource === 'user-row' && (+ <MAdminNote warn>{t('admin.transitProvider.personalKeyWarning')}</MAdminNote>+ )}+ </MAdminField>++ {/* Which keyed provider answers place search. */}+ <MAdminField label={t('admin.placesProvider.title')} hint={t('admin.placesProvider.subtitle')}>+ <MAdminSelect+ title={t('admin.placesProvider.title')}+ value={placesProvider}+ disabled={savingPlacesProvider}+ onChange={(value) => void handleSavePlacesProvider(value)}+ options={[+ { value: 'auto', label: t('admin.placesProvider.auto') },+ { value: 'google', label: t('admin.placesProvider.google') },+ { value: 'amap', label: t('admin.placesProvider.amap') },+ { value: 'openstreetmap', label: t('admin.placesProvider.openstreetmap') },+ ]}+ />+ {/* From app-config, like the desktop card: the key fields are empty+ on a managed install and on an operator key set by environment. */}+ {providerMissingKey && <MAdminNote warn>{t('admin.placesProvider.missingKey')}</MAdminNote>}+ </MAdminField>++ {/* The instance's own search log, which is not Google's to spend. */}+ <div>+ <MAdminRow+ first+ title={t('admin.placeShadow.title')}+ hint={t('admin.placeShadow.subtitle')}+ trailing={+ <MToggle+ checked={placeShadowEnabled}+ ariaLabel={t('admin.placeShadow.title')}+ onChange={togglePlaceShadow}+ />+ }+ />+ </div>+ </div>+ </MAdminCard>+ )}++ {/* The keys of the keyed providers, in the desktop order: Google, Unsplash, Amap. */}+ {!managed && (+ <MAdminCard>+ <MAdminCardHead title={t('admin.apiKeys')} hint={t('admin.apiKeysHint')} />+ <div className="space-y-3"><MProviderBlock title={t('admin.mapsKey')} badge={t('admin.googleCaveat.badge')} tone="caution">{/* Said before the field, not after it: somebody about to paste a keyshould read this while deciding, not once they already have. */}- <p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">- {t('admin.mapsKeyHintShort')}- </p>+ <MAdminNote>{t('admin.mapsKeyHintShort')}</MAdminNote><div className="flex gap-2"><div className="min-w-0 flex-1"><MAdminSecretInput@@ -274,18 +362,17 @@ export default function MAdminSettingsSection({ admin, t, part }: MAdminSettings</MAdminButton></div>{validation.maps === true && (- <p className="font-geist text-[0.625rem] font-bold text-[color:var(--m-st-confirmed)]">+ <p className="font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold text-[color:var(--m-st-confirmed)]">{t('admin.keyValid')}</p>)}{validation.maps === false && (- <p className="font-geist text-[0.625rem] font-bold text-[color:var(--m-st-danger)]">+ <p className="font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold text-[color:var(--m-st-danger)]">{t('admin.keyInvalid')}</p>)}- {/* What the key is allowed to be spent on. Under the key rather than- loose at the foot of the card: every one of them is a Google- request, and none of them mean anything without it. */}+ {/* What the key may be spent on, and how much of it a day. Under the key:+ every one of them is a Google request. */}<MBlockDisclosure label={t('admin.placesUsageTitle')}><MAdminRowtitle={t('admin.placesPhotos.title')}@@ -342,23 +429,12 @@ export default function MAdminSettingsSection({ admin, t, part }: MAdminSettings/>}/>+ <MAdminGoogleDailyLimit /></MBlockDisclosure></MProviderBlock>- {/* No Test button, same as the desktop tab: /auth/validate-keys only- knows how to probe Google Places and OpenWeatherMap. */}- <MProviderBlock title={t('admin.amapKey')}>- <p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">{t('admin.amapKeyHintShort')}</p>- <MAdminSecretInput- aria-label={t('admin.amapKey')}- value={amapKey}- onChange={(e) => setAmapKey(e.target.value)}- {...keyInputProps('amap')}- />- </MProviderBlock>-<MProviderBlock title={t('admin.unsplashKey')}>- <p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">{t('admin.unsplashKeyHint')}</p>+ <MAdminNote>{t('admin.unsplashKeyHint')}</MAdminNote><MAdminSecretInputaria-label={t('admin.unsplashKey')}value={unsplashKey}@@ -367,56 +443,17 @@ export default function MAdminSettingsSection({ admin, t, part }: MAdminSettings/></MProviderBlock>- <MAdminField label={t('admin.placesProvider.title')} hint={t('admin.placesProvider.subtitle')}>- {/* The app's own picker rather than a bare <select>: a native one is- drawn by the operating system and was the one control on this page- that did not belong to TREK. Same sheet the settings selects use. */}- <button- type="button"- disabled={savingPlacesProvider}- onClick={() => setProviderPickerOpen(true)}- className="flex h-[42px] w-full items-center gap-2 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-start text-[0.84375rem] text-m-ink disabled:opacity-50"- >- <span className="min-w-0 flex-1 truncate">{t(`admin.placesProvider.${placesProvider}`)}</span>- <ChevronDown size={15} strokeWidth={2.2} className="flex-none text-m-faint" aria-hidden />- </button>- <MSetPickerSheet- open={providerPickerOpen}- onClose={() => setProviderPickerOpen(false)}- title={t('admin.placesProvider.title')}- value={placesProvider}- onSelect={(value) => { if (value !== placesProvider) void handleSavePlacesProvider(value) }}- options={[- { value: 'auto', label: t('admin.placesProvider.auto') },- { value: 'google', label: t('admin.placesProvider.google') },- { value: 'amap', label: t('admin.placesProvider.amap') },- { value: 'openstreetmap', label: t('admin.placesProvider.openstreetmap') },- ]}- />- {/* From app-config, like the desktop card: the key fields are empty- on a managed install and on an operator key set by environment. */}- {((placesProvider === 'google' && !hasMapsKey) || (placesProvider === 'amap' && !hasAmapKey)) && (- <p className="mt-1 font-geist text-[0.625rem] font-bold text-[color:var(--m-st-pending)]">- {t('admin.placesProvider.missingKey')}- </p>- )}- </MAdminField>-- <div>- {/* The instance's own search log, which is not Google's to spend. */}- <MAdminRow- first- title={t('admin.placeShadow.title')}- hint={t('admin.placeShadow.subtitle')}- trailing={- <MToggle- checked={placeShadowEnabled}- ariaLabel={t('admin.placeShadow.title')}- onChange={togglePlaceShadow}- />- }+ {/* No Test button, same as the desktop tab: /auth/validate-keys only+ knows how to probe Google Places and OpenWeatherMap. */}+ <MProviderBlock title={t('admin.amapKey')}>+ <MAdminNote>{t('admin.amapKeyHintShort')}</MAdminNote>+ <MAdminSecretInput+ aria-label={t('admin.amapKey')}+ value={amapKey}+ onChange={(e) => setAmapKey(e.target.value)}+ {...keyInputProps('amap')}/>- </div>+ </MProviderBlock><MAdminButton busy={savingKeys} onClick={handleSaveApiKeys}>{t('common.save')}diff --git a/client/src/mobile/screens/admin/MAdminUi.tsx b/client/src/mobile/screens/admin/MAdminUi.tsxindex 744ca4c03..89d970488 100644--- a/client/src/mobile/screens/admin/MAdminUi.tsx+++ b/client/src/mobile/screens/admin/MAdminUi.tsx@@ -80,10 +80,23 @@ export function MAdminClampedText({ children, className = '' }: { children: stri)}+/** A short line in a card body: a fact under a control, or (warn) what a setting will not do as things stand. */+export function MAdminNote({ warn = false, children }: { warn?: boolean; children: ReactNode }) {+ return (+ <p+ className={`mt-[5px] font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-relaxed ${+ warn ? 'font-bold text-[color:var(--m-st-pending)]' : 'text-m-muted'+ }`}+ >+ {children}+ </p>+ )+}+/** Labelled form field; its hint waits behind the label's info mark. */export function MAdminField({ label, hint, children }: { label: ReactNode; hint?: ReactNode; children: ReactNode }) {return (- <div>+ <div data-m-field=""><div className="mb-[5px]"><MHintLabellabel={label}diff --git a/client/src/pages/admin/AdminSettingsTab.test.tsx b/client/src/pages/admin/AdminSettingsTab.test.tsxindex eef0ca0d9..746024a01 100644--- a/client/src/pages/admin/AdminSettingsTab.test.tsx+++ b/client/src/pages/admin/AdminSettingsTab.test.tsx@@ -100,7 +100,7 @@ describe('AdminSettingsTab', () => {expect(screen.getByRole('heading', { name: 'Authentication Methods' })).toBeInTheDocument();expect(screen.getByRole('heading', { name: 'Passkey login' })).toBeInTheDocument();// Requiring two-factor is a switch of the sign-in card now, not a card of its own.- expect(screen.getByText(/require two-factor/i)).toBeInTheDocument();+ expect(screen.getByText(/require 2fa/i)).toBeInTheDocument();expect(screen.getByRole('heading', { name: 'Allowed File Types' })).toBeInTheDocument();expect(screen.getByRole('heading', { name: 'API Keys' })).toBeInTheDocument();expect(screen.getByRole('heading', { name: /single sign-on/i })).toBeInTheDocument();diff --git a/client/src/pages/admin/AdminSettingsTab.tsx b/client/src/pages/admin/AdminSettingsTab.tsxindex 205653dc0..302e34781 100644--- a/client/src/pages/admin/AdminSettingsTab.tsx+++ b/client/src/pages/admin/AdminSettingsTab.tsx@@ -1,6 +1,4 @@import React from 'react'-import { adminApi } from '../../api/client'-import { getApiErrorMessage } from '../../types'import {AlertTriangle, CheckCircle, Compass, Eye, EyeOff, FileType, Fingerprint, KeyRound, Loader2, LockKeyhole, LogIn,Plane, RefreshCw, Save, XCircle,@@ -120,11 +118,10 @@ function SaveBar({ onClick, saving, label }: { onClick: () => void; saving: bool// "Settings" tab. Pure layout around the useAdmin hook.export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabProps): React.ReactElement {const {- toast,placesPhotosEnabled, placesAutocompleteEnabled, placesDetailsEnabled, placesEnrichEnabled,placesGoogleOnly, handleTogglePlacesGoogleOnly,- transitProvider, setTransitProviderState,- transitGoogleKeySource, setTransitGoogleKeySource,+ transitProvider,+ transitGoogleKeySource,placeShadowEnabled,oidcConfig, setOidcConfig, savingOidc,passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,@@ -143,7 +140,7 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabPro} = adminconst {saveOidc, saveFileTypes, togglePlacesPhotos, togglePlacesAutocomplete, togglePlacesDetails, togglePlacesEnrich,- togglePlaceShadow,+ togglePlaceShadow, changeTransitProvider,} = useAdminSettingsActions(admin, t)const passwordLoginLocked = !passwordLogin && !oidcLogin@@ -452,24 +449,7 @@ export default function AdminSettingsTab({ admin, t, part }: AdminSettingsTabProthe body, which is what lets it escape the card's overflow-hidden. */}<CustomSelectvalue={transitProvider}- onChange={async value => {- // A native select stayed silent when the option already selected was- // picked again; this one reports every pick, and a no-op PUT is still- // a write on an audited settings route.- if (value === transitProvider) return- const next = value === 'google' ? 'google' : 'transitous'- const previous = transitProvider- setTransitProviderState(next)- try {- const saved = await adminApi.updateTransitProvider(next)- setTransitGoogleKeySource(saved.googleKeySource)- } catch (err: unknown) {- // The select springs back on its own; without a word that reads- // as a broken control, not as a save that failed.- setTransitProviderState(previous)- toast.error(getApiErrorMessage(err, t('common.error')))- }- }}+ onChange={value => void changeTransitProvider(String(value))}options={[{ value: 'transitous', label: t('admin.transitProvider.transitous') },{ value: 'google', label: t('admin.transitProvider.google') },diff --git a/client/tests/unit/mobile/admin/MAdminDefaultUserSettings.test.tsx b/client/tests/unit/mobile/admin/MAdminDefaultUserSettings.test.tsxindex d68787931..47e995be5 100644--- a/client/tests/unit/mobile/admin/MAdminDefaultUserSettings.test.tsx+++ b/client/tests/unit/mobile/admin/MAdminDefaultUserSettings.test.tsx@@ -50,7 +50,7 @@ function resetLink(label: string): HTMLElement {/** The CARTO key input sits under its label inside the field's own wrapper. */function cartoInput(): HTMLInputElement {- return within(screen.getByText('Shared CARTO key').parentElement as HTMLElement).getByRole('textbox');+ return within(screen.getByText('Shared CARTO key').closest('[data-m-field]') as HTMLElement).getByRole('textbox');}describe('MAdminDefaultUserSettings', () => {diff --git a/client/tests/unit/mobile/admin/MAdminServices.test.tsx b/client/tests/unit/mobile/admin/MAdminServices.test.tsxnew file mode 100644index 000000000..b706e6b54--- /dev/null+++ b/client/tests/unit/mobile/admin/MAdminServices.test.tsx@@ -0,0 +1,174 @@+// FE-MOB-ASVC-001 to FE-MOB-ASVC-009+import userEvent from '@testing-library/user-event';+import type { PlaceContribDecisionRequest, PlaceContribState, ServiceIdentityStatus } from '@trek/shared';+import { http, HttpResponse } from 'msw';+import { describe, expect, it, vi } from 'vitest';+import MAdminGoogleDailyLimit from '../../../../src/mobile/screens/admin/MAdminGoogleDailyLimit';+import MAdminPlaceContrib from '../../../../src/mobile/screens/admin/MAdminPlaceContrib';+import MAdminServiceQuota from '../../../../src/mobile/screens/admin/MAdminServiceQuota';+import { server } from '../../../helpers/msw/server';+import { render, screen, waitFor, within } from '../../../helpers/render';++// The keys themselves, so a test fails on a missing or renamed key rather than on wording.+vi.mock('../../../../src/i18n', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../../src/i18n')>()),+ useTranslation: () => ({ t: (key: string) => key, locale: 'en-US' }),+}));++const QUOTA = { limit: 10_000, used: 2_500, remaining: 7_500, resetAt: '2026-10-30T00:00:00.000Z' };+const CONNECTED: ServiceIdentityStatus = {+ state: 'connected',+ tier: 'std',+ keySource: 'registered',+ services: [+ { service: 'places', inUse: true, quota: QUOTA },+ { service: 'photon', inUse: false, quota: null },+ ],+ lastSeenAt: '2026-10-29T12:00:00.000Z',+} as ServiceIdentityStatus;++const ON = { website: true, phone: true, email: true, opening_hours: true, description: true, image: true };+const AGREED: PlaceContribState = {+ termsVersion: 1,+ ceiling: 'admin',+ eligible: true,+ ineligibleReason: null,+ consent: {+ enabled: true,+ fields: ON,+ termsVersion: 1,+ decision: 'agreed',+ decidedBy: 1,+ decidedAt: '2026-10-30T10:00:00Z',+ },+ showPrompt: false,+ snoozedUntil: null,+ active: true,+ counts: { accepted: 42, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 },+ lastSuccessDay: '2026-10-29',+ queue: { size: 7, cap: 5000, full: false },+ pauseReason: null,+ registrationOpen: false,+};++function serveContrib(state: PlaceContribState) {+ const decisions: PlaceContribDecisionRequest[] = [];+ server.use(+ http.get('/api/admin/places-contribute', () => HttpResponse.json(state)),+ http.put('/api/admin/places-contribute/decision', async ({ request }) => {+ decisions.push((await request.json()) as PlaceContribDecisionRequest);+ return HttpResponse.json(state);+ }),+ http.get('/api/admin/places-contribute/log', () =>+ HttpResponse.json({ entries: [], total: 0, page: 1, perPage: 20 })+ )+ );+ return decisions;+}++describe('MAdminServiceQuota', () => {+ it('FE-MOB-ASVC-001: shows the state, the day used against the limit and an unused service', async () => {+ server.use(http.get('/api/admin/service-identity', () => HttpResponse.json(CONNECTED)));+ render(<MAdminServiceQuota />);+ expect(await screen.findByText('admin.trekApi.quota.state.connected')).toBeInTheDocument();+ expect(screen.getByRole('progressbar', { name: 'admin.trekApi.quota.service.places' })).toHaveAttribute(+ 'aria-valuenow',+ '2500'+ );+ expect(screen.getByText('admin.trekApi.quota.notInUse')).toBeInTheDocument();+ });++ it('FE-MOB-ASVC-002: a new key is asked for through a confirm sheet', async () => {+ const user = userEvent.setup();+ let regenerated = false;+ server.use(+ http.get('/api/admin/service-identity', () => HttpResponse.json(CONNECTED)),+ http.post('/api/admin/service-identity/regenerate', () => {+ regenerated = true;+ return HttpResponse.json(CONNECTED);+ })+ );+ render(<MAdminServiceQuota />);+ await user.click(await screen.findByRole('button', { name: /admin.trekApi.quota.regenerate/ }));+ const sheet = await screen.findByRole('dialog', { name: 'admin.trekApi.quota.regenerateTitle' });+ await user.click(within(sheet).getByRole('button', { name: 'admin.trekApi.quota.regenerate' }));+ await waitFor(() => expect(regenerated).toBe(true));+ });++ it('FE-MOB-ASVC-003: a managed install offers no new key', async () => {+ server.use(http.get('/api/admin/service-identity', () => HttpResponse.json(CONNECTED)));+ render(<MAdminServiceQuota managed />);+ await screen.findByText('admin.trekApi.quota.state.connected');+ expect(screen.queryByRole('button', { name: /admin.trekApi.quota.regenerate/ })).not.toBeInTheDocument();+ });+});++describe('MAdminGoogleDailyLimit', () => {+ it('FE-MOB-ASVC-004: shows today against the cap and saves a new cap', async () => {+ const user = userEvent.setup();+ let body: unknown = null;+ server.use(+ http.get('/api/admin/google-quota', () =>+ HttpResponse.json({ daily_limit: 500, used_today: 3, exhausted: false })+ ),+ http.put('/api/admin/google-quota', async ({ request }) => {+ body = await request.json();+ return HttpResponse.json({ daily_limit: 800, used_today: 3, exhausted: false });+ })+ );+ render(<MAdminGoogleDailyLimit />);+ expect(await screen.findByText('admin.googleQuota.usedOfLimit')).toBeInTheDocument();+ const field = screen.getByRole('textbox', { name: 'admin.googleQuota.title' });+ await user.clear(field);+ await user.type(field, '800');+ await user.click(screen.getByRole('button', { name: /common.save/ }));+ await waitFor(() => expect(body).not.toBeNull());+ });++ it('FE-MOB-ASVC-005: a used-up day reads as reached', async () => {+ server.use(+ http.get('/api/admin/google-quota', () => HttpResponse.json({ daily_limit: 10, used_today: 10, exhausted: true }))+ );+ render(<MAdminGoogleDailyLimit />);+ expect(await screen.findByText('admin.googleQuota.reached')).toBeInTheDocument();+ });+});++describe('MAdminPlaceContrib', () => {+ it('FE-MOB-ASVC-006: on, it shows the figures and one switch per field', async () => {+ serveContrib(AGREED);+ render(<MAdminPlaceContrib />);+ expect(await screen.findByRole('switch', { name: 'admin.contribute.title' })).toHaveAttribute(+ 'aria-checked',+ 'true'+ );+ expect(screen.getByText(/admin.contribute.figure.accepted 42/)).toBeInTheDocument();+ expect(screen.getByRole('switch', { name: 'admin.contribute.field.website' })).toBeInTheDocument();+ });++ it('FE-MOB-ASVC-007: switching a field off sends the remaining fields', async () => {+ const user = userEvent.setup();+ const decisions = serveContrib(AGREED);+ render(<MAdminPlaceContrib />);+ await user.click(await screen.findByRole('switch', { name: 'admin.contribute.field.phone' }));+ await waitFor(() => expect(decisions).toHaveLength(1));+ expect(decisions[0]).toMatchObject({ action: 'fields', fields: { ...ON, phone: false } });+ });++ it('FE-MOB-ASVC-008: switching it off asks first, then sends off', async () => {+ const user = userEvent.setup();+ const decisions = serveContrib(AGREED);+ render(<MAdminPlaceContrib />);+ await user.click(await screen.findByRole('switch', { name: 'admin.contribute.title' }));+ const sheet = await screen.findByRole('dialog', { name: 'admin.contribute.offTitle' });+ await user.click(within(sheet).getByRole('button', { name: 'admin.contribute.offConfirm' }));+ await waitFor(() => expect(decisions).toEqual([{ action: 'off' }]));+ });++ it('FE-MOB-ASVC-009: standing alone, a switch the environment turned off hides the panel', async () => {+ serveContrib({ ...AGREED, eligible: false, ineligibleReason: 'env_off' });+ render(<MAdminPlaceContrib hideWhenSwitchedOff />);+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(screen.queryByRole('switch')).not.toBeInTheDocument();+ });+});diff --git a/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx b/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsxindex 56386224e..f17c3f660 100644--- a/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx+++ b/client/tests/unit/mobile/admin/MAdminSettingsSection.test.tsx@@ -10,6 +10,12 @@ import { buildAdminHook, type AdminHook } from '../../../helpers/mobileAdmin';import { useTranslation } from '../../../../src/i18n';import MAdminSettingsSection from '../../../../src/mobile/screens/admin/MAdminSettingsSection';+// The services section's own panels load their data and have their own suite+// (MAdminServices.test.tsx); here only where they sit matters.+vi.mock('../../../../src/mobile/screens/admin/MAdminServiceQuota', () => ({ default: () => <div data-testid="service-quota" /> }));+vi.mock('../../../../src/mobile/screens/admin/MAdminPlaceContrib', () => ({ default: () => <div data-testid="place-contrib" /> }));+vi.mock('../../../../src/mobile/screens/admin/MAdminGoogleDailyLimit', () => ({ default: () => <div data-testid="google-daily-limit" /> }));+const PARTS = ['security', 'services', 'features'] as const;/** All three sections at once, so each card's behaviour is tested wherever it now lives. */@@ -241,7 +247,7 @@ describe('MAdminSettingsSection', () => {);const admin = renderSettings({ allowedFileTypes: 'jpg,png' });- await user.click(screen.getAllByRole('button', { name: 'Save' })[1]);+ await user.click(screen.getAllByRole('button', { name: 'Save' })[3]);await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('File type settings saved'));expect(sent).toEqual({ allowed_file_types: 'jpg,png' });@@ -256,7 +262,7 @@ describe('MAdminSettingsSection', () => {);const admin = renderSettings();- await user.click(screen.getAllByRole('button', { name: 'Save' })[1]);+ await user.click(screen.getAllByRole('button', { name: 'Save' })[3]);await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));expect(admin.setSavingFileTypes).toHaveBeenLastCalledWith(false);@@ -477,7 +483,7 @@ describe('MAdminSettingsSection', () => {expect(screen.getByDisplayValue('trek')).toBeInTheDocument();expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();- await user.click(screen.getAllByRole('button', { name: 'Save' })[3]);+ await user.click(screen.getAllByRole('button', { name: 'Save' })[1]);await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('OIDC configuration saved'));expect(sent).toEqual({@@ -509,7 +515,7 @@ describe('MAdminSettingsSection', () => {},});- await user.click(screen.getAllByRole('button', { name: 'Save' })[3]);+ await user.click(screen.getAllByRole('button', { name: 'Save' })[1]);await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Issuer unreachable'));expect(sent.client_secret).toBe('s3cr3t');