feat(transit): let an admin route transit search through Google

Transitous has no GTFS coverage for much of Asia, so a search between two
Osaka subway stops finds nothing — the stops are not in the feed at all.
Add Google as an optional backend behind an admin setting, reusing the
install's existing Places key, and fall back to Transitous whenever no
key resolves.

Uses the Routes API rather than the legacy Directions endpoint the
request named: every other Google call here already speaks the
v1/X-Goog-Api-Key family, and Google closed the legacy endpoint to Cloud
projects created after March 2025.

Google returns walking as turn-by-turn navigation steps where MOTIS
returns one leg per walking segment, so consecutive walk steps are
coalesced into a single leg — otherwise a finely-sliced walk pushed a
real journey past the 20-leg cap and the whole itinerary was dropped.

Both responses now name the backend that answered. The fallback is
silent by design, which left an empty result ambiguous between "no data
here" and "the provider you picked never ran", and the admin panel warns
when Google is selected but no key resolves — or when only the admin's
own key is set, which serves them and nobody else.

Cost shaped the implementation, since Google bills where Transitous does
not: both field masks are cut to the cheapest SKU tier that still
answers the question, cache TTLs are longer than the Transitous path's,
and route alternatives ride along inside the already-billed request.

Addresses #1699
This commit is contained in:
Konstantinos Thermos
2026-09-03 19:35:23 +03:00
committed by Maurice
parent 8e2840b29d
commit 2a0ceb2687
72 changed files with 2065 additions and 35 deletions
+7 -2
View File
@@ -1,6 +1,7 @@
import axios, { AxiosInstance } from 'axios'
import type { z } from 'zod'
import type { Place } from '../types'
import type { TransitProvider } from '@trek/shared'
import { randomId } from '../utils/randomId'
import {
weatherResultSchema, type WeatherResult,
@@ -652,6 +653,8 @@ export const adminApi = {
updatePlacesDetails: (enabled: boolean) => apiClient.put('/admin/places-details', { enabled }).then(r => r.data),
getPlacesEnrich: () => apiClient.get('/admin/places-enrich').then(r => r.data),
updatePlacesEnrich: (enabled: boolean) => apiClient.put('/admin/places-enrich', { enabled }).then(r => r.data),
getTransitProvider: () => apiClient.get('/admin/transit-provider').then(r => r.data),
updateTransitProvider: (provider: TransitProvider) => apiClient.put('/admin/transit-provider', { provider }).then(r => r.data),
getCollabFeatures: () => apiClient.get('/admin/collab-features').then(r => r.data),
updateCollabFeatures: (features: Record<string, boolean>) => apiClient.put('/admin/collab-features', features).then(r => r.data),
packingTemplates: () => apiClient.get('/admin/packing-templates').then(r => r.data),
@@ -1230,11 +1233,13 @@ export const shareApi = {
getSharedTrip: (token: string) => apiClient.get(`/shared/${token}`).then(r => r.data),
}
// Public transit routing (#1065) — Transitous/MOTIS proxied through the server.
// Public transit routing (#1065) — proxied through the server, which picks the
// backend (Transitous/MOTIS, or Google since #1699). `lang` reaches the Google
// backend as the languageCode, so station names come back in the user's script.
export const transitApi = {
geocode: (q: string, opts?: { lang?: string; near?: string }) =>
apiClient.get('/transit/geocode', { params: { q, lang: opts?.lang, near: opts?.near } }).then(r => r.data),
plan: (params: { from: string; to: string; time?: string; arriveBy?: boolean; modes?: string; maxTransfers?: number }) =>
plan: (params: { from: string; to: string; time?: string; arriveBy?: boolean; modes?: string; maxTransfers?: number; lang?: string }) =>
apiClient.get('/transit/plan', { params }).then(r => r.data),
}
@@ -175,6 +175,29 @@ describe('TransitSearchPanel', () => {
await user.click(await screen.findByText(/London Victoria/))
}
/**
* An empty result is ambiguous without the backend's name: the fallback to
* Transitous is silent, so "no connections" could mean the provider has no
* data here or that the provider you picked never ran (#1699).
*/
it('FE-PLANNER-TRANSIT-006b: the empty state names the backend that answered', async () => {
const user = userEvent.setup()
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [], provider: 'transitous' })
render(<TransitSearchPanel {...makeProps()} />)
await pickFromAndLondon(user)
await user.click(screen.getByRole('button', { name: /^Search$/ }))
expect(await screen.findByText(/No connections found via Transitous/)).toBeInTheDocument()
})
it('FE-PLANNER-TRANSIT-006c: falls back to the unnamed message when the server sends no provider', async () => {
const user = userEvent.setup()
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [] })
render(<TransitSearchPanel {...makeProps()} />)
await pickFromAndLondon(user)
await user.click(screen.getByRole('button', { name: /^Search$/ }))
expect(await screen.findByText(/^No connections found\./)).toBeInTheDocument()
})
it('FE-PLANNER-TRANSIT-007: depart-by anchors the entered time to the origin timezone', async () => {
const user = userEvent.setup()
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [] })
@@ -8,6 +8,7 @@ import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import type { Day, Place, Accommodation } from '../../types'
import type { TransitProvider } from '@trek/shared'
/**
* Public transit route search (#1065), backed by Transitous (MOTIS) through the
@@ -36,6 +37,14 @@ interface TransitPlaceResult { name: string; lat: number; lng: number; type: str
export interface PickedPlace { name: string; lat: number; lng: number }
// Backend names as they are written, not translated — the empty state says
// which one answered so "nothing here" can be told apart from "not the one you
// picked" (#1699).
const PROVIDER_NAMES: Record<TransitProvider, string> = {
transitous: 'Transitous',
google: 'Google',
}
// ── helpers ──────────────────────────────────────────────────────────────────
const MODE_GROUPS: { key: string; labelKey: string; Icon: React.ComponentType<{ size?: number; strokeWidth?: number }>; modes: string }[] = [
@@ -340,7 +349,7 @@ interface TransitSearchPanelProps {
}
export default function TransitSearchPanel({ day, days, places, accommodations = [], onAdd, initialFrom = null, initialTo = null, initialTime = null }: TransitSearchPanelProps) {
const { t } = useTranslation()
const { t, language } = useTranslation()
const toast = useToast()
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
@@ -355,6 +364,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
const [loading, setLoading] = useState(false)
const [expandedIdx, setExpandedIdx] = useState<number | null>(null)
const [addingIdx, setAddingIdx] = useState<number | null>(null)
const [provider, setProvider] = useState<TransitProvider | null>(null)
// Quick picks: the day's located places, plus the trip's located accommodations.
const quickPicks = useMemo<PickedPlace[]>(() => {
@@ -387,6 +397,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
setLoading(true)
setItineraries(null)
setExpandedIdx(null)
setProvider(null)
try {
const tzFrom = tzAt(from.lat, from.lng)
const tzTo = tzAt(to.lat, to.lng)
@@ -395,7 +406,11 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
const timeIso = localToUtcIso(day.date, time, arriveBy ? tzTo : tzFrom)
const allModes = activeModes.size === MODE_GROUPS.length
const modes = allModes ? undefined : MODE_GROUPS.filter(m => activeModes.has(m.key)).map(m => m.modes).join(',')
const d = await transitApi.plan({ from: `${from.lat},${from.lng}`, to: `${to.lat},${to.lng}`, time: timeIso, arriveBy, modes })
const d = await transitApi.plan({ from: `${from.lat},${from.lng}`, to: `${to.lat},${to.lng}`, time: timeIso, arriveBy, modes, lang: language })
// Which backend actually answered (#1699). Named in the empty state so
// "nothing found" can be told apart from "the provider you picked never
// ran" — the fallback to Transitous is silent by design.
setProvider(d.provider ?? null)
// MOTIS names the request coordinates START/END — swap in the places the
// user actually picked so walks read "Walk to Zoologischer Garten".
const cleanStop = (n: string) => (n === 'START' ? from.name : n === 'END' ? to.name : n)
@@ -606,7 +621,9 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
)}
{!loading && ranked && ranked.length === 0 && (
<div className="text-content-faint" style={{ textAlign: 'center', padding: '24px 0', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>
{t('transit.noResults')}
{provider
? t('transit.noResultsVia', { provider: PROVIDER_NAMES[provider] })
: t('transit.noResults')}
</div>
)}
{!loading && ranked && ranked.length > 0 && (
+59
View File
@@ -517,6 +517,65 @@ describe('AdminPage', () => {
});
});
describe('FE-PAGE-ADMIN-023b: Transit provider select in Settings tab (#1699)', () => {
it('choosing Google calls PUT /api/admin/transit-provider', async () => {
let capturedBody: Record<string, unknown> | null = null;
server.use(
http.get('/api/admin/transit-provider', () =>
HttpResponse.json({ provider: 'transitous', googleKeySource: 'instance' })),
http.put('/api/admin/transit-provider', async ({ request }) => {
capturedBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ provider: 'google', googleKeySource: 'instance' });
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /settings/i }));
const select = await screen.findByRole('combobox', { name: /transit provider/i });
await waitFor(() => expect(select).toHaveValue('transitous'));
fireEvent.change(select, { target: { value: 'google' } });
await waitFor(() => expect(capturedBody).toEqual({ provider: 'google' }));
expect(select).toHaveValue('google');
});
});
describe('FE-PAGE-ADMIN-023c: Transit provider key warnings (#1699)', () => {
async function openSettingsWith(googleKeySource: string | null) {
server.use(
http.get('/api/admin/transit-provider', () =>
HttpResponse.json({ provider: 'google', googleKeySource })),
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /settings/i }));
await screen.findByRole('combobox', { name: /transit provider/i });
}
it('warns that Google is selected but no key is configured', async () => {
await openSettingsWith(null);
expect(await screen.findByText(/no google api key is configured/i)).toBeInTheDocument();
});
it('warns that only the admin\'s own key is set, so others fall back', async () => {
await openSettingsWith('user-row');
expect(await screen.findByText(/only your own google key is set/i)).toBeInTheDocument();
});
it('stays quiet when an instance-wide key resolves', async () => {
await openSettingsWith('instance');
await waitFor(() =>
expect(screen.getByRole('combobox', { name: /transit provider/i })).toHaveValue('google'));
expect(screen.queryByText(/no google api key is configured/i)).not.toBeInTheDocument();
expect(screen.queryByText(/only your own google key is set/i)).not.toBeInTheDocument();
});
});
describe('FE-PAGE-ADMIN-024: JWT rotation modal opens from Danger Zone', () => {
it('clicking Rotate in Danger Zone opens the JWT rotation confirmation modal', async () => {
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -21,6 +21,8 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
placesAutocompleteEnabled, setPlacesAutocompleteEnabledState,
placesDetailsEnabled, setPlacesDetailsEnabledState,
placesEnrichEnabled, setPlacesEnrichEnabledState,
transitProvider, setTransitProviderState,
transitGoogleKeySource, setTransitGoogleKeySource,
oidcConfig, setOidcConfig, savingOidc, setSavingOidc,
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,
oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration,
@@ -420,6 +422,52 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): R
/>
</div>
{/* Transit Backend (#1699) — Transitous has no GTFS for much of Asia,
so an install can point transit search at Google instead, on the
same key. Falls back to Transitous when no key resolves. */}
<div className="py-3 border-t border-slate-100">
<p className="text-sm font-medium text-slate-700">{t('admin.transitProvider.title')}</p>
<p className="text-xs text-slate-400 mt-0.5">{t('admin.transitProvider.subtitle')}</p>
<select
value={transitProvider}
aria-label={t('admin.transitProvider.title')}
onChange={async e => {
const next = e.target.value === 'google' ? 'google' : 'transitous'
const previous = transitProvider
setTransitProviderState(next)
try {
const saved = await adminApi.updateTransitProvider(next)
setTransitGoogleKeySource(saved.googleKeySource)
} catch { setTransitProviderState(previous) }
}}
className="mt-2 w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
>
<option value="transitous">{t('admin.transitProvider.transitous')}</option>
<option value="google">{t('admin.transitProvider.google')}</option>
</select>
<p className="text-xs text-slate-400 mt-1">
{transitProvider === 'google' ? t('admin.transitProvider.googleHint') : t('admin.transitProvider.transitousHint')}
</p>
{/* Picking Google without a key that resolves changes nothing — the
request-time fallback is silent, so this is the only place it can
be said. 'user-row' is the subtler half: the resolver's last step
is the caller's own row, so a personal key serves this admin and
nobody else. */}
{transitProvider === 'google' && transitGoogleKeySource === null && (
<p className="flex items-start gap-2 text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mt-2">
<AlertTriangle size={14} className="flex-shrink-0 mt-0.5" />
{t('admin.transitProvider.noKeyWarning')}
</p>
)}
{transitProvider === 'google' && transitGoogleKeySource === 'user-row' && (
<p className="flex items-start gap-2 text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2 mt-2">
<AlertTriangle size={14} className="flex-shrink-0 mt-0.5" />
{t('admin.transitProvider.personalKeyWarning')}
</p>
)}
</div>
{/* Open-Meteo Weather Info */}
<div className="rounded-lg border border-emerald-200 bg-emerald-50 dark:bg-emerald-950/30 dark:border-emerald-800 overflow-hidden">
<div className="px-4 py-3 flex items-center justify-between">
+14
View File
@@ -9,6 +9,7 @@ import { getApiErrorMessage } from '../../types'
import { useToast } from '../../components/shared/Toast'
import { managedAdminTabs } from '../../managed'
import type { AdminUser, AdminStats, OidcConfig, UpdateInfo } from './adminModel'
import type { TransitProvider, TransitKeySource } from '@trek/shared'
/**
* Every tab id AdminPage can render a panel for, whatever this install offers.
@@ -99,6 +100,17 @@ export function useAdmin() {
useEffect(() => { adminApi.getPlacesDetails().then(d => setPlacesDetailsEnabledState(d.enabled)).catch(() => {}) }, [])
useEffect(() => { adminApi.getPlacesEnrich().then(d => setPlacesEnrichEnabledState(d.enabled)).catch(() => {}) }, [])
// Transit backend (#1699). googleKeySource says where a Google key would come
// from for this admin — null means picking Google changes nothing, since the
// request-time fallback to Transitous is silent by design.
const [transitProvider, setTransitProviderState] = useState<TransitProvider>('transitous')
const [transitGoogleKeySource, setTransitGoogleKeySource] = useState<TransitKeySource>(null)
useEffect(() => {
adminApi.getTransitProvider()
.then(d => { setTransitProviderState(d.provider); setTransitGoogleKeySource(d.googleKeySource) })
.catch(() => {})
}, [])
// Collab features
const [collabFeatures, setCollabFeatures] = useState<{ chat: boolean; notes: boolean; polls: boolean; whatsnext: boolean }>({ chat: true, notes: true, polls: true, whatsnext: true })
useEffect(() => { adminApi.getCollabFeatures().then(d => setCollabFeatures(d)).catch(() => {}) }, [])
@@ -430,6 +442,8 @@ export function useAdmin() {
placesAutocompleteEnabled, setPlacesAutocompleteEnabledState,
placesDetailsEnabled, setPlacesDetailsEnabledState,
placesEnrichEnabled, setPlacesEnrichEnabledState,
transitProvider, setTransitProviderState,
transitGoogleKeySource, setTransitGoogleKeySource,
collabFeatures, setCollabFeatures,
oidcConfig, setOidcConfig, savingOidc, setSavingOidc,
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,