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
fix: the findings of the final 4.3.0 audit
Mauriceed18c379036e
diff --git a/charts/trek/templates/configmap.yaml b/charts/trek/templates/configmap.yamlindex aeab34b07..a7397e76f 100644--- a/charts/trek/templates/configmap.yaml+++ b/charts/trek/templates/configmap.yaml@@ -85,3 +85,15 @@ data:{{- if .Values.env.OVERPASS_TIMEOUT_MS }}OVERPASS_TIMEOUT_MS: {{ .Values.env.OVERPASS_TIMEOUT_MS | quote }}{{- end }}+ {{- /* Tested for presence rather than truth: the one value this switch gets set to is+ false, and an unquoted false (or --set env.TREK_PLACES_ENABLED=false) would+ otherwise drop the key and leave the index on. */}}+ {{- if not (kindIs "invalid" .Values.env.TREK_PLACES_ENABLED) }}+ TREK_PLACES_ENABLED: {{ .Values.env.TREK_PLACES_ENABLED | quote }}+ {{- end }}+ {{- if .Values.env.TREK_PLACES_URL }}+ TREK_PLACES_URL: {{ .Values.env.TREK_PLACES_URL | quote }}+ {{- end }}+ {{- if .Values.env.AMAP_API_BASE }}+ AMAP_API_BASE: {{ .Values.env.AMAP_API_BASE | quote }}+ {{- end }}diff --git a/charts/trek/templates/deployment.yaml b/charts/trek/templates/deployment.yamlindex 7b24b98dd..24e67325c 100644--- a/charts/trek/templates/deployment.yaml+++ b/charts/trek/templates/deployment.yaml@@ -75,6 +75,18 @@ spec:name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}key: UNSPLASH_ACCESS_KEYoptional: true+ - name: AMAP_API_KEY+ valueFrom:+ secretKeyRef:+ name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}+ key: AMAP_API_KEY+ optional: true+ - name: AMAP_API_SECRET+ valueFrom:+ secretKeyRef:+ name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}+ key: AMAP_API_SECRET+ optional: truevolumeMounts:- name: datamountPath: /app/datadiff --git a/charts/trek/templates/secret.yaml b/charts/trek/templates/secret.yamlindex 08d81cabd..c465e8e34 100644--- a/charts/trek/templates/secret.yaml+++ b/charts/trek/templates/secret.yaml@@ -20,6 +20,12 @@ data:{{- if .Values.secretEnv.UNSPLASH_ACCESS_KEY }}UNSPLASH_ACCESS_KEY: {{ .Values.secretEnv.UNSPLASH_ACCESS_KEY | b64enc | quote }}{{- end }}+ {{- if .Values.secretEnv.AMAP_API_KEY }}+ AMAP_API_KEY: {{ .Values.secretEnv.AMAP_API_KEY | b64enc | quote }}+ {{- end }}+ {{- if .Values.secretEnv.AMAP_API_SECRET }}+ AMAP_API_SECRET: {{ .Values.secretEnv.AMAP_API_SECRET | b64enc | quote }}+ {{- end }}{{- end }}{{- if and (not .Values.existingSecret) (.Values.generateEncryptionKey) }}@@ -50,4 +56,10 @@ stringData:{{- if .Values.secretEnv.UNSPLASH_ACCESS_KEY }}UNSPLASH_ACCESS_KEY: {{ .Values.secretEnv.UNSPLASH_ACCESS_KEY }}{{- end }}+ {{- if .Values.secretEnv.AMAP_API_KEY }}+ AMAP_API_KEY: {{ .Values.secretEnv.AMAP_API_KEY }}+ {{- end }}+ {{- if .Values.secretEnv.AMAP_API_SECRET }}+ AMAP_API_SECRET: {{ .Values.secretEnv.AMAP_API_SECRET }}+ {{- end }}{{- end }}diff --git a/charts/trek/values.yaml b/charts/trek/values.yamlindex 69c136e04..0d4bb1aeb 100644--- a/charts/trek/values.yaml+++ b/charts/trek/values.yaml@@ -90,8 +90,24 @@ env:# Custom Overpass endpoint(s) for the map POI "explore" search, comma-separated. When set, REPLACES the bundled# public mirrors — point it at an internal/self-hosted Overpass instance when the public mirrors are unreachable# from the cluster (e.g. locked-down egress). Non-http(s) entries are ignored.- # OVERPASS_TIMEOUT_MS: "12000"- # Per-endpoint timeout (ms) for Overpass POI requests. Raise it for a slow self-hosted Overpass instance. Defaults to 12000.+ # OVERPASS_TIMEOUT_MS: "25000"+ # Per-endpoint timeout (ms) for Overpass POI requests. The query itself gives Overpass 20 seconds of work, so a+ # lower value hangs up on answers that were still coming. Raise it for a slow self-hosted Overpass instance.+ # Defaults to 25000.+ # TREK_PLACES_ENABLED: "false"+ # Place search (suggestions, full search, category buttons, Road trip search, import geocoding, offline downloads)+ # asks the TREK Places API at https://places.liketrek.com by default, so the pod makes outbound requests to that+ # host. Set "false" to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send+ # nothing there. There is no switch in the admin panel on purpose: whether searches leave the instance is decided+ # here. Defaults to on.+ # TREK_PLACES_URL: ""+ # Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from+ # configuration rather than typed by a user, so an in-cluster address works without ALLOW_INTERNAL_NETWORK.+ # Defaults to https://places.liketrek.com.+ # AMAP_API_BASE: ""+ # Send the Amap (高德地图) calls through an egress proxy, a cache or a gateway that speaks the same API instead of+ # restapi.amap.com directly. The key itself is a credential and goes under secretEnv.AMAP_API_KEY, or into+ # Admin > Settings > API Keys. Defaults to https://restapi.amap.com.# Secret environment variables stored in a Kubernetes Secret.@@ -117,6 +133,15 @@ secretEnv:# Get a free key at https://unsplash.com/developers. Can also be set per-admin# in Admin > Settings; this value overrides that. Leave empty to disable.UNSPLASH_ACCESS_KEY: ""+ # Optional Amap (高德地图) Web 服务 key for place search and geocoding inside mainland+ # China. Overrides the key set in Admin > Settings > API Keys. A Web 端 (JS API) key is+ # a different credential and is rejected with INVALID_USER_KEY. Leave empty to use the+ # key from the admin panel, or none.+ AMAP_API_KEY: ""+ # The private secret (数字签名) of that key. Required exactly when the key was created+ # with signing enabled, because such a key rejects every unsigned request. Leave empty+ # otherwise. The endpoint itself is not a secret and is set under env.AMAP_API_BASE.+ AMAP_API_SECRET: ""# If true, a random ENCRYPTION_KEY is generated at install and preserved across upgradesgenerateEncryptionKey: falsediff --git a/client/src/api/client.surface.test.ts b/client/src/api/client.surface.test.tsindex eebc8f933..be5aee90b 100644--- a/client/src/api/client.surface.test.ts+++ b/client/src/api/client.surface.test.ts@@ -1,4 +1,4 @@-// FE-APISURF-001 to FE-APISURF-056+// FE-APISURF-001 to FE-APISURF-057import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import type { AxiosResponse } from 'axios'import { http, HttpResponse } from 'msw'@@ -10,7 +10,7 @@ import {mapsApi, airportsApi, budgetApi, filesApi, reservationsApi, healthApi, weatherApi,configApi, helpApi, settingsApi, accommodationsApi, dayNotesApi, collabApi, backupApi,shareApi, transitApi, tripInviteApi, notificationsApi, inAppNotificationsApi, memoriesApi,- docsyncApi,+ docsyncApi, DOCSYNC_RUN_TIMEOUT_MS, DOCSYNC_UPSTREAM_TIMEOUT_MS,} from './client'interface Recorded { method: string; url: string; body: unknown }@@ -902,4 +902,47 @@ describe('client > multipart uploads', () => {expect(call[2]).toMatchObject({ timeout: 40000 })}})++ it('FE-APISURF-057: every document-sync call that reaches the store outlives the 8s global timeout', async () => {+ const post = spyPost()+ const get = vi.spyOn(apiClient, 'get').mockResolvedValue({ data: { ok: true } } as unknown as AxiosResponse)+ const del = vi.spyOn(apiClient, 'delete').mockResolvedValue({ data: { ok: true } } as unknown as AxiosResponse)++ // The server allows each request to a store 15 s, and a run waits for the+ // whole listing and every transfer; cut off at 8 s the browser reported a+ // failure while the server carried on and finished.+ await docsyncApi.testConnection(1, { providerId: 'paperless' })+ await docsyncApi.createScope(1, 5, 'Norway')+ await docsyncApi.createLink(1, { connectionId: 5 })+ await docsyncApi.listScopes(1, 5)+ await docsyncApi.deleteLink(1, 9)++ expect(post.mock.calls.map(c => c[0])).toEqual([+ '/trips/1/docsync/connections/test',+ '/trips/1/docsync/connections/5/scopes',+ '/trips/1/docsync/links',+ ])+ for (const call of post.mock.calls) {+ expect(call[2]).toMatchObject({ timeout: DOCSYNC_UPSTREAM_TIMEOUT_MS })+ }+ expect(get.mock.calls[0][0]).toBe('/trips/1/docsync/connections/5/scopes')+ expect(get.mock.calls[0][1]).toMatchObject({ timeout: DOCSYNC_UPSTREAM_TIMEOUT_MS })+ expect(del.mock.calls[0][0]).toBe('/trips/1/docsync/links/9')+ expect(del.mock.calls[0][1]).toMatchObject({ timeout: DOCSYNC_UPSTREAM_TIMEOUT_MS })+ expect(DOCSYNC_UPSTREAM_TIMEOUT_MS).toBeGreaterThan(8000)++ // A run, and a conflict choice that runs the binding afterwards.+ post.mockClear()+ await docsyncApi.syncNow(1, 9)+ await docsyncApi.resolve(1, 4, 'trek')++ expect(post.mock.calls.map(c => c[0])).toEqual([+ '/trips/1/docsync/links/9/sync',+ '/trips/1/docsync/items/4/resolve',+ ])+ for (const call of post.mock.calls) {+ expect(call[2]).toMatchObject({ timeout: DOCSYNC_RUN_TIMEOUT_MS })+ }+ expect(DOCSYNC_RUN_TIMEOUT_MS).toBeGreaterThan(DOCSYNC_UPSTREAM_TIMEOUT_MS)+ })})diff --git a/client/src/api/client.ts b/client/src/api/client.tsindex c033fc057..4d5809557 100644--- a/client/src/api/client.ts+++ b/client/src/api/client.ts@@ -1361,6 +1361,34 @@ export const filesApi = {getLinks: (tripId: number | string, fileId: number) => apiClient.get(`/trips/${tripId}/files/${fileId}/links`).then(r => r.data),}+/**+ * How long the browser waits for a document-sync call that makes the server go+ * and ask the store.+ *+ * The shared 8 s on `apiClient` is right for TREK's own routes and wrong for+ * these, for the reason `dawarich.ts` gives: the server allows each request to+ * a store 15 s by itself (20 s for Papra), a connection test may probe more+ * than once, and binding or unbinding first registers or removes a webhook at+ * the store. Cut off at 8 s, the browser reported a failure while the server+ * carried on and finished, so a listing that took twelve seconds read as a+ * broken store.+ */+export const DOCSYNC_UPSTREAM_TIMEOUT_MS = 60_000++/**+ * A run is longer again. The server answers only once the whole of it is+ * through: a listing of up to 40 pages, then up to 25 transfers at up to 120 s+ * each, and Paperless-ngx holds every push until its consume task has run.+ * Resolving a conflict runs the binding afterwards, so it waits just as long.+ * Ten minutes covers a full transfer budget of ordinary documents; a run that+ * outlasts it still finishes on the server, and the `docsync:changed` ping+ * refreshes the dialog when it does.+ */+export const DOCSYNC_RUN_TIMEOUT_MS = 600_000++const docsyncUpstream = { timeout: DOCSYNC_UPSTREAM_TIMEOUT_MS }+const docsyncRun = { timeout: DOCSYNC_RUN_TIMEOUT_MS }+/*** Document sync: one provider connection per trip, shared by every member.*@@ -1373,22 +1401,22 @@ export const docsyncApi = {status: (tripId: number | string) => apiClient.get(`/trips/${tripId}/docsync/status`).then(r => r.data),listConnections: (tripId: number | string) => apiClient.get(`/trips/${tripId}/docsync/connections`).then(r => r.data),saveConnection: (tripId: number | string, data: unknown) => apiClient.put(`/trips/${tripId}/docsync/connections`, data).then(r => r.data),- testConnection: (tripId: number | string, data: unknown) => apiClient.post(`/trips/${tripId}/docsync/connections/test`, data).then(r => r.data),+ testConnection: (tripId: number | string, data: unknown) => apiClient.post(`/trips/${tripId}/docsync/connections/test`, data, docsyncUpstream).then(r => r.data),deleteConnection: (tripId: number | string, connectionId: number) => apiClient.delete(`/trips/${tripId}/docsync/connections/${connectionId}`).then(r => r.data),listScopes: (tripId: number | string, connectionId: number, q?: string) =>- apiClient.get(`/trips/${tripId}/docsync/connections/${connectionId}/scopes`, { params: q ? { q } : {} }).then(r => r.data),+ apiClient.get(`/trips/${tripId}/docsync/connections/${connectionId}/scopes`, { params: q ? { q } : {}, ...docsyncUpstream }).then(r => r.data),createScope: (tripId: number | string, connectionId: number, name: string) =>- apiClient.post(`/trips/${tripId}/docsync/connections/${connectionId}/scopes`, { name }).then(r => r.data),+ apiClient.post(`/trips/${tripId}/docsync/connections/${connectionId}/scopes`, { name }, docsyncUpstream).then(r => r.data),listLinks: (tripId: number | string) => apiClient.get(`/trips/${tripId}/docsync/links`).then(r => r.data),- createLink: (tripId: number | string, data: unknown) => apiClient.post(`/trips/${tripId}/docsync/links`, data).then(r => r.data),+ createLink: (tripId: number | string, data: unknown) => apiClient.post(`/trips/${tripId}/docsync/links`, data, docsyncUpstream).then(r => r.data),updateLink: (tripId: number | string, linkId: number, data: unknown) => apiClient.patch(`/trips/${tripId}/docsync/links/${linkId}`, data).then(r => r.data),- deleteLink: (tripId: number | string, linkId: number) => apiClient.delete(`/trips/${tripId}/docsync/links/${linkId}`).then(r => r.data),+ deleteLink: (tripId: number | string, linkId: number) => apiClient.delete(`/trips/${tripId}/docsync/links/${linkId}`, docsyncUpstream).then(r => r.data),syncNow: (tripId: number | string, linkId: number, full = false) =>- apiClient.post(`/trips/${tripId}/docsync/links/${linkId}/sync`, { full }).then(r => r.data),+ apiClient.post(`/trips/${tripId}/docsync/links/${linkId}/sync`, { full }, docsyncRun).then(r => r.data),items: (tripId: number | string, state?: string) =>apiClient.get(`/trips/${tripId}/docsync/items`, { params: state ? { state } : {} }).then(r => r.data),resolve: (tripId: number | string, itemId: number, keep: 'trek' | 'provider' | 'both') =>- apiClient.post(`/trips/${tripId}/docsync/items/${itemId}/resolve`, { keep }).then(r => r.data),+ apiClient.post(`/trips/${tripId}/docsync/items/${itemId}/resolve`, { keep }, docsyncRun).then(r => r.data),}export const reservationsApi = {diff --git a/client/src/components/Admin/AddonManager.test.tsx b/client/src/components/Admin/AddonManager.test.tsxindex 0964cedc0..1b86b373c 100644--- a/client/src/components/Admin/AddonManager.test.tsx+++ b/client/src/components/Admin/AddonManager.test.tsx@@ -1,4 +1,4 @@-// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-036+// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-037import { render, screen, waitFor } from '../../../tests/helpers/render';import userEvent from '@testing-library/user-event';import { delay, http, HttpResponse } from 'msw';@@ -543,6 +543,22 @@ describe('AddonManager', () => {expect(screen.queryByText('Polls')).not.toBeInTheDocument();});+ it('FE-ADMIN-ADDON-037: the links row describes the feature, not an empty list', async () => {+ // The row's tooltip is its description. The links tab's empty state read as a+ // status here, and a status that never changes reads as a broken feature.+ server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));+ render(+ <AddonManager+ collabFeatures={{ chat: true, notes: true, links: true, polls: true, whatsnext: true }}+ onToggleCollabFeature={vi.fn()}+ />,+ );++ const links = await screen.findByText('Links');+ expect(links).toHaveAttribute('title');+ expect(links.getAttribute('title')).not.toBe('No shared links yet');+ });+it('FE-ADMIN-ADDON-020: a disabled AI-parsing addon renders the row without its config block', async () => {server.use(addonsRoute([{ ...llmAddon({ provider: 'local' }), enabled: false }]));render(<AddonManager />);diff --git a/client/src/components/Admin/AddonManager.tsx b/client/src/components/Admin/AddonManager.tsxindex 6002d42c7..94755412a 100644--- a/client/src/components/Admin/AddonManager.tsx+++ b/client/src/components/Admin/AddonManager.tsx@@ -99,7 +99,7 @@ interface CollabFeatures { chat: boolean; notes: boolean; links?: boolean; pollsconst COLLAB_SUB_FEATURES = [{ key: 'chat', icon: MessageCircle, titleKey: 'admin.collab.chat.title', subtitleKey: 'admin.collab.chat.subtitle' },{ key: 'notes', icon: StickyNote, titleKey: 'admin.collab.notes.title', subtitleKey: 'admin.collab.notes.subtitle' },- { key: 'links', icon: Link2, titleKey: 'collab.tabs.links', subtitleKey: 'collab.links.empty' },+ { key: 'links', icon: Link2, titleKey: 'collab.tabs.links', subtitleKey: 'admin.collab.links.subtitle' },{ key: 'polls', icon: BarChart3, titleKey: 'admin.collab.polls.title', subtitleKey: 'admin.collab.polls.subtitle' },{ key: 'whatsnext', icon: Sparkles, titleKey: 'admin.collab.whatsnext.title', subtitleKey: 'admin.collab.whatsnext.subtitle' },] as constdiff --git a/client/src/components/Collab/CollabChat.test.tsx b/client/src/components/Collab/CollabChat.test.tsxindex 2f818b142..2ed6657d6 100644--- a/client/src/components/Collab/CollabChat.test.tsx+++ b/client/src/components/Collab/CollabChat.test.tsx@@ -708,4 +708,31 @@ describe('CollabChat', () => {{ timeout: 3000 });});++ // The strip shows the four pictures that will go out; the two the cap turned away+ // vanish without a word otherwise, and the sender believes all six were sent.+ it('FE-COMP-CHAT-037: picking more images than fit on one message says so, and says it once', async () => {+ const addToast = vi.fn();+ window.__addToast = addToast as unknown as typeof window.__addToast;+ let minted = 0;+ const createObjURL = vi.spyOn(URL, 'createObjectURL').mockImplementation(() => `blob:mock/${++minted}`);+ const revokeObjURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});+ try {+ render(<CollabChat {...defaultProps} />);+ await screen.findByText('Start the conversation');+ const input = document.querySelector('input[type="file"]') as HTMLInputElement;+ const files = Array.from({ length: 6 }, (_, i) => new File([new Uint8Array(8)], `${i}.png`, { type: 'image/png' }));++ fireEvent.change(input, { target: { files } });++ await waitFor(() => expect(document.querySelectorAll('img[src^="blob:mock/"]')).toHaveLength(4));+ expect(addToast).toHaveBeenCalledTimes(1);+ const [message, type] = addToast.mock.calls[0];+ expect(type).toBe('error');+ expect(message).not.toBe('Only JPEG, PNG, GIF and WebP images up to 10 MB are allowed');+ } finally {+ delete window.__addToast;+ createObjURL.mockRestore(); revokeObjURL.mockRestore();+ }+ });});diff --git a/client/src/components/Collab/CollabChat.tsx b/client/src/components/Collab/CollabChat.tsxindex f3cc80526..a1badfd38 100644--- a/client/src/components/Collab/CollabChat.tsx+++ b/client/src/components/Collab/CollabChat.tsx@@ -48,8 +48,8 @@ export default function CollabChat({ tripId, currentUser }: CollabChatProps) {</div>)}- {imagePreviews.length > 0 && <div style={{ display: 'flex', gap: 8, marginBottom: 8, overflowX: 'auto' }}>{imagePreviews.map((url, i) => <div key={url} style={{ position: 'relative' }}><img src={url} alt="" style={{ width: 56, height: 56, objectFit: 'cover', borderRadius: 8 }} /><button type="button" onClick={() => removeImage(i)} aria-label="Remove image" style={{ position: 'absolute', top: -6, right: -6, border: 0, borderRadius: '50%', background: 'var(--text-primary)', color: 'var(--bg-primary)', width: 18, height: 18, cursor: 'pointer' }}>×</button></div>)}</div>}- {uploadProgress > 0 && uploadProgress < 100 && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>Uploading {uploadProgress}%</div>}+ {imagePreviews.length > 0 && <div style={{ display: 'flex', gap: 8, marginBottom: 8, overflowX: 'auto' }}>{imagePreviews.map((url, i) => <div key={url} style={{ position: 'relative' }}><img src={url} alt="" style={{ width: 56, height: 56, objectFit: 'cover', borderRadius: 8 }} /><button type="button" onClick={() => removeImage(i)} aria-label={t('places.removeImage')} style={{ position: 'absolute', top: -6, right: -6, border: 0, borderRadius: '50%', background: 'var(--text-primary)', color: 'var(--bg-primary)', width: 18, height: 18, cursor: 'pointer' }}>×</button></div>)}</div>}+ {uploadProgress > 0 && uploadProgress < 100 && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>{t('collab.chat.uploading', { percent: uploadProgress })}</div>}<div style={{ display: 'flex', alignItems: 'flex-end', gap: 6 }}>{/* Emoji button */}{canEdit && (@@ -63,7 +63,7 @@ export default function CollabChat({ tripId, currentUser }: CollabChatProps) {</button>)}- {canEdit && <><input ref={imageInputRef} type="file" accept="image/jpeg,image/png,image/gif,image/webp" multiple hidden onChange={e => { if (e.target.files) addImageFiles(e.target.files); e.currentTarget.value = '' }} /><button type="button" onClick={() => imageInputRef.current?.click()} aria-label="Attach images" style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'transparent', color: 'var(--text-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', padding: 0 }}><ImagePlus size={19} /></button></>}+ {canEdit && <><input ref={imageInputRef} type="file" accept="image/jpeg,image/png,image/gif,image/webp" multiple hidden onChange={e => { if (e.target.files) addImageFiles(e.target.files); e.currentTarget.value = '' }} /><button type="button" onClick={() => imageInputRef.current?.click()} aria-label={t('collab.chat.attachImages')} style={{ width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'transparent', color: 'var(--text-muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', padding: 0 }}><ImagePlus size={19} /></button></>}<textarearef={textareaRef}diff --git a/client/src/components/Collab/CollabChatAttachment.tsx b/client/src/components/Collab/CollabChatAttachment.tsxindex c19c744f5..f6036fa2e 100644--- a/client/src/components/Collab/CollabChatAttachment.tsx+++ b/client/src/components/Collab/CollabChatAttachment.tsx@@ -1,10 +1,13 @@import { useState } from 'react'import { X } from 'lucide-react'+import { useTranslation } from '../../i18n'export function CollabChatAttachment({ attachment }: { attachment: { url: string; original_name?: string; mime_type?: string } }) {+ const { t } = useTranslation()const [open, setOpen] = useState(false)+ const alt = attachment.original_name || t('collab.chat.attachedImage')return <>- <img src={attachment.url} alt={attachment.original_name || 'Attached image'} onClick={() => setOpen(true)} style={{ display: 'block', width: 180, maxWidth: '100%', maxHeight: 220, objectFit: 'cover', borderRadius: 10, cursor: 'zoom-in', marginTop: 4 }} />- {open && <div role="dialog" onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,.82)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}><button aria-label="Close image" onClick={() => setOpen(false)} style={{ position: 'fixed', top: 18, right: 18, background: 'rgba(255,255,255,.15)', color: '#fff', border: 0, borderRadius: '50%', width: 36, height: 36 }}><X size={20} /></button><img src={attachment.url} alt={attachment.original_name || 'Attached image'} onClick={e => e.stopPropagation()} style={{ maxWidth: '95vw', maxHeight: '90vh', objectFit: 'contain' }} /></div>}+ <img src={attachment.url} alt={alt} onClick={() => setOpen(true)} style={{ display: 'block', width: 180, maxWidth: '100%', maxHeight: 220, objectFit: 'cover', borderRadius: 10, cursor: 'zoom-in', marginTop: 4 }} />+ {open && <div role="dialog" onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,.82)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}><button aria-label={t('collab.chat.closeImage')} onClick={() => setOpen(false)} style={{ position: 'fixed', top: 18, right: 18, background: 'rgba(255,255,255,.15)', color: '#fff', border: 0, borderRadius: '50%', width: 36, height: 36 }}><X size={20} /></button><img src={attachment.url} alt={alt} onClick={e => e.stopPropagation()} style={{ maxWidth: '95vw', maxHeight: '90vh', objectFit: 'contain' }} /></div>}</>}diff --git a/client/src/components/Collab/useChatImages.test.ts b/client/src/components/Collab/useChatImages.test.tsindex 6f309a7e2..3485b1182 100644--- a/client/src/components/Collab/useChatImages.test.ts+++ b/client/src/components/Collab/useChatImages.test.ts@@ -1,5 +1,5 @@/**- * FE-CHATIMG-001..006 — the pictures pinned to a chat message before it is sent.+ * FE-CHATIMG-001..009: the pictures pinned to a chat message before it is sent.** The reason this file exists: the hook used to create object URLs and enqueue* the preview state from inside a `setFiles` updater. React invokes an updater@@ -11,7 +11,7 @@import { describe, it, expect, beforeEach, vi } from 'vitest'import { StrictMode } from 'react'import { act, renderHook } from '@testing-library/react'-import { useChatImages, MAX_CHAT_IMAGES } from './useChatImages'+import { useChatImages, MAX_CHAT_IMAGES, type ChatImageDrop } from './useChatImages'let nextUrl = 0const revoked: string[] = []@@ -92,4 +92,44 @@ describe('useChatImages', () => {expect(result.current.files).toEqual([])expect(revoked.sort()).toEqual(['blob:mock/1', 'blob:mock/2'])})++ // The strip shows what will be sent, so a picture the cap turned away is as gone as+ // one of the wrong kind. The sender hears about both, and hears which it was.+ it('FE-CHATIMG-007: a pick past the cap is reported as an overflow and is not a clean add', () => {+ const { result } = strict()+ const drops: ChatImageDrop[] = []+ let ok = true++ act(() => {+ ok = result.current.add(Array.from({ length: MAX_CHAT_IMAGES + 2 }, (_, i) => img(`${i}.png`)), d => drops.push(d))+ })++ expect(ok).toBe(false)+ expect(drops).toEqual([{ rejected: 0, overflow: 2 }])+ expect(result.current.files).toHaveLength(MAX_CHAT_IMAGES)+ })++ it('FE-CHATIMG-008: a wrong kind and an overflow in one pick are told apart', () => {+ const { result } = strict()+ act(() => { result.current.add([img('a.png'), img('b.png'), img('c.png')]) })+ const drops: ChatImageDrop[] = []++ act(() => {+ result.current.add([new File(['x'], 'notes.pdf', { type: 'application/pdf' }), img('d.png'), img('e.png')], d => drops.push(d))+ })++ expect(result.current.files.map(f => f.name)).toEqual(['a.png', 'b.png', 'c.png', 'd.png'])+ expect(drops).toEqual([{ rejected: 1, overflow: 1 }])+ })++ it('FE-CHATIMG-009: a pick that fits is a clean add and reports nothing', () => {+ const { result } = strict()+ const onDrop = vi.fn()+ let ok = false++ act(() => { ok = result.current.add([img('a.png')], onDrop) })++ expect(ok).toBe(true)+ expect(onDrop).not.toHaveBeenCalled()+ })})diff --git a/client/src/components/Collab/useChatImages.ts b/client/src/components/Collab/useChatImages.tsindex 29ac30411..d6d7cf803 100644--- a/client/src/components/Collab/useChatImages.ts+++ b/client/src/components/Collab/useChatImages.ts@@ -28,11 +28,24 @@ interface PickedImage {url: string}+/**+ * What an add() left out: files of the wrong type or over the size limit, and+ * valid files past the cap of MAX_CHAT_IMAGES. Either can be zero, both cannot.+ */+export interface ChatImageDrop {+ rejected: number+ overflow: number+}+export interface ChatImages {files: File[]previews: string[]- /** Returns false when something was dropped, so the caller can say why. */- add: (incoming: FileList | File[]) => boolean+ /**+ * Returns false when something was dropped, so the caller can say why. The+ * optional callback tells it what was dropped, because a picture past the cap+ * is a different message from a picture of the wrong kind.+ */+ add: (incoming: FileList | File[], onDrop?: (drop: ChatImageDrop) => void) => booleanremove: (index: number) => voidclear: () => void}@@ -52,7 +65,7 @@ export function useChatImages(): ChatImages {itemsRef.current = []}, [])- const add = useCallback((incoming: FileList | File[]) => {+ const add = useCallback((incoming: FileList | File[], onDrop?: (drop: ChatImageDrop) => void) => {const all = Array.from(incoming)const valid = all.filter(f => CHAT_IMAGE_TYPES.includes(f.type) && f.size <= MAX_CHAT_IMAGE_BYTES)const room = MAX_CHAT_IMAGES - itemsRef.current.length@@ -61,7 +74,11 @@ export function useChatImages(): ChatImages {// Only the new files get a URL; the ones already in the list keep theirs.commit([...itemsRef.current, ...added.map(file => ({ file, url: URL.createObjectURL(file) }))])}- return valid.length === all.length+ // A picture the cap turned away is as gone as one of the wrong kind: the strip+ // shows what will be sent, and the sender deserves to hear why it is short.+ const drop = { rejected: all.length - valid.length, overflow: valid.length - added.length }+ if (drop.rejected || drop.overflow) onDrop?.(drop)+ return drop.rejected === 0 && drop.overflow === 0}, [commit])const remove = useCallback((index: number) => {diff --git a/client/src/components/Collab/useCollabChat.ts b/client/src/components/Collab/useCollabChat.tsindex fb26bd3e5..51e071ae4 100644--- a/client/src/components/Collab/useCollabChat.ts+++ b/client/src/components/Collab/useCollabChat.ts@@ -5,7 +5,7 @@ import { useCanDo } from '../../store/permissionsStore'import { useTripStore } from '../../store/tripStore'import { addListener, removeListener } from '../../api/websocket'import { useTranslation } from '../../i18n'-import { useChatImages } from './useChatImages'+import { useChatImages, MAX_CHAT_IMAGES } from './useChatImages'import { useToast } from '../shared/Toast'export function useCollabChat(tripId: any, currentUser: any) {@@ -122,7 +122,10 @@ export function useCollabChat(tripId: any, currentUser: any) {/* ── send ── */const addImageFiles = useCallback((incoming: File[] | FileList) => {- if (!images.add(incoming)) toast.error(t('collab.chat.imageRejected'))+ images.add(incoming, ({ rejected, overflow }) => {+ if (rejected) toast.error(t('collab.chat.imageRejected'))+ if (overflow) toast.error(t('collab.chat.imageLimit', { max: MAX_CHAT_IMAGES }))+ })}, [images, toast, t])const removeImage = images.removeconst handlePaste = useCallback((e: ClipboardEvent) => { if (e.clipboardData.files.length) addImageFiles(e.clipboardData.files) }, [addImageFiles])diff --git a/client/src/components/Dawarich/DawarichAcceptDialog.test.tsx b/client/src/components/Dawarich/DawarichAcceptDialog.test.tsxindex 9ec20f1d9..d409c3629 100644--- a/client/src/components/Dawarich/DawarichAcceptDialog.test.tsx+++ b/client/src/components/Dawarich/DawarichAcceptDialog.test.tsx@@ -1,4 +1,4 @@-// FE-DAWARICH-ACCEPT-001 to FE-DAWARICH-ACCEPT-024+// FE-DAWARICH-ACCEPT-001 to FE-DAWARICH-ACCEPT-026/*** The review step between a detector's guess and a row in somebody's trip.*@@ -11,7 +11,8 @@* pinning, and it is the one a refactor breaks first.** The rest is the shape of the three targets. `place` needs a trip and offers a- * day, `journal` needs a journey and asks for a story, `bucket_list` needs a+ * day (and no date: the day IS where it lands, and the server reads no date for+ * a place), `journal` needs a journey, a date and a story, `bucket_list` needs a* matched wish and hides the clock entirely because ticking a wish off uses the* recorded timestamp and nothing else. Each of the three can be in a state* where there is nothing to write to (no trips, no journeys, no matched wish),@@ -173,20 +174,20 @@ describe('DawarichAcceptDialog', () => {fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Café Reichard am Dom' } })fireEvent.change(screen.getByLabelText('Notes'), { target: { value: 'Two hours and a lot of cake.' } })- typeDate('2026-09-12')fireEvent.change(screen.getByLabelText('Arrived'), { target: { value: '09:00' } })fireEvent.change(screen.getByLabelText('Left'), { target: { value: '11:45' } })pick('Not on a day yet', 'Day 1')fireEvent.click(screen.getByRole('button', { name: 'Add place' }))+ // The day is the only calendar fact a place carries: there is no date in+ // this body because there is no date field on this rail.expect(onConfirm).toHaveBeenCalledWith({target: 'place',tripId: 31,dayId: 401,name: 'Café Reichard am Dom',notes: 'Two hours and a lot of cake.',- date: '2026-09-12',time: '09:00',endTime: '11:45',})@@ -381,10 +382,11 @@ describe('DawarichAcceptDialog', () => {it('FE-DAWARICH-ACCEPT-018: a recording with no readable clock or date sends neither', () => {// Dawarich has shipped date-only and non-ISO timestamps; the clock parser// answers with an empty string rather than a guess, and an empty string must- // not reach the body as `time: ""`.+ // not reach the body as `time: ""` or `date: ""`. On the journal rail,+ // because that is the one rail that shows the date beside the clock.const { onConfirm } = open({- trips: TRIPS,- daysForTrip,+ target: 'journal',+ journals: JOURNALS,suggestion: stay({ startedAt: '2026-09-10', endedAt: '2026-09-10', localDate: '' }),})@@ -392,8 +394,8 @@ describe('DawarichAcceptDialog', () => {expect(screen.getByLabelText('Left')).toHaveValue('')expect(screen.getByRole('button', { name: 'Date' })).toBeInTheDocument()- fireEvent.click(screen.getByRole('button', { name: 'Add place' }))- expect(onConfirm).toHaveBeenCalledWith({ target: 'place', tripId: 31 })+ fireEvent.click(screen.getByRole('button', { name: 'Add entry' }))+ expect(onConfirm).toHaveBeenCalledWith({ target: 'journal', journalId: 71 })})it('FE-DAWARICH-ACCEPT-019: the fields follow the stay, and survive a re-render of the same one', () => {@@ -524,4 +526,43 @@ describe('DawarichAcceptDialog', () => {endTime: '12:40',})})++ it('FE-DAWARICH-ACCEPT-025: the place rail offers no date, because the day picker is where a place lands', () => {+ open({ trips: TRIPS, daysForTrip })++ // A place has no date of its own: the server reads a date for a journal+ // entry and for nothing else, so a date field on this rail was one whose+ // change moved the place nowhere while the toast still said it landed.+ // The clock stays, the server does read that.+ expect(screen.queryByText('Date')).toBeNull()+ expect(screen.queryByRole('button', { name: 'Enter date manually' })).toBeNull()+ expect(screen.getByLabelText('Arrived')).toHaveValue('10:15')+ expect(screen.getByLabelText('Left')).toHaveValue('12:40')+ expect(screen.getByRole('button', { name: 'Not on a day yet' })).toBeInTheDocument()+ })++ it('FE-DAWARICH-ACCEPT-026: a corrected date travels with a journal entry, and never with a place', () => {+ // Both rails on one stay, so the dialog holds the corrected date in state+ // across the switch: the same shape as switching rails with a note typed.+ const { onConfirm, update } = open({ target: 'journal', journals: JOURNALS, trips: TRIPS, daysForTrip })++ expect(screen.getByText('Date')).toBeInTheDocument()+ typeDate('2026-09-12')+ fireEvent.click(screen.getByRole('button', { name: 'Add entry' }))+ expect(onConfirm).toHaveBeenLastCalledWith({+ target: 'journal',+ journalId: 71,+ date: '2026-09-12',+ time: '10:15',+ endTime: '12:40',+ })++ // Same stay, now as a place. The corrected date is still in state and would+ // be silently dropped by the server; it must not be in the body at all,+ // so what the dialog claims to send is what is actually written.+ update({ target: 'place' })+ expect(screen.queryByText('Date')).toBeNull()+ fireEvent.click(screen.getByRole('button', { name: 'Add place' }))+ expect(onConfirm).toHaveBeenLastCalledWith({ target: 'place', tripId: 31, time: '10:15', endTime: '12:40' })+ })})diff --git a/client/src/components/Dawarich/DawarichAcceptDialog.tsx b/client/src/components/Dawarich/DawarichAcceptDialog.tsxindex 9faeca089..c8cdcfc01 100644--- a/client/src/components/Dawarich/DawarichAcceptDialog.tsx+++ b/client/src/components/Dawarich/DawarichAcceptDialog.tsx@@ -114,7 +114,10 @@ export default function DawarichAcceptDialog({}if (name.trim() && name.trim() !== suggestion.name) body.name = name.trim()if (notes.trim()) body.notes = notes.trim()- if (date && date !== suggestion.localDate) body.date = date+ // Only an entry carries a date. A place lands on the day chosen below and+ // the server reads nothing else for it, so a date corrected on the journal+ // rail must not ride along when the same stay is then added as a place.+ if (target === 'journal' && date && date !== suggestion.localDate) body.date = dateif (time) body.time = timeif (endTime) body.endTime = endTimeonConfirm(body)@@ -199,15 +202,27 @@ export default function DawarichAcceptDialog({itself from the OS locale and a native `type="time"` ignores the 12h/24hsetting outright (#2067) — and neither follows the colour scheme. Thedate column is the wide one because a localized date is long and a- clock never is. */}+ clock never is.++ The date is the journal rail's alone. A place has no date of its own:+ the day picker below is where it lands, and a date field beside that+ picker was a second answer to the same question, one the server never+ read. The two clocks then share the row the way they do on the place+ form. */}{target !== 'bucket_list' && (- <div className="grid grid-cols-1 sm:grid-cols-[minmax(0,1fr)_124px_124px] gap-2">- <div>- <span className="block text-caption font-medium mb-1.5 text-content-secondary">- {t('dawarich.accept.date')}- </span>- <CustomDatePicker value={date} onChange={setDate} />- </div>+ <div+ className={`grid grid-cols-1 gap-2 ${+ target === 'journal' ? 'sm:grid-cols-[minmax(0,1fr)_124px_124px]' : 'sm:grid-cols-2'+ }`}+ >+ {target === 'journal' && (+ <div>+ <span className="block text-caption font-medium mb-1.5 text-content-secondary">+ {t('dawarich.accept.date')}+ </span>+ <CustomDatePicker value={date} onChange={setDate} />+ </div>+ )}<div><span className="block text-caption font-medium mb-1.5 text-content-secondary">{t('dawarich.accept.from')}diff --git a/client/src/components/Files/docsync/DocSyncBinding.test.tsx b/client/src/components/Files/docsync/DocSyncBinding.test.tsxindex b47112f65..5e5f240ca 100644--- a/client/src/components/Files/docsync/DocSyncBinding.test.tsx+++ b/client/src/components/Files/docsync/DocSyncBinding.test.tsx@@ -1,5 +1,6 @@-// FE-DOCSYNC-BIND-001 to FE-DOCSYNC-BIND-026+// FE-DOCSYNC-BIND-001 to FE-DOCSYNC-BIND-030import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import en from '@trek/shared/i18n/en'import { render, screen, fireEvent, waitFor, within } from '../../../../tests/helpers/render'import DocSyncBinding from './DocSyncBinding'import type { DocSyncLink, useDocSync } from './useDocSync'@@ -64,6 +65,7 @@ function renderCard(sync?: Partial<Sync>canManage?: booleanproviderName?: string+ onReconnect?: () => void} = {},) {const utils = render(@@ -72,6 +74,7 @@ function renderCard(providerName={opts.providerName ?? 'Paperless'}sync={makeSync(opts.sync)}canManage={opts.canManage ?? true}+ onReconnect={opts.onReconnect}/>,)const header = utils.container.querySelector('header') as HTMLElement@@ -82,6 +85,15 @@ const openSettings = () => fireEvent.click(screen.getByRole('button', { name: 'Sconst rowFor = (label: string) => screen.getByText(label).closest('div') as HTMLElement+const UNLINK_QUESTION = 'Documents stay in TREK and at the store. Only the pairing between them goes.'++/** The confirmation the disconnect button opens; it renders in a portal. */+const unlinkDialog = () => within(screen.getByText(UNLINK_QUESTION).closest('.trek-modal-enter') as HTMLElement)++/** Named through the same fallback chain `t()` uses, so the label can land in the locales later. */+const reconnectButton = () =>+ screen.queryByRole('button', { name: (en as unknown as Record<string, string>)['docsync.binding.reconnect'] ?? 'docsync.binding.reconnect' })+beforeEach(() => {vi.clearAllMocks()})@@ -112,12 +124,75 @@ describe('DocSyncBinding: running a sync', () => {expect(screen.getByRole('button', { name: 'Sync now' })).toBeEnabled()})- it('FE-DOCSYNC-BIND-004: the disconnect button unlinks this binding', () => {+ it('FE-DOCSYNC-BIND-004: the disconnect button asks first and unlinks once that is confirmed', () => {+ // As the phone does. The button sits beside "Sync now", and a binding+ // cannot be put back: rebinding the same folder starts from nothing.renderCard()fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }))+ expect(removeLink).not.toHaveBeenCalled()+ expect(screen.getByText(UNLINK_QUESTION)).toBeInTheDocument()++ fireEvent.click(unlinkDialog().getByRole('button', { name: 'Disconnect' }))+expect(removeLink).toHaveBeenCalledWith(4)+ expect(screen.queryByText(UNLINK_QUESTION)).not.toBeInTheDocument()+ })++ it('FE-DOCSYNC-BIND-027: cancelling the question leaves the binding as it was', () => {+ renderCard()++ fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }))+ fireEvent.click(unlinkDialog().getByRole('button', { name: 'Cancel' }))++ expect(removeLink).not.toHaveBeenCalled()+ expect(screen.queryByText(UNLINK_QUESTION)).not.toBeInTheDocument()+ })+})++describe('DocSyncBinding: a refused credential', () => {+ it('FE-DOCSYNC-BIND-028: offers to sign in again beside the notice, and hands the click to the panel', () => {+ // The sidebar opens the credential form only for a store with no+ // connection yet, so a rotated token had no way back in from the app.+ const onReconnect = vi.fn()+ renderCard({ link: { lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' }, onReconnect })++ expect(screen.getByText('Sign in again · The credentials were refused.')).toBeInTheDocument()+ fireEvent.click(reconnectButton() as HTMLElement)++ expect(onReconnect).toHaveBeenCalledTimes(1)+ })++ it('FE-DOCSYNC-BIND-029: a refusal recorded as a failed run offers it too', () => {+ const onReconnect = vi.fn()+ renderCard({ link: { lastSyncState: 'failed', lastSyncError: 'unauthorized' }, onReconnect })++ expect(reconnectButton()).toBeInTheDocument()+ })++ it('FE-DOCSYNC-BIND-030: is not offered to a member, for another failure, or while the provider is switched off', () => {+ const onReconnect = vi.fn()+ const refused = { lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' } as const++ const member = renderCard({ link: refused, onReconnect, canManage: false })+ expect(reconnectButton()).not.toBeInTheDocument()+ member.unmount()++ const other = renderCard({ link: { lastSyncState: 'failed', lastSyncError: 'unreachable' }, onReconnect })+ expect(reconnectButton()).not.toBeInTheDocument()+ other.unmount()++ // An admin has switched the store off: the paused notice stands in front,+ // and a new credential would change nothing until it is back on.+ const paused = renderCard({ link: { ...refused, providerOff: true }, onReconnect })+ expect(reconnectButton()).not.toBeInTheDocument()+ paused.unmount()++ // The panel could not find the provider's form: nothing to open.+ renderCard({ link: refused })+ expect(reconnectButton()).not.toBeInTheDocument()+ expect(onReconnect).not.toHaveBeenCalled()})})diff --git a/client/src/components/Files/docsync/DocSyncBinding.tsx b/client/src/components/Files/docsync/DocSyncBinding.tsxindex fa6a67c06..c8419c623 100644--- a/client/src/components/Files/docsync/DocSyncBinding.tsx+++ b/client/src/components/Files/docsync/DocSyncBinding.tsx@@ -2,6 +2,7 @@ import { useState } from 'react'import {AlertTriangle, Check, ChevronDown, Clock, Copy, FolderOpen, Link2Off, RefreshCw,} from 'lucide-react'+import ConfirmDialog from '../../shared/ConfirmDialog'import CustomSelect from '../../shared/CustomSelect'import ToggleSwitch from '../../Settings/ToggleSwitch'import Tooltip from '../../shared/Tooltip'@@ -9,7 +10,7 @@ import { useTranslation } from '../../../i18n/TranslationContext'import { DOCUMENT_PROVIDER_ICONS } from '../../shared/DocumentProviderIcons'import DocSyncFlow, { type SyncDirection } from './DocSyncFlow'import { Badge, CONFLICT_POLICIES, conflictPolicyKey, LastRun, StateBadge } from './DocSyncBits'-import { bindingNotice, type DocSyncLink, type useDocSync } from './useDocSync'+import { bindingNotice, needsReauth, type DocSyncLink, type useDocSync } from './useDocSync'/*** One binding: where this trip's documents live, which way they move, and what@@ -25,18 +26,30 @@ export default function DocSyncBinding({providerName,sync,canManage,+ onReconnect,}: {link: DocSyncLinkproviderName: stringsync: ReturnType<typeof useDocSync>canManage: boolean+ /**+ * Opens the credential form for this binding's store. Only the panel can,+ * because the form needs the provider's field list, which the card does+ * not carry; left out, a refused credential is reported but not curable.+ */+ onReconnect?: () => void}) {const { t } = useTranslation()const [open, setOpen] = useState(false)const [copied, setCopied] = useState(false)+ const [confirmUnlink, setConfirmUnlink] = useState(false)const Icon = DOCUMENT_PROVIDER_ICONS[link.providerId]const busy = sync.busy === `sync-${link.id}`const notice = bindingNotice(link, t)+ // Not while the provider is switched off: the paused notice stands in front+ // of the refusal then, and a new credential would change nothing until an+ // admin turns the provider back on.+ const reconnect = canManage && onReconnect && !link.providerOff && needsReauth(link) ? onReconnect : nullconst copyWebhook = async () => {if (!link.webhookUrl) return@@ -97,11 +110,15 @@ export default function DocSyncBinding({text still changes to "Syncing". */}<span className="sr-only sm:not-sr-only">{busy ? t('docsync.syncing') : t('docsync.syncNow')}</span></button>+ {/* Asked first, as the phone does: the button sits a hand's width+ from "Sync now", and a binding cannot be put back. Rebinding the+ same folder starts from nothing and copies both sides over+ again. */}{canManage && (<Tooltip label={t('docsync.unlink')}><buttontype="button"- onClick={() => void sync.removeLink(link.id)}+ onClick={() => setConfirmUnlink(true)}className="grid h-9 w-9 place-items-center rounded-lg border border-edge bg-surface text-content-muted transition-colors hover:bg-danger-soft hover:text-danger"aria-label={t('docsync.unlink')}>@@ -115,10 +132,31 @@ export default function DocSyncBinding({{notice && (<p className="mx-4 mb-3 flex items-start gap-2 rounded-lg bg-warning-soft px-3 py-2 text-caption text-warning"><AlertTriangle size={13} className="mt-px shrink-0" />- <span>{notice}</span>+ <span className="min-w-0 flex-1">{notice}</span>+ {/* The one state a person can act on from here. Without this the+ only way past a rotated token was the API: the sidebar opens the+ form for a store that has no connection yet, and this one has. */}+ {reconnect && (+ <button+ type="button"+ onClick={reconnect}+ className="shrink-0 rounded-lg border border-edge bg-surface px-2.5 py-1 text-caption font-medium text-content transition-colors hover:bg-surface-hover"+ >+ {t('docsync.binding.reconnect')}+ </button>+ )}</p>)}+ <ConfirmDialog+ isOpen={confirmUnlink}+ onClose={() => setConfirmUnlink(false)}+ onConfirm={() => void sync.removeLink(link.id)}+ title={t('docsync.unlink')}+ message={t('docsync.confirmUnlink')}+ confirmLabel={t('docsync.unlink')}+ />+<div className="px-4 pb-3"><DocSyncFlowdirection={link.direction}diff --git a/client/src/components/Files/docsync/DocSyncPanel.test.tsx b/client/src/components/Files/docsync/DocSyncPanel.test.tsxindex 9cd137490..1eee95f65 100644--- a/client/src/components/Files/docsync/DocSyncPanel.test.tsx+++ b/client/src/components/Files/docsync/DocSyncPanel.test.tsx@@ -1,4 +1,4 @@-// FE-DOCSYNC-PANEL-001 to FE-DOCSYNC-PANEL-018+// FE-DOCSYNC-PANEL-001 to FE-DOCSYNC-PANEL-022/*** The document-sync dialog shell (#2391).@@ -25,6 +25,9 @@ const status = vi.fn()const deleteLink = vi.fn()const updateLink = vi.fn()const syncNow = vi.fn()+const items = vi.fn()+const resolve = vi.fn()+const saveConnection = vi.fn()vi.mock('../../../api/client', async (importOriginal) => {const actual = await importOriginal<typeof import('../../../api/client')>()@@ -39,6 +42,9 @@ vi.mock('../../../api/client', async (importOriginal) => {deleteLink: (tripId: number | string, linkId: number) => deleteLink(tripId, linkId),updateLink: (tripId: number | string, linkId: number, patch: unknown) => updateLink(tripId, linkId, patch),syncNow: (tripId: number | string, linkId: number, full: boolean) => syncNow(tripId, linkId, full),+ items: (tripId: number | string, state?: string) => items(tripId, state),+ resolve: (tripId: number | string, itemId: number, keep: string) => resolve(tripId, itemId, keep),+ saveConnection: (tripId: number | string, data: unknown) => saveConnection(tripId, data),},}})@@ -76,15 +82,17 @@ const link = (id: number, providerId: string, overrides: Partial<DocSyncLink> =/** What the server answers, as one object the tests reshape per case. */function serverHas({providers: p = [],+ connections = [],links = [],items = {},}: {providers?: DocSyncProvider[]+ connections?: Array<Record<string, unknown>>links?: DocSyncLink[]items?: Record<string, number>}): void {providers.mockResolvedValue(p)- listConnections.mockResolvedValue([])+ listConnections.mockResolvedValue(connections)listLinks.mockResolvedValue(links)status.mockResolvedValue({items,@@ -92,6 +100,18 @@ function serverHas({})}+/** The stored connection a binding runs under. */+const connection = (id: number, providerId: string) => ({+ id,+ providerId,+ baseUrl: 'https://docs.example.org',+ settings: {},+ secrets: { token: '***' },+ allowInsecureTls: false,+ lastProbeState: 'ok',+ lastProbeError: null,+})+function deferred<T>() {let resolve!: (value: T) => voidconst promise = new Promise<T>(r => { resolve = r })@@ -110,12 +130,25 @@ const sidebar = () => screen.getByRole('navigation')const group = (heading: string) =>within(screen.getByRole('heading', { name: heading }).parentElement as HTMLElement)+/** The "needs a look" section under the binding card. */+const issues = () =>+ within(screen.getByRole('heading', { name: t('docsync.issues.title') }).closest('section') as HTMLElement)++/** Disconnect asks first; this answers yes. The question renders in a portal. */+const confirmUnlink = () => {+ const dialog = screen.getByText(t('docsync.confirmUnlink')).closest('.trek-modal-enter') as HTMLElement+ fireEvent.click(within(dialog).getByRole('button', { name: t('docsync.unlink') }))+}+beforeEach(() => {vi.clearAllMocks()serverHas({})deleteLink.mockResolvedValue({})updateLink.mockResolvedValue({})syncNow.mockResolvedValue({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })+ items.mockResolvedValue([])+ resolve.mockResolvedValue({ success: true })+ saveConnection.mockResolvedValue({ id: 1 })})describe('DocSyncPanel: first load', () => {@@ -316,6 +349,7 @@ describe('DocSyncPanel: removing a binding', () => {expect(within(binding()).getByText('Folder 2')).toBeInTheDocument()fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.unlink') }))+ confirmUnlink()await waitFor(() => expect(deleteLink).toHaveBeenCalledWith(7, 2))await waitFor(() => expect(within(binding()).getByText('Folder 1')).toBeInTheDocument())@@ -334,6 +368,7 @@ describe('DocSyncPanel: removing a binding', () => {await screen.findByRole('article')fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.unlink') }))+ confirmUnlink()expect(await screen.findByText(t('docsync.empty.title'))).toBeInTheDocument()expect(screen.getByText(t('docsync.empty.hintOwner'))).toBeInTheDocument()@@ -388,6 +423,93 @@ describe('DocSyncPanel: what needs a look', () => {expect(within(rows[1]).getByText('1')).toBeInTheDocument()expect(panel.queryByText(t('docsync.state.pending'))).not.toBeInTheDocument()})++ it('FE-DOCSYNC-PANEL-019: a member is shown the conflict count but offered no choice', async () => {+ // The server refuses a member's choice with 403, so the three buttons+ // would only ever fail for them. The count is what they are owed.+ serverHas({+ providers: [provider('paperless', 'Paperless-ngx')],+ links: [link(1, 'paperless')],+ items: { conflict: 2 },+ })++ render(<DocSyncPanel tripId={7} canManage={false} onClose={onClose} />)+ await screen.findByRole('article')++ const row = issues().getAllByRole('listitem')[0]+ expect(within(row).getByText(t('docsync.state.conflict'))).toBeInTheDocument()+ expect(within(row).getByText('2')).toBeInTheDocument()+ expect(within(row).queryByRole('button')).not.toBeInTheDocument()+ expect(items).not.toHaveBeenCalled()+ })++ it('FE-DOCSYNC-PANEL-020: a choice the server refuses is said in the column, and the row stays', async () => {+ serverHas({+ providers: [provider('paperless', 'Paperless-ngx')],+ links: [link(1, 'paperless')],+ items: { conflict: 1 },+ })+ items.mockResolvedValue([{ id: 40, file_name: 'boarding-pass.pdf', remote_name: 'boarding-pass.pdf' }])+ // Settled by the owner in another tab a moment ago.+ resolve.mockRejectedValue({ response: { status: 400, data: { error: 'conflict' } } })++ render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)+ await screen.findByRole('article')++ fireEvent.click(issues().getByRole('button', { name: /Resolve/ }))+ fireEvent.click(await issues().findByRole('button', { name: t('docsync.conflict.keepTrek') }))++ await waitFor(() => expect(resolve).toHaveBeenCalledWith(7, 40, 'trek'))+ expect(await screen.findByRole('alert')).toHaveTextContent(t('docsync.error.conflict'))+ // The list is read back rather than trimmed by hand, so the row is still+ // there, ready for another try.+ await waitFor(() => expect(issues().getByRole('button', { name: t('docsync.conflict.keepTrek') })).toBeEnabled())+ expect(issues().getByText('boarding-pass.pdf')).toBeInTheDocument()+ expect(items).toHaveBeenCalledTimes(2)+ })+})++describe('DocSyncPanel: what a click on the card reports', () => {+ it('FE-DOCSYNC-PANEL-021: a refused run is said under the card rather than swallowed', async () => {+ serverHas({ providers: [provider('paperless', 'Paperless-ngx')], links: [link(1, 'paperless')] })+ syncNow.mockRejectedValue({ response: { status: 409, data: { error: 'provider_disabled' } } })++ render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)+ await screen.findByRole('article')+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()++ fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.syncNow') }))++ expect(await screen.findByRole('alert')).toHaveTextContent(t('docsync.error.provider_disabled'))+ expect(screen.getByRole('article')).toBeInTheDocument()+ })++ it('FE-DOCSYNC-PANEL-022: a refused credential opens the form for the bound store, and saving runs the binding', async () => {+ // The sidebar only ever opened the form for a store with no connection+ // yet, and a bound store is not listed there, so a rotated token could+ // only be entered through the API.+ serverHas({+ providers: [provider('paperless', 'Paperless-ngx')],+ connections: [connection(5, 'paperless')],+ links: [link(1, 'paperless', { lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' })],+ })++ render(<DocSyncPanel tripId={7} canManage onClose={onClose} />)+ await screen.findByRole('article')++ fireEvent.click(within(binding()).getByRole('button', { name: t('docsync.binding.reconnect') }))++ // The credential form, for this store, not the folder picker.+ expect(screen.getByRole('button', { name: t('docsync.connect.submit') })).toBeInTheDocument()+ expect(screen.queryByText(t('docsync.scope.pickTitle'))).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: t('docsync.connect.submit') }))++ await waitFor(() => expect(saveConnection).toHaveBeenCalledWith(7, expect.objectContaining({ providerId: 'paperless' })))+ await waitFor(() => expect(syncNow).toHaveBeenCalledWith(7, 1, false))+ await waitFor(() => expect(screen.queryByRole('button', { name: t('docsync.connect.submit') })).not.toBeInTheDocument())+ expect(screen.queryByText(t('docsync.scope.pickTitle'))).not.toBeInTheDocument()+ })})describe('DocSyncPanel: the dialog itself', () => {diff --git a/client/src/components/Files/docsync/DocSyncPanel.tsx b/client/src/components/Files/docsync/DocSyncPanel.tsxindex de5f2af10..0eb8afca6 100644--- a/client/src/components/Files/docsync/DocSyncPanel.tsx+++ b/client/src/components/Files/docsync/DocSyncPanel.tsx@@ -41,10 +41,17 @@ export default function DocSyncPanel({const [selected, setSelected] = useState<number | null>(null)const [connecting, setConnecting] = useState<DocSyncProvider | null>(null)const [scopeFor, setScopeFor] = useState<string | null>(null)+ // The credential form again, for a store this trip is already bound to. Kept+ // apart from `connecting`, whose next step is the folder picker: here the+ // folder is known and the next step is the run that the refusal stopped.+ const [reconnecting, setReconnecting] = useState<DocSyncProvider | null>(null)const bound = useMemo(() => new Set(sync.links.map(l => l.providerId)), [sync.links])const available = sync.providers.filter(p => !bound.has(p.id))const active = sync.links.find(l => l.id === selected) ?? sync.links[0] ?? null+ // Undefined once an admin has switched the store off: the form needs the+ // provider's field list, and the providers route no longer carries it.+ const activeProvider = active ? sync.providers.find(p => p.id === active.providerId) : undefined// Follow the list: a freshly bound store should be the one on screen, and a// removed one must not leave the detail column pointing at nothing.@@ -98,8 +105,20 @@ export default function DocSyncPanel({providerName={storeName(active, sync.providers)}sync={sync}canManage={canManage}+ onReconnect={activeProvider ? () => setReconnecting(activeProvider) : undefined}/>- {attention > 0 && <Attention counts={sync.itemCounts} tripId={tripId} sync={sync} />}+ {/* Every action in this column reports here: a refused run, a+ switch that flipped back, a conflict the server would not+ settle. The two dialogs say their own, but nothing said+ what happened to a click on the card itself. */}+ {sync.error && (+ <p role="alert" className="rounded-xl border border-edge bg-danger-soft px-3 py-2.5 text-caption text-danger">+ {t(`docsync.error.${sync.error}`)}+ </p>+ )}+ {attention > 0 && (+ <Attention counts={sync.itemCounts} tripId={tripId} sync={sync} canManage={canManage} />+ )}</div>) : (<NothingBound canManage={canManage} />@@ -118,6 +137,22 @@ export default function DocSyncPanel({/>)}+ {reconnecting && (+ <DocSyncConnectModal+ provider={reconnecting}+ sync={sync}+ onClose={() => setReconnecting(null)}+ onConnected={id => {+ setReconnecting(null)+ // Run straight away, as binding does: the card still reports the+ // refusal until a run says otherwise, and the person has just+ // done the one thing that could change the answer.+ const rebound = sync.links.find(l => l.providerId === id)+ if (rebound) void sync.syncNow(rebound.id)+ }}+ />+ )}+{scopeFor && sync.connectionFor(scopeFor) && (<DocSyncScopeModalconnection={sync.connectionFor(scopeFor)!}@@ -267,10 +302,12 @@ function Attention({counts,tripId,sync,+ canManage,}: {counts: Record<string, number>tripId: number | stringsync: ReturnType<typeof useDocSync>+ canManage: boolean}) {const { t } = useTranslation()const rows = ATTENTION_STATES.filter(k => (counts[k] ?? 0) > 0)@@ -292,8 +329,10 @@ function Attention({<span className="mt-0.5 block text-caption text-content-muted">{t(`docsync.issues.${k}`)}</span></span>{/* A conflict is the one of these a person can act on, so it is- the one that opens. The rest are a state to read. */}- {k === 'conflict' ? (+ the one that opens. The rest are a state to read. Only for+ the owner: the server refuses a member's choice, so a member+ gets the count, like every other row. */}+ {k === 'conflict' && canManage ? (<buttontype="button"onClick={() => setShowConflicts(v => !v)}@@ -306,7 +345,7 @@ function Attention({)}</div>- {k === 'conflict' && showConflicts && (+ {k === 'conflict' && canManage && showConflicts && (<ul className="mt-3 space-y-2">{conflicts.items === null && (<li className="flex justify-center py-2">diff --git a/client/src/components/Files/docsync/DocSyncScopeModal.test.tsx b/client/src/components/Files/docsync/DocSyncScopeModal.test.tsxindex 3bea464d2..f9c0ebdd7 100644--- a/client/src/components/Files/docsync/DocSyncScopeModal.test.tsx+++ b/client/src/components/Files/docsync/DocSyncScopeModal.test.tsx@@ -1,4 +1,4 @@-// FE-DOCSYNC-SCOPE-001 to FE-DOCSYNC-SCOPE-022+// FE-DOCSYNC-SCOPE-001 to FE-DOCSYNC-SCOPE-023/*** The folder picker of the document-sync dialog.@@ -364,4 +364,20 @@ describe('DocSyncScopeModal errors', () => {expect(await screen.findByText(S['docsync.error.scope_missing'])).toBeInTheDocument()expect(screen.queryByText('Trips')).not.toBeInTheDocument()})++ it('FE-DOCSYNC-SCOPE-023: a listing request that fell over says so instead of spinning forever', async () => {+ // The store answers 200 with a code when it refuses, but a request that+ // never got an answer (a store behind a VPN that is down, a connection an+ // admin deleted meanwhile) rejected instead, nothing caught it, and the+ // spinner was all the picker ever showed.+ listScopes.mockRejectedValue({ code: 'ECONNABORTED', message: 'timeout of 60000ms exceeded' })+ render(<Harness />)++ expect(await screen.findByText(S['docsync.error.unknown'])).toBeInTheDocument()+ expect(document.querySelector('.animate-spin')).toBeNull()+ expect(screen.queryByText(S['docsync.noFolders'])).not.toBeInTheDocument()+ // Making a new folder is still on offer: the store may well be reachable+ // for that, and it is the way out when the listing is what failed.+ expect(createButton()).toBeEnabled()+ })})diff --git a/client/src/components/Files/docsync/useDocSync.test.ts b/client/src/components/Files/docsync/useDocSync.test.tsindex 02128c8d9..48fc21a7b 100644--- a/client/src/components/Files/docsync/useDocSync.test.ts+++ b/client/src/components/Files/docsync/useDocSync.test.ts@@ -1,4 +1,4 @@-// FE-DOCSYNC-HOOK-001 to FE-DOCSYNC-HOOK-026+// FE-DOCSYNC-HOOK-001 to FE-DOCSYNC-HOOK-030/*** The document-sync hook.@@ -21,6 +21,8 @@ const saveConnectionApi = vi.fn(async (_tripId: number | string, _data: unknown)const testConnectionApi = vi.fn(async (_tripId: number | string, _data: unknown): Promise<unknown> => ({ connected: true }))const updateLinkApi = vi.fn(async (_tripId: number | string, _linkId: number, _patch: unknown): Promise<unknown> => ({}))const syncNowApi = vi.fn(async (_tripId: number | string, _linkId: number, _full: boolean): Promise<unknown> => ({}))+const listScopesApi = vi.fn(async (_tripId: number | string, _connectionId: number, _q?: string): Promise<unknown> => ({ scopes: [] }))+const resolveApi = vi.fn(async (_tripId: number | string, _itemId: number, _keep: string): Promise<unknown> => ({ success: true }))vi.mock('../../../api/client', async (importOriginal) => {const actual = await importOriginal<typeof import('../../../api/client')>()@@ -36,11 +38,13 @@ vi.mock('../../../api/client', async (importOriginal) => {testConnection: (tripId: number | string, data: unknown) => testConnectionApi(tripId, data),updateLink: (tripId: number | string, linkId: number, patch: unknown) => updateLinkApi(tripId, linkId, patch),syncNow: (tripId: number | string, linkId: number, full: boolean) => syncNowApi(tripId, linkId, full),+ listScopes: (tripId: number | string, connectionId: number, q?: string) => listScopesApi(tripId, connectionId, q),+ resolve: (tripId: number | string, itemId: number, keep: string) => resolveApi(tripId, itemId, keep),},}})-import { useDocSync, canManageDocSync, storeName, type DocSyncLink, type DocSyncProvider } from './useDocSync'+import { useDocSync, canManageDocSync, needsReauth, storeName, type DocSyncLink, type DocSyncProvider } from './useDocSync'const TRIP = 3@@ -120,6 +124,8 @@ beforeEach(() => {testConnectionApi.mockResolvedValue({ connected: true })updateLinkApi.mockResolvedValue({})syncNowApi.mockResolvedValue({ state: 'ok', pulled: 0, pushed: 0, conflicts: 0, missing: 0 })+ listScopesApi.mockResolvedValue({ scopes: [] })+ resolveApi.mockResolvedValue({ success: true })})describe('useDocSync initial load', () => {@@ -410,6 +416,71 @@ describe('useDocSync run and save feedback', () => {})})+describe('useDocSync loadScopes', () => {+ it('FE-DOCSYNC-HOOK-027: a request that fell over still produces a listing the picker can render', async () => {+ // The picker awaits this inside an effect with nothing to catch, so a+ // rejection never reached `setScopes` and the spinner ran forever. A store+ // behind a VPN that is down answers this way every time.+ listScopesApi.mockRejectedValueOnce({ code: 'ECONNABORTED', message: 'timeout of 60000ms exceeded' })+ const { result } = await mountLoaded()++ let listing: unknown+ await act(async () => { listing = await result.current.loadScopes(9) })++ expect(listing).toEqual({ scopes: [], error: 'unknown' })+ })++ it('FE-DOCSYNC-HOOK-028: a refusal with a code keeps the code, a sentence does not become a key', async () => {+ const { result } = await mountLoaded()+ let listing: { scopes: unknown[]; error?: string } | undefined++ listScopesApi.mockRejectedValueOnce({ response: { status: 400, data: { error: 'unknown_provider' } } })+ await act(async () => { listing = await result.current.loadScopes(9, 'tri') })+ expect(listing?.error).toBe('unknown_provider')+ expect(listScopesApi).toHaveBeenCalledWith(TRIP, 9, 'tri')++ // The picker renders this as docsync.error.<value>, so prose must not+ // arrive there as a translation key.+ listScopesApi.mockRejectedValueOnce({ response: { status: 404, data: { message: 'Connection not found' } } })+ await act(async () => { listing = await result.current.loadScopes(9) })+ expect(listing?.error).toBe('unknown')+ })+})++describe('useDocSync resolveConflict', () => {+ it('FE-DOCSYNC-HOOK-029: a refused choice says why instead of vanishing into a void call', async () => {+ // Both shells call this as `void conflicts.resolve(...)`. A member's choice+ // answers 403 and a row settled elsewhere answers 400; either way the+ // button came back and nothing said what happened.+ resolveApi.mockRejectedValueOnce({ response: { status: 403, data: { error: 'forbidden' } } })+ const { result } = await mountLoaded()++ let outcome: boolean | undefined+ await act(async () => { outcome = await result.current.resolveConflict(4, 'trek') })++ expect(outcome).toBe(false)+ expect(result.current.error).toBe('forbidden')+ // reloaded, so the counts are the server's, and the message survived it+ expect(listLinksApi).toHaveBeenCalledTimes(2)++ await act(async () => { outcome = await result.current.resolveConflict(4, 'provider') })++ expect(outcome).toBe(true)+ expect(result.current.error).toBeNull()+ expect(resolveApi).toHaveBeenLastCalledWith(TRIP, 4, 'provider')+ })+})++describe('needsReauth', () => {+ it('FE-DOCSYNC-HOOK-030: reads a refused credential off either the state or the error code', () => {+ expect(needsReauth({ lastSyncState: 'needs_reauth', lastSyncError: null })).toBe(true)+ expect(needsReauth({ lastSyncState: 'failed', lastSyncError: 'unauthorized' })).toBe(true)+ expect(needsReauth({ lastSyncState: 'partial', lastSyncError: 'unauthorized' })).toBe(true)+ expect(needsReauth({ lastSyncState: 'failed', lastSyncError: 'unreachable' })).toBe(false)+ expect(needsReauth({ lastSyncState: 'ok', lastSyncError: null })).toBe(false)+ })+})+describe('storeName', () => {it('FE-DOCSYNC-HOOK-024: prefers the provider list, then the name on the link, then the raw id', () => {const bound = link() as DocSyncLinkdiff --git a/client/src/components/Files/docsync/useDocSync.ts b/client/src/components/Files/docsync/useDocSync.tsindex 7d2732df1..9cd8564f8 100644--- a/client/src/components/Files/docsync/useDocSync.ts+++ b/client/src/components/Files/docsync/useDocSync.ts@@ -111,6 +111,19 @@ export function bindingNotice(return link.lastSyncError ? `${state} · ${t(`docsync.error.${link.lastSyncError}`)}` : state}+/**+ * Whether the store has refused the stored credential.+ *+ * Two shapes say so. A refusal while listing is recorded as its own state; a+ * refusal anywhere else (resolving the folder, one transfer) leaves the state+ * at failed or partial and puts the reason in the error code. Either way the+ * cure is the same, a new credential, and both shells decide from here+ * whether to offer the form for it.+ */+export function needsReauth(link: Pick<DocSyncLink, 'lastSyncState' | 'lastSyncError'>): boolean {+ return link.lastSyncState === 'needs_reauth' || link.lastSyncError === 'unauthorized'+}+/*** Whether this person may change a sync binding.*@@ -261,9 +274,22 @@ export function useDocSync(tripId: number | string, enabled: boolean) {}}, [tripId])+ /**+ * The containers a connection can be bound to.+ *+ * Always resolves to a listing, the way `testConnection` always resolves to+ * a verdict: the route answers 200 with an error code when the store refuses,+ * and a request that fell over on the way (a store behind a VPN that is not+ * up, a connection an admin deleted meanwhile) has to reach the picker the+ * same way. Left to reject, it never reached `setScopes`, and the picker+ * spun forever with nothing said.+ */const loadScopes = useCallback(async (connectionId: number, q?: string) => {- const res = await docsyncApi.listScopes(tripId, connectionId, q) as { scopes: DocSyncScope[]; error?: string }- return res+ try {+ return await docsyncApi.listScopes(tripId, connectionId, q) as { scopes: DocSyncScope[]; error?: string }+ } catch (e: unknown) {+ return { scopes: [] as DocSyncScope[], error: readError(e) }+ }}, [tripId])/**@@ -364,9 +390,27 @@ export function useDocSync(tripId: number | string, enabled: boolean) {}}, [tripId, load])+ /**+ * Settle one conflict.+ *+ * Reports failure the way the other writes do. The rejection used to escape+ * into the `void` at the call site, so a refused choice (the row was settled+ * elsewhere a moment ago, or the server answered 403) put the button back+ * and left the row standing with nothing said.+ */const resolveConflict = useCallback(async (itemId: number, keep: 'trek' | 'provider' | 'both') => {- await docsyncApi.resolve(tripId, itemId, keep)- await load()+ setError(null)+ try {+ await docsyncApi.resolve(tripId, itemId, keep)+ await load()+ return true+ } catch (e: unknown) {+ // Reload first, so the counts match what the server has, then say why.+ // The other way round the reload cleared the message again.+ await load()+ setError(readError(e))+ return false+ }}, [tripId, load])/** Providers the admin switched on that also have a working adapter. */diff --git a/client/src/components/Map/MapViewGL.test.tsx b/client/src/components/Map/MapViewGL.test.tsxindex aa7e9dc1b..78f863aba 100644--- a/client/src/components/Map/MapViewGL.test.tsx+++ b/client/src/components/Map/MapViewGL.test.tsx@@ -2165,6 +2165,118 @@ describe('MapViewGL', () => {// in the wrong place.expect(layer.firstElementChild).not.toBe(handle)})++ // Both GL libraries take their clicks from the canvas container, and the handle sits+ // inside it, right on the route's hit band. Stopping pointerdown does not stop the click+ // that follows, so a click on a handle also read as a click on the road under it and+ // dropped a second via exactly there.+ it('FE-COMP-MAPVIEWGL-VIA-003: a click on a via handle is the handle\'s, not the road\'s', async () => {+ loadOnAttach()+ glCanvasContainer.replaceChildren()+ glMap.project.mockReturnValue({ x: 100, y: 80 })+ glMap.getLayer.mockImplementation((id: string) => (id === 'trip-route-hit' ? { id } : null))+ const onRouteClick = vi.fn()++ const stored = { id: 5, day_id: 1, after_order_index: 0, sequence: 0, lat: 48.1, lng: 2.1 }+ render(+ <MapViewGL+ places={[]}+ fitKey={1}+ glProvider="maplibre-gl"+ roadtripVias={{ 1: [stored] }}+ onMoveVia={() => {}}+ onRouteClick={onRouteClick}+ />,+ )+ await flushFrames()++ const layer = glCanvasContainer.firstElementChild as HTMLElement+ const handle = layer.firstElementChild as HTMLElement++ const reachedMap = vi.fn()+ glCanvasContainer.addEventListener('click', reachedMap)+ try {+ act(() => { handle.dispatchEvent(new MouseEvent('click', { bubbles: true })) })+ expect(reachedMap).not.toHaveBeenCalled()+ } finally {+ glCanvasContainer.removeEventListener('click', reachedMap)+ }++ // And the road's own handler leaves a click that came through the handle alone.+ const roadClick = layerHandler('click', 'trip-route-hit')+ expect(roadClick).toBeTypeOf('function')+ act(() => { roadClick({ lngLat: { lat: 48.1, lng: 2.1 }, point: { x: 100, y: 80 }, originalEvent: { target: handle } }) })+ expect(onRouteClick).not.toHaveBeenCalled()+ act(() => { roadClick({ lngLat: { lat: 48.1, lng: 2.1 }, point: { x: 100, y: 80 }, originalEvent: { target: glCanvasContainer } }) })+ expect(onRouteClick).toHaveBeenCalledWith(48.1, 2.1)+ })++ it('FE-COMP-MAPVIEWGL-VIA-004: a right-click on a via handle removes it and opens nothing underneath', async () => {+ loadOnAttach()+ glCanvasContainer.replaceChildren()+ glMap.project.mockReturnValue({ x: 100, y: 80 })+ const onRemoveVia = vi.fn()++ const stored = { id: 5, day_id: 1, after_order_index: 0, sequence: 0, lat: 48.1, lng: 2.1 }+ render(+ <MapViewGL+ places={[]}+ fitKey={1}+ glProvider="maplibre-gl"+ roadtripVias={{ 1: [stored] }}+ onMoveVia={() => {}}+ onRemoveVia={onRemoveVia}+ />,+ )+ await flushFrames()++ const layer = glCanvasContainer.firstElementChild as HTMLElement+ const handle = layer.firstElementChild as HTMLElement++ // The map's contextmenu is the add-place gesture; it must not fire for the spot the+ // via has just been removed from.+ const reachedMap = vi.fn()+ glCanvasContainer.addEventListener('contextmenu', reachedMap)+ try {+ act(() => { handle.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })) })+ } finally {+ glCanvasContainer.removeEventListener('contextmenu', reachedMap)+ }++ expect(onRemoveVia).toHaveBeenCalledWith(1, 5)+ expect(reachedMap).not.toHaveBeenCalled()+ })++ it('FE-COMP-MAPVIEWGL-VIA-005: the handles go away below the zoom a via can be aimed at', async () => {+ loadOnAttach()+ glCanvasContainer.replaceChildren()+ glMap.project.mockReturnValue({ x: 100, y: 80 })+ // Country scale: a day's vias collapse into a heap of dots over one town, and a+ // short drag on one of them moves the route by kilometres.+ vi.mocked(glMap.getZoom).mockReturnValue(8)+ try {+ const stored = { id: 5, day_id: 1, after_order_index: 0, sequence: 0, lat: 48.1, lng: 2.1 }+ render(+ <MapViewGL places={[]} fitKey={1} glProvider="maplibre-gl" roadtripVias={{ 1: [stored] }} onMoveVia={() => {}} />,+ )+ await flushFrames()++ const layer = glCanvasContainer.firstElementChild as HTMLElement+ const handle = layer.firstElementChild as HTMLElement+ expect(handle.style.display).toBe('none')++ // Back in close enough, the zoom that settles brings them back.+ vi.mocked(glMap.getZoom).mockReturnValue(12)+ act(() => {+ glMap.on.mock.calls+ .filter(c => c[0] === 'zoomend' && typeof c[1] === 'function')+ .forEach(c => (c[1] as () => void)())+ })+ expect(handle.style.display).toBe('block')+ } finally {+ vi.mocked(glMap.getZoom).mockReturnValue(10)+ }+ })// ── Satellite ───────────────────────────────────────────────────────────────//// Leaflet has had the imagery for a while and swaps its whole tile layer for it.diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsxindex 24c5dcf97..bb159d40e 100644--- a/client/src/components/Map/MapViewGL.tsx+++ b/client/src/components/Map/MapViewGL.tsx@@ -845,15 +845,17 @@ export function MapViewGL({const VIA_MIN_ZOOM = 9const applyViaZoom = () => {const on = map.getZoom() >= VIA_MIN_ZOOM- for (const pin of viaPinsRef.current) {- const node = (pin as { getElement?: () => HTMLElement | null }).getElement?.()- if (node) node.style.display = on ? '' : 'none'- }+ // `el` is the one handle both pin paths expose; the library marker's own accessor+ // does not exist on the hand-positioned pin, so reading that left every handle on.+ for (const pin of viaPinsRef.current) pin.el.style.display = on ? 'block' : 'none'}for (const via of vias) {const el = document.createElement('span')el.style.cssText = 'display:block;width:12px;height:12px;border-radius:9999px;background:#0a84ff;border:2.5px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.45);cursor:grab;touch-action:none'+ // Marks the handle for the map's own click handlers: the drive's hit band runs+ // right under it, and a click that lands here is the handle's, not the road's.+ el.dataset.viaHandle = ''const pin = attachPin(map, gl, pinLayerRef.current, el, via.lng, via.lat)viaPinsRef.current.push(pin)if (!viasDraggable) continue@@ -918,6 +920,10 @@ export function MapViewGL({}const onContext = (e: MouseEvent) => {e.preventDefault()+ // Stopped here as well: both GL libraries listen on the canvas container the+ // handle sits in, and the map's own contextmenu opens the add-place form at+ // the very spot the via has just been removed from.+ e.stopPropagation()viaHandlersRef.current.onRemoveVia?.(via.day_id, via.id)}el.addEventListener('pointerdown', onDown)@@ -928,6 +934,10 @@ export function MapViewGL({el.addEventListener('mousedown', swallow)el.addEventListener('touchstart', swallow, { passive: true })el.addEventListener('dblclick', swallow)+ // Stopping pointerdown does not stop the click that follows it, and the handle sits+ // on the route's hit band: the map's click landed on the road and dropped a second+ // via exactly under the one that was clicked.+ el.addEventListener('click', swallow)viaCleanupRef.current.push(() => {el.removeEventListener('pointerdown', onDown)el.removeEventListener('pointermove', onMove)@@ -937,6 +947,7 @@ export function MapViewGL({el.removeEventListener('mousedown', swallow)el.removeEventListener('touchstart', swallow)el.removeEventListener('dblclick', swallow)+ el.removeEventListener('click', swallow)})}@@ -1072,8 +1083,19 @@ export function MapViewGL({useEffect(() => {const map = mapRef.currentif (!map || !mapReady || !onRouteClick) return- const onClick = (e: { lngLat: { lat: number; lng: number }; point?: { x: number; y: number }; preventDefault?: () => void }) => {+ const onClick = (e: {+ lngLat: { lat: number; lng: number }+ point?: { x: number; y: number }+ originalEvent?: { target?: EventTarget | null }+ preventDefault?: () => void+ }) => {e.preventDefault?.()+ // A layer handler only asks what is drawn under the point, not what element the+ // click came through. A via handle sits on the band by definition, and a click on+ // it must not read as a click on the road under it; the map-level handler below+ // filters markers the same way.+ const target = e.originalEvent?.target+ if (target instanceof Element && target.closest('[data-via-handle], .mapboxgl-marker, .maplibregl-marker')) return// Layer handlers are independent: MapLibre evaluates each registration// against the same click, so a point that hits both the offered-route band// and the current-route band fires both. Every alternative starts and endsdiff --git a/client/src/components/Map/TripRouteOverview.test.tsx b/client/src/components/Map/TripRouteOverview.test.tsxindex 93a91eca7..3bc881995 100644--- a/client/src/components/Map/TripRouteOverview.test.tsx+++ b/client/src/components/Map/TripRouteOverview.test.tsx@@ -87,4 +87,39 @@ describe('TripRouteOverviewPanel', () => {const { container } = render(<TripRouteOverviewPanel overview={overview({ days: [], totalDistance: 0 })} unit="metric" />)expect(container).toBeEmptyDOMElement()})++ it('FE-MAP-TROU-009: says when legs could not be routed, and marks the day that is short', () => {+ // A refused leg stays a straight line and adds nothing to the sum, so a total shown+ // without a word about it reads as the whole trip when it is not.+ const days = overview().days+ const short = overview({+ days: [{ ...days[0], unroutedLegs: 1 }, { ...days[1], unroutedLegs: 0 }],+ unroutedLegs: 1,+ })+ render(<TripRouteOverviewPanel overview={short} unit="metric" />)++ expect(screen.getByTestId('trip-overview-unrouted')).toHaveTextContent('map.overview.unrouted')+ expect(screen.getAllByRole('img', { name: 'map.overview.dayUnrouted' })).toHaveLength(1)+ })++ it('FE-MAP-TROU-010: does not call a leg unrouted while the round is still running', () => {+ // Every leg still waiting is unrouted too; the ellipsis already says the number grows.+ const days = overview().days+ const running = overview({+ days: [{ ...days[0], unroutedLegs: 1 }, { ...days[1], unroutedLegs: 1 }],+ unroutedLegs: 2,+ loading: true,+ })+ render(<TripRouteOverviewPanel overview={running} unit="metric" />)++ expect(screen.queryByTestId('trip-overview-unrouted')).toBeNull()+ expect(screen.queryByRole('img', { name: 'map.overview.dayUnrouted' })).toBeNull()+ })++ it('FE-MAP-TROU-011: a fully routed trip carries no warning at all', () => {+ render(<TripRouteOverviewPanel overview={overview({ unroutedLegs: 0 })} unit="metric" />)++ expect(screen.queryByTestId('trip-overview-unrouted')).toBeNull()+ expect(screen.queryByRole('img', { name: 'map.overview.dayUnrouted' })).toBeNull()+ })})diff --git a/client/src/components/Map/TripRouteOverview.tsx b/client/src/components/Map/TripRouteOverview.tsxindex 1806dd3c6..2f9278a8d 100644--- a/client/src/components/Map/TripRouteOverview.tsx+++ b/client/src/components/Map/TripRouteOverview.tsx@@ -1,4 +1,4 @@-import { Route } from 'lucide-react'+import { AlertTriangle, Route } from 'lucide-react'import { useTranslation } from '../../i18n'import { Tooltip } from '../shared/Tooltip'import { profileIcon } from '../Planner/DayPlanSidebarRouteConnector'@@ -66,6 +66,9 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect}) {const { t } = useTranslation()if (!overview.days.length) return null+ // Only once the round is over: while it runs every leg still waiting is unrouted too,+ // and the ellipsis on the total already says the number is growing.+ const unrouted = overview.loading ? 0 : (overview.unroutedLegs ?? 0)return (<div@@ -95,9 +98,23 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect{overview.loading && <span className="text-content-muted" style={{ fontWeight: 400 }}>{' '}…</span>}</span></div>+ {/* A leg the router refused stays a straight line and adds nothing to the sum, so+ the total is short by however much road those legs are. Said in words rather than+ left to the reader to notice, because the number is what a fuel estimate starts from. */}+ {unrouted > 0 && (+ <div+ data-testid="trip-overview-unrouted"+ className="text-warning"+ style={{ display: 'flex', alignItems: 'flex-start', gap: 6, padding: '0 14px 8px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))' }}+ >+ <AlertTriangle size={12} style={{ flexShrink: 0, marginTop: 1 }} aria-hidden />+ <span>{t('map.overview.unrouted', { count: unrouted })}</span>+ </div>+ )}<div style={{ maxHeight: 220, overflowY: 'auto', borderTop: '1px solid var(--border-primary)' }}>{overview.days.map(day => {const label = day.title || t('dayplan.dayN', { n: day.dayNumber })+ const dayUnrouted = overview.loading ? 0 : (day.unroutedLegs ?? 0)const row = (<><span style={{ width: 8, height: 8, borderRadius: 999, background: day.color.line, flexShrink: 0 }} aria-hidden />@@ -110,6 +127,17 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectreturn <Icon key={mode} size={12} strokeWidth={2} aria-hidden />})}</span>+ {/* The day's own share of the shortfall, so the reader knows which figure+ to distrust rather than only that one of them is off. */}+ {dayUnrouted > 0 && (+ <AlertTriangle+ size={12}+ className="text-warning"+ style={{ flexShrink: 0 }}+ role="img"+ aria-label={t('map.overview.dayUnrouted', { count: dayUnrouted })}+ />+ )}<span className="text-content-muted" style={{ flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>{formatDistance(day.distance / 1000, unit)}</span>diff --git a/client/src/components/Map/tripRouteGeometry.test.ts b/client/src/components/Map/tripRouteGeometry.test.tsindex b082983ae..8df07b8cc 100644--- a/client/src/components/Map/tripRouteGeometry.test.ts+++ b/client/src/components/Map/tripRouteGeometry.test.ts@@ -9,7 +9,7 @@ vi.mock('./RouteCalculator', async (importActual) => {return { ...actual, calculateRouteWithLegs: vi.fn() }})-const { calculateRouteWithLegs } = await import('./RouteCalculator')+const { calculateRouteWithLegs, RoutingRefusedError } = await import('./RouteCalculator')const leg = (distance: number): RouteSegment => ({mid: [0, 0], from: [0, 0], to: [0, 0], distance, duration: 600,@@ -104,4 +104,112 @@ describe('tripRouteGeometry', () => {await expect(pending).resolves.toMatchObject({ totalDistance: 0 })})++ // The public OSRM hosts allow about one request a second. Every leg of every day at+ // once is exactly the burst they answer with 429 from the second second on, and each+ // refused leg used to stay a straight line with no distance and no word about it.+ it('FE-MAP-TRG-007: asks the router one leg at a time, a second apart', async () => {+ vi.useFakeTimers()+ try {+ // A round trip takes time; only a network answer is paced, a cache hit is not.+ vi.mocked(calculateRouteWithLegs).mockImplementation(() => new Promise(resolve => {+ setTimeout(() => resolve({ coordinates: [[48.86, 2.35], [48.90, 2.42]], distance: 10000, duration: 600, legs: [leg(10000)] }), 100)+ }))+ const pending = routeTrip(input, { profile: 'driving', tripId: 7 })++ // The second day waits for the first to answer...+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(100)+ // ...and then for the gap the shared hosts need between two requests.+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(1100)+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)++ await vi.advanceTimersByTimeAsync(100)+ const summary = await pending+ expect(summary.totalDistance).toBe(20000)+ expect(summary.unroutedLegs).toBe(0)+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-MAP-TRG-008: a rate limit is waited out and the leg asked for again', async () => {+ vi.useFakeTimers()+ try {+ vi.mocked(calculateRouteWithLegs)+ .mockRejectedValueOnce(new RoutingRefusedError(429, null))+ .mockResolvedValue({ coordinates: [[48.86, 2.35], [48.90, 2.42]], distance: 10000, duration: 600, legs: [leg(10000)] })+ const pending = routeTrip(input, { profile: 'driving', tripId: 7 })++ await vi.advanceTimersByTimeAsync(1500)+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)+ await vi.advanceTimersByTimeAsync(1100)+ const summary = await pending++ // Both days routed: the refused leg answered on its second try.+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(3)+ expect(summary.totalDistance).toBe(20000)+ expect(summary.unroutedLegs).toBe(0)+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-MAP-TRG-009: a host that says how long to wait is given that long', async () => {+ vi.useFakeTimers()+ try {+ vi.mocked(calculateRouteWithLegs)+ .mockRejectedValueOnce(new RoutingRefusedError(429, 6000))+ .mockResolvedValue({ coordinates: [[48.86, 2.35], [48.90, 2.42]], distance: 10000, duration: 600, legs: [leg(10000)] })+ const pending = routeTrip(input, { profile: 'driving', tripId: 7 })++ // The own first backoff would be 1500 ms; asking then is just a second refusal.+ await vi.advanceTimersByTimeAsync(2000)+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(4000)+ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)++ await vi.advanceTimersByTimeAsync(1100)+ await expect(pending).resolves.toMatchObject({ totalDistance: 20000 })+ } finally {+ vi.useRealTimers()+ }+ })++ it('FE-MAP-TRG-010: a refusal the host meant is not repeated, and the leg is counted as unrouted', async () => {+ // A 400 objects to these coordinates; the same request earns the same answer.+ vi.mocked(calculateRouteWithLegs)+ .mockRejectedValueOnce(new RoutingRefusedError(400, null))+ .mockResolvedValue({ coordinates: [[45.76, 4.83], [45.80, 4.90]], distance: 10000, duration: 600, legs: [leg(10000)] })++ const summary = await routeTrip(input, { profile: 'driving', tripId: 7 })++ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)+ // The first day keeps its straight line and adds nothing to the sum...+ expect(summary.lines[0]).toEqual([[48.86, 2.35], [48.90, 2.42]])+ expect(summary.days[0].distance).toBe(0)+ expect(summary.totalDistance).toBe(10000)+ // ...and says so, per day and for the trip, so the total is not mistaken for complete.+ expect(summary.days.map(d => d.unroutedLegs)).toEqual([1, 0])+ expect(summary.unroutedLegs).toBe(1)+ })++ it('FE-MAP-TRG-011: a rate limit that never lifts gives up after the retries and is counted', async () => {+ vi.useFakeTimers()+ try {+ vi.mocked(calculateRouteWithLegs).mockRejectedValue(new RoutingRefusedError(429, null))+ const pending = routeTrip(input, { profile: 'driving', tripId: 7 })++ // Two backoffs per leg, a gap between the legs, then it stops asking.+ await vi.advanceTimersByTimeAsync(20000)+ const summary = await pending++ expect(calculateRouteWithLegs).toHaveBeenCalledTimes(6)+ expect(summary.totalDistance).toBe(0)+ expect(summary.unroutedLegs).toBe(2)+ } finally {+ vi.useRealTimers()+ }+ })})diff --git a/client/src/components/Map/tripRouteGeometry.ts b/client/src/components/Map/tripRouteGeometry.tsindex b48405f01..8f14f676e 100644--- a/client/src/components/Map/tripRouteGeometry.ts+++ b/client/src/components/Map/tripRouteGeometry.ts@@ -1,4 +1,4 @@-import { calculateRouteWithLegs, type RouteProfileKey } from './RouteCalculator'+import { calculateRouteWithLegs, RoutingRefusedError, type RouteProfileKey } from './RouteCalculator'import { buildDayRouteRuns, type DayRouteInputs, type DayRoutePoint } from './dayRoutePlan'import { resolveLegMode } from '../Planner/legMode'import { dayColor } from '../Roadtrip/dayColors'@@ -21,6 +21,12 @@ export interface TripOverviewDay {duration: number/** The modes this day is actually travelled in, first use first. */modes: string[]+ /**+ * Legs drawn as a straight line because the router gave no road for them: not asked+ * yet while the round is running, refused or cut off by the deadline once it is over.+ * Those legs add nothing to `distance`, so a day with any of them reads too short.+ */+ unroutedLegs?: number}export interface TripRouteSummary {@@ -34,6 +40,8 @@ export interface TripRouteSummary {focusPoints: [number, number][]totalDistance: numbertotalDuration: number+ /** `unroutedLegs` over every day: above zero, `totalDistance` is a partial sum. */+ unroutedLegs?: number}/** Neighbouring legs of one run that resolve to the same mode travel as one request,@@ -44,6 +52,8 @@ interface Chunk { points: DayRoutePoint[]; mode: string }export interface TripRoutePlanDay { day: Day; runs: Chunk[][] }type Answer = { coordinates: [number, number][]; legs: RouteSegment[] } | null+/** Every leg's answer so far, indexed like the plan: day, run, chunk. */+export type TripRouteAnswers = Answer[][][]/** The palette entry a day keeps, whatever else is added to the trip around it. */export const dayRouteColor = (day: Day): { line: string; casing: string } =>@@ -90,10 +100,12 @@ export function assembleTripRoute(plan: TripRoutePlanDay[], routed: Answer[][][]return plan.map(({ day, runs }, d) => {const lines: [number, number][][] = []const segments: RouteSegment[] = []+ let unroutedLegs = 0runs.forEach((chunks, r) => {const polyline: [number, number][] = []chunks.forEach((chunk, c) => {const answer = routed[d]?.[r]?.[c]+ if (!answer) unroutedLegs++const coords = answer && answer.coordinates.length >= 2 ? answer.coordinates : straight(chunk.points)for (const point of coords) {// Drop the point shared with the previous chunk so concatenated legs@@ -119,6 +131,7 @@ export function assembleTripRoute(plan: TripRoutePlanDay[], routed: Answer[][][]distance: segments.reduce((sum, s) => sum + s.distance, 0),duration: segments.reduce((sum, s) => sum + s.duration, 0),modes,+ unroutedLegs,}})}@@ -133,18 +146,49 @@ export function summariseTripRoute(days: TripOverviewDay[]): TripRouteSummary {focusPoints: lines.flat(),totalDistance: days.reduce((sum, d) => sum + d.distance, 0),totalDuration: days.reduce((sum, d) => sum + d.duration, 0),+ unroutedLegs: days.reduce((sum, d) => sum + (d.unroutedLegs ?? 0), 0),}}/**- * Ask the router for every leg of every day, a few at a time.+ * Gap between two routing requests. The public OSRM hosts TREK ships with state one+ * request per second; the overview asks for every leg of every day, so without spacing+ * the first handful answer and the rest come back 429 (the road trip rail learnt this+ * first and paces itself the same way).+ */+const REQUEST_SPACING_MS = 1100+/** Anything answered faster than this came out of RouteCalculator's cache, not the network. */+const CACHE_HIT_MS = 60+/** How often a rate-limited leg is tried again, and how long after. */+const RETRY_DELAYS_MS = [1500, 4000]++const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>+ new Promise(resolve => {+ if (signal?.aborted || ms <= 0) { resolve(); return }+ const timer = setTimeout(done, ms)+ function done(): void {+ clearTimeout(timer)+ signal?.removeEventListener('abort', done)+ resolve()+ }+ signal?.addEventListener('abort', done, { once: true })+ })++/**+ * Ask the router for every leg of every day, one at a time.*- * A fortnight is dozens of legs and the routing host is usually a shared OSRM, so the- * pool is deliberately small — the same one the sidebar connectors use. RouteCalculator's- * cache is shared with the day route, so a day already drawn on screen costs nothing.+ * A fortnight is dozens of legs and the routing host is usually a shared OSRM that+ * refuses a burst, so the legs go out one after another with a pause between them, and+ * a rate limit is waited out (for as long as the host asks, when it says) and asked+ * again. Only what actually went to the network is paced: RouteCalculator's cache is+ * shared with the day route, so a day already drawn on screen costs nothing and waits+ * for nothing.*- * A leg the router refuses keeps its straight line and contributes no distance, exactly- * as a failed leg of a day route does. Nothing here throws.+ * A leg the router still refuses keeps its straight line and contributes no distance,+ * exactly as a failed leg of a day route does; `assembleTripRoute` counts it so the+ * caller can say the total is short. A refusal the host meant (these coordinates, this+ * profile) is not repeated, because the same request earns the same answer. Nothing+ * here throws.*/export async function routeTripLegs(plan: TripRoutePlanDay[],@@ -161,26 +205,37 @@ export async function routeTripLegs(runs.forEach((chunks, r) => {chunks.forEach((chunk, c) => {tasks.push(async () => {- try {- const answer = await calculateRouteWithLegs(- chunk.points.map(p => ({ lat: p.lat, lng: p.lng })),- { signal, profile: chunk.mode, tripId, dayId: day.id },- )- routed[d][r][c] = { coordinates: answer.coordinates, legs: answer.legs }- onAnswer?.(routed)- } catch {- // Refused (usually a rate limit) — the straight line stands.+ const waypoints = chunk.points.map(p => ({ lat: p.lat, lng: p.lng }))+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {+ if (signal?.aborted) return+ try {+ const answer = await calculateRouteWithLegs(+ waypoints,+ { signal, profile: chunk.mode, tripId, dayId: day.id },+ )+ routed[d][r][c] = { coordinates: answer.coordinates, legs: answer.legs }+ onAnswer?.(routed)+ return+ } catch (err) {+ if (signal?.aborted) return+ const rateLimit = err instanceof RoutingRefusedError && err.isRateLimit ? err : null+ if (!rateLimit || attempt === RETRY_DELAYS_MS.length) return+ // When the host says how long to wait, waiting less is just a second refusal.+ await sleep(Math.max(RETRY_DELAYS_MS[attempt], rateLimit.retryAfterMs ?? 0), signal)+ }}})})})})- let next = 0- const worker = async () => {- while (next < tasks.length && !signal?.aborted) await tasks[next++]()+ for (let i = 0; i < tasks.length; i++) {+ if (signal?.aborted) break+ const startedAt = performance.now()+ await tasks[i]()+ const wasNetwork = performance.now() - startedAt > CACHE_HIT_MS+ if (wasNetwork && i < tasks.length - 1) await sleep(REQUEST_SPACING_MS, signal)}- await Promise.all(Array.from({ length: Math.min(6, tasks.length) }, worker))return routed}diff --git a/client/src/components/Map/useTripRouteOverview.test.ts b/client/src/components/Map/useTripRouteOverview.test.tsindex fd7d2e596..c51051c4c 100644--- a/client/src/components/Map/useTripRouteOverview.test.ts+++ b/client/src/components/Map/useTripRouteOverview.test.ts@@ -1,4 +1,4 @@-import { renderHook, waitFor } from '@testing-library/react'+import { act, renderHook, waitFor } from '@testing-library/react'import { describe, it, expect, vi, beforeEach } from 'vitest'import { dayColor } from '../Roadtrip/dayColors'import { useTripRouteOverview } from './useTripRouteOverview'@@ -10,7 +10,9 @@ vi.mock('./RouteCalculator', async (importActual) => {return { ...actual, calculateRouteWithLegs: vi.fn() }})-const { calculateRouteWithLegs } = await import('./RouteCalculator')+const { calculateRouteWithLegs, RoutingRefusedError } = await import('./RouteCalculator')++type RouteAnswer = Awaited<ReturnType<typeof calculateRouteWithLegs>>const leg = (distance: number, duration: number): RouteSegment => ({mid: [0, 0], from: [0, 0], to: [0, 0],@@ -136,4 +138,76 @@ describe('useTripRouteOverview', () => {await waitFor(() => expect(result.current.loading).toBe(false))expect(vi.mocked(calculateRouteWithLegs).mock.calls.length).toBe(calls)})++ it('FE-MAP-TRO-009: a leg the router refused outright is counted, so the total is not taken for complete', async () => {+ // A 400 objects to these coordinates; the leg stays a straight line with no distance.+ vi.mocked(calculateRouteWithLegs).mockRejectedValueOnce(new RoutingRefusedError(400, null))+ const { result } = render()++ await waitFor(() => expect(result.current.loading).toBe(false), { timeout: 3000 })+ expect(result.current.days.map(d => d.unroutedLegs)).toEqual([1, 0])+ expect(result.current.unroutedLegs).toBe(1)+ expect(result.current.totalDistance).toBe(12000)+ })++ it('FE-MAP-TRO-010: each day is drawn as soon as its road answers, not when the round is over', async () => {+ // The legs go to the router one at a time with a pause between them, so a cold trip+ // takes a second per leg; roads filling in one by one is what makes that read as+ // progress rather than as a hang.+ const answer: RouteAnswer = {+ coordinates: [[48.86, 2.35], [48.87, 2.355], [48.88, 2.36]],+ distance: 12000, duration: 900,+ legs: [leg(12000, 900)],+ }+ const answers: Array<(value: RouteAnswer) => void> = []+ vi.mocked(calculateRouteWithLegs).mockImplementation(+ () => new Promise<RouteAnswer>(resolve => { answers.push(resolve) }),+ )+ const { result } = render()++ // Only the first leg has been asked for.+ expect(answers).toHaveLength(1)+ await act(async () => { answers[0](answer) })++ // Its day is on the map while the second is still waiting.+ expect(result.current.loading).toBe(true)+ expect(result.current.days[0].distance).toBe(12000)+ expect(result.current.days[1].distance).toBe(0)++ await waitFor(() => expect(answers).toHaveLength(2), { timeout: 3000 })+ await act(async () => { answers[1](answer) })+ await waitFor(() => expect(result.current.loading).toBe(false))+ expect(result.current.totalDistance).toBe(24000)+ })++ it('FE-MAP-TRO-011: keeps the frame it set on the straight lines until the round is over', async () => {+ // A fresh `focusPoints` array is what tells the map to fit the camera. One per+ // answering leg would take the map back from wherever the reader has panned to, so+ // the frame changes exactly twice: on the straight lines, and on the finished roads.+ const answer: RouteAnswer = {+ coordinates: [[48.86, 2.35], [48.87, 2.355], [48.88, 2.36]],+ distance: 12000, duration: 900,+ legs: [leg(12000, 900)],+ }+ const answers: Array<(value: RouteAnswer) => void> = []+ vi.mocked(calculateRouteWithLegs).mockImplementation(+ () => new Promise<RouteAnswer>(resolve => { answers.push(resolve) }),+ )+ const { result } = render()+ const frame = result.current.focusPoints+ expect(frame.length).toBeGreaterThan(0)++ await act(async () => { answers[0](answer) })+ // The road is drawn, the camera stays put.+ expect(result.current.days[0].distance).toBe(12000)+ expect(result.current.focusPoints).toBe(frame)++ await waitFor(() => expect(answers).toHaveLength(2), { timeout: 3000 })+ await act(async () => { answers[1](answer) })+ await waitFor(() => expect(result.current.loading).toBe(false))+ // The finished result frames the roads themselves, which have more points than the+ // straight lines had.+ expect(result.current.focusPoints).not.toBe(frame)+ expect(result.current.focusPoints.length).toBeGreaterThan(frame.length)+ })})diff --git a/client/src/components/Map/useTripRouteOverview.ts b/client/src/components/Map/useTripRouteOverview.tsindex 16e64dee4..81f8689ac 100644--- a/client/src/components/Map/useTripRouteOverview.ts+++ b/client/src/components/Map/useTripRouteOverview.ts@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'import { type RouteProfileKey } from './RouteCalculator'import {assembleTripRoute, emptyAnswers, planTripRoute, routeTripLegs, summariseTripRoute,- type TripRouteSummary,+ type TripRouteAnswers, type TripRouteSummary,} from './tripRouteGeometry'import { useSettingsStore } from '../../store/settingsStore'import type { Accommodation, AssignmentsMap, Day, Reservation } from '../../types'@@ -66,12 +66,25 @@ export function useTripRouteOverview(// Straight lines first so the shape of the trip is on screen immediately, then the// real roads replace them — the same two-step the single-day route draws with.- setResult({ ...summariseTripRoute(assembleTripRoute(plan, emptyAnswers(plan))), loading: true })+ const first = summariseTripRoute(assembleTripRoute(plan, emptyAnswers(plan)))+ setResult({ ...first, loading: true })- routeTripLegs(plan, { tripId, signal: controller.signal }).then(routed => {+ // Published leg by leg: the legs go to the router one at a time with a pause between+ // them, so a cold trip takes a second per leg, and roads that fill in as they answer+ // read as progress where straight lines that all flip at once read as a hang.+ //+ // The frame is the exception. A fresh `focusPoints` array is what tells the map to+ // fit the camera, and a fit every second would take the map back from wherever the+ // reader has panned to. The frame set on the straight lines therefore holds until+ // the round is over, and only the finished result brings a new one, exactly the two+ // fits the overview made when every answer landed at once.+ const publish = (routed: TripRouteAnswers, loading: boolean): void => {if (controller.signal.aborted) return- setResult({ ...summariseTripRoute(assembleTripRoute(plan, routed)), loading: false })- })+ const next = summariseTripRoute(assembleTripRoute(plan, routed))+ setResult({ ...next, focusPoints: loading ? first.focusPoints : next.focusPoints, loading })+ }+ routeTripLegs(plan, { tripId, signal: controller.signal, onAnswer: routed => publish(routed, true) })+ .then(routed => publish(routed, false))return () => controller.abort()// planKey is derived from the same inputs as plan, so keying on the string isdiff --git a/client/src/components/Planner/DayPlanSidebar.test.tsx b/client/src/components/Planner/DayPlanSidebar.test.tsxindex 1d9da4c76..c2cd1d9c9 100644--- a/client/src/components/Planner/DayPlanSidebar.test.tsx+++ b/client/src/components/Planner/DayPlanSidebar.test.tsx@@ -4299,6 +4299,104 @@ describe('DayPlanSidebar', () => {fireEvent.dragEnd(row)expect(row.style.opacity).toBe('1')})++ // ── Drop positions count the rows the list hides ───────────────────────+ // The stop a booked night wrote is in the day but not in the list. The store+ // splices into the full day, so a position counted over the visible rows would+ // land one slot early and reorder would persist it that way.++ /** A day whose first stored row is the hotel a booking put there, hidden from the list. */+ function dayWithHiddenHotel(dayId: number) {+ const hotel = buildPlace({ id: 600, name: 'Hotel Adlon', stop_type: 'hotel' })+ const lunch = buildPlace({ id: 601, name: 'Lunch' })+ const museum = buildPlace({ id: 602, name: 'Museum' })+ return {+ places: [hotel, lunch, museum],+ assignments: [+ buildAssignment({ id: 400, day_id: dayId, order_index: 0, place: hotel, accommodation_id: 7 } as never),+ buildAssignment({ id: 401, day_id: dayId, order_index: 1, place: lunch }),+ buildAssignment({ id: 402, day_id: dayId, order_index: 2, place: museum }),+ ],+ }+ }++ it('FE-PLANNER-DAYPLAN-210: a place dropped on a row lands ahead of that row in the stored day', () => {+ const onAssignToDay = vi.fn()+ const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })+ const { places, assignments } = dayWithHiddenHotel(10)+ render(<DayPlanSidebar {...makeDefaultProps({+ days: [day], places, assignments: { '10': assignments }, onAssignToDay,+ })} />)+ ;(window as any).__dragData = { placeId: '55' }+ fireEvent.drop(dragRow(screen.getByText('Museum')), { dataTransfer: { getData: vi.fn(() => '') } })+ // Museum is the second visible row but the third stored one.+ expect(onAssignToDay).toHaveBeenCalledWith(55, 10, 2)++ ;(window as any).__dragData = { placeId: '55' }+ fireEvent.drop(dragRow(screen.getByText('Lunch')), { dataTransfer: { getData: vi.fn(() => '') } })+ expect(onAssignToDay).toHaveBeenLastCalledWith(55, 10, 1)+ ;(window as any).__dragData = null+ })++ it('FE-PLANNER-DAYPLAN-211: a stop moved from another day onto a row lands ahead of that row in the stored day', () => {+ const moveAssignment = vi.fn(async () => undefined)+ stubTripActions({ moveAssignment })+ const days = [+ buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),+ buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),+ ]+ const source = buildPlace({ id: 1, name: 'Source place' })+ const { places, assignments } = dayWithHiddenHotel(11)+ render(<DayPlanSidebar {...makeDefaultProps({+ days, places: [source, ...places],+ assignments: { '10': [buildAssignment({ id: 11, day_id: 10, order_index: 0, place: source })], '11': assignments },+ })} />)+ fireEvent.dragStart(dragRow(screen.getByText('Source place')), { dataTransfer: emptyDataTransfer })+ fireEvent.drop(dragRow(screen.getByText('Museum')), { dataTransfer: { getData: vi.fn(() => '') } })+ expect(moveAssignment).toHaveBeenCalledWith(1, 11, 10, 11, 2)+ })++ it('FE-PLANNER-DAYPLAN-212: a place dropped on a note lands ahead of the next stop below it, or last', () => {+ const onAssignToDay = vi.fn()+ const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })+ const { places, assignments } = dayWithHiddenHotel(10)+ mockDayNotesState.dayNotes = { '10': [+ buildDayNote({ id: 70, day_id: 10, text: 'Between note', sort_order: 1.5 }),+ buildDayNote({ id: 71, day_id: 10, text: 'Closing note', sort_order: 5 }),+ ] }+ render(<DayPlanSidebar {...makeDefaultProps({+ days: [day], places, assignments: { '10': assignments }, onAssignToDay,+ })} />)+ ;(window as any).__dragData = { placeId: '55' }+ fireEvent.drop(cardRow(screen.getByText('Between note')), { dataTransfer: { getData: vi.fn(() => '') } })+ expect(onAssignToDay).toHaveBeenCalledWith(55, 10, 2)++ // Nothing below the closing note, so the stop goes to the end of the stored+ // day: three rows, the hidden hotel among them.+ ;(window as any).__dragData = { placeId: '55' }+ fireEvent.drop(cardRow(screen.getByText('Closing note')), { dataTransfer: { getData: vi.fn(() => '') } })+ expect(onAssignToDay).toHaveBeenLastCalledWith(55, 10, 3)+ ;(window as any).__dragData = null+ })++ it('FE-PLANNER-DAYPLAN-213: a stop moved from another day onto a note lands ahead of the next stop below it', () => {+ const moveAssignment = vi.fn(async () => undefined)+ stubTripActions({ moveAssignment })+ const days = [+ buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),+ buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),+ ]+ const source = buildPlace({ id: 1, name: 'Source place' })+ const { places, assignments } = dayWithHiddenHotel(11)+ mockDayNotesState.dayNotes = { '11': [buildDayNote({ id: 70, day_id: 11, text: 'Between note', sort_order: 1.5 })] }+ render(<DayPlanSidebar {...makeDefaultProps({+ days, places: [source, ...places],+ assignments: { '10': [buildAssignment({ id: 11, day_id: 10, order_index: 0, place: source })], '11': assignments },+ })} />)+ fireEvent.dragStart(dragRow(screen.getByText('Source place')), { dataTransfer: emptyDataTransfer })+ fireEvent.drop(cardRow(screen.getByText('Between note')), { dataTransfer: { getData: vi.fn(() => '') } })+ expect(moveAssignment).toHaveBeenCalledWith(1, 11, 10, 11, 2)+ })})// FE-W5DPS-001 to FE-W5DPS-006 — booking subtitles, the collections entry in thediff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsxindex 1cfbd786a..ff565277b 100644--- a/client/src/components/Planner/DayPlanSidebar.tsx+++ b/client/src/components/Planner/DayPlanSidebar.tsx@@ -494,6 +494,26 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {getDisplayTime: getDisplayTimeForDay,})+ // The list is a filtered view of the day, and the store is not: assignPlaceToDay+ // and moveAssignment splice into the full day, hidden rows included, and persist+ // the result. A position counted over the rows on screen therefore lands one slot+ // early for every hidden row above the target. So a drop names the row it should+ // land ahead of, and what goes to the store is that row's slot in the full day,+ // in the order the list reads it. No row (an empty day, a note under the last+ // stop) means the end of the full day.+ const storedPositionBefore = (dayId: number, target: { id: number } | null | undefined): number => {+ const stored = (assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)+ const idx = target ? stored.findIndex(a => a.id === target.id) : -1+ return idx >= 0 ? idx : stored.length+ }++ // The stop a drop on a note lands ahead of: the next place below the note.+ const placeBelowNote = (dayId: number, noteId: number): Assignment | undefined => {+ const tm = getMergedItems(dayId)+ const noteIdx = tm.findIndex(i => i.type === 'note' && i.data.id === noteId)+ return noteIdx < 0 ? undefined : tm.slice(noteIdx + 1).find(i => i.type === 'place')?.data+ }+// Pre-compute merged items for all days so the render loop doesn't recompute on unrelated state changes (e.g. hover)// eslint-disable-next-line react-hooks/exhaustive-depsconst mergedItemsMap = useMemo(() => {@@ -1190,6 +1210,8 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {computeTransportPosition,initTransportPositions,getMergedItems,+ storedPositionBefore,+ placeBelowNote,mergedItemsMap,applyMergedOrder,handleMergedDrop,@@ -1388,6 +1410,8 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarPcomputeTransportPosition,initTransportPositions,getMergedItems,+ storedPositionBefore,+ placeBelowNote,mergedItemsMap,applyMergedOrder,handleMergedDrop,@@ -2017,8 +2041,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarPe.preventDefault(); e.stopPropagation()const { placeId, assignmentId: fromAssignmentId, noteId, reservationId: fromReservationId, fromDayId, phase } = getDragData(e)if (placeId) {- const pos = placeItems.findIndex(i => i.data.id === assignment.id)- onAssignToDay?.(Number.parseInt(placeId), day.id, pos >= 0 ? pos : undefined)+ onAssignToDay?.(Number.parseInt(placeId), day.id, storedPositionBefore(day.id, assignment))setDropTargetKey(null); window.__dragData = null} else if (fromReservationId && fromDayId !== day.id) {const r = reservations.find(x => x.id === Number(fromReservationId))@@ -2027,8 +2050,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP} else if (fromReservationId) {handleMergedDrop(day.id, 'transport', Number(fromReservationId), 'place', assignment.id)} else if (fromAssignmentId && fromDayId !== day.id) {- const toIdx = getDayAssignments(day.id).findIndex(a => a.id === assignment.id)- tripActions.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, toIdx).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError')))+ tripActions.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, storedPositionBefore(day.id, assignment)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError')))setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null} else if (fromAssignmentId) {handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'place', assignment.id)@@ -2617,12 +2639,9 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarPconst { placeId, noteId: fromNoteId, assignmentId: fromAssignmentId, reservationId: fromReservationId, fromDayId, phase } = getDragData(e)if (placeId) {// New place dropped onto a note: insert it among the- // assignments at the note's position (after the places- // above it), so it lands right where the note sits.- const tm = getMergedItems(day.id)- const noteIdx = tm.findIndex(i => i.type === 'note' && i.data.id === note.id)- const pos = tm.slice(0, noteIdx).filter(i => i.type === 'place').length- onAssignToDay?.(Number.parseInt(placeId), day.id, pos)+ // assignments at the note's position (ahead of the first+ // place below it), so it lands right where the note sits.+ onAssignToDay?.(Number.parseInt(placeId), day.id, storedPositionBefore(day.id, placeBelowNote(day.id, note.id)))setDropTargetKey(null); window.__dragData = null} else if (fromReservationId && fromDayId !== day.id) {const r = reservations.find(x => x.id === Number(fromReservationId))@@ -2639,10 +2658,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP} else if (fromNoteId && fromNoteId !== String(note.id)) {handleMergedDrop(day.id, 'note', Number(fromNoteId), 'note', note.id)} else if (fromAssignmentId && fromDayId !== day.id) {- const tm = getMergedItems(day.id)- const noteIdx = tm.findIndex(i => i.type === 'note' && i.data.id === note.id)- const toIdx = tm.slice(0, noteIdx).filter(i => i.type === 'place').length- tripActions.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, toIdx).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError')))+ tripActions.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, storedPositionBefore(day.id, placeBelowNote(day.id, note.id))).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError')))setDraggingId(null); setDropTargetKey(null)} else if (fromAssignmentId) {handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'note', note.id)diff --git a/client/src/components/Planner/PlaceInspector.test.tsx b/client/src/components/Planner/PlaceInspector.test.tsxindex f215b4131..f3478d578 100644--- a/client/src/components/Planner/PlaceInspector.test.tsx+++ b/client/src/components/Planner/PlaceInspector.test.tsx@@ -1498,4 +1498,50 @@ describe('PlaceInspector', () => {expect(screen.queryByRole('button', { name: /remove from day/i })).toBeNull();expect(screen.queryByRole('button', { name: /add to day/i })).toBeNull();});++ it('FE-PLANNER-INSPECTOR-017c: the booked stop stays off the buttons when the day list hides it', () => {+ // The day view hands the inspector the day without the stop a booking wrote,+ // while the store still holds it. Judged on the list alone the hotel looked+ // unassigned, and "Add to day" put a second copy beside the booked night.+ const booked = [{ id: 99, place, day_id: 1, place_id: place.id, order_index: 0, notes: null, accommodation_id: 4 }];+ seedStore(useTripStore, { assignments: { '1': booked } as never });+ render(<PlaceInspector {...defaultProps} selectedDayId={1} assignments={{ '1': [] }} />);++ expect(screen.queryByText('Add to Day')).toBeNull();+ expect(screen.queryByText('Remove from Day')).toBeNull();+ });++ it('FE-PLANNER-INSPECTOR-017d: a stop the traveller placed at the booked hotel can still be removed', () => {+ // A second copy that did get onto the day is the traveller's own row and shows+ // in the list. That one keeps its "Remove from day", which is the way back.+ const onRemoveAssignment = vi.fn();+ const booked = { id: 99, place, day_id: 1, place_id: place.id, order_index: 0, notes: null, accommodation_id: 4 };+ const own = { id: 100, place, day_id: 1, place_id: place.id, order_index: 1, notes: null };+ seedStore(useTripStore, { assignments: { '1': [booked, own] } as never });+ render(+ <PlaceInspector+ {...defaultProps}+ selectedDayId={1}+ assignments={{ '1': [own] } as never}+ onRemoveAssignment={onRemoveAssignment}+ />+ );++ fireEvent.click(screen.getByText('Remove from Day').closest('button')!);+ expect(onRemoveAssignment).toHaveBeenCalledWith(1, 100);+ expect(screen.queryByText('Add to Day')).toBeNull();+ });++ it('FE-PLANNER-INSPECTOR-017e: any booked stop at the place keeps the buttons off, whichever row the store lists first', () => {+ // With the service stops switched off the day list can hide a hotel the traveller+ // placed as well, so the store may list that row ahead of the booked one. The+ // question is whether a booking holds this place on this day, not which row comes first.+ const own = { id: 100, place, day_id: 1, place_id: place.id, order_index: 0, notes: null };+ const booked = { id: 99, place, day_id: 1, place_id: place.id, order_index: 1, notes: null, accommodation_id: 4 };+ seedStore(useTripStore, { assignments: { '1': [own, booked] } as never });+ render(<PlaceInspector {...defaultProps} selectedDayId={1} assignments={{ '1': [] }} />);++ expect(screen.queryByText('Add to Day')).toBeNull();+ expect(screen.queryByText('Remove from Day')).toBeNull();+ });})diff --git a/client/src/components/Planner/PlaceInspector.tsx b/client/src/components/Planner/PlaceInspector.tsxindex 9c1138ee6..692276803 100644--- a/client/src/components/Planner/PlaceInspector.tsx+++ b/client/src/components/Planner/PlaceInspector.tsx@@ -209,6 +209,12 @@ export default function PlaceInspector({const { t, locale, language } = useTranslation()// Currency-less prices mean "the trip's currency"; null in collection mode (EUR fallback below).const tripCurrency = useTripStore(s => s.trip?.currency)+ // The day list handed in is the one the planner shows, and in the day view that+ // list leaves out the stop a booking wrote. The store still holds it, so the+ // booked-night check below reads the day from there as well: on the list alone+ // the hotel of a booked night looked unassigned and could be put on the day a+ // second time, which is the duplicate that check exists to prevent.+ const storedDayAssignments = useTripStore(s => (selectedDayId ? s.assignments[String(selectedDayId)] : undefined))const toast = useToast()const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'const distanceUnit = useSettingsStore(s => s.settings.distance_unit) || 'metric'@@ -322,7 +328,9 @@ export default function PlaceInspector({?? dayAssignments.find(a => a.place?.id === place.id)): null/** This stop belongs to a booked night rather than to the traveller. */- const bookedNight = assignmentInDay?.accommodation_id != null+ const bookedNight = assignmentInDay+ ? assignmentInDay.accommodation_id != null+ : !!storedDayAssignments?.some(a => a.place?.id === place.id && a.accommodation_id != null)// The weekday lines are display text; the ring is computed from the structured// periods next to them, in the place's own timezone. open_now stays the fallback.diff --git a/client/src/components/Planner/usePlacesSidebar.test.tsx b/client/src/components/Planner/usePlacesSidebar.test.tsxindex 3bf66d52f..83107e1b7 100644--- a/client/src/components/Planner/usePlacesSidebar.test.tsx+++ b/client/src/components/Planner/usePlacesSidebar.test.tsx@@ -1,4 +1,4 @@-// FE-PLANNER-PSHOOK-001 to FE-PLANNER-PSHOOK-051+// FE-PLANNER-PSHOOK-001 to FE-PLANNER-PSHOOK-052import { http, HttpResponse } from 'msw';import userEvent from '@testing-library/user-event';import { render, screen, fireEvent, act, waitFor } from '../../../tests/helpers/render';@@ -333,6 +333,21 @@ describe('usePlacesSidebar day helpers', () => {expect(S.inDaySet.size).toBe(0);expect(S.isAssignedToSelectedDay(5)).toBe(false);});++ it('FE-PLANNER-PSHOOK-052: the stop a booking wrote counts as in the day when the list hides it', () => {+ // The day view hands the pool the day without the stop a booking wrote, while+ // the store still holds it. Judged on the list alone the hotel offered "add to+ // day" on its own check-in day, and that put a second row beside the night.+ const hotel = buildPlace({ id: 5, name: 'Hotel' });+ const loose = buildPlace({ id: 6, name: 'Loose' });+ const booked = buildAssignment({ place: hotel, day_id: 3, accommodation_id: 4 });+ seedStore(useTripStore, { assignments: { '3': [booked] } });+ render(<Host {...makeProps({ places: [hotel, loose], assignments: { '3': [] }, selectedDayId: 3 })} />);++ expect([...S.inDaySet]).toEqual([5]);+ expect(S.isAssignedToSelectedDay(5)).toBe(true);+ expect(S.isAssignedToSelectedDay(6)).toBe(false);+ });});// ── Scroll restoration and row refs ───────────────────────────────────────────diff --git a/client/src/components/Planner/usePlacesSidebar.ts b/client/src/components/Planner/usePlacesSidebar.tsindex 145ff677d..f027881c4 100644--- a/client/src/components/Planner/usePlacesSidebar.ts+++ b/client/src/components/Planner/usePlacesSidebar.ts@@ -307,16 +307,24 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {lastAutoScrolledPlaceIdRef.current = props.selectedPlaceId}, [filtered, props.selectedPlaceId])- const isAssignedToSelectedDay = (placeId) =>- selectedDayId && (assignments[String(selectedDayId)] || []).some(a => a.place?.id === placeId)-const selectedDayIdRef = useRef<number | null>(selectedDayId)useEffect(() => { selectedDayIdRef.current = selectedDayId }, [selectedDayId])+ // The day list handed in is the one the planner shows, and in the day view that+ // list leaves out the stop a booking wrote. The store still holds it, so the set+ // that decides between "in the day" and the add button reads the day from there+ // as well: on the list alone the hotel of a booked night offered "add to day" on+ // its own check-in day, and taking that offer put a second row beside the night.+ const storedDayAssignments = useTripStore((s) => (selectedDayId ? s.assignments[String(selectedDayId)] : undefined))+const inDaySet = useMemo(() => {if (!selectedDayId) return new Set<number>()- return new Set<number>((assignments[String(selectedDayId)] || []).map((a: any) => a.place?.id).filter(Boolean))- }, [assignments, selectedDayId])+ const ids = new Set<number>((assignments[String(selectedDayId)] || []).map((a: any) => a.place?.id).filter(Boolean))+ for (const a of storedDayAssignments ?? []) if (a.place?.id) ids.add(a.place.id)+ return ids+ }, [assignments, storedDayAssignments, selectedDayId])++ const isAssignedToSelectedDay = (placeId) => inDaySet.has(placeId)const openContextMenu = useCallback((e: React.MouseEvent, place: Place) => {const selDayId = selectedDayIdRef.currentdiff --git a/client/src/components/Roadtrip/RoadtripLimitsCard.test.tsx b/client/src/components/Roadtrip/RoadtripLimitsCard.test.tsxindex a7ffd1c7e..e91c814d2 100644--- a/client/src/components/Roadtrip/RoadtripLimitsCard.test.tsx+++ b/client/src/components/Roadtrip/RoadtripLimitsCard.test.tsx@@ -145,14 +145,17 @@ describe('RoadtripLimitsCard', () => {})it('FE-ROADTRIP-LIMITS-008: without a way to save, the dialog is read-only', () => {+ useSettingsStore.setState({+ settings: { roadtrip_leg_minutes: 180, roadtrip_day_minutes: 0, roadtrip_range_km: 0, distance_unit: 'metric' } as never,+ })// `onSave` absent is how the caller says the reader may look but not change.open(undefined)- const [leg] = inputs()- fireEvent.change(leg, { target: { value: '180' } })- // Nothing to assert but the absence of a crash: the commit path has no- // handler to call, and must not assume one.- expect(() => fireEvent.blur(leg)).not.toThrow()+ // Disabled rather than accepting a number it would then drop: a field that took 400+ // and sprang back to 180 on Enter, with no word about why, read as broken.+ for (const field of inputs()) expect(field).toBeDisabled()+ // What is stored is still there to be read.+ expect(screen.getByTestId('limit-legMinutes')).toHaveValue(180)})it('FE-ROADTRIP-LIMITS-009: naming the kind of car brings out its own figures', () => {@@ -275,6 +278,42 @@ describe('RoadtripLimitsCard', () => {expect(onSave).toHaveBeenCalledWith('roadtrip_connect_days', false)})})++ /**+ * A member without the right to edit days gets the dialog without a way to save. Every+ * control has to say so by being disabled: a switch that flips and stays off, or a+ * field that takes a number and springs back, is a fault report waiting to happen.+ */+ describe('read-only', () => {+ it('FE-ROADTRIP-LIMITS-016: the kind of car and its figures cannot be changed', () => {+ useSettingsStore.setState({+ settings: { roadtrip_vehicle: 'electric', roadtrip_battery_kwh: 58, distance_unit: 'metric' } as never,+ })+ open(undefined)++ for (const name of ['Either', 'Petrol', 'Electric']) {+ expect(screen.getByRole('radio', { name })).toBeDisabled()+ }+ // The stored figure holds the disclosure open, so the car's own rows are on show.+ expect(screen.getByTestId('limit-batteryKwh')).toBeDisabled()+ expect(screen.getByTestId('limit-batteryKwh')).toHaveValue(58)+ expect(screen.getByTestId('limit-fill')).toBeDisabled()+ })++ it('FE-ROADTRIP-LIMITS-017: the switches over the route line are not offered', () => {+ useSettingsStore.setState({+ settings: { roadtrip_connect_days: true, distance_unit: 'metric' } as never,+ })+ open(undefined)++ expect(screen.queryByRole('button', { name: 'Connect the days' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'A colour per day' })).not.toBeInTheDocument()+ // The rows stay in the dialog, the same way the service-stop and hazard rows do+ // without a way to save: a switch withheld is not a setting that vanished.+ expect(screen.getByText('Connect the days')).toBeInTheDocument()+ expect(screen.getByText('A colour per day')).toBeInTheDocument()+ })+ })})vi.mock('../../hooks/useRoadtripSettings', () => ({diff --git a/client/src/components/Roadtrip/RoadtripLimitsCard.tsx b/client/src/components/Roadtrip/RoadtripLimitsCard.tsxindex 9700c5087..c0031f41f 100644--- a/client/src/components/Roadtrip/RoadtripLimitsCard.tsx+++ b/client/src/components/Roadtrip/RoadtripLimitsCard.tsx@@ -52,7 +52,7 @@ function parseLimit(raw: string): number {* its shape either way, because a range that switched between an input and a line of text* would move every row under it the moment a consumption was typed.*/-function LimitRow({ icon: Icon, label, suffix, value, placeholder, step, derived, testId, onDraft, onChange }: {+function LimitRow({ icon: Icon, label, suffix, value, placeholder, step, derived, disabled, testId, onDraft, onChange }: {icon: typeof Clocklabel: stringsuffix: string@@ -60,6 +60,12 @@ function LimitRow({ icon: Icon, label, suffix, value, placeholder, step, derivedplaceholder: stringstep?: numberderived?: string+ /**+ * Readable but not editable, which is how a reader without the right to change the+ * settings sees the dialog. Nothing this row could commit would be saved, and a field+ * that takes a number and springs back to the old one reads as broken.+ */+ disabled?: boolean/*** A stable handle for the tests, because the rows are no longer at fixed indices.*@@ -133,6 +139,7 @@ function LimitRow({ icon: Icon, label, suffix, value, placeholder, step, derivedplaceholder={placeholder}aria-label={`${label}, ${suffix}`}data-testid={testId}+ disabled={disabled}onChange={e => { setDraft(e.target.value); onDraft?.(parseLimit(e.target.value)) }}onBlur={commit}// Committed here rather than by blurring and letting onBlur do it: a@@ -141,7 +148,7 @@ function LimitRow({ icon: Icon, label, suffix, value, placeholder, step, derivedonKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); commit(); (e.target as HTMLInputElement).blur() } }}// The spinners are the other half of the width problem: they eat a third of a// narrow field and nobody sets a driving limit by clicking an arrow.- className="w-full rounded-lg border border-edge bg-surface px-2.5 py-1.5 text-end text-body tabular-nums text-content [appearance:textfield] focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"+ className="w-full rounded-lg border border-edge bg-surface px-2.5 py-1.5 text-end text-body tabular-nums text-content [appearance:textfield] focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent disabled:opacity-50 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"/>)}</span>@@ -269,6 +276,11 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadiconst [open, setOpen] = useState(false)const distanceUnit: DistanceUnit = unit === 'imperial' ? 'imperial' : 'metric'const imperial = distanceUnit === 'imperial'+ // No way to save is the caller saying the reader may look but not change. Every+ // control below is disabled on that one answer: a member without the right to edit+ // days gets the dialog with the trip's figures in it, not a form that takes a number+ // and drops it.+ const readOnly = !onSaveconst legMinutes = settings.roadtrip_leg_minutesconst dayMinutes = settings.roadtrip_day_minutes@@ -448,6 +460,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadisuffix={t('roadtrip.limit.minutes')}value={legMinutes}placeholder={t('roadtrip.limit.off')}+ disabled={readOnly}testId="limit-legMinutes"onChange={v => onSave?.('roadtrip_leg_minutes', v)}/>@@ -457,6 +470,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadisuffix={t('roadtrip.limit.minutes')}value={dayMinutes}placeholder={t('roadtrip.limit.off')}+ disabled={readOnly}testId="limit-dayMinutes"onChange={v => onSave?.('roadtrip_day_minutes', v)}/>@@ -478,7 +492,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadiicon={icon}label={label}on={avoiding.includes(cls)}- disabled={!canAvoid}+ disabled={!canAvoid || readOnly}onToggle={() => toggleAvoid(cls)}/>))}@@ -486,7 +500,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadi<Panel icon={Signpost} title={t('roadtrip.stops.section')} note={t('roadtrip.stops.daysHint')}><AvoidRow icon={Link2} label={t('roadtrip.stops.inDays')}on={settings.roadtrip_service_stops_in_days !== false}- disabled={!onSave}+ disabled={readOnly}onToggle={() => onSave?.('roadtrip_service_stops_in_days', settings.roadtrip_service_stops_in_days === false)}/></Panel>@@ -516,6 +530,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadiname="roadtrip-vehicle"className="peer sr-only"checked={(settings.roadtrip_vehicle || '') === (key ?? '')}+ disabled={readOnly}onChange={() => {// Never writes the car's figures away: switching kind leaves// both sets stored, `rangeFromSpec` simply returns null for@@ -526,7 +541,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadionSave?.('roadtrip_vehicle', key ?? '')}}/>- <span className="flex min-w-0 cursor-pointer items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-center text-body text-content-secondary transition-colors hover:bg-surface-hover peer-checked:bg-accent peer-checked:text-accent-text peer-focus-visible:ring-2 peer-focus-visible:ring-accent">+ <span className="flex min-w-0 cursor-pointer items-center justify-center gap-1.5 rounded-lg px-2 py-1.5 text-center text-body text-content-secondary transition-colors hover:bg-surface-hover peer-checked:bg-accent peer-checked:text-accent-text peer-focus-visible:ring-2 peer-focus-visible:ring-accent peer-disabled:pointer-events-none"><Icon size={14} className="shrink-0" aria-hidden />{t(labelKey)}</span>@@ -555,6 +570,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadivalue={rangeShown}placeholder={t('roadtrip.limit.off')}derived={computedKm ? t('roadtrip.limit.computed') : undefined}+ disabled={readOnly}testId="limit-range"onDraft={v => setPreview({ key: 'range', value: v })}onChange={setRange}@@ -569,6 +585,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadisuffix="%"value={settings.roadtrip_fill_percent}placeholder={t('roadtrip.limit.fillFull')}+ disabled={readOnly}testId="limit-fill"onDraft={v => setPreview({ key: 'fill', value: v > 100 ? 100 : v })}onChange={v => onSave?.('roadtrip_fill_percent', v > 100 ? 100 : v)}@@ -611,6 +628,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadistep={step}value={showSpec(key, saved[key], imperial)}placeholder={t('roadtrip.limit.off')}+ disabled={readOnly}testId={`limit-${key}`}onDraft={v => setPreview({ key, value: v })}onChange={v => onSave?.(setting, storeSpec(key, v, imperial))}@@ -636,7 +654,7 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadiicon={Link2}label={t('roadtrip.line.connect')}on={!!settings.roadtrip_connect_days}- disabled={false}+ disabled={readOnly}onToggle={() => onSave?.('roadtrip_connect_days', !settings.roadtrip_connect_days)}/>}{/* Which matters most once the line IS continuous: end to end it is one@@ -645,12 +663,12 @@ export default function RoadtripLimitsCard({ onSave, onResetDayBoundaries, loadiicon={Palette}label={t('roadtrip.line.dayColors')}on={!!settings.roadtrip_day_colors}- disabled={false}+ disabled={readOnly}onToggle={() => onSave?.('roadtrip_day_colors', !settings.roadtrip_day_colors)}/></Panel><Panel icon={Signpost} title={t('roadtrip.hazards.current')} note={t('roadtrip.hazards.note')}>- <AvoidRow icon={Signpost} label={t('roadtrip.hazards.show')} on={settings.roadtrip_show_hazards === true} disabled={!onSave}+ <AvoidRow icon={Signpost} label={t('roadtrip.hazards.show')} on={settings.roadtrip_show_hazards === true} disabled={readOnly}onToggle={() => onSave?.('roadtrip_show_hazards', !settings.roadtrip_show_hazards)} /></Panel>diff --git a/client/src/components/SystemNotices/SystemNoticeHost.tsx b/client/src/components/SystemNotices/SystemNoticeHost.tsxindex d622d3148..6399da29c 100644--- a/client/src/components/SystemNotices/SystemNoticeHost.tsx+++ b/client/src/components/SystemNotices/SystemNoticeHost.tsx@@ -46,6 +46,10 @@ const KEY_SHAPE = /^[a-z0-9_-]+(\.[a-z0-9_-]+)+$/i;** Deliberately generous: one resolved key is enough. Half a translation is still readable,* and a notice hidden by mistake is a worse failure than an ugly one.+ *+ * A bundle older than this filter cannot run it, so the server holds the release notice+ * back until the store announces the layout (see systemNoticeStore.fetch). This filter is+ * for the bundles after that one: they announce the layout but may still lack the copy.*/function hasCopy(notice: SystemNoticeDTO, t: (key: string) => string): boolean {const keys = notice.releasediff --git a/client/src/mobile/screens/admin/MAdminAddonManager.tsx b/client/src/mobile/screens/admin/MAdminAddonManager.tsxindex 99ef39e61..797b35fc0 100644--- a/client/src/mobile/screens/admin/MAdminAddonManager.tsx+++ b/client/src/mobile/screens/admin/MAdminAddonManager.tsx@@ -81,7 +81,7 @@ interface CollabFeatures { chat: boolean; notes: boolean; links?: boolean; pollsconst COLLAB_SUB_FEATURES = [{ key: 'chat', icon: MessageCircle, titleKey: 'admin.collab.chat.title', subtitleKey: 'admin.collab.chat.subtitle' },{ key: 'notes', icon: StickyNote, titleKey: 'admin.collab.notes.title', subtitleKey: 'admin.collab.notes.subtitle' },- { key: 'links', icon: Link2, titleKey: 'collab.tabs.links', subtitleKey: 'collab.links.empty' },+ { key: 'links', icon: Link2, titleKey: 'collab.tabs.links', subtitleKey: 'admin.collab.links.subtitle' },{ key: 'polls', icon: BarChart3, titleKey: 'admin.collab.polls.title', subtitleKey: 'admin.collab.polls.subtitle' },{ key: 'whatsnext', icon: Sparkles, titleKey: 'admin.collab.whatsnext.title', subtitleKey: 'admin.collab.whatsnext.subtitle' },] as constdiff --git a/client/src/mobile/screens/trip/roadtrip/MRoadtripRows.tsx b/client/src/mobile/screens/trip/roadtrip/MRoadtripRows.tsxindex c784d5385..e392f5bd6 100644--- a/client/src/mobile/screens/trip/roadtrip/MRoadtripRows.tsx+++ b/client/src/mobile/screens/trip/roadtrip/MRoadtripRows.tsx@@ -514,7 +514,7 @@ export function RtSpillRow({ fromDayNumber, departs, chrome, children }: {</span>{departs && (<span className="ms-auto text-[0.71875rem] font-semibold tabular-nums text-m-ink">- {t('roadtrip.spill.departs', { time: departs })}+ {t('roadtrip.spill.departs', { time: formatClockTime(departs, chrome.is12h) })}</span>)}</div>diff --git a/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx b/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsxindex 6d4dca398..d84836846 100644--- a/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx+++ b/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx@@ -64,6 +64,14 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {const stage = rt.stage+ // The map's whole-trip view leaves no day selected, and it stays that way when the+ // list comes up: the switch here restores nothing on purpose, and the plan tab's+ // toggle does that job only for its own timeline. The chain is one stage wide, so+ // with routed days and no day picked it asks for one, rather than claiming there is+ // no route while the header above prints the whole drive's distance. A day that is+ // picked and has no drive of its own still gets the empty stage further down.+ const noDayPicked = !stage && !rt.empty && !rt.loading && planner.selectedDayId == null+// The disc is only a control for somebody who may change a place. Read here rather than// inside the row so the whole chain asks once, the way `rt` and `chrome` are handled.const canEditPlaces = planner.can('place_edit', planner.trip)@@ -127,7 +135,9 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) {searchBar ? 'pt-[calc(var(--m-safe-top,12px)+150px)]' : 'pt-[calc(var(--m-safe-top,12px)+102px)]'}`}>- {rt.empty || !stage ? (+ {noDayPicked ? (+ <PickDay planner={planner} />+ ) : rt.empty || !stage ? (<EmptyStage planner={planner} loading={rt.loading} />) : (<>@@ -375,6 +385,25 @@ function EmptyStage({ planner, loading }: { planner: MTripTabPanelProps['planner)}+/**+ * No day on screen, because the map is showing all of them.+ *+ * Same shape as the empty stage, different sentence: the drive is there, the chips+ * above are where a stage comes back from, and the line says so.+ */+function PickDay({ planner }: { planner: MTripTabPanelProps['planner'] }) {+ const { t } = planner+ return (+ <div className="flex flex-col items-center justify-center px-5 py-16 text-center">+ <MDancingTrek scene="guide" className="mb-2" />+ <p className="text-[0.9375rem] font-semibold text-m-ink">{t('mobileTrip.rtNoDay')}</p>+ <p className="mt-1.5 max-w-[27ch] font-geist text-[0.78125rem] leading-[1.5] text-m-muted">+ {t('mobileTrip.rtNoDayHint')}+ </p>+ </div>+ )+}+/* ── small helpers ────────────────────────────────────────────────────────── */function stageDateLabel(planner: MTripTabPanelProps['planner'], dayId: number): string | null {diff --git a/client/src/mobile/screens/trip/sheets/MTripSheets.tsx b/client/src/mobile/screens/trip/sheets/MTripSheets.tsxindex 6c304c84c..84c067c0e 100644--- a/client/src/mobile/screens/trip/sheets/MTripSheets.tsx+++ b/client/src/mobile/screens/trip/sheets/MTripSheets.tsx@@ -179,12 +179,20 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {/>{/* Delete-place confirm behind handleDeletePlace (the place edit sheet- arms the same flag for its own two-tap delete — skip it there). */}+ arms the same flag for its own two-tap delete — skip it there).+ A night booked at the place goes down with it, and with the night+ the booking and its expense: the planner adds that as a second+ sentence, the same one the desktop question carries. */}<MConfirmSheetopen={planner.deletePlaceId != null && !planner.showPlaceForm}onClose={() => planner.setDeletePlaceId(null)}title={t('common.delete')}- message={t('trip.confirm.deletePlace')}+ message={planner.deletePlaceNote ? (+ <>+ <span className="block">{t('trip.confirm.deletePlace')}</span>+ <span className="mt-1 block">{planner.deletePlaceNote}</span>+ </>+ ) : t('trip.confirm.deletePlace')}confirmLabel={t('common.delete')}cancelLabel={t('common.cancel')}dangerdiff --git a/client/src/mobile/screens/trip/tabs/MCollabChat.tsx b/client/src/mobile/screens/trip/tabs/MCollabChat.tsxindex 966d0add8..c68ac1b77 100644--- a/client/src/mobile/screens/trip/tabs/MCollabChat.tsx+++ b/client/src/mobile/screens/trip/tabs/MCollabChat.tsx@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { ArrowUp, ChevronUp, ImagePlus, Loader2, Reply, Trash2 } from 'lucide-react'import MDancingTrek from '../../../components/MDancingTrek'-import { useChatImages } from '../../../../components/Collab/useChatImages'+import { useChatImages, MAX_CHAT_IMAGES } from '../../../../components/Collab/useChatImages'import { collabApi } from '../../../../api/client'import { addListener, removeListener } from '../../../../api/websocket'import { useAuthStore } from '../../../../store/authStore'@@ -160,7 +160,10 @@ export default function MCollabChat({ planner }: MCollabChatProps) {}const addImageFiles = (incoming: FileList | File[]) => {- if (!images.add(incoming)) toast.error(t('collab.chat.imageRejected'))+ images.add(incoming, ({ rejected, overflow }) => {+ if (rejected) toast.error(t('collab.chat.imageRejected'))+ if (overflow) toast.error(t('collab.chat.imageLimit', { max: MAX_CHAT_IMAGES }))+ })}const handleSend = useCallback(async () => {diff --git a/client/src/mobile/screens/trip/tabs/MDocSyncSheet.test.tsx b/client/src/mobile/screens/trip/tabs/MDocSyncSheet.test.tsxindex 869e65ce6..e21a4f56b 100644--- a/client/src/mobile/screens/trip/tabs/MDocSyncSheet.test.tsx+++ b/client/src/mobile/screens/trip/tabs/MDocSyncSheet.test.tsx@@ -1,4 +1,4 @@-// FE-DOCSYNC-MOBILE-001 to FE-DOCSYNC-MOBILE-018+// FE-DOCSYNC-MOBILE-001 to FE-DOCSYNC-MOBILE-024import type { ComponentProps } from 'react'import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { render, screen, fireEvent, waitFor, within } from '../../../../../tests/helpers/render'@@ -135,8 +135,18 @@ beforeEach(() => {vi.spyOn(docsyncApi, 'saveConnection').mockResolvedValue({})vi.spyOn(docsyncApi, 'createScope').mockResolvedValue(scope({}))vi.spyOn(docsyncApi, 'createLink').mockResolvedValue({})+ vi.spyOn(docsyncApi, 'items').mockResolvedValue([])+ vi.spyOn(docsyncApi, 'resolve').mockResolvedValue({ success: true })})+/** The status route with a number of conflicts on it, holdings as usual. */+function withConflicts(count: number) {+ vi.spyOn(docsyncApi, 'status').mockImplementation(async () => ({+ items: { conflict: count },+ links: links.map(l => ({ id: l.id, holdings: { inTrek: 4, atProvider: 2, paired: 2, missing: 0 } })),+ }))+}+afterEach(() => {vi.restoreAllMocks()})@@ -273,6 +283,21 @@ describe('MDocSyncSheet: moving between the views', () => {// A folder name is suggested from the trip so nobody has to invent one.expect(screen.getByDisplayValue('rome-3')).toBeInTheDocument()})++ it('FE-DOCSYNC-MOBILE-019: a folder listing that fails outright says so instead of spinning', async () => {+ // Not a provider failure, which the route folds into a 200: the request itself+ // dies, as it does when the phone loses its signal or a proxy answers 502.+ vi.spyOn(docsyncApi, 'listScopes').mockRejectedValue({ response: { status: 502, data: '<html>Bad Gateway</html>' } })+ renderSheet()++ fireEvent.click(await screen.findByRole('button', { name: /Nextcloud/ }))++ expect(await screen.findByText('Something went wrong.')).toBeInTheDocument()+ expect(document.querySelector('.animate-spin')).toBeNull()+ expect(screen.queryByRole('button', { name: /Photos/ })).not.toBeInTheDocument()+ // The new-folder lane stays usable: a listing that failed is not a store that is gone.+ expect(screen.getByRole('button', { name: /Create/ })).toBeEnabled()+ })})describe('MDocSyncSheet: the two lanes', () => {@@ -352,11 +377,92 @@ describe('MDocSyncSheet: what the owner may do', () => {})renderSheet()await openDetail()- expect(screen.queryByText('Paused: an administrator has switched this provider off. Syncing resumes once it is back on.')).not.toBeInTheDocument()+ const paused = 'Paused: an administrator has switched this provider off. Syncing resumes once it is back on.'+ expect(screen.queryByText(paused)).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Sync now' }))++ // The standing notice on the binding, and the refused run's own report+ // under it, which says the same reason for this one.+ expect(await screen.findAllByText(paused)).toHaveLength(2)+ expect(screen.getByRole('alert')).toHaveTextContent(paused)+ })++ it('FE-DOCSYNC-MOBILE-021: a choice the server refuses is said in the sheet, and the row stays', async () => {+ withConflicts(1)+ vi.spyOn(docsyncApi, 'items').mockResolvedValue([{ id: 40, file_name: 'boarding-pass.pdf', remote_name: 'boarding-pass.pdf' }])+ // Settled by the owner on another device a moment ago.+ vi.spyOn(docsyncApi, 'resolve').mockRejectedValue({ response: { status: 400, data: { error: 'conflict' } } })+ renderSheet()+ await openDetail()+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: /Resolve/ }))+ fireEvent.click(await screen.findByRole('button', { name: 'Keep the TREK version' }))++ await waitFor(() => expect(docsyncApi.resolve).toHaveBeenCalledWith(TRIP_ID, 40, 'trek'))+ expect(await screen.findByRole('alert')).toHaveTextContent('The document changed on both sides.')+ // The list is read back rather than trimmed by hand, so the row is still+ // there, ready for another try.+ await waitFor(() => expect(screen.getByRole('button', { name: 'Keep the TREK version' })).toBeEnabled())+ expect(screen.getByText('boarding-pass.pdf')).toBeInTheDocument()+ expect(docsyncApi.items).toHaveBeenCalledTimes(2)+ })++ it('FE-DOCSYNC-MOBILE-022: a refused credential offers Reconnect, and saving runs the binding and comes back to it', async () => {+ // The list only ever opens the form for a store with no connection yet,+ // and a bound store is not listed there, so a rotated token could only+ // be entered through the API.+ links = [link({ lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' })]+ renderSheet()+ await openDetail()++ fireEvent.click(screen.getByRole('button', { name: 'Reconnect' }))++ // The credential form for this store, not the folder picker.+ expect(await screen.findByRole('button', { name: 'Save' })).toBeInTheDocument()+ expect(screen.getByDisplayValue('https://paperless.example')).toBeInTheDocument()+ expect(screen.queryByText('Or use one you already have')).not.toBeInTheDocument()+ expect(docsyncApi.listScopes).not.toHaveBeenCalled()++ fireEvent.change(screen.getByLabelText(/API token/), { target: { value: 'fresh-token' } })+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(docsyncApi.saveConnection).toHaveBeenCalledWith(TRIP_ID, expect.objectContaining({+ providerId: 'paperless',+ credentials: expect.objectContaining({ api_token: 'fresh-token' }),+ })))+ await waitFor(() => expect(docsyncApi.syncNow).toHaveBeenCalledWith(TRIP_ID, 11, false))+ // Back on the binding, not at the list and not in the folder picker.+ expect(await screen.findByRole('button', { name: 'Sync now' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()+ expect(screen.queryByText('Or use one you already have')).not.toBeInTheDocument()+ })++ it('FE-DOCSYNC-MOBILE-023: the back arrow from the reconnect form returns to the binding, and a paused provider offers no Reconnect', async () => {+ links = [link({ lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' })]+ renderSheet()+ await openDetail()++ fireEvent.click(screen.getByRole('button', { name: 'Reconnect' }))+ await screen.findByRole('button', { name: 'Save' })+ fireEvent.click(screen.getByRole('button', { name: 'Back' }))++ expect(await screen.findByRole('button', { name: 'Sync now' })).toBeInTheDocument()+ expect(screen.queryByText('Add another')).not.toBeInTheDocument()+ expect(docsyncApi.saveConnection).not.toHaveBeenCalled()+ expect(docsyncApi.syncNow).not.toHaveBeenCalled()+ // Switched off by an admin meanwhile: a new credential would change+ // nothing until it is back on, so the paused notice stands alone.+ vi.spyOn(docsyncApi, 'status').mockImplementation(async () => ({+ items: {},+ links: links.map(l => ({ id: l.id, providerOff: true, holdings: { inTrek: 4, atProvider: 2, paired: 2, missing: 0 } })),+ }))fireEvent.click(screen.getByRole('button', { name: 'Sync now' }))- expect(await screen.findByText('Paused: an administrator has switched this provider off. Syncing resumes once it is back on.')).toBeInTheDocument()+ expect(await screen.findByText(/Paused: an administrator/)).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Reconnect' })).not.toBeInTheDocument()})it('FE-DOCSYNC-MOBILE-014: Sync now runs that binding', async () => {@@ -387,6 +493,30 @@ describe('MDocSyncSheet: what a member may do', () => {expect(screen.getByRole('button', { name: 'Sync now' })).toBeEnabled()})+ it('FE-DOCSYNC-MOBILE-020: a member is shown the conflict count but offered no choice', async () => {+ // The server refuses a member's choice with 403, so the three buttons+ // would only ever fail for them. The count is what they are owed.+ withConflicts(3)+ renderSheet({ canManage: false })+ await openDetail()++ expect(screen.getByText('Both copies changed')).toBeInTheDocument()+ expect(screen.getByText('Changed in both places. Pick which one to keep.')).toBeInTheDocument()+ expect(screen.getByText('3')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /Resolve/ })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Keep the TREK version' })).not.toBeInTheDocument()+ expect(docsyncApi.items).not.toHaveBeenCalled()+ })++ it('FE-DOCSYNC-MOBILE-024: a member whose store refused its credential is told, but not offered Reconnect', async () => {+ links = [link({ lastSyncState: 'needs_reauth', lastSyncError: 'unauthorized' })]+ renderSheet({ canManage: false })+ await openDetail()++ expect(screen.getByText(/The credentials were refused/)).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Reconnect' })).not.toBeInTheDocument()+ })+it('FE-DOCSYNC-MOBILE-016: a member is not offered stores to add, and an unbound trip explains who sets it up', async () => {links = []renderSheet({ canManage: false })diff --git a/client/src/mobile/screens/trip/tabs/MDocSyncSheet.tsx b/client/src/mobile/screens/trip/tabs/MDocSyncSheet.tsxindex a3bc14bbf..c2dc08487 100644--- a/client/src/mobile/screens/trip/tabs/MDocSyncSheet.tsx+++ b/client/src/mobile/screens/trip/tabs/MDocSyncSheet.tsx@@ -1,6 +1,6 @@import { useEffect, useMemo, useState } from 'react'import {- ArrowLeft, ArrowRight, Check, ChevronLeft, ChevronRight, FolderPlus, FolderSync, Link2Off,+ ArrowLeft, ArrowRight, Check, ChevronLeft, ChevronRight, FolderPlus, FolderSync, KeyRound, Link2Off,Loader2, Plus, RefreshCw,} from 'lucide-react'import MSheet from '../../../components/MSheet'@@ -12,7 +12,7 @@ import { useTranslation } from '../../../../i18n'import { DOCUMENT_PROVIDER_ICONS } from '../../../../components/shared/DocumentProviderIcons'import TrekIcon from '../../../../components/shared/TrekIcon'import {- bindingNotice, storeName, useDocSync, type DocSyncLink, type DocSyncProvider,+ bindingNotice, needsReauth, storeName, useDocSync, type DocSyncLink, type DocSyncProvider,} from '../../../../components/Files/docsync/useDocSync'import { useConnectForm } from '../../../../components/Files/docsync/useConnectForm'import { conflictPolicyKey, nextConflictPolicy } from '../../../../components/Files/docsync/DocSyncBits'@@ -52,10 +52,18 @@ export default function MDocSyncSheet({const [selected, setSelected] = useState<number | null>(null)const [pending, setPending] = useState<DocSyncProvider | null>(null)const [confirmUnlink, setConfirmUnlink] = useState(false)+ // The binding whose credentials are being entered again, while the connect+ // view is open for it. Kept apart from `pending`, whose next step is the+ // folder picker: here the folder is known and the next step is the run that+ // the refusal stopped.+ const [reconnectFor, setReconnectFor] = useState<number | null>(null)const bound = useMemo(() => new Set(sync.links.map(l => l.providerId)), [sync.links])const available = sync.providers.filter(p => !bound.has(p.id))const link = sync.links.find(l => l.id === selected) ?? null+ // Undefined once an admin has switched the store off: the form needs the+ // provider's field list, and the providers route no longer carries it.+ const linkProvider = link ? sync.providers.find(p => p.id === link.providerId) : undefined// A store that was removed elsewhere must not leave the detail view pointing// at nothing.@@ -66,14 +74,37 @@ export default function MDocSyncSheet({// Every open starts at the list: a sheet that reopens three steps deep is a// sheet somebody has to find their way out of.useEffect(() => {- if (!open) { setView('list'); setPending(null) }+ if (!open) { setView('list'); setPending(null); setReconnectFor(null) }}, [open])const openStore = (p: DocSyncProvider) => {+ setReconnectFor(null)setPending(p)setView(sync.connectionFor(p.id) ? 'scope' : 'connect')}+ const reconnect = (l: DocSyncLink, p: DocSyncProvider) => {+ setReconnectFor(l.id)+ setPending(p)+ setView('connect')+ }++ /** The step before this one: the binding for a reconnect, the list otherwise. */+ const back = () => {+ if (reconnectFor !== null) { setReconnectFor(null); setView('detail') } else setView('list')+ }++ const connected = () => {+ if (reconnectFor === null) { setView('scope'); return }+ // Run straight away, as binding does: the card still reports the refusal+ // until a run says otherwise, and the person has just done the one thing+ // that could change the answer.+ const id = reconnectFor+ setReconnectFor(null)+ setView('detail')+ void sync.syncNow(id)+ }+const title =view === 'connect' || view === 'scope'? pending?.name ?? t('docsync.title')@@ -87,7 +118,7 @@ export default function MDocSyncSheet({<div className="flex-none px-[18px] pt-4"><div className="flex items-center gap-2">{view !== 'list' && (- <MIconBtn variant="neutral" size={34} onClick={() => setView('list')} ariaLabel={t('common.back')}>+ <MIconBtn variant="neutral" size={34} onClick={back} ariaLabel={t('common.back')}><ChevronLeft size={16} strokeWidth={2.2} /></MIconBtn>)}@@ -115,7 +146,7 @@ export default function MDocSyncSheet({<ConnectViewprovider={pending}sync={sync}- onDone={() => setView('scope')}+ onDone={connected}/>) : view === 'scope' && pending && sync.connectionFor(pending.id) ? (<ScopeView@@ -132,6 +163,7 @@ export default function MDocSyncSheet({sync={sync}canManage={canManage}onUnlink={() => setConfirmUnlink(true)}+ onReconnect={linkProvider ? () => reconnect(link, linkProvider) : undefined}/>) : (<ListView@@ -233,6 +265,7 @@ function DetailView({sync,canManage,onUnlink,+ onReconnect,}: {link: DocSyncLinktripId: number | string@@ -240,9 +273,19 @@ function DetailView({sync: ReturnType<typeof useDocSync>canManage: booleanonUnlink: () => void+ /**+ * Opens the credential form for this binding's store. Only the sheet can,+ * because the form needs the provider's field list, which the card does+ * not carry; left out, a refused credential is reported but not curable.+ */+ onReconnect?: () => void}) {const { t, language } = useTranslation()const busy = sync.busy === `sync-${link.id}`+ // Not while the provider is switched off: the paused notice stands in front+ // of the refusal then, and a new credential would change nothing until an+ // admin turns the provider back on.+ const reconnect = canManage && onReconnect && !link.providerOff && needsReauth(link) ? onReconnect : nullconst holdings = link.holdings ?? { inTrek: 0, atProvider: 0, paired: 0, missing: 0 }const pushOn = link.direction === 'both' || link.direction === 'push'const pullOn = link.direction === 'both' || link.direction === 'pull'@@ -305,7 +348,30 @@ function DetailView({</p>)}- <MConflicts tripId={tripId} sync={sync} count={sync.itemCounts.conflict ?? 0} />+ {/* The one state a person can act on from here. Without this the only+ way past a rotated token was the API: the list opens the form for a+ store that has no connection yet, and this one has. */}+ {reconnect && (+ <button+ type="button"+ onClick={reconnect}+ className="flex h-11 w-full items-center justify-center gap-2 rounded-2xl border border-[color:var(--m-rowbr)] text-[0.8125rem] font-bold text-m-ink"+ >+ <KeyRound size={15} strokeWidth={2.2} />+ {t('docsync.binding.reconnect')}+ </button>+ )}++ {/* Every action on this view reports here: a refused run, a switch that+ flipped back, a conflict the server would not settle. Nothing said+ what happened to a tap before. */}+ {sync.error && (+ <p role="alert" className="rounded-2xl bg-[color:var(--m-ic)] px-3 py-2 font-geist text-[0.6875rem] text-[color:var(--m-st-danger)]">+ {t(`docsync.error.${sync.error}`)}+ </p>+ )}++ <MConflicts tripId={tripId} sync={sync} count={sync.itemCounts.conflict ?? 0} canManage={canManage} /><buttontype="button"@@ -767,33 +833,48 @@ function MConflicts({tripId,sync,count,+ canManage,}: {tripId: number | stringsync: ReturnType<typeof useDocSync>count: number+ canManage: boolean}) {const { t } = useTranslation()const [open, setOpen] = useState(false)- const conflicts = useConflicts(tripId, sync, open)+ const conflicts = useConflicts(tripId, sync, canManage && open)if (count === 0) return null+ const heading = (+ <span className="min-w-0">+ <span className="block font-geist text-[0.75rem] font-bold text-m-ink">{t('docsync.conflict.title')}</span>+ <span className="mt-0.5 block font-geist text-[0.6875rem] text-m-muted">{t('docsync.issues.conflict')}</span>+ </span>+ )+return (<section className="rounded-2xl bg-[color:var(--m-ic)] px-3 py-2.5">- <button- type="button"- onClick={() => setOpen(v => !v)}- className="flex w-full items-center justify-between gap-3 text-left"- >- <span className="min-w-0">- <span className="block font-geist text-[0.75rem] font-bold text-m-ink">{t('docsync.conflict.title')}</span>- <span className="mt-0.5 block font-geist text-[0.6875rem] text-m-muted">{t('docsync.issues.conflict')}</span>- </span>- <span className="shrink-0 font-geist text-[0.6875rem] font-bold text-m-ink">- {open ? t('common.close') : t('docsync.conflict.resolve', { count })}- </span>- </button>+ {/* Only the owner gets to open it: the server refuses a member's choice,+ so a member gets the count, as the desktop panel gives it. */}+ {canManage ? (+ <button+ type="button"+ onClick={() => setOpen(v => !v)}+ className="flex w-full items-center justify-between gap-3 text-left"+ >+ {heading}+ <span className="shrink-0 font-geist text-[0.6875rem] font-bold text-m-ink">+ {open ? t('common.close') : t('docsync.conflict.resolve', { count })}+ </span>+ </button>+ ) : (+ <div className="flex w-full items-center justify-between gap-3 text-left">+ {heading}+ <span className="shrink-0 font-geist text-[0.6875rem] font-bold tabular-nums text-m-ink">{count}</span>+ </div>+ )}- {open && (+ {canManage && open && (<ul className="mt-2.5 space-y-2">{conflicts.items === null && (<li className="flex justify-center py-2">diff --git a/client/src/pages/TripPlannerPage.tsx b/client/src/pages/TripPlannerPage.tsxindex c46dbec0a..500a4cfb0 100644--- a/client/src/pages/TripPlannerPage.tsx+++ b/client/src/pages/TripPlannerPage.tsx@@ -294,7 +294,8 @@ function TripPlannerPageDesktop(): React.ReactElement | null {reservationPrefill, transportPrefill, importReviewActive, advanceImportReview,routeShown, setRouteShown, transitRoutesShown, routeProfile, setRouteProfile, routeVias, fitKey, setFitKey,mobileSidebarOpen, setMobileSidebarOpen, mobilePlanScrollTopRef, mobilePlacesScrollTopRef,- deletePlaceId, setDeletePlaceId, deletePlaceIds, setDeletePlaceIds,+ deletePlaceId, setDeletePlaceId, deletePlaceIds, setDeletePlaceIds, deletePlaceNote, deletePlacesNote,+ stayRelease, setStayRelease, confirmStayRelease,visibleConnections, toggleConnection, allConnectionsShown, toggleAllConnections, mapTransportDetail, setMapTransportDetail,isMobile, isTouch,expandedDayIds, setExpandedDayIds, mapPlaces,@@ -1137,14 +1138,26 @@ function TripPlannerPageDesktop(): React.ReactElement | null {onClose={() => setDeletePlaceId(null)}onConfirm={confirmDeletePlace}title={t('common.delete')}- message={t('trip.confirm.deletePlace')}+ message={deletePlaceNote ? `${t('trip.confirm.deletePlace')} ${deletePlaceNote}` : t('trip.confirm.deletePlace')}/><ConfirmDialogisOpen={!!deletePlaceIds?.length}onClose={() => setDeletePlaceIds(null)}onConfirm={confirmDeletePlaces}title={t('common.delete')}- message={t('trip.confirm.deletePlaces', { count: deletePlaceIds?.length ?? 0 })}+ message={deletePlacesNote+ ? `${t('trip.confirm.deletePlaces', { count: deletePlaceIds?.length ?? 0 })} ${deletePlacesNote}`+ : t('trip.confirm.deletePlaces', { count: deletePlaceIds?.length ?? 0 })}+ />+ <ConfirmDialog+ isOpen={!!stayRelease}+ onClose={() => setStayRelease(null)}+ onConfirm={confirmStayRelease}+ title={t('roadtrip.stay.releaseTitle')}+ message={stayRelease?.booking+ ? t('roadtrip.stay.releaseBookedBody', { name: stayRelease.name, booking: stayRelease.booking })+ : t('roadtrip.stay.releaseBody', { name: stayRelease?.name ?? '' })}+ confirmLabel={t('roadtrip.stay.releaseAction')}/></div>)diff --git a/client/src/pages/TripPlannerPage.wiring.test.tsx b/client/src/pages/TripPlannerPage.wiring.test.tsxindex 724b919e9..f8d44b47d 100644--- a/client/src/pages/TripPlannerPage.wiring.test.tsx+++ b/client/src/pages/TripPlannerPage.wiring.test.tsx@@ -1,4 +1,4 @@-// FE-PAGE-TPW-001 to FE-PAGE-TPW-061+// FE-PAGE-TPW-001 to FE-PAGE-TPW-062//// The planner page is a wiring container: everything stateful lives in// useTripPlanner (covered in src/pages/tripPlanner/useTripPlanner.test.tsx).@@ -285,6 +285,9 @@ function baseState(): HookState {setDeletePlaceId: vi.fn(),deletePlaceIds: null,setDeletePlaceIds: vi.fn(),+ stayRelease: null,+ setStayRelease: vi.fn(),+ confirmStayRelease: vi.fn(async () => undefined),visibleConnections: [],toggleConnection: vi.fn(),allConnectionsShown: false,@@ -1291,4 +1294,17 @@ describe('TripPlannerPage — modals', () => {expect(hookState.setDeletePlaceIds).toHaveBeenCalledWith(null)expect(hookState.confirmDeletePlaces).toHaveBeenCalled()})++ it('FE-PAGE-TPW-062: the question before a booked night becomes a pause answers through the hook', () => {+ renderPage({ stayRelease: { stop: { stopType: null, dwellMinutes: 30 }, name: 'Hotel Fjord', booking: 'Booking 4711' } })++ const [, , release] = confirmDialogs as unknown as Array<Record<string, () => unknown> & { isOpen: boolean }>+ expect(release.isOpen).toBe(true)++ act(() => { release.onClose() })+ expect(hookState.setStayRelease).toHaveBeenCalledWith(null)++ act(() => { release.onConfirm() })+ expect(hookState.confirmStayRelease).toHaveBeenCalled()+ })})diff --git a/client/src/pages/admin/AdminSettingsTab.test.tsx b/client/src/pages/admin/AdminSettingsTab.test.tsxindex 5a5b95c23..91d28cd10 100644--- a/client/src/pages/admin/AdminSettingsTab.test.tsx+++ b/client/src/pages/admin/AdminSettingsTab.test.tsx@@ -1,4 +1,4 @@-// FE-ADMSET-001 to FE-ADMSET-040+// FE-ADMSET-001 to FE-ADMSET-042import { http, HttpResponse } from 'msw';import React from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -566,4 +566,26 @@ describe('AdminSettingsTab', () => {expect(screen.queryByRole('button', { name: /trek place index/i })).not.toBeInTheDocument();expect(screen.queryByText(/place search uses openstreetmap/i)).not.toBeInTheDocument();});++ it('FE-ADMSET-042: a failing transit provider save rolls back and says why', async () => {+ // CustomSelect renders a plain button named after the selected option, so the+ // trigger is found through its own block, and the menu entry is the button that+ // is not the trigger.+ server.use(http.put('/api/admin/transit-provider', () => HttpResponse.json({ error: 'Settings are read-only' }, { status: 500 })));+ const admin = renderTab({+ transitProvider: 'transitous',+ setTransitProviderState: vi.fn(),+ transitGoogleKeySource: 'instance',+ setTransitGoogleKeySource: vi.fn(),+ });+ const block = screen.getByText('Transit Provider').closest<HTMLElement>('.rounded-xl')!;++ fireEvent.click(within(block).getByRole('button'));+ fireEvent.click(screen.getByText('Google'));++ expect(admin.setTransitProviderState).toHaveBeenNthCalledWith(1, 'google');+ await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Settings are read-only'));+ expect(admin.setTransitProviderState).toHaveBeenLastCalledWith('transitous');+ expect(admin.setTransitGoogleKeySource).not.toHaveBeenCalled();+ });});diff --git a/client/src/pages/admin/AdminSettingsTab.tsx b/client/src/pages/admin/AdminSettingsTab.tsxindex 13dc91cfb..668ad3caa 100644--- a/client/src/pages/admin/AdminSettingsTab.tsx+++ b/client/src/pages/admin/AdminSettingsTab.tsx@@ -597,7 +597,12 @@ export default function AdminSettingsTab({ admin, t }: AdminSettingsTabProps): Rtry {const saved = await adminApi.updateTransitProvider(next)setTransitGoogleKeySource(saved.googleKeySource)- } catch { setTransitProviderState(previous) }+ } 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')))+ }}}options={[{ value: 'transitous', label: t('admin.transitProvider.transitous') },diff --git a/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsxindex b06938313..594475846 100644--- a/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx+++ b/client/src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx@@ -1,5 +1,5 @@import { roadtripPreferencesRepo } from '../../repo/roadtripPreferencesRepo'-// FE-TP-ROAD-001 to FE-TP-ROAD-099+// FE-TP-ROAD-001 to FE-TP-ROAD-108import React from 'react'import { renderHook, act, waitFor } from '@testing-library/react'import { TranslationProvider } from '../../i18n/TranslationContext'@@ -11,7 +11,7 @@ import { usePermissionsStore } from '../../store/permissionsStore'import { useSettingsStore } from '../../store/settingsStore'import { useBackgroundTasksStore } from '../../store/backgroundTasksStore'import { resetAllStores, seedStore } from '../../../tests/helpers/store'-import { buildUser, buildTrip, buildDay, buildPlace, buildAssignment } from '../../../tests/helpers/factories'+import { buildUser, buildTrip, buildDay, buildPlace, buildAssignment, buildReservation } from '../../../tests/helpers/factories'import {addonsApi, accommodationsApi, authApi, tripsApi, healthApi, airtrailApi, mapsApi,} from '../../api/client'@@ -2168,3 +2168,257 @@ describe('useTripPlanner road trip: the phone feed', () => {expect(result.current.roadtripFeedActive).toBe(true)})})++/**+ * The vias of a day are anchored by POSITION among the stops the router counts, and+ * that count is taken over the STORED list: the day list read as a plan hides the stop+ * a lodging booking put on the day and, behind the switch, the service stops, but the+ * server and the routing round count every one of them. The handlers below are+ * reachable from the place inspector and the day plan in Days mode, where the hook's+ * own list is the shorter one, and a plan measured on it deleted the via behind a+ * hidden hotel or pinned it to a leg nobody drew.+ */+describe('useTripPlanner road trip: corrections measured on the stored day', () => {+ /** A day whose last stop is the hotel a booking put there, hidden under Days. */+ const dayWithHiddenNight = () => {+ seedTrip({+ days: [buildDay({ id: 5, day_number: 1 })],+ assignments: { '5': [stopAt(11, 5, 0), stopAt(13, 5, 1), stopAt(14, 5, 2, { accommodation_id: 7 })] },+ })+ rt.corridor.day = { dayId: 5, dayNumber: 1 }+ }++ it('FE-TP-ROAD-100: removing a stop under Days counts the night the list hides, so the via behind it moves instead of going', async () => {+ dayWithHiddenNight()+ // On the leg from the second stop to the hotel.+ rt.vias.byDay = { 5: [via(1, 5, 1)] }+ const { result } = await renderRoadtrip()+ act(() => result.current.toggleRoadtripMode())+ expect(result.current.assignments['5'].map(a => a.id)).toEqual([11, 13])++ await act(async () => { await result.current.handleRemoveAssignment(5, 11) })++ expect(actions.removeAssignment).toHaveBeenCalledWith(42, 5, 11)+ // Three stops, not two: with two the day would have no leg left and every via+ // of the day would be deleted on the server.+ expect(rt.vias.reanchor).toHaveBeenCalledWith(5, { vias: [{ id: 1, after_order_index: 0 }], remove: [] })+ })++ it('FE-TP-ROAD-101: a drag under Days keeps a via behind the stop it was drawn after, hotel included', async () => {+ dayWithHiddenNight()+ // On the leg from the first stop to the second.+ rt.vias.byDay = { 5: [via(1, 5, 0)] }+ const { result } = await renderRoadtrip()+ act(() => result.current.toggleRoadtripMode())++ await act(async () => result.current.handleReorder(5, [13, 11]))++ expect(actions.reorderAssignments).toHaveBeenCalledWith(42, 5, [13, 11, 14])+ // The first stop is now second, and the leg from it to the hotel still exists.+ await waitFor(() => expect(rt.vias.reanchor).toHaveBeenCalledWith(5, { vias: [{ id: 1, after_order_index: 1 }], remove: [] }))+ })++ it('FE-TP-ROAD-102: a drop under Days past the last visible row still lands before the hidden hotel', async () => {+ dayWithHiddenNight()+ rt.routes.days = [{+ dayId: 5,+ dayNumber: 1,+ stops: [{ lat: 53, lng: 10 }, { lat: 54, lng: 11 }, { lat: 55, lng: 12 }],+ geometry: [[53, 10], [54, 11], [55, 12]],+ }]+ // On the leg from the second stop to the hotel, past where the new stop goes.+ rt.vias.byDay = { 5: [via(1, 5, 1, 0, 54.8, 11.8)] }+ seedStore(useTripStore, { places: [buildPlace({ id: 300, lat: 54.2, lng: 11.2 })] })+ const { result } = await renderRoadtrip()+ act(() => result.current.toggleRoadtripMode())++ // Row index 2 is the hotel's row in the day as it is stored, one past the last+ // row the day plan shows.+ await act(async () => { await result.current.handleAssignToDay(300, 5, 2) })++ expect(actions.assignPlaceToDay).toHaveBeenCalledWith(42, 5, 300, 2)+ expect(rt.vias.reanchor).toHaveBeenCalledWith(5, { vias: [{ id: 1, after_order_index: 2 }], remove: [] })+ })++ it('FE-TP-ROAD-103: a row index is translated into a stop index before the vias are corrected', async () => {+ // A row without coordinates is never a stop, so the number of rows ahead of a drop+ // is not the number of stops ahead of it.+ seedTrip({+ days: [buildDay({ id: 5, day_number: 1 })],+ assignments: { '5': [placeless(10, 5, 0), stopAt(11, 5, 1), stopAt(13, 5, 2)] },+ })+ rt.corridor.day = { dayId: 5, dayNumber: 1 }+ rt.routes.days = [{+ dayId: 5,+ dayNumber: 1,+ stops: [{ lat: 54, lng: 11 }, { lat: 55, lng: 12 }],+ geometry: [[54, 11], [55, 12]],+ }]+ rt.vias.byDay = { 5: [via(1, 5, 0, 0, 54.8, 11.8)] }+ seedStore(useTripStore, { places: [buildPlace({ id: 300, lat: 54.2, lng: 11.2 })] })+ const { result } = await renderRoadtrip()++ await act(async () => { await result.current.handleAssignToDay(300, 5, 2) })++ // Row 2 is stop 1: the via on the only leg is now behind the new stop.+ expect(rt.vias.reanchor).toHaveBeenCalledWith(5, { vias: [{ id: 1, after_order_index: 1 }], remove: [] })+ })+})++describe('useTripPlanner road trip: a booked night in the popup', () => {+ const hotel = () => buildPlace({ id: 102, name: 'Hotel Fjord', stop_type: 'hotel', lat: 60.39, lng: 5.32 })++ /** The popup as `openPlaceEditor` opens it on a booked night. */+ const editingNight = (result: { current: ReturnType<typeof useTripPlanner> }) => {+ act(() => {+ result.current.setStopDraft({+ poi: poi({ name: 'Hotel Fjord', category: 'hotel', lat: 60.39, lng: 5.32 }) as never,+ dayId: 5,+ dayNumber: 1,+ position: 1,+ editing: { placeId: 102, stopType: 'hotel', dwellMinutes: 30, accommodationId: 7, checkIn: '15:00', checkOut: '' },+ overnight: { days: [{ id: 5, number: 1, date: null }, { id: 6, number: 2, date: null }], defaultEndDayId: 6 },+ })+ })+ }++ it('FE-TP-ROAD-104: switching a booked night to a pause asks first, naming the booking that would go', async () => {+ const stay = hotel()+ seedTrip({+ places: [stay],+ days: [buildDay({ id: 5, day_number: 1 }), buildDay({ id: 6, day_number: 2 })],+ assignments: { '5': [buildAssignment({ id: 12, day_id: 5, order_index: 1, place: stay, accommodation_id: 7 })] },+ reservations: [buildReservation({ id: 9, type: 'hotel', title: 'Booking 4711', accommodation_id: 7 })],+ })+ const remove = vi.spyOn(accommodationsApi, 'delete').mockResolvedValue({} as never)+ const { result } = await renderRoadtrip()+ editingNight(result)++ await act(async () => { await result.current.saveStopDraft({ stopType: null, dwellMinutes: 45 }) })++ // Nothing has been written, and the popup is still open behind the question.+ expect(remove).not.toHaveBeenCalled()+ expect(actions.updatePlace).not.toHaveBeenCalled()+ expect(result.current.stopDraft).not.toBeNull()+ expect(result.current.stayRelease).toEqual({+ stop: { stopType: null, dwellMinutes: 45 },+ name: 'Hotel Fjord',+ booking: 'Booking 4711',+ })++ // A no leaves the traveller where they were.+ act(() => { result.current.setStayRelease(null) })+ expect(result.current.stopDraft).not.toBeNull()+ expect(remove).not.toHaveBeenCalled()++ // A yes is the very save that was asked for.+ await act(async () => { await result.current.saveStopDraft({ stopType: null, dwellMinutes: 45 }) })+ await act(async () => { await result.current.confirmStayRelease() })++ expect(actions.updatePlace).toHaveBeenCalledWith(42, 102, { stop_type: null, duration_minutes: 45 })+ expect(remove).toHaveBeenCalledWith(42, 7, { keepStop: true })+ expect(result.current.stayRelease).toBeNull()+ expect(result.current.stopDraft).toBeNull()+ })++ it('FE-TP-ROAD-105: a night without a booking of its own asks too, and names none', async () => {+ const stay = hotel()+ seedTrip({+ places: [stay],+ days: [buildDay({ id: 5, day_number: 1 }), buildDay({ id: 6, day_number: 2 })],+ assignments: { '5': [buildAssignment({ id: 12, day_id: 5, order_index: 1, place: stay, accommodation_id: 7 })] },+ })+ vi.mocked(accommodationRepo.list).mockResolvedValue({+ accommodations: [{ id: 7, trip_id: 42, place_id: 102, start_day_id: 5, end_day_id: 6, reservation_title: null }],+ } as never)+ const remove = vi.spyOn(accommodationsApi, 'delete').mockResolvedValue({} as never)+ const { result } = await renderRoadtrip()+ await waitFor(() => expect(result.current.tripAccommodations).toHaveLength(1))+ editingNight(result)++ await act(async () => { await result.current.saveStopDraft({ stopType: null, dwellMinutes: 20 }) })++ expect(remove).not.toHaveBeenCalled()+ expect(result.current.stayRelease).toMatchObject({ name: 'Hotel Fjord', booking: null })+ })++ it('FE-TP-ROAD-106: a check-in moved in the popup folds the re-seated night into the day', async () => {+ // The server seats the night by its check-in and answers with the moved stop. The+ // socket skips the session that asked, so this answer is the only way the writer's+ // own rail learns the new order before a reload.+ const stay = hotel()+ const museum = buildPlace({ id: 101, name: 'Museum', lat: 60.4, lng: 5.3 })+ const dinner = buildPlace({ id: 103, name: 'Dinner', lat: 60.41, lng: 5.31 })+ const night = buildAssignment({ id: 12, day_id: 5, order_index: 1, place: stay, accommodation_id: 7 })+ seedTrip({+ places: [museum, stay, dinner],+ days: [buildDay({ id: 5, day_number: 1 }), buildDay({ id: 6, day_number: 2 })],+ assignments: { '5': [+ buildAssignment({ id: 11, day_id: 5, order_index: 0, place: museum }),+ night,+ buildAssignment({ id: 13, day_id: 5, order_index: 2, place: dinner }),+ ] },+ })+ const update = vi.spyOn(accommodationsApi, 'update').mockResolvedValue({+ accommodation: { id: 7 },+ movedAssignment: { assignment: { ...night, order_index: 2 }, oldDayId: 5 },+ } as never)+ const { result } = await renderRoadtrip()+ editingNight(result)++ await act(async () => {+ await result.current.saveStopDraftAsNight({ endDayId: 6, checkIn: '20:00', checkOut: '' })+ })++ expect(update).toHaveBeenCalledWith(42, 7, { place_id: 102, start_day_id: 5, end_day_id: 6, check_in: '20:00', check_out: null })+ expect(useTripStore.getState().assignments['5'].find(a => a.id === 12)?.order_index).toBe(2)+ // The neighbours were renumbered as well, and the answer names only the night.+ expect(actions.refreshDays).toHaveBeenCalledWith(42)+ expect(result.current.stopDraft).toBeNull()+ })+})++describe('useTripPlanner road trip: a hit handed to the full form', () => {+ it('FE-TP-ROAD-107: saving it through the form re-anchors the vias the way the popup does', async () => {+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 })] })+ rt.corridor.day = { dayId: 5, dayNumber: 1 }+ rt.corridor.insertIndexFor.mockReturnValue(1)+ rt.routes.days = [{+ dayId: 5,+ dayNumber: 1,+ stops: [{ lat: 53.55, lng: 9.99 }, { lat: 53.0, lng: 11.5 }, { lat: 52.52, lng: 13.4 }],+ geometry: [[53.55, 9.99], [53.0, 11.5], [52.52, 13.4]],+ }]+ // On the second leg, behind the stop the hit goes in front of.+ rt.vias.byDay = { 5: [via(11, 5, 1, 0, 52.8, 12.2)] }+ const { result } = await renderRoadtrip()++ act(() => { result.current.handlePoiClick(poi({ lat: 53.2, lng: 10.7 }) as never) })+ act(() => { result.current.stopDraftToForm({ stopType: 'fuel', dwellMinutes: 10 }) })+ await act(async () => { await result.current.handleSavePlace({ name: 'Rasthof', lat: 53.2, lng: 10.7 }) })++ expect(actions.assignPlaceToDay).toHaveBeenCalledWith(42, 5, 900, 1)+ // Left alone the via keeps index 1 and is redrawn onto the leg the new stop took.+ expect(rt.vias.reanchor).toHaveBeenCalledWith(5, { vias: [{ id: 11, after_order_index: 2 }], remove: [] })+ const assigned = actions.assignPlaceToDay.mock.invocationCallOrder[0] ?? 0+ const corrected = rt.vias.reanchor.mock.invocationCallOrder[0] ?? 0+ expect(assigned).toBeLessThan(corrected)+ })++ it('FE-TP-ROAD-108: the position dies with the form, so the next add from a day goes to its end', async () => {+ seedTrip({ days: [buildDay({ id: 5, day_number: 1 }), buildDay({ id: 6, day_number: 2 })] })+ rt.corridor.day = { dayId: 5, dayNumber: 1 }+ rt.corridor.insertIndexFor.mockReturnValue(2)+ const { result } = await renderRoadtrip()++ act(() => { result.current.handlePoiClick(poi() as never) })+ act(() => { result.current.stopDraftToForm() })+ expect(result.current.placeFormDayId).toBe(5)+ // Closed unsaved, then opened again from another day's own "add place".+ act(() => { result.current.setShowPlaceForm(false) })+ act(() => { result.current.setPlaceFormDayId(6); result.current.setShowPlaceForm(true) })+ await act(async () => { await result.current.handleSavePlace({ name: 'Museum' }) })++ expect(actions.assignPlaceToDay).toHaveBeenCalledWith(42, 6, 900, null)+ })+})diff --git a/client/src/pages/tripPlanner/useTripPlanner.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.test.tsxindex 843ae9e38..eb3037fd5 100644--- a/client/src/pages/tripPlanner/useTripPlanner.test.tsx+++ b/client/src/pages/tripPlanner/useTripPlanner.test.tsx@@ -1,7 +1,8 @@-// FE-TP-HOOK-001 to FE-TP-HOOK-115+// FE-TP-HOOK-001 to FE-TP-HOOK-119import React from 'react'import { renderHook, act, waitFor } from '@testing-library/react'import { TranslationProvider } from '../../i18n/TranslationContext'+import { useTranslation } from '../../i18n'import { useTripPlanner } from './useTripPlanner'import { useTripStore, type TripStoreState } from '../../store/tripStore'import { useAuthStore } from '../../store/authStore'@@ -755,6 +756,31 @@ describe('useTripPlanner — map derivations', () => {expect(result.current.dayPlaces).toEqual([])})+ it('FE-TP-HOOK-031c: a service stop on the selected day takes no number on the map', async () => {+ const hamburg = geo(1)+ const pump = geo(2, { stop_type: 'fuel' })+ const berlin = geo(3)+ seedTrip({+ places: [hamburg, pump, berlin],+ selectedDayId: 7,+ assignments: {+ '7': [+ buildAssignment({ id: 10, day_id: 7, place: hamburg, order_index: 0 }),+ buildAssignment({ id: 11, day_id: 7, place: pump, order_index: 1 }),+ buildAssignment({ id: 12, day_id: 7, place: berlin, order_index: 2 }),+ ],+ },+ })++ const { result } = await renderPlanner()++ // The pump is drawn without a badge and the rail gives it no number, so the stop+ // after it is the second, not the third. The pin and the rail have to agree.+ expect(result.current.dayOrderMap).toEqual({ 1: [1], 3: [2] })+ // Still on the map: what is skipped is the number, not the stop.+ expect(result.current.dayPlaces).toHaveLength(3)+ })+it('FE-TP-HOOK-032: without a selected day both day derivations stay empty', async () => {seedTrip({ places: [geo(1)] })@@ -1258,6 +1284,56 @@ describe('useTripPlanner — place CRUD', () => {expect(toasts.some(t => t.message === 'nope')).toBe(true)})+ it('FE-TP-HOOK-118: the delete question names the booked night, its booking and the expense before the yes', async () => {+ // The server takes the night down with the place, and the booking and its+ // expense with the night. The question only named the place, so a traveller+ // deleting a hotel learnt about the rest from the costs total afterwards.+ const hotel = buildPlace({ id: 1, name: 'Hotel Fjord', lat: 60.39, lng: 5.32 })+ const cafe = buildPlace({ id: 2, name: 'Cafe', lat: 1, lng: 2 })+ seedTrip({+ places: [hotel, cafe],+ reservations: [buildReservation({ id: 9, type: 'hotel', title: 'Booking 4711', accommodation_id: 7 })],+ })+ vi.mocked(accommodationRepo.list).mockResolvedValue({+ accommodations: [{ id: 7, trip_id: 42, place_id: 1, start_day_id: 5, end_day_id: 6 }] as never,+ })++ const { result } = await renderPlanner()+ await waitFor(() => expect(result.current.tripAccommodations).toHaveLength(1))+ const { result: i18n } = renderHook(() => useTranslation(), { wrapper })++ act(() => { result.current.handleDeletePlace(1) })+ expect(result.current.deletePlaceNote).toBe(+ i18n.current.t('trip.confirm.deletePlaceBooked', { name: 'Hotel Fjord', booking: 'Booking 4711' }),+ )+ // Still a question: nothing has been written.+ expect(actions.deletePlace).not.toHaveBeenCalled()++ // A place without a night adds nothing to the question.+ act(() => { result.current.handleDeletePlace(2) })+ expect(result.current.deletePlaceNote).toBeNull()+ })++ it('FE-TP-HOOK-119: a bulk delete warns once any of the places carries a night, booking or not', async () => {+ const hotel = buildPlace({ id: 1, name: 'Hotel Fjord', lat: 60.39, lng: 5.32 })+ const cafe = buildPlace({ id: 2, name: 'Cafe', lat: 1, lng: 2 })+ seedTrip({ places: [hotel, cafe] })+ vi.mocked(accommodationRepo.list).mockResolvedValue({+ accommodations: [{ id: 7, trip_id: 42, place_id: 1, start_day_id: 5, end_day_id: 6 }] as never,+ })++ const { result } = await renderPlanner()+ await waitFor(() => expect(result.current.tripAccommodations).toHaveLength(1))+ const { result: i18n } = renderHook(() => useTranslation(), { wrapper })++ // A night without a partner booking still goes with the place, so it is still named.+ act(() => { result.current.setDeletePlaceIds([2, 1]) })+ expect(result.current.deletePlacesNote).toBe(i18n.current.t('trip.confirm.deletePlaceNight', { name: 'Hotel Fjord' }))++ act(() => { result.current.setDeletePlaceIds([2]) })+ expect(result.current.deletePlacesNote).toBeNull()+ })+it('FE-TP-HOOK-061: a bulk category change restores each previous category group on undo', async () => {seedTrip({places: [diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.tsindex 21937a0be..f03cd3909 100644--- a/client/src/pages/tripPlanner/useTripPlanner.ts+++ b/client/src/pages/tripPlanner/useTripPlanner.ts@@ -309,6 +309,14 @@ export function useTripPlanner() {* Null means the old behaviour: the server appends it at the end.*/const [placeFormPosition, setPlaceFormPosition] = useState<number | null>(null)+ // The position belongs to the form it was opened with and to nothing after it. The+ // day-scoped openers set the day, the form's close clears the coordinates, but the+ // position is written by one opener and read by every save, so a stop handed to the+ // form from the corridor popup once left the next add from any day landing at that+ // same index. Tied to the form being open, the only time it means anything.+ useEffect(() => {+ if (!showPlaceForm) setPlaceFormPosition(null)+ }, [showPlaceForm])/*** Whether the open place form is asking for a service stop on the drive.*@@ -333,6 +341,20 @@ export function useTripPlanner() {* instead, and the form stays one click away behind "more details".*/const [stopDraft, setStopDraft] = useState<RoadtripStopDraft | null>(null)+ /**+ * A booked night the popup was asked to turn into a pause, waiting for a yes.+ *+ * The switch in the popup reads like a change of stop kind, but the night is a+ * booking row, and the server takes the reservation and the expense written against+ * it down with that row. It is the one write the popup can make that nothing brings+ * back, so it is the one that asks first. The name and the booking title are read+ * once, here, so the dialog does not have to know where either lives.+ */+ const [stayRelease, setStayRelease] = useState<{+ stop: { stopType: RoadtripStopType | null; dwellMinutes: number }+ name: string+ booking: string | null+ } | null>(null)const [reservationModalDayId, setReservationModalDayId] = useState<number | null>(null)// The bottom-nav "+" opens the new-place form via ?create=place.@@ -475,6 +497,38 @@ export function useTripPlanner() {const mobilePlacesScrollTopRef = useRef<number>(0)const [deletePlaceId, setDeletePlaceId] = useState<number | null>(null)const [deletePlaceIds, setDeletePlaceIds] = useState<number[] | null>(null)+ /**+ * The sentence the delete question adds when a night is booked at one of the places.+ *+ * The server takes a booked night down with its place, and with the night the+ * booking made for it and the expense written against that booking. The question+ * itself only names the place, and those are the rows the traveller least expects+ * to lose, so the dialog says so before the yes. The expense list is loaded with+ * the costs tab, not here, so the sentence speaks of any expense rather than+ * counting them. Null when nothing beyond the place is at stake.+ */+ const bookedNightsNote = useCallback((placeIds: number[]): string | null => {+ const stays = tripAccommodations.filter(stay => stay.place_id != null && placeIds.includes(stay.place_id))+ if (stays.length === 0) return null+ const names = [...new Set(stays.map(stay => allPlaces.find(p => p.id === stay.place_id)?.name ?? stay.place_name ?? ''))]+ .filter(Boolean)+ const bookings = stays+ .map(stay => reservations.find(r => r.accommodation_id != null && Number(r.accommodation_id) === stay.id)?.title+ ?? stay.reservation_title ?? null)+ .filter((title): title is string => !!title)+ const name = names.join(', ')+ return bookings.length > 0+ ? t('trip.confirm.deletePlaceBooked', { name, booking: bookings.join(', ') })+ : t('trip.confirm.deletePlaceNight', { name })+ }, [tripAccommodations, allPlaces, reservations, t])+ const deletePlaceNote = useMemo(+ () => (deletePlaceId ? bookedNightsNote([deletePlaceId]) : null),+ [deletePlaceId, bookedNightsNote],+ )+ const deletePlacesNote = useMemo(+ () => (deletePlaceIds?.length ? bookedNightsNote(deletePlaceIds) : null),+ [deletePlaceIds, bookedNightsNote],+ )useEffect(() => {if (!trip) return@@ -885,16 +939,38 @@ export function useTripPlanner() {** This is the index space `after_order_index` lives in: sorted by `order_index`, and* filtered to the rows that have coordinates, because a place the map cannot put- * anywhere is not a point the router is given. Built from `assignments` rather than- * from `roadtripRoutes` so it also answers for a day with one stop or none — exactly- * the day a stop gets pushed onto when a leg turns out too long.+ * anywhere is not a point the router is given. Built from the STORED list, the same+ * one the routing round and the server count over. The day list read as a plan+ * hides the stop a lodging booking put on the day and, behind the switch, the+ * service stops; the handlers that correct a day's vias run in that mode too, and a+ * plan measured on the shorter list deleted a via behind a hidden hotel or pinned+ * it to a leg nobody drew. Built from the list rather than from `roadtripRoutes` so+ * it also answers for a day with one stop or none, which is exactly the day a stop+ * gets pushed onto when a leg turns out too long.*/const roadtripStopsOf = useCallback((dayId: number) =>- (assignments[String(dayId)] ?? [])+ (storedAssignments[String(dayId)] ?? []).slice().sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0)).filter(a => typeof a.place?.lat === 'number' && typeof a.place?.lng === 'number'),- [assignments])+ [storedAssignments])++ /**+ * Where a place dropped at `position` in a day's row list lands among the stops the+ * road trip counts.+ *+ * The day plan hands over a row index and the store splices the new row in at that+ * index, so the stop's place in the chain is the number of routable rows ahead of+ * it, not the index itself: a row without coordinates is never a stop.+ */+ const roadtripIndexOf = useCallback((dayId: number, position: number) =>+ (storedAssignments[String(dayId)] ?? [])+ .slice()+ .sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0))+ .slice(0, Math.max(0, position))+ .filter(a => typeof a.place?.lat === 'number' && typeof a.place?.lng === 'number')+ .length,+ [storedAssignments])/*** Which half of a split leg a via belongs to, measured on the road actually driven.@@ -1035,16 +1111,30 @@ export function useTripPlanner() {}}, [tripId, trip, can, roadtripPreferencesState.ready, toast, t])- const saveStopDraft = useCallback(async ({ stopType, dwellMinutes }: { stopType: RoadtripStopType | null; dwellMinutes: number }) => {+ const saveStopDraft = useCallback(async (+ { stopType, dwellMinutes }: { stopType: RoadtripStopType | null; dwellMinutes: number },+ { releaseStay = false }: { releaseStay?: boolean } = {},+ ) => {if (!stopDraft) returnconst { poi, dayId, position } = stopDraft+ const accommodationId = stopDraft.editing?.accommodationId+ // Turning a booked night into a pause deletes the booking, and with it the+ // reservation and the expense the server keeps against it. The popup stays open+ // behind the question, so a no leaves the traveller exactly where they were.+ if (accommodationId && !releaseStay) {+ const stay = tripAccommodations.find(s => s.id === accommodationId)+ const booking = reservations.find(r => r.accommodation_id != null && Number(r.accommodation_id) === accommodationId)?.title+ ?? stay?.reservation_title ?? null+ setStayRelease({ stop: { stopType, dwellMinutes }, name: poi.name, booking })+ return+ }try {if (stopDraft.editing) {await tripActions.updatePlace(tripId, stopDraft.editing.placeId, { stop_type: stopType, duration_minutes: dwellMinutes })- if (stopDraft.editing.accommodationId) {+ if (accommodationId) {// The night is what was switched off, not the stop: it stays where it is// in the drive and becomes an ordinary pause.- applyStayStops(await accommodationsApi.delete(tripId, stopDraft.editing.accommodationId, { keepStop: true }))+ applyStayStops(await accommodationsApi.delete(tripId, accommodationId, { keepStop: true }))await loadAccommodations()}updateRouteForDay(dayId)@@ -1083,7 +1173,14 @@ export function useTripPlanner() {} catch (err: unknown) {toast.error(err instanceof Error ? err.message : t('common.unknownError'))}- }, [stopDraft, tripId, tripActions, updateRouteForDay, toast, t, roadtripVias, viaLiesBefore, loadAccommodations])+ }, [stopDraft, tripId, tripActions, updateRouteForDay, toast, t, roadtripVias, viaLiesBefore, loadAccommodations, tripAccommodations, reservations])++ /** The yes to the question above: the same save, this time allowed to drop the night. */+ const confirmStayRelease = useCallback(async () => {+ const pending = stayRelease+ setStayRelease(null)+ if (pending) await saveStopDraft(pending.stop, { releaseStay: true })+ }, [stayRelease, saveStopDraft])const saveStopDraftAsNight = useCallback(async ({ endDayId, checkIn, checkOut }: {endDayId: number@@ -1095,8 +1192,17 @@ export function useTripPlanner() {try {if (stopDraft.editing) {const booking = { place_id: stopDraft.editing.placeId, start_day_id: dayId, end_day_id: endDayId, check_in: checkIn || null, check_out: checkOut || null }- if (stopDraft.editing.accommodationId) await accommodationsApi.update(tripId, stopDraft.editing.accommodationId, booking)- else await accommodationsApi.create(tripId, booking)+ // The answer carries the day stop the booking moved or added. The socket+ // deliberately skips the session that sent the request, so without folding+ // it in the one person whose rail still shows the night at its old place in+ // the chain is the one who just moved its check-in.+ const written = stopDraft.editing.accommodationId+ ? await accommodationsApi.update(tripId, stopDraft.editing.accommodationId, booking)+ : await accommodationsApi.create(tripId, booking)+ applyStayStops(written)+ // A night seated by a new check-in renumbers its neighbours as well, and the+ // answer names only the night. The day is read back whole rather than guessed.+ if (written?.movedAssignment) await tripActions.refreshDays(tripId)await tripActions.updatePlace(tripId, stopDraft.editing.placeId, { stop_type: poi.category === 'campsite' ? 'campsite' : 'hotel' })await loadAccommodations()updateRouteForDay(dayId)@@ -1917,12 +2023,15 @@ export function useTripPlanner() {// leg each via was drawn for. A via is stored as (day, after_order_index) and// that index is a POSITION in the day's stop list, so a stop dropped into the// middle of a routed day pushes every via at or behind it onto the wrong leg and- // the drawn road runs forward, doubles back and runs out again.- const plan = insert && typeof data.lat === 'number' && typeof data.lng === 'number'+ // the drawn road runs forward, doubles back and runs out again. Keyed on the+ // position rather than on the service-stop form: a corridor hit handed to the+ // full form carries its position too, and was the one way into the middle of a+ // day that left the vias where they were.+ const plan = position != null && typeof data.lat === 'number' && typeof data.lng === 'number'? reanchorAfterInsert(- roadtripVias.byDay[insert.dayId] ?? [],- insert.position,- viaLiesBefore(insert.dayId, { lat: data.lat, lng: data.lng }),+ roadtripVias.byDay[dayId] ?? [],+ position,+ viaLiesBefore(dayId, { lat: data.lat, lng: data.lng }),): nulltry {@@ -2108,7 +2217,8 @@ export function useTripPlanner() {// the correction — and the predicate decides which side of the new stop a// via falls on when it is dropped into the middle of a leg.const stopsBefore = roadtripStopsOf(target)- const insertAt = position === undefined ? stopsBefore.length : position+ // The position is a row index in the day list, the anchors count stops.+ const insertAt = position === undefined ? stopsBefore.length : roadtripIndexOf(target, position)const place = places.find(p => p.id === placeId)const plan = insertAt >= stopsBefore.length || typeof place?.lat !== 'number' || typeof place?.lng !== 'number'? null@@ -2130,7 +2240,7 @@ export function useTripPlanner() {})}} catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) }- }, [selectedDayId, tripId, toast, updateRouteForDay, pushUndo, t, places, roadtripVias, roadtripStopsOf, viaLiesBefore])+ }, [selectedDayId, tripId, toast, updateRouteForDay, pushUndo, t, places, roadtripVias, roadtripStopsOf, roadtripIndexOf, viaLiesBefore])const handleRemoveAssignment = useCallback(async (dayId: number, assignmentId: number) => {const state = useTripStore.getState()@@ -2442,16 +2552,21 @@ export function useTripPlanner() {? inspectorStay(roadtripRoutes.days, endDayStop, selectedPlace, can('place_edit', trip) ? editRoadtripStay : undefined): undefined- // Build placeId → order-number map from the selected day's assignments+ // Build placeId → order-number map from the selected day's assignments. A service+ // stop is passed over rather than counted: the map draws it without a badge and the+ // rail gives it no number, so a number spent on it left the pin after a fuel stop+ // wearing "3" where the rail said "2".const dayOrderMap = useMemo(() => {if (!selectedDayId) return {}const da = assignments[String(selectedDayId)] || []const sorted = [...da].sort((a, b) => a.order_index - b.order_index)const map = {}- sorted.forEach((a, i) => {- if (!a.place?.id) return+ let counted = 0+ sorted.forEach(a => {+ if (!a.place?.id || isServiceStopType(a.place.stop_type)) return+ counted += 1if (!map[a.place.id]) map[a.place.id] = []- map[a.place.id].push(i + 1)+ map[a.place.id].push(counted)})return map}, [selectedDayId, assignments])@@ -2497,6 +2612,7 @@ export function useTripPlanner() {prefillCoords, setPrefillCoords, editingAssignmentId, setEditingAssignmentId,placeFormDayId, setPlaceFormDayId, reservationModalDayId, setReservationModalDayId,stopDraft, setStopDraft, saveStopDraft, saveStopDraftAsNight, stopDraftToForm, stopDraftDuplicate, reorderRoadtripStop,+ stayRelease, setStayRelease, confirmStayRelease,setRoadtripStopKind,setRoadtripStopFill,roadtripEndsDayAt,@@ -2525,7 +2641,7 @@ export function useTripPlanner() {reservationPrefill, transportPrefill, importReviewActive, startImportReview, advanceImportReview,routeShown, setRouteShown, autoShowRoute, transitRoutesShown, routeProfile, setRouteProfile, routeVias, fitKey, setFitKey,mobileSidebarOpen, setMobileSidebarOpen, mobilePlanScrollTopRef, mobilePlacesScrollTopRef,- deletePlaceId, setDeletePlaceId, deletePlaceIds, setDeletePlaceIds,+ deletePlaceId, setDeletePlaceId, deletePlaceIds, setDeletePlaceIds, deletePlaceNote, deletePlacesNote,visibleConnections, toggleConnection, allConnectionsShown, toggleAllConnections, mapTransportDetail, setMapTransportDetail,isMobile, isTouch,expandedDayIds, setExpandedDayIds, mapPlaces,diff --git a/client/src/repo/roadtripHazardsRepo.test.ts b/client/src/repo/roadtripHazardsRepo.test.tsnew file mode 100644index 000000000..570ba735a--- /dev/null+++ b/client/src/repo/roadtripHazardsRepo.test.ts@@ -0,0 +1,61 @@+/**+ * FE-ROADTRIP-HAZARDREPO-001 to FE-ROADTRIP-HAZARDREPO-002: the one read behind+ * the hazard overlay.+ *+ * The server keeps the feed for ten minutes and rebuilds it on the first read+ * after that: the GDACS event list and then its polygons, each allowed 15 s.+ * At the shared 8 s the browser gave up on exactly that read, the overlay+ * reported the feed as unavailable, and nothing asked again for ten minutes,+ * by which time the cache had expired once more. These cases pin the wait the+ * read carries, that the caller's signal still cuts it short, and that the+ * answer is parsed rather than trusted.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { apiClient } from '../api/client'+import { roadtripHazardsRepo, ROADTRIP_HAZARDS_TIMEOUT_MS } from './roadtripHazardsRepo'++vi.mock('../api/client', () => ({ apiClient: { get: vi.fn() } }))++const FEED = {+ fetchedAt: '2026-09-14T10:00:00.000Z',+ hazards: [+ {+ id: 'dwd-1',+ source: 'DWD',+ title: 'Sturmboeen',+ description: 'Boeen bis 85 km/h',+ updatedAt: '2026-09-14T10:00:00.000Z',+ validUntil: null,+ url: 'https://www.dwd.de/warnungen',+ geometry: { type: 'Point', coordinates: [13.4, 52.5] },+ },+ ],+ sources: [+ { source: 'DWD', status: 'ok' },+ { source: 'GDACS', status: 'partial' },+ ],+}++beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(apiClient.get).mockResolvedValue({ data: FEED })+})++describe('roadtripHazardsRepo', () => {+ it('FE-ROADTRIP-HAZARDREPO-001: waits long enough for the server to rebuild the feed, on the caller signal', async () => {+ const signal = new AbortController().signal++ await roadtripHazardsRepo.read(7, signal)++ expect(apiClient.get).toHaveBeenCalledWith('/trips/7/roadtrip/hazards', { signal, timeout: ROADTRIP_HAZARDS_TIMEOUT_MS })+ // The event list and then the polygons, 15 s each, plus parsing.+ expect(ROADTRIP_HAZARDS_TIMEOUT_MS).toBeGreaterThanOrEqual(30_000)+ })++ it('FE-ROADTRIP-HAZARDREPO-002: parses the answer and refuses one that does not match the contract', async () => {+ expect(await roadtripHazardsRepo.read(7, new AbortController().signal)).toEqual(FEED)++ vi.mocked(apiClient.get).mockResolvedValue({ data: { fetchedAt: 'yesterday', hazards: [], sources: [] } })+ await expect(roadtripHazardsRepo.read(7, new AbortController().signal)).rejects.toThrow()+ })+})diff --git a/client/src/repo/roadtripHazardsRepo.ts b/client/src/repo/roadtripHazardsRepo.tsindex e7e72e88d..f7bcb0db6 100644--- a/client/src/repo/roadtripHazardsRepo.ts+++ b/client/src/repo/roadtripHazardsRepo.ts@@ -1,9 +1,22 @@import { roadtripHazardsSchema } from '@trek/shared'import { apiClient } from '../api/client'+/**+ * How long the browser waits for the hazard feed.+ *+ * The server keeps the feed for ten minutes and, once that is up, answers the+ * next request only after it has fetched DWD and GDACS afresh: the GDACS event+ * list and then up to twelve polygon lookups, each allowed 15 s. A cold read+ * takes nine to twenty seconds, so at the shared 8 s the browser gave up on+ * every first read after the cache expired, the map showed no warnings, and+ * the next attempt was ten minutes away although the server had the answer a+ * moment later. The bound is the sum of the server's own ceilings.+ */+export const ROADTRIP_HAZARDS_TIMEOUT_MS = 45_000+export const roadtripHazardsRepo = {async read(tripId: number, signal: AbortSignal) {- const fetched = await apiClient.get(`/trips/${tripId}/roadtrip/hazards`, { signal })+ const fetched = await apiClient.get(`/trips/${tripId}/roadtrip/hazards`, { signal, timeout: ROADTRIP_HAZARDS_TIMEOUT_MS })return roadtripHazardsSchema.parse(fetched.data)},}diff --git a/client/src/store/slices/assignmentsSlice.ts b/client/src/store/slices/assignmentsSlice.tsindex 26a4d3183..2db8a5031 100644--- a/client/src/store/slices/assignmentsSlice.ts+++ b/client/src/store/slices/assignmentsSlice.ts@@ -66,7 +66,12 @@ export const createAssignmentsSlice = (set: SetState, get: GetState): Assignmentif (!place) returnconst tempId = Date.now() * -1- const current = [...(state.assignments[String(dayId)] || [])]+ // Sorted first, as moveAssignment does: the position is an index in the day as+ // it is shown, and that day is sorted by order_index. The stored list is not+ // always, a stop that arrived over the socket is appended wherever its+ // order_index says it belongs, so a splice into the raw list landed the new+ // row behind the wrong neighbour and the reorder that follows wrote that order.+ const current = (state.assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index)const insertIdx = position != null ? position : current.lengthconst tempAssignment: Assignment = {id: tempId,diff --git a/client/src/store/stayStops.ts b/client/src/store/stayStops.tsindex 6a0204478..d3b3da207 100644--- a/client/src/store/stayStops.ts+++ b/client/src/store/stayStops.ts@@ -16,9 +16,11 @@ export interface StayStopsResult {** Booking a night also puts the place on its check-in day, because that stop is* what the road trip routes and the map draws. The server announces it over the- * socket like any other assignment, but the socket deliberately skips the session- * that sent the request (X-Socket-Id), so without this the one person who cannot- * see their new stop is the one who just booked it. Goes through the same applier+ * socket like any other assignment, and unlike the booking events it does not+ * skip the session that sent the request: the stop and the order it was seated+ * into arrive there together. The answer carries the stop as well, for a session+ * whose socket is down at that moment, and applying it a second time is harmless+ * because the store drops a stop it already holds. Goes through the same applier* the socket uses, so the write-through to IndexedDB happens either way.*/export function applyStayStops(result: StayStopsResult | null | undefined): void {diff --git a/client/src/store/systemNoticeStore.ts b/client/src/store/systemNoticeStore.tsindex 70c095731..614c21c29 100644--- a/client/src/store/systemNoticeStore.ts+++ b/client/src/store/systemNoticeStore.ts@@ -25,7 +25,12 @@ export const useSystemNoticeStore = create<SystemNoticeState>()((set, get) => ({if (get().fetching || get().loaded) return;set({ fetching: true });try {- const res = await axios.get('/system-notices/active');+ // Names the layouts this bundle can draw. The server holds the release notice+ // back from a bundle that does not say so: after an update the service worker+ // serves the previous bundle until the new one is installed, and that bundle+ // would draw the release notice as bare keys and let the reader dismiss it for+ // good. It gets the notice after the reload, from this very line.+ const res = await axios.get('/system-notices/active', { params: { supports: 'release' } });const notices = parseInDev(systemNoticeDtoSchema.array(), res.data, 'systemNotices.fetch');set({ notices, loaded: true, fetching: false });} catch (err) {diff --git a/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx b/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsxindex c369aacb8..970645c3e 100644--- a/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx+++ b/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx@@ -1,4 +1,4 @@-// FE-MOB-AADD-001 to FE-MOB-AADD-031+// FE-MOB-AADD-001 to FE-MOB-AADD-032import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import userEvent from '@testing-library/user-event';import { delay, http, HttpResponse } from 'msw';@@ -242,6 +242,23 @@ describe('MAdminAddonManager', () => {expect(onToggleCollabFeature).toHaveBeenCalledWith('polls');});+ it('FE-MOB-AADD-032: the links row describes the feature, not an empty list', async () => {+ // The line under the row is its description. The links tab's empty state+ // read as a status here, and a status that never changes reads as a+ // broken feature.+ server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));+ render(+ <MAdminAddonManager+ collabFeatures={{ chat: true, notes: true, links: true, polls: true, whatsnext: true }}+ onToggleCollabFeature={vi.fn()}+ />,+ );++ await screen.findByText('Links');+ expect(screen.getByText('Shared links and bookmarks')).toBeInTheDocument();+ expect(screen.queryByText('No shared links yet')).not.toBeInTheDocument();+ });+it('FE-MOB-AADD-013: collab sub-features stay hidden without the handler props', async () => {server.use(addonsRoute([buildAddon({ id: 'collab', name: 'Collab', enabled: true })]));render(<MAdminAddonManager />);diff --git a/client/tests/unit/mobile/trip/MCollabChat.test.tsx b/client/tests/unit/mobile/trip/MCollabChat.test.tsxindex 752c505d1..8b7553dee 100644--- a/client/tests/unit/mobile/trip/MCollabChat.test.tsx+++ b/client/tests/unit/mobile/trip/MCollabChat.test.tsx@@ -11,7 +11,7 @@ import { resetAllStores, seedStore } from '../../../helpers/store'import { server } from '../../../helpers/msw/server'import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render'-// FE-MOB-CCHAT-001 to FE-MOB-CCHAT-031+// FE-MOB-CCHAT-001 to FE-MOB-CCHAT-033const ME = 7@@ -264,6 +264,39 @@ describe('MCollabChat', () => {expect(input).toHaveValue('no network')})+ // The strip shows the four pictures that will go out; the two the cap turned+ // away vanished without a word, and the sender believed all six were sent.+ it('FE-MOB-CCHAT-032: picking more images than fit on one message says so, and says it once', async () => {+ serveMessages([])+ let minted = 0+ vi.spyOn(URL, 'createObjectURL').mockImplementation(() => `blob:mock/${++minted}`)+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})+ const { planner } = await renderChat()++ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ const files = Array.from({ length: 6 }, (_, i) => new File([new Uint8Array(8)], `${i}.png`, { type: 'image/png' }))+ fireEvent.change(input, { target: { files } })++ await waitFor(() => expect(document.querySelectorAll('img[src^="blob:mock/"]')).toHaveLength(4))+ expect(planner.toast.error).toHaveBeenCalledTimes(1)+ expect(planner.toast.error).toHaveBeenCalledWith('collab.chat.imageLimit:4')+ expect(planner.toast.error).not.toHaveBeenCalledWith('collab.chat.imageRejected')+ })++ it('FE-MOB-CCHAT-033: a file of the wrong kind is still turned away with the type message', async () => {+ serveMessages([])+ vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:mock/1')+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})+ const { planner } = await renderChat()++ const input = document.querySelector('input[type="file"]') as HTMLInputElement+ fireEvent.change(input, { target: { files: [new File([new Uint8Array(8)], 'notes.pdf', { type: 'application/pdf' })] } })++ await waitFor(() => expect(planner.toast.error).toHaveBeenCalledWith('collab.chat.imageRejected'))+ expect(planner.toast.error).toHaveBeenCalledTimes(1)+ expect(document.querySelectorAll('img[src^="blob:mock/"]')).toHaveLength(0)+ })+it('FE-MOB-CCHAT-015: auto-grows the composer and caps it at 100px', async () => {serveMessages([])await renderChat()diff --git a/client/tests/unit/mobile/trip/MRoadtripRows.test.tsx b/client/tests/unit/mobile/trip/MRoadtripRows.test.tsxindex 567f1bee2..82e9adce8 100644--- a/client/tests/unit/mobile/trip/MRoadtripRows.test.tsx+++ b/client/tests/unit/mobile/trip/MRoadtripRows.test.tsx@@ -9,7 +9,7 @@ import type { TranslationFn } from '../../../../src/types'import type { RefuelSearch } from '../../../../src/components/Roadtrip/useRefuelSearch'import type { RefuelCandidate } from '../../../../src/components/Roadtrip/refuelSuggestion'-// FE-MOB-RTROW-001 to FE-MOB-RTROW-048+// FE-MOB-RTROW-001 to FE-MOB-RTROW-049// Same echo strategy as tests/helpers/mobileTrip: assertions stay on keys, not copy.const t: TranslationFn = (key, params) =>@@ -640,4 +640,13 @@ describe('RtSpillRow', () => {expect(screen.getByText('roadtrip.spill.title:1')).toBeInTheDocument()expect(screen.queryByText(/roadtrip\.spill\.departs/)).toBeNull()})++ it('FE-MOB-RTROW-049: the departure follows the reader twelve hour setting like every other clock in the chain', () => {+ // The band sits directly above stops that print their clocks through the same+ // setting, so a raw 21:30 over a 9:45 PM is two clocks on one screen.+ render(<RtSpillRow fromDayNumber={1} departs="21:30" chrome={{ ...chrome, is12h: true }} />)++ expect(screen.getByText('roadtrip.spill.departs:9:30 PM')).toBeInTheDocument()+ expect(screen.queryByText('roadtrip.spill.departs:21:30')).toBeNull()+ })})diff --git a/client/tests/unit/mobile/trip/MRoadtripTab.test.tsx b/client/tests/unit/mobile/trip/MRoadtripTab.test.tsxindex b755b89a3..bffb5965d 100644--- a/client/tests/unit/mobile/trip/MRoadtripTab.test.tsx+++ b/client/tests/unit/mobile/trip/MRoadtripTab.test.tsx@@ -9,7 +9,7 @@ import type { Day, Place } from '../../../../src/types'import type { RoadtripDay, RoadtripRoutes, RouteSegment } from '@trek/shared/roadtrip'import type { LegAlternatives } from '../../../../src/components/Roadtrip/useRouteAlternatives'-// FE-MOB-RTTAB-001 to FE-MOB-RTTAB-050+// FE-MOB-RTTAB-001 to FE-MOB-RTTAB-053//// The stage bar pictures the place its day ends at. It reads that place out of the trip// store rather than the planner, the unfiltered list, so the picture tests seed the store.@@ -284,6 +284,32 @@ describe('MRoadtripTab', () => {expect(screen.queryByText('mobileTrip.rtPlanOnDesktop')).toBeNull()})+ it('FE-MOB-RTTAB-053: with the drive routed and no day picked it asks for a day, not for a route', () => {+ // The map's whole-trip view deselects the day and the list switch leaves it so.+ // The header keeps printing the drive's distance meanwhile, so "no route yet"+ // here contradicted the line right above it.+ renderTab(planner({ selectedDayId: null }))++ expect(screen.getByText('mobileTrip.rtNoDay')).toBeInTheDocument()+ expect(screen.getByText('mobileTrip.rtNoDayHint')).toBeInTheDocument()+ expect(screen.queryByText('roadtrip.empty.title')).toBeNull()+ expect(screen.queryByText('mobileTrip.rtPlanOnDesktop')).toBeNull()+ expect(screen.queryByText('mobileTrip.rtStart')).toBeNull()++ // A picked day the routing has nothing for is still the empty stage: that one is+ // about the day, and the sentence about two places is the right one there.+ const unrouted = render(<MRoadtripTab planner={planner({ selectedDayId: 1 })} shell={buildShell()} tab="roadtrip" />)+ expect(within(unrouted.container).getByText('roadtrip.empty.title')).toBeInTheDocument()+ expect(within(unrouted.container).queryByText('mobileTrip.rtNoDay')).toBeNull()++ // And while the round is still running, no day picked is still the partial hint.+ const running = render(+ <MRoadtripTab planner={planner({ selectedDayId: null, roadtripRoutes: routes({ loading: true }) })} shell={buildShell()} tab="roadtrip" />,+ )+ expect(within(running.container).getByText('roadtrip.summary.partial')).toBeInTheDocument()+ expect(within(running.container).queryByText('mobileTrip.rtNoDay')).toBeNull()+ })+it('FE-MOB-RTTAB-010: draws no day colour dot in the head card, even with the day colours on', () => {// The colour keys the day's line on the map, which lies under the list on this half,// so a dot here had nothing on screen to explain it.diff --git a/client/tests/unit/mobile/trip/MTripSheets.test.tsx b/client/tests/unit/mobile/trip/MTripSheets.test.tsxindex 164cb638e..735267a8c 100644--- a/client/tests/unit/mobile/trip/MTripSheets.test.tsx+++ b/client/tests/unit/mobile/trip/MTripSheets.test.tsx@@ -11,7 +11,7 @@ import { buildPlanner, buildShell } from '../../../helpers/mobileTrip'import { resetAllStores, seedStore } from '../../../helpers/store'import { fireEvent, render, screen, waitFor } from '../../../helpers/render'-// FE-MOB-SHOST-001 to FE-MOB-SHOST-028+// FE-MOB-SHOST-001 to FE-MOB-SHOST-029//// Every child sheet is stubbed: this file is about the host — which sheet is// mounted for which shell.sheet id, and how the host's own callbacks wire the@@ -425,6 +425,18 @@ describe('MTripSheets', () => {expect(planner.setDeletePlaceId).toHaveBeenCalledWith(null)})+ it('FE-MOB-SHOST-029: a night booked at the place is said before the yes, and only then', () => {+ // The server takes the night down with the place, and the booking and the+ // expense with the night. The planner builds the sentence; the sheet has to+ // show it under the question.+ const note = 'The booking at Hotel Okura and its expense go with it.'+ renderHost({ deletePlaceId: 101, deletePlaceNote: note })++ const confirm = screen.getByTestId('stub-confirm')+ expect(confirm).toHaveTextContent('trip.confirm.deletePlace')+ expect(screen.getByText(note)).toBeInTheDocument()+ })+it('FE-MOB-SHOST-026: cancelling the confirm only disarms the flag', () => {const { planner } = renderHost({ deletePlaceId: 101 })fireEvent.click(screen.getByText('cancel delete'))diff --git a/client/tests/unit/slices/assignmentsSlice.test.ts b/client/tests/unit/slices/assignmentsSlice.test.tsindex c8e9dc12b..4a3c62cca 100644--- a/client/tests/unit/slices/assignmentsSlice.test.ts+++ b/client/tests/unit/slices/assignmentsSlice.test.ts@@ -173,6 +173,35 @@ describe('assignmentsSlice', () => {expect(useTripStore.getState().assignments['1'].map(a => a.id)).toEqual([999, 1]);});+ it('FE-ASSIGN-023: the position counts in the day as sorted, not as the store happens to hold it', async () => {+ // A row that came in over the socket sits at the end of the stored list whatever+ // its order_index says, so the day the planner shows and the list the splice+ // ran on disagreed and the new row landed behind the wrong neighbour.+ const place = buildPlace({ id: 10, trip_id: 1 });+ const later = buildAssignment({ id: 2, day_id: 1, order_index: 1 });+ const first = buildAssignment({ id: 1, day_id: 1, order_index: 0 });+ seedStore(useTripStore, { places: [place], assignments: { '1': [later, first] } });++ let reorderBody: number[] | undefined;+ server.use(+ http.post('/api/trips/1/days/1/assignments', () =>+ HttpResponse.json({ assignment: buildAssignment({ id: 999, day_id: 1, place_id: 10, place, order_index: 7 }) })+ ),+ http.put('/api/trips/1/days/1/assignments/reorder', async ({ request }) => {+ const body = await request.json() as { orderedIds: number[] };+ reorderBody = body.orderedIds;+ return HttpResponse.json({ success: true });+ }),+ );++ await useTripStore.getState().assignPlaceToDay(1, 1, 10, 1);++ const items = useTripStore.getState().assignments['1'];+ expect(items.map(a => a.id)).toEqual([1, 999, 2]);+ expect(items.map(a => a.order_index)).toEqual([0, 1, 2]);+ expect(reorderBody).toEqual([1, 999, 2]);+ });+it('FE-ASSIGN-012: no reorder call when the day holds no server-side ids', async () => {const place = buildPlace({ id: 10, trip_id: 1 });seedStore(useTripStore, { places: [place], assignments: { '1': [] } });diff --git a/client/tests/unit/stores/systemNoticeStore.test.ts b/client/tests/unit/stores/systemNoticeStore.test.tsnew file mode 100644index 000000000..0e96965a0--- /dev/null+++ b/client/tests/unit/stores/systemNoticeStore.test.ts@@ -0,0 +1,71 @@+import { describe, it, expect, beforeEach } from 'vitest';+import { http, HttpResponse } from 'msw';+import { server } from '../../helpers/msw/server';+import { useSystemNoticeStore } from '../../../src/store/systemNoticeStore';++const initial = useSystemNoticeStore.getState();++beforeEach(() => {+ useSystemNoticeStore.setState(initial, true);+});++describe('systemNoticeStore', () => {+ // After an update the service worker serves the previous bundle until the new one is+ // installed. The server only hands the release notice to a bundle that announces it+ // can draw the release layout, so an older bundle never shows it as bare keys and+ // never dismisses it for good. This bundle has to announce it on every fetch.+ describe('FE-SYSNOTICE-001: fetch() announces the layouts this bundle can draw', () => {+ it('sends supports=release with the active-notices request', async () => {+ const urls: URL[] = [];+ server.use(+ http.get('/api/system-notices/active', ({ request }) => {+ urls.push(new URL(request.url));+ return HttpResponse.json([]);+ }),+ );++ await useSystemNoticeStore.getState().fetch();++ expect(urls).toHaveLength(1);+ expect(urls[0].searchParams.get('supports')).toBe('release');+ expect(useSystemNoticeStore.getState().loaded).toBe(true);+ });++ it('keeps the notices the server returns, release layout included', async () => {+ const release = {+ id: 'release-notes', display: 'modal', severity: 'info', dismissible: true,+ titleKey: 'system_notice.release_notes.headline', bodyKey: 'system_notice.release_notes.intro',+ release: {+ version: '4.3.0',+ eyebrowKey: 'system_notice.release_notes.eyebrow',+ headlineKey: 'system_notice.release_notes.headline',+ introKey: 'system_notice.release_notes.intro',+ featuresLabelKey: 'system_notice.release_notes.features_label',+ features: [],+ note: {+ eyebrowKey: 'system_notice.release_notes.note_eyebrow',+ titleKey: 'system_notice.release_notes.note_title',+ bodyKey: 'system_notice.release_notes.note_body',+ promiseLabelKey: 'system_notice.release_notes.promise_label',+ promiseLeadKey: 'system_notice.release_notes.promise_lead',+ promiseTextKey: 'system_notice.release_notes.promise_text',+ bodyAfterKey: 'system_notice.release_notes.note_body_after',+ closingKey: 'system_notice.release_notes.note_closing',+ },+ supportLeadKey: 'system_notice.release_notes.support_lead',+ supportTextKey: 'system_notice.release_notes.support_text',+ },+ };+ server.use(+ http.get('/api/system-notices/active', () => HttpResponse.json([release])),+ );++ await useSystemNoticeStore.getState().fetch();++ const state = useSystemNoticeStore.getState();+ expect(state.loaded).toBe(true);+ expect(state.notices.map(n => n.id)).toEqual(['release-notes']);+ expect(state.notices[0].release?.version).toBe('4.3.0');+ });+ });+});diff --git a/docker-compose.yml b/docker-compose.ymlindex d2b3a1feb..980fbc0ae 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -53,6 +53,11 @@ services:# - LLM_TIMEOUT_MS=900000 # Optional. Ceiling (ms) for one AI-parsing call before it is abandoned, applied to every provider and to the HTTP client underneath. Generous by default so heavier documents fit; lower it on a cloud provider to fail fast. Must be a whole number of milliseconds between 1 and 2147483647 — anything else stops the server at startup with the reason. (default: 900000)# - TREK_PLUGINS_IGNORE_TREK_RANGE=true # Optional. Lets plugins whose declared TREK version range predates this build, and plugins that declare none, be installed and activated anyway. Every gate warns instead of refusing; the plugin-API version gate and the Discover compatibility verdict stay hard. Off unless set. (default: off)# - UNSPLASH_ACCESS_KEY= # Optional. Unsplash Access Key for trip-cover / place-image search. Without one, TREK uses Unsplash's unauthenticated endpoint, which some datacenter/VPS IPs are blocked from (#1449). Free key at unsplash.com/developers. Can also be set per-admin in Admin > Settings; the env var overrides that.+# - TREK_PLACES_ENABLED=false # Optional. Place search (suggestions, full search, category buttons, Road trip search, import geocoding, offline downloads) asks the TREK Places API at https://places.liketrek.com by default, so the server makes outbound requests to that host. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing there. No switch in the admin panel on purpose: whether searches leave the instance is decided here. (default: true)+# - TREK_PLACES_URL=https://places.liketrek.com # Optional. Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com)+# - AMAP_API_KEY= # Optional. Amap (高德地图) Web 服务 key for place search and geocoding inside mainland China. Overrides the key set in Admin > Settings > API Keys. A Web 端 (JS API) key is a different credential and is rejected with INVALID_USER_KEY.+# - AMAP_API_SECRET= # Optional. The private secret (数字签名) of that key. Required exactly when the key was created with signing enabled, because such a key rejects every unsigned request. Leave unset otherwise.+# - AMAP_API_BASE=https://restapi.amap.com # Optional. Send the Amap calls through an egress proxy, a cache or a gateway that speaks the same API instead of restapi.amap.com directly. (default: https://restapi.amap.com)volumes:- ./data:/app/data- ./uploads:/app/uploadsdiff --git a/docs/system-notices.md b/docs/system-notices.mdindex 612a9ef3f..bdec4a5bf 100644--- a/docs/system-notices.md+++ b/docs/system-notices.md@@ -60,8 +60,8 @@ There are **no database rows for notice definitions**. The registry is code-only3. SystemNoticeHost mounts → calls useSystemNoticeStore.fetch()│ (also triggered on cold page reload if store not yet loaded)▼-4. GET /api/system-notices/active- │+4. GET /api/system-notices/active?supports=release+ │ (`supports` lists the layouts this bundle can draw; see section 10)▼5. service.getActiveNoticesFor(userId)├── reads user row (login_count, first_seen_version, role)@@ -75,6 +75,10 @@ There are **no database rows for notice definitions**. The registry is code-only└── strips server-only fields (conditions, publishedAt, minVersion, maxVersion, priority)│▼+ Nest SystemNoticesService drops every notice with a `release` block unless the+ request announced `supports=release`+ │+ ▼6. Client receives SystemNoticeDTO[]│▼@@ -500,7 +504,7 @@ system_notice.pager.position → "Notice {current} of {total}" (aria-live)| Action | Behaviour ||---|---|-| `fetch()` | `GET /api/system-notices/active`. Fails silently (non-critical). Sets `loaded = true` regardless. |+| `fetch()` | `GET /api/system-notices/active?supports=release`. Fails silently (non-critical). Sets `loaded = true` regardless. `supports` names the layouts this bundle can draw: after an update the service worker keeps serving the previous bundle until the new one is installed, and a bundle that does not announce the release layout would draw the release notice as bare keys and could dismiss it for good. The server holds a notice with a `release` block back from such a client and delivers it after the reload. || `dismiss(id)` | Optimistic: removes notice from store immediately. POSTs to `/api/system-notices/{id}/dismiss` in background with one retry on failure. |`SystemNoticeHost` triggers `fetch()` on mount if `loaded === false`. Auth store also triggers it after login, so on a fresh login the fetch happens exactly once.diff --git a/server/.env.example b/server/.env.exampleindex 5eeccc1ce..a61fe0641 100644--- a/server/.env.example+++ b/server/.env.example@@ -53,7 +53,14 @@ DEMO_MODE=false # Demo mode - resets data hourly# NOMINATIM_URL=https://nominatim.openstreetmap.org # Custom HTTP(S) Nominatim base URL for every geocoding call the server makes: place search, reverse lookup, place details and the Atlas region fill. When set it REPLACES the public service with no fallback, so whatever answers has to speak the Nominatim API (/search, /reverse, /lookup) and hold the coverage you expect. TREK keeps its ~1 request per second spacing whichever instance answers. Unset/blank uses the public default.# OVERPASS_URL= # Custom Overpass endpoint(s) for the map POI "explore" search, comma-separated. When set, REPLACES the bundled public mirrors — point it at an internal/self-hosted Overpass instance when the public ones are unreachable from your network. Non-http(s) entries are ignored. If you don't self-host Overpass but the public mirrors throttle you, setting APP_URL also gives outbound requests a unique User-Agent the mirrors rate-limit less.-# OVERPASS_TIMEOUT_MS=12000 # Per-endpoint timeout (ms) for Overpass POI requests; slower endpoints are abandoned so a faster mirror wins. Raise it for a slow self-hosted instance. (default: 12000)+# OVERPASS_TIMEOUT_MS=25000 # Per-endpoint timeout (ms) for Overpass POI requests; slower endpoints are abandoned so a faster mirror wins. The query itself gives Overpass 20 seconds of work, so a lower value hangs up on answers that were still coming. Raise it for a slow self-hosted instance. (default: 25000)++# TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding and offline downloads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true)+# TREK_PLACES_URL=https://places.liketrek.com # Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com)++# AMAP_API_KEY= # Amap (高德地图) Web 服务 key for place search and geocoding inside mainland China. Overrides the key set in Admin > Settings > API Keys. A Web 端 (JS API) key is a different credential and is rejected with INVALID_USER_KEY.+# AMAP_API_SECRET= # The private secret (数字签名) of that key. Required exactly when the key was created with signing enabled, because such a key rejects every unsigned request. Leave unset otherwise.+# AMAP_API_BASE=https://restapi.amap.com # Send the Amap calls through an egress proxy, a cache or a gateway that speaks the same API instead of restapi.amap.com directly. (default: https://restapi.amap.com)# KITINERARY_EXTRACTOR_PATH= # Full path to the kitinerary-extractor binary. Unset, TREK searches /usr/lib/*/libexec/kf6/ and then PATH; the official image pins it. Set it to run a newer extractor than your distribution packages — the version in use is in the startup log and in GET /api/admin/system-info. (default: auto-detected)diff --git a/server/scripts/migrate-encryption.ts b/server/scripts/migrate-encryption.tsindex 4b4e2559e..5ce11fe7b 100644--- a/server/scripts/migrate-encryption.ts+++ b/server/scripts/migrate-encryption.ts@@ -554,6 +554,44 @@ async function main() {db.prepare('UPDATE trek_photos SET passphrase = ? WHERE id = ?').run(newVal, row.id);}}++ // --- document_connections: secrets ---+ // Every credential of a document connection sits in ONE encrypted JSON blob+ // (src/nest/doc-sync/doc-sync-secrets.ts) rather than in a column per+ // provider, so a new provider changes nothing here: the blob is rotated as+ // an opaque value. It also holds secrets the provider handed out itself,+ // such as the DSM device token, which no form can re-enter. Left out of a+ // rotation, every trip binding on the instance reads back as unauthorized+ // and Synology needs a fresh OTP pairing. The table arrived with a later+ // migration, hence the existence check.+ if (tableExists('document_connections')) {+ const documentConnections = db+ .prepare('SELECT id, secrets FROM document_connections WHERE secrets IS NOT NULL')+ .all() as { id: number; secrets: string }[];+ for (const row of documentConnections) {+ const newVal = migrateApiKeyValue(row.secrets, `document_connections[${row.id}].secrets`);+ if (newVal !== null) {+ db.prepare('UPDATE document_connections SET secrets = ? WHERE id = ?').run(newVal, row.id);+ }+ }+ }++ // --- trip_document_links: webhook_secret ---+ // The secret a provider signs its webhook calls with, stored through the+ // same blob helper. It is written once when the link is created and never+ // regenerated, so a rotation that misses it leaves the link with nothing to+ // check a signature against.+ if (tableExists('trip_document_links')) {+ const documentLinks = db+ .prepare('SELECT id, webhook_secret FROM trip_document_links WHERE webhook_secret IS NOT NULL')+ .all() as { id: number; webhook_secret: string }[];+ for (const row of documentLinks) {+ const newVal = migrateApiKeyValue(row.webhook_secret, `trip_document_links[${row.id}].webhook_secret`);+ if (newVal !== null) {+ db.prepare('UPDATE trip_document_links SET webhook_secret = ? WHERE id = ?').run(newVal, row.id);+ }+ }+ }})();db.close();diff --git a/server/src/app-config/derive.ts b/server/src/app-config/derive.tsindex d644211de..8f817239e 100644--- a/server/src/app-config/derive.ts+++ b/server/src/app-config/derive.ts@@ -151,8 +151,14 @@ export function deriveMaps(raw: RawEnv) {* whether searches leave the instance, and a setting that reaches for the* network is one an operator wants pinned in their compose file, not one a* second admin can flip in a browser.+ *+ * Off only on a value of the false family the schema admits (false, 0,+ * off, no), so the switch reads like every other boolean here. Unset,+ * blank and anything else stay on: the schema refuses a value outside the+ * family at boot, and a path that skips validation must not quietly drop+ * the install back to Nominatim.*/- trekPlacesEnabled: raw.TREK_PLACES_ENABLED !== 'false',+ trekPlacesEnabled: parseBool(raw.TREK_PLACES_ENABLED) !== false,placesApiKey: raw.PLACES_API_KEY || undefined,/** The same two knobs for Amap (高德), which an install in China uses instead. */amapApiBase: raw.AMAP_API_BASE || undefined,diff --git a/server/src/bootstrap.ts b/server/src/bootstrap.tsindex 392416a44..ddca87bcd 100644--- a/server/src/bootstrap.ts+++ b/server/src/bootstrap.ts@@ -148,9 +148,11 @@ export async function buildApp(): Promise<INestApplication> {* A list file is the same story at a smaller scale. Its contract allows a* megabyte and the import posts it whole, yet a list of a few hundred places* with notes is past a hundred kilobytes already, and so is the favourites- * GPX of anybody who uses OsmAnd (#2301). The two routes that carry one are- * measured against that megabyte, doubled for the JSON escaping of a- * document full of quotes. Everything else keeps the tighter limit.+ * GPX of anybody who uses OsmAnd (#2301). The three routes that carry one,+ * the import into a new list, the GPX reader and the import into a list that+ * already exists, are measured against that megabyte, doubled for the JSON+ * escaping of a document full of quotes. Everything else keeps the tighter+ * limit.*/const bookBody = express.json({ limit: '8mb', verify: rawBodyKeeper });const listFileBody = express.json({ limit: MAX_COLLECTION_FILE_BYTES * 2, verify: rawBodyKeeper });@@ -159,8 +161,8 @@ export async function buildApp(): Promise<INestApplication> {const isMcp = (req: Request) => req.path === '/mcp' || req.path === '/mcp/';const isBookWrite = (req: Request) =>req.method === 'PUT' && /^\/api\/journeys\/\d+\/book$/.test(req.path);- const listFilePaths = new Set(['/api/addons/collections/import', '/api/addons/collections/gpx/read']);- const isListFile = (req: Request) => req.method === 'POST' && listFilePaths.has(req.path);+ const isListFile = (req: Request) =>+ req.method === 'POST' && /^\/api\/addons\/collections\/(import|gpx\/read|\d+\/import)$/.test(req.path);instance.use(function jsonParser(req: Request, res: Response, next: NextFunction) {if (isBookWrite(req)) return bookBody(req, res, next);diff --git a/server/src/nest/accommodations/accommodations.controller.ts b/server/src/nest/accommodations/accommodations.controller.tsindex b81f3337b..91cdc90c5 100644--- a/server/src/nest/accommodations/accommodations.controller.ts+++ b/server/src/nest/accommodations/accommodations.controller.ts@@ -12,7 +12,7 @@ import {UseGuards,} from '@nestjs/common';import type { User } from '../../types';-import { AccommodationsService } from './accommodations.service';+import { AccommodationsService, type MirrorSender } from './accommodations.service';import { AccommodationCreateDto, AccommodationUpdateDto } from './accommodations.dto';import { JwtAuthGuard } from '../auth/jwt-auth.guard';import { CurrentUser } from '../auth/current-user.decorator';@@ -39,10 +39,10 @@ type AccommodationBody = {* accommodation also emits reservation:created; a delete emits the linked* reservation/budget deletions) with the forwarded X-Socket-Id.*- * A booking also writes the day stop that puts it on the route, so the answers- * carry that stop alongside the existing fields: the broadcast skips the socket- * that sent the request, and the client that booked the night has to be able to- * draw it without waiting for a reload.+ * A booking also writes the day stop that puts it on the route. What that did to+ * the day plan goes to every socket, the sender's included (see mirrorSender),+ * and the answers carry the stop alongside the existing fields as well, for a+ * session whose socket is down at that moment.*/@Controller('api/trips/:tripId/accommodations')// TripAccessGuard resolves :tripId and 404s a trip the user cannot reach; mutations@@ -52,7 +52,20 @@ type AccommodationBody = {export class AccommodationsController {constructor(private readonly accommodations: AccommodationsService) {}-+ /**+ * The mirror's door out, with no socket to skip.+ *+ * The booking events above it are echo-suppressed because the client already drew+ * what it sent. It never sent the day plan's side of the write: the stop is in the+ * answer, but the order the night was seated into and the vias re-pinned around it+ * are not, and a session that applies the stop from the answer alone keeps the+ * stops behind it on their old numbers until a reload. Over the socket the stop+ * and the order arrive together and in order, and the answer's copy of the stop+ * is a duplicate the store already drops.+ */+ private mirrorSender(tripId: string): MirrorSender {+ return (event, payload) => this.accommodations.broadcast(tripId, event, payload, undefined);+ }@Get()list(@CurrentUser() user: User, @Param('tripId') tripId: string) {@@ -79,10 +92,9 @@ export class AccommodationsController {const { accommodation, mirror } = this.accommodations.create(tripId, { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } as never);this.accommodations.broadcast(tripId, 'accommodation:created', { accommodation }, socketId);this.accommodations.broadcast(tripId, 'reservation:created', {}, socketId);- this.accommodations.announceMirror(tripId, mirror, (event, payload) => this.accommodations.broadcast(tripId, event, payload, socketId), socketId);- // The stop rides in the answer as well: the broadcast above deliberately skips- // the socket that sent the request, so without it the very session that booked- // the night would be the one that cannot see it until a reload.+ this.accommodations.announceMirror(tripId, mirror, this.mirrorSender(tripId), socketId);+ // The stop rides in the answer as well, for the session that booked the night+ // with its socket down: over the socket it would already have it.return { accommodation, assignment: mirror.created };}@@ -107,7 +119,7 @@ export class AccommodationsController {}const { accommodation, mirror } = this.accommodations.update(id, existing as never, { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } as never);this.accommodations.broadcast(tripId, 'accommodation:updated', { accommodation }, socketId);- this.accommodations.announceMirror(tripId, mirror, (event, payload) => this.accommodations.broadcast(tripId, event, payload, socketId), socketId);+ this.accommodations.announceMirror(tripId, mirror, this.mirrorSender(tripId), socketId);return { accommodation, assignment: mirror.created, movedAssignment: mirror.moved, removedAssignments: mirror.removed };}@@ -127,7 +139,7 @@ export class AccommodationsController {// stop stays and becomes the traveller's. Everywhere else a cancelled booking// takes the stop it brought with it.const { linkedReservationIds, deletedBudgetItemIds, mirror } = this.accommodations.remove(id, { keepStop: keepStop === 'true' });- this.accommodations.announceMirror(tripId, mirror, (event, payload) => this.accommodations.broadcast(tripId, event, payload, socketId), socketId);+ this.accommodations.announceMirror(tripId, mirror, this.mirrorSender(tripId), socketId);for (const reservationId of linkedReservationIds) {this.accommodations.broadcast(tripId, 'reservation:deleted', { reservationId }, socketId);}diff --git a/server/src/nest/accommodations/accommodations.service.ts b/server/src/nest/accommodations/accommodations.service.tsindex ad434c867..b140feb9f 100644--- a/server/src/nest/accommodations/accommodations.service.ts+++ b/server/src/nest/accommodations/accommodations.service.ts@@ -1,5 +1,5 @@import { Injectable } from '@nestjs/common';-import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';+import type { RoadtripVia, TrekWsPayload, TrekWsTripEventName } from '@trek/shared';import { RealtimeService } from '../realtime/realtime.service';import { DatabaseService, type PlaceWithTags, type TripAccess } from '../database/database.service';import { PermissionsService } from '../permissions/permissions.service';@@ -10,6 +10,12 @@ type Trip = TripAccess;type MirroredAssignment = ReturnType<AssignmentsService['createAssignment']>;+/** One day's drawn roads after a write re-pinned them, as the road trip broadcasts them. */+type DayVias = { dayId: number; vias: RoadtripVia[] };++/** A via as the re-pinning reads it: where it is pinned and its place on that leg. */+type PinnedVia = { id: number; after_order_index: number; sequence: number };+/** How a surface sends the mirror's events; see announceMirror. */export type MirrorSender = <E extends TrekWsTripEventName>(event: E, payload: TrekWsPayload<E>) => void;@@ -25,6 +31,9 @@ export interface AccommodationMirror {removed: { id: number; dayId: number }[];/** The place, when this write was the one that typed it as lodging. */stamped: PlaceWithTags | null;+ /** Days whose drawn roads were re-pinned because a stop of theirs changed position.+ * Absent when none did, which is what a mirror built elsewhere means too. */+ vias?: DayVias[];}/** A write that left the day plan alone. Exported for the surfaces that write a@@ -169,9 +178,11 @@ export class AccommodationsService {* Send what a stay write did to the day plan, and let the journey skeletons* catch up the way an assignment route does.*- * Takes the sender rather than broadcasting itself: REST and the plugin RPC- * hand their socket id in, the MCP tools tag their events, and the fan-out is- * the one part that must not exist in three copies.+ * Takes the sender rather than broadcasting itself: the MCP tools tag their+ * events, REST and the plugin RPC send them plain, and the fan-out is the one+ * part that must not exist in three copies. None of them skips the socket that+ * sent the request. The day order and the vias sent here are news to that+ * session too, and they only make sense arriving behind the stop they concern.*/announceMirror(tripId: string | number, mirror: AccommodationMirror, send: MirrorSender, socketId?: string): void {for (const stop of mirror.removed) send('assignment:deleted', { assignmentId: stop.id, dayId: stop.dayId });@@ -194,6 +205,9 @@ export class AccommodationsService {'SELECT id FROM day_assignments WHERE day_id = ? ORDER BY order_index', dayId).map(row => row.id);send('assignment:reordered', { dayId, orderedIds });}+ // After the order, the way the time sort sends them: the planner routes the+ // anchors it holds against the order it holds, and the two have to land together.+ for (const day of mirror.vias ?? []) send('roadtripVia:changed', day);if (mirror.created || mirror.moved || mirror.removed.length > 0) this.assignments.reconcile(tripId, socketId);}@@ -324,6 +338,121 @@ export class AccommodationsService {return this.db.getPlaceWithTags(placeId);}+ /**+ * Each day's located stops in order, taken before a write that can move them.+ *+ * That order is the index space the day's vias are pinned to: a via sits behind+ * the n-th stop that has coordinates, not behind a row id. Stops without+ * coordinates are never routed and so never counted.+ */+ private stopOrders(dayIds: number[]): Map<number, number[]> {+ return new Map([...new Set(dayIds)].map((dayId): [number, number[]] => [dayId, this.locatedStopIds(dayId)]));+ }++ private locatedStopIds(dayId: number): number[] {+ return this.db.all<{ id: number }>(`+ SELECT da.id FROM day_assignments da JOIN places p ON p.id = da.place_id+ WHERE da.day_id = ? AND p.lat IS NOT NULL AND p.lng IS NOT NULL+ ORDER BY da.order_index ASC, da.created_at ASC, da.id ASC+ `, dayId).map(row => row.id);+ }++ /**+ * Keep every drawn road behind the stop it was drawn after, now that this write+ * has seated, moved or taken out a stop on these days.+ *+ * A night seated by its check-in ahead of the afternoon renumbers everything+ * behind it, and a via pinned to position one would otherwise bend the drive+ * into the hotel instead of the leg it was drawn on. Persisted and visible to+ * everyone, so it is put right where the stop moved, by the rules the planner+ * applies when a stop is dragged or taken out: a via follows its stop, a stop+ * that left the day hands its road to the stop before it, and a stop that is+ * last has no leg to keep a via on.+ *+ * Runs inside the caller's transaction.+ */+ private reanchorVias(mirror: AccommodationMirror, before: Map<number, number[]>): void {+ for (const [dayId, previousIds] of before) {+ const nextIds = this.locatedStopIds(dayId);+ if (previousIds.length === nextIds.length && previousIds.every((id, i) => id === nextIds[i])) continue;+ const vias = this.db.all<PinnedVia>('SELECT id, after_order_index, sequence FROM roadtrip_vias WHERE day_id = ?', dayId);+ if (!vias.length) continue;++ // A via behind the day's last stop bends the drive into the next day. It stays+ // with that stop when the stop is still last, whatever its number is now:+ // measured as a leg it would be dropped, because a last stop has no leg.+ const previousLast = previousIds.length - 1;+ const nextLast = nextIds.length - 1;+ const lastStayed = previousLast >= 0 && previousIds[previousLast] === nextIds[nextLast];+ const remove: number[] = [];+ const moved: { id: number; after_order_index: number }[] = [];+ for (const via of vias) {+ const next = lastStayed && via.after_order_index === previousLast+ ? nextLast+ : this.legAfter(via.after_order_index, previousIds, nextIds);+ if (next === null) remove.push(via.id);+ else if (next !== via.after_order_index) moved.push({ id: via.id, after_order_index: next });+ }+ if (!remove.length && !moved.length) continue;++ for (const viaId of remove) this.db.run('DELETE FROM roadtrip_vias WHERE id = ? AND day_id = ?', viaId, dayId);+ for (const via of moved) this.db.run('UPDATE roadtrip_vias SET after_order_index = ? WHERE id = ? AND day_id = ?', via.after_order_index, via.id, dayId);+ this.renumberMergedLegs(dayId, vias.filter(via => !remove.includes(via.id)), moved);+ this.noteVias(mirror, {+ dayId,+ vias: this.db.all<RoadtripVia>(+ 'SELECT id, day_id, after_order_index, sequence, lat, lng, created_at FROM roadtrip_vias WHERE day_id = ? ORDER BY after_order_index, sequence, id', dayId),+ });+ }+ }++ /**+ * The leg a via pinned behind the n-th stop of the old order is on in the new one.+ *+ * A stop this write took off the day hands its road to the stop before it: the+ * leg it was drawn on merges into the one ahead, the way taking a stop out of the+ * drive merges them (`RoadtripService.reanchor`). Null when no leg is left for it,+ * because the stop it follows is the last one now, nothing ahead of it survived,+ * or it was pinned past the day's end to begin with.+ */+ private legAfter(index: number, previousIds: number[], nextIds: number[]): number | null {+ if (index > previousIds.length - 1) return null;+ let at = index;+ while (at >= 0 && !nextIds.includes(previousIds[at])) at -= 1;+ if (at < 0) return null;+ const next = nextIds.indexOf(previousIds[at]);+ return next >= nextIds.length - 1 ? null : next;+ }++ /**+ * Two legs that merged carry two sequence series side by side, and everything+ * that draws the route orders by sequence: the drive would run through the first+ * leg's point, the second leg's, and back. Renumbered the way+ * `RoadtripService.reanchor` does it, the earlier leg's points first, then by+ * their old sequence, then by id. Only a leg that received a via is touched.+ */+ private renumberMergedLegs(dayId: number, kept: PinnedVia[], moved: { id: number; after_order_index: number }[]): void {+ const landed = new Map(moved.map(via => [via.id, via.after_order_index]));+ const byLeg = new Map<number, PinnedVia[]>();+ for (const via of kept) {+ const leg = landed.get(via.id) ?? via.after_order_index;+ byLeg.set(leg, [...(byLeg.get(leg) ?? []), via]);+ }+ for (const onLeg of byLeg.values()) {+ if (!onLeg.some(via => landed.has(via.id))) continue;+ onLeg.sort((a, b) => a.after_order_index - b.after_order_index || a.sequence - b.sequence || a.id - b.id);+ onLeg.forEach((via, index) => {+ if (via.sequence !== index) this.db.run('UPDATE roadtrip_vias SET sequence = ? WHERE id = ? AND day_id = ?', index, via.id, dayId);+ });+ }+ }++ /** One entry per day: a write that takes a stop off a day and puts one back on+ * the same day reports the state it left behind, not both steps. */+ private noteVias(mirror: AccommodationMirror, day: DayVias): void {+ mirror.vias = [...(mirror.vias ?? []).filter(known => known.dayId !== day.dayId), day];+ }+/*** Carry the booking's own stop to where the booking now is, in place.*@@ -389,6 +518,7 @@ export class AccommodationsService {// answer for a place already planned for that day by hand.if (this.db.get('SELECT id FROM day_assignments WHERE day_id = ? AND place_id = ?', dayId, placeId)) return mirror;+ const before = this.stopOrders([dayId]);// Through AssignmentsService, so the stop lands at the end of the day with the// order_index every other new assignment gets. Evening is where you arrive at a// hotel, and the day planner has no drive to position it against anyway.@@ -402,6 +532,7 @@ export class AccommodationsService {accommodationId,orderIndex: this.positionForCheckIn(dayId, checkIn),});+ this.reanchorVias(mirror, before);return mirror;}@@ -428,7 +559,9 @@ export class AccommodationsService {*/private releaseStops(accommodationId: number, opts: { keepStop?: boolean }): AccommodationMirror {const mirror = noMirror();- for (const stop of this.ownStops(accommodationId)) {+ const own = this.ownStops(accommodationId);+ const before = this.stopOrders(own.map(stop => stop.day_id));+ for (const stop of own) {if (opts.keepStop) {this.db.run('UPDATE day_assignments SET accommodation_id = NULL WHERE id = ?', stop.id);// The stop stays, but it is the traveller's now. Days hides a stop whose@@ -441,6 +574,7 @@ export class AccommodationsService {this.db.run('DELETE FROM day_assignments WHERE id = ?', stop.id);mirror.removed.push({ id: stop.id, dayId: stop.day_id });}+ this.reanchorVias(mirror, before);return mirror;}@@ -473,21 +607,26 @@ export class AccommodationsService {// note, its hour, its end-of-day flag and the road-trip day boundary anchored// on its id, all of which a DELETE takes with it.if (own.length === 1 && placeId) {+ const before = this.stopOrders([own[0].day_id, dayId]);const moved = this.relocateOwnStop(own[0], placeId, dayId, checkIn);if (moved) {mirror.moved = { assignment: moved, oldDayId: own[0].day_id };mirror.stamped = this.stampLodging(placeId);+ this.reanchorVias(mirror, before);return mirror;}}+ const beforeRebuild = this.stopOrders(own.map(stop => stop.day_id));for (const stop of own) {this.db.run('DELETE FROM day_assignments WHERE id = ?', stop.id);mirror.removed.push({ id: stop.id, dayId: stop.day_id });}+ this.reanchorVias(mirror, beforeRebuild);const fresh = this.mirrorStay(accommodationId, placeId, dayId, checkIn);mirror.created = fresh.created;mirror.stamped = fresh.stamped;+ for (const day of fresh.vias ?? []) this.noteVias(mirror, day);return mirror;}diff --git a/server/src/nest/calendar/calendar.service.ts b/server/src/nest/calendar/calendar.service.tsindex 39f49325f..61037343a 100644--- a/server/src/nest/calendar/calendar.service.ts+++ b/server/src/nest/calendar/calendar.service.ts@@ -241,6 +241,11 @@ export class CalendarService {for (const day of days) {if (!day.date) continue;+ // A booked night puts a stop of its own on its check-in day, so the route+ // can reach the hotel. That stop is the booking, not a place the traveller+ // planned to visit, and the booking already comes through below as the+ // stay block or its check-in and check-out markers. Read here as well it+ // would put the hotel on the day a second time.const assignments = this.db.prepare(`SELECT da.*, p.name as place_name, p.address as place_address,p.lat as place_lat, p.lng as place_lng,@@ -249,6 +254,7 @@ export class CalendarService {FROM day_assignments daJOIN places p ON da.place_id = p.idWHERE da.day_id = ?+ AND da.accommodation_id IS NULLORDER BY da.order_index ASC, da.created_at ASC`).all(day.id) as any[];diff --git a/server/src/nest/doc-sync/doc-sync-config.service.ts b/server/src/nest/doc-sync/doc-sync-config.service.tsindex 080a45083..77a25f307 100644--- a/server/src/nest/doc-sync/doc-sync-config.service.ts+++ b/server/src/nest/doc-sync/doc-sync-config.service.ts@@ -6,6 +6,7 @@ import { checkSsrf } from '../../utils/ssrfGuard';import { DocumentProviderRegistry } from './document-provider.registry';import type { DocumentConnectionRef, DocumentScopeRef, DocResult } from './document-provider';import { docFailed } from './document-provider';+import { sameOrigin } from './doc-sync.helpers';import { decryptSecrets, encryptSecrets, maskSecrets, mergeSecrets } from './doc-sync-secrets';/**@@ -239,9 +240,23 @@ export class DocSyncConfigService {* Secrets that arrive blank or masked keep their stored value, so a client* that renders the form from a GET never has to hold the real credential.* A secret the provider earned itself is kept too, whatever the form sends.- * DSM's device token is stored with the address and account it was issued- * for, so an edit that points the connection somewhere else leaves it- * unusable, and the adapter drops it on its next call.+ *+ * Only for the address the credential was stored against, the same rule the+ * probe route applies. Written under a new host, a blank form would carry+ * the stored token to a server of the caller's choosing: a trip changes+ * hands with its connection, and the new owner, or an instance admin, could+ * point the previous owner's Paperless token at a machine of their own and+ * read it off the first request. A new address takes the credentials typed+ * for it and nothing stored, DSM's device token included: it was issued for+ * the old address and account and would only be sent somewhere it does not+ * belong.+ *+ * `owner_user_id` names whose credential the connection runs under. It moves+ * to the caller only when the caller typed every required secret in, so the+ * connection now runs on a credential of their own; an edit that keeps the+ * stored one keeps its owner, or the orphan check would read the previous+ * owner's token as the caller's own. An optional secret alone (DSM's+ * one-time code) does not count: it is used against the stored password.*/async upsertConnection(tripId: number,@@ -260,7 +275,23 @@ export class DocSyncConfigService {.get(tripId, input.providerId) as ConnectionRow | undefined;const storedSecrets = existing ? decryptSecrets(existing.secrets) : {};- const nextSecrets = mergeSecrets(storedSecrets, input.credentials, secretKeys);+ // What the form actually filled in, by the same rule the merge below uses.+ const typedSecrets = mergeSecrets({}, input.credentials, secretKeys);+ const sameTarget = !existing || sameOrigin(existing.base_url, urlCheck.data.url);+ if (!sameTarget) {+ const kept = fields.find(+ (f) => f.secret === 1 && f.required === 1 && !!storedSecrets[f.field_key] && !typedSecrets[f.field_key],+ );+ if (kept) {+ return {+ success: false,+ error: { code: 'unauthorized', detail: `${kept.field_key} has to be entered again for a new address` },+ };+ }+ }+ const nextSecrets = sameTarget ? mergeSecrets(storedSecrets, input.credentials, secretKeys) : typedSecrets;+ const ownCredential = fields.every((f) => f.secret !== 1 || f.required !== 1 || !!typedSecrets[f.field_key]);+ const ownerId = existing && !ownCredential ? existing.owner_user_id : userId;const settings: Record<string, string> = {};for (const key of plainKeys) {@@ -294,7 +325,7 @@ export class DocSyncConfigService {owner_user_id = ?, updated_at = CURRENT_TIMESTAMPWHERE id = ?`,)- .run(urlCheck.data.url, encrypted, settingsJson, insecure, userId, existing.id);+ .run(urlCheck.data.url, encrypted, settingsJson, insecure, ownerId, existing.id);return this.getConnection(existing.id) as ConnectionRow;}const info = this.db.connection@@ -467,14 +498,27 @@ export class DocSyncConfigService {lastSyncError: link.last_sync_error,failureCount: link.failure_count,// Shown so a user can paste it into a provider that will not let TREK- // subscribe on its own (Papra, and Nextcloud without admin rights).- webhookUrl: webhookBaseUrl && link.webhook_token+ // subscribe on its own (Papra, and Nextcloud without admin rights). Not+ // for a provider that takes no webhook at all: an address with nowhere+ // to paste it only promises what the timer delivers anyway.+ webhookUrl: webhookBaseUrl && link.webhook_token && this.takesWebhook(link)? `${webhookBaseUrl}/api/docsync/webhook/${link.webhook_token}`: null,webhookSecret: link.webhook_secret ? DOCSYNC_SECRET_MASK : null,};}+ /**+ * Whether the store behind a binding can call TREK at all, as the last probe+ * recorded it. Unknown counts as yes: a connection that was never probed+ * still gets the address, and a stale answer costs nothing but a line.+ */+ private takesWebhook(link: LinkRow): boolean {+ const recorded = this.getConnection(link.connection_id)?.capabilities;+ const caps = recorded ? safeParse(recorded) : null;+ return !(caps && typeof caps === 'object' && (caps as { push?: unknown }).push === 'none');+ }+/*** Whether a binding must not run. The sweep below marks it, but only while* Sync automatically is on, so a paused binding whose owner left is notdiff --git a/server/src/nest/doc-sync/doc-sync-webhook.controller.ts b/server/src/nest/doc-sync/doc-sync-webhook.controller.tsindex 11bf142b8..5a2c5f660 100644--- a/server/src/nest/doc-sync/doc-sync-webhook.controller.ts+++ b/server/src/nest/doc-sync/doc-sync-webhook.controller.ts@@ -20,8 +20,9 @@ import { DocSyncService } from './doc-sync.service';** `@Public` because a provider cannot hold a TREK session. The token in the URL* is the authentication, one per binding, so a leaked URL can only ever nudge- * the one trip it belongs to, and nudging is all it can do. Where the provider- * supports it, a shared secret is checked as well.+ * the one trip it belongs to, and nudging is all it can do. Where TREK+ * registered the subscription itself, the shared secret it handed over is+ * checked as well.*/@Controller('api/docsync/webhook')export class DocSyncWebhookController implements OnModuleDestroy {@@ -78,7 +79,14 @@ export class DocSyncWebhookController implements OnModuleDestroy {if (!link || link.sync_enabled !== 1) return { received: true };if (!this.syncIsOn(link)) return { received: true };- const secret = this.config.webhookSecret(link);+ // The secret is only known to a provider TREK subscribed at itself, so it+ // is only demanded there. A URL pasted into a store by hand (Papra, or a+ // Nextcloud without admin rights) carries the token and nothing else: the+ // secret is never shown to anybody, and Papra signs with a secret of its+ // own that TREK cannot know. Demanding it there meant every such call was+ // dropped and the binding ran on the timer while the screen promised+ // instant updates.+ const secret = link.webhook_subscription_id ? this.config.webhookSecret(link) : '';if (secret && !this.secretMatches(req, secret)) return { received: true };// Fire and forget. Paperless allows five seconds before it counts the calldiff --git a/server/src/nest/doc-sync/doc-sync.controller.ts b/server/src/nest/doc-sync/doc-sync.controller.tsindex fc50ea7f8..3ad7c4f42 100644--- a/server/src/nest/doc-sync/doc-sync.controller.ts+++ b/server/src/nest/doc-sync/doc-sync.controller.ts@@ -5,6 +5,7 @@ import {Get,HttpCode,HttpException,+ Logger,Param,Patch,Post,@@ -28,6 +29,7 @@ import { DocSyncConfigService, type LinkRow } from './doc-sync-config.service';import { DocSyncService } from './doc-sync.service';import { DocumentProviderRegistry } from './document-provider.registry';import { PROVIDER_DISABLED } from './doc-sync.constants';+import { sameOrigin } from './doc-sync.helpers';import {DocsyncConnectionDto,DocsyncConnectionTestDto,@@ -62,6 +64,8 @@ import {@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)@RequireAddon(ADDON_IDS.DOCUMENTS, 'Documents')export class DocSyncController {+ private readonly logger = new Logger(DocSyncController.name);+constructor(private readonly config: DocSyncConfigService,private readonly sync: DocSyncService,@@ -205,7 +209,7 @@ export class DocSyncController {@Delete('connections/:connectionId')@HttpCode(200)- deleteConnection(+ async deleteConnection(@Param('tripId') tripId: string,@Param('connectionId') connectionId: string,@CurrentUser() user: User,@@ -213,8 +217,19 @@ export class DocSyncController {this.assertCanManage(tripId, user);const conn = this.config.getConnection(Number(connectionId));if (!conn || conn.trip_id !== Number(tripId)) throw new HttpException('Connection not found', 404);- // Its bindings go with it (ON DELETE CASCADE), so read them first.+ // Its bindings go with it (ON DELETE CASCADE), so read them first. Every+ // subscription TREK registered for one of them is taken down while the+ // credential is still here to do it with, as unbinding one does: left+ // standing, a Paperless workflow or a Nextcloud listener keeps posting to+ // a token that answers nothing, for good.const unbound = this.config.listLinks(conn.trip_id).filter((l) => l.connection_id === conn.id);+ const provider = this.registry.get(conn.provider_id);+ if (provider?.unregisterWebhook) {+ const ref = this.config.toRef(conn);+ for (const link of unbound) {+ if (link.webhook_subscription_id) await provider.unregisterWebhook(ref, link.webhook_subscription_id);+ }+ }this.config.deleteConnection(conn.id);for (const link of unbound) this.announceBinding(link);return { success: true };@@ -280,7 +295,8 @@ export class DocSyncController {// Subscribe where the provider lets TREK do it itself. A failure here is// not a failure of the binding (polling still carries it), so it is logged- // into the link state rather than thrown at the user.+ // rather than thrown at the user; the first run that follows would write+ // over anything put into the link state.const conn = this.config.getConnection(res.data.connection_id);const provider = conn ? this.registry.get(conn.provider_id) : undefined;if (conn && provider?.registerWebhook) {@@ -292,7 +308,11 @@ export class DocSyncController {`${base}/api/docsync/webhook/${res.data.webhook_token}`,this.config.webhookSecret(res.data),);- if (hook.success) {+ if (docFailed(hook)) {+ this.logger.warn(+ `link ${res.data.id}: ${conn.provider_id} refused the webhook subscription (${hook.error.code}${hook.error.detail ? `: ${hook.error.detail}` : ''}), polling carries it`,+ );+ } else {this.db.connection.prepare('UPDATE trip_document_links SET webhook_subscription_id = ? WHERE id = ?').run(hook.data.subscriptionId, res.data.id);@@ -408,19 +428,6 @@ export class DocSyncController {}}--/** Whether two URLs address the same server, for deciding if a stored secret may be reused. */-function sameOrigin(a: string | null | undefined, b: string): boolean {- if (!a) return false;- try {- const x = new URL(a);- const y = new URL(b);- return x.protocol === y.protocol && x.host === y.host;- } catch {- return false;- }-}-/*** The origin a provider has to call back on.*diff --git a/server/src/nest/doc-sync/doc-sync.helpers.ts b/server/src/nest/doc-sync/doc-sync.helpers.tsindex 03ddcfcf0..531fa838c 100644--- a/server/src/nest/doc-sync/doc-sync.helpers.ts+++ b/server/src/nest/doc-sync/doc-sync.helpers.ts@@ -75,6 +75,22 @@ export function isAllowedByOperator(name: string, allowedCsv: string): boolean {.includes(ext);}+/**+ * Whether two URLs address the same server, for deciding if a stored secret+ * may be reused. Same scheme, same host, same port: a path may differ, because+ * the token still only ever reaches the server it was issued for.+ */+export function sameOrigin(a: string | null | undefined, b: string): boolean {+ if (!a) return false;+ try {+ const x = new URL(a);+ const y = new URL(b);+ return x.protocol === y.protocol && x.host === y.host;+ } catch {+ return false;+ }+}+// ── The plan ─────────────────────────────────────────────────────────────────/** What the core knows about one pairing before the run. */@@ -141,8 +157,13 @@ export type PlanAction =| { kind: 'conflict'; itemId: number; remote: RemoteDocument | null; local: LocalDocument | null }/** Present upstream last run, absent now. Recorded, never acted on. */| { kind: 'mark_remote_missing'; itemId: number }- /** Deleted in TREK; what happens upstream is the link's delete policy. */- | { kind: 'local_deleted'; itemId: number; remoteId: string }+ /**+ * Deleted in TREK; what happens upstream is the link's delete policy. With+ * `remoteGone`, the provider copy was already on record as missing and the+ * TREK copy has since been purged: the row closes, and no policy runs,+ * because there is nothing left on either side for it to act on.+ */+ | { kind: 'local_deleted'; itemId: number; remoteId: string; remoteGone?: true }/*** Back out of TREK's trash while the provider copy stayed: the pairing counts* again. With `missing`, the copy is gone and TREK did not bin it, so the row@@ -414,10 +435,26 @@ export function planReconcile(input: ReconcileInput): ReconcilePlan {if (it.fileId !== null) itemsByFile.set(it.fileId, it);}+ /**+ * A copy on record as gone whose TREK copy has been purged since.+ *+ * The row was kept for a person to decide about the TREK copy, and they+ * did: it is out of the trash and cannot come back, so nothing is left to+ * decide and nothing to restore. Only a purge closes the row. A TREK copy+ * merely in the trash keeps it open, because binning the gap as TREK's own+ * doing would let a later restore upload what somebody else deleted.+ */+ const goneOnBothSides = (it: SyncItemState): boolean =>+ it.state === 'remote_missing' && it.fileId === null && it.remoteId !== null;+// Upstream is unchanged: only what happened in TREK can need doing, and the// remote half of the plan would be reading a list the adapter did not fetch.if (input.remoteUnchanged) {for (const it of items) {+ if (goneOnBothSides(it)) {+ add({ kind: 'local_deleted', itemId: it.id, remoteId: it.remoteId, remoteGone: true });+ continue;+ }// A deletion already acted on stays acted on, as in the pair loop. A copy// on record as gone is absent from a full listing too, so a full run// plans nothing for it until it comes back; binning it here would also@@ -466,6 +503,21 @@ export function planReconcile(input: ReconcileInput): ReconcilePlan {r.contentHash !== null &&it.pushedSha256 !== null &&r.contentHash === it.pushedSha256;+ // The same reading for bytes both sides agreed on: a version marker moves+ // on a tag, a correspondent or a title as much as on a new revision, and+ // where the listing carries a hash it says which. Downloading the same+ // bytes again replaced the TREK file with a fresh row and sent the one+ // that carried the booking link to the trash, on every edit of metadata.+ // A row in error is left out: `touch` leaves that state alone, so it would+ // sit in error for good over bytes that are in step, while the download+ // it gets instead finds the same bytes and settles it without a new row.+ const sameBytes =+ remoteChanged &&+ r.contentHash !== null &&+ it.state !== 'error' &&+ it.contentSha256 !== null &&+ r.contentHash === it.contentSha256;+ const remoteBytesChanged = remoteChanged && !isEcho && !sameBytes;const localChanged = !!l && l.sha256 !== null && it.contentSha256 !== null && l.sha256 !== it.contentSha256;@@ -509,11 +561,11 @@ export function planReconcile(input: ReconcileInput): ReconcilePlan {continue;}- if (remoteChanged && !isEcho && localChanged) {+ if (remoteBytesChanged && localChanged) {settle(it, r, l ?? null);continue;}- if (remoteChanged && !isEcho) {+ if (remoteBytesChanged) {if (direction === 'push') { add({ kind: 'touch', itemId: it.id, remote: r }); continue; }add({ kind: 'pull_update', remote: r, itemId: it.id });continue;@@ -538,11 +590,19 @@ export function planReconcile(input: ReconcileInput): ReconcilePlan {// would have given it: a Paperless title with a slash in it used to land// in the file manager as it was, and the next run read that as a rename// made in TREK and sent it upstream again.+ //+ // TREK's own name goes through it too. An upload keeps whatever name the+ // browser sent, and on Linux and macOS that may hold a colon or a question+ // mark, which a push stores as the agreed name. Compared raw against the+ // cleaned agreed name, such a file read as renamed in TREK on every run:+ // Paperless got the same title again each time, and on Nextcloud, whose+ // own cleaning differs, the row sat in a conflict that "keep TREK" could+ // never settle.const incoming = sanitizeIncomingName(r.name);if (l && incoming !== l.name) {const agreed = it.remoteName === null ? null : sanitizeIncomingName(it.remoteName);const providerRenamed = agreed !== null && incoming !== agreed;- const localRenamed = agreed !== null && l.name !== agreed;+ const localRenamed = agreed !== null && sanitizeIncomingName(l.name) !== agreed;if (providerRenamed && !localRenamed && direction !== 'push') {add({ kind: 'rename_local', itemId: it.id, fileId: l.fileId, name: incoming });@@ -559,6 +619,12 @@ export function planReconcile(input: ReconcileInput): ReconcilePlan {settleName(it, r, l, incoming);continue;}+ if (agreed !== null && !providerRenamed && !localRenamed) {+ // Neither side renamed: the two names differ only by what the cleaning+ // did to one of them, and there is nothing to send anywhere.+ add({ kind: 'touch', itemId: it.id, remote: r });+ continue;+ }// No stored name to arbitrate with (a row from before this column, or a// freshly paired document): follow the binding's direction.if (direction === 'pull') add({ kind: 'rename_local', itemId: it.id, fileId: l.fileId, name: incoming });@@ -570,6 +636,14 @@ export function planReconcile(input: ReconcileInput): ReconcilePlan {add({ kind: 'touch', itemId: it.id, remote: r });}+ // ── Gone on both sides ────────────────────────────────────────────────────+ // A copy listed again went through the pair loop, where a purged file is a+ // deletion like any other.+ for (const it of items) {+ if (!goneOnBothSides(it) || remoteById.has(it.remoteId)) continue;+ add({ kind: 'local_deleted', itemId: it.id, remoteId: it.remoteId, remoteGone: true });+ }+// ── Upstream only ─────────────────────────────────────────────────────────if (direction !== 'push') {for (const r of remote) {diff --git a/server/src/nest/doc-sync/doc-sync.service.ts b/server/src/nest/doc-sync/doc-sync.service.tsindex e88f1ba45..35d7f139a 100644--- a/server/src/nest/doc-sync/doc-sync.service.ts+++ b/server/src/nest/doc-sync/doc-sync.service.ts@@ -13,7 +13,7 @@ import { StorageService } from '../storage/storage.service';import { FilesService } from '../files/files.service';import { AllowedFileTypesService } from '../files/allowed-file-types.service';import { RealtimeService } from '../realtime/realtime.service';-import { MAX_FILE_SIZE } from '../files/files.constants';+import { MAX_FILE_SIZE, isVideoExtension } from '../files/files.constants';import { DocumentProviderRegistry } from './document-provider.registry';import { DocSyncConfigService, type ConnectionRow, type LinkRow } from './doc-sync-config.service';import type { DocumentProvider, RemoteDocument } from './document-provider';@@ -357,7 +357,10 @@ export class DocSyncService {return 'ok';}case 'local_deleted': {- const binned = ctx.link.delete_policy === 'trash';+ // A copy already gone upstream cannot be binned, and asking would only+ // fail the run for a document that no longer exists anywhere.+ const remoteGone = action.remoteGone === true;+ const binned = ctx.link.delete_policy === 'trash' && !remoteGone;if (binned) {const res = await ctx.provider.trash(ctx.ref, ctx.scope, action.remoteId);if (docFailed(res)) return res.error.code;@@ -366,15 +369,18 @@ export class DocSyncService {// `local_deleted` row alone, so a policy changed later cannot reach// back. Whether TREK binned the copy is written down with it, because a// restore in TREK later has to know whether the gap upstream is TREK's.+ // A copy on record as gone stays on record: the holdings count reads+ // the mark, and the copy is no more at the store than it was before.this.db.connection.prepare(`UPDATE document_sync_items- SET state = 'local_deleted', remote_missing_at = NULL,+ SET state = 'local_deleted',+ remote_missing_at = CASE WHEN ? = 1 THEN remote_missing_at ELSE NULL END,remote_trashed_at = CASE WHEN ? = 1 THEN CURRENT_TIMESTAMP ELSE NULL END,last_seen_at = CURRENT_TIMESTAMPWHERE id = ?`,)- .run(binned ? 1 : 0, action.itemId);+ .run(remoteGone ? 1 : 0, binned ? 1 : 0, action.itemId);return 'ok';}case 'local_restored': {@@ -448,14 +454,18 @@ export class DocSyncService {remote: RemoteDocument,itemId: number | null,ctx: { provider: DocumentProvider; ref: ReturnType<DocSyncConfigService['toRef']>; scope: ReturnType<DocSyncConfigService['toScopeRef']>; link: LinkRow },- ): Promise<'pulled' | DocsyncErrorCode> {+ ): Promise<'pulled' | 'ok' | DocsyncErrorCode> {const name = sanitizeIncomingName(remote.name);// The same defences an upload goes through. A provider folder routinely// holds .svg and .html, and TREK serves downloads inline with a// Content-Type derived from the extension: letting those through would be// stored XSS. Rejected documents become a visible row, never a silent skip.- if (isBlockedName(name) || !isAllowedByOperator(name, this.allowedTypes.get())) {+ // Video is admitted the way the upload admits it, whatever the operator's+ // list says: a clip the file manager takes must not come back as refused+ // when it arrives through the store instead.+ const allowed = isVideoExtension(path.extname(name)) || isAllowedByOperator(name, this.allowedTypes.get());+ if (isBlockedName(name) || !allowed) {this.upsertItem(ctx.link, { itemId, remote, state: 'rejected_type', errorCode: 'unsupported_type' });return 'unsupported_type';}@@ -499,6 +509,36 @@ export class DocSyncService {}const sha256 = hash.digest('hex');++ // What this row pointed at before, if anything: a pull_update replaces a+ // document TREK already holds, and `createFile` only ever inserts.+ const pairing = itemId === null+ ? undefined+ : (this.db.connection+ .prepare('SELECT file_id, remote_name, content_sha256 FROM document_sync_items WHERE id = ?')+ .get(itemId) as { file_id: number | null; remote_name: string | null; content_sha256: string | null } | undefined);+ const supersededId = pairing?.file_id ?? null;+ const superseded = supersededId === null ? undefined : this.files.getFileById(supersededId, ctx.link.trip_id);++ // The bytes TREK already holds, under a version marker that moved on+ // metadata: Paperless bumps it for a tag or a correspondent as much as for+ // a new revision, and not every listing carries a hash the planner could+ // have read this off. Nothing to replace, so the file stays, and with it+ // the booking it hangs on. The agreed name stays too: a rename that came+ // with the edit is the planner's business next run, and moving the arbiter+ // here would read it as TREK's own and send the old name back up.+ if (superseded && !superseded.deleted_at && pairing?.content_sha256 === sha256) {+ await fs.promises.rm(tmpPath, { force: true });+ this.upsertItem(ctx.link, {+ itemId,+ remote,+ state: 'synced',+ remoteNameOverride: pairing.remote_name ?? undefined,+ errorCode: null,+ });+ return 'ok';+ }+try {await this.storage.put('files', storageKey, { tmpPath });} catch {@@ -507,14 +547,6 @@ export class DocSyncService {return 'provider_error';}- // What this row pointed at before, if anything: a pull_update replaces a- // document TREK already holds, and `createFile` only ever inserts.- const supersededId = itemId === null- ? null- : (this.db.connection- .prepare('SELECT file_id FROM document_sync_items WHERE id = ?')- .get(itemId) as { file_id: number | null } | undefined)?.file_id ?? null;-/*** The file row, the retirement of the copy it replaces and the pairing are* one fact, so they are one transaction. Written separately, a crash@@ -524,7 +556,9 @@ export class DocSyncService {** The superseded copy goes to the trash rather than out of existence: the* bytes it holds are a version somebody may still want, and TREK's own- * delete works the same way.+ * delete works the same way. What it was attached to goes to the new row:+ * a new revision is the same document to the trip, and without this every+ * edit in the store quietly took the attachment off its booking.*/const { created, retired } = this.db.transaction(() => {const file = this.files.createFile(@@ -533,10 +567,24 @@ export class DocSyncService {// Attributed to the person whose connection brought it in, which is the// only honest answer: nobody in TREK uploaded it.this.config.getConnection(ctx.link.connection_id)?.owner_user_id ?? 0,- {},+ {+ place_id: superseded?.place_id ?? null,+ reservation_id: superseded?.reservation_id ?? null,+ description: superseded?.description ?? null,+ },);const gone = supersededId !== null && Number(supersededId) !== Number(file.id);- if (gone) this.files.softDeleteFile(supersededId as number);+ const starred = gone && !!superseded?.starred;+ if (gone) {+ if (starred) this.db.connection.prepare('UPDATE trip_files SET starred = 1 WHERE id = ?').run(file.id);+ this.db.connection+ .prepare(+ `INSERT OR IGNORE INTO file_links (file_id, reservation_id, assignment_id, place_id, budget_item_id)+ SELECT ?, reservation_id, assignment_id, place_id, budget_item_id FROM file_links WHERE file_id = ?`,+ )+ .run(file.id, supersededId);+ this.files.softDeleteFile(supersededId as number);+ }this.upsertItem(ctx.link, {itemId,remote,@@ -545,7 +593,7 @@ export class DocSyncService {contentSha256: sha256,errorCode: null,});- return { created: file, retired: gone ? (supersededId as number) : null };+ return { created: starred ? { ...file, starred: 1 } : file, retired: gone ? (supersededId as number) : null };});// Announced only once it is committed: a rolled-back transaction that had@@ -1077,7 +1125,10 @@ export class DocSyncService {.prepare(`SELECT link_id,SUM(CASE WHEN file_id IS NOT NULL AND remote_id IS NOT NULL AND state = 'synced' THEN 1 ELSE 0 END) AS paired,+ -- A deletion closed over a copy already gone keeps its missing mark,+ -- and that copy is at the store no more than a binned one is.SUM(CASE WHEN remote_id IS NOT NULL AND state != 'remote_missing' AND remote_trashed_at IS NULL+ AND (state != 'local_deleted' OR remote_missing_at IS NULL)THEN 1 ELSE 0 END) AS atProvider,SUM(CASE WHEN state = 'remote_missing' THEN 1 ELSE 0 END) AS missingFROM document_sync_itemsdiff --git a/server/src/nest/doc-sync/providers/paperless.provider.ts b/server/src/nest/doc-sync/providers/paperless.provider.tsindex dd2d939ee..c4fe58366 100644--- a/server/src/nest/doc-sync/providers/paperless.provider.ts+++ b/server/src/nest/doc-sync/providers/paperless.provider.ts@@ -176,6 +176,15 @@ export function documentFileName(doc: PaperlessDocument): string {return base.toLowerCase().endsWith(extension) ? base : `${base}${extension}`;}+/**+ * The longest title Paperless stores. `Document.title` is a 128-character+ * column, and a PATCH with more is refused with a validation error that reaches+ * TREK as a bare provider_error, on every run, for as long as the name stays+ * that long. The consumer trims an upload's title on its own; the rename path+ * has to do it here.+ */+export const PAPERLESS_TITLE_MAX_LENGTH = 128;+/*** The title for a file name. Only an extension this adapter would have ADDED is* removed, so a document genuinely called `Vertrag 2026.2` keeps its name.@@ -183,9 +192,16 @@ export function documentFileName(doc: PaperlessDocument): string {export function titleFromFileName(name: string): string {const trimmed = name.trim();const extension = extensionOf(trimmed);- if (extension === null || !KNOWN_EXTENSIONS.has(extension)) return trimmed;- const base = trimmed.slice(0, trimmed.length - extension.length).trim();- return base.length > 0 ? base : trimmed;+ const base =+ extension === null || !KNOWN_EXTENSIONS.has(extension)+ ? trimmed+ : trimmed.slice(0, trimmed.length - extension.length).trim();+ const title = base.length > 0 ? base : trimmed;+ // Counted in code points, the way Paperless counts them: a cut by UTF-16+ // units would split a surrogate pair and send a title Paperless cannot store.+ const glyphs = [...title];+ if (glyphs.length <= PAPERLESS_TITLE_MAX_LENGTH) return title;+ return glyphs.slice(0, PAPERLESS_TITLE_MAX_LENGTH).join('').trim();}export function formatScopeKey(tagId: number): string {diff --git a/server/src/nest/doc-sync/providers/provider-http.ts b/server/src/nest/doc-sync/providers/provider-http.tsindex bf87a52eb..0b6f39316 100644--- a/server/src/nest/doc-sync/providers/provider-http.ts+++ b/server/src/nest/doc-sync/providers/provider-http.ts@@ -88,6 +88,19 @@ const CERTIFICATE_CODES = new Set([]);const CERTIFICATE_CODE = /CERT|SELF_SIGNED|ERR_TLS/i;+/**+ * The guard's own wording for a name DNS could not resolve. It arrives as an+ * SsrfBlockedError like every other refusal, but nothing was blocked: there is+ * no address to block. Reporting it as a policy verdict sends the self-hoster+ * to the SSRF settings when the fault is a typo in the host name.+ */+const UNRESOLVED_HOST = /could not resolve hostname/i;++/** Whether a guard refusal is really a host that does not exist. */+export function isUnresolvedHost(message: string): boolean {+ return UNRESOLVED_HOST.test(message);+}+/*** The codes every product answers alike. A client layers its own meaning on* top through `overrides`, and `fallback` answers whatever neither table knows.@@ -128,7 +141,9 @@ export function classifyTransportFailure(err: unknown): TransportFailure {.filter((message) => message.length > 0).join(': ');- if (err instanceof SsrfBlockedError) return { code: 'ssrf_blocked', detail };+ if (err instanceof SsrfBlockedError) {+ return { code: isUnresolvedHost(err.message) ? 'unreachable' : 'ssrf_blocked', detail };+ }const codes = chain.map(codeOf);const names = chain.map((entry) => (entry instanceof Error ? entry.name : ''));diff --git a/server/src/nest/doc-sync/providers/synology-drive.provider.ts b/server/src/nest/doc-sync/providers/synology-drive.provider.tsindex 0fa81b6ac..4c6bac610 100644--- a/server/src/nest/doc-sync/providers/synology-drive.provider.ts+++ b/server/src/nest/doc-sync/providers/synology-drive.provider.ts@@ -426,6 +426,16 @@ export class SynologyDriveDocumentProvider implements DocumentProvider {return docFail('provider_error', 'The resulting file path is not one DSM accepts');}+ // Without a remoteId a name collision is a real conflict: the file at+ // that path is somebody else's, and overwriting it would destroy it+ // silently. The path is asked before a byte moves, because a successful+ // upload says nothing about a file that was already there, and the+ // checks below would read one as a transfer that arrived broken and+ // send the whole file again on every retry.+ if (req.remoteId === undefined && (await this.exists(creds, targetPath))) {+ return docFail('conflict', `${targetPath} already exists on the NAS`);+ }+await this.client.upload(creds, {folderPath,fileName,@@ -433,9 +443,9 @@ export class SynologyDriveDocumentProvider implements DocumentProvider {size: req.size,mimeType: req.mimeType,mtimeSeconds: req.mtimeSeconds,- // Replacing is only ever what the caller asked for. Without a remoteId a- // name collision is a real conflict: the file at that path is somebody- // else's, and overwriting it would destroy it silently.+ // Replacing is only ever what the caller asked for. For a new file the+ // flag stays off, so a namesake that appeared since the check above is+ // not overwritten either.overwrite: req.remoteId !== undefined,createParents: true,});@@ -517,16 +527,15 @@ export class SynologyDriveDocumentProvider implements DocumentProvider {const path = this.requireInScope(scope, remoteId);const trashPath = joinSynoPath(scopePath, TRASH_FOLDER);await this.client.createFolder(creds, scopePath, TRASH_FOLDER);- try {- await this.client.move(creds, path, trashPath, { overwrite: false });- } catch (error: unknown) {- if (!(error instanceof SynologyDriveError) || error.code !== 'conflict') throw error;+ if (!(await this.moveIntoBin(creds, path, trashPath))) {// A file of that name is already in the bin. Overwriting it would throw// away the older copy, which is the one thing a bin exists to prevent,// so the older copy steps aside under a timestamped name.const occupant = joinSynoPath(trashPath, baseName(path));await this.client.rename(creds, occupant, this.archivedName(baseName(path)));- await this.client.move(creds, path, trashPath, { overwrite: false });+ if (!(await this.moveIntoBin(creds, path, trashPath))) {+ return docFail('conflict', `${path} is still in place after the bin made room for it`);+ }}return docOk(undefined);} catch (error: unknown) {@@ -534,6 +543,37 @@ export class SynologyDriveDocumentProvider implements DocumentProvider {}}+ /**+ * One attempt to move a file into the bin without overwriting a namesake.+ *+ * False means something of that name is in the way. DSM can say so with a+ * conflict, but a task that finished is only its word that the task ran, not+ * that the file left its folder, so the source is asked afterwards: a file+ * that is still there was not moved, whatever the task reported. Reporting+ * success on its word alone would mark the document as binned in TREK while+ * every NAS user still sees it in the trip's folder.+ */+ private async moveIntoBin(creds: SynologyDriveCreds, path: string, trashPath: string): Promise<boolean> {+ try {+ await this.client.move(creds, path, trashPath, { overwrite: false });+ } catch (error: unknown) {+ if (error instanceof SynologyDriveError && error.code === 'conflict') return false;+ throw error;+ }+ return !(await this.exists(creds, path));+ }++ /** Whether the NAS has an entry at that path. A folder counts: nothing can be uploaded over one. */+ private async exists(creds: SynologyDriveCreds, path: string): Promise<boolean> {+ try {+ await this.client.getInfo(creds, path);+ return true;+ } catch (error: unknown) {+ if (error instanceof SynologyDriveError && error.code === 'not_found') return false;+ throw error;+ }+ }+/** `boarding.pdf` → `boarding.1789745537.pdf`, keeping the extension readable. */private archivedName(name: string): string {const stamp = Math.floor(Date.now() / 1000);diff --git a/server/src/nest/doc-sync/providers/webdav.client.ts b/server/src/nest/doc-sync/providers/webdav.client.tsindex eb96ddbeb..cfbebeef8 100644--- a/server/src/nest/doc-sync/providers/webdav.client.ts+++ b/server/src/nest/doc-sync/providers/webdav.client.ts@@ -48,8 +48,20 @@ import { DOWNLOAD_MAX_BYTES, guardDownload, providerFetch, statusErrorCode } froexport type WebdavFlavor = 'nextcloud' | 'opencloud';export interface WebdavCreds {- /** Instance origin, already normalised: no trailing slash, no DAV suffix. */+ /**+ * Where the instance lives, already normalised: no trailing slash, no DAV+ * suffix. It carries the install's own path when there is one, so+ * `https://home.example.com/nextcloud` is as good a base as an origin, and+ * every request path is appended to it as is.+ */origin: string;+ /**+ * The path part of `origin` (`/nextcloud`), absent for an install at the+ * root. The instance spells that prefix into every href it answers, and it+ * comes off again before the href is used as a request path, or the next+ * request would go to `/nextcloud/nextcloud/remote.php/...`.+ */+ prefix?: string;username: string;password: string;allowInsecureTls: boolean;@@ -79,7 +91,7 @@ export class WebdavError extends Error {/** One `<d:response>` of a PROPFIND, reduced to what the sync core reads. */export interface WebdavEntry {- /** Path portion of the `d:href`, still percent-encoded, as sent. */+ /** Path portion of the `d:href`, still percent-encoded, with the install's prefix taken off. */href: string;/** The same path decoded, for comparing against a requested path. */path: string;@@ -112,8 +124,8 @@ export interface WebdavDrive {* Path of `root.webDavUrl`, never its origin: the instance answers with its* own configured `OC_URL` (`https://localhost:8804` for a host reached as* 127.0.0.1), and following a host that an untrusted response chose is how an- * SSRF guard gets walked around. Only the path survives, re-based on the- * connection's own origin.+ * SSRF guard gets walked around. Only the path survives, minus the install's+ * prefix, re-based on the connection's own origin.*/webDavPath: string;}@@ -193,11 +205,15 @@ export function normalizeFileId(raw: string | null, flavor: WebdavFlavor): strin}/**- * What a user pastes into the URL field, reduced to an origin.+ * What a user pastes into the URL field, reduced to the instance's base.*- * People paste the address bar of their own file list, so the DAV and Graph- * prefixes come off rather than turning into `/remote.php/dav/remote.php/dav`- * 404s, which read like a wrong password.+ * People paste the address bar of their own file list, so the DAV, Graph and+ * web-app prefixes come off rather than turning into+ * `/remote.php/dav/remote.php/dav` 404s, which read like a wrong password.+ * What stays is the install's own path, if it has one: a Nextcloud under+ * `/nextcloud` is addressed there, not at the host's root. Only the two pages+ * a browser lands on are cut, the file list and the dashboard: a bare `/apps`+ * rule would also eat an install that lives under `/apps/nextcloud`.*/export function normalizeOrigin(baseUrl: string): string {return baseUrl@@ -205,11 +221,29 @@ export function normalizeOrigin(baseUrl: string): string {.replace(/[?#].*$/, '').replace(/\/+$/, '').replace(/\/(?:remote|index)\.php(?:\/.*)?$/i, '')+ .replace(/\/apps\/(?:files|dashboard)(?:\/.*)?$/i, '').replace(/\/dav\/spaces(?:\/.*)?$/i, '').replace(/\/graph(?:\/.*)?$/i, '').replace(/\/+$/, '');}+/**+ * A path the instance answered, minus the install's own prefix, so it can be+ * appended to `creds.origin` again. A path that does not start with the prefix+ * is left alone: an instance that answers hrefs relative to the host root+ * while being reached through a proxy path is not something to guess at.+ */+export function stripPrefix(path: string, prefix: string): string {+ if (!prefix) return path;+ if (path === prefix) return '/';+ return path.startsWith(`${prefix}/`) ? path.slice(prefix.length) : path;+}++/** The install's prefix on this connection, '' when it lives at the host root. */+export function prefixOf(creds: WebdavCreds): string {+ return creds.prefix ?? '';+}+/** Percent-encode each segment of a decoded path, keeping the separators. */export function encodePath(path: string): string {return path@@ -246,13 +280,17 @@ function hrefPathname(href: string): string {}}-/** The still-encoded path of an href, which is what the next request is built from. */-function hrefPath(href: string): string {- return /^https?:\/\//i.test(href) ? hrefPathname(href) : href;+/**+ * The still-encoded path of an href, which is what the next request is built+ * from: relative to the install, with the prefix the instance spelled into it+ * taken off again.+ */+function hrefPath(href: string, prefix: string): string {+ const path = /^https?:\/\//i.test(href) ? hrefPathname(href) : href;+ return stripPrefix(path, prefix);}-function decodeHrefPath(href: string): string {- const raw = hrefPath(href);+function decodePath(raw: string): string {try {return normalizePath(decodeURIComponent(raw));} catch {@@ -260,6 +298,10 @@ function decodeHrefPath(href: string): string {}}+function decodeHrefPath(href: string, prefix: string): string {+ return decodePath(hrefPath(href, prefix));+}+/*** 405 is MKCOL on an existing collection, 412 a failed If-Match, 423 a locked* node: with 409, four ways of saying the caller's picture of the remote is@@ -348,12 +390,13 @@ function sha256Of(checksums: unknown): string | null {return null;}-function entryOf(response: Record<string, unknown>, flavor: WebdavFlavor): WebdavEntry | null {+function entryOf(response: Record<string, unknown>, creds: WebdavCreds): WebdavEntry | null {const href = textOf(response.href);if (!href) return null;+ const prefix = prefixOf(creds);const props = propsOf(response);- const path = decodeHrefPath(href);+ const path = decodeHrefPath(href, prefix);const segments = path.split('/');const length = textOf(props.getcontentlength);const modified = textOf(props.getlastmodified);@@ -362,12 +405,12 @@ function entryOf(response: Record<string, unknown>, flavor: WebdavFlavor): Webdaconst resourceType = asRecord(props.resourcetype);return {- href: hrefPath(href),+ href: hrefPath(href, prefix),path,name: segments[segments.length - 1] ?? '',isCollection: resourceType !== null && 'collection' in resourceType,etag: textOf(props.getetag) ?? '',- fileId: normalizeFileId(textOf(props.fileid), flavor),+ fileId: normalizeFileId(textOf(props.fileid), creds.flavor),size: length !== null && length !== '' && Number.isFinite(Number(length)) ? Number(length) : null,mimeType: mimeType ? mimeType.split(';')[0].trim() : null,lastModifiedIso:@@ -376,16 +419,17 @@ function entryOf(response: Record<string, unknown>, flavor: WebdavFlavor): Webda};}-function toDrive(value: unknown): WebdavDrive | null {+function toDrive(value: unknown, prefix: string): WebdavDrive | null {const record = asRecord(value);const id = textOf(record?.id);if (!record || !id) return null;const webDavUrl = textOf(asRecord(record.root)?.webDavUrl);+ const webDavPath = webDavUrl ? davPathOf(webDavUrl) : null;return {id,name: textOf(record.name) ?? id,driveType: textOf(record.driveType) ?? '',- webDavPath: (webDavUrl ? davPathOf(webDavUrl) : null) ?? `/dav/spaces/${encodeURIComponent(id)}`,+ webDavPath: webDavPath === null ? `/dav/spaces/${encodeURIComponent(id)}` : stripPrefix(webDavPath, prefix),};}@@ -469,7 +513,7 @@ export class WebdavClient {const entries: WebdavEntry[] = [];for (const element of asArray(multistatus.response)) {const record = asRecord(element);- const entry = record ? entryOf(record, creds.flavor) : null;+ const entry = record ? entryOf(record, creds) : null;if (entry) entries.push(entry);}if (entries.length === 0) {@@ -478,8 +522,9 @@ export class WebdavClient {// RFC 4918 puts the requested resource first, but it is matched by path// rather than trusted by position: the root must never end up in the- // document list, and one misordered server would put it there.- const wanted = decodeHrefPath(path);+ // document list, and one misordered server would put it there. The+ // requested path never carried the prefix, so it is only decoded.+ const wanted = decodePath(path);const selfIndex = Math.max(entries.findIndex((entry) => entry.path === wanted),0,@@ -670,7 +715,7 @@ export class WebdavClient {const parsed = asRecord(await this.graph(creds, 'GET', '/graph/v1.0/me/drives'));const drives: WebdavDrive[] = [];for (const value of asArray(parsed?.value)) {- const drive = toDrive(value);+ const drive = toDrive(value, prefixOf(creds));if (drive) drives.push(drive);}return drives;@@ -679,7 +724,10 @@ export class WebdavClient {/** One space, or null when it is gone, which is what makes `scope_missing` detectable. */async getDrive(creds: WebdavCreds, driveId: string): Promise<WebdavDrive | null> {try {- return toDrive(await this.graph(creds, 'GET', `/graph/v1.0/drives/${encodeURIComponent(driveId)}`));+ return toDrive(+ await this.graph(creds, 'GET', `/graph/v1.0/drives/${encodeURIComponent(driveId)}`),+ prefixOf(creds),+ );} catch (err: unknown) {if (err instanceof WebdavError && err.status === 404) return null;throw err;@@ -689,6 +737,7 @@ export class WebdavClient {async createDrive(creds: WebdavCreds, name: string): Promise<WebdavDrive> {const drive = toDrive(await this.graph(creds, 'POST', '/graph/v1.0/drives', { name, driveType: 'project' }),+ prefixOf(creds),);if (!drive) {throw new WebdavError('provider_error', 'OpenCloud created a space it then described incompletely');diff --git a/server/src/nest/doc-sync/providers/webdav.provider.ts b/server/src/nest/doc-sync/providers/webdav.provider.tsindex 11e900503..3975d8861 100644--- a/server/src/nest/doc-sync/providers/webdav.provider.ts+++ b/server/src/nest/doc-sync/providers/webdav.provider.ts@@ -21,6 +21,8 @@ import {encodePath,normalizeOrigin,normalizePath,+ prefixOf,+ stripPrefix,type WebdavCreds,type WebdavEntry,type WebdavFlavor,@@ -113,10 +115,20 @@ export function flavorOf(conn: DocumentConnectionRef): WebdavFlavor | null {return null;}+/**+ * A usable base: scheme and host, then the install's own path if it has one.+ * The second group is that path (`/nextcloud`), or '' for an install at the+ * root, which is what most Docker and snap setups are. A Nextcloud under a+ * sub-path is the ordinary package install, and refusing it here used to read+ * as "wrong password" on the settings screen.+ */+const BASE_URL = /^(https?:\/\/[^/]+)((?:\/[^/]+)*)$/i;+function credsOf(conn: DocumentConnectionRef): WebdavCreds | null {const flavor = flavorOf(conn);const origin = normalizeOrigin(conn.baseUrl);- if (!flavor || !/^https?:\/\/[^/]+$/i.test(origin)) return null;+ const base = BASE_URL.exec(origin);+ if (!flavor || !base) return null;const username =flavor === 'nextcloud'@@ -128,7 +140,7 @@ function credsOf(conn: DocumentConnectionRef): WebdavCreds | null {: textSetting(conn.secrets, 'app_token');if (!username || !password) return null;- return { origin, username, password, allowInsecureTls: conn.allowInsecureTls, flavor };+ return { origin, prefix: base[2], username, password, allowInsecureTls: conn.allowInsecureTls, flavor };}/** `/remote.php/dav/files/<login>`: the per-account root of Nextcloud's file DAV. */@@ -759,9 +771,11 @@ export class WebdavDocumentProvider implements DocumentProvider {// The stored root is the space's own webDavUrl. Only its path is used, and// it is re-based on the connection's origin: the URL came out of a provider// response, and following the host in it would hand an attacker who can- // answer for that instance a way past the SSRF guard.+ // answer for that instance a way past the SSRF guard. The origin already+ // carries the install's prefix, so the path is stored with it and loses it+ // here, or the request would spell it twice.const path = scope.remoteRootPath ? davPathOf(scope.remoteRootPath) : null;- const rootPath = path ?? `/dav/spaces/${encodeURIComponent(scopeId)}`;+ const rootPath = path === null ? `/dav/spaces/${encodeURIComponent(scopeId)}` : stripPrefix(path, prefixOf(creds));let decoded: string;try {decoded = normalizePath(decodeURIComponent(rootPath));diff --git a/server/src/nest/integrations/airtrail.service.ts b/server/src/nest/integrations/airtrail.service.tsindex 253084b49..579c8ac40 100644--- a/server/src/nest/integrations/airtrail.service.ts+++ b/server/src/nest/integrations/airtrail.service.ts@@ -156,6 +156,13 @@ export class AirtrailService {/*** "Test connection" from the settings form. Uses the typed URL/key when given;* falls back to the stored key when the key field still shows the mask.+ *+ * The stored key only for the origin it was stored against. The form prefills+ * the address and never the key, so retyping the address and pressing Test is+ * the ordinary way to move an instance, and a test button that carried the+ * stored key to whatever address was just typed would post the credential at+ * a stranger's server. A path edit on the same origin is the same instance+ * and keeps it.*/async testConnection(userId: number,@@ -168,7 +175,15 @@ export class AirtrailService {const stored = this.getAirtrailCredentials(userId);const effectiveUrl = trimmedUrl || stored?.baseUrl;- const effectiveKey = provided && provided !== KEY_MASK ? provided : stored?.apiKey;+ const typedKey = provided && provided !== KEY_MASK ? provided : '';++ if (!typedKey && stored && movedHost(stored.baseUrl, trimmedUrl)) {+ return {+ connected: false,+ error: `The stored key was issued for ${stored.baseUrl}. Enter the key for this address to test it.`,+ };+ }+ const effectiveKey = typedKey || stored?.apiKey;if (!effectiveUrl || !effectiveKey) {return { connected: false, error: 'URL and API key required' };@@ -190,3 +205,21 @@ export class AirtrailService {return raw.map(normalizeFlight);}}++/**+ * Does the typed address point at a different AirTrail instance than the stored one?+ *+ * Scheme, host and port, because that is what decides where a credential is+ * sent. A path change ("/", "/api", a typo) is the same instance. Anything+ * unparseable is compared as written, which errs towards withholding the key+ * rather than shipping it somewhere new. An empty address is no move at all:+ * the stored one stands in for it.+ */+function movedHost(before: string | null, after: string): boolean {+ if (!before || !after) return false;+ try {+ return new URL(before).origin !== new URL(after).origin;+ } catch {+ return before !== after;+ }+}diff --git a/server/src/nest/integrations/dawarich-suggestions.service.ts b/server/src/nest/integrations/dawarich-suggestions.service.tsindex 57b50fdc8..28b281455 100644--- a/server/src/nest/integrations/dawarich-suggestions.service.ts+++ b/server/src/nest/integrations/dawarich-suggestions.service.ts@@ -579,11 +579,17 @@ export class DawarichSuggestionsService {if (!creds) throw new AcceptError('not_connected', 'Dawarich is not connected', 400);const countries = await this.client.listVisitedCities(creds, from, to);- const visited = new Set(- this.db- .all<{ country_code: string }>('SELECT country_code FROM visited_countries WHERE user_id = ?', userId)- .map((r) => r.country_code.toUpperCase()),- );++ // "Already on the map" is what the Atlas itself paints as visited: the+ // countries a finished trip's places resolve to, a booking landed in, or a+ // hand mark added, minus the ones the user removed. Reading only the hand+ // marks would offer somebody their own past trips as news.+ const visited = new Set<string>();+ for (const country of (await this.atlas.stats(userId)).countries) {+ // The shape for a user without trips carries no status; everything in it+ // is a hand mark, which the Atlas draws as visited.+ if (!('status' in country) || country.status === 'visited') visited.add(country.code.toUpperCase());+ }const resolved: DawarichAtlasCountry[] = [];const unresolved: string[] = [];diff --git a/server/src/nest/integrations/dawarich-sync.service.ts b/server/src/nest/integrations/dawarich-sync.service.tsindex 08d8f5dce..d22541f5c 100644--- a/server/src/nest/integrations/dawarich-sync.service.ts+++ b/server/src/nest/integrations/dawarich-sync.service.ts@@ -169,7 +169,7 @@ export class DawarichSyncService {if (!window) continue;try {- const result = await this.syncTripWindow(userId, trip.id, creds, window.from, window.to);+ const result = await this.syncTripWindow(userId, trip.id, creds, window.from, window.to, trips);created += result.created;updated += result.updated;missing += result.missing;@@ -234,6 +234,10 @@ export class DawarichSyncService {* it — so a changed-since filter, even if one existed, could never see a* deletion. Comparing the whole window against what TREK already holds is the* only thing that can.+ *+ * `trips` is every trip this run walks. A window reaches past its own trip+ * on both sides, so a stay can be fetched by two neighbouring trips, and the+ * one whose dates actually hold it is the one that gets it (see `tripForVisit`).*/async syncTripWindow(userId: number,@@ -241,6 +245,7 @@ export class DawarichSyncService {creds: DawarichCreds,from: Date,to: Date,+ trips: TripRow[] = [],): Promise<{ created: number; updated: number; missing: number }> {const { visits } = await this.client.listVisits(creds, from, to);@@ -268,6 +273,8 @@ export class DawarichSyncService {visit.countryCodeFromSource ??(visit.lat !== null && visit.lng !== null ? getCountryFromCoords(visit.lat, visit.lng) : null);+ const ownerTripId = tripForVisit(visit.localDate, tripId, existing?.trip_id ?? null, trips);+if (!existing) {this.db.run(`INSERT INTO dawarich_visit_suggestions@@ -277,7 +284,7 @@ export class DawarichSyncService {VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new', ?, ?, ?)`,userId,visit.sourceVisitId,- tripId,+ ownerTripId,visit.name,visit.lat,visit.lng,@@ -302,13 +309,15 @@ export class DawarichSyncService {if (existing.state === 'new') {// Nobody has acted on it yet, so the newest version of the source is- // simply the better suggestion. Overwriting here loses nothing.+ // simply the better suggestion. Overwriting here loses nothing, and+ // that includes the trip: a stay parked on a neighbour by an earlier+ // run moves to the trip whose dates hold it.this.db.run(`UPDATE dawarich_visit_suggestionsSET name = ?, lat = ?, lng = ?, started_at = ?, ended_at = ?, duration_minutes = ?,local_date = ?, source_status = ?, confidence = ?, confidence_band = ?,country_code = ?, source_hash = ?, source_missing_at = NULL,- trip_id = COALESCE(trip_id, ?), last_seen_at = ?+ trip_id = ?, last_seen_at = ?WHERE id = ?`,visit.name,visit.lat,@@ -322,7 +331,7 @@ export class DawarichSyncService {visit.confidenceBand,countryCode,hash,- tripId,+ ownerTripId,new Date().toISOString(),existing.id,);@@ -520,6 +529,47 @@ interface TripRow {interface SuggestionRow {id: number;+ trip_id: number | null;state: string;source_hash: string;}++/**+ * Does the trip's own span, not its widened window, hold this local date?+ *+ * Plain string order, because both sides are `YYYY-MM-DD`. A start that is not+ * a date at all covers nothing: `syncWindow` skips such a trip, and it must+ * not claim other trips' stays from the sidelines either.+ */+function tripCovers(trip: TripRow, localDate: string): boolean {+ if (!trip.start_date || !Number.isFinite(Date.parse(`${trip.start_date}T00:00:00Z`))) return false;+ if (localDate < trip.start_date) return false;+ return !trip.end_date || localDate <= trip.end_date;+}++/**+ * The trip a stay belongs to.+ *+ * Every window is padded by the lookback, so two trips a few days apart both+ * fetch the last days of the earlier one, and whichever asked first would+ * otherwise keep those stays for good. The trip whose dates hold the stay+ * outranks the trip whose padding merely reached it. A row already sitting on+ * a trip that covers its date stays put, so two overlapping trips cannot hand+ * a stay back and forth on every run. A stay outside every trip, such as the+ * evening before departure, keeps the trip it has or goes to the window that+ * found it, exactly as before.+ */+function tripForVisit(+ localDate: string,+ currentTripId: number,+ existingTripId: number | null,+ trips: TripRow[],+): number {+ const existing = existingTripId === null ? undefined : trips.find((t) => t.id === existingTripId);+ if (existing && tripCovers(existing, localDate)) return existing.id;+ const current = trips.find((t) => t.id === currentTripId);+ if (current && tripCovers(current, localDate)) return current.id;+ const other = trips.find((t) => tripCovers(t, localDate));+ if (other) return other.id;+ return existingTripId ?? currentTripId;+}diff --git a/server/src/nest/integrations/dawarich.service.ts b/server/src/nest/integrations/dawarich.service.tsindex 20f0ecd30..6740bff6a 100644--- a/server/src/nest/integrations/dawarich.service.ts+++ b/server/src/nest/integrations/dawarich.service.ts@@ -169,14 +169,22 @@ export class DawarichService {// instance's credential somewhere it was never issued for, so the key goes// with the host — and only with the host: correcting a typo in the path,// or adding a trailing slash, keeps it.- if (newKey === undefined && movedHost(previousUrl, trimmedUrl)) {+ //+ // What the old instance answered goes with the host regardless of the+ // key: its probed capabilities and its sync history describe a server+ // this row no longer points at, and a fresh key does not make them true+ // of the new one.+ if (movedHost(previousUrl, trimmedUrl)) {this.db.run(`UPDATE dawarich_connections- SET api_key = NULL, capabilities = NULL, last_sync_state = 'never',+ SET capabilities = NULL, last_sync_state = 'never',last_sync_error = NULL, last_sync_at = NULLWHERE user_id = ?`,userId,);+ if (newKey === undefined) {+ this.db.run('UPDATE dawarich_connections SET api_key = NULL WHERE user_id = ?', userId);+ }}// Clearing the address leaves a key that can no longer be used for@@ -213,6 +221,11 @@ export class DawarichService {* Try the connection as it is about to be saved — with the typed key if there* is one, otherwise with the stored one.*+ * The stored one only for the host it was stored against. `saveSettings`+ * drops the key on a host change for a reason, and a test button that still+ * carried it to whatever address was just typed would post the credential+ * at a stranger's server before the save ever got the chance to refuse.+ ** Answers 200 with `connected: false` rather than throwing, because "wrong* key" is an answer the form has to render, not a server error.*/@@ -225,7 +238,16 @@ export class DawarichService {const typedKey = (apiKey || '').trim();const stored = this.getCredentials(userId);const baseUrl = (url || '').trim() || stored?.baseUrl || '';- const key = typedKey && typedKey !== DAWARICH_KEY_MASK ? typedKey : stored?.apiKey;+ const typed = typedKey && typedKey !== DAWARICH_KEY_MASK ? typedKey : '';++ if (!typed && stored && movedHost(stored.baseUrl, baseUrl)) {+ return {+ connected: false,+ error: 'not_connected',+ errorDetail: `The stored key was issued for ${stored.baseUrl}. Enter the key for this address to test it.`,+ };+ }+ const key = typed || stored?.apiKey;if (!baseUrl || !key) {return { connected: false, error: 'not_connected' };diff --git a/server/src/nest/maps/maps.helpers.ts b/server/src/nest/maps/maps.helpers.tsindex e07b555b7..0bec3b714 100644--- a/server/src/nest/maps/maps.helpers.ts+++ b/server/src/nest/maps/maps.helpers.ts@@ -740,8 +740,9 @@ export function parseWikipediaTag(tag: string | undefined | null): { lang: strinconst NON_GOOGLE_PLACE_ID =/^(?:coords|gers|node|way|relation|amap):|^https?:\/\/|^-?\d+(?:\.\d+)?,\s*-?\d+(?:\.\d+)?$|~p\d+$/i;// The subset that still has a provider behind it — Overpass for details,-// Wikimedia for photos.-export const OSM_PLACE_ID = /^(?:node|way|relation):/i;+// Wikimedia for photos. The id has to be the whole of what follows the colon:+// it is written into an Overpass query as it is, and an element id is a number.+export const OSM_PLACE_ID = /^(?:node|way|relation):\d+$/i;export function isGooglePlaceId(placeId: string): boolean {return !NON_GOOGLE_PLACE_ID.test(placeId);diff --git a/server/src/nest/maps/maps.service.ts b/server/src/nest/maps/maps.service.tsindex fbe65c17a..d5c2d0290 100644--- a/server/src/nest/maps/maps.service.ts+++ b/server/src/nest/maps/maps.service.ts@@ -495,6 +495,17 @@ async function flattenBrandLogo(bytes: Buffer): Promise<BrandLogo | null> {// day at the provider rather than a slow answer worth waiting for.const IDENTITY_TIMEOUT_MS = 2500;+// The explicit search asks Nominatim alongside the index, and the pair costs+// the slower one. The index gives up after 3.5 s and the browser after 8 s, so a+// Nominatim that accepts the connection and then sits on it (the public service+// under load, a self-hosted one that hung) has to give up in between: without a+// deadline of its own the request rides undici's 300 s default, and the index's+// answer is thrown away with the request that timed out waiting for it. The+// deadline starts after the throttle wait, so it measures the answer alone:+// generous for a slow one, still inside the browser's budget with the wait+// added on.+const SEARCH_TIMEOUT_MS = 6000;+const MAX_CONCURRENT_PHOTO_FETCHES = 5;let photoFetchActive = 0;const photoFetchQueue: Array<() => void> = [];@@ -1149,7 +1160,7 @@ export class MapsService {params.set('bounded', '0');}// Through the shared client: one throttle for the whole process.- const response = await nominatimFetch('search', params, { lane });+ const response = await nominatimFetch('search', params, { lane, timeoutMs: SEARCH_TIMEOUT_MS });if (!response.ok) {const text = await response.text().catch(() => '');throw new Error(@@ -1314,6 +1325,10 @@ export class MapsService {const typeMap: Record<string, string> = { node: 'node', way: 'way', relation: 'rel' };const oType = typeMap[osmType];if (!oType) return null;+ // The id is the one thing written into the query, and the query is a+ // language. An OSM element id is a number and nothing else; anything with+ // more in it is a statement of its own, sent under TREK's shared user agent.+ if (!/^\d+$/.test(osmId)) return null;const query = `[out:json][timeout:5];${oType}(${osmId});out tags;`;try {const res = await fetch('https://overpass-api.de/api/interpreter', {@@ -2338,6 +2353,10 @@ export class MapsService {// colon branch below, which would otherwise read "gers" as an OSM type// and ask Overpass for an element that does not exist.if (placeId.startsWith('gers:')) {+ // The switch is a deployment property, and off means nothing leaves for+ // the index: a place saved while it was on is still opened from what the+ // trip holds, not looked up again.+ if (!this.trekPlacesEnabled()) return { place: null };const found = await trekPlacesById(placeId.slice('gers:'.length)).catch(() => null);if (!found) return { place: null };@@ -2407,6 +2426,13 @@ export class MapsService {// OSM details: placeId is "node:123456" or "way:123456" etc.if (placeId.includes(':')) {+ // Only an element type with a numeric id is looked up. The id is written+ // into an Overpass query and a Nominatim lookup as it came in, and nothing+ // else with a colon in it (a legacy image URL, a coordinate pseudo-id) has+ // a details source: answering those with an empty record cost two+ // requests that could not succeed, and let anything after the colon be+ // sent as a query of its own.+ if (!OSM_PLACE_ID.test(placeId)) return { place: null };const [osmType, osmId] = placeId.split(':');// buildOsmDetails never yields name/address/coordinates — Nominatim is// always the source for those (Overpass contributes the tag-derived rest).diff --git a/server/src/nest/maps/trek-places.client.ts b/server/src/nest/maps/trek-places.client.tsindex 5881aea09..5913acf97 100644--- a/server/src/nest/maps/trek-places.client.ts+++ b/server/src/nest/maps/trek-places.client.ts@@ -159,6 +159,14 @@ async function getJson<T>(params: Record<string, string | number | undefined>,opts: { maxBytes?: number; timeoutMs?: number } = {},): Promise<T> {+ // TREK_PLACES_ENABLED=false is the operator's word that nothing leaves for+ // the index. Every caller checks it before asking, and this is the one place+ // every request passes, so a caller that did not is still stopped here. Ahead+ // of the breaker: a refusal says nothing about reachability.+ if (!readEnv().maps.trekPlacesEnabled) {+ throw new Error('TREK Places API is switched off on this instance');+ }+const url = new URL(trekPlacesBaseUrl() + path);for (const [k, v] of Object.entries(params)) {if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v));diff --git a/server/src/nest/place-enrichment/place-enrichment.service.ts b/server/src/nest/place-enrichment/place-enrichment.service.tsindex 050803397..ce22188d6 100644--- a/server/src/nest/place-enrichment/place-enrichment.service.ts+++ b/server/src/nest/place-enrichment/place-enrichment.service.ts@@ -14,6 +14,7 @@ import { safeFetchFollow } from '../../utils/ssrfGuard';import { DatabaseService } from '../database/database.service';import {MapsService,+ isGoogleMapsHost,readBrandIdentity,readWikiIdentity,withPhotoFetchSlot,@@ -182,6 +183,23 @@ function yesNo(value: unknown): 'yes' | 'no' | string | null {return typeof value === 'string' && value.trim() ? value.trim().toLowerCase() : null;}+/**+ * The Google Maps link a provider record carries, or nothing.+ *+ * The record comes with the request, and the link goes out labelled "Google"+ * on a description every user of the instance reads from the cache. So it has+ * to be a Google Maps address by shape, over http(s), and anything else is+ * dropped rather than linked.+ */+function googleMapsLink(value: unknown): string | null {+ if (typeof value !== 'string' || !placeWebsiteSchema.safeParse(value).success) return null;+ try {+ return isGoogleMapsHost(new URL(value).hostname) ? value : null;+ } catch {+ return null;+ }+}+/*** Turns the place's OpenStreetMap tags into the short facts the column shows.*@@ -342,14 +360,25 @@ export class PlaceEnrichmentService {// while the same building in OpenStreetMap carried all of it. Each field is// taken from whichever source actually has it rather than from one source// for everything.+ const ownFacts = collectFacts(details);const result: CachedEnrichment = {photos,description,- facts: mergeFacts(collectFacts(details), collectFacts(osmDetails)),+ facts: mergeFacts(ownFacts, collectFacts(osmDetails)),hours: collectHours(details) ?? collectHours(osmDetails),rating: collectRating(details) ?? collectRating(osmDetails),};- this.writeCache(placeId, lang, result);+ // The cache is keyed by place and language, so a row written here is what+ // every user of the instance sees for a week. An OpenStreetMap summary and+ // a menu link are the two things read straight off the request's own+ // `details` that become a link on every screen, and when the request+ // carried those, the text and the link are the caller's word rather than+ // the map's: fine to answer them with, not to serve to everyone else. The+ // row simply is not written, and the next request computes its own answer.+ // A summary or a link the lookup here fetched itself is the map's and keeps.+ const fromCaller = req.details != null+ && (description?.source === 'osm' || ownFacts.some((fact) => fact.url != null));+ if (!fromCaller) this.writeCache(placeId, lang, result);return result;}@@ -585,22 +614,21 @@ export class PlaceEnrichmentService {* The API fetches each page once, keeps the summary, and every instance reads* it from there. Only places carrying a GERS id can be looked up, which is* exactly the ones that came from the API in the first place.+ *+ * Asked of the index here, although the request's `details` carry the very+ * same field from the dialog's own lookup a moment earlier. The answer is+ * written into a cache the whole instance reads from for a week, and a+ * description with a link in it is the one thing in there that must not be+ * whatever the sender chose to put in the request body. One more short+ * lookup per place and week is the price of the text being the index's.*/- private async websiteDescription(- placeId: string,- details?: Record<string, unknown> | null,- ): Promise<PlaceDescription | null> {+ private async websiteDescription(placeId: string): Promise<PlaceDescription | null> {if (!placeId.startsWith('gers:')) return null;+ // Off means nothing leaves for the index, a saved place included.+ if (!this.maps.trekPlacesEnabled()) return null;try {- // The details lookup already fetched this place and now carries its- // description, so the ordinary path costs nothing. Asking again meant two- // full round trips to the index for one added place, each with its own- // timeout budget, for a field the first answer already contained.- const carried = (details as { description?: { text?: string; sourceUrl?: string } } | null | undefined)+ const got = (await trekPlacesById(placeId.slice(5)) as { description?: { text?: string; sourceUrl?: string } } | null)?.description;- const got = carried- ?? (await trekPlacesById(placeId.slice(5)) as { description?: { text?: string; sourceUrl?: string } } | null)- ?.description;const text = typeof got?.text === 'string' ? got.text.trim() : '';if (!text) return null;// Through the same allow-list a place's website goes through: this@@ -662,7 +690,7 @@ export class PlaceEnrichmentService {// exists, and it is published in JSON-LD or og:description precisely so// machines can read it. That covers roughly 43 percent of places, where the// encyclopaedias cover a fraction of a percent.- const fromSite = await this.websiteDescription(placeId, details);+ const fromSite = await this.websiteDescription(placeId);if (fromSite) return fromSite;const apiKey = this.maps.getMapsKey(userId);@@ -672,7 +700,7 @@ export class PlaceEnrichmentService {return {text: summary,source: 'google',- sourceUrl: typeof details?.google_maps_url === 'string' ? details.google_maps_url : null,+ sourceUrl: googleMapsLink(details?.google_maps_url),license: null,};}diff --git a/server/src/nest/places/places.controller.ts b/server/src/nest/places/places.controller.tsindex e151c5fce..2ee824448 100644--- a/server/src/nest/places/places.controller.ts+++ b/server/src/nest/places/places.controller.ts@@ -328,11 +328,16 @@ export class PlacesController {// A night booked at this place went with it, and took its partner booking and// that booking's expense along. Neither is covered by place:deleted, and an// expense linked by reservation_id is not one linkedExpenseIds finds.+ //+ // Sent to the deleting tab as well, on purpose. The socket id keeps a tab+ // from hearing back what it just did itself, and that tab only removed the+ // places: the booking and the expense went on the server alone, and a tab+ // that never hears about them keeps showing both until a reload.for (const reservationId of cancelled.reservationIds) {- this.places.broadcast(tripId, 'reservation:deleted', { reservationId }, socketId);+ this.places.broadcast(tripId, 'reservation:deleted', { reservationId }, undefined);}for (const itemId of [...expenseIds, ...cancelled.budgetItemIds]) {- this.places.broadcast(tripId, 'budget:deleted', { itemId }, socketId);+ this.places.broadcast(tripId, 'budget:deleted', { itemId }, undefined);}return { deleted, count: deleted.length };}@@ -503,11 +508,12 @@ export class PlacesController {// A night booked at this place went with it, and took its partner booking and// that booking's expense along. Neither is covered by place:deleted, and an// expense linked by reservation_id is not one linkedExpenseIds finds.+ // Without a socket id, so the deleting tab hears it too: see bulkDelete.for (const reservationId of cancelled.reservationIds) {- this.places.broadcast(tripId, 'reservation:deleted', { reservationId }, socketId);+ this.places.broadcast(tripId, 'reservation:deleted', { reservationId }, undefined);}for (const itemId of [...expenseIds, ...cancelled.budgetItemIds]) {- this.places.broadcast(tripId, 'budget:deleted', { itemId }, socketId);+ this.places.broadcast(tripId, 'budget:deleted', { itemId }, undefined);}return { success: true };}diff --git a/server/src/nest/places/places.mcp.ts b/server/src/nest/places/places.mcp.tsindex 531a2939e..740559c5a 100644--- a/server/src/nest/places/places.mcp.ts+++ b/server/src/nest/places/places.mcp.ts@@ -237,7 +237,7 @@ export class PlacesMcp {@Tool({name: 'delete_place',- description: 'Delete a place from a trip.',+ description: 'Delete a place from a trip. Removes its day assignments, its linked expenses and any nights booked at it, including each night\'s reservation and that reservation\'s expense. Warn the user before calling this on a hotel with a booking: it cannot be undone.',inputSchema: {tripId: z.number().int().positive(),placeId: z.number().int().positive(),@@ -413,7 +413,7 @@ export class PlacesMcp {@Tool({name: 'bulk_delete_places',- description: 'Delete multiple places from a trip at once. Removes all day assignments for each place as well. Warn the user before calling this — it cannot be undone.',+ description: 'Delete multiple places from a trip at once. Removes all day assignments for each place as well, plus each place\'s linked expenses and any nights booked at it, with their reservations and expenses. Warn the user before calling this: it cannot be undone.',inputSchema: {tripId: z.number().int().positive(),placeIds: z.array(z.number().int().positive()).min(1).max(200),diff --git a/server/src/nest/public-api/public-api.service.ts b/server/src/nest/public-api/public-api.service.tsindex 6281926d5..e212015d6 100644--- a/server/src/nest/public-api/public-api.service.ts+++ b/server/src/nest/public-api/public-api.service.ts@@ -136,6 +136,12 @@ export class PublicApiService {* `order_index` decides the sequence and is then dropped: it is a storage detail* that only means something relative to its siblings, and an array already* carries order.+ *+ * A booked night puts a stop of its own on its check-in day, so the route can+ * reach the hotel. That stop is the booking, not a place the traveller planned+ * to visit, and the booking is already reported in full under `accommodations`;+ * listed here as well it would read as two different intentions. Same rule as+ * the shortlist below.*/private placesByDay(tripId: number): Map<number, PublicApiPlace[]> {const rows = this.db.all<PlaceRow>(@@ -147,6 +153,7 @@ export class PublicApiService {JOIN places p ON p.id = da.place_idLEFT JOIN categories c ON c.id = p.category_idWHERE p.trip_id = ?+ AND da.accommodation_id IS NULLORDER BY da.day_id ASC, da.order_index ASC`,tripId,);diff --git a/server/src/nest/reservations/reservations.rpc.ts b/server/src/nest/reservations/reservations.rpc.tsindex 6786c8728..73a664d49 100644--- a/server/src/nest/reservations/reservations.rpc.ts+++ b/server/src/nest/reservations/reservations.rpc.ts@@ -38,7 +38,7 @@ export class ReservationsRpc {const input = parsed.data as Record<string, unknown>;this.requireValidEndpoints(input.endpoints);this.guards.requireTripEdit(tripId, actor, RESERVATION_EDIT_ACTION);- this.requireResolvableReferences(tripId, input);+ this.requireOwnReferences(tripId, input);const { reservation, accommodationCreated } = this.reservations.create(String(tripId), input as never);if (accommodationCreated) this.realtime.broadcast(tripId, 'accommodation:created', {}, undefined);const i = input as { title?: string; type?: string; create_budget_entry?: unknown };@@ -60,7 +60,7 @@ export class ReservationsRpc {this.guards.requireTripEdit(tripId, actor, RESERVATION_EDIT_ACTION);const current = this.reservations.getReservation(String(reservationId), String(tripId));if (!current) throw new ForbiddenResource(`no reservation ${reservationId} on trip ${tripId}`);- this.requireResolvableReferences(tripId, input);+ this.requireOwnReferences(tripId, input);const { reservation, accommodationChanged } = this.reservations.update(String(reservationId), String(tripId), input as never, current as never);if (accommodationChanged) this.realtime.broadcast(tripId, 'accommodation:updated', {}, undefined);const cur = current as { title: string; type?: string };@@ -100,18 +100,19 @@ export class ReservationsRpc {}/**- * An id that resolves to nothing is a foreign-key error the plugin reads as a- * crash (#2355), so it is named here instead. Only that case: a plugin has- * always been able to point at another trip's day or place through this- * surface, and taking that away is a decision for the plugin contract, not a- * side effect of a bug fix — so the ids the REST route refuses for being- * somebody else's are filtered back out.+ * The body's ids have to be this trip's, and they have to exist. reservation_edit+ * on tripId says the plugin may write here and nothing about day_id, place_id,+ * assignment_id, accommodation_id or the create_accommodation days it puts in the+ * body: a stay written against another trip's day puts a stop on that day, in a+ * plan the acting user may not even be able to read. The REST route and the MCP+ * tool refuse the same ids; this is the plugin half of that rule. An id that+ * resolves to nothing is a foreign-key error the plugin reads as a crash (#2355),+ * so it is named here as well, after the ownership check.*/- private requireResolvableReferences(tripId: number, input: Record<string, unknown>): void {- const elsewhere = new Set(this.reservations.referencesOutsideTrip(String(tripId), input as never));- const unknown = this.reservations- .unresolvedReferences(String(tripId), input as never)- .filter((field) => !elsewhere.has(field));+ private requireOwnReferences(tripId: number, input: Record<string, unknown>): void {+ const offenders = this.reservations.referencesOutsideTrip(String(tripId), input as never);+ if (offenders.length > 0) throw new ForbiddenResource(`not part of trip ${tripId}: ${offenders.join(', ')}`);+ const unknown = this.reservations.unresolvedReferences(String(tripId), input as never);if (unknown.length > 0) throw new BadParams(`unknown reference: ${unknown.join(', ')}`);}diff --git a/server/src/nest/roadtrip/charging.mcp.ts b/server/src/nest/roadtrip/charging.mcp.tsindex a6d50e357..008efc9b0 100644--- a/server/src/nest/roadtrip/charging.mcp.ts+++ b/server/src/nest/roadtrip/charging.mcp.ts@@ -7,6 +7,7 @@ import { addonGate } from '../addons/addon-gate';import { AddonsService } from '../addons/addons.service';import { DatabaseService } from '../database/database.service';import { ChargingService } from './charging.service';+import { answeringRefusals } from './roadtrip-mcp.helpers';@McpController()export class ChargingMcp {@@ -16,7 +17,7 @@ export class ChargingMcp {annotations: TOOL_ANNOTATIONS_READONLY, access: { group: 'trips', mode: 'read' }, when: addonGate(ADDON_IDS.ROADTRIP) })async read({ tripId, placeId }: { tripId: number; placeId: number }, ctx: McpContext) {if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();- return ok(await this.charging.read(tripId, placeId));+ return answeringRefusals(async () => ok(await this.charging.read(tripId, placeId)));}@Tool({ name: 'lookup_roadtrip_charging_info', description: 'Read open charging availability and published tariffs for a charging station by coordinate, before it is added to a trip. Needs a trip only for access control. No API key required. Every caveat of get_roadtrip_charging_info applies unchanged: coverage varies by region and operator, unknown or stale status is not available capacity, prices are gross per-component figures that can carry conditions and extra fees and are not personalized roaming quotes. Report the source, licence and timestamp alongside any figure from it. Charging power, socket types and socket counts are not in this answer; they come from the place search.',inputSchema: { tripId: z.number().int().positive(), ...chargingLookupSchema.shape },diff --git a/server/src/nest/roadtrip/day-boundaries.mcp.ts b/server/src/nest/roadtrip/day-boundaries.mcp.tsindex 42295c0c6..a96b5284f 100644--- a/server/src/nest/roadtrip/day-boundaries.mcp.ts+++ b/server/src/nest/roadtrip/day-boundaries.mcp.ts@@ -10,6 +10,7 @@ import { AddonsService } from '../addons/addons.service';import { addonGate } from '../addons/addon-gate';import { ADDON_IDS } from '../../addons';import { DayBoundariesService } from './day-boundaries.service';+import { answeringRefusals } from './roadtrip-mcp.helpers';const when = addonGate(ADDON_IDS.ROADTRIP);@@ -44,10 +45,13 @@ export class DayBoundariesMcp {if (this.auth.isDemoUser(ctx.userId)) return demoDenied();if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();- const boundaries = boundary- ? this.boundaries.save(tripId, { ...boundary, day_number: dayNumber })- : this.boundaries.remove(tripId, dayNumber);- this.realtime.broadcast(String(tripId), 'roadtripBoundary:changed', { boundaries });- return ok({ boundaries });+ // A stop from another trip is refused by the service, with the reason.+ return answeringRefusals(() => {+ const boundaries = boundary+ ? this.boundaries.save(tripId, { ...boundary, day_number: dayNumber })+ : this.boundaries.remove(tripId, dayNumber);+ this.realtime.broadcast(String(tripId), 'roadtripBoundary:changed', { boundaries });+ return ok({ boundaries });+ });}}diff --git a/server/src/nest/roadtrip/google-route.mcp.ts b/server/src/nest/roadtrip/google-route.mcp.tsindex 6bd0a7c5a..3a5e6a566 100644--- a/server/src/nest/roadtrip/google-route.mcp.ts+++ b/server/src/nest/roadtrip/google-route.mcp.ts@@ -7,6 +7,7 @@ import { addonGate } from '../addons/addon-gate';import { GoogleRouteService } from './google-route.service';import { AuthService } from '../auth/auth.service';import { demoDenied } from '../../mcp/tools/_shared';+import { answeringRefusals } from './roadtrip-mcp.helpers';@McpController()export class GoogleRouteMcp {@@ -14,7 +15,7 @@ export class GoogleRouteMcp {@Tool({ name: 'preview_google_maps_route', description: 'Read ordered stops from a Google Maps directions link. No changes are saved. Review geocoded positions and unresolved stops before importing. The exact Google road geometry is not imported.',inputSchema: googleRoutePreviewRequestSchema.shape, annotations: TOOL_ANNOTATIONS_READONLY,access: { group: 'trips', mode: 'read' }, when: addonGate(ADDON_IDS.ROADTRIP) })- async preview({ url }: { url: string }) { return ok(await this.routes.preview(url)); }+ async preview({ url }: { url: string }) { return answeringRefusals(async () => ok(await this.routes.preview(url))); }@Tool({ name: 'import_google_maps_route', description: 'Append reviewed Google Maps stops to an existing trip day in supplied order. Creates places and visits atomically. Requires place and day editing permissions. Existing visits remain. TREK calculates the road geometry; no Google route geometry is preserved.',inputSchema: { tripId: z.number().int().positive(), ...googleRouteImportSchema.shape },@@ -26,6 +27,6 @@ export class GoogleRouteMcp {access: { group: 'places', mode: 'write' }, when: addonGate(ADDON_IDS.ROADTRIP) })import(input: GoogleRouteImport & { tripId: number }, ctx: McpContext) {if (this.auth.isDemoUser(ctx.userId)) return demoDenied();- return ok(this.routes.import(input.tripId, ctx.userId, input));+ return answeringRefusals(() => ok(this.routes.import(input.tripId, ctx.userId, input)));}}diff --git a/server/src/nest/roadtrip/roadtrip-mcp.helpers.ts b/server/src/nest/roadtrip/roadtrip-mcp.helpers.tsnew file mode 100644index 000000000..1ca671c75--- /dev/null+++ b/server/src/nest/roadtrip/roadtrip-mcp.helpers.ts@@ -0,0 +1,37 @@+import { HttpException } from '@nestjs/common';+import { errorResult, type McpTextResult } from '../../nest-mcp';++/**+ * Run a tool body and answer a refusal from the service with its reason.+ *+ * The roadtrip services refuse with an HttpException whose body is `{ error }`,+ * and the REST filter sends that body verbatim. A tool that lets the exception+ * escape gets the SDK's treatment instead: an error result made of+ * `error.message`, which Nest fills with the class name when the body carries no+ * `message` of its own. The assistant then reads "Http Exception" where the route+ * reads "Day end must be later than day start."+ *+ * Only a refusal is answered. A 5xx is a failure, not a refusal, and it keeps+ * propagating so it is logged and reported the way any other failure is.+ */+export function answeringRefusals<T extends McpTextResult>(work: () => Promise<T>): Promise<T | McpTextResult>;+export function answeringRefusals<T extends McpTextResult>(work: () => T): T | McpTextResult;+export function answeringRefusals<T extends McpTextResult>(work: () => T | Promise<T>): T | McpTextResult | Promise<T | McpTextResult> {+ try {+ const result = work();+ return isPending(result) ? result.catch(refusal) : result;+ } catch (error) {+ return refusal(error);+ }+}++function isPending<T>(value: T | Promise<T>): value is Promise<T> {+ return value instanceof Promise;+}++function refusal(error: unknown): McpTextResult {+ if (!(error instanceof HttpException) || error.getStatus() >= 500) throw error;+ const body = error.getResponse();+ const reason = typeof body === 'string' ? body : (body as { error?: unknown }).error;+ return errorResult(typeof reason === 'string' ? reason : error.message);+}diff --git a/server/src/nest/roadtrip/roadtrip-planning.mcp.ts b/server/src/nest/roadtrip/roadtrip-planning.mcp.tsindex 51abd6c9c..dd7fd0019 100644--- a/server/src/nest/roadtrip/roadtrip-planning.mcp.ts+++ b/server/src/nest/roadtrip/roadtrip-planning.mcp.ts@@ -11,6 +11,7 @@ import {type RoadtripCorridorRequest,} from '@trek/shared';import { corridorTiles, projectOntoRoute, simplifyLine } from '@trek/shared/roadtrip';+import { answeringRefusals } from './roadtrip-mcp.helpers';import { z } from 'zod';@@ -34,7 +35,7 @@ export class RoadtripPlanningMcp {when,})async context({ tripId }: { tripId: number }, ctx: McpContext) {- return ok(this.plans.context(tripId, ctx.userId));+ return answeringRefusals(() => ok(this.plans.context(tripId, ctx.userId)));}@Tool({@@ -47,34 +48,36 @@ export class RoadtripPlanningMcp {when,})async calculate(input: RoadtripPlanRequest, ctx: McpContext) {- const plan = await this.plans.calculate(input.tripId, ctx.userId, input.settings);- const { calculated } = plan;- return ok({- complete: !plan.failures.length && !plan.omittedVisits.length && !calculated.dayWindowIssue,- settings: plan.preferences,- failures: plan.failures,- omittedVisitIds: plan.omittedVisits,- dayWindowIssue: calculated.dayWindowIssue,- totalDistanceMetres: calculated.totalDistance,- totalDurationSeconds: calculated.totalDuration,- totalStops: calculated.totalStops,- days: calculated.days.map((day) => ({- dayId: day.dayId,- dayNumber: day.dayNumber,- date: day.date,- title: day.title,- stops: day.stops,- schedule: day.schedule,- legs: day.legs,- distanceMetres: day.distance,- durationSeconds: day.duration,- driveWarnings: day.driveWarnings,- dayWarning: day.dayWarning,- avoidMissed: day.avoidMissed,- dryPoints: day.dryPoints,- ...(input.includeGeometry ? { geometry: day.geometry } : {}),- })),- quietDays: calculated.quietDays,+ return answeringRefusals(async () => {+ const plan = await this.plans.calculate(input.tripId, ctx.userId, input.settings);+ const { calculated } = plan;+ return ok({+ complete: !plan.failures.length && !plan.omittedVisits.length && !calculated.dayWindowIssue,+ settings: plan.preferences,+ failures: plan.failures,+ omittedVisitIds: plan.omittedVisits,+ dayWindowIssue: calculated.dayWindowIssue,+ totalDistanceMetres: calculated.totalDistance,+ totalDurationSeconds: calculated.totalDuration,+ totalStops: calculated.totalStops,+ days: calculated.days.map((day) => ({+ dayId: day.dayId,+ dayNumber: day.dayNumber,+ date: day.date,+ title: day.title,+ stops: day.stops,+ schedule: day.schedule,+ legs: day.legs,+ distanceMetres: day.distance,+ durationSeconds: day.duration,+ driveWarnings: day.driveWarnings,+ dayWarning: day.dayWarning,+ avoidMissed: day.avoidMissed,+ dryPoints: day.dryPoints,+ ...(input.includeGeometry ? { geometry: day.geometry } : {}),+ })),+ quietDays: calculated.quietDays,+ });});}@@ -88,73 +91,75 @@ export class RoadtripPlanningMcp {when,})async corridor(input: RoadtripCorridorRequest, ctx: McpContext) {- const plan = await this.plans.calculate(input.tripId, ctx.userId);- if (plan.failures.length || plan.omittedVisits.length || plan.calculated.dayWindowIssue)- return errorResult(- 'Resolve missing coordinates, routing or day-window conflicts before searching this corridor.',+ return answeringRefusals(async () => {+ const plan = await this.plans.calculate(input.tripId, ctx.userId);+ if (plan.failures.length || plan.omittedVisits.length || plan.calculated.dayWindowIssue)+ return errorResult(+ 'Resolve missing coordinates, routing or day-window conflicts before searching this corridor.',+ );+ if (input.fromKm != null && input.toKm != null && input.fromKm > input.toKm)+ return errorResult('fromKm must not exceed toKm.');+ const day = plan.calculated.days.find((d) => d.dayNumber === input.dayNumber);+ if (!day?.geometry.length) return errorResult('This day has no routed road.');+ const line = simplifyLine(+ day.geometry.map(([lat, lng]) => ({ lat, lng })),+ Math.max(1, input.widthKm / 3),);- if (input.fromKm != null && input.toKm != null && input.fromKm > input.toKm)- return errorResult('fromKm must not exceed toKm.');- const day = plan.calculated.days.find((d) => d.dayNumber === input.dayNumber);- if (!day?.geometry.length) return errorResult('This day has no routed road.');- const line = simplifyLine(- day.geometry.map(([lat, lng]) => ({ lat, lng })),- Math.max(1, input.widthKm / 3),- );- const tiles = corridorTiles(line, input.widthKm);- const hits = new Map<- string,- { poi: Awaited<ReturnType<RoadtripSearchService['search']>>['pois'][number]; alongKm: number; distanceKm: number }- >();- const page = tiles.slice(input.offset, input.offset + 6);- const failedAreas: number[] = [];- let truncatedAreas = 0;- const sources = new Set<string>();- const failedSources = new Set<string>();- for (const bbox of page) {- try {- const found = await this.maps.search({ categories: [input.category], bbox }, ctx.userId);- found.sources.forEach(source => sources.add(source));- found.failedSources.forEach(source => failedSources.add(source));- if (found.truncated || found.clamped) truncatedAreas++;- for (const poi of found.pois) {- const projection = projectOntoRoute(poi, line);- if (!projection || projection.offRouteKm > input.widthKm) continue;- if (- (input.fromKm != null && projection.alongKm < input.fromKm) ||- (input.toKm != null && projection.alongKm > input.toKm)- )- continue;- if (- input.name &&- !`${poi.name} ${poi.brand ?? ''}`.toLocaleLowerCase().includes(input.name.toLocaleLowerCase())- )- continue;- if (poi.category === 'charging') {- if (input.socket && !poi.charging?.sockets.some((socket) => socket.type === input.socket)) continue;+ const tiles = corridorTiles(line, input.widthKm);+ const hits = new Map<+ string,+ { poi: Awaited<ReturnType<RoadtripSearchService['search']>>['pois'][number]; alongKm: number; distanceKm: number }+ >();+ const page = tiles.slice(input.offset, input.offset + 6);+ const failedAreas: number[] = [];+ let truncatedAreas = 0;+ const sources = new Set<string>();+ const failedSources = new Set<string>();+ for (const bbox of page) {+ try {+ const found = await this.maps.search({ categories: [input.category], bbox }, ctx.userId);+ found.sources.forEach(source => sources.add(source));+ found.failedSources.forEach(source => failedSources.add(source));+ if (found.truncated || found.clamped) truncatedAreas++;+ for (const poi of found.pois) {+ const projection = projectOntoRoute(poi, line);+ if (!projection || projection.offRouteKm > input.widthKm) continue;if (- input.minKw &&- poi.charging?.sockets.some((socket) => socket.kw != null) &&- !poi.charging.sockets.some((socket) => (socket.kw ?? 0) >= input.minKw!)+ (input.fromKm != null && projection.alongKm < input.fromKm) ||+ (input.toKm != null && projection.alongKm > input.toKm))continue;+ if (+ input.name &&+ !`${poi.name} ${poi.brand ?? ''}`.toLocaleLowerCase().includes(input.name.toLocaleLowerCase())+ )+ continue;+ if (poi.category === 'charging') {+ if (input.socket && !poi.charging?.sockets.some((socket) => socket.type === input.socket)) continue;+ if (+ input.minKw &&+ poi.charging?.sockets.some((socket) => socket.kw != null) &&+ !poi.charging.sockets.some((socket) => (socket.kw ?? 0) >= input.minKw!)+ )+ continue;+ }+ hits.set(poi.osm_id, { poi, alongKm: projection.alongKm, distanceKm: projection.offRouteKm });}- hits.set(poi.osm_id, { poi, alongKm: projection.alongKm, distanceKm: projection.offRouteKm });+ } catch {+ failedAreas.push(input.offset + page.indexOf(bbox));}- } catch {- failedAreas.push(input.offset + page.indexOf(bbox));}- }- return ok({- dayNumber: day.dayNumber,- sources: [...sources],- failedSources: [...failedSources],- complete: !failedSources.size && !failedAreas.length && !truncatedAreas && input.offset + page.length >= tiles.length,- failedAreas,- truncatedAreas,- totalAreas: tiles.length,- hits: [...hits.values()].sort((a, b) => a.alongKm - b.alongKm),- nextOffset: input.offset + page.length < tiles.length ? input.offset + page.length : null,+ return ok({+ dayNumber: day.dayNumber,+ sources: [...sources],+ failedSources: [...failedSources],+ complete: !failedSources.size && !failedAreas.length && !truncatedAreas && input.offset + page.length >= tiles.length,+ failedAreas,+ truncatedAreas,+ totalAreas: tiles.length,+ hits: [...hits.values()].sort((a, b) => a.alongKm - b.alongKm),+ nextOffset: input.offset + page.length < tiles.length ? input.offset + page.length : null,+ });});}}diff --git a/server/src/nest/roadtrip/roadtrip-preferences.mcp.ts b/server/src/nest/roadtrip/roadtrip-preferences.mcp.tsindex 286f42be7..4d1f1e843 100644--- a/server/src/nest/roadtrip/roadtrip-preferences.mcp.ts+++ b/server/src/nest/roadtrip/roadtrip-preferences.mcp.ts@@ -15,6 +15,7 @@ import { AuthService } from '../auth/auth.service';import { DatabaseService } from '../database/database.service';import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';import { RoadtripPreferencesService } from './roadtrip-preferences.service';+import { answeringRefusals } from './roadtrip-mcp.helpers';import { roadtripPreferencesUpdateSchema, type RoadtripPreferences } from '@trek/shared';import { z } from 'zod';@@ -58,6 +59,7 @@ export class RoadtripPreferencesMcp {if (this.auth.isDemoUser(ctx.userId)) return demoDenied();if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();- return ok({ tripId, settings: this.preferences.update(tripId, settings), scope: 'trip' });+ // A day window that ends before it starts is refused by the service, with the reason.+ return answeringRefusals(() => ok({ tripId, settings: this.preferences.update(tripId, settings), scope: 'trip' }));}}diff --git a/server/src/nest/system-notices/system-notices.controller.ts b/server/src/nest/system-notices/system-notices.controller.tsindex a0cd1e3f2..d23a4e2d3 100644--- a/server/src/nest/system-notices/system-notices.controller.ts+++ b/server/src/nest/system-notices/system-notices.controller.ts@@ -1,10 +1,21 @@-import { Controller, Get, HttpCode, HttpException, Param, Post, UseGuards } from '@nestjs/common';+import { Controller, Get, HttpCode, HttpException, Param, Post, Query, UseGuards } from '@nestjs/common';import type { SystemNoticeDto } from '@trek/shared';import type { User } from '../../types';import { SystemNoticesService } from './system-notices.service';import { JwtAuthGuard } from '../auth/jwt-auth.guard';import { CurrentUser } from '../auth/current-user.decorator';+/**+ * `?supports=release` names the layouts the calling bundle can draw, comma separated.+ * A missing or malformed value means none, which is what every bundle before this+ * parameter sent.+ */+function parseSupports(raw: string | string[] | undefined): Set<string> {+ const values = Array.isArray(raw) ? raw : [raw];+ const names = values.flatMap(v => (typeof v === 'string' ? v.split(',') : []));+ return new Set(names.map(s => s.trim()).filter(Boolean));+}+/*** /api/system-notices — active announcements for the current user + dismissal.*@@ -19,8 +30,8 @@ export class SystemNoticesController {constructor(private readonly notices: SystemNoticesService) {}@Get('active')- active(@CurrentUser() user: User): SystemNoticeDto[] {- return this.notices.getActiveFor(user.id);+ active(@CurrentUser() user: User, @Query('supports') supports?: string | string[]): SystemNoticeDto[] {+ return this.notices.getActiveFor(user.id, parseSupports(supports));}@Post(':id/dismiss')diff --git a/server/src/nest/system-notices/system-notices.service.ts b/server/src/nest/system-notices/system-notices.service.tsindex 28cf0c97b..4b143de66 100644--- a/server/src/nest/system-notices/system-notices.service.ts+++ b/server/src/nest/system-notices/system-notices.service.ts@@ -18,12 +18,23 @@ export class SystemNoticesService {private readonly env: RuntimeEnvService,) {}- getActiveFor(userId: number): SystemNoticeDto[] {- return getActiveNoticesFor(+ /**+ * `supports` names the layouts the calling bundle can draw. A notice with a release+ * block is held back from a bundle that does not name `release`: after an update the+ * service worker keeps serving the previous bundle until the new one is installed,+ * and that bundle would draw the release notice as bare keys and let the reader+ * dismiss it for good, because the dismissal is recorded against the server's+ * version. A bundle that never sends the parameter loses only the notice it could+ * not read anyway and gets it after the reload. Nothing is spent by holding it back:+ * a notice is used up by a dismissal and by nothing else.+ */+ getActiveFor(userId: number, supports: ReadonlySet<string> = new Set()): SystemNoticeDto[] {+ const notices = getActiveNoticesFor(userId,(addonId) => this.addons.isAddonEnabled(addonId),this.env.isManaged(),) as SystemNoticeDto[];+ return supports.has('release') ? notices : notices.filter(n => !n.release);}dismiss(userId: number, noticeId: string): boolean {diff --git a/server/src/nest/transit/google-transit.provider.ts b/server/src/nest/transit/google-transit.provider.tsindex d4fba0e2c..623e087c1 100644--- a/server/src/nest/transit/google-transit.provider.ts+++ b/server/src/nest/transit/google-transit.provider.ts@@ -150,6 +150,17 @@ const VEHICLE_MODES: Record<string, string> = {GONDOLA_LIFT: 'AERIAL_LIFT',};+/**+ * The rail tokens that name one thing at two levels of detail. MOTIS knows a+ * train by its service, so the client's train filter asks for the five fine+ * modes and never for the umbrella; Google knows it by its vehicle, and+ * HEAVY_RAIL (any conventional train) lands on the umbrella. A request may+ * come at either level and a leg may be labelled at either, so the response+ * filter treats the family as one mode. SUBWAY stays outside it: a subway-only+ * search must not be handed a train, and a train-only search not a subway.+ */+const RAIL_FAMILY = new Set(['RAIL', 'HIGHSPEED_RAIL', 'LONG_DISTANCE', 'NIGHT_RAIL', 'REGIONAL_RAIL', 'SUBURBAN']);+/** '600s' → 600. Google's Duration JSON encoding; anything else is 0. */function parseDuration(value: unknown): number {if (typeof value !== 'string') return 0;@@ -537,5 +548,8 @@ function fillWalkGaps(legs: TransitLeg[]): void {function matchesRequestedModes(itinerary: TransitItinerary, requested: string[]): boolean {if (requested.length === 0) return true;const wanted = new Set(requested);- return itinerary.legs.every((leg) => leg.mode === 'WALK' || wanted.has(leg.mode));+ const railWanted = requested.some((mode) => RAIL_FAMILY.has(mode));+ return itinerary.legs.every(+ (leg) => leg.mode === 'WALK' || wanted.has(leg.mode) || (railWanted && RAIL_FAMILY.has(leg.mode)),+ );}diff --git a/server/tests/e2e/dawarich.e2e.test.ts b/server/tests/e2e/dawarich.e2e.test.tsindex 1d201cdf3..eae7e327f 100644--- a/server/tests/e2e/dawarich.e2e.test.ts+++ b/server/tests/e2e/dawarich.e2e.test.ts@@ -252,6 +252,32 @@ describe('Dawarich e2e (real addon gate + real auth guard + real services + tempexpect(res.body).toEqual({ success: true });});+ it('DAWARICH-E2E-016: POST test with a blank key against a host other than the stored one answers not_connected and never dials out', async () => {+ // The stored key is the one thing this route must not carry to an address+ // the form just typed. The client stub throws on every call, so a probe+ // that did go out would surface as `unreachable` here rather than as the+ // refusal the form is meant to render.+ db.prepare('INSERT INTO dawarich_connections (user_id, url, api_key) VALUES (?, ?, ?)').run(+ ownerId,+ 'https://dawarich.old.example',+ 'plain-legacy-key',+ );++ const res = await request(server)+ .post('/api/integrations/dawarich/test')+ .set('Cookie', sessionCookie(ownerId))+ .send({ url: 'https://dawarich.elsewhere.example' });++ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ connected: false, error: 'not_connected' });+ expect(res.body.errorDetail).toContain('https://dawarich.old.example');+ // And the stored connection is untouched by a test, as it always was.+ expect(db.prepare('SELECT url, api_key FROM dawarich_connections WHERE user_id = ?').get(ownerId)).toEqual({+ url: 'https://dawarich.old.example',+ api_key: 'plain-legacy-key',+ });+ });+// ── Suggestions ──────────────────────────────────────────────────────────it('DAWARICH-E2E-020: GET suggestions without a connection answers the envelope with connected:false — an empty list alone would read as "no stays"', async () => {diff --git a/server/tests/e2e/doc-sync.e2e.test.ts b/server/tests/e2e/doc-sync.e2e.test.tsindex 483ea4f76..22c66cf03 100644--- a/server/tests/e2e/doc-sync.e2e.test.ts+++ b/server/tests/e2e/doc-sync.e2e.test.ts@@ -269,6 +269,18 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>expect(row.secrets).toMatch(/^enc:v1:/);});+ it('does not let a blank form carry the stored secret to another address', async () => {+ // The stored token only ever goes to the server it was stored against;+ // anywhere else, the credential has to be typed in for that address.+ await request(server)+ .put(`/api/trips/${tripId}/docsync/connections`)+ .set('Cookie', sessionCookie(ownerId))+ .send({ providerId: 'paperless', baseUrl: 'https://paperless.example.net', credentials: { api_token: '' } })+ .expect(400);+ const row = db.prepare('SELECT base_url FROM document_connections WHERE trip_id = ?').get(tripId) as { base_url: string };+ expect(row.base_url).toBe('https://paperless.example.com');+ });+it('creates a folder or tag through the connection the path names', async () => {const conns = await request(server).get(`/api/trips/${tripId}/docsync/connections`)@@ -434,6 +446,31 @@ describe('Document sync e2e (real guards + real services + temp SQLite)', () =>expect(db.prepare('SELECT COUNT(*) AS n FROM trip_document_links WHERE id = ?').get(linkId)).toEqual({ n: 0 });});+ it('disconnects the store through the real contract, bindings included', async () => {+ const conns = await request(server)+ .get(`/api/trips/${tripId}/docsync/connections`)+ .set('Cookie', sessionCookie(ownerId));+ const connectionId = conns.body[0].id;+ await request(server)+ .post(`/api/trips/${tripId}/docsync/links`)+ .set('Cookie', sessionCookie(ownerId))+ .send({ connectionId, scopeKey: 'tag:2', remoteLabel: 'Norway', direction: 'both', deletePolicy: 'unlink', conflictPolicy: 'manual', syncEnabled: true })+ .expect(200);++ await request(server)+ .delete(`/api/trips/${tripId}/docsync/connections/${connectionId}`)+ .set('Cookie', sessionCookie(memberId))+ .expect(403);+ const res = await request(server)+ .delete(`/api/trips/${tripId}/docsync/connections/${connectionId}`)+ .set('Cookie', sessionCookie(ownerId))+ .expect(200);++ expect(res.body).toEqual({ success: true });+ expect(db.prepare('SELECT COUNT(*) AS n FROM document_connections WHERE trip_id = ?').get(tripId)).toEqual({ n: 0 });+ expect(db.prepare('SELECT COUNT(*) AS n FROM trip_document_links WHERE trip_id = ?').get(tripId)).toEqual({ n: 0 });+ });+it('accepts an unknown webhook token without revealing that it is unknown', async () => {// A 404 here would let anyone enumerate which bindings exist.await request(server).post('/api/docsync/webhook/definitely-not-a-token').expect(200);diff --git a/server/tests/e2e/maps.e2e.test.ts b/server/tests/e2e/maps.e2e.test.tsindex abbd66f45..981d97db7 100644--- a/server/tests/e2e/maps.e2e.test.ts+++ b/server/tests/e2e/maps.e2e.test.ts@@ -95,4 +95,21 @@ describe('Maps e2e (real auth guard + temp SQLite)', () => {expect(res.status).toBe(400);expect(res.body).toEqual({ error: 'lat and lng required' });});++ it('200 with no place for an OSM id that carries more than a number, and nothing goes out', async () => {+ // The path segment reaches the service as it is, and the id used to be+ // written into an Overpass query as it was: this one would have run a+ // global scan on the mirror under TREK's shared user agent.+ const fetchMock = vi.fn(async () => { throw new Error('nothing may leave for this id'); });+ vi.stubGlobal('fetch', fetchMock);+ try {+ const injected = encodeURIComponent('node:1);nwr["amenity"](-90,-180,90,180');+ const res = await request(server).get(`/api/maps/details/${injected}`).set('Cookie', sessionCookie(1));+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ place: null });+ expect(fetchMock).not.toHaveBeenCalled();+ } finally {+ vi.unstubAllGlobals();+ }+ });});diff --git a/server/tests/e2e/places.e2e.test.ts b/server/tests/e2e/places.e2e.test.tsindex 74942e403..e181a7ef3 100644--- a/server/tests/e2e/places.e2e.test.ts+++ b/server/tests/e2e/places.e2e.test.ts@@ -72,6 +72,7 @@ vi.mock('../../src/db/database', () => ({db, canAccessTrip, isOwner: vi.fn(() => true), getPlaceWithTags, closeDb: () => {}, reinitialize: () => {},}));vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));+import { broadcast } from '../../src/websocket';import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';import { PermissionsService } from '../../src/nest/permissions/permissions.service';@@ -282,6 +283,22 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {expect(db.prepare('SELECT id FROM budget_items ORDER BY id').all()).toEqual([{ id: 45 }]);});+ it('DELETE :id tells the deleting tab about the expense that went with the place', async () => {+ // X-Socket-Id keeps a tab from hearing back what it did itself. The tab+ // removed the place; the expense went on the server alone, so that event+ // goes out without the filter or the tab keeps the expense until a reload.+ db.prepare("INSERT INTO places (id, trip_id, name) VALUES (13, 5, 'Louvre')").run();+ db.prepare("INSERT INTO budget_items (id, trip_id, name, total_price, place_id) VALUES (46, 5, 'Tickets', 34, 13)").run();+ vi.mocked(broadcast).mockClear();++ const res = await request(server).delete('/api/trips/5/places/13')+ .set('Cookie', sessionCookie(1)).set('X-Socket-Id', 'tab-1');++ expect(res.status).toBe(200);+ expect(broadcast).toHaveBeenCalledWith('5', 'place:deleted', { placeId: 13 }, 'tab-1');+ expect(broadcast).toHaveBeenCalledWith('5', 'budget:deleted', { itemId: 46 }, undefined);+ });+it('404 trip when not accessible', async () => {canAccessTrip.mockReturnValue(undefined);const res = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));diff --git a/server/tests/e2e/public-api.e2e.test.ts b/server/tests/e2e/public-api.e2e.test.tsindex e8d7de6e3..da99c184f 100644--- a/server/tests/e2e/public-api.e2e.test.ts+++ b/server/tests/e2e/public-api.e2e.test.ts@@ -43,7 +43,7 @@ const { db } = vi.hoisted(() => {created_at DATETIME DEFAULT CURRENT_TIMESTAMP);CREATE TABLE categories (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL);CREATE TABLE day_assignments (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,- place_id INTEGER NOT NULL, order_index INTEGER NOT NULL DEFAULT 0);+ place_id INTEGER NOT NULL, order_index INTEGER NOT NULL DEFAULT 0, accommodation_id INTEGER);CREATE TABLE day_notes (id INTEGER PRIMARY KEY AUTOINCREMENT, day_id INTEGER NOT NULL,trip_id INTEGER NOT NULL, text TEXT NOT NULL, time TEXT, icon TEXT, sort_order REAL DEFAULT 0);CREATE TABLE day_accommodations (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,@@ -213,8 +213,11 @@ describe('Public API v1 e2e (real guard + real SQL)', () => {"INSERT INTO reservations (trip_id, day_id, type, title, location, reservation_time, status) VALUES (1, 1, 'flight', 'LH 1234', 'FRA', '2026-06-14T08:00', 'confirmed')",).run();db.prepare(- "INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out) VALUES (1, 3, 1, 2, '15:00', '11:00')",+ "INSERT INTO day_accommodations (id, trip_id, place_id, start_day_id, end_day_id, check_in, check_out) VALUES (1, 1, 3, 1, 2, '15:00', '11:00')",).run();+ // The stop a booked night puts on its check-in day, so the route can reach the+ // hotel. It belongs to the stay, not to the day's plan.+ db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index, accommodation_id) VALUES (1, 3, 2, 1)').run();app = await build();server = app.getHttpServer() as Server;@@ -350,6 +353,16 @@ describe('Public API v1 e2e (real guard + real SQL)', () => {]);});+ it('reports the night once, under accommodations, not again as a place on its check-in day', async () => {+ // The stop a booking puts on its check-in day is how the route reaches the+ // hotel. To a consumer it is the same booking twice: a hotel that is also a+ // planned place reads as two different intentions.+ const res = await get('/api/v1/trips/1?include=places,accommodations', ADA_TOKEN);+ expect(res.status).toBe(200);+ expect(res.body.days[0].places.map((p: { name: string }) => p.name)).toEqual(['Uffizien', 'Ponte Vecchio']);+ expect(res.body.accommodations.map((a: { name: string }) => a.name)).toEqual(['Hotel Alba']);+ });+it('lists travellers by name, owner first, without ids or emails', async () => {const res = await get('/api/v1/trips/3?include=travellers', ADA_TOKEN);expect(res.status).toBe(200);@@ -366,8 +379,9 @@ describe('Public API v1 e2e (real guard + real SQL)', () => {expect(res.body.unplanned_places).toEqual([expect.objectContaining({ name: 'Boboli-Garten', lat: 43.762, lng: 11.248, notes: 'vielleicht' }),]);- // Hotel Alba has no day either, but it is the accommodation and is- // reported there — a shortlist that includes your hotel is not a shortlist.+ // Hotel Alba stands on a day only through the stop its booking put there. It+ // is the accommodation and is reported as such: a shortlist that includes+ // your hotel is not a shortlist.expect(res.body.unplanned_places.map((p: { name: string }) => p.name)).not.toContain('Hotel Alba');// And the scheduled ones still sit on their day, not in both places.expect(res.body.days[0].places.map((p: { name: string }) => p.name)).toEqual(['Uffizien', 'Ponte Vecchio']);diff --git a/server/tests/e2e/system-notices.e2e.test.ts b/server/tests/e2e/system-notices.e2e.test.tsindex b9c41ae93..074c4b9ea 100644--- a/server/tests/e2e/system-notices.e2e.test.ts+++ b/server/tests/e2e/system-notices.e2e.test.ts@@ -78,6 +78,34 @@ describe('System-notices e2e (real auth guard + temp SQLite)', () => {expect(mockGetActive).toHaveBeenCalledWith(1, expect.any(Function), false);});+ // A bundle from before the release layout never sends `?supports=`, and it would+ // draw the release notice as bare keys. The route keeps that notice for a client+ // that announces the layout and serves everything else to both.+ describe('the release layout and ?supports=', () => {+ const release = {+ ...notice,+ id: 'release-notes',+ release: { version: '4.3.0', headlineKey: 'system_notice.release_notes.headline' },+ };++ it('holds the release notice back when the parameter is missing', async () => {+ mockGetActive.mockReturnValue([release, notice]);+ const res = await request(server).get('/api/system-notices/active').set('Cookie', sessionCookie(1));+ expect(res.status).toBe(200);+ expect(res.body).toEqual([notice]);+ });++ it('delivers the release notice to a client that announces the layout', async () => {+ mockGetActive.mockReturnValue([release, notice]);+ const res = await request(server)+ .get('/api/system-notices/active')+ .query({ supports: 'release' })+ .set('Cookie', sessionCookie(1));+ expect(res.status).toBe(200);+ expect(res.body).toEqual([release, notice]);+ });+ });+it('204 with no body on a successful dismiss', async () => {mockDismiss.mockReturnValue(true);const res = await request(server).post('/api/system-notices/welcome/dismiss').set('Cookie', sessionCookie(1));diff --git a/server/tests/integration/misc.test.ts b/server/tests/integration/misc.test.tsindex 2c26390a3..308d0cf4a 100644--- a/server/tests/integration/misc.test.ts+++ b/server/tests/integration/misc.test.ts@@ -166,10 +166,16 @@ describe('Request body ceiling', () => {expect(res.status).not.toBe(413);});- // A list file may be a megabyte (#2198), and the two routes that carry one- // whole are measured against that instead (#2301). Only those two.- it('MISC-011: a list file over 100kb reaches the import and the GPX reader', async () => {- for (const route of ['/api/addons/collections/import', '/api/addons/collections/gpx/read']) {+ // A list file may be a megabyte (#2198), and the three routes that carry one+ // whole are measured against that instead (#2301): the import into a new+ // list, the GPX reader, and the import into a list that already exists.+ // Only those three.+ it('MISC-011: a list file over 100kb reaches both imports and the GPX reader', async () => {+ for (const route of [+ '/api/addons/collections/import',+ '/api/addons/collections/gpx/read',+ '/api/addons/collections/7/import',+ ]) {const res = await request(app).post(route).set('Content-Type', 'application/json')diff --git a/server/tests/integration/systemNotices.test.ts b/server/tests/integration/systemNotices.test.tsindex bd75ae9cb..afbc2b4e2 100644--- a/server/tests/integration/systemNotices.test.ts+++ b/server/tests/integration/systemNotices.test.ts@@ -235,9 +235,12 @@ describe('GET /api/system-notices/active', () => {const { user } = createUser(testDb);testDb.prepare('UPDATE users SET login_count = 5, first_seen_version = ? WHERE id = ?').run('3.0.0', user.id);+ // The client announces the release layout with `?supports=release`; a bundle that+ // predates it never gets the notice (pinned separately below).const shows = async () => {const res = await request(app).get('/api/system-notices/active')+ .query({ supports: 'release' }).set('Cookie', authCookie(user.id));expect(res.status).toBe(200);return res.body.some((n: { id: string }) => n.id === 'release-notes');@@ -267,6 +270,29 @@ describe('GET /api/system-notices/active', () => {await dismiss();expect(await shows()).toBe(false);});++ // Right after an update the browser still runs the bundle the service worker cached,+ // which has neither the copy for the new release notice nor a way to tell. It would+ // draw the keys and, on close, spend the notice for this whole version. So the notice+ // waits for a client that announces the release layout; the reload brings one.+ it('keeps the release notes from a client that does not announce the release layout', async () => {+ const { user } = createUser(testDb);+ testDb.prepare('UPDATE users SET login_count = 5, first_seen_version = ? WHERE id = ?').run('3.0.0', user.id);++ const fetchActive = (query: Record<string, string>) => request(app)+ .get('/api/system-notices/active')+ .query(query)+ .set('Cookie', authCookie(user.id));++ const without = await fetchActive({});+ expect(without.status).toBe(200);+ expect(without.body.some((n: { id: string }) => n.id === 'release-notes')).toBe(false);+ expect(without.body.some((n: { release?: unknown }) => n.release !== undefined)).toBe(false);++ const withLayout = await fetchActive({ supports: 'release' });+ expect(withLayout.status).toBe(200);+ expect(withLayout.body.some((n: { id: string }) => n.id === 'release-notes')).toBe(true);+ });});// ─────────────────────────────────────────────────────────────────────────────diff --git a/server/tests/unit/app-config/config-templates.test.ts b/server/tests/unit/app-config/config-templates.test.tsnew file mode 100644index 000000000..bec2e55bc--- /dev/null+++ b/server/tests/unit/app-config/config-templates.test.ts@@ -0,0 +1,83 @@+/**+ * The shipped configuration templates (server/.env.example, docker-compose.yml,+ * the Helm values and ConfigMap) are the first place an operator looks for a+ * variable, and nothing else ties them to the code: a default raised in+ * derive.ts stays wrong in the template until somebody notices, and a switch+ * that only the wiki knows about is one the compose file never shows. These+ * tests pin the pieces that drifted once.+ */+import { describe, it, expect } from 'vitest';+import fs from 'node:fs';+import path from 'node:path';++import { OVERPASS_TIMEOUT_DEFAULT_MS } from '../../../src/nest/maps/maps.helpers';++const REPO_ROOT = path.join(__dirname, '..', '..', '..', '..');++const envExample = fs.readFileSync(path.join(REPO_ROOT, 'server', '.env.example'), 'utf8');+const compose = fs.readFileSync(path.join(REPO_ROOT, 'docker-compose.yml'), 'utf8');+const helmValues = fs.readFileSync(path.join(REPO_ROOT, 'charts', 'trek', 'values.yaml'), 'utf8');+const helmConfigMap = fs.readFileSync(path.join(REPO_ROOT, 'charts', 'trek', 'templates', 'configmap.yaml'), 'utf8');+const helmSecret = fs.readFileSync(path.join(REPO_ROOT, 'charts', 'trek', 'templates', 'secret.yaml'), 'utf8');+const helmDeployment = fs.readFileSync(path.join(REPO_ROOT, 'charts', 'trek', 'templates', 'deployment.yaml'), 'utf8');++describe('OVERPASS_TIMEOUT_MS in the templates', () => {+ it('.env.example shows the code default as both the example value and the stated default', () => {+ const line = envExample.split(/\r?\n/).find((l) => l.includes('OVERPASS_TIMEOUT_MS='));+ expect(line).toBeDefined();+ expect(line).toContain(`OVERPASS_TIMEOUT_MS=${OVERPASS_TIMEOUT_DEFAULT_MS}`);+ expect(line).toContain(`(default: ${OVERPASS_TIMEOUT_DEFAULT_MS})`);+ });++ it('the Helm values show the code default as both the example value and the stated default', () => {+ expect(helmValues).toContain(`# OVERPASS_TIMEOUT_MS: "${OVERPASS_TIMEOUT_DEFAULT_MS}"`);+ expect(helmValues).toContain(`Defaults to ${OVERPASS_TIMEOUT_DEFAULT_MS}.`);+ });+});++describe('the Places and Amap switches in the templates', () => {+ // The index is asked by default and the only way to stop that is this+ // variable, so an operator has to be able to find it where they look.+ const documented = ['TREK_PLACES_ENABLED', 'TREK_PLACES_URL', 'AMAP_API_KEY', 'AMAP_API_SECRET', 'AMAP_API_BASE'];++ it('.env.example documents every one of them', () => {+ for (const name of documented) {+ expect(envExample).toContain(`# ${name}=`);+ }+ });++ it('docker-compose.yml documents every one of them', () => {+ for (const name of documented) {+ expect(compose).toContain(`# - ${name}=`);+ }+ });++ it('the Helm ConfigMap passes through the non-secret ones the values file documents', () => {+ for (const name of ['TREK_PLACES_ENABLED', 'TREK_PLACES_URL', 'AMAP_API_BASE']) {+ expect(helmValues).toContain(`# ${name}:`);+ expect(helmConfigMap).toContain(`${name}: {{ .Values.env.${name} | quote }}`);+ }+ });++ it('the Helm ConfigMap emits TREK_PLACES_ENABLED on presence, since its one useful value is false', () => {+ // A guard of the `if .Values.env.X` shape drops a boolean false, and with+ // it the only setting anyone makes here.+ expect(helmConfigMap).not.toContain('{{- if .Values.env.TREK_PLACES_ENABLED }}');+ expect(helmConfigMap).toContain('{{- if not (kindIs "invalid" .Values.env.TREK_PLACES_ENABLED) }}');+ });++ it('the Helm chart carries the Amap credentials in the Secret, never in the ConfigMap', () => {+ // A ConfigMap is readable by anyone who can read the namespace; the key and+ // its signing secret belong next to the other credentials, in both the+ // plain and the generated branch of the Secret, and the pod reads them from+ // there like it reads the Unsplash key.+ for (const name of ['AMAP_API_KEY', 'AMAP_API_SECRET']) {+ expect(helmValues).toContain(` ${name}: ""`);+ expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} | b64enc | quote }}`);+ expect(helmSecret).toContain(`${name}: {{ .Values.secretEnv.${name} }}`);+ expect(helmDeployment).toContain(`- name: ${name}\n valueFrom:\n secretKeyRef:`);+ expect(helmDeployment).toContain(`key: ${name}\n optional: true`);+ expect(helmConfigMap).not.toContain(name);+ }+ });+});diff --git a/server/tests/unit/app-config/derive.test.ts b/server/tests/unit/app-config/derive.test.tsindex 1c3e05286..79a9fef28 100644--- a/server/tests/unit/app-config/derive.test.ts+++ b/server/tests/unit/app-config/derive.test.ts@@ -285,13 +285,26 @@ describe('deriveAll', () => {});describe('deriveMaps', () => {- it('TREK_PLACES_ENABLED is on unless it says the literal "false"', () => {- // Fail-open, and deliberately not the boolean-like family the switches- // above accept: a typo must not silently drop a whole install back to- // Nominatim, whose usage policy forbids what TREK was doing with it.- expect(deriveMaps({} as never).trekPlacesEnabled).toBe(true);+ it('TREK_PLACES_ENABLED accepts the same false family as every other switch', () => {+ // The schema admits the whole boolean-like family for this variable, so a+ // value it lets through must also count: an operator who writes 0 or off,+ // as the .env.example header invites, gets the index switched off rather+ // than a silent no-op.expect(deriveMaps({ TREK_PLACES_ENABLED: 'false' } as never).trekPlacesEnabled).toBe(false);- for (const value of ['true', 'FALSE', '0', 'no', '']) {+ for (const value of ['FALSE', '0', 'off', 'no', ' No ']) {+ expect(deriveMaps({ TREK_PLACES_ENABLED: value } as never).trekPlacesEnabled, value).toBe(false);+ }+ for (const value of ['true', 'TRUE', '1', 'on', 'yes']) {+ expect(deriveMaps({ TREK_PLACES_ENABLED: value } as never).trekPlacesEnabled, value).toBe(true);+ }+ });++ it('TREK_PLACES_ENABLED fails open when unset, blank or outside the family', () => {+ // A typo must not silently drop a whole install back to Nominatim, whose+ // usage policy forbids what TREK was doing with it. Outside the family the+ // schema aborts boot anyway; this covers the paths that skip validation.+ expect(deriveMaps({} as never).trekPlacesEnabled).toBe(true);+ for (const value of ['', ' ', 'maybe', 'fasle']) {expect(deriveMaps({ TREK_PLACES_ENABLED: value } as never).trekPlacesEnabled, value).toBe(true);}});diff --git a/server/tests/unit/db/migrate-encryption-parity.test.ts b/server/tests/unit/db/migrate-encryption-parity.test.tsindex 299946d07..9a3c8ab3d 100644--- a/server/tests/unit/db/migrate-encryption-parity.test.ts+++ b/server/tests/unit/db/migrate-encryption-parity.test.ts@@ -136,6 +136,22 @@ describe('migrate-encryption.ts app_settings parity', () => {expect(script).toContain("UPDATE plugins SET config = ?");expect(script).toContain('plugin_user_config');});++ // doc-sync-secrets.ts wraps every document connection credential and the+ // per-link webhook secret in one blob under the same enc:v1: scheme. Missed+ // by a rotation, every trip binding reads back as unauthorized and the+ // webhook signature check has nothing to compare against.+ it('ROTPAR-010: rotates the document connection blob and the link webhook secret', () => {+ const docSyncSecrets = fs.readFileSync(+ path.join(SERVER_ROOT, 'src', 'nest', 'doc-sync', 'doc-sync-secrets.ts'),+ 'utf8',+ );+ expect(docSyncSecrets).toContain('maybe_encrypt_api_key');+ expect(script).toContain('SELECT id, secrets FROM document_connections');+ expect(script).toContain('UPDATE document_connections SET secrets = ?');+ expect(script).toContain('SELECT id, webhook_secret FROM trip_document_links');+ expect(script).toContain('UPDATE trip_document_links SET webhook_secret = ?');+ });});describe('migrate-encryption.ts storage.backends: malformed shape', () => {@@ -310,4 +326,56 @@ describe('migrate-encryption.ts rotates the stores the app writes', () => {expect(decryptWith('new-key', userConfig.token)).toBe('user-secret');after.close();}, 30000);++ // The columns the doc-sync tables keep encrypted, and only those: the blob+ // is one opaque enc:v1: value per row, exactly what doc-sync-secrets.ts writes.+ const DOC_SYNC_SCHEMA = `+ CREATE TABLE document_connections (id INTEGER PRIMARY KEY, secrets TEXT);+ CREATE TABLE trip_document_links (id INTEGER PRIMARY KEY, webhook_secret TEXT);+ `;++ it('ROTPAR-011: re-encrypts document connection secrets and link webhook secrets, leaving rows already on the new key alone', () => {+ const seed = new Database(dbPath);+ seed.exec(BASE_SCHEMA);+ seed.exec(DOC_SYNC_SCHEMA);+ const connectionBlob = JSON.stringify({ token: 'paperless-token', deviceId: 'dsm-device' });+ seed.prepare('INSERT INTO document_connections (id, secrets) VALUES (1, ?)').run(encryptWith('old-key', connectionBlob));+ // A second run over a half-rotated database must not touch a row that is+ // already readable under the new key, let alone re-encrypt it under the old.+ const alreadyRotated = encryptWith('new-key', JSON.stringify({ token: 'nextcloud-app-password' }));+ seed.prepare('INSERT INTO document_connections (id, secrets) VALUES (2, ?)').run(alreadyRotated);+ seed.prepare('INSERT INTO document_connections (id, secrets) VALUES (3, NULL)').run();+ seed.prepare('INSERT INTO trip_document_links (id, webhook_secret) VALUES (1, ?)').run(+ encryptWith('old-key', JSON.stringify({ webhook: 'hook-secret' })),+ );+ seed.close();++ const output = execFileSync(process.execPath, ['--import', 'tsx', 'scripts/migrate-encryption.ts'], {+ cwd: SERVER_ROOT,+ env: { ...process.env, DB_PATH: dbPath },+ input: ['old-key', 'new-key', 'yes', ''].join(String.fromCharCode(10)),+ stdio: 'pipe',+ encoding: 'utf8',+ });++ const after = new Database(dbPath, { readonly: true });+ const rotated = (after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 1').get() as { v: string }).v;+ expect(decryptWith('old-key', rotated)).toBeNull();+ expect(JSON.parse(decryptWith('new-key', rotated) ?? 'null')).toEqual({ token: 'paperless-token', deviceId: 'dsm-device' });++ const untouched = (after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 2').get() as { v: string }).v;+ expect(untouched).toBe(alreadyRotated);++ const empty = (after.prepare('SELECT secrets AS v FROM document_connections WHERE id = 3').get() as { v: string | null }).v;+ expect(empty).toBeNull();++ const webhook = (after.prepare('SELECT webhook_secret AS v FROM trip_document_links WHERE id = 1').get() as { v: string }).v;+ expect(JSON.parse(decryptWith('new-key', webhook) ?? 'null')).toEqual({ webhook: 'hook-secret' });+ after.close();++ // The summary counts these rows like every other store the script walks.+ expect(output).toMatch(/Migrated:\s+2\b/);+ expect(output).toMatch(/Already on new key:\s+1\b/);+ expect(output).toContain('All secrets successfully re-encrypted.');+ }, 30000);});diff --git a/server/tests/unit/nest/accommodations.controller.test.ts b/server/tests/unit/nest/accommodations.controller.test.tsindex d426ad8f9..7c6235867 100644--- a/server/tests/unit/nest/accommodations.controller.test.ts+++ b/server/tests/unit/nest/accommodations.controller.test.ts@@ -60,8 +60,8 @@ describe('AccommodationsController (parity with the legacy accommodations sub-ro});it('ACC-CTL-001 hands the day stop back in the answer and announces it', () => {- // The broadcast skips the socket that sent the request, so the answer is the- // only way the session that booked the night learns about its own stop.+ // The stop reaches the session that booked the night over the socket as well;+ // the answer is what it has left when that socket is down.const stop = { id: 77, day_id: 10 };const create = vi.fn().mockReturnValue({ accommodation: { id: 9 }, mirror: { created: stop, removed: [], stamped: null } });const announceMirror = vi.fn();@@ -107,10 +107,12 @@ describe('AccommodationsController (parity with the legacy accommodations sub-roexpect(update).not.toHaveBeenCalled();});- it('ACC-CTL-004 the mirror sender is the same broadcast, socket id and all', () => {+ it('ACC-CTL-004 the mirror sender is the same broadcast, reaching the sender too', () => {// announceMirror decides which events a stay write implies; the controller only- // hands it the door out. That door has to carry the sender's socket id, or the- // session that just moved the booking is told about its own stop twice.+ // hands it the door out. That door must not skip the sender's socket: the day's+ // new order and its re-pinned vias are not in the answer, and a session that+ // takes the stop from the answer alone keeps the stops behind it on their old+ // numbers. The stop itself arriving twice is a duplicate the store drops.const get = vi.fn().mockReturnValue({ id: 9 });const mirror = { created: { id: 78, day_id: 11 }, removed: [{ id: 77, dayId: 10 }], stamped: null };const update = vi.fn().mockReturnValue({ accommodation: { id: 9 }, mirror });@@ -119,11 +121,18 @@ describe('AccommodationsController (parity with the legacy accommodations sub-roconst announceMirror = vi.fn((_tripId: string, m: typeof mirror, send: Send) => {for (const stop of m.removed) send('assignment:deleted', { assignmentId: stop.id, dayId: stop.dayId });if (m.created) send('assignment:created', { assignment: m.created });+ send('assignment:reordered', { dayId: 11, orderedIds: [70, 78, 71] });+ send('roadtripVia:changed', { dayId: 11, vias: [] });});const svc = makeService({ get, update, broadcast, announceMirror } as Partial<AccommodationsService>);new AccommodationsController(svc).update(user, '5', '9', refs, 'sock');- expect(broadcast).toHaveBeenCalledWith('5', 'assignment:deleted', { assignmentId: 77, dayId: 10 }, 'sock');- expect(broadcast).toHaveBeenCalledWith('5', 'assignment:created', { assignment: mirror.created }, 'sock');+ expect(broadcast).toHaveBeenCalledWith('5', 'assignment:deleted', { assignmentId: 77, dayId: 10 }, undefined);+ expect(broadcast).toHaveBeenCalledWith('5', 'assignment:created', { assignment: mirror.created }, undefined);+ expect(broadcast).toHaveBeenCalledWith('5', 'assignment:reordered', { dayId: 11, orderedIds: [70, 78, 71] }, undefined);+ expect(broadcast).toHaveBeenCalledWith('5', 'roadtripVia:changed', { dayId: 11, vias: [] }, undefined);+ // The booking's own event is still the sender's echo, and still suppressed, and+ // the journey reconcile behind announceMirror still gets the socket id (ACC-CTL-002).+ expect(broadcast).toHaveBeenCalledWith('5', 'accommodation:updated', { accommodation: { id: 9 } }, 'sock');});});diff --git a/server/tests/unit/nest/accommodations.service.test.ts b/server/tests/unit/nest/accommodations.service.test.tsindex ab5c39f1c..0fdd0e26c 100644--- a/server/tests/unit/nest/accommodations.service.test.ts+++ b/server/tests/unit/nest/accommodations.service.test.ts@@ -1030,6 +1030,222 @@ describe('the day stop a booking implies', () => {});});+describe('the drawn roads a booking moves', () => {+ // A via is pinned to a POSITION among the day's located stops, not to a row. A+ // night seated by its check-in ahead of the afternoon renumbers every stop behind+ // it, and every road drawn behind those stops has to move with them, or the+ // detour is driven on the wrong leg for everyone.+ const stopsOn = (dayId: number) =>+ (testDb.prepare('SELECT place_id FROM day_assignments WHERE day_id = ? ORDER BY order_index').all(dayId) as { place_id: number }[])+ .map(row => row.place_id);+ const addVia = (dayId: number, afterOrderIndex: number): number =>+ Number(testDb.prepare('INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (?, ?, 0, 48.1, 11.5)')+ .run(dayId, afterOrderIndex).lastInsertRowid);+ const viaAnchors = (dayId: number) =>+ testDb.prepare('SELECT id, after_order_index FROM roadtrip_vias WHERE day_id = ? ORDER BY id').all(dayId) as+ { id: number; after_order_index: number }[];+ /** The day's roads as the route reads them: leg by leg, and in order within a leg. */+ const legOrder = (dayId: number) =>+ testDb.prepare('SELECT id, after_order_index, sequence FROM roadtrip_vias WHERE day_id = ? ORDER BY after_order_index, sequence, id').all(dayId) as+ { id: number; after_order_index: number; sequence: number }[];+ const pin = (assignmentId: number, time: string) =>+ testDb.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run(time, assignmentId);++ /** A(0), B(1) pinned to noon, C(2): the day a check-in at eleven lands in the middle of. */+ function afternoonDay() {+ const { user } = createUser(testDb);+ const trip = createTrip(testDb, user.id);+ const day = createDay(testDb, trip.id);+ const [a, b, c, hotel] = ['Harbour', 'Mercure', 'Museum', 'Billstedt'].map(name => createPlace(testDb, trip.id, { name }));+ createDayAssignment(testDb, day.id, a.id);+ pin(createDayAssignment(testDb, day.id, b.id).id, '12:00');+ createDayAssignment(testDb, day.id, c.id);+ return { trip, day, a, b, c, hotel };+ }++ it('ACC-034 a night seated ahead of the afternoon carries the roads behind it along', () => {+ const { trip, day, a, b, c, hotel } = afternoonDay();+ const afterA = addVia(day.id, 0);+ const afterB = addVia(day.id, 1);+ // Behind the last stop: the drive into the next day. It stays with C, which is+ // still last, rather than being dropped as a leg C never had.+ const intoTomorrow = addVia(day.id, 2);++ const { mirror } = svc.createAccommodation(trip.id, { place_id: hotel.id, start_day_id: day.id, end_day_id: day.id, check_in: '11:00' }) as any;++ expect(stopsOn(day.id)).toEqual([a.id, hotel.id, b.id, c.id]);+ expect(viaAnchors(day.id)).toEqual([+ { id: afterA, after_order_index: 0 },+ { id: afterB, after_order_index: 2 },+ { id: intoTomorrow, after_order_index: 3 },+ ]);+ // Reported on the mirror in the shape the road trip broadcasts, so every planner+ // routes the new anchors against the new order.+ expect(mirror.vias).toEqual([{+ dayId: day.id,+ vias: [+ expect.objectContaining({ id: afterA, day_id: day.id, after_order_index: 0 }),+ expect.objectContaining({ id: afterB, day_id: day.id, after_order_index: 2 }),+ expect.objectContaining({ id: intoTomorrow, day_id: day.id, after_order_index: 3 }),+ ],+ }]);+ });++ it('ACC-034b a night appended at the end of the day moves no road and reports none', () => {+ const { trip, day, a, b, c, hotel } = afternoonDay();+ const afterA = addVia(day.id, 0);+ const afterB = addVia(day.id, 1);++ const { mirror } = svc.createAccommodation(trip.id, { place_id: hotel.id, start_day_id: day.id, end_day_id: day.id }) as any;++ expect(stopsOn(day.id)).toEqual([a.id, b.id, c.id, hotel.id]);+ expect(viaAnchors(day.id)).toEqual([{ id: afterA, after_order_index: 0 }, { id: afterB, after_order_index: 1 }]);+ expect(mirror.vias).toBeUndefined();+ });++ it('ACC-034c re-seating the night by a later check-in re-pins the roads around it', () => {+ const { trip, day, a, b, c, hotel } = afternoonDay();+ const { accommodation } = svc.createAccommodation(trip.id, { place_id: hotel.id, start_day_id: day.id, end_day_id: day.id, check_in: '11:00' }) as any;+ expect(stopsOn(day.id)).toEqual([a.id, hotel.id, b.id, c.id]);+ const afterA = addVia(day.id, 0);+ const afterHotel = addVia(day.id, 1);+ const afterB = addVia(day.id, 2);+ const afterC = addVia(day.id, 3);++ const existing = svc.getAccommodation(accommodation.id, trip.id)!;+ const { mirror } = svc.updateAccommodation(accommodation.id, existing, { check_in: '20:00' }) as any;++ // The night is last now. The road out of it has no leg left and goes; the roads+ // behind B and C follow them one number up, and the one into the next day is+ // C's no longer.+ expect(stopsOn(day.id)).toEqual([a.id, b.id, c.id, hotel.id]);+ expect(viaAnchors(day.id)).toEqual([+ { id: afterA, after_order_index: 0 },+ { id: afterB, after_order_index: 1 },+ { id: afterC, after_order_index: 2 },+ ]);+ expect(viaAnchors(day.id).map(via => via.id)).not.toContain(afterHotel);+ expect(mirror.moved).not.toBeNull();+ expect(mirror.vias).toEqual([{ dayId: day.id, vias: expect.arrayContaining([expect.objectContaining({ id: afterB, after_order_index: 1 })]) }]);+ });++ it('ACC-034d cancelling the booking takes its stop out and re-pins the roads behind it', () => {+ const { user } = createUser(testDb);+ const trip = createTrip(testDb, user.id);+ const day = createDay(testDb, trip.id);+ const [a, b, hotel] = ['Harbour', 'Mercure', 'Billstedt'].map(name => createPlace(testDb, trip.id, { name }));+ createDayAssignment(testDb, day.id, a.id);+ pin(createDayAssignment(testDb, day.id, b.id).id, '12:00');+ const { accommodation } = svc.createAccommodation(trip.id, { place_id: hotel.id, start_day_id: day.id, end_day_id: day.id, check_in: '11:00' }) as any;+ expect(stopsOn(day.id)).toEqual([a.id, hotel.id, b.id]);+ // The road out of the hotel is drawn first: by id alone it would lead the leg+ // it ends up sharing with A's road.+ const afterHotel = addVia(day.id, 1);+ const afterA = addVia(day.id, 0);+ const intoTomorrow = addVia(day.id, 2);++ const { mirror } = svc.deleteAccommodation(accommodation.id);++ expect(stopsOn(day.id)).toEqual([a.id, b.id]);+ // The two legs around the hotel are one leg now, A to B, and the road out of the+ // hotel joins A's road on it, behind it: the drive runs A's point first, then the+ // hotel's, then B. The drive into the next day stays behind B, which is still last.+ expect(legOrder(day.id)).toEqual([+ { id: afterA, after_order_index: 0, sequence: 0 },+ { id: afterHotel, after_order_index: 0, sequence: 1 },+ { id: intoTomorrow, after_order_index: 1, sequence: 0 },+ ]);+ expect(mirror.vias).toEqual([{ dayId: day.id, vias: [+ expect.objectContaining({ id: afterA, after_order_index: 0, sequence: 0 }),+ expect.objectContaining({ id: afterHotel, after_order_index: 0, sequence: 1 }),+ expect.objectContaining({ id: intoTomorrow, after_order_index: 1 }),+ ] }]);+ });++ it('ACC-034e moving the booking to another day re-pins the roads on both days', () => {+ const { user } = createUser(testDb);+ const trip = createTrip(testDb, user.id);+ const day1 = createDay(testDb, trip.id);+ const day2 = createDay(testDb, trip.id);+ const [a, b, c, hotel] = ['Harbour', 'Mercure', 'Museum', 'Billstedt'].map(name => createPlace(testDb, trip.id, { name }));+ createDayAssignment(testDb, day1.id, a.id);+ pin(createDayAssignment(testDb, day1.id, b.id).id, '12:00');+ pin(createDayAssignment(testDb, day2.id, c.id).id, '14:00');+ const { accommodation } = svc.createAccommodation(trip.id, { place_id: hotel.id, start_day_id: day1.id, end_day_id: day1.id, check_in: '11:00' }) as any;+ expect(stopsOn(day1.id)).toEqual([a.id, hotel.id, b.id]);+ const afterA = addVia(day1.id, 0);+ const afterHotel = addVia(day1.id, 1);+ const outOfC = addVia(day2.id, 0);++ const existing = svc.getAccommodation(accommodation.id, trip.id)!;+ const { mirror } = svc.updateAccommodation(accommodation.id, existing, { start_day_id: day2.id, end_day_id: day2.id }) as any;++ expect(stopsOn(day1.id)).toEqual([a.id, b.id]);+ expect(stopsOn(day2.id)).toEqual([hotel.id, c.id]);+ // The hotel's road on day one joins A's on the leg that is left, behind it.+ expect(legOrder(day1.id)).toEqual([+ { id: afterA, after_order_index: 0, sequence: 0 },+ { id: afterHotel, after_order_index: 0, sequence: 1 },+ ]);+ // C is still the last stop of its day, one number further on.+ expect(viaAnchors(day2.id)).toEqual([{ id: outOfC, after_order_index: 1 }]);+ expect(mirror.vias.map((day: { dayId: number }) => day.dayId).sort()).toEqual([day1.id, day2.id].sort());+ });++ it('ACC-034f a stop the booking hands to the traveller moves no road', () => {+ const { trip, day, hotel } = afternoonDay();+ const { accommodation } = svc.createAccommodation(trip.id, { place_id: hotel.id, start_day_id: day.id, end_day_id: day.id, check_in: '11:00' }) as any;+ const afterB = addVia(day.id, 2);++ const { mirror } = svc.deleteAccommodation(accommodation.id, { keepStop: true });++ expect(viaAnchors(day.id)).toEqual([{ id: afterB, after_order_index: 2 }]);+ expect(mirror.vias).toBeUndefined();+ });++ it('ACC-034h a booking rebuilt from two stops reports its day once, as it stands at the end', () => {+ // A stay that owns two stops on one day cannot be carried across, so both go and+ // one comes back, and the day's roads are re-pinned at each step. What the mirror+ // reports is the state that was left behind, not both steps.+ const { trip, day, a, b, c, hotel } = afternoonDay();+ const { accommodation } = svc.createAccommodation(trip.id, { place_id: hotel.id, start_day_id: day.id, end_day_id: day.id, check_in: '11:00' }) as any;+ testDb.prepare('INSERT INTO day_assignments (day_id, place_id, order_index, accommodation_id) VALUES (?, ?, 4, ?)').run(day.id, hotel.id, accommodation.id);+ const afterA = addVia(day.id, 0);+ const afterHotel = addVia(day.id, 1);+ const afterB = addVia(day.id, 2);+ addVia(day.id, 3);++ const existing = svc.getAccommodation(accommodation.id, trip.id)!;+ const { mirror } = svc.updateAccommodation(accommodation.id, existing, { notes: 'late arrival' }) as any;++ expect(stopsOn(day.id)).toEqual([a.id, hotel.id, b.id, c.id]);+ expect(mirror.removed).toHaveLength(2);+ expect(mirror.created).not.toBeNull();+ // Both stops went, so the hotel's road joined A's; then the night came back+ // behind A, and B's road moved up with B. C's road was the last stop's leg+ // once the second stop was gone, and stayed gone.+ expect(mirror.vias).toEqual([{ dayId: day.id, vias: [+ expect.objectContaining({ id: afterA, after_order_index: 0, sequence: 0 }),+ expect.objectContaining({ id: afterHotel, after_order_index: 0, sequence: 1 }),+ expect.objectContaining({ id: afterB, after_order_index: 2 }),+ ] }]);+ });++ it('ACC-034g announceMirror sends the re-pinned roads behind the day order', () => {+ const sent: Array<{ event: string; payload: unknown }> = [];+ svc.announceMirror(5, {+ created: { id: 78, day_id: 11 } as never,+ moved: null,+ updated: [],+ removed: [],+ stamped: null,+ vias: [{ dayId: 11, vias: [] }],+ }, (event, payload) => { sent.push({ event, payload }); });+ expect(sent.map(e => e.event)).toEqual(['assignment:created', 'assignment:reordered', 'roadtripVia:changed']);+ expect(sent[2].payload).toEqual({ dayId: 11, vias: [] });+ });+});+describe('AccommodationsService wiring', () => {it('ACC-001: the module carries the controller and the RPC surface, and re-exports the service', () => {expectRegisteredController(AccommodationsModule, AccommodationsController);diff --git a/server/tests/unit/nest/calendar.service.test.ts b/server/tests/unit/nest/calendar.service.test.tsindex f27c780c2..8a00d2b8a 100644--- a/server/tests/unit/nest/calendar.service.test.ts+++ b/server/tests/unit/nest/calendar.service.test.ts@@ -1121,6 +1121,29 @@ describe('accommodations', () => {expect(ics).not.toContain('Check-in: Bellevue second room');expect(ics).toContain('SUMMARY:Bellevue second room');});++ it('CAL-060: the stop a booking puts on its check-in day does not list the hotel a second time', () => {+ const { user } = createUser(testDb);+ const trip = createTrip(testDb, user.id, { title: 'Paris' });+ const { stayId, placeId } = createStay(trip.id, { start: '2026-07-07', end: '2026-07-12' });+ const stay = testDb.prepare('SELECT start_day_id FROM day_accommodations WHERE id = ?')+ .get(stayId) as { start_day_id: number };+ // The stop a booked night puts on its check-in day, so the route can reach+ // the hotel. It belongs to the stay, not to the day's plan, and the stay+ // block already carries the hotel.+ testDb.prepare('INSERT INTO day_assignments (day_id, place_id, order_index, accommodation_id) VALUES (?, ?, 0, ?)')+ .run(stay.start_day_id, placeId, stayId);+ // A place the traveller planned by hand on the same day stays on it.+ const museum = createPlace(testDb, trip.id, { name: 'Louvre' });+ createDayAssignment(testDb, stay.start_day_id, museum.id);++ const { ics } = svc.exportICS(trip.id);++ expect(ics).toContain('DTSTART;VALUE=DATE:20260707\r\nDTEND;VALUE=DATE:20260713');+ expect(ics.match(/Hotel Bellevue/g)).toHaveLength(1);+ expect(ics).toContain('• Louvre');+ expect(ics).not.toContain('• Hotel Bellevue');+ });});// ── Car rental pickup/drop-off in the feed (#1721) ──────────────────────────diff --git a/server/tests/unit/nest/collections.service.test.ts b/server/tests/unit/nest/collections.service.test.tsindex 438e007cd..48fd050bf 100644--- a/server/tests/unit/nest/collections.service.test.ts+++ b/server/tests/unit/nest/collections.service.test.ts@@ -619,7 +619,8 @@ describe('collection labels', () => {const viewer = createUser(testDb).user;const col = svc.createCollection(owner.id, { name: 'Trip' });addMember(col.id, viewer.id, 'viewer');- try { svc.createLabel(viewer.id, col.id, 'X'); } catch (e) { expect((e as { status: number }).status).toBe(403); }+ expect(() => svc.createLabel(viewer.id, col.id, 'X')).toThrow(expect.objectContaining({ status: 403, message: 'You have read-only access to this list' }));+ expect(svc.getCollection(owner.id, col.id).collection.labels).toHaveLength(0);const editor = createUser(testDb).user;addMember(col.id, editor.id, 'editor');diff --git a/server/tests/unit/nest/dawarich-suggestions.service.test.ts b/server/tests/unit/nest/dawarich-suggestions.service.test.tsindex 00c912e35..5999e467e 100644--- a/server/tests/unit/nest/dawarich-suggestions.service.test.ts+++ b/server/tests/unit/nest/dawarich-suggestions.service.test.ts@@ -1,5 +1,5 @@/**- * Unit tests for DawarichSuggestionsService: DAWARICH-SUG-001..062.+ * Unit tests for DawarichSuggestionsService: DAWARICH-SUG-001..064.** This is the only service in the Dawarich domain that writes into TREK proper,* and every write it makes crosses an ownership line: a suggestion belongs to@@ -99,7 +99,10 @@ const clientStub = {findVisitsNear: vi.fn(),listVisitedCities: vi.fn(),};-const atlasStub = { markCountry: vi.fn() };+// `stats` is what the Atlas map is drawn from, and "already visited" in the+// hand-off means "already on that map", so the stub answers it as the map+// would: a list of countries with the status each is painted in.+const atlasStub = { markCountry: vi.fn(), stats: vi.fn() };// `broadcast` and `onCreated` are stubbed because an acceptance is a normal// place write and has to behave like one: everyone on the trip is told, and a// live journey mirrors it. Both are asserted rather than merely tolerated.@@ -151,6 +154,8 @@ function armStubs(): void {clientStub.listVisitedCities.mockReset();// Answers true — it added the country — unless a case says otherwise.atlasStub.markCountry.mockReset().mockReturnValue(true);+ // An empty map unless a case paints something on it.+ atlasStub.stats.mockReset().mockResolvedValue({ countries: [] });placesStub.create.mockReset().mockImplementation((tripId: string, body: { name?: string; lat?: number; lng?: number }) =>@@ -1137,7 +1142,9 @@ describe('DawarichSuggestionsService — the Atlas hand-off', () => {it('DAWARICH-SUG-030: atlasSuggestions codes what it can, lists what it cannot, and flags what TREK already has', async () => {const { user } = createUser(testDb);- testDb.prepare('INSERT INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(user.id, 'DE');+ // A hand mark, as the Atlas reports it back: the map merges visited_countries+ // into its own list, so it is the map that is asked, not the table.+ atlasStub.stats.mockResolvedValue({ countries: [{ code: 'DE', status: 'visited' }] });clientStub.listVisitedCities.mockResolvedValue([{ country: 'Germany', cities: [{ city: 'Berlin', stayed_for: 120, timestamp: 1757000000 }] },{ country: 'France', cities: [] },@@ -1152,6 +1159,49 @@ describe('DawarichSuggestionsService — the Atlas hand-off', () => {expect(suggestions.countries[1].alreadyVisited).toBe(false);// A country TREK cannot code is still a country the user went to.expect(suggestions.unresolved).toEqual(['Absurdistan']);+ expect(atlasStub.stats).toHaveBeenCalledWith(user.id);+ });++ it('DAWARICH-SUG-063: a country the Atlas already paints from a past trip is not offered as new, hand mark or not', async () => {+ // The map derives Japan from the places on a finished trip and needs no+ // visited_countries row to do so. Offering it back, preselected, would+ // make the dialog a list of things the user has known for years, and the+ // toast afterwards would count countries that changed nothing on the map.+ const { user } = createUser(testDb);+ atlasStub.stats.mockResolvedValue({+ countries: [+ { code: 'JP', status: 'visited' },+ // Planned is a future trip: not on the map as visited yet, so still news.+ { code: 'FR', status: 'planned' },+ ],+ });+ clientStub.listVisitedCities.mockResolvedValue([+ { country: 'Japan', cities: [{ city: 'Tokyo', stayed_for: 600 }] },+ { country: 'France', cities: [] },+ { country: 'Austria', cities: [] },+ ]);++ const suggestions = await svc.atlasSuggestions(user.id, new Date('2026-08-01'), new Date('2026-09-01'));++ expect(suggestions.countries.map((c) => [c.countryCode, c.alreadyVisited])).toEqual([+ ['JP', true],+ ['FR', false],+ ['AT', false],+ ]);+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM visited_countries WHERE user_id = ?').get(user.id)).toEqual({ n: 0 });+ });++ it('DAWARICH-SUG-064: the shape the Atlas answers for a user without trips carries no status and reads as visited', async () => {+ // With no trips at all the map lists only hand marks, without a status+ // field, and paints every one of them as visited.+ const { user } = createUser(testDb);+ atlasStub.stats.mockResolvedValue({ countries: [{ code: 'DE' }] });+ clientStub.listVisitedCities.mockResolvedValue([{ country: 'Germany', cities: [] }]);++ const suggestions = await svc.atlasSuggestions(user.id, new Date('2026-08-01'), new Date('2026-09-01'));++ expect(suggestions.countries).toHaveLength(1);+ expect(suggestions.countries[0]).toMatchObject({ countryCode: 'DE', alreadyVisited: true });});it('DAWARICH-SUG-057: atlasSuggestions without a connection refuses before a request', async () => {diff --git a/server/tests/unit/nest/dawarich-sync.service.test.ts b/server/tests/unit/nest/dawarich-sync.service.test.tsindex cbccb36d5..ae31c8ca0 100644--- a/server/tests/unit/nest/dawarich-sync.service.test.ts+++ b/server/tests/unit/nest/dawarich-sync.service.test.ts@@ -310,6 +310,101 @@ describe('DawarichSyncService — new visits', () => {});});+// ── Which trip a stay lands on ───────────────────────────────────────────────++describe('DawarichSyncService, neighbouring trips', () => {+ /** A trip that starts the day after TRIP ends, so its lookback reaches into TRIP's last days. */+ function nextTrip(): number {+ return createTrip(testDb, USER, { start_date: dayOffset(-24), end_date: dayOffset(-20) }).id;+ }++ /** A stay on TRIP's last day: inside TRIP's own dates and inside the next trip's lookback. */+ function lastDayVisit(id: number): DawarichVisitRaw {+ return visit({ id, started_at: `${TRIP_END}T09:00:00Z`, ended_at: `${TRIP_END}T12:00:00Z` });+ }++ it('DAWARICH-SYNC-074: a stay on the last day of a trip lands on that trip, not on the neighbour whose lookback reached it', async () => {+ // Trips are walked newest first, so the neighbour asks first and both+ // windows return the same stay. The trip whose dates hold it has to win,+ // or the last days of every city hop show up under the next city.+ const next = nextTrip();+ withVisits(lastDayVisit(910));++ const result = await svc.syncUser(USER);++ expect(listVisits).toHaveBeenCalledTimes(2);+ expect(result).toMatchObject({ state: 'ok', created: 1, missing: 0 });+ const row = only();+ expect(row.trip_id).toBe(TRIP);+ expect(row.trip_id).not.toBe(next);+ });++ it('DAWARICH-SYNC-075: a stay already parked on the wrong neighbour moves to the trip whose dates hold it', async () => {+ // What an earlier run left behind. Nobody acted on the row, so re-homing+ // it loses nothing, and the panel of the trip it belongs to fills in.+ const next = nextTrip();+ testDb+ .prepare(+ `INSERT INTO dawarich_visit_suggestions+ (user_id, source_visit_id, trip_id, name, lat, lng, started_at, ended_at, duration_minutes,+ local_date, source_status, state, source_hash)+ VALUES (?, '911', ?, 'Hotel Adlon', ?, ?, ?, ?, 180, ?, 'suggested', 'new', 'stale')`,+ )+ .run(USER, next, LAT, LNG, `${TRIP_END}T09:00:00Z`, `${TRIP_END}T12:00:00Z`, TRIP_END);+ withVisits(lastDayVisit(911));++ const result = await svc.syncUser(USER);++ expect(result).toMatchObject({ created: 0, missing: 0 });+ expect(only().trip_id).toBe(TRIP);+ });++ it('DAWARICH-SYNC-076: a row the user already acted on keeps its trip', async () => {+ // An acceptance made a place on that trip. Moving the row out from under+ // it would leave the handled list pointing somewhere else than the place.+ const next = nextTrip();+ testDb+ .prepare(+ `INSERT INTO dawarich_visit_suggestions+ (user_id, source_visit_id, trip_id, name, lat, lng, started_at, ended_at, duration_minutes,+ local_date, source_status, state, source_hash)+ VALUES (?, '912', ?, 'Hotel Adlon', ?, ?, ?, ?, 180, ?, 'suggested', 'accepted', 'stale')`,+ )+ .run(USER, next, LAT, LNG, `${TRIP_END}T09:00:00Z`, `${TRIP_END}T12:00:00Z`, TRIP_END);+ withVisits(lastDayVisit(912));++ await svc.syncUser(USER);++ expect(only().trip_id).toBe(next);+ });++ it('DAWARICH-SYNC-077: a stay in the slack before departure, inside no trip at all, stays with the window that found it', async () => {+ // The evening before is why the lookback exists. With no other trip to+ // claim it, the stay belongs to the trip that asked, exactly as before.+ const eve = dayOffset(-31);+ withVisits(visit({ id: 913, started_at: `${eve}T20:00:00Z`, ended_at: `${eve}T22:00:00Z` }));++ await svc.syncUser(USER);++ const row = only();+ expect(row.local_date).toBe(eve);+ expect(row.trip_id).toBe(TRIP);+ });++ it('DAWARICH-SYNC-078: a trip whose start is not a date cannot claim a stay from the sidelines', async () => {+ // Such a trip is skipped by the window guard, and it must not turn into a+ // catch-all for every stay outside the trips that are actually walked.+ createTrip(testDb, USER, { start_date: '0000-00-00' });+ const eve = dayOffset(-31);+ withVisits(visit({ id: 914, started_at: `${eve}T20:00:00Z`, ended_at: `${eve}T22:00:00Z` }));++ await svc.syncUser(USER);++ expect(listVisits).toHaveBeenCalledTimes(1);+ expect(only().trip_id).toBe(TRIP);+ });+});+// ── Idempotency and change detection ─────────────────────────────────────────describe('DawarichSyncService — repeated runs', () => {diff --git a/server/tests/unit/nest/dawarich.service.test.ts b/server/tests/unit/nest/dawarich.service.test.tsindex 62cf5f645..e048ae3f7 100644--- a/server/tests/unit/nest/dawarich.service.test.ts+++ b/server/tests/unit/nest/dawarich.service.test.ts@@ -798,6 +798,46 @@ describe('DawarichService saveSettings', () => {capabilities: JSON.stringify(FULL_CAPS),});});++ it('DAWARICH-SVC-072: a key typed with the host change keeps the key but still drops what the old instance answered', async () => {+ // The probe blob and the sync history describe the server the row used to+ // point at. Carrying them over would show the old instance's version and+ // "last sync ok" on a connection that has never been asked anything, and+ // the tracks layer would skip an endpoint the new instance does have.+ connect(USER, {+ url: 'https://old.example',+ apiKey: 'stored-key',+ lastSyncAt: '2026-09-12T04:15:00.000Z',+ lastSyncState: 'ok',+ lastSyncError: 'rate_limited',+ capabilities: JSON.stringify(FULL_CAPS),+ });++ await svc.saveSettings(USER, 'https://new.example', 'minted-for-new', false, true, IP);++ expect(svc.getCredentials(USER)?.apiKey).toBe('minted-for-new');+ const stored = row();+ expect(stored?.url).toBe('https://new.example');+ expect(stored?.capabilities).toBeNull();+ expect(stored?.last_sync_state).toBe('never');+ expect(stored?.last_sync_error).toBeNull();+ expect(stored?.last_sync_at).toBeNull();+ });++ it('DAWARICH-SVC-073: a new key on the same host keeps the probe, because it describes the host and not the key', async () => {+ connect(USER, {+ url: 'https://d.example/api',+ apiKey: 'stored-key',+ lastSyncState: 'ok',+ capabilities: JSON.stringify(FULL_CAPS),+ });++ await svc.saveSettings(USER, 'https://d.example/', 'rotated-key', false, true, IP);++ expect(svc.getCredentials(USER)?.apiKey).toBe('rotated-key');+ expect(row()?.capabilities).toBe(JSON.stringify(FULL_CAPS));+ expect(row()?.last_sync_state).toBe('ok');+ });});// ---------------------------------------------------------------------------@@ -987,6 +1027,50 @@ describe('DawarichService testConnection', () => {});expect(client.probe).not.toHaveBeenCalled();});++ it('DAWARICH-SVC-105: a blank key field against a different host than the stored one is refused before anything is sent', async () => {+ // The form prefills the address and never the key, so "retype the URL and+ // press Test" is the ordinary way to move an instance. Falling back to the+ // stored key here would carry it to whatever host was just typed, which is+ // exactly what saveSettings refuses to persist.+ connect(USER, { url: 'https://old.example', apiKey: 'stored-key' });++ const out = await svc.testConnection(USER, 'https://someone-elses.example', undefined, false);++ expect(out).toMatchObject({ connected: false, error: 'not_connected' });+ expect(out.errorDetail).toContain('https://old.example');+ expect(client.probe).not.toHaveBeenCalled();+ });++ it('DAWARICH-SVC-106: the mask against a different host is a blank field, not a key', async () => {+ connect(USER, { url: 'https://old.example', apiKey: 'stored-key' });++ const out = await svc.testConnection(USER, 'https://old.example:8443', DAWARICH_KEY_MASK, false);++ expect(out).toMatchObject({ connected: false, error: 'not_connected' });+ expect(client.probe).not.toHaveBeenCalled();+ });++ it('DAWARICH-SVC-107: a path edit on the same origin still tests with the stored key', async () => {+ // The mirror of 105: the same instance under a corrected path is where the+ // key was issued, and refusing it would make every trailing-slash edit+ // demand the key again.+ connect(USER, { url: 'https://d.example/api', apiKey: 'stored-key' });++ const out = await svc.testConnection(USER, 'https://d.example/', undefined, false);++ expect(out.connected).toBe(true);+ expect(client.probe).toHaveBeenCalledWith({ baseUrl: 'https://d.example/', apiKey: 'stored-key', allowInsecureTls: false });+ });++ it('DAWARICH-SVC-108: a key typed for the new host is used as typed, so moving an instance and testing it first still works', async () => {+ connect(USER, { url: 'https://old.example', apiKey: 'stored-key' });++ const out = await svc.testConnection(USER, 'https://new.example', 'minted-for-new', false);++ expect(out.connected).toBe(true);+ expect(client.probe).toHaveBeenCalledWith({ baseUrl: 'https://new.example', apiKey: 'minted-for-new', allowInsecureTls: false });+ });});// ---------------------------------------------------------------------------diff --git a/server/tests/unit/nest/doc-sync/doc-sync-config.service.test.ts b/server/tests/unit/nest/doc-sync/doc-sync-config.service.test.tsindex b25f1eadb..7db14c809 100644--- a/server/tests/unit/nest/doc-sync/doc-sync-config.service.test.ts+++ b/server/tests/unit/nest/doc-sync/doc-sync-config.service.test.ts@@ -175,6 +175,102 @@ describe('upsertConnection secrets', () => {expect(count.n).toBe(1);});+ /**+ * A stored secret only ever goes to the address it was stored against.+ *+ * Merged under a new host, a blank form carried the token there: a trip+ * changes hands with its connection, and the new owner or an instance admin+ * could point the previous owner's Paperless token at a server of their own+ * and read it off the first request. The probe route had this rule; the+ * save route did not.+ */+ describe('under a new address', () => {+ it('refuses to carry the stored secret over, and writes nothing', async () => {+ const created = await connect();+ const result = await svc.upsertConnection(TRIP, MEMBER, connectionInput({+ baseUrl: 'https://attacker.example.net',+ credentials: {},+ }));++ expect(docFailed(result)).toBe(true);+ expect(docFailed(result) && result.error.code).toBe('unauthorized');+ const row = svc.getConnection(created.id) as ConnectionRow;+ expect(row.base_url).toBe('https://paperless.example.com');+ expect(row.owner_user_id).toBe(OWNER);+ expect(storedSecret(created.id)).toBe(TOKEN);+ });++ it('refuses the mask as well, since the mask is not the credential', async () => {+ await connect();+ const result = await svc.upsertConnection(TRIP, OWNER, connectionInput({+ baseUrl: 'https://paperless.example.net',+ credentials: { api_token: DOCSYNC_SECRET_MASK },+ }));+ expect(docFailed(result) && result.error.code).toBe('unauthorized');+ });++ it('takes a credential typed in for it', async () => {+ const created = await connect();+ const moved = await connect({ baseUrl: 'https://paperless.example.net', credentials: { api_token: 'new-token' } });+ expect(moved.id).toBe(created.id);+ expect(moved.base_url).toBe('https://paperless.example.net');+ expect(storedSecret(created.id)).toBe('new-token');+ });++ it('drops a secret the provider earned for the old address, even when the form is complete', async () => {+ const conn = await connect({ providerId: 'synologydrive', baseUrl: 'https://nas.example.com:5001', credentials: { username: 'anna', password: 'nas-pw' } });+ svc.saveEarnedSecret(conn.id, 'device_token', 'a1b2c3:DEVICE-7');++ await connect({ providerId: 'synologydrive', baseUrl: 'https://nas.example.net:5001', credentials: { username: 'anna', password: 'nas-pw' } });++ expect(svc.toRef(svc.getConnection(conn.id) as ConnectionRow).secrets).toEqual({ password: 'nas-pw' });+ });++ it('reads a path or a trailing slash on the same server as the same address', async () => {+ const created = await connect();+ await connect({ baseUrl: 'https://paperless.example.com/paperless/', credentials: {} });+ expect(storedSecret(created.id)).toBe(TOKEN);+ });++ it('reads another port or scheme as another server', async () => {+ await connect();+ const port = await svc.upsertConnection(TRIP, OWNER, connectionInput({ baseUrl: 'https://paperless.example.com:8443', credentials: {} }));+ const scheme = await svc.upsertConnection(TRIP, OWNER, connectionInput({ baseUrl: 'http://paperless.example.com', credentials: {} }));+ expect(docFailed(port)).toBe(true);+ expect(docFailed(scheme)).toBe(true);+ });+ });++ /**+ * Who the credential belongs to is written down with it, and the orphan+ * check reads it: a binding stands down once that person leaves the trip.+ * The caller took the row over on every save, so an edit that kept the+ * stored token read as the caller's own token from then on.+ */+ describe('the credential owner', () => {+ it('stays with the person whose secret is stored when somebody else saves the form blank', async () => {+ const created = await connect();+ await connect({ credentials: {} }, MEMBER);+ expect((svc.getConnection(created.id) as ConnectionRow).owner_user_id).toBe(OWNER);+ });++ it('moves to the person who typed a new secret in', async () => {+ const created = await connect();+ await connect({ credentials: { api_token: 'members-own-token' } }, MEMBER);+ expect((svc.getConnection(created.id) as ConnectionRow).owner_user_id).toBe(MEMBER);+ });++ it('stays put when only an optional secret is typed, since that runs against the stored password', async () => {+ const nas = { providerId: 'synologydrive' as const, baseUrl: 'https://nas.example.com:5001' };+ const created = await connect({ ...nas, credentials: { username: 'anna', password: 'nas-pw' } });+ await connect({ ...nas, credentials: { username: 'anna', otp_code: '123456' } }, MEMBER);++ const row = svc.getConnection(created.id) as ConnectionRow;+ expect(row.owner_user_id).toBe(OWNER);+ expect(svc.toRef(row).secrets).toEqual({ password: 'nas-pw', otp_code: '123456' });+ });+ });+it('carries a non-secret setting forward when a later save omits it', async () => {const created = await svc.upsertConnection(TRIP, OWNER, {providerId: 'nextcloud',diff --git a/server/tests/unit/nest/doc-sync/doc-sync-webhook.controller.test.ts b/server/tests/unit/nest/doc-sync/doc-sync-webhook.controller.test.tsindex a3415ef52..6043b0b99 100644--- a/server/tests/unit/nest/doc-sync/doc-sync-webhook.controller.test.ts+++ b/server/tests/unit/nest/doc-sync/doc-sync-webhook.controller.test.ts@@ -37,6 +37,11 @@ import type { DatabaseService } from '../../../../src/nest/database/database.serconst SECRET = 'M7dQ2vLp5rTn8kYw1xZc4bJh';+/**+ * A binding whose subscription TREK registered itself, so the provider was+ * handed the secret and is expected to present it. A binding pasted in by+ * hand has no subscription id; see the cases on that below.+ */const link = (over: Partial<LinkRow> = {}): LinkRow => ({id: 4,trip_id: 1,@@ -52,7 +57,7 @@ const link = (over: Partial<LinkRow> = {}): LinkRow => ({sync_enabled: 1,webhook_token: 'tok-live',webhook_secret: 'enc:v1:whatever',- webhook_subscription_id: null,+ webhook_subscription_id: 'sub-7',remote_cursor: null,last_sync_at: null,last_sync_state: 'never',@@ -182,6 +187,45 @@ describe('a shared-secret header', () => {});});+/**+ * A URL somebody pasted into the store by hand.+ *+ * Papra's webhook settings are closed to API keys and Nextcloud's need admin+ * rights, so the person copies the address off the binding card. The secret+ * behind it is never shown to anybody, and Papra signs with a secret of its+ * own, so no such call could ever carry the one TREK holds. Every one of them+ * was dropped, and the binding ran on the timer while the card promised+ * instant updates. The token in the URL is the whole credential there.+ */+describe('a binding pasted into the store by hand', () => {+ const pasted = () => link({ webhook_subscription_id: null });++ beforeEach(() => {+ config.getLinkByToken.mockImplementation((token: string) => (token === 'tok-live' ? pasted() : undefined));+ config.getLink.mockImplementation((id: number) => (id === 4 ? pasted() : undefined));+ });++ it('runs on the token alone, with no secret in the call', () => {+ controller.nudge('tok-live', makeReq());+ settle();+ expect(sync.syncLink).toHaveBeenCalledTimes(1);+ expect(config.webhookSecret).not.toHaveBeenCalled();+ });++ it('runs on a Papra call signed with a secret TREK has never seen', () => {+ const payload = JSON.stringify({ event: 'document.created', documentId: 'doc_1' });+ controller.nudge('tok-live', papraReq(payload, sign(payload, 'papras-own-signing-secret')));+ settle();+ expect(sync.syncLink).toHaveBeenCalledTimes(1);+ });++ it('still needs the right token', () => {+ controller.nudge('tok-guessed', makeReq());+ settle();+ expect(sync.syncLink).not.toHaveBeenCalled();+ });+});+describe('a Papra standard-webhooks signature', () => {const payload = JSON.stringify({ event: 'document.created', documentId: 'doc_1' });diff --git a/server/tests/unit/nest/doc-sync/doc-sync.controller.test.ts b/server/tests/unit/nest/doc-sync/doc-sync.controller.test.tsindex c732a7882..db5196f11 100644--- a/server/tests/unit/nest/doc-sync/doc-sync.controller.test.ts+++ b/server/tests/unit/nest/doc-sync/doc-sync.controller.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';-import { HttpException } from '@nestjs/common';+import { HttpException, Logger } from '@nestjs/common';import type { Request } from 'express';/**@@ -276,6 +276,19 @@ describe('storing a connection', () => {expect(config.listConnections(tripId)).toHaveLength(0);});+ it('refuses to point the stored secret at another server when the form leaves it blank', async () => {+ // The probe route had this rule; the save route let an instance admin, or+ // whoever the trip was handed to, redirect the owner's token to a host of+ // their own with an empty form.+ const conn = await storedPaperless();+ const err = await thrown(() =>+ controller.upsertConnection(String(tripId), admin, connBody({ baseUrl: 'https://elsewhere.example', credentials: {} })),+ );+ expect(err.getStatus()).toBe(400);+ expect(config.getConnection(conn.id)!.base_url).toBe('https://paperless.example.com');+ expect(config.getConnection(conn.id)!.owner_user_id).toBe(Number(owner.id));+ });+it('refuses a provider the instance admin has not switched on, and names it', async () => {testDb.prepare("UPDATE document_providers SET enabled = 0 WHERE id = 'papra'").run();const err = await thrown(() =>@@ -432,11 +445,43 @@ describe('removing a connection', () => {.run(tripId, 'stored.pdf', 'boarding.pdf').lastInsertRowid,);- expect(controller.deleteConnection(String(tripId), String(conn.id), owner)).toEqual({ success: true });+ await expect(controller.deleteConnection(String(tripId), String(conn.id), owner)).resolves.toEqual({ success: true });expect(config.getConnection(conn.id)).toBeUndefined();expect(testDb.prepare('SELECT id FROM trip_files WHERE id = ?').get(fileId)).toBeTruthy();});+ it('takes down every subscription TREK registered for its bindings, before the credential goes', async () => {+ // The bindings cascade away with the connection, and the rows were the+ // only record of the Paperless workflows and Nextcloud listeners TREK had+ // set up: left standing, they keep posting to a token that answers+ // nothing, for good. Unbinding one binding already did this.+ const conn = await storedPaperless();+ const first = (await controller.createLink(+ String(tripId), owner, linkBody(conn.id, { scopeKey: 'tag:1' }), makeReq({ host: 'trek.example' }),+ )) as { id: number };+ paperless.registerWebhook.mockResolvedValueOnce({ success: true, data: { subscriptionId: 'sub-8' } } as never);+ await controller.createLink(String(tripId), owner, linkBody(conn.id, { scopeKey: 'tag:2' }), makeReq({ host: 'trek.example' }));+ // One that never got a subscription, which must not be unregistered as ''.+ await controller.createLink(String(tripId), owner, linkBody(conn.id, { scopeKey: 'tag:3' }), makeReq());+ paperless.unregisterWebhook.mockClear();++ await controller.deleteConnection(String(tripId), String(conn.id), owner);++ expect(paperless.unregisterWebhook.mock.calls.map((c) => c[1]).sort()).toEqual(['sub-7', 'sub-8']);+ expect(paperless.unregisterWebhook.mock.calls[0][0]).toMatchObject({ connectionId: conn.id, secrets: { api_token: 'stored-token' } });+ expect(config.getConnection(conn.id)).toBeUndefined();+ expect(config.getLink(first.id)).toBeUndefined();+ });++ it('still unbinds when the provider refuses to take a subscription down', async () => {+ const conn = await storedPaperless();+ await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq({ host: 'trek.example' }));+ paperless.unregisterWebhook.mockResolvedValueOnce({ success: false, error: { code: 'unreachable' } } as never);++ await expect(controller.deleteConnection(String(tripId), String(conn.id), owner)).resolves.toEqual({ success: true });+ expect(config.getConnection(conn.id)).toBeUndefined();+ });+it('refuses a connection that belongs to a different trip', async () => {const conn = await storedPaperless();const err = await thrown(() => controller.deleteConnection(String(otherTripId), String(conn.id), admin));@@ -462,7 +507,7 @@ describe('removing a connection', () => {const second = bind(conn.id, 'tag:2');bind(cloud.data.id, 'folder:1');- controller.deleteConnection(String(tripId), String(conn.id), owner);+ await controller.deleteConnection(String(tripId), String(conn.id), owner);expect(realtime.broadcast.mock.calls).toEqual([[tripId, 'docsync:changed', { linkId: first, pulled: 0, pushed: 0 }],@@ -571,6 +616,27 @@ describe('creating a binding', () => {expect(row.sync_enabled).toBe(1);});+ it('says so in the log when the provider refuses the subscription, since nothing on screen will', async () => {+ // The refusal used to go nowhere at all: not thrown, not logged, and the+ // first run overwrites the link state a moment later. An admin whose+ // Paperless kept declining the workflow had no way to find out why the+ // binding only ever ran on the timer.+ const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);+ try {+ const conn = await storedPaperless();+ paperless.registerWebhook.mockResolvedValueOnce({ success: false, error: { code: 'forbidden', detail: 'API key may not manage workflows' } } as never);++ const link = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq({ host: 'trek.example' }))) as { id: number };++ const lines = warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes(`link ${link.id}`));+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('forbidden');+ expect(lines[0]).toContain('API key may not manage workflows');+ } finally {+ warn.mockRestore();+ }+ });+it('does not offer a webhook when no host reaches TREK', async () => {const conn = await storedPaperless();const link = (await controller.createLink(String(tripId), owner, linkBody(conn.id), makeReq())) as { webhookUrl: string | null };@@ -808,6 +874,22 @@ describe('the callback origin a provider is given', () => {const [link] = controller.listLinks(String(tripId), makeReq()) as Array<{ webhookUrl: string | null }>;expect(link.webhookUrl).toBeNull();});++ it('offers no callback URL for a store the probe found unable to call back at all', async () => {+ // Synology takes no webhook. Showing the address with "paste this into+ // your provider" next to it promised something there was nowhere to do.+ const row = await linkedTrip();+ config.recordProbe(row.connection_id, 'ok', null, { ...CAPS, push: 'none' });+ const [link] = controller.listLinks(String(tripId), makeReq({ host: 'trek.example' })) as Array<{ webhookUrl: string | null }>;+ expect(link.webhookUrl).toBeNull();+ });++ it('keeps offering it for a store the probe found able to take one', async () => {+ const row = await linkedTrip();+ config.recordProbe(row.connection_id, 'ok', null, { ...CAPS, push: 'webhook-manual' });+ const [link] = controller.listLinks(String(tripId), makeReq({ host: 'trek.example' })) as Array<{ webhookUrl: string | null }>;+ expect(link.webhookUrl).toBe(`http://trek.example/api/docsync/webhook/${row.webhook_token}`);+ });});/**diff --git a/server/tests/unit/nest/doc-sync/doc-sync.helpers.test.ts b/server/tests/unit/nest/doc-sync/doc-sync.helpers.test.tsindex 0019eaa23..c81eb6111 100644--- a/server/tests/unit/nest/doc-sync/doc-sync.helpers.test.ts+++ b/server/tests/unit/nest/doc-sync/doc-sync.helpers.test.ts@@ -133,6 +133,50 @@ describe('planReconcile', () => {expect(p.actions[0].kind).toBe('pull_update');});+ /**+ * A version marker that moved over the same bytes. Paperless bumps+ * `modified` for a tag, a correspondent or a title, and a pulled document+ * has no `pushedSha256` for the echo guard to read: every such edit fetched+ * the same bytes again, put them in a fresh row without the booking link the+ * old one carried, and sent the old row to the trash.+ */+ it('treats a marker that moved over the agreed bytes as no change either', () => {+ const p = plan({+ items: [item({ contentSha256: 'aaa', pushedSha256: null })],+ remote: [remote({ remoteVersion: 'v2', contentHash: 'aaa' })],+ local: [local()],+ });+ expect(p.actions).toEqual([{ kind: 'touch', itemId: 10, remote: remote({ remoteVersion: 'v2', contentHash: 'aaa' }) }]);+ });++ it('still follows a rename that came with such an edit', () => {+ const renamed = remote({ remoteVersion: 'v2', contentHash: 'aaa', name: 'hotel-booking.pdf' });+ const p = plan({+ items: [item({ contentSha256: 'aaa', pushedSha256: null })],+ remote: [renamed],+ local: [local()],+ });+ expect(p.actions).toEqual([{ kind: 'rename_local', itemId: 10, fileId: 1, name: 'hotel-booking.pdf' }]);+ });++ it('still pulls when the listing carries no hash to compare', () => {+ const p = plan({+ items: [item({ contentSha256: 'aaa', pushedSha256: null })],+ remote: [remote({ remoteVersion: 'v2', contentHash: null })],+ local: [local()],+ });+ expect(p.actions[0].kind).toBe('pull_update');+ });++ it('still retries a row in error over the same bytes, since touch would leave it there for good', () => {+ const p = plan({+ items: [item({ state: 'error', contentSha256: 'aaa', pushedSha256: null })],+ remote: [remote({ remoteVersion: 'v2', contentHash: 'aaa' })],+ local: [local()],+ });+ expect(p.actions[0].kind).toBe('pull_update');+ });+/*** An unmounted share and a revoked token both answer with a short listing.* Reading that as a mass deletion would empty a trip, so the run refuses@@ -632,6 +676,51 @@ describe('planReconcile > a provider name TREK had to clean up', () => {});});+/**+ * TREK's own name with a character the cleaning replaces.+ *+ * An upload keeps the name the browser sent, and on Linux and macOS that may+ * be `Zugticket 08:15.pdf`. A push stores it as the agreed name, and the next+ * run compared the raw TREK name with the cleaned agreed name, which never+ * match: Paperless was sent the same title on every run, and on Nextcloud,+ * which cleans the colon its own way, the row sat in a conflict that "keep+ * TREK" could never settle, because the three names came out the same again.+ */+describe('planReconcile > a TREK name the cleaning would change', () => {+ const pushed = item({ remoteName: 'Zugticket 08:15.pdf', contentSha256: 'aaa', pushedSha256: 'aaa' });+ const mine = local({ fileId: 1, name: 'Zugticket 08:15.pdf' });++ it('does not read the cleaning as a rename made in TREK', () => {+ // Paperless keeps the title as it was sent, so the listing carries the colon.+ const p = plan({ items: [pushed], remote: [remote({ name: 'Zugticket 08:15.pdf' })], local: [mine] });+ expect(p.actions.map(a => a.kind)).toEqual(['touch']);+ });++ it('follows the name the store made of it where the store cleans differently', () => {+ // Nextcloud stores a dash, which is the store's rename to follow, once.+ const stored = remote({ name: 'Zugticket 08-15.pdf' });+ const first = plan({ items: [pushed], remote: [stored], local: [mine] });+ expect(first.actions).toEqual([{ kind: 'rename_local', itemId: 10, fileId: 1, name: 'Zugticket 08-15.pdf' }]);++ const second = plan({+ items: [item({ remoteName: 'Zugticket 08-15.pdf', contentSha256: 'aaa', pushedSha256: 'aaa' })],+ remote: [stored],+ local: [local({ fileId: 1, name: 'Zugticket 08-15.pdf' })],+ });+ expect(second.actions).toEqual([{ kind: 'touch', itemId: 10, remote: stored }]);+ });++ it('sends nothing upstream on a push-only binding either', () => {+ const p = plan({ items: [pushed], remote: [remote({ name: 'Zugticket 08:15.pdf' })], local: [mine], direction: 'push' });+ expect(p.actions.map(a => a.kind)).toEqual(['touch']);+ });++ it('still sends a real rename made in TREK', () => {+ const p = plan({ items: [pushed], remote: [remote({ name: 'Zugticket 08:15.pdf' })], local: [local({ fileId: 1, name: 'Zugticket 09:15.pdf' })] });+ expect(p.actions).toEqual([{ kind: 'rename_remote', itemId: 10, remoteId: 'r1', name: 'Zugticket 09:15.pdf' }]);+ });+});+/*** A rename upstream where the id is the path, which is Synology FileStation.*@@ -983,6 +1072,35 @@ describe('planReconcile > a deletion TREK already acted on', () => {expect(p.actions).toEqual([]);});+ /**+ * A copy on record as gone whose TREK copy was then purged.+ *+ * The row waited for a person to decide about the TREK copy, and nothing+ * closed it once they had: the pair loop never sees a row with no listing+ * entry, the unchanged branch skips the state by name, and the purge left+ * `file_id` NULL with the row still counting under "Needs a look" for good.+ * With nothing left on either side, the row closes, and without asking the+ * provider to bin a copy that is not there.+ */+ it('closes a row whose copies are gone on both sides, without binning anything', () => {+ const gone = item({ state: 'remote_missing', remoteMissingAt: '2026-09-17 08:00:00', fileId: null });+ const p = plan({ items: [gone], remote: [], local: [] });+ expect(p.actions).toEqual([{ kind: 'local_deleted', itemId: 10, remoteId: 'r1', remoteGone: true }]);+ expect(p.missingCount).toBe(0);+ });++ it('does the same under an unchanged upstream', () => {+ const gone = item({ state: 'remote_missing', remoteMissingAt: '2026-09-17 08:00:00', fileId: null });+ const p = plan({ items: [gone], remote: [], local: [], remoteUnchanged: true });+ expect(p.actions).toEqual([{ kind: 'local_deleted', itemId: 10, remoteId: 'r1', remoteGone: true }]);+ });++ it('treats a purged file as an ordinary deletion once the copy is listed again', () => {+ const gone = item({ state: 'remote_missing', remoteMissingAt: '2026-09-17 08:00:00', fileId: null });+ const p = plan({ items: [gone], remote: [remote()], local: [] });+ expect(p.actions).toEqual([{ kind: 'local_deleted', itemId: 10, remoteId: 'r1' }]);+ });+it('notices when the copy TREK binned is listed again', () => {const p = plan({items: [settled({ remoteTrashedAt: '2026-09-18 08:05:00' })],diff --git a/server/tests/unit/nest/doc-sync/doc-sync.service.test.ts b/server/tests/unit/nest/doc-sync/doc-sync.service.test.tsindex 324f4e3dc..563295302 100644--- a/server/tests/unit/nest/doc-sync/doc-sync.service.test.ts+++ b/server/tests/unit/nest/doc-sync/doc-sync.service.test.ts@@ -163,13 +163,17 @@ const files = {tripId: string | number,file: { filename: string; originalname: string; size: number; mimetype: string },uploadedBy: number,+ opts: { place_id?: string | number | null; reservation_id?: string | number | null; description?: string | null } = {},) => {const info = testDb.prepare(- `INSERT INTO trip_files (trip_id, filename, original_name, file_size, mime_type, uploaded_by)- VALUES (?, ?, ?, ?, ?, ?)`,+ `INSERT INTO trip_files (trip_id, place_id, reservation_id, filename, original_name, file_size, mime_type, description, uploaded_by)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,)- .run(tripId, file.filename, file.originalname, file.size, file.mimetype, uploadedBy || null);+ .run(+ tripId, opts.place_id || null, opts.reservation_id || null,+ file.filename, file.originalname, file.size, file.mimetype, opts.description || null, uploadedBy || null,+ );return testDb.prepare('SELECT * FROM trip_files WHERE id = ?').get(info.lastInsertRowid);}),// Writes for real, like the two above: a double that answers but changes@@ -1388,6 +1392,120 @@ describe('DocSyncService', () => {expect(fileRows().filter(r => r.deleted_at === null)).toHaveLength(1);});++ /**+ * The booking a document hangs on has to survive a new revision.+ *+ * The fresh row was created bare, and the old one went to the trash with+ * the reservation, the description, the star and the extra links still on+ * it: an edit in the store took the attachment off its booking, and the+ * reservation showed no document until somebody dug the old copy out.+ */+ it('carries the attachments of the superseded copy over to the new revision', async () => {+ const link = makeLink();+ const { itemId, fileId } = seedSynced(link);+ const reservationId = Number(+ testDb.prepare("INSERT INTO reservations (trip_id, title) VALUES (?, 'Hotel Kyoto')").run(tripId).lastInsertRowid,+ );+ const otherReservationId = Number(+ testDb.prepare("INSERT INTO reservations (trip_id, title) VALUES (?, 'Ryokan Hakone')").run(tripId).lastInsertRowid,+ );+ testDb.prepare('UPDATE trip_files SET reservation_id = ?, description = ?, starred = 1 WHERE id = ?')+ .run(reservationId, 'Booking confirmation', fileId);+ testDb.prepare('INSERT INTO file_links (file_id, reservation_id) VALUES (?, ?)').run(fileId, otherReservationId);+ provider.list.mockResolvedValueOnce(ok(listing([+ remoteDoc({ remoteId: 'r1', name: 'invoice.pdf', remoteVersion: 'v2' }),+ ])));++ await service.syncLink(link);++ const fresh = fileRows().find(r => Number(r.id) !== fileId) as Record<string, unknown>;+ expect(fresh).toMatchObject({ reservation_id: reservationId, description: 'Booking confirmation', starred: 1, deleted_at: null });+ expect(itemRow(itemId).file_id).toBe(Number(fresh.id));+ const links = testDb.prepare('SELECT reservation_id FROM file_links WHERE file_id = ? ORDER BY id').all(fresh.id) as Array<{ reservation_id: number }>;+ expect(links.map(l => l.reservation_id)).toEqual([otherReservationId]);+ // The old copy keeps what it had: the trash shows it as it was.+ expect(fileRows().find(r => Number(r.id) === fileId)).toMatchObject({ reservation_id: reservationId, starred: 1 });+ expect(realtime.broadcast).toHaveBeenCalledWith(tripId, 'file:created', { file: expect.objectContaining({ id: fresh.id, starred: 1 }) });+ });++ /**+ * A version marker that moved over the same bytes.+ *+ * Paperless bumps `modified` for a tag or a correspondent, and its listing+ * only carries a hash the planner can read where the checksum is sha256.+ * Without one the bytes were fetched again and a fresh row replaced the+ * file, booking link and all, on every edit of metadata. The download+ * cannot be avoided without a hash, but what it brings back can be+ * compared before anything is written.+ */+ it('keeps the file when the download turns out to be the bytes TREK already holds', async () => {+ const link = makeLink();+ const fileId = makeFile({ name: 'invoice.pdf' });+ const itemId = seedItem(link, {+ remoteId: 'r1', remoteName: 'invoice.pdf', remoteVersion: 'v1', fileId, state: 'synced', contentSha256: FILE_SHA,+ });+ provider.list.mockResolvedValueOnce(ok(listing([+ remoteDoc({ remoteId: 'r1', name: 'invoice.pdf', remoteVersion: 'v2', contentHash: null }),+ ])));++ const res = await service.syncLink(link);++ expect(fileRows()).toHaveLength(1);+ expect(fileRows()[0]).toMatchObject({ id: fileId, deleted_at: null });+ expect(itemRow(itemId)).toMatchObject({ file_id: fileId, remote_version: 'v2', state: 'synced', content_sha256: FILE_SHA });+ expect(storage.put).not.toHaveBeenCalled();+ expect(fs.readdirSync(spoolDir)).toHaveLength(0);+ expect(res.pulled).toBe(0);+ expect(realtime.broadcast).not.toHaveBeenCalledWith(tripId, 'file:created', expect.anything());+ });++ it('leaves a rename that came with such an edit for the planner to follow', async () => {+ // Moving the agreed name here would read the store's rename as TREK's+ // own on the next run and send the old name back up.+ const link = makeLink();+ const fileId = makeFile({ name: 'invoice.pdf' });+ const itemId = seedItem(link, {+ remoteId: 'r1', remoteName: 'invoice.pdf', remoteVersion: 'v1', fileId, state: 'synced', contentSha256: FILE_SHA,+ });+ provider.list.mockResolvedValueOnce(ok(listing([+ remoteDoc({ remoteId: 'r1', name: 'hotel-invoice.pdf', remoteVersion: 'v2', contentHash: null }),+ ])));++ await service.syncLink(link);++ expect(itemRow(itemId)).toMatchObject({ remote_name: 'invoice.pdf', remote_version: 'v2' });+ expect(fileRows()[0].original_name).toBe('invoice.pdf');++ provider.list.mockResolvedValueOnce(ok(listing([+ remoteDoc({ remoteId: 'r1', name: 'hotel-invoice.pdf', remoteVersion: 'v2', contentHash: null }),+ ])));+ await service.syncLink(link);++ expect(provider.rename).not.toHaveBeenCalled();+ expect(fileRows()[0].original_name).toBe('hotel-invoice.pdf');+ expect(itemRow(itemId).remote_name).toBe('hotel-invoice.pdf');+ });+ });++ /**+ * Video comes in the way the file manager takes it: regardless of the+ * operator's allowed types, which do not list a video extension by default.+ * A clip in a bound Nextcloud folder was refused as *Type not allowed* while+ * the same clip uploaded by hand went through.+ */+ describe('video from the store', () => {+ it('is pulled, not refused for its type', async () => {+ const link = makeLink();+ provider.list.mockResolvedValueOnce(ok(listing([remoteDoc({ remoteId: 'r-clip', name: 'flug.mp4', mimeType: 'video/mp4' })])));++ const res = await service.syncLink(link);++ expect(provider.fetch).toHaveBeenCalledTimes(1);+ expect(fileRows().map(r => r.original_name)).toEqual(['flug.mp4']);+ expect(itemRows()[0].state).toBe('synced');+ expect(res.state).toBe('ok');+ });});/**@@ -1674,6 +1792,10 @@ describe('DocSyncService', () => {const { itemId, fileId } = await deletedAndSeen(link);restore(fileId);+ // An edit is new bytes, not only a new version marker: the same bytes under+ // a moved marker are kept as they are.+ const edited = Buffer.from('trek-document-bytes, revised upstream');+ provider.fetch.mockResolvedValueOnce(ok({ body: Readable.from([edited]), size: edited.length, mimeType: 'application/pdf', remoteVersion: 'v2' }));provider.list.mockResolvedValueOnce(ok(listing([remoteDoc({ remoteId: 'r1', remoteVersion: 'v2' })])));const run = await service.syncLink(config.getLink(link.id));@@ -1922,6 +2044,37 @@ describe('DocSyncService', () => {expect(provider.trash).toHaveBeenCalledTimes(1);expect(itemRow(itemId).state).toBe('local_deleted');});++ /**+ * A copy on record as gone from the store, whose TREK copy is then purged.+ *+ * The row had no way out: nothing planned anything for a `remote_missing`+ * row without a listing entry, so it kept counting under "Needs a look"+ * with a sentence about a TREK copy that no longer existed. With both+ * copies gone the row closes, and the store is not asked to bin a copy+ * that is not there, whatever the delete policy says.+ */+ it('closes a row on record as gone from the store once the TREK copy is purged too', async () => {+ const link = makeLink({ deletePolicy: 'trash' });+ const fileId = makeFile({ name: 'boarding.pdf', deletedAt: '2026-09-18 08:00:00' });+ const itemId = seedItem(link, {+ remoteId: 'r1', remoteName: 'boarding.pdf', remoteVersion: 'v1', fileId, state: 'remote_missing',+ remoteMissingAt: '2026-09-17 08:00:00',+ });+ purge(fileId);+ provider.list.mockResolvedValue(ok(listing([])));++ const res = await service.syncLink(link);++ expect(provider.trash).not.toHaveBeenCalled();+ expect(itemRow(itemId)).toMatchObject({ state: 'local_deleted', remote_trashed_at: null, file_id: null });+ expect(itemRow(itemId).remote_missing_at).not.toBeNull();+ expect(service.issues(tripId).map((r) => r.id)).not.toContain(itemId);+ // Closed is not "back at the store": the holdings must not count it there.+ const [status] = (service.status(tripId) as { links: Array<{ holdings: { atProvider: number; missing: number } }> }).links;+ expect(status.holdings).toMatchObject({ atProvider: 0, missing: 0 });+ expect(res.state).toBe('ok');+ });});/**diff --git a/server/tests/unit/nest/doc-sync/paperless.provider.test.ts b/server/tests/unit/nest/doc-sync/paperless.provider.test.tsindex 15a26d08d..655764165 100644--- a/server/tests/unit/nest/doc-sync/paperless.provider.test.ts+++ b/server/tests/unit/nest/doc-sync/paperless.provider.test.ts@@ -65,6 +65,7 @@ import {} from '../../../../src/nest/doc-sync/providers/paperless.client';import {PaperlessDocumentProvider,+ PAPERLESS_TITLE_MAX_LENGTH,PAPERLESS_WEBHOOK_SECRET_HEADER,TRIP_UID_FIELD_NAME,documentFileName,@@ -859,6 +860,29 @@ describe('PaperlessProvider: renaming and trashing', () => {expect(expectFail(await provider.rename(CONN, SCOPE, '11', 'neu.pdf')).code).toBe('not_found');});+ it('PAPERLESS-072: a name longer than the title column is cut to fit instead of refused on every run', async () => {+ // Paperless keeps 128 characters of a title. Sending more is a 400 that+ // repeats on each poll, with nothing in the message that names the file.+ const long = `${'Reservierungsbestätigung Hotel Alpenblick Zermatt '.repeat(4)}Familie Mustermann final`;+ expect(long.length).toBeGreaterThan(PAPERLESS_TITLE_MAX_LENGTH);+ expect(titleFromFileName(`${long}.pdf`)).toBe(long.slice(0, PAPERLESS_TITLE_MAX_LENGTH).trim());+ expect(titleFromFileName(`${long}.pdf`).length).toBeLessThanOrEqual(PAPERLESS_TITLE_MAX_LENGTH);+ // Exactly the limit is still sent whole.+ const exact = 'x'.repeat(PAPERLESS_TITLE_MAX_LENGTH);+ expect(titleFromFileName(`${exact}.pdf`)).toBe(exact);+ // The limit counts characters as Paperless does, so a cut never lands inside+ // one: U+1D538 is two UTF-16 units, and a cut by units would end on half of it.+ const wide = '\u{1D538}';+ const glyphs = [...titleFromFileName(`${wide.repeat(PAPERLESS_TITLE_MAX_LENGTH + 2)}.pdf`)];+ expect(glyphs).toHaveLength(PAPERLESS_TITLE_MAX_LENGTH);+ expect(glyphs.every((glyph) => glyph === wide)).toBe(true);++ on('PATCH /api/documents/11/', reply(docRow({ modified: '2026-09-18T19:00:00.000000+02:00' })));+ expectOk(await provider.rename(CONN, SCOPE, '11', `${long}.pdf`));+ const sent = JSON.parse(lastRequest('PATCH /api/documents/11/').body) as { title: string };+ expect(sent.title.length).toBeLessThanOrEqual(PAPERLESS_TITLE_MAX_LENGTH);+ });+it('PAPERLESS-080: trashing is a soft delete, and doing it twice is still success', async () => {on('DELETE /api/documents/11/', reply('', 204), reply({ detail: 'No Document matches the given query.' }, 404));expectOk(await provider.trash(CONN, SCOPE, '11'));diff --git a/server/tests/unit/nest/doc-sync/provider-http.test.ts b/server/tests/unit/nest/doc-sync/provider-http.test.tsindex 062f89bfb..33d21f7b3 100644--- a/server/tests/unit/nest/doc-sync/provider-http.test.ts+++ b/server/tests/unit/nest/doc-sync/provider-http.test.ts@@ -30,6 +30,7 @@ import {classifyTransportFailure,declaredLength,guardDownload,+ isUnresolvedHost,providerFetch,statusErrorCode,type TransportFailure,@@ -173,6 +174,18 @@ describe('classifyTransportFailure', () => {);expect(classifyTransportFailure(error).code).toBe('unreachable');});++ it('PROVIDER-HTTP-008: a name DNS cannot resolve is unreachable, not a policy verdict', () => {+ // The guard refuses it the same way it refuses loopback, but a typo in the+ // host name is not something the SSRF settings can fix.+ const error = new SsrfBlockedErrorMock('Could not resolve hostname (ENOTFOUND)');+ expect(classifyTransportFailure(error)).toEqual({+ code: 'unreachable',+ detail: 'Could not resolve hostname (ENOTFOUND)',+ });+ expect(isUnresolvedHost('Could not resolve hostname (EAI_AGAIN)')).toBe(true);+ expect(isUnresolvedHost('Requests to loopback are not allowed')).toBe(false);+ });});describe('providerFetch', () => {diff --git a/server/tests/unit/nest/doc-sync/synology-drive.provider.test.ts b/server/tests/unit/nest/doc-sync/synology-drive.provider.test.tsindex 05c423dd2..ea4fed0d6 100644--- a/server/tests/unit/nest/doc-sync/synology-drive.provider.test.ts+++ b/server/tests/unit/nest/doc-sync/synology-drive.provider.test.ts@@ -232,11 +232,11 @@ function push(overrides: Partial<PushRequest> = {}): PushRequest {};}-/** The four answers a successful push needs after the upload itself. */+/** The answers a successful push needs: nothing at the path before the upload, the stored file after it. */function pushRoutes(path: string, size = BYTES.length, md5 = BYTES_MD5): Record<string, Handler | Reply> {return {'SYNO.FileStation.Upload:upload': ok({ file: path.slice(path.lastIndexOf('/') + 1) }),- 'SYNO.FileStation.List:getinfo': ok({ files: [entry(path, { size })] }),+ 'SYNO.FileStation.List:getinfo': sequence(fail(408), ok({ files: [entry(path, { size })] })),'SYNO.FileStation.MD5:start': ok({ taskid: 'T-md5' }),'SYNO.FileStation.MD5:status': ok({ finished: true, md5 }),};@@ -1063,13 +1063,37 @@ describe('SynologyDriveDocumentProvider: push', () => {});it('SYNO-PROVIDER-061: a name collision without a remoteId is a conflict, never an overwrite', async () => {- route({ 'SYNO.FileStation.Upload:upload': fail(1805) });+ // A namesake that appears between the check and the upload is not+ // overwritten: the upload never goes out with overwrite on for a new file,+ // and a refusal from the NAS at that point is a conflict.+ route({+ 'SYNO.FileStation.List:getinfo': fail(408),+ 'SYNO.FileStation.Upload:upload': fail(1805),+ });const result = await provider.push(connection(), scope(), push());expect(result).toMatchObject({ success: false, error: { code: 'conflict', detail: 'syno_code=1805' } });+ expect(callsTo('SYNO.FileStation.Upload')[0].params.overwrite).toBe('false');+ });++ it('SYNO-PROVIDER-061a: a name already taken is a conflict before a single byte is uploaded', async () => {+ // A success from the upload says nothing about a file that was already+ // there, and the size and digest checks would read it as a broken transfer+ // and upload the whole file again on every retry. So the path is asked first.+ route({ 'SYNO.FileStation.List:getinfo': ok({ files: [entry(`${SCOPE}/itinerary.pdf`, { size: 200 })] }) });+ const result = await provider.push(connection(), scope(), push());++ expect(result).toMatchObject({ success: false, error: { code: 'conflict' } });+ expect(result.success === false && result.error.detail).toContain(`${SCOPE}/itinerary.pdf`);+ expect(callsTo('SYNO.FileStation.Upload')).toHaveLength(0);+ expect(callsTo('SYNO.FileStation.MD5')).toHaveLength(0);});it('SYNO-PROVIDER-062: a remoteId means replace in place, and the request name is ignored', async () => {- route(pushRoutes(`${SCOPE}/leg-2/hotel.pdf`));+ // The path is expected to be taken: it is the file being replaced.+ route({+ ...pushRoutes(`${SCOPE}/leg-2/hotel.pdf`),+ 'SYNO.FileStation.List:getinfo': ok({ files: [entry(`${SCOPE}/leg-2/hotel.pdf`, { size: BYTES.length })] }),+ });const result = await provider.push(connection(),scope(),@@ -1131,7 +1155,10 @@ describe('SynologyDriveDocumentProvider: push', () => {// version has to come from that, or the next listing looks like a change.route({'SYNO.FileStation.Upload:upload': ok({}),- 'SYNO.FileStation.List:getinfo': ok({ files: [entry(`${SCOPE}/itinerary.pdf`, { size: BYTES.length, mtime: 1_700_000_042 })] }),+ 'SYNO.FileStation.List:getinfo': sequence(+ fail(408),+ ok({ files: [entry(`${SCOPE}/itinerary.pdf`, { size: BYTES.length, mtime: 1_700_000_042 })] }),+ ),'SYNO.FileStation.MD5:start': ok({ taskid: 'T' }),'SYNO.FileStation.MD5:status': ok({ finished: true, md5: BYTES_MD5 }),});@@ -1179,6 +1206,7 @@ describe('SynologyDriveDocumentProvider: rename and trash', () => {'SYNO.FileStation.CreateFolder:create': ok({ folders: [entry(`${SCOPE}/.trek-trash`, { dir: true })] }),'SYNO.FileStation.CopyMove:start': ok({ taskid: 'T-move' }),'SYNO.FileStation.CopyMove:status': sequence(ok({ finished: false }), ok({ finished: true })),+ 'SYNO.FileStation.List:getinfo': fail(408),});const result = await provider.trash(connection(), scope(), `${SCOPE}/a.pdf`);@@ -1193,6 +1221,11 @@ describe('SynologyDriveDocumentProvider: rename and trash', () => {// A CopyMove is asynchronous: returning on the start call would let the// caller list the folder and find the file in both places, or in neither.expect(callsTo('SYNO.FileStation.CopyMove', 'status')).toHaveLength(2);+ // And a finished task is not the same as a moved file: the source is asked.+ const asked = callsTo('SYNO.FileStation.List', 'getinfo');+ expect(asked).toHaveLength(1);+ expect(JSON.parse(asked[0].params.path)).toEqual([`${SCOPE}/a.pdf`]);+ expect(calls.indexOf(asked[0])).toBeGreaterThan(calls.indexOf(callsTo('SYNO.FileStation.CopyMove', 'status')[1]));});it('SYNO-PROVIDER-073: a twin already in the bin steps aside instead of being overwritten', async () => {@@ -1201,6 +1234,7 @@ describe('SynologyDriveDocumentProvider: rename and trash', () => {'SYNO.FileStation.CopyMove:start': sequence(fail(1805), ok({ taskid: 'T-move' })),'SYNO.FileStation.CopyMove:status': ok({ finished: true }),'SYNO.FileStation.Rename:rename': ok({ files: [entry(`${SCOPE}/.trek-trash/a.123.pdf`)] }),+ 'SYNO.FileStation.List:getinfo': fail(408),});const result = await provider.trash(connection(), scope(), `${SCOPE}/a.pdf`);@@ -1217,6 +1251,42 @@ describe('SynologyDriveDocumentProvider: rename and trash', () => {expect(result).toMatchObject({ success: false, error: { code: 'not_found' } });expect(calls).toHaveLength(0);});++ it('SYNO-PROVIDER-075: a task that finished while the file stayed put is a twin in the bin, not a done deal', async () => {+ // Nothing in a finished task says whether the file moved. The source path+ // does: still there means not moved, so the twin steps aside and the move+ // runs again, and only a source that is gone counts as binned.+ route({+ 'SYNO.FileStation.CreateFolder:create': ok({ folders: [entry(`${SCOPE}/.trek-trash`, { dir: true })] }),+ 'SYNO.FileStation.CopyMove:start': ok({ taskid: 'T-move' }),+ 'SYNO.FileStation.CopyMove:status': ok({ finished: true }),+ 'SYNO.FileStation.List:getinfo': sequence(ok({ files: [entry(`${SCOPE}/a.pdf`)] }), fail(408)),+ 'SYNO.FileStation.Rename:rename': ok({ files: [entry(`${SCOPE}/.trek-trash/a.123.pdf`)] }),+ });+ const result = await provider.trash(connection(), scope(), `${SCOPE}/a.pdf`);++ expect(result).toMatchObject({ success: true });+ const renamed = callsTo('SYNO.FileStation.Rename', 'rename');+ expect(renamed).toHaveLength(1);+ expect(JSON.parse(renamed[0].params.path)).toEqual([`${SCOPE}/.trek-trash/a.pdf`]);+ expect(callsTo('SYNO.FileStation.CopyMove', 'start')).toHaveLength(2);+ expect(callsTo('SYNO.FileStation.List', 'getinfo')).toHaveLength(2);+ });++ it('SYNO-PROVIDER-076: a file that will not leave even after the bin made room is a conflict, not a success', async () => {+ route({+ 'SYNO.FileStation.CreateFolder:create': ok({ folders: [entry(`${SCOPE}/.trek-trash`, { dir: true })] }),+ 'SYNO.FileStation.CopyMove:start': ok({ taskid: 'T-move' }),+ 'SYNO.FileStation.CopyMove:status': ok({ finished: true }),+ 'SYNO.FileStation.List:getinfo': ok({ files: [entry(`${SCOPE}/a.pdf`)] }),+ 'SYNO.FileStation.Rename:rename': ok({ files: [entry(`${SCOPE}/.trek-trash/a.123.pdf`)] }),+ });+ const result = await provider.trash(connection(), scope(), `${SCOPE}/a.pdf`);++ expect(result).toMatchObject({ success: false, error: { code: 'conflict' } });+ expect(callsTo('SYNO.FileStation.CopyMove', 'start')).toHaveLength(2);+ expect(callsTo('SYNO.FileStation.Rename', 'rename')).toHaveLength(1);+ });});// ── error classification ─────────────────────────────────────────────────────@@ -1325,14 +1395,20 @@ describe('SynologyDriveDocumentProvider: how a NAS disappoints', () => {it('SYNO-PROVIDER-090: an upload the NAS answers with a bare HTTP error keeps the status', async () => {// 507 reads as a full volume, the same verdict DSM's own 415/416/1101 give.- route({ 'SYNO.FileStation.Upload:upload': reply({}, { status: 507 }) });+ route({+ 'SYNO.FileStation.List:getinfo': fail(408),+ 'SYNO.FileStation.Upload:upload': reply({}, { status: 507 }),+ });expect(await provider.push(connection(), scope(), push())).toMatchObject({success: false,error: { code: 'quota_exceeded', status: 507 },});provider = new SynologyDriveDocumentProvider(new SynologyDriveClient());- route({ 'SYNO.FileStation.Upload:upload': reply({}, { status: 500 }) });+ route({+ 'SYNO.FileStation.List:getinfo': fail(408),+ 'SYNO.FileStation.Upload:upload': reply({}, { status: 500 }),+ });expect(await provider.push(connection(), scope(), push())).toMatchObject({success: false,error: { code: 'provider_error', status: 500 },@@ -1340,7 +1416,10 @@ describe('SynologyDriveDocumentProvider: how a NAS disappoints', () => {});it('SYNO-PROVIDER-091: an upload answered with HTML is a provider_error, not a parse crash', async () => {- route({ 'SYNO.FileStation.Upload:upload': reply(null, { raw: '<html>413</html>', contentType: 'text/html' }) });+ route({+ 'SYNO.FileStation.List:getinfo': fail(408),+ 'SYNO.FileStation.Upload:upload': reply(null, { raw: '<html>413</html>', contentType: 'text/html' }),+ });const result = await provider.push(connection(), scope(), push());expect(result).toMatchObject({ success: false, error: { code: 'provider_error' } });});@@ -1369,7 +1448,7 @@ describe('SynologyDriveDocumentProvider: how a NAS disappoints', () => {provider = new SynologyDriveDocumentProvider(new SynologyDriveClient());route({'SYNO.FileStation.Upload:upload': ok({}),- 'SYNO.FileStation.List:getinfo': ok({ files: [entry(`${SCOPE}/itinerary.pdf`)] }),+ 'SYNO.FileStation.List:getinfo': sequence(fail(408), ok({ files: [entry(`${SCOPE}/itinerary.pdf`)] })),'SYNO.FileStation.MD5:start': ok({}),});expect(await provider.push(connection(), scope(), push({ size: 100 }))).toMatchObject({@@ -1382,6 +1461,7 @@ describe('SynologyDriveDocumentProvider: how a NAS disappoints', () => {route({'SYNO.FileStation.CreateFolder:create': ok({ folders: [entry(`${SCOPE}/.trek-trash`, { dir: true })] }),'SYNO.FileStation.CopyMove:start': ok({}),+ 'SYNO.FileStation.List:getinfo': fail(408),});const result = await provider.trash(connection(), scope(), `${SCOPE}/a.pdf`);expect(result).toMatchObject({ success: true });diff --git a/server/tests/unit/nest/doc-sync/webdav.provider.test.ts b/server/tests/unit/nest/doc-sync/webdav.provider.test.tsindex 312ead271..e1c26160e 100644--- a/server/tests/unit/nest/doc-sync/webdav.provider.test.ts+++ b/server/tests/unit/nest/doc-sync/webdav.provider.test.ts@@ -865,6 +865,119 @@ describe('webhooks', () => {});});+describe('an install below a path', () => {+ const NC_PREFIXED = 'https://home.example.org/nextcloud';+ const OC_PREFIXED = 'https://opencloud.example.org/oc';+ const prefixedNc: DocumentConnectionRef = { ...ncConn, baseUrl: NC_PREFIXED };+ const prefixedOc: DocumentConnectionRef = { ...ocConn, baseUrl: OC_PREFIXED };++ it('reaches a Nextcloud under a sub-path instead of calling its address a wrong password', async () => {+ route(+ `PROPFIND /nextcloud${NC_ROOT}`,+ multistatus([{ href: `/nextcloud${NC_ROOT}/`, collection: true, fileid: '1' }]),+ );+ route('GET /nextcloud/ocs/v2.php/apps/webhook_listeners/api/v1/webhooks', reply('{"ocs":{"data":[]}}'));++ const result = await nextcloud.probe(prefixedNc);++ expect(result).toMatchObject({ success: true, data: { account: 'admin' } });+ expect(calls[0].url).toBe(`${NC_PREFIXED}${NC_ROOT}`);+ });++ it('strips the file-app address people paste and keeps the install path underneath it', async () => {+ route(+ `PROPFIND /nextcloud${NC_ROOT}`,+ multistatus([{ href: `/nextcloud${NC_ROOT}/`, collection: true, fileid: '1' }]),+ );+ route('GET /nextcloud/ocs/v2.php/apps/webhook_listeners/api/v1/webhooks', reply('{}', { status: 403 }));++ const result = await nextcloud.probe({ ...ncConn, baseUrl: `${NC_PREFIXED}/apps/files/files/123?dir=/TREK` });++ expect(result).toMatchObject({ success: true });+ expect(calls[0].url).toBe(`${NC_PREFIXED}${NC_ROOT}`);+ });++ it('keeps an install path that happens to contain apps, cutting only the pasted page behind it', async () => {+ const APPS_ROOT = 'https://home.example.org/apps/nextcloud';+ route(+ `PROPFIND /apps/nextcloud${NC_ROOT}`,+ multistatus([{ href: `/apps/nextcloud${NC_ROOT}/`, collection: true, fileid: '1' }]),+ );+ route('GET /apps/nextcloud/ocs/v2.php/apps/webhook_listeners/api/v1/webhooks', reply('{}', { status: 403 }));++ expect(await nextcloud.probe({ ...ncConn, baseUrl: `${APPS_ROOT}/apps/dashboard/` })).toMatchObject({ success: true });+ expect(calls[0].url).toBe(`${APPS_ROOT}${NC_ROOT}`);++ calls = [];+ expect(await nextcloud.probe({ ...ncConn, baseUrl: APPS_ROOT })).toMatchObject({ success: true });+ expect(calls[0].url).toBe(`${APPS_ROOT}${NC_ROOT}`);+ });++ it('takes the prefix off the hrefs it is answered, so a download is not addressed twice over', async () => {+ route(+ `PROPFIND /nextcloud${NC_ROOT}/TREK/trip%2042`,+ multistatus([+ { href: `/nextcloud${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60', etag: '"root-1"' },+ { href: `/nextcloud${NC_ROOT}/TREK/trip%2042/pass.pdf`, fileid: '61', etag: '"doc-1"', size: 4, type: 'application/pdf' },+ ]),+ );+ route(`GET /nextcloud${NC_ROOT}/TREK/trip%2042/pass.pdf`, reply('pdf!', { headers: { etag: '"doc-1"' } }));++ const listed = await nextcloud.list(prefixedNc, ncScope);+ expect(listed.success && listed.data.documents.map((doc) => doc.name)).toEqual(['pass.pdf']);+ expect(listed.success && listed.data.cursor).toBe('"root-1"');++ const fetched = await nextcloud.fetch(prefixedNc, ncScope, '61');+ expect(fetched).toMatchObject({ success: true, data: { remoteVersion: '"doc-1"' } });+ expect(requests('GET').map((call) => call.url)).toEqual([`${NC_PREFIXED}${NC_ROOT}/TREK/trip%2042/pass.pdf`]);+ });++ it('renames within the prefixed folder and points the Destination at the full base', async () => {+ route(+ `PROPFIND /nextcloud${NC_ROOT}/TREK/trip%2042`,+ multistatus([+ { href: `/nextcloud${NC_ROOT}/TREK/trip%2042/`, collection: true, fileid: '60' },+ { href: `/nextcloud${NC_ROOT}/TREK/trip%2042/pass.pdf`, fileid: '61', size: 4, type: 'application/pdf' },+ ]),+ );+ route(`MOVE /nextcloud${NC_ROOT}/TREK/trip%2042/pass.pdf`, reply(null, { status: 201, headers: { 'oc-etag': '"moved"' } }));++ const result = await nextcloud.rename(prefixedNc, ncScope, '61', 'passport.pdf');++ expect(result).toEqual({ success: true, data: { remoteVersion: '"moved"' } });+ expect(requests('MOVE')[0].headers.destination).toBe(`${NC_PREFIXED}${NC_ROOT}/TREK/trip%2042/passport.pdf`);+ });++ it('re-bases an OpenCloud space below a path without spelling the path twice', async () => {+ route(+ 'GET /oc/graph/v1.0/me/drives',+ reply(JSON.stringify({ value: [drive(OC_DRIVE, 'TREK Trip 42', 'project', `https://internal.lan:9200/oc${OC_ROOT}`)] })),+ );+ route(+ `PROPFIND /oc${OC_ROOT}`,+ multistatus([+ { href: `/oc${OC_ROOT}/`, collection: true, fileid: `${OC_DRIVE}!root`, etag: '"root"' },+ { href: `/oc${OC_ROOT}/pass.pdf`, fileid: `${OC_DRIVE}!doc`, etag: '"doc"', size: 10, type: 'application/pdf' },+ ]),+ );++ const scopes = await opencloud.listScopes(prefixedOc);+ expect(scopes.success && scopes.data[0].remoteRootPath).toBe(`${OC_PREFIXED}${OC_ROOT}`);++ const listed = await opencloud.list(prefixedOc, { ...ocScope, remoteRootPath: `${OC_PREFIXED}${OC_ROOT}` });+ expect(listed.success && listed.data.documents[0]).toMatchObject({ remoteId: `${OC_DRIVE}!doc`, name: 'pass.pdf' });+ expect(requests('PROPFIND').map((call) => call.url)).toEqual([`${OC_PREFIXED}${OC_ROOT}`]);+ });++ it('leaves a root install exactly as it was', async () => {+ route(`PROPFIND ${NC_ROOT}`, multistatus([{ href: `${NC_ROOT}/`, collection: true, fileid: '1' }]));+ route('GET /ocs/v2.php/apps/webhook_listeners/api/v1/webhooks', reply('{}', { status: 403 }));++ expect(await nextcloud.probe({ ...ncConn, baseUrl: `${NC_ORIGIN}/index.php/apps/files/` })).toMatchObject({ success: true });+ expect(calls[0].url).toBe(`${NC_ORIGIN}${NC_ROOT}`);+ });+});+describe('failure classification', () => {it('separates a timeout, an untrusted certificate and a blocked host', async () => {const timeout = Object.assign(new TypeError('fetch failed'), {diff --git a/server/tests/unit/nest/google-transit.provider.test.ts b/server/tests/unit/nest/google-transit.provider.test.tsindex 1a723946a..d5048ddc6 100644--- a/server/tests/unit/nest/google-transit.provider.test.ts+++ b/server/tests/unit/nest/google-transit.provider.test.ts@@ -363,6 +363,64 @@ describe('request shape', () => {});});+/**+ * MOTIS names a train by its service, Google by its vehicle. The client's train+ * chip therefore asks for the fine-grained rail modes and never for RAIL, while+ * Google labels every conventional train HEAVY_RAIL, which lands on RAIL. The+ * response filter has to read both as the same family, or the one billed call+ * comes back with the trains the user asked for and throws them all away.+ */+describe('rail mode filter', () => {+ /** The subway fixture with its one transit leg relabelled as another vehicle. */+ function withVehicle(type: string): FixtureRoutes {+ const route = subwayRoute();+ const details = route.routes[0].legs[0].steps[1].transitDetails;+ if (details) details.transitLine.vehicle.type = type;+ return route;+ }++ // What the train chip sends, verbatim.+ const TRAIN_CHIP = 'HIGHSPEED_RAIL,LONG_DISTANCE,NIGHT_RAIL,REGIONAL_RAIL,SUBURBAN';++ it('GTRANSIT-039: the train filter keeps the trains Google labels HEAVY_RAIL', async () => {+ const provider = new GoogleTransitProvider(googleDb());+ for (const vehicle of ['HEAVY_RAIL', 'RAIL', 'COMMUTER_TRAIN', 'HIGH_SPEED_TRAIN']) {+ clearGoogleTransitCache();+ fetchMock.mockResolvedValue(okJson(withVehicle(vehicle)));+ const { itineraries } = await provider.plan({ from: FROM, to: TO, modes: TRAIN_CHIP }, 'en', 1);+ expect(itineraries, vehicle).toHaveLength(1);+ }+ // The request side is unchanged: the five fine modes collapse to Google's one TRAIN bucket.+ expect(lastBody().transitPreferences).toEqual({ allowedTravelModes: ['TRAIN'] });+ });++ it('GTRANSIT-040: the RAIL umbrella keeps the fine-grained rail legs, and neither side leaks a subway', async () => {+ const provider = new GoogleTransitProvider(googleDb());+ // An MCP caller may name the umbrella; Google still answers by vehicle.+ for (const vehicle of ['COMMUTER_TRAIN', 'HIGH_SPEED_TRAIN', 'HEAVY_RAIL']) {+ clearGoogleTransitCache();+ fetchMock.mockResolvedValue(okJson(withVehicle(vehicle)));+ const { itineraries } = await provider.plan({ from: FROM, to: TO, modes: 'RAIL' }, 'en', 1);+ expect(itineraries, vehicle).toHaveLength(1);+ }++ clearGoogleTransitCache();+ fetchMock.mockResolvedValue(okJson(withVehicle('HEAVY_RAIL')));+ expect((await provider.plan({ from: FROM, to: TO, modes: 'SUBWAY' }, 'en', 1)).itineraries).toEqual([]);++ clearGoogleTransitCache();+ fetchMock.mockResolvedValue(okJson(withVehicle('SUBWAY')));+ expect((await provider.plan({ from: FROM, to: TO, modes: TRAIN_CHIP }, 'en', 1)).itineraries).toEqual([]);+ });++ it('GTRANSIT-041: a bus-only filter still refuses a train', async () => {+ fetchMock.mockResolvedValue(okJson(withVehicle('HEAVY_RAIL')));+ const provider = new GoogleTransitProvider(googleDb());+ const { itineraries } = await provider.plan({ from: FROM, to: TO, modes: 'BUS,COACH' }, 'en', 1);+ expect(itineraries).toEqual([]);+ });+});+describe('geocode', () => {const places = {places: [diff --git a/server/tests/unit/nest/maps.gers-details.test.ts b/server/tests/unit/nest/maps.gers-details.test.tsindex dfa2e1277..628b9bd5b 100644--- a/server/tests/unit/nest/maps.gers-details.test.ts+++ b/server/tests/unit/nest/maps.gers-details.test.ts@@ -119,4 +119,18 @@ describe('MapsService.getPlaceDetails for a gers: id', () => {// The index's own hours survive: they came with the record, not from OSM.expect(out.place?.opening_hours).toBeTruthy();});++ it('MAPS-GERS-009: with the index switched off, opening a saved place asks nobody', async () => {+ // TREK_PLACES_ENABLED=false is the operator's word that nothing leaves for+ // the index. Search, autocomplete and the area download honoured it; the+ // lookup by id did not, so every saved place that came from the index was+ // still sent out, with the instance token, on every open.+ const svc = make({ opening_hours: 'Mo-Su 11:30-23:00' });+ vi.spyOn(svc, 'trekPlacesEnabled').mockReturnValue(false);++ await expect(svc.getPlaceDetails(1, 'gers:abc-123')).resolves.toEqual({ place: null });++ expect(mockById).not.toHaveBeenCalled();+ expect(svc.resolveOsmIdentity).not.toHaveBeenCalled();+ });});diff --git a/server/tests/unit/nest/maps.search-merge.test.ts b/server/tests/unit/nest/maps.search-merge.test.tsindex 32b85da64..cba176ab8 100644--- a/server/tests/unit/nest/maps.search-merge.test.ts+++ b/server/tests/unit/nest/maps.search-merge.test.ts@@ -205,6 +205,23 @@ describe('MapsService.searchPlaces — the merged path', () => {expect(out.source).toBe('openstreetmap');});+ it('MAPS-SEARCH-010: the OpenStreetMap half runs on a deadline of its own', async () => {+ // The pair costs the slower one. The index gives up after 3.5 s; without a+ // deadline the Nominatim side rode undici's 300 s default, so a Nominatim+ // that accepted the connection and sat on it held the whole answer past the+ // browser's 8 s and threw the index's results away with it. The client+ // builds the signal after its throttle wait, so this only has to fit the+ // answer itself, and it has to stay under the browser's budget.+ mockSearch.mockResolvedValue([indexHit("L'Osteria")]);++ await make().searchPlaces(1, "L'Osteria");++ const opts = mockNominatim.mock.calls[0][2] as { lane?: string; timeoutMs?: number };+ expect(opts.lane).toBe('interactive');+ expect(opts.timeoutMs).toBeGreaterThan(0);+ expect(opts.timeoutMs).toBeLessThan(8000);+ });+it('MAPS-SEARCH-008: the location bias reaches both sources', async () => {mockSearch.mockResolvedValue([indexHit("L'Osteria")]);diff --git a/server/tests/unit/nest/maps.service.test.ts b/server/tests/unit/nest/maps.service.test.tsindex 88d6515d0..00472067b 100644--- a/server/tests/unit/nest/maps.service.test.ts+++ b/server/tests/unit/nest/maps.service.test.ts@@ -904,6 +904,19 @@ describe('fetchOverpassDetails (fetch stubbed)', () => {expect(result).toBeNull();});+ it('MAPS-032b: refuses an id that is not a number, without sending anything', async () => {+ // The id is interpolated into Overpass QL. Anything past the digits is a+ // statement of its own, run on the mirror under TREK's shared user agent:+ // this one turns a millisecond lookup into a global scan capped only by the+ // query's own five second timeout.+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ for (const bad of ['1);nwr["amenity"](-90,-180,90,180', '12345;out geom', '', ' 1', '1e3', '-5']) {+ expect(await svc.fetchOverpassDetails('node', bad), bad).toBeNull();+ }+ expect(fetchMock).not.toHaveBeenCalled();+ });+it('MAPS-033: returns null when fetch throws', async () => {vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network error')));const result = await svc.fetchOverpassDetails('node', '99999');@@ -1719,6 +1732,27 @@ describe('getPlaceDetails (fetch stubbed)', () => {expect((result.place as any).website).toBeNull();});+ it('MAPS-040c: an OSM id with anything but digits after the colon is no place, and asks nobody', async () => {+ // The route takes the id as a path segment and nothing validates it before+ // it reaches here. Split at the colon, the rest went into an Overpass query+ // as it was and to Nominatim as an osm_ids value, so a doctored id ran a+ // query of its own on the mirror. A coordinate pseudo-id and a legacy image+ // URL carry a colon too and have no details source either way.+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ for (const id of [+ 'node:1);nwr["amenity"](-90,-180,90,180',+ 'way:12345;out geom',+ 'relation:',+ 'node:abc',+ 'coords:48.8,2.3',+ 'https://example.test/pic.jpg',+ ]) {+ await expect(svc.getPlaceDetails(1, id), id).resolves.toEqual({ place: null });+ }+ expect(fetchMock).not.toHaveBeenCalled();+ });+// A Google id has no OpenStreetMap equivalent, so without a key there is// nothing to look up. That is an empty result, not a client error: search and// autocomplete already answer their keyless case with the OSM stack, and thisdiff --git a/server/tests/unit/nest/place-enrichment.description.test.ts b/server/tests/unit/nest/place-enrichment.description.test.tsindex e0db2a534..86b4f2f14 100644--- a/server/tests/unit/nest/place-enrichment.description.test.ts+++ b/server/tests/unit/nest/place-enrichment.description.test.ts@@ -75,6 +75,7 @@ function mapsStub(over: Partial<Record<keyof MapsService, unknown>> = {}) {fetchWikidataSitelinks: vi.fn(async () => ({}) as Record<string, string>),resolveOsmIdentity: vi.fn(async () => null as { tags: Record<string, string>; osmUrl: string | null; matchedName: string } | null),details: vi.fn(async () => ({ place: null })),+ trekPlacesEnabled: vi.fn(() => true),...over,} as unknown as MapsService;}@@ -179,7 +180,7 @@ describe('description source order', () => {it('ENRICH-074: still falls back to Google when nothing free describes the place', async () => {const maps = mapsStub({getMapsKey: vi.fn(() => 'key'),- details: vi.fn(async () => ({ place: { source: 'google', google_maps_url: 'https://maps.google/x' } })),+ details: vi.fn(async () => ({ place: { source: 'google', google_maps_url: 'https://maps.google.com/x' } })),fetchEditorialSummary: vi.fn(async () => 'Casual chain for wood-fired pizza.'),});@@ -188,11 +189,40 @@ describe('description source order', () => {expect(out.description).toMatchObject({source: 'google',text: 'Casual chain for wood-fired pizza.',- sourceUrl: 'https://maps.google/x',+ sourceUrl: 'https://maps.google.com/x',license: null,});});+ it('ENRICH-120: links Google\'s summary only to a Google Maps address', async () => {+ // The record and its link come with the request, and the answer is cached+ // for every user of the instance under the label "Google". A link that is+ // not a Google Maps address by shape is dropped; the text stays.+ for (const bad of ['https://phish.example/maps', 'https://google.evil.example/x', 'javascript:alert(1)', 'maps.google.com/x']) {+ const maps = mapsStub({+ getMapsKey: vi.fn(() => 'key'),+ fetchEditorialSummary: vi.fn(async () => 'Casual chain for wood-fired pizza.'),+ });+ const out = await make(maps).enrich(1, {+ ...GOOGLE_REQ,+ details: { source: 'google', google_maps_url: bad },+ });+ expect(out.description, bad).toMatchObject({ source: 'google', text: 'Casual chain for wood-fired pizza.', sourceUrl: null });+ }++ for (const ok of ['https://maps.google.com/?cid=1', 'https://www.google.de/maps/place/x', 'https://maps.app.goo.gl/abc']) {+ const maps = mapsStub({+ getMapsKey: vi.fn(() => 'key'),+ fetchEditorialSummary: vi.fn(async () => 'Casual chain for wood-fired pizza.'),+ });+ const out = await make(maps).enrich(1, {+ ...GOOGLE_REQ,+ details: { source: 'google', google_maps_url: ok },+ });+ expect(out.description, ok).toMatchObject({ source: 'google', sourceUrl: ok });+ }+ });+it('ENRICH-075: keeps the OpenStreetMap description ahead of everything', async () => {const maps = mapsStub({details: vi.fn(async () => ({@@ -362,23 +392,37 @@ describe("the description on the place's own website", () => {lang: 'de',};- it('ENRICH-100: reads the description the details lookup already fetched', async () => {- // The details call fetched this place a moment ago and its answer carries- // the description. Asking again made adding one place cost two full round- // trips to the index, each with its own timeout, for a field already in- // hand.+ it('ENRICH-100: asks the index for the description, not the request that carries one', async () => {+ // The dialog's own lookup fetched this place a moment ago and the request+ // carries its answer, description included. It is still not read from+ // there: the result lands in a cache the whole instance reads from for a+ // week, and the text and the link in it have to be the index's, not+ // whatever the sender put in the body. The cached row is the proof.mockTrekPlacesById.mockClear();+ mockTrekPlacesById.mockResolvedValue({+ description: { text: 'Pizza in Rostock, seit 2015.', sourceUrl: 'https://losteria.net/rostock' },+ });const out = await make(mapsStub()).enrich(1, {...GERS_REQ,- details: { description: { text: 'Pizza in Rostock, seit 2015.', sourceUrl: 'https://losteria.net/rostock' } },+ details: {+ source: 'trek-places',+ description: { text: 'Buchung nur noch über https://phish.example', sourceUrl: 'https://phish.example' },+ },});- expect(out.description).toMatchObject({ text: 'Pizza in Rostock, seit 2015.', source: 'website' });- expect(mockTrekPlacesById).not.toHaveBeenCalled();+ expect(mockTrekPlacesById).toHaveBeenCalledWith('abc-123');+ expect(out.description).toMatchObject({+ text: 'Pizza in Rostock, seit 2015.',+ source: 'website',+ sourceUrl: 'https://losteria.net/rostock',+ });+ const written = mockDbRun.mock.calls.find(([sql]) => String(sql).includes('INSERT OR REPLACE INTO place_details_cache'));+ expect(written).toBeTruthy();+ expect(String(written![4])).not.toContain('phish.example');});- it('ENRICH-101: still asks when the caller passed no details', async () => {+ it('ENRICH-101: asks when the caller passed no details, all the same', async () => {mockTrekPlacesById.mockClear();mockTrekPlacesById.mockResolvedValue({description: { text: 'Pizza in Rostock, seit 2015.', sourceUrl: 'https://losteria.net/rostock' },@@ -394,24 +438,109 @@ describe("the description on the place's own website", () => {// It becomes an href on the client, and the value comes from whatever index// the instance is pointed at. The same allow-list a place's website goes// through, for the same reason.- mockTrekPlacesById.mockClear();-for (const bad of ['javascript:alert(1)', 'data:text/html,<script>', 'file:///etc/passwd', 'not a url']) {- const out = await make(mapsStub()).enrich(1, {- ...GERS_REQ,- details: { description: { text: 'Pizza in Rostock.', sourceUrl: bad } },- });+ mockTrekPlacesById.mockResolvedValue({ description: { text: 'Pizza in Rostock.', sourceUrl: bad } });+ const out = await make(mapsStub()).enrich(1, GERS_REQ);expect(out.description, bad).toMatchObject({ text: 'Pizza in Rostock.', sourceUrl: null });}// The ordinary case still keeps its link.- const ok = await make(mapsStub()).enrich(1, {- ...GERS_REQ,- details: { description: { text: 'Pizza in Rostock.', sourceUrl: 'https://losteria.net/rostock' } },+ mockTrekPlacesById.mockResolvedValue({+ description: { text: 'Pizza in Rostock.', sourceUrl: 'https://losteria.net/rostock' },});+ const ok = await make(mapsStub()).enrich(1, GERS_REQ);expect(ok.description).toMatchObject({ sourceUrl: 'https://losteria.net/rostock' });});+ it('ENRICH-117: a description the request made up never reaches the shared cache', async () => {+ // The index knows no description for this place. The request claims one,+ // with a link. Nobody gets to see it, the sender included: the website+ // rung reads the index and nothing else.+ mockTrekPlacesById.mockClear();+ mockTrekPlacesById.mockResolvedValue({ description: null });++ const out = await make(mapsStub()).enrich(1, {+ ...GERS_REQ,+ details: {+ source: 'trek-places',+ description: { text: 'Buchung nur noch über https://phish.example', sourceUrl: 'https://phish.example' },+ },+ });++ expect(out.description).toBeNull();+ for (const [sql, ...params] of mockDbRun.mock.calls) {+ expect(JSON.stringify(params), String(sql)).not.toContain('phish.example');+ }+ });++ it('ENRICH-118: an OpenStreetMap summary the request carried is answered, but not cached for everyone', async () => {+ // The OSM rung reads `summary` and `osm_url` straight off the details, and+ // the details came with the request. Answering the sender with their own+ // payload is harmless; writing it into the row every other user of the+ // instance reads for a week is not. The row simply is not written.+ const carried = {+ ...OSM_REQ,+ details: {+ source: 'openstreetmap',+ summary: 'Buchung nur noch über https://phish.example',+ osm_url: 'https://phish.example',+ },+ };++ const out = await make(mapsStub()).enrich(1, carried);++ expect(out.description).toMatchObject({ source: 'osm', text: 'Buchung nur noch über https://phish.example' });+ expect(mockDbRun.mock.calls.some(([sql]) => String(sql).includes('place_details_cache'))).toBe(false);++ // The same summary from the service's own lookup is the map's, and keeps.+ const maps = mapsStub({+ details: vi.fn(async () => ({+ place: { source: 'openstreetmap', summary: 'Größter Kreuzungsbahnhof Europas.', osm_url: 'https://www.openstreetmap.org/relation/3600565' },+ })),+ });+ mockDbRun.mockClear();+ const own = await make(maps).enrich(1, OSM_REQ);+ expect(own.description).toMatchObject({ source: 'osm', text: 'Größter Kreuzungsbahnhof Europas.' });+ expect(mockDbRun.mock.calls.some(([sql]) => String(sql).includes('INSERT OR REPLACE INTO place_details_cache'))).toBe(true);+ });++ it('ENRICH-121: a menu link the request carried is answered, but not cached for everyone', async () => {+ // The menu chip is the other link read straight off the details: it goes+ // out as an href under the label "Menu", and a request can put any http(s)+ // address there. Same treatment as the summary: the sender sees it, the+ // row is not written.+ const out = await make(mapsStub()).enrich(1, {+ ...OSM_REQ,+ details: { source: 'openstreetmap', menu_url: 'https://phish.example/menu' },+ });++ expect(out.facts).toContainEqual({ kind: 'menu', value: null, url: 'https://phish.example/menu' });+ expect(mockDbRun.mock.calls.some(([sql]) => String(sql).includes('place_details_cache'))).toBe(false);++ // The same link from the service's own lookup is the map's, and keeps.+ const maps = mapsStub({+ details: vi.fn(async () => ({ place: { source: 'openstreetmap', menu_url: 'https://example.org/karte' } })),+ });+ mockDbRun.mockClear();+ const own = await make(maps).enrich(1, OSM_REQ);+ expect(own.facts).toContainEqual({ kind: 'menu', value: null, url: 'https://example.org/karte' });+ expect(mockDbRun.mock.calls.some(([sql]) => String(sql).includes('INSERT OR REPLACE INTO place_details_cache'))).toBe(true);+ });++ it('ENRICH-119: with the index switched off, no lookup leaves for the description', async () => {+ // TREK_PLACES_ENABLED=false is a promise about egress, and a saved index+ // place opened later is still an index place.+ mockTrekPlacesById.mockClear();+ mockTrekPlacesById.mockResolvedValue({+ description: { text: 'Pizza in Rostock, seit 2015.', sourceUrl: 'https://losteria.net/rostock' },+ });++ const out = await make(mapsStub({ trekPlacesEnabled: vi.fn(() => false) })).enrich(1, GERS_REQ);++ expect(mockTrekPlacesById).not.toHaveBeenCalled();+ expect(out.description).toBeNull();+ });+it('ENRICH-090: quotes the site and credits it by URL', async () => {mockTrekPlacesById.mockResolvedValue({description: { text: 'Pizza in Rostock, seit 2015.', sourceUrl: 'https://losteria.net/rostock' },diff --git a/server/tests/unit/nest/place-enrichment.service.test.ts b/server/tests/unit/nest/place-enrichment.service.test.tsindex de1d25949..94256772d 100644--- a/server/tests/unit/nest/place-enrichment.service.test.ts+++ b/server/tests/unit/nest/place-enrichment.service.test.ts@@ -87,6 +87,7 @@ function mapsStub(over: Partial<Record<keyof MapsService, unknown>> = {}) {fetchWikidataSitelinks: vi.fn(async () => ({}) as Record<string, string>),fetchWikiExtractFor: vi.fn(async () => null as { text: string; sourceUrl: string; source: 'wikivoyage' | 'wikipedia' } | null),details: vi.fn(async () => ({ place: null })),+ trekPlacesEnabled: vi.fn(() => true),...over,} as unknown as MapsService;}diff --git a/server/tests/unit/nest/places.controller.test.ts b/server/tests/unit/nest/places.controller.test.tsindex b9dc565ab..7dfa107eb 100644--- a/server/tests/unit/nest/places.controller.test.ts+++ b/server/tests/unit/nest/places.controller.test.ts@@ -274,7 +274,22 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rouexpect(linkedExpenseIds).toHaveBeenCalledWith('5', [1, 2]);expect(linkedExpenseIds.mock.invocationCallOrder[0]).toBeLessThan(removeMany.mock.invocationCallOrder[0]);- expect(broadcast).toHaveBeenCalledWith('5', 'budget:deleted', { itemId: 77 }, 'sock');+ // Without the socket id: the deleting tab removed the places itself, not+ // the expense, so it has to hear about that one like everybody else.+ expect(broadcast).toHaveBeenCalledWith('5', 'budget:deleted', { itemId: 77 }, undefined);+ });++ it('tells the deleting tab about the booking and the expense a cancelled night took down', async () => {+ const removeMany = vi.fn().mockReturnValue({ deleted: [1], cancelled: { reservationIds: [12], budgetItemIds: [77] } });+ const broadcast = vi.fn();+ const s = svc({ removeMany, broadcast, scopedIds: vi.fn().mockReturnValue([1]) } as Partial<PlacesService>);+ await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1] }, 'sock');++ // The place is the one change the tab made itself, so that echo stays+ // filtered. The booking and its expense went on the server alone.+ expect(broadcast).toHaveBeenCalledWith('5', 'place:deleted', { placeId: 1 }, 'sock');+ expect(broadcast).toHaveBeenCalledWith('5', 'reservation:deleted', { reservationId: 12 }, undefined);+ expect(broadcast).toHaveBeenCalledWith('5', 'budget:deleted', { itemId: 77 }, undefined);});});@@ -440,8 +455,13 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rouawait new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9', 'sock');- expect(broadcast).toHaveBeenCalledWith('5', 'reservation:deleted', { reservationId: 12 }, 'sock');- expect(broadcast).toHaveBeenCalledWith('5', 'budget:deleted', { itemId: 77 }, 'sock');+ // The place echo stays filtered by the socket id; the booking and the+ // expense are sent to the deleting tab as well, because that tab only+ // removed the place itself and would otherwise keep showing both until a+ // reload.+ expect(broadcast).toHaveBeenCalledWith('5', 'place:deleted', { placeId: 9 }, 'sock');+ expect(broadcast).toHaveBeenCalledWith('5', 'reservation:deleted', { reservationId: 12 }, undefined);+ expect(broadcast).toHaveBeenCalledWith('5', 'budget:deleted', { itemId: 77 }, undefined);});// #1745: a place on another trip must 404 without the hook ever running —diff --git a/server/tests/unit/nest/roadtrip-mcp.helpers.test.ts b/server/tests/unit/nest/roadtrip-mcp.helpers.test.tsnew file mode 100644index 000000000..65822da3f--- /dev/null+++ b/server/tests/unit/nest/roadtrip-mcp.helpers.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';+import { HttpException } from '@nestjs/common';+import { ok, type McpTextResult } from '../../../src/nest-mcp';+import { answeringRefusals } from '../../../src/nest/roadtrip/roadtrip-mcp.helpers';++/** A tool body whose service refuses, typed as the answer it never produces. */+const refusing = (body: unknown, status = 400) => (): McpTextResult => { throw new HttpException(body as never, status); };+const failing = (message: string) => (): McpTextResult => { throw new Error(message); };++describe('answeringRefusals', () => {+ it('answers a refusal with the reason the route would send, sync and async', async () => {+ // The `{ error }` body is what the HTTP filter passes through verbatim. Nest sets+ // the exception's message to the class name for such a body, and that is all the+ // SDK would have shown.+ const sync = answeringRefusals(refusing({ error: 'Day end must be later than day start.' }));+ expect(sync).toEqual({ content: [{ type: 'text', text: 'Day end must be later than day start.' }], isError: true });+ const async = await answeringRefusals(async () => refusing({ error: 'Trip not found' }, 404)());+ expect(async).toEqual({ content: [{ type: 'text', text: 'Trip not found' }], isError: true });+ });++ it('takes a string body as the reason and falls back to the message for anything else', () => {+ expect(answeringRefusals(refusing('Permission denied', 403)).content[0].text).toBe('Permission denied');+ expect(answeringRefusals(refusing({ statusCode: 400, message: 'Bad Request' })).content[0].text).toBe('Bad Request');+ });++ it('passes a successful body through untouched', async () => {+ expect(answeringRefusals(() => ok({ n: 1 }))).toEqual(ok({ n: 1 }));+ expect(await answeringRefusals(async () => ok({ n: 2 }))).toEqual(ok({ n: 2 }));+ });++ it('keeps propagating anything that is not a refusal', async () => {+ // A 5xx is a failure to be logged and reported like any other, not an answer,+ // and an ordinary error is not the SDK's to swallow either.+ expect(() => answeringRefusals(refusing({ error: 'boom' }, 500))).toThrow(HttpException);+ expect(() => answeringRefusals(failing('plain'))).toThrow('plain');+ await expect(answeringRefusals(async () => failing('later')())).rejects.toThrow('later');+ });+});diff --git a/server/tests/unit/nest/roadtrip-planning.test.ts b/server/tests/unit/nest/roadtrip-planning.test.tsindex 79ff1b6b5..0d3e26e0b 100644--- a/server/tests/unit/nest/roadtrip-planning.test.ts+++ b/server/tests/unit/nest/roadtrip-planning.test.ts@@ -134,6 +134,21 @@ describe('roadtrip preferences', () => {await mcp.update({ tripId: 10, settings: { roadtrip_range_km: 300 } }, ctx);expect(s.preferenceDb.run).not.toHaveBeenCalled();});+ it('tells the assistant why a window was refused instead of the exception class name', async () => {+ // The service refuses an inverted window with the `{ error }` body the route+ // sends verbatim; left to the SDK the tool would answer "Http Exception".+ const s = setup();+ const mcp = new RoadtripPreferencesMcp(+ s.preferences,+ { isDemoUser: () => false } as never,+ {} as never,+ s.db as never,+ { hasTripPermission: () => true } as never,+ );+ const res = await mcp.update({ tripId: 10, settings: { roadtrip_day_end: '06:00' } }, ctx);+ expect([res.isError, res.content[0].text]).toEqual([true, 'Day end must be later than day start.']);+ expect(s.preferences.read(10).roadtrip_day_end).toBe('10:00');+ });});describe('browser-independent roadtrip calculation', () => {@@ -161,6 +176,22 @@ describe('browser-independent roadtrip calculation', () => {expect(s.db.all).not.toHaveBeenCalled();expect(s.router.route).not.toHaveBeenCalled();});+ it('tells the assistant why a read, a calculation or a corridor search was refused', async () => {+ // The service refuses with the `{ error }` body the route sends verbatim. Left+ // to the SDK, the tool would answer "Http Exception" and the assistant could+ // name no reason.+ const s = setup();+ const mcp = new RoadtripPlanningMcp(s.plans, {} as never, {} as never);+ const reason = (res: { content: { text: string }[]; isError?: boolean }) => [res.isError, res.content[0].text];+ s.db.canAccessTrip.mockReturnValue(false);+ expect(reason(await mcp.context({ tripId: 20 }, ctx))).toEqual([true, 'Trip not found']);+ expect(reason(await mcp.calculate({ tripId: 20, includeGeometry: false }, ctx))).toEqual([true, 'Trip not found']);+ expect(reason(await mcp.corridor({ tripId: 20, dayNumber: 1, category: 'fuel', widthKm: 5, offset: 0 } as never, ctx))).toEqual([true, 'Trip not found']);+ s.db.canAccessTrip.mockReturnValue(true);+ const window = await mcp.calculate({ tripId: 10, includeGeometry: false, settings: { roadtrip_day_start: '18:00', roadtrip_day_end: '08:00' } }, ctx);+ expect(reason(window)).toEqual([true, 'Day end must be later than day start.']);+ expect(s.router.route).not.toHaveBeenCalled();+ });it('marks provider failures incomplete and never leaks an endpoint from its exception', async () => {const s = setup();s.router.route.mockRejectedValue(new Error('secret https://private.example'));diff --git a/server/tests/unit/nest/roadtrip-read-tools.test.ts b/server/tests/unit/nest/roadtrip-read-tools.test.tsindex df3b4a4ca..0f8f948b8 100644--- a/server/tests/unit/nest/roadtrip-read-tools.test.ts+++ b/server/tests/unit/nest/roadtrip-read-tools.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi } from 'vitest';+import { HttpException } from '@nestjs/common';import type { McpContext } from '../../../src/nest-mcp';import { ChargingMcp } from '../../../src/nest/roadtrip/charging.mcp';import { RoadtripHazardsMcp } from '../../../src/nest/roadtrip/roadtrip-hazards.mcp';@@ -43,6 +44,31 @@ describe('roadtrip read tools', () => {expect(res.isError).toBe(true);expect(routes.import).not.toHaveBeenCalled();});+ it('answers a refusal from the service with its reason, not with the exception class name', async () => {+ // The services refuse with `{ error }` bodies the REST filter sends verbatim. Let+ // through as exceptions, the SDK would show the assistant "Http Exception" and+ // nothing else, so every tool on this surface answers them as error results.+ const refuse = (error: string, status: number) => () => { throw new HttpException({ error }, status); };+ const text = (res: { content: { text: string }[]; isError?: boolean }) => [res.isError, res.content[0].text];++ const db = { canAccessTrip: vi.fn(() => true) };+ const charging = new ChargingMcp({ read: refuse('Place not found', 404) } as never, db as never, {} as never);+ expect(text(await charging.read({ tripId: 10, placeId: 2 }, ctx))).toEqual([true, 'Place not found']);++ const auth = { isDemoUser: vi.fn(() => false) };+ const routes = { preview: refuse('Use a Google Maps directions link.', 400), import: refuse('Permission denied', 403) };+ const google = new GoogleRouteMcp(routes as never, auth as never, {} as never);+ expect(text(await google.preview({ url: 'https://www.google.com/maps/place/A' }))).toEqual([true, 'Use a Google Maps directions link.']);+ expect(text(google.import({ tripId: 10, dayId: 1, stops: [{ name: 'A', lat: 1, lng: 2 }] } as never, ctx))).toEqual([true, 'Permission denied']);++ const realtime = { broadcast: vi.fn() };+ const guards = { hasTripPermission: vi.fn(() => true) };+ const boundaries = new DayBoundariesMcp({ save: refuse('Stop not found', 404) } as never, db as never, auth as never, guards as never, realtime as never, {} as never);+ const boundary = { day_number: 1, from_assignment_id: 11, to_assignment_id: 12, fraction: 0.4 };+ expect(text(await boundaries.save({ tripId: 10, dayNumber: 1, boundary }, ctx))).toEqual([true, 'Stop not found']);+ expect(realtime.broadcast).not.toHaveBeenCalled();+ });+it('does not expose manual boundaries to nonmembers', async () => {const boundaries = { list: vi.fn(() => [{ day_number: 1 }]) };const db = { canAccessTrip: vi.fn(() => false) };diff --git a/server/tests/unit/nest/system-notices.controller.test.ts b/server/tests/unit/nest/system-notices.controller.test.tsindex 11f7473cd..e7e5c64b4 100644--- a/server/tests/unit/nest/system-notices.controller.test.ts+++ b/server/tests/unit/nest/system-notices.controller.test.ts@@ -33,7 +33,33 @@ describe('SystemNoticesController (parity with the legacy /api/system-notices roit('returns the evaluated notices for the current user', () => {const getActiveFor = vi.fn().mockReturnValue([notice]);expect(makeController({ getActiveFor }).active(user)).toEqual([notice]);- expect(getActiveFor).toHaveBeenCalledWith(7);+ expect(getActiveFor).toHaveBeenCalledWith(7, new Set());+ });++ // The layouts a bundle announces with `?supports=` reach the service as a set, so+ // a bundle that predates the parameter announces nothing.+ it('passes the announced layouts through as a set', () => {+ const getActiveFor = vi.fn().mockReturnValue([]);+ makeController({ getActiveFor }).active(user, 'release');+ expect(getActiveFor).toHaveBeenCalledWith(7, new Set(['release']));+ });++ it('splits a comma separated list and a repeated parameter alike', () => {+ const getActiveFor = vi.fn().mockReturnValue([]);+ const ctrl = makeController({ getActiveFor });+ ctrl.active(user, ' release, banner ,,');+ expect(getActiveFor).toHaveBeenLastCalledWith(7, new Set(['release', 'banner']));+ ctrl.active(user, ['release', 'banner']);+ expect(getActiveFor).toHaveBeenLastCalledWith(7, new Set(['release', 'banner']));+ });++ it('announces nothing for an empty or missing parameter', () => {+ const getActiveFor = vi.fn().mockReturnValue([]);+ const ctrl = makeController({ getActiveFor });+ ctrl.active(user, '');+ expect(getActiveFor).toHaveBeenLastCalledWith(7, new Set());+ ctrl.active(user, undefined);+ expect(getActiveFor).toHaveBeenLastCalledWith(7, new Set());});});diff --git a/server/tests/unit/nest/system-notices.service.test.ts b/server/tests/unit/nest/system-notices.service.test.tsindex 9f4ed3943..de9bfb894 100644--- a/server/tests/unit/nest/system-notices.service.test.ts+++ b/server/tests/unit/nest/system-notices.service.test.ts@@ -44,6 +44,44 @@ describe('SystemNoticesService', () => {expect(mockDismiss).toHaveBeenCalledWith(7, 'welcome');});+ // After an update the service worker keeps serving the previous bundle for a while.+ // That bundle would draw a release notice as bare keys and let the reader dismiss it+ // for good, so the release layout is only delivered to a client that says it can+ // draw it. Everything without a release block goes out as before.+ describe('getActiveFor holds the release layout back from a client that does not announce it', () => {+ const generic = {+ id: 'outage', display: 'banner', severity: 'warn',+ titleKey: 'system_notice.outage.title', bodyKey: 'system_notice.outage.body', dismissible: true,+ };+ const release = {+ id: 'release-notes', display: 'modal', severity: 'info',+ titleKey: 'system_notice.release_notes.headline', bodyKey: 'system_notice.release_notes.intro',+ dismissible: true,+ release: { version: '4.3.0', headlineKey: 'system_notice.release_notes.headline' },+ };++ it('drops a notice with a release block when nothing is announced', () => {+ mockGetActive.mockReturnValue([release, generic]);+ expect(svc.getActiveFor(7).map(n => n.id)).toEqual(['outage']);+ });++ it('drops it when other layouts are announced but not release', () => {+ mockGetActive.mockReturnValue([release, generic]);+ expect(svc.getActiveFor(7, new Set(['banner'])).map(n => n.id)).toEqual(['outage']);+ });++ it('delivers it, in place, once the client announces the release layout', () => {+ mockGetActive.mockReturnValue([release, generic]);+ expect(svc.getActiveFor(7, new Set(['release'])).map(n => n.id)).toEqual(['release-notes', 'outage']);+ });++ it('always delivers a notice without a release block', () => {+ mockGetActive.mockReturnValue([generic]);+ expect(svc.getActiveFor(7).map(n => n.id)).toEqual(['outage']);+ expect(svc.getActiveFor(7, new Set(['release'])).map(n => n.id)).toEqual(['outage']);+ });+ });+it('still loads and works when the AddonsService binding is unresolved (import-cycle fallback)', async () => {// The emitted design:paramtypes metadata guards an unresolved class binding// with `typeof AddonsService === 'undefined' ? Object : AddonsService`.diff --git a/server/tests/unit/nest/trek-places.client.test.ts b/server/tests/unit/nest/trek-places.client.test.tsindex 927b8dad1..a93a72ca2 100644--- a/server/tests/unit/nest/trek-places.client.test.ts+++ b/server/tests/unit/nest/trek-places.client.test.ts@@ -10,7 +10,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';// Mutable, so the instance URL and the operator's own index can be set per test.const { env } = vi.hoisted(() => ({env: {- maps: { trekPlacesUrl: '' },+ maps: { trekPlacesUrl: '', trekPlacesEnabled: true },app: { appUrl: 'https://trip.example.org', port: 3001 },http: { allowedOriginsRaw: '' },},@@ -112,6 +112,7 @@ beforeEach(() => {// Process state, so it leaks between cases unless it is cleared.resetTrekPlacesBreaker();env.maps.trekPlacesUrl = '';+ env.maps.trekPlacesEnabled = true;env.app.appUrl = 'https://trip.example.org';env.app.port = 3001;env.http.allowedOriginsRaw = '';@@ -439,6 +440,32 @@ describe('trekPlacesById', () => {});});+describe('the switch', () => {+ it('lets nothing leave once the operator turned the index off, a lookup by id included', async () => {+ // TREK_PLACES_ENABLED=false is a promise about egress. The service checks+ // it before each call it makes; this is the one place every request passes,+ // so a caller that did not is stopped here rather than at the firewall.+ env.maps.trekPlacesEnabled = false;+ stubFetch({ place: PLACE });++ await expect(trekPlacesById('abc-123')).rejects.toThrow('switched off');+ await expect(trekPlacesSearch('osteria')).rejects.toThrow('switched off');+ await expect(trekPlacesNearby(54, 12)).rejects.toThrow('switched off');+ await expect(trekPlacesArea(BOX)).rejects.toThrow('switched off');+ expect(calls).toEqual([]);+ });++ it('is not an outage: the refusal never opens the breaker', async () => {+ env.maps.trekPlacesEnabled = false;+ for (let i = 0; i < 6; i++) await trekPlacesById('abc-123').catch(() => null);++ env.maps.trekPlacesEnabled = true;+ stubFetch({ place: PLACE });+ await expect(trekPlacesById('abc-123')).resolves.toEqual(PLACE);+ expect(calls).toHaveLength(1);+ });+});+describe('trekPlacesNearby', () => {it('rounds the radius and passes the category list through', async () => {stubFetch({ results: [] });diff --git a/server/tests/unit/reservations/bookings.rpc.test.ts b/server/tests/unit/reservations/bookings.rpc.test.tsindex b17501159..0cbac2d25 100644--- a/server/tests/unit/reservations/bookings.rpc.test.ts+++ b/server/tests/unit/reservations/bookings.rpc.test.ts@@ -206,22 +206,38 @@ describe('ReservationsRpc', () => {expect(f.reservations.create).not.toHaveBeenCalled();});- it('BOOK-RPC-019 the same on update, while an id on another trip still writes', async () => {+ it('BOOK-RPC-019 the same on update', async () => {const f = build({ unresolved: ['day_id'] });const res = (await f.host().dispatch(req('reservations.update', { tripId: 1, reservationId: 5, input: { title: 'x', type: 'lodging', day_id: 999999 } }), 42,)) as RpcError;expect(res.error.code).toBe('BAD_PARAMS');expect(f.reservations.update).not.toHaveBeenCalled();+ });++ it('BOOK-RPC-020 an id from another trip is RESOURCE_FORBIDDEN before the write, on create and update', async () => {+ // reservation_edit on trip 1 says nothing about the ids in the body. A stay+ // written against another trip's day puts a stop on that day, in a plan the+ // acting user may not even read, so the body is checked the way the REST route+ // and the MCP tool check it, and ownership is judged before existence.+ const f = build({ foreign: ['create_accommodation.start_day_id'], unresolved: ['create_accommodation.start_day_id'] });+ const stay = { title: 'Hotel', type: 'lodging', create_accommodation: { place_id: 9, start_day_id: 4711, end_day_id: 4712 } };+ const created = (await f.host().dispatch(req('reservations.create', { tripId: 1, input: stay }), 42)) as RpcError;+ expect(created.error.code).toBe('RESOURCE_FORBIDDEN');+ expect(created.error.message).toBe('not part of trip 1: create_accommodation.start_day_id');+ expect(f.reservations.create).not.toHaveBeenCalled();++ const g = build({ foreign: ['day_id'] });+ const updated = (await g.host().dispatch(req('reservations.update', { tripId: 1, reservationId: 5, input: { title: 'x', type: 'lodging', day_id: 4711 } }), 42)) as RpcError;+ expect(updated.error.code).toBe('RESOURCE_FORBIDDEN');+ expect(updated.error.message).toBe('not part of trip 1: day_id');+ expect(g.reservations.update).not.toHaveBeenCalled();+ expect(g.realtime.broadcast).not.toHaveBeenCalled();- // A plugin has always been able to name another trip's row through this- // surface. Taking that away is a change to the plugin contract, not part of- // turning a crash into an error.- const foreign = build({ unresolved: ['day_id'], foreign: ['day_id'] });- expect((await foreign.host().dispatch(- req('reservations.update', { tripId: 1, reservationId: 5, input: { title: 'x', type: 'lodging', day_id: 7 } }), 42,- )).ok).toBe(true);- expect(foreign.reservations.update).toHaveBeenCalled();+ // The same body with this trip's ids goes through.+ const h = build();+ expect((await h.host().dispatch(req('reservations.create', { tripId: 1, input: { ...stay, create_accommodation: { ...stay.create_accommodation, start_day_id: 3 } } }), 42)).ok).toBe(true);+ expect(h.reservations.referencesOutsideTrip).toHaveBeenLastCalledWith('1', expect.objectContaining({ create_accommodation: expect.objectContaining({ start_day_id: 3 }) }));});it('BOOK-RPC-009 the class is listed in its module providers', () => {diff --git a/server/tests/unit/services/airtrailTestConnection.test.ts b/server/tests/unit/services/airtrailTestConnection.test.tsnew file mode 100644index 000000000..22ec47cc6--- /dev/null+++ b/server/tests/unit/services/airtrailTestConnection.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Avoid any real DNS/network from the SSRF guard during saveSettings and the probe.+vi.mock('../../../src/utils/ssrfGuard', () => ({+ checkSsrf: vi.fn(async () => ({ allowed: true, isPrivate: false })),+ safeFetch: vi.fn(),+}));++import { db } from '../../../src/db/database';+import { createUser } from '../../helpers/factories';+import { AirtrailService } from '../../../src/nest/integrations/airtrail.service';+import type { AirtrailClient } from '../../../src/nest/integrations/airtrail.client';+import { DatabaseService } from '../../../src/nest/database/database.service';+import { AuditService } from '../../../src/nest/audit/audit.service';++// The probe is the only call that would leave the process, so the client is a+// stub; the credential handling around it runs against the real row.+const listFlights = vi.fn();+const svc = new AirtrailService(+ new DatabaseService(db),+ new AuditService(new DatabaseService(db)),+ { listFlights } as unknown as AirtrailClient,+);++const MASK = '••••••••';++beforeEach(() => {+ listFlights.mockReset();+ listFlights.mockResolvedValue([]);+});++describe('airtrail test connection keeps the stored key with its host', () => {+ it('refuses a blank key field against a different host than the stored one before anything is sent', async () => {+ // The form prefills the address and never the key, so retyping the URL and+ // pressing Test is the ordinary way to move an instance. Falling back to the+ // stored key here would carry it to whatever host was just typed.+ const { user } = createUser(db);+ await svc.saveSettings(user.id, 'https://old.example', 'stored-key', false, false, null);++ const out = await svc.testConnection(user.id, 'https://someone-elses.example', undefined, false);++ expect(out.connected).toBe(false);+ expect(out.error).toContain('https://old.example');+ expect(listFlights).not.toHaveBeenCalled();+ });++ it('treats the mask against a different port as a blank field, not a key', async () => {+ const { user } = createUser(db);+ await svc.saveSettings(user.id, 'https://old.example', 'stored-key', false, false, null);++ const out = await svc.testConnection(user.id, 'https://old.example:8443', MASK, false);++ expect(out.connected).toBe(false);+ expect(listFlights).not.toHaveBeenCalled();+ });++ it('still tests a path edit on the same origin with the stored key', async () => {+ // The same instance under a corrected path is where the key was issued, and+ // refusing it would make every trailing-slash edit demand the key again.+ const { user } = createUser(db);+ await svc.saveSettings(user.id, 'https://at.example/api', 'stored-key', false, false, null);++ const out = await svc.testConnection(user.id, 'https://at.example/', undefined, false);++ expect(out.connected).toBe(true);+ expect(listFlights).toHaveBeenCalledWith({ baseUrl: 'https://at.example/', apiKey: 'stored-key', allowInsecureTls: false });+ });++ it('uses a key typed for the new host as typed, so moving an instance and testing it first still works', async () => {+ const { user } = createUser(db);+ await svc.saveSettings(user.id, 'https://old.example', 'stored-key', false, false, null);++ const out = await svc.testConnection(user.id, 'https://new.example', 'minted-for-new', false);++ expect(out.connected).toBe(true);+ expect(listFlights).toHaveBeenCalledWith({ baseUrl: 'https://new.example', apiKey: 'minted-for-new', allowInsecureTls: false });+ });+});diff --git a/shared/src/dawarich/dawarich.schema.ts b/shared/src/dawarich/dawarich.schema.tsindex 612379e23..098bf27a5 100644--- a/shared/src/dawarich/dawarich.schema.ts+++ b/shared/src/dawarich/dawarich.schema.ts@@ -425,7 +425,11 @@ export const DAWARICH_BUCKET_MATCH_MIN_MINUTES = 20;export const DAWARICH_BUCKET_SCAN_LIMIT = 50;/** Points kept per day after thinning, so a month-long trip stays drawable. */export const DAWARICH_TRACK_POINTS_PER_DAY = 600;-/** How far back a sync looks for trips that have no end date yet. */+/**+ * Days before a trip's start a sync still asks about, for every trip: the+ * visits endpoint filters on the start of a visit, so a stay that began the+ * evening before is invisible at an exact boundary.+ */export const DAWARICH_SYNC_LOOKBACK_DAYS = 3;/** Days past a trip's end still worth polling — a stay can end after midnight. */export const DAWARICH_SYNC_LOOKAHEAD_DAYS = 1;diff --git a/shared/src/i18n/ar/admin.ts b/shared/src/i18n/ar/admin.tsindex dcafbe8f2..950c0a098 100644--- a/shared/src/i18n/ar/admin.ts+++ b/shared/src/i18n/ar/admin.ts@@ -781,5 +781,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'فيمَ يُستخدم المفتاح','admin.mapsKeyHintShort': 'يضيف الصور والتقييمات وساعات العمل. عندها يذهب كل بحث إلى Google.','admin.amapKeyHintShort': 'للبحث عن الأماكن داخل الصين القارية. يحتاج مفتاح خدمة ويب، لا مفتاح JS API.',+ 'admin.collab.links.subtitle': 'الروابط المشتركة والإشارات المرجعية',};export default admin;diff --git a/shared/src/i18n/ar/collab.ts b/shared/src/i18n/ar/collab.tsindex ef5b4ef82..1cb6e4ae3 100644--- a/shared/src/i18n/ar/collab.ts+++ b/shared/src/i18n/ar/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.delete': 'حذف','collab.polls.closedSection': 'مغلق','collab.notes.websitePlaceholder': 'https://...', // en-fallback+ 'collab.chat.imageLimit': 'يمكنك إرفاق ما يصل إلى {max} صور لكل رسالة',+ 'collab.chat.uploading': 'جارٍ الرفع {percent}%',+ 'collab.chat.attachImages': 'إرفاق صور',+ 'collab.chat.attachedImage': 'صورة مرفقة',+ 'collab.chat.closeImage': 'إغلاق الصورة',};export default collab;diff --git a/shared/src/i18n/ar/docsync.ts b/shared/src/i18n/ar/docsync.tsindex 388f42a29..23473bfaa 100644--- a/shared/src/i18n/ar/docsync.ts+++ b/shared/src/i18n/ar/docsync.ts@@ -170,6 +170,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'هذا المزوّد غير متاح على هذا الخادم.','docsync.error.provider_disabled': 'متوقفة مؤقتاً: أوقف مسؤول الخادم هذا المزوّد. ستُستأنف المزامنة عند إعادة تشغيله.',+ 'docsync.binding.reconnect': 'إعادة الاتصال',};export default docsync;diff --git a/shared/src/i18n/ar/map.ts b/shared/src/i18n/ar/map.tsindex 994a58b10..a1f4ca267 100644--- a/shared/src/i18n/ar/map.ts+++ b/shared/src/i18n/ar/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'إخفاء الرحلة كاملة','map.overview.total': 'المسافة الإجمالية','map.attribution': 'مصادر الخريطة',+ 'map.overview.unrouted': 'تعذّر حساب {count} مرحلة، لذا المسافات غير مكتملة.',+ 'map.overview.dayUnrouted': 'تعذّر حساب {count} مرحلة من هذا اليوم',};export default map;diff --git a/shared/src/i18n/ar/mobileTrip.ts b/shared/src/i18n/ar/mobileTrip.tsindex 858aa3b7b..fc887761a 100644--- a/shared/src/i18n/ar/mobileTrip.ts+++ b/shared/src/i18n/ar/mobileTrip.ts@@ -66,5 +66,7 @@ const mobileTrip: TranslationStrings = {'mobileTrip.rtNoneOnStage': 'لا شيء من هذا النوع على طول هذه المرحلة.','mobileTrip.rtTruncated.one': 'مقطع واحد فيه أكثر مما يتسع في إجابة واحدة. اختر أنواعًا أقل لرؤية الباقي.','mobileTrip.rtTruncated.other': 'مقاطع فيها أكثر مما يتسع في إجابة واحدة: {count}. اختر أنواعًا أقل لرؤية الباقي.',+ 'mobileTrip.rtNoDay': 'لم يتم اختيار يوم',+ 'mobileTrip.rtNoDayHint': 'تعرض الخريطة الرحلة كاملة. اضغط على يوم في الأعلى لعرض مسيره.',};export default mobileTrip;diff --git a/shared/src/i18n/ar/roadtrip.ts b/shared/src/i18n/ar/roadtrip.tsindex 331618790..89b30ddb8 100644--- a/shared/src/i18n/ar/roadtrip.ts+++ b/shared/src/i18n/ar/roadtrip.ts@@ -260,5 +260,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'بدون رسوم','roadtrip.alt.noFerry': 'بدون عبّارة','roadtrip.summary.partial': 'لا يزال يجري حساب بقية الطريق',+ 'roadtrip.stay.releaseTitle': 'إلغاء المبيت؟',+ 'roadtrip.stay.releaseBody': 'ستُزال ليلة المبيت في "{name}". تبقى المحطة على الرحلة كاستراحة.',+ 'roadtrip.stay.releaseBookedBody': 'ستُزال ليلة المبيت في "{name}" مع الحجز "{booking}" وأي مصروف مرتبط به. تبقى المحطة على الرحلة كاستراحة.',+ 'roadtrip.stay.releaseAction': 'اجعلها استراحة',};export default roadtrip;diff --git a/shared/src/i18n/ar/trip.ts b/shared/src/i18n/ar/trip.tsindex a39c7aaea..2566f9e73 100644--- a/shared/src/i18n/ar/trip.ts+++ b/shared/src/i18n/ar/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'التحويلات','transit.walkLabel': 'المشي','transit.searchHint': 'ابحث عن رحلات فعلية وأضفها مباشرة إلى اليوم — البيانات عبر Transitous.',+ 'trip.confirm.deletePlaceNight': 'ستُحذف الليلة المحجوزة في "{name}" مع المكان.',+ 'trip.confirm.deletePlaceBooked': 'ستُحذف الليلة المحجوزة في "{name}" مع المكان، ومعها الحجز "{booking}" وأي مصروف مرتبط به.',};export default trip;diff --git a/shared/src/i18n/br/admin.ts b/shared/src/i18n/br/admin.tsindex ee22578dc..7a550e0bb 100644--- a/shared/src/i18n/br/admin.ts+++ b/shared/src/i18n/br/admin.ts@@ -800,5 +800,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Para que a chave é usada','admin.mapsKeyHintShort': 'Adiciona fotos, avaliações e horários. Cada consulta passa então pelo Google.','admin.amapKeyHintShort': 'Para busca de lugares na China continental. Precisa de uma chave de serviço web, não de API JS.',+ 'admin.collab.links.subtitle': 'Ligações partilhadas e marcadores',};export default admin;diff --git a/shared/src/i18n/br/collab.ts b/shared/src/i18n/br/collab.tsindex 924019a60..1c3163f5b 100644--- a/shared/src/i18n/br/collab.ts+++ b/shared/src/i18n/br/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Opções','collab.polls.delete': 'Excluir','collab.polls.closedSection': 'Encerradas',+ 'collab.chat.imageLimit': 'Podes anexar até {max} imagens por mensagem',+ 'collab.chat.uploading': 'A enviar {percent}%',+ 'collab.chat.attachImages': 'Anexar imagens',+ 'collab.chat.attachedImage': 'Imagem anexada',+ 'collab.chat.closeImage': 'Fechar imagem',};export default collab;diff --git a/shared/src/i18n/br/docsync.ts b/shared/src/i18n/br/docsync.tsindex 0e24e06d1..41a9a0e3c 100644--- a/shared/src/i18n/br/docsync.ts+++ b/shared/src/i18n/br/docsync.ts@@ -177,6 +177,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Este provedor não está disponível nesta instância.','docsync.error.provider_disabled': 'Pausado: um administrador desativou este provedor. A sincronização continua assim que ele for reativado.',+ 'docsync.binding.reconnect': 'Voltar a ligar',};export default docsync;diff --git a/shared/src/i18n/br/map.ts b/shared/src/i18n/br/map.tsindex d14722b7b..5a1c03d32 100644--- a/shared/src/i18n/br/map.ts+++ b/shared/src/i18n/br/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Ocultar a viagem inteira','map.overview.total': 'Distância total','map.attribution': 'Créditos do mapa',+ 'map.overview.unrouted': 'Não foi possível calcular {count} troço(s), por isso as distâncias estão incompletas.',+ 'map.overview.dayUnrouted': 'Não foi possível calcular {count} troço(s) deste dia',};export default map;diff --git a/shared/src/i18n/br/mobileTrip.ts b/shared/src/i18n/br/mobileTrip.tsindex 5de92ae9f..f351a690a 100644--- a/shared/src/i18n/br/mobileTrip.ts+++ b/shared/src/i18n/br/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'1 trecho tinha mais do que cabe em uma resposta. Escolha menos tipos para ver o resto.','mobileTrip.rtTruncated.other':'{count} trechos tinham mais do que cabe em uma resposta. Escolha menos tipos para ver o resto.',+ 'mobileTrip.rtNoDay': 'Nenhum dia escolhido',+ 'mobileTrip.rtNoDayHint': 'O mapa mostra a viagem inteira. Toque num dia acima para ver o seu percurso.',};export default mobileTrip;diff --git a/shared/src/i18n/br/roadtrip.ts b/shared/src/i18n/br/roadtrip.tsindex a9fe72725..fa47f3f4a 100644--- a/shared/src/i18n/br/roadtrip.ts+++ b/shared/src/i18n/br/roadtrip.ts@@ -265,5 +265,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Sem pedagio','roadtrip.alt.noFerry': 'Sem balsa','roadtrip.summary.partial': 'O restante do trajeto ainda está sendo calculado',+ 'roadtrip.stay.releaseTitle': 'Remover a pernoita?',+ 'roadtrip.stay.releaseBody': 'A noite em “{name}” será removida. A paragem continua na viagem como pausa.',+ 'roadtrip.stay.releaseBookedBody': 'A noite em “{name}” será removida juntamente com a reserva “{booking}” e qualquer despesa associada. A paragem continua na viagem como pausa.',+ 'roadtrip.stay.releaseAction': 'Tornar uma pausa',};export default roadtrip;diff --git a/shared/src/i18n/br/trip.ts b/shared/src/i18n/br/trip.tsindex ea2cd0410..23aaf14f3 100644--- a/shared/src/i18n/br/trip.ts+++ b/shared/src/i18n/br/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Baldeações','transit.walkLabel': 'A pé','transit.searchHint': 'Busque conexões reais e adicione direto ao dia — dados via Transitous.',+ 'trip.confirm.deletePlaceNight': 'A noite reservada em “{name}” desaparece com o local.',+ 'trip.confirm.deletePlaceBooked': 'A noite reservada em “{name}” desaparece com o local, juntamente com a reserva “{booking}” e qualquer despesa associada.',};export default trip;diff --git a/shared/src/i18n/ca/admin.ts b/shared/src/i18n/ca/admin.tsindex ff616ddf6..eae86f3a1 100644--- a/shared/src/i18n/ca/admin.ts+++ b/shared/src/i18n/ca/admin.ts@@ -723,5 +723,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': "Per a què s'usa la clau",'admin.mapsKeyHintShort': 'Afegeix fotos, valoracions i horaris. Cada consulta passa llavors per Google.','admin.amapKeyHintShort': 'Per a la cerca de llocs a la Xina continental. Cal una clau de servei web, no una clau API JS.',+ 'admin.collab.links.subtitle': 'Enllaços compartits i adreces d’interès',};export default admin;diff --git a/shared/src/i18n/ca/collab.ts b/shared/src/i18n/ca/collab.tsindex 55c36652f..8a4a117cc 100644--- a/shared/src/i18n/ca/collab.ts+++ b/shared/src/i18n/ca/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.countdownHoursMinutes': '{h}h {m}m restants','collab.polls.countdownMinutes': '{m}m restants','collab.polls.clearDeadline': 'Esborra la data límit',+ 'collab.chat.imageLimit': 'Pots adjuntar fins a {max} imatges per missatge',+ 'collab.chat.uploading': 'Pujant {percent} %',+ 'collab.chat.attachImages': 'Adjunta imatges',+ 'collab.chat.attachedImage': 'Imatge adjunta',+ 'collab.chat.closeImage': 'Tanca la imatge',};export default collab;diff --git a/shared/src/i18n/ca/docsync.ts b/shared/src/i18n/ca/docsync.tsindex 921d89ece..598fb9064 100644--- a/shared/src/i18n/ca/docsync.ts+++ b/shared/src/i18n/ca/docsync.ts@@ -179,6 +179,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Aquest proveïdor no està disponible en aquesta instància.','docsync.error.provider_disabled': 'En pausa: un administrador ha desactivat aquest proveïdor. La sincronització es reprèn quan es torni a activar.',+ 'docsync.binding.reconnect': 'Torna a connectar',};export default docsync;diff --git a/shared/src/i18n/ca/map.ts b/shared/src/i18n/ca/map.tsindex a5ec3b491..741598ca0 100644--- a/shared/src/i18n/ca/map.ts+++ b/shared/src/i18n/ca/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Amaga tot el viatge','map.overview.total': 'Distància total','map.attribution': 'Crèdits del mapa',+ 'map.overview.unrouted': 'No s’han pogut calcular {count} tram(s), per això les distàncies són incompletes.',+ 'map.overview.dayUnrouted': 'No s’han pogut calcular {count} tram(s) d’aquest dia',};export default map;diff --git a/shared/src/i18n/ca/mobileTrip.ts b/shared/src/i18n/ca/mobileTrip.tsindex c156ddf71..9c451825d 100644--- a/shared/src/i18n/ca/mobileTrip.ts+++ b/shared/src/i18n/ca/mobileTrip.ts@@ -70,6 +70,8 @@ const mobileTrip: TranslationStrings = {'mobileTrip.rtTruncated.one': '1 tram tenia més del que cap en una resposta. Tria menys tipus per veure la resta.','mobileTrip.rtTruncated.other':'{count} trams tenien més del que cap en una resposta. Tria menys tipus per veure la resta.',+ 'mobileTrip.rtNoDay': 'Cap dia seleccionat',+ 'mobileTrip.rtNoDayHint': 'El mapa mostra tot el viatge. Toca un dia a dalt per veure’n el trajecte.',};export default mobileTrip;diff --git a/shared/src/i18n/ca/roadtrip.ts b/shared/src/i18n/ca/roadtrip.tsindex b66999305..aebd4b320 100644--- a/shared/src/i18n/ca/roadtrip.ts+++ b/shared/src/i18n/ca/roadtrip.ts@@ -268,5 +268,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Sense peatges','roadtrip.alt.noFerry': 'Sense ferri','roadtrip.summary.partial': 'Encara s’està calculant la resta del trajecte',+ 'roadtrip.stay.releaseTitle': 'Treure la pernoctació?',+ 'roadtrip.stay.releaseBody': 'Es traurà la nit a «{name}». La parada es manté a la ruta com a pausa.',+ 'roadtrip.stay.releaseBookedBody': 'Es traurà la nit a «{name}» juntament amb la reserva «{booking}» i qualsevol despesa vinculada. La parada es manté a la ruta com a pausa.',+ 'roadtrip.stay.releaseAction': 'Converteix en pausa',};export default roadtrip;diff --git a/shared/src/i18n/ca/trip.ts b/shared/src/i18n/ca/trip.tsindex e521ba59a..e70656cc0 100644--- a/shared/src/i18n/ca/trip.ts+++ b/shared/src/i18n/ca/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'trip.loadingSteps.road': 'Sortint de camí...','trip.loadingSteps.arrive': 'Gairebé hi som...','trip.toast.tripUpdated': 'Viatge actualitzat',+ 'trip.confirm.deletePlaceNight': 'La nit reservada a «{name}» es perd amb el lloc.',+ 'trip.confirm.deletePlaceBooked': 'La nit reservada a «{name}» es perd amb el lloc, juntament amb la reserva «{booking}» i qualsevol despesa vinculada.',};export default trip;diff --git a/shared/src/i18n/cs/admin.ts b/shared/src/i18n/cs/admin.tsindex 2e0389a3e..f45a1a4eb 100644--- a/shared/src/i18n/cs/admin.ts+++ b/shared/src/i18n/cs/admin.ts@@ -793,5 +793,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'K čemu se klíč používá','admin.mapsKeyHintShort': 'Přidá fotky, hodnocení a otevírací dobu. Každý dotaz pak jde na Google.','admin.amapKeyHintShort': 'Pro vyhledávání míst v pevninské Číně. Potřebuje klíč webové služby, ne klíč JS API.',+ 'admin.collab.links.subtitle': 'Sdílené odkazy a záložky',};export default admin;diff --git a/shared/src/i18n/cs/collab.ts b/shared/src/i18n/cs/collab.tsindex 9122cd561..a77dd7ecc 100644--- a/shared/src/i18n/cs/collab.ts+++ b/shared/src/i18n/cs/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Možnosti','collab.polls.delete': 'Smazat','collab.polls.closedSection': 'Uzavřené',+ 'collab.chat.imageLimit': 'K jedné zprávě můžete připojit nejvýše {max} obrázků',+ 'collab.chat.uploading': 'Nahrávání {percent} %',+ 'collab.chat.attachImages': 'Připojit obrázky',+ 'collab.chat.attachedImage': 'Připojený obrázek',+ 'collab.chat.closeImage': 'Zavřít obrázek',};export default collab;diff --git a/shared/src/i18n/cs/docsync.ts b/shared/src/i18n/cs/docsync.tsindex 9b2deabcb..004101c3b 100644--- a/shared/src/i18n/cs/docsync.ts+++ b/shared/src/i18n/cs/docsync.ts@@ -174,6 +174,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Tento poskytovatel není na této instanci dostupný.','docsync.error.provider_disabled': 'Pozastaveno: správce tohoto poskytovatele vypnul. Synchronizace bude pokračovat, jakmile ho znovu zapne.',+ 'docsync.binding.reconnect': 'Znovu připojit',};export default docsync;diff --git a/shared/src/i18n/cs/map.ts b/shared/src/i18n/cs/map.tsindex 4d834319e..fb0f5e6b5 100644--- a/shared/src/i18n/cs/map.ts+++ b/shared/src/i18n/cs/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Skrýt celou cestu','map.overview.total': 'Celková vzdálenost','map.attribution': 'Zdroje mapy',+ 'map.overview.unrouted': '{count} úsek(ů) se nepodařilo spočítat, vzdálenosti jsou neúplné.',+ 'map.overview.dayUnrouted': '{count} úsek(ů) tohoto dne se nepodařilo spočítat',};export default map;diff --git a/shared/src/i18n/cs/mobileTrip.ts b/shared/src/i18n/cs/mobileTrip.tsindex da78552fe..9c4386583 100644--- a/shared/src/i18n/cs/mobileTrip.ts+++ b/shared/src/i18n/cs/mobileTrip.ts@@ -70,5 +70,7 @@ const mobileTrip: TranslationStrings = {'1 úsek měl víc, než se vejde do jedné odpovědi. Vyberte méně druhů, ať uvidíte zbytek.','mobileTrip.rtTruncated.other':'Úseky, kde bylo víc, než se vejde do jedné odpovědi: {count}. Vyberte méně druhů, ať uvidíte zbytek.',+ 'mobileTrip.rtNoDay': 'Není vybrán žádný den',+ 'mobileTrip.rtNoDayHint': 'Mapa zobrazuje celou cestu. Klepněte nahoře na den a zobrazí se jeho trasa.',};export default mobileTrip;diff --git a/shared/src/i18n/cs/roadtrip.ts b/shared/src/i18n/cs/roadtrip.tsindex fbe521635..3f442361f 100644--- a/shared/src/i18n/cs/roadtrip.ts+++ b/shared/src/i18n/cs/roadtrip.ts@@ -263,5 +263,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Bez mytneho','roadtrip.alt.noFerry': 'Bez trajektu','roadtrip.summary.partial': 'Zbytek trasy se ještě počítá',+ 'roadtrip.stay.releaseTitle': 'Zrušit přenocování?',+ 'roadtrip.stay.releaseBody': 'Noc v „{name}“ bude odstraněna. Zastávka zůstane na trase jako pauza.',+ 'roadtrip.stay.releaseBookedBody': 'Noc v „{name}“ bude odstraněna spolu s rezervací „{booking}“ a všemi navázanými výdaji. Zastávka zůstane na trase jako pauza.',+ 'roadtrip.stay.releaseAction': 'Změnit na pauzu',};export default roadtrip;diff --git a/shared/src/i18n/cs/trip.ts b/shared/src/i18n/cs/trip.tsindex a7131943a..431802fc9 100644--- a/shared/src/i18n/cs/trip.ts+++ b/shared/src/i18n/cs/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Přestupy','transit.walkLabel': 'Chůze','transit.searchHint': 'Vyhledejte reálná spojení a přidejte je rovnou do dne — data přes Transitous.',+ 'trip.confirm.deletePlaceNight': 'Noc rezervovaná v „{name}“ zmizí spolu s místem.',+ 'trip.confirm.deletePlaceBooked': 'Noc rezervovaná v „{name}“ zmizí spolu s místem, včetně rezervace „{booking}“ a všech navázaných výdajů.',};export default trip;diff --git a/shared/src/i18n/de/admin.ts b/shared/src/i18n/de/admin.tsindex a34267e23..e2cb027d8 100644--- a/shared/src/i18n/de/admin.ts+++ b/shared/src/i18n/de/admin.ts@@ -807,5 +807,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Wofür der Schlüssel benutzt wird','admin.mapsKeyHintShort': 'Ergänzt Fotos, Bewertungen und Öffnungszeiten. Jede Abfrage geht dann an Google.','admin.amapKeyHintShort': 'Für die Ortssuche in Festlandchina. Braucht einen Web-Service-Schlüssel, keinen JS-API-Schlüssel.',+ 'admin.collab.links.subtitle': 'Geteilte Links und Lesezeichen',};export default admin;diff --git a/shared/src/i18n/de/collab.ts b/shared/src/i18n/de/collab.tsindex 503cf2d90..c86fb542d 100644--- a/shared/src/i18n/de/collab.ts+++ b/shared/src/i18n/de/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Optionen','collab.polls.delete': 'Löschen','collab.polls.closedSection': 'Geschlossen',+ 'collab.chat.imageLimit': 'Pro Nachricht kannst du bis zu {max} Bilder anhängen',+ 'collab.chat.uploading': 'Wird hochgeladen, {percent} %',+ 'collab.chat.attachImages': 'Bilder anhängen',+ 'collab.chat.attachedImage': 'Angehängtes Bild',+ 'collab.chat.closeImage': 'Bild schließen',};export default collab;diff --git a/shared/src/i18n/de/docsync.ts b/shared/src/i18n/de/docsync.tsindex 797b0a0a9..dd2419520 100644--- a/shared/src/i18n/de/docsync.ts+++ b/shared/src/i18n/de/docsync.ts@@ -179,6 +179,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Dieser Anbieter steht auf dieser Instanz nicht zur Verfügung.','docsync.error.provider_disabled': 'Pausiert: Ein Administrator hat diesen Anbieter abgeschaltet. Der Abgleich läuft weiter, sobald er wieder eingeschaltet ist.',+ 'docsync.binding.reconnect': 'Neu verbinden',};export default docsync;diff --git a/shared/src/i18n/de/map.ts b/shared/src/i18n/de/map.tsindex baa750e0a..b7d57b732 100644--- a/shared/src/i18n/de/map.ts+++ b/shared/src/i18n/de/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Ganze Reise ausblenden','map.overview.total': 'Gesamtstrecke','map.attribution': 'Kartenquellen',+ 'map.overview.unrouted': '{count} Etappe(n) konnten nicht berechnet werden, die Entfernungen sind unvollständig.',+ 'map.overview.dayUnrouted': '{count} Etappe(n) dieses Tages konnten nicht berechnet werden',};export default map;diff --git a/shared/src/i18n/de/mobileTrip.ts b/shared/src/i18n/de/mobileTrip.tsindex 8a6e6ce28..274a2a4f2 100644--- a/shared/src/i18n/de/mobileTrip.ts+++ b/shared/src/i18n/de/mobileTrip.ts@@ -70,5 +70,7 @@ const mobileTrip: TranslationStrings = {'1 Abschnitt hatte mehr, als in eine Antwort passt. Wähl weniger Arten, um den Rest zu sehen.','mobileTrip.rtTruncated.other':'{count} Abschnitte hatten mehr, als in eine Antwort passt. Wähl weniger Arten, um den Rest zu sehen.',+ 'mobileTrip.rtNoDay': 'Kein Tag gewählt',+ 'mobileTrip.rtNoDayHint': 'Die Karte zeigt die ganze Reise. Tippe oben auf einen Tag, um seine Fahrt zu sehen.',};export default mobileTrip;diff --git a/shared/src/i18n/de/roadtrip.ts b/shared/src/i18n/de/roadtrip.tsindex ac4bcf476..f64530bc6 100644--- a/shared/src/i18n/de/roadtrip.ts+++ b/shared/src/i18n/de/roadtrip.ts@@ -262,5 +262,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Ohne Maut','roadtrip.alt.noFerry': 'Ohne Fähre','roadtrip.summary.partial': 'Der Rest der Strecke wird noch berechnet',+ 'roadtrip.stay.releaseTitle': 'Übernachtung aufheben?',+ 'roadtrip.stay.releaseBody': 'Die Nacht in „{name}“ wird entfernt. Der Stopp bleibt als Pause auf der Fahrt.',+ 'roadtrip.stay.releaseBookedBody': 'Die Nacht in „{name}“ wird zusammen mit der Buchung „{booking}“ und jeder damit verknüpften Ausgabe entfernt. Der Stopp bleibt als Pause auf der Fahrt.',+ 'roadtrip.stay.releaseAction': 'Als Pause behalten',};export default roadtrip;diff --git a/shared/src/i18n/de/trip.ts b/shared/src/i18n/de/trip.tsindex 6c851bf1e..fe876de1f 100644--- a/shared/src/i18n/de/trip.ts+++ b/shared/src/i18n/de/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Umstiege','transit.walkLabel': 'Fußweg','transit.searchHint': 'Echte Verbindungen suchen und direkt zum Tag hinzufügen — Daten via Transitous.',+ 'trip.confirm.deletePlaceNight': 'Die in „{name}“ gebuchte Nacht geht mit dem Ort verloren.',+ 'trip.confirm.deletePlaceBooked': 'Die in „{name}“ gebuchte Nacht geht mit dem Ort verloren, zusammen mit der Buchung „{booking}“ und jeder damit verknüpften Ausgabe.',};export default trip;diff --git a/shared/src/i18n/en/admin.ts b/shared/src/i18n/en/admin.tsindex 857994d11..3f5907373 100644--- a/shared/src/i18n/en/admin.ts+++ b/shared/src/i18n/en/admin.ts@@ -782,5 +782,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'What the key is used for','admin.mapsKeyHintShort': 'Adds photos, ratings and opening hours. Every lookup then goes to Google.','admin.amapKeyHintShort': 'For place search inside mainland China. Needs a web service key, not a JS API key.',+ 'admin.collab.links.subtitle': 'Shared links and bookmarks',};export default admin;diff --git a/shared/src/i18n/en/collab.ts b/shared/src/i18n/en/collab.tsindex 9d7c82f08..7e52cd538 100644--- a/shared/src/i18n/en/collab.ts+++ b/shared/src/i18n/en/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Options','collab.polls.delete': 'Delete','collab.polls.closedSection': 'Closed',+ 'collab.chat.imageLimit': 'You can attach up to {max} images per message',+ 'collab.chat.uploading': 'Uploading {percent}%',+ 'collab.chat.attachImages': 'Attach images',+ 'collab.chat.attachedImage': 'Attached image',+ 'collab.chat.closeImage': 'Close image',};export default collab;diff --git a/shared/src/i18n/en/docsync.ts b/shared/src/i18n/en/docsync.tsindex 1dc661173..89eb50780 100644--- a/shared/src/i18n/en/docsync.ts+++ b/shared/src/i18n/en/docsync.ts@@ -175,6 +175,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'This provider is not available on this instance.','docsync.error.provider_disabled': 'Paused: an administrator has switched this provider off. Syncing resumes once it is back on.',+ 'docsync.binding.reconnect': 'Reconnect',};export default docsync;diff --git a/shared/src/i18n/en/map.ts b/shared/src/i18n/en/map.tsindex 26f01b3ad..3a7612d69 100644--- a/shared/src/i18n/en/map.ts+++ b/shared/src/i18n/en/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Hide whole trip','map.overview.total': 'Total distance','map.attribution': 'Map credits',+ 'map.overview.unrouted': '{count} leg(s) could not be routed, so the distances are incomplete.',+ 'map.overview.dayUnrouted': '{count} leg(s) of this day could not be routed',};export default map;diff --git a/shared/src/i18n/en/mobileTrip.ts b/shared/src/i18n/en/mobileTrip.tsindex d5f91ae10..4f93273a6 100644--- a/shared/src/i18n/en/mobileTrip.ts+++ b/shared/src/i18n/en/mobileTrip.ts@@ -68,5 +68,7 @@ const mobileTrip: TranslationStrings = {'mobileTrip.rtTruncated.one': '1 stretch had more than fits in one answer. Pick fewer kinds to see the rest.','mobileTrip.rtTruncated.other':'{count} stretches had more than fits in one answer. Pick fewer kinds to see the rest.',+ 'mobileTrip.rtNoDay': 'No day picked',+ 'mobileTrip.rtNoDayHint': 'The map is showing the whole trip. Tap a day above to see its drive.',};export default mobileTrip;diff --git a/shared/src/i18n/en/roadtrip.ts b/shared/src/i18n/en/roadtrip.tsindex 96e8a355f..c3f028809 100644--- a/shared/src/i18n/en/roadtrip.ts+++ b/shared/src/i18n/en/roadtrip.ts@@ -260,5 +260,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'No tolls','roadtrip.alt.noFerry': 'No ferry','roadtrip.summary.partial': 'Still working out the rest of the drive',+ 'roadtrip.stay.releaseTitle': 'Drop the overnight stay?',+ 'roadtrip.stay.releaseBody': 'The night at “{name}” will be removed. The stop stays on the drive as a pause.',+ 'roadtrip.stay.releaseBookedBody': 'The night at “{name}” will be removed together with the booking “{booking}” and any expense linked to it. The stop stays on the drive as a pause.',+ 'roadtrip.stay.releaseAction': 'Make it a pause',};export default roadtrip;diff --git a/shared/src/i18n/en/trip.ts b/shared/src/i18n/en/trip.tsindex de458bbf4..7d137b450 100644--- a/shared/src/i18n/en/trip.ts+++ b/shared/src/i18n/en/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Transfers','transit.walkLabel': 'Walking','transit.searchHint': 'Search real connections and add them straight to the day — data via Transitous.',+ 'trip.confirm.deletePlaceNight': 'The night booked at “{name}” goes with the place.',+ 'trip.confirm.deletePlaceBooked': 'The night booked at “{name}” goes with the place, together with the booking “{booking}” and any expense linked to it.',};export default trip;diff --git a/shared/src/i18n/es/admin.ts b/shared/src/i18n/es/admin.tsindex 14aee177a..dcda22477 100644--- a/shared/src/i18n/es/admin.ts+++ b/shared/src/i18n/es/admin.ts@@ -817,5 +817,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Para qué se usa la clave','admin.mapsKeyHintShort': 'Añade fotos, valoraciones y horarios. Cada consulta pasa entonces por Google.','admin.amapKeyHintShort': 'Para la búsqueda de lugares en China continental. Necesita una clave de servicio web, no de API JS.',+ 'admin.collab.links.subtitle': 'Enlaces compartidos y marcadores',};export default admin;diff --git a/shared/src/i18n/es/collab.ts b/shared/src/i18n/es/collab.tsindex f4ee0657e..13d0343ab 100644--- a/shared/src/i18n/es/collab.ts+++ b/shared/src/i18n/es/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Opciones','collab.polls.delete': 'Eliminar','collab.polls.closedSection': 'Cerradas',+ 'collab.chat.imageLimit': 'Puedes adjuntar hasta {max} imágenes por mensaje',+ 'collab.chat.uploading': 'Subiendo {percent} %',+ 'collab.chat.attachImages': 'Adjuntar imágenes',+ 'collab.chat.attachedImage': 'Imagen adjunta',+ 'collab.chat.closeImage': 'Cerrar imagen',};export default collab;diff --git a/shared/src/i18n/es/docsync.ts b/shared/src/i18n/es/docsync.tsindex 44fa1412c..c356c2ed6 100644--- a/shared/src/i18n/es/docsync.ts+++ b/shared/src/i18n/es/docsync.ts@@ -179,6 +179,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Este proveedor no está disponible en esta instancia.','docsync.error.provider_disabled': 'En pausa: un administrador ha desactivado este proveedor. La sincronización se reanuda en cuanto vuelva a activarse.',+ 'docsync.binding.reconnect': 'Volver a conectar',};export default docsync;diff --git a/shared/src/i18n/es/map.ts b/shared/src/i18n/es/map.tsindex 13dbf234d..d54e61d7c 100644--- a/shared/src/i18n/es/map.ts+++ b/shared/src/i18n/es/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Ocultar todo el viaje','map.overview.total': 'Distancia total','map.attribution': 'Créditos del mapa',+ 'map.overview.unrouted': 'No se pudieron calcular {count} tramo(s), así que las distancias están incompletas.',+ 'map.overview.dayUnrouted': 'No se pudieron calcular {count} tramo(s) de este día',};export default map;diff --git a/shared/src/i18n/es/mobileTrip.ts b/shared/src/i18n/es/mobileTrip.tsindex f5513f10b..1e12d38d6 100644--- a/shared/src/i18n/es/mobileTrip.ts+++ b/shared/src/i18n/es/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'1 tramo tenía más de lo que cabe en una respuesta. Elige menos tipos para ver el resto.','mobileTrip.rtTruncated.other':'{count} tramos tenían más de lo que cabe en una respuesta. Elige menos tipos para ver el resto.',+ 'mobileTrip.rtNoDay': 'Ningún día seleccionado',+ 'mobileTrip.rtNoDayHint': 'El mapa muestra todo el viaje. Toca un día arriba para ver su ruta.',};export default mobileTrip;diff --git a/shared/src/i18n/es/roadtrip.ts b/shared/src/i18n/es/roadtrip.tsindex 3cc9eb990..7be1d83b2 100644--- a/shared/src/i18n/es/roadtrip.ts+++ b/shared/src/i18n/es/roadtrip.ts@@ -267,5 +267,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Sin peajes','roadtrip.alt.noFerry': 'Sin ferri','roadtrip.summary.partial': 'Aún se está calculando el resto del trayecto',+ 'roadtrip.stay.releaseTitle': '¿Quitar la pernoctación?',+ 'roadtrip.stay.releaseBody': 'Se quitará la noche en «{name}». La parada se mantiene en la ruta como pausa.',+ 'roadtrip.stay.releaseBookedBody': 'Se quitará la noche en «{name}» junto con la reserva «{booking}» y cualquier gasto vinculado. La parada se mantiene en la ruta como pausa.',+ 'roadtrip.stay.releaseAction': 'Convertir en pausa',};export default roadtrip;diff --git a/shared/src/i18n/es/trip.ts b/shared/src/i18n/es/trip.tsindex 6ae8c10bf..c158090ff 100644--- a/shared/src/i18n/es/trip.ts+++ b/shared/src/i18n/es/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Transbordos','transit.walkLabel': 'A pie','transit.searchHint': 'Busca conexiones reales y añádelas directamente al día — datos vía Transitous.',+ 'trip.confirm.deletePlaceNight': 'La noche reservada en «{name}» se pierde con el lugar.',+ 'trip.confirm.deletePlaceBooked': 'La noche reservada en «{name}» se pierde con el lugar, junto con la reserva «{booking}» y cualquier gasto vinculado.',};export default trip;diff --git a/shared/src/i18n/fr/admin.ts b/shared/src/i18n/fr/admin.tsindex 1265eaa4a..495c03e67 100644--- a/shared/src/i18n/fr/admin.ts+++ b/shared/src/i18n/fr/admin.ts@@ -815,5 +815,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'À quoi sert la clé','admin.mapsKeyHintShort': 'Ajoute photos, avis et horaires. Chaque recherche passe alors par Google.','admin.amapKeyHintShort': 'Pour la recherche de lieux en Chine continentale. Nécessite une clé de service web, pas une clé API JS.',+ 'admin.collab.links.subtitle': 'Liens partagés et favoris',};export default admin;diff --git a/shared/src/i18n/fr/collab.ts b/shared/src/i18n/fr/collab.tsindex fdc7b6776..04312f926 100644--- a/shared/src/i18n/fr/collab.ts+++ b/shared/src/i18n/fr/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Options','collab.polls.delete': 'Supprimer','collab.polls.closedSection': 'Fermés',+ 'collab.chat.imageLimit': 'Vous pouvez joindre jusqu’à {max} images par message',+ 'collab.chat.uploading': 'Envoi {percent} %',+ 'collab.chat.attachImages': 'Joindre des images',+ 'collab.chat.attachedImage': 'Image jointe',+ 'collab.chat.closeImage': 'Fermer l’image',};export default collab;diff --git a/shared/src/i18n/fr/docsync.ts b/shared/src/i18n/fr/docsync.tsindex 7aca1725b..decc3f896 100644--- a/shared/src/i18n/fr/docsync.ts+++ b/shared/src/i18n/fr/docsync.ts@@ -181,6 +181,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Ce fournisseur n’est pas disponible sur cette instance.','docsync.error.provider_disabled': 'En pause : un administrateur a désactivé ce fournisseur. La synchronisation reprendra dès qu’il sera réactivé.',+ 'docsync.binding.reconnect': 'Reconnecter',};export default docsync;diff --git a/shared/src/i18n/fr/map.ts b/shared/src/i18n/fr/map.tsindex 5b0093622..10883dab5 100644--- a/shared/src/i18n/fr/map.ts+++ b/shared/src/i18n/fr/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Masquer tout le voyage','map.overview.total': 'Distance totale','map.attribution': 'Crédits de la carte',+ 'map.overview.unrouted': '{count} étape(s) n’ont pas pu être calculées, les distances sont incomplètes.',+ 'map.overview.dayUnrouted': '{count} étape(s) de cette journée n’ont pas pu être calculées',};export default map;diff --git a/shared/src/i18n/fr/mobileTrip.ts b/shared/src/i18n/fr/mobileTrip.tsindex 3672402a6..5b8eed2c1 100644--- a/shared/src/i18n/fr/mobileTrip.ts+++ b/shared/src/i18n/fr/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'1 tronçon avait plus que ce qui tient dans une réponse. Choisissez moins de types pour voir le reste.','mobileTrip.rtTruncated.other':'{count} tronçons avaient plus que ce qui tient dans une réponse. Choisissez moins de types pour voir le reste.',+ 'mobileTrip.rtNoDay': 'Aucun jour sélectionné',+ 'mobileTrip.rtNoDayHint': 'La carte affiche tout le voyage. Touchez un jour ci-dessus pour voir son trajet.',};export default mobileTrip;diff --git a/shared/src/i18n/fr/roadtrip.ts b/shared/src/i18n/fr/roadtrip.tsindex 4d37912b7..7ef4eeebd 100644--- a/shared/src/i18n/fr/roadtrip.ts+++ b/shared/src/i18n/fr/roadtrip.ts@@ -267,5 +267,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Sans peage','roadtrip.alt.noFerry': 'Sans ferry','roadtrip.summary.partial': 'Le reste du trajet est encore en cours de calcul',+ 'roadtrip.stay.releaseTitle': 'Supprimer la nuitée ?',+ 'roadtrip.stay.releaseBody': 'La nuit à « {name} » sera supprimée. L’arrêt reste sur le trajet comme pause.',+ 'roadtrip.stay.releaseBookedBody': 'La nuit à « {name} » sera supprimée avec la réservation « {booking} » et toute dépense qui y est liée. L’arrêt reste sur le trajet comme pause.',+ 'roadtrip.stay.releaseAction': 'En faire une pause',};export default roadtrip;diff --git a/shared/src/i18n/fr/trip.ts b/shared/src/i18n/fr/trip.tsindex f3e7d4c0b..2a4420e0f 100644--- a/shared/src/i18n/fr/trip.ts+++ b/shared/src/i18n/fr/trip.ts@@ -89,5 +89,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Correspondances','transit.walkLabel': 'Marche','transit.searchHint': 'Recherchez de vraies liaisons et ajoutez-les directement au jour — données via Transitous.',+ 'trip.confirm.deletePlaceNight': 'La nuit réservée à « {name} » disparaît avec le lieu.',+ 'trip.confirm.deletePlaceBooked': 'La nuit réservée à « {name} » disparaît avec le lieu, ainsi que la réservation « {booking} » et toute dépense qui y est liée.',};export default trip;diff --git a/shared/src/i18n/gr/admin.ts b/shared/src/i18n/gr/admin.tsindex 78f6e58b7..abbd2d089 100644--- a/shared/src/i18n/gr/admin.ts+++ b/shared/src/i18n/gr/admin.ts@@ -823,5 +823,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Σε τι χρησιμοποιείται το κλειδί','admin.mapsKeyHintShort': 'Προσθέτει φωτογραφίες, βαθμολογίες και ώρες λειτουργίας. Κάθε αναζήτηση πηγαίνει τότε στη Google.','admin.amapKeyHintShort': 'Για αναζήτηση τόπων στην ηπειρωτική Κίνα. Χρειάζεται κλειδί web service, όχι JS API.',+ 'admin.collab.links.subtitle': 'Κοινόχρηστοι σύνδεσμοι και σελιδοδείκτες',};export default admin;diff --git a/shared/src/i18n/gr/collab.ts b/shared/src/i18n/gr/collab.tsindex 7eb0300b0..2fb4ba5a1 100644--- a/shared/src/i18n/gr/collab.ts+++ b/shared/src/i18n/gr/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Επιλογές','collab.polls.delete': 'Διαγραφή','collab.polls.closedSection': 'Κλειστές',+ 'collab.chat.imageLimit': 'Μπορείτε να επισυνάψετε έως {max} εικόνες ανά μήνυμα',+ 'collab.chat.uploading': 'Μεταφόρτωση {percent}%',+ 'collab.chat.attachImages': 'Επισύναψη εικόνων',+ 'collab.chat.attachedImage': 'Συνημμένη εικόνα',+ 'collab.chat.closeImage': 'Κλείσιμο εικόνας',};export default collab;diff --git a/shared/src/i18n/gr/docsync.ts b/shared/src/i18n/gr/docsync.tsindex e211101af..d1c9a9e86 100644--- a/shared/src/i18n/gr/docsync.ts+++ b/shared/src/i18n/gr/docsync.ts@@ -182,6 +182,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Αυτός ο πάροχος δεν είναι διαθέσιμος σε αυτή την εγκατάσταση.','docsync.error.provider_disabled': 'Σε παύση: ένας διαχειριστής απενεργοποίησε αυτόν τον πάροχο. Ο συγχρονισμός θα συνεχιστεί μόλις ενεργοποιηθεί ξανά.',+ 'docsync.binding.reconnect': 'Επανασύνδεση',};export default docsync;diff --git a/shared/src/i18n/gr/map.ts b/shared/src/i18n/gr/map.tsindex 463bbc831..820b01925 100644--- a/shared/src/i18n/gr/map.ts+++ b/shared/src/i18n/gr/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Απόκρυψη όλου του ταξιδιού','map.overview.total': 'Συνολική απόσταση','map.attribution': 'Πηγές χάρτη',+ 'map.overview.unrouted': '{count} σκέλος/η δεν μπόρεσαν να υπολογιστούν, οι αποστάσεις είναι ελλιπείς.',+ 'map.overview.dayUnrouted': '{count} σκέλος/η αυτής της ημέρας δεν μπόρεσαν να υπολογιστούν',};export default map;diff --git a/shared/src/i18n/gr/mobileTrip.ts b/shared/src/i18n/gr/mobileTrip.tsindex c0bf509a0..922f9fe9e 100644--- a/shared/src/i18n/gr/mobileTrip.ts+++ b/shared/src/i18n/gr/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'1 τμήμα είχε περισσότερα από όσα χωρούν σε μία απάντηση. Διαλέξτε λιγότερα είδη για να δείτε τα υπόλοιπα.','mobileTrip.rtTruncated.other':'{count} τμήματα είχαν περισσότερα από όσα χωρούν σε μία απάντηση. Διαλέξτε λιγότερα είδη για να δείτε τα υπόλοιπα.',+ 'mobileTrip.rtNoDay': 'Δεν επιλέχθηκε ημέρα',+ 'mobileTrip.rtNoDayHint': 'Ο χάρτης δείχνει ολόκληρο το ταξίδι. Πατήστε μια ημέρα παραπάνω για τη διαδρομή της.',};export default mobileTrip;diff --git a/shared/src/i18n/gr/roadtrip.ts b/shared/src/i18n/gr/roadtrip.tsindex e4959968a..f49df7d5c 100644--- a/shared/src/i18n/gr/roadtrip.ts+++ b/shared/src/i18n/gr/roadtrip.ts@@ -269,5 +269,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Χωρις διοδια','roadtrip.alt.noFerry': 'Χωρίς φέρι','roadtrip.summary.partial': 'Υπολογίζεται ακόμη η υπόλοιπη διαδρομή',+ 'roadtrip.stay.releaseTitle': 'Να αφαιρεθεί η διανυκτέρευση;',+ 'roadtrip.stay.releaseBody': 'Η διανυκτέρευση στο «{name}» θα αφαιρεθεί. Η στάση παραμένει στη διαδρομή ως παύση.',+ 'roadtrip.stay.releaseBookedBody': 'Η διανυκτέρευση στο «{name}» θα αφαιρεθεί μαζί με την κράτηση «{booking}» και κάθε συνδεδεμένο έξοδο. Η στάση παραμένει στη διαδρομή ως παύση.',+ 'roadtrip.stay.releaseAction': 'Κάνε το παύση',};export default roadtrip;diff --git a/shared/src/i18n/gr/trip.ts b/shared/src/i18n/gr/trip.tsindex 4c74bec7c..6069ea0d4 100644--- a/shared/src/i18n/gr/trip.ts+++ b/shared/src/i18n/gr/trip.ts@@ -90,5 +90,7 @@ const trip: TranslationStrings = {'transit.walkLabel': 'Περπάτημα','transit.searchHint':'Αναζητήστε πραγματικές συνδέσεις και προσθέστε τις απευθείας στην ημέρα — δεδομένα μέσω Transitous.',+ 'trip.confirm.deletePlaceNight': 'Η διανυκτέρευση που κρατήθηκε στο «{name}» χάνεται μαζί με το μέρος.',+ 'trip.confirm.deletePlaceBooked': 'Η διανυκτέρευση που κρατήθηκε στο «{name}» χάνεται μαζί με το μέρος, μαζί με την κράτηση «{booking}» και κάθε συνδεδεμένο έξοδο.',};export default trip;diff --git a/shared/src/i18n/hu/admin.ts b/shared/src/i18n/hu/admin.tsindex 485a97c23..45d7a02d0 100644--- a/shared/src/i18n/hu/admin.ts+++ b/shared/src/i18n/hu/admin.ts@@ -815,5 +815,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Mire használjuk a kulcsot','admin.mapsKeyHintShort': 'Fényképeket, értékeléseket és nyitvatartást ad hozzá. Minden lekérdezés a Google-höz megy.','admin.amapKeyHintShort': 'Helykereséshez a szárazföldi Kínában. Webszolgáltatás-kulcs kell, nem JS API-kulcs.',+ 'admin.collab.links.subtitle': 'Megosztott linkek és könyvjelzők',};export default admin;diff --git a/shared/src/i18n/hu/collab.ts b/shared/src/i18n/hu/collab.tsindex b31eba80c..07cb30a96 100644--- a/shared/src/i18n/hu/collab.ts+++ b/shared/src/i18n/hu/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Opciók','collab.polls.delete': 'Törlés','collab.polls.closedSection': 'Lezárva',+ 'collab.chat.imageLimit': 'Üzenetenként legfeljebb {max} képet csatolhatsz',+ 'collab.chat.uploading': 'Feltöltés {percent}%',+ 'collab.chat.attachImages': 'Képek csatolása',+ 'collab.chat.attachedImage': 'Csatolt kép',+ 'collab.chat.closeImage': 'Kép bezárása',};export default collab;diff --git a/shared/src/i18n/hu/docsync.ts b/shared/src/i18n/hu/docsync.tsindex 6e409d47a..417d7bf0d 100644--- a/shared/src/i18n/hu/docsync.ts+++ b/shared/src/i18n/hu/docsync.ts@@ -180,6 +180,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Ez a szolgáltató nem érhető el ezen a példányon.','docsync.error.provider_disabled': 'Szüneteltetve: egy rendszergazda kikapcsolta ezt a szolgáltatót. A szinkronizálás folytatódik, amint újra bekapcsolják.',+ 'docsync.binding.reconnect': 'Újracsatlakozás',};export default docsync;diff --git a/shared/src/i18n/hu/map.ts b/shared/src/i18n/hu/map.tsindex a44d5185b..9c4320e5f 100644--- a/shared/src/i18n/hu/map.ts+++ b/shared/src/i18n/hu/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Teljes utazás elrejtése','map.overview.total': 'Teljes távolság','map.attribution': 'Térkép forrásai',+ 'map.overview.unrouted': '{count} szakaszt nem sikerült kiszámítani, a távolságok hiányosak.',+ 'map.overview.dayUnrouted': 'Ennek a napnak {count} szakaszát nem sikerült kiszámítani',};export default map;diff --git a/shared/src/i18n/hu/mobileTrip.ts b/shared/src/i18n/hu/mobileTrip.tsindex daa2f7652..a2850371e 100644--- a/shared/src/i18n/hu/mobileTrip.ts+++ b/shared/src/i18n/hu/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'1 szakaszon több volt, mint ami egy válaszba fér. Válassz kevesebb fajtát, hogy lásd a többit.','mobileTrip.rtTruncated.other':'{count} szakaszon több volt, mint ami egy válaszba fér. Válassz kevesebb fajtát, hogy lásd a többit.',+ 'mobileTrip.rtNoDay': 'Nincs kiválasztott nap',+ 'mobileTrip.rtNoDayHint': 'A térkép a teljes utat mutatja. Koppints fent egy napra a napi útvonalhoz.',};export default mobileTrip;diff --git a/shared/src/i18n/hu/roadtrip.ts b/shared/src/i18n/hu/roadtrip.tsindex 07c4ad42b..efd692224 100644--- a/shared/src/i18n/hu/roadtrip.ts+++ b/shared/src/i18n/hu/roadtrip.ts@@ -264,5 +264,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Dijmentes','roadtrip.alt.noFerry': 'Komp nélkül','roadtrip.summary.partial': 'A hátralévő útszakasz számítása még folyamatban',+ 'roadtrip.stay.releaseTitle': 'Elveted az éjszakázást?',+ 'roadtrip.stay.releaseBody': 'A(z) „{name}” helyen töltött éjszaka törlődik. A megálló szünetként az útvonalon marad.',+ 'roadtrip.stay.releaseBookedBody': 'A(z) „{name}” helyen töltött éjszaka a(z) „{booking}” foglalással és a hozzá kapcsolt kiadásokkal együtt törlődik. A megálló szünetként az útvonalon marad.',+ 'roadtrip.stay.releaseAction': 'Legyen szünet',};export default roadtrip;diff --git a/shared/src/i18n/hu/trip.ts b/shared/src/i18n/hu/trip.tsindex fb7722a0a..3991d6409 100644--- a/shared/src/i18n/hu/trip.ts+++ b/shared/src/i18n/hu/trip.ts@@ -90,5 +90,7 @@ const trip: TranslationStrings = {'transit.walkLabel': 'Gyaloglás','transit.searchHint':'Keress valós összeköttetéseket, és add hozzá őket közvetlenül a naphoz – adatok a Transitous révén.',+ 'trip.confirm.deletePlaceNight': 'A(z) „{name}” helyre foglalt éjszaka a hellyel együtt törlődik.',+ 'trip.confirm.deletePlaceBooked': 'A(z) „{name}” helyre foglalt éjszaka a hellyel együtt törlődik, a(z) „{booking}” foglalással és a hozzá kapcsolt kiadásokkal.',};export default trip;diff --git a/shared/src/i18n/id/admin.ts b/shared/src/i18n/id/admin.tsindex a27ea6f03..7b67a18f9 100644--- a/shared/src/i18n/id/admin.ts+++ b/shared/src/i18n/id/admin.ts@@ -809,5 +809,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Untuk apa kunci ini dipakai','admin.mapsKeyHintShort': 'Menambahkan foto, penilaian, dan jam buka. Setiap pencarian lalu ke Google.','admin.amapKeyHintShort': 'Untuk pencarian tempat di Tiongkok daratan. Perlu kunci layanan web, bukan kunci JS API.',+ 'admin.collab.links.subtitle': 'Tautan bersama dan penanda',};export default admin;diff --git a/shared/src/i18n/id/collab.ts b/shared/src/i18n/id/collab.tsindex 908b2389c..1f15afc33 100644--- a/shared/src/i18n/id/collab.ts+++ b/shared/src/i18n/id/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Pilihan','collab.polls.delete': 'Hapus','collab.polls.closedSection': 'Ditutup',+ 'collab.chat.imageLimit': 'Anda dapat melampirkan hingga {max} gambar per pesan',+ 'collab.chat.uploading': 'Mengunggah {percent}%',+ 'collab.chat.attachImages': 'Lampirkan gambar',+ 'collab.chat.attachedImage': 'Gambar terlampir',+ 'collab.chat.closeImage': 'Tutup gambar',};export default collab;diff --git a/shared/src/i18n/id/docsync.ts b/shared/src/i18n/id/docsync.tsindex b478d9397..9bc96f74d 100644--- a/shared/src/i18n/id/docsync.ts+++ b/shared/src/i18n/id/docsync.ts@@ -179,6 +179,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Penyedia ini tidak tersedia di instans ini.','docsync.error.provider_disabled': 'Dijeda: administrator menonaktifkan penyedia ini. Sinkronisasi berlanjut setelah penyedia diaktifkan kembali.',+ 'docsync.binding.reconnect': 'Hubungkan ulang',};export default docsync;diff --git a/shared/src/i18n/id/map.ts b/shared/src/i18n/id/map.tsindex 885b8decb..60fb1eff4 100644--- a/shared/src/i18n/id/map.ts+++ b/shared/src/i18n/id/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Sembunyikan seluruh perjalanan','map.overview.total': 'Jarak total','map.attribution': 'Kredit peta',+ 'map.overview.unrouted': '{count} ruas tidak dapat dihitung, jadi jaraknya belum lengkap.',+ 'map.overview.dayUnrouted': '{count} ruas pada hari ini tidak dapat dihitung',};export default map;diff --git a/shared/src/i18n/id/mobileTrip.ts b/shared/src/i18n/id/mobileTrip.tsindex 28424694e..e0ea095da 100644--- a/shared/src/i18n/id/mobileTrip.ts+++ b/shared/src/i18n/id/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'1 ruas punya lebih banyak daripada yang muat dalam satu jawaban. Pilih lebih sedikit jenis untuk melihat sisanya.','mobileTrip.rtTruncated.other':'{count} ruas punya lebih banyak daripada yang muat dalam satu jawaban. Pilih lebih sedikit jenis untuk melihat sisanya.',+ 'mobileTrip.rtNoDay': 'Belum ada hari yang dipilih',+ 'mobileTrip.rtNoDayHint': 'Peta menampilkan seluruh perjalanan. Ketuk hari di atas untuk melihat rutenya.',};export default mobileTrip;diff --git a/shared/src/i18n/id/roadtrip.ts b/shared/src/i18n/id/roadtrip.tsindex 598ab0bff..6374679e8 100644--- a/shared/src/i18n/id/roadtrip.ts+++ b/shared/src/i18n/id/roadtrip.ts@@ -267,5 +267,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Tanpa tol','roadtrip.alt.noFerry': 'Tanpa feri','roadtrip.summary.partial': 'Sisa perjalanan masih dihitung',+ 'roadtrip.stay.releaseTitle': 'Hapus menginap semalam?',+ 'roadtrip.stay.releaseBody': 'Malam di “{name}” akan dihapus. Perhentian tetap ada di perjalanan sebagai jeda.',+ 'roadtrip.stay.releaseBookedBody': 'Malam di “{name}” akan dihapus bersama pemesanan “{booking}” dan pengeluaran yang terkait. Perhentian tetap ada di perjalanan sebagai jeda.',+ 'roadtrip.stay.releaseAction': 'Jadikan jeda',};export default roadtrip;diff --git a/shared/src/i18n/id/trip.ts b/shared/src/i18n/id/trip.tsindex 0bffcaeb5..c8468cc75 100644--- a/shared/src/i18n/id/trip.ts+++ b/shared/src/i18n/id/trip.ts@@ -89,5 +89,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Transit','transit.walkLabel': 'Jalan kaki','transit.searchHint': 'Cari koneksi nyata dan tambahkan langsung ke hari itu — data melalui Transitous.',+ 'trip.confirm.deletePlaceNight': 'Malam yang dipesan di “{name}” ikut hilang bersama tempat ini.',+ 'trip.confirm.deletePlaceBooked': 'Malam yang dipesan di “{name}” ikut hilang bersama tempat ini, beserta pemesanan “{booking}” dan pengeluaran yang terkait.',};export default trip;diff --git a/shared/src/i18n/it/admin.ts b/shared/src/i18n/it/admin.tsindex 7163602d0..a2b7dbea6 100644--- a/shared/src/i18n/it/admin.ts+++ b/shared/src/i18n/it/admin.ts@@ -810,5 +810,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'A cosa serve la chiave','admin.mapsKeyHintShort': 'Aggiunge foto, valutazioni e orari. Ogni ricerca passa allora da Google.','admin.amapKeyHintShort': 'Per la ricerca di luoghi nella Cina continentale. Richiede una chiave web service, non una chiave API JS.',+ 'admin.collab.links.subtitle': 'Link condivisi e segnalibri',};export default admin;diff --git a/shared/src/i18n/it/collab.ts b/shared/src/i18n/it/collab.tsindex 26e94fe2f..0bf2c0d92 100644--- a/shared/src/i18n/it/collab.ts+++ b/shared/src/i18n/it/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Opzioni','collab.polls.delete': 'Elimina','collab.polls.closedSection': 'Chiusi',+ 'collab.chat.imageLimit': 'Puoi allegare fino a {max} immagini per messaggio',+ 'collab.chat.uploading': 'Caricamento {percent}%',+ 'collab.chat.attachImages': 'Allega immagini',+ 'collab.chat.attachedImage': 'Immagine allegata',+ 'collab.chat.closeImage': 'Chiudi immagine',};export default collab;diff --git a/shared/src/i18n/it/docsync.ts b/shared/src/i18n/it/docsync.tsindex a442f60cc..83fe92f3f 100644--- a/shared/src/i18n/it/docsync.ts+++ b/shared/src/i18n/it/docsync.ts@@ -179,6 +179,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Questo provider non è disponibile su questa istanza.','docsync.error.provider_disabled': 'In pausa: un amministratore ha disattivato questo provider. La sincronizzazione riprende appena viene riattivato.',+ 'docsync.binding.reconnect': 'Riconnetti',};export default docsync;diff --git a/shared/src/i18n/it/map.ts b/shared/src/i18n/it/map.tsindex eed483926..ac5b58c08 100644--- a/shared/src/i18n/it/map.ts+++ b/shared/src/i18n/it/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Nascondi tutto il viaggio','map.overview.total': 'Distanza totale','map.attribution': 'Crediti della mappa',+ 'map.overview.unrouted': '{count} tratta/e non calcolabile/i, le distanze sono incomplete.',+ 'map.overview.dayUnrouted': '{count} tratta/e di questo giorno non calcolabile/i',};export default map;diff --git a/shared/src/i18n/it/mobileTrip.ts b/shared/src/i18n/it/mobileTrip.tsindex 54236308b..296e6fad1 100644--- a/shared/src/i18n/it/mobileTrip.ts+++ b/shared/src/i18n/it/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'1 tratto aveva più di quanto stia in una risposta. Scegli meno tipi per vedere il resto.','mobileTrip.rtTruncated.other':'{count} tratti avevano più di quanto stia in una risposta. Scegli meno tipi per vedere il resto.',+ 'mobileTrip.rtNoDay': 'Nessun giorno selezionato',+ 'mobileTrip.rtNoDayHint': 'La mappa mostra l’intero viaggio. Tocca un giorno qui sopra per vederne il percorso.',};export default mobileTrip;diff --git a/shared/src/i18n/it/roadtrip.ts b/shared/src/i18n/it/roadtrip.tsindex 4012694eb..dd62d23e5 100644--- a/shared/src/i18n/it/roadtrip.ts+++ b/shared/src/i18n/it/roadtrip.ts@@ -267,5 +267,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Senza pedaggi','roadtrip.alt.noFerry': 'Senza traghetto','roadtrip.summary.partial': 'Il resto del percorso è ancora in calcolo',+ 'roadtrip.stay.releaseTitle': 'Rimuovere il pernottamento?',+ 'roadtrip.stay.releaseBody': 'La notte a «{name}» verrà rimossa. La tappa resta sul percorso come pausa.',+ 'roadtrip.stay.releaseBookedBody': 'La notte a «{name}» verrà rimossa insieme alla prenotazione «{booking}» e a ogni spesa collegata. La tappa resta sul percorso come pausa.',+ 'roadtrip.stay.releaseAction': 'Rendi una pausa',};export default roadtrip;diff --git a/shared/src/i18n/it/trip.ts b/shared/src/i18n/it/trip.tsindex c387edb1e..674edcdcf 100644--- a/shared/src/i18n/it/trip.ts+++ b/shared/src/i18n/it/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Cambi','transit.walkLabel': 'A piedi','transit.searchHint': 'Cerca collegamenti reali e aggiungili direttamente alla giornata — dati via Transitous.',+ 'trip.confirm.deletePlaceNight': 'La notte prenotata a «{name}» va via con il luogo.',+ 'trip.confirm.deletePlaceBooked': 'La notte prenotata a «{name}» va via con il luogo, insieme alla prenotazione «{booking}» e a ogni spesa collegata.',};export default trip;diff --git a/shared/src/i18n/ja/admin.ts b/shared/src/i18n/ja/admin.tsindex 4686cd054..0788a23e2 100644--- a/shared/src/i18n/ja/admin.ts+++ b/shared/src/i18n/ja/admin.ts@@ -772,5 +772,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'キーの使いみち','admin.mapsKeyHintShort': '写真・評価・営業時間が加わります。以降の検索はすべて Google に送られます。','admin.amapKeyHintShort': '中国本土での地点検索用。JS API キーではなく Web サービスキーが必要です。',+ 'admin.collab.links.subtitle': '共有リンクとブックマーク',};export default admin;diff --git a/shared/src/i18n/ja/collab.ts b/shared/src/i18n/ja/collab.tsindex bc410289a..fadbec1f9 100644--- a/shared/src/i18n/ja/collab.ts+++ b/shared/src/i18n/ja/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': '選択肢','collab.polls.delete': '削除','collab.polls.closedSection': '終了',+ 'collab.chat.imageLimit': '1件のメッセージに添付できる画像は{max}枚までです',+ 'collab.chat.uploading': 'アップロード中 {percent}%',+ 'collab.chat.attachImages': '画像を添付',+ 'collab.chat.attachedImage': '添付画像',+ 'collab.chat.closeImage': '画像を閉じる',};export default collab;diff --git a/shared/src/i18n/ja/docsync.ts b/shared/src/i18n/ja/docsync.tsindex 568e0026e..e1002da71 100644--- a/shared/src/i18n/ja/docsync.ts+++ b/shared/src/i18n/ja/docsync.ts@@ -173,6 +173,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'この連携先はこのインスタンスでは利用できません。','docsync.error.provider_disabled': '一時停止中:管理者がこの連携先を無効にしました。再び有効になると同期が再開されます。',+ 'docsync.binding.reconnect': '再接続',};export default docsync;diff --git a/shared/src/i18n/ja/map.ts b/shared/src/i18n/ja/map.tsindex a4ee235d6..3ae0a5752 100644--- a/shared/src/i18n/ja/map.ts+++ b/shared/src/i18n/ja/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': '旅程全体を非表示','map.overview.total': '合計距離','map.attribution': '地図のクレジット',+ 'map.overview.unrouted': '{count}区間のルートを計算できなかったため、距離は不完全です。',+ 'map.overview.dayUnrouted': 'この日の{count}区間のルートを計算できませんでした',};export default map;diff --git a/shared/src/i18n/ja/mobileTrip.ts b/shared/src/i18n/ja/mobileTrip.tsindex 452299269..c31b01562 100644--- a/shared/src/i18n/ja/mobileTrip.ts+++ b/shared/src/i18n/ja/mobileTrip.ts@@ -66,5 +66,7 @@ const mobileTrip: TranslationStrings = {'mobileTrip.rtNoneOnStage': 'この区間沿いにはそうした場所はありません。','mobileTrip.rtTruncated.one': '1 区間は1回の答えに収まりきりませんでした。種類を減らすと残りも見られます。','mobileTrip.rtTruncated.other': '{count} 区間は1回の答えに収まりきりませんでした。種類を減らすと残りも見られます。',+ 'mobileTrip.rtNoDay': '日が選択されていません',+ 'mobileTrip.rtNoDayHint': '地図には旅程全体が表示されています。上の日をタップするとその日の行程が見られます。',};export default mobileTrip;diff --git a/shared/src/i18n/ja/roadtrip.ts b/shared/src/i18n/ja/roadtrip.tsindex cd5efebea..3199e8256 100644--- a/shared/src/i18n/ja/roadtrip.ts+++ b/shared/src/i18n/ja/roadtrip.ts@@ -262,5 +262,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': '有料道路なし','roadtrip.alt.noFerry': 'フェリーなし','roadtrip.summary.partial': '残りの行程を計算しています',+ 'roadtrip.stay.releaseTitle': '宿泊を取り消しますか?',+ 'roadtrip.stay.releaseBody': '「{name}」での宿泊を取り消します。停車地は休憩として行程に残ります。',+ 'roadtrip.stay.releaseBookedBody': '「{name}」での宿泊を、予約「{booking}」と関連する支出とともに取り消します。停車地は休憩として行程に残ります。',+ 'roadtrip.stay.releaseAction': '休憩にする',};export default roadtrip;diff --git a/shared/src/i18n/ja/trip.ts b/shared/src/i18n/ja/trip.tsindex c30584a26..80e6e78b2 100644--- a/shared/src/i18n/ja/trip.ts+++ b/shared/src/i18n/ja/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': '乗り換え','transit.walkLabel': '徒歩','transit.searchHint': '実際の経路を検索して、そのまま日程に追加できます — データは Transitous 提供。',+ 'trip.confirm.deletePlaceNight': '「{name}」で予約した宿泊も場所と一緒に削除されます。',+ 'trip.confirm.deletePlaceBooked': '「{name}」で予約した宿泊も場所と一緒に削除され、予約「{booking}」と関連する支出も失われます。',};export default trip;diff --git a/shared/src/i18n/ko/admin.ts b/shared/src/i18n/ko/admin.tsindex 0670da5d3..9adba5abc 100644--- a/shared/src/i18n/ko/admin.ts+++ b/shared/src/i18n/ko/admin.ts@@ -769,5 +769,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': '키를 사용하는 곳','admin.mapsKeyHintShort': '사진, 평점, 영업시간이 추가됩니다. 이후 모든 조회는 Google로 갑니다.','admin.amapKeyHintShort': '중국 본토에서의 장소 검색용. JS API 키가 아니라 웹 서비스 키가 필요합니다.',+ 'admin.collab.links.subtitle': '공유 링크와 북마크',};export default admin;diff --git a/shared/src/i18n/ko/collab.ts b/shared/src/i18n/ko/collab.tsindex fe2d9279e..96839286d 100644--- a/shared/src/i18n/ko/collab.ts+++ b/shared/src/i18n/ko/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': '옵션','collab.polls.delete': '삭제','collab.polls.closedSection': '종료됨',+ 'collab.chat.imageLimit': '메시지당 최대 {max}장의 이미지를 첨부할 수 있습니다',+ 'collab.chat.uploading': '업로드 중 {percent}%',+ 'collab.chat.attachImages': '이미지 첨부',+ 'collab.chat.attachedImage': '첨부된 이미지',+ 'collab.chat.closeImage': '이미지 닫기',};export default collab;diff --git a/shared/src/i18n/ko/docsync.ts b/shared/src/i18n/ko/docsync.tsindex 3a9ab3653..49a5b7355 100644--- a/shared/src/i18n/ko/docsync.ts+++ b/shared/src/i18n/ko/docsync.ts@@ -172,6 +172,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': '이 저장소는 이 인스턴스에서 사용할 수 없습니다.','docsync.error.provider_disabled': '일시 중지됨: 관리자가 이 저장소를 껐습니다. 다시 켜지면 동기화가 재개됩니다.',+ 'docsync.binding.reconnect': '다시 연결',};export default docsync;diff --git a/shared/src/i18n/ko/map.ts b/shared/src/i18n/ko/map.tsindex 585b5d433..0f06e3c7b 100644--- a/shared/src/i18n/ko/map.ts+++ b/shared/src/i18n/ko/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': '전체 여행 숨기기','map.overview.total': '총 거리','map.attribution': '지도 출처',+ 'map.overview.unrouted': '{count}개 구간의 경로를 계산할 수 없어 거리가 불완전합니다.',+ 'map.overview.dayUnrouted': '이 날의 {count}개 구간 경로를 계산할 수 없습니다',};export default map;diff --git a/shared/src/i18n/ko/mobileTrip.ts b/shared/src/i18n/ko/mobileTrip.tsindex 5ab402a2f..b45f6724e 100644--- a/shared/src/i18n/ko/mobileTrip.ts+++ b/shared/src/i18n/ko/mobileTrip.ts@@ -67,5 +67,7 @@ const mobileTrip: TranslationStrings = {'mobileTrip.rtTruncated.one': '1개 구간은 한 번의 답에 담기지 않았습니다. 종류를 줄이면 나머지도 볼 수 있습니다.','mobileTrip.rtTruncated.other':'{count}개 구간은 한 번의 답에 담기지 않았습니다. 종류를 줄이면 나머지도 볼 수 있습니다.',+ 'mobileTrip.rtNoDay': '선택된 날이 없습니다',+ 'mobileTrip.rtNoDayHint': '지도에 전체 여행이 표시됩니다. 위에서 날짜를 눌러 해당 일정을 확인하세요.',};export default mobileTrip;diff --git a/shared/src/i18n/ko/roadtrip.ts b/shared/src/i18n/ko/roadtrip.tsindex fa0c3c437..cf519ab56 100644--- a/shared/src/i18n/ko/roadtrip.ts+++ b/shared/src/i18n/ko/roadtrip.ts@@ -260,5 +260,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': '통행료 없음','roadtrip.alt.noFerry': '페리 없음','roadtrip.summary.partial': '남은 구간을 계산하고 있습니다',+ 'roadtrip.stay.releaseTitle': '숙박을 취소할까요?',+ 'roadtrip.stay.releaseBody': '“{name}”에서의 숙박이 삭제됩니다. 이 정차지는 휴식으로 경로에 남습니다.',+ 'roadtrip.stay.releaseBookedBody': '“{name}”에서의 숙박이 예약 “{booking}” 및 연결된 지출과 함께 삭제됩니다. 이 정차지는 휴식으로 경로에 남습니다.',+ 'roadtrip.stay.releaseAction': '휴식으로 바꾸기',};export default roadtrip;diff --git a/shared/src/i18n/ko/trip.ts b/shared/src/i18n/ko/trip.tsindex e29db7c70..942133bdd 100644--- a/shared/src/i18n/ko/trip.ts+++ b/shared/src/i18n/ko/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': '환승','transit.walkLabel': '도보','transit.searchHint': '실제 연결편을 검색하고 바로 일정에 추가하세요 — 데이터 제공: Transitous.',+ 'trip.confirm.deletePlaceNight': '“{name}”에 예약된 숙박도 장소와 함께 삭제됩니다.',+ 'trip.confirm.deletePlaceBooked': '“{name}”에 예약된 숙박이 장소와 함께 삭제되며, 예약 “{booking}” 및 연결된 지출도 함께 삭제됩니다.',};export default trip;diff --git a/shared/src/i18n/nl/admin.ts b/shared/src/i18n/nl/admin.tsindex 962f6a972..fa5e9e40a 100644--- a/shared/src/i18n/nl/admin.ts+++ b/shared/src/i18n/nl/admin.ts@@ -806,5 +806,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Waar de sleutel voor wordt gebruikt','admin.mapsKeyHintShort': 'Voegt foto\'s, beoordelingen en openingstijden toe. Elke opzoeking gaat dan naar Google.','admin.amapKeyHintShort': 'Voor plaatszoeken in het vasteland van China. Vereist een webservicesleutel, geen JS-API-sleutel.',+ 'admin.collab.links.subtitle': 'Gedeelde links en bladwijzers',};export default admin;diff --git a/shared/src/i18n/nl/collab.ts b/shared/src/i18n/nl/collab.tsindex 37fa70836..3567ced61 100644--- a/shared/src/i18n/nl/collab.ts+++ b/shared/src/i18n/nl/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Opties','collab.polls.delete': 'Verwijderen','collab.polls.closedSection': 'Gesloten',+ 'collab.chat.imageLimit': 'Je kunt maximaal {max} afbeeldingen per bericht toevoegen',+ 'collab.chat.uploading': 'Uploaden {percent}%',+ 'collab.chat.attachImages': 'Afbeeldingen toevoegen',+ 'collab.chat.attachedImage': 'Bijgevoegde afbeelding',+ 'collab.chat.closeImage': 'Afbeelding sluiten',};export default collab;diff --git a/shared/src/i18n/nl/docsync.ts b/shared/src/i18n/nl/docsync.tsindex 9c5f6069b..6e4f9f124 100644--- a/shared/src/i18n/nl/docsync.ts+++ b/shared/src/i18n/nl/docsync.ts@@ -176,6 +176,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Deze aanbieder is niet beschikbaar op deze instantie.','docsync.error.provider_disabled': 'Gepauzeerd: een beheerder heeft deze aanbieder uitgeschakeld. De synchronisatie gaat verder zodra hij weer aanstaat.',+ 'docsync.binding.reconnect': 'Opnieuw verbinden',};export default docsync;diff --git a/shared/src/i18n/nl/map.ts b/shared/src/i18n/nl/map.tsindex 021eb524d..1b6832fb2 100644--- a/shared/src/i18n/nl/map.ts+++ b/shared/src/i18n/nl/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Hele reis verbergen','map.overview.total': 'Totale afstand','map.attribution': 'Kaartvermeldingen',+ 'map.overview.unrouted': '{count} etappe(s) konden niet worden berekend, de afstanden zijn onvolledig.',+ 'map.overview.dayUnrouted': '{count} etappe(s) van deze dag konden niet worden berekend',};export default map;diff --git a/shared/src/i18n/nl/mobileTrip.ts b/shared/src/i18n/nl/mobileTrip.tsindex f68d85c68..0b07c179b 100644--- a/shared/src/i18n/nl/mobileTrip.ts+++ b/shared/src/i18n/nl/mobileTrip.ts@@ -68,5 +68,7 @@ const mobileTrip: TranslationStrings = {'mobileTrip.rtTruncated.one': '1 stuk had meer dan in één antwoord past. Kies minder soorten om de rest te zien.','mobileTrip.rtTruncated.other':'{count} stukken hadden meer dan in één antwoord past. Kies minder soorten om de rest te zien.',+ 'mobileTrip.rtNoDay': 'Geen dag gekozen',+ 'mobileTrip.rtNoDayHint': 'De kaart toont de hele reis. Tik hierboven op een dag om de rit te zien.',};export default mobileTrip;diff --git a/shared/src/i18n/nl/roadtrip.ts b/shared/src/i18n/nl/roadtrip.tsindex 2e125090b..29d57ad42 100644--- a/shared/src/i18n/nl/roadtrip.ts+++ b/shared/src/i18n/nl/roadtrip.ts@@ -266,5 +266,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Zonder tol','roadtrip.alt.noFerry': 'Zonder veerboot','roadtrip.summary.partial': 'De rest van de rit wordt nog berekend',+ 'roadtrip.stay.releaseTitle': 'Overnachting laten vervallen?',+ 'roadtrip.stay.releaseBody': 'De nacht bij ‘{name}’ wordt verwijderd. De stop blijft als pauze op de route.',+ 'roadtrip.stay.releaseBookedBody': 'De nacht bij ‘{name}’ wordt verwijderd, samen met de boeking ‘{booking}’ en elke gekoppelde uitgave. De stop blijft als pauze op de route.',+ 'roadtrip.stay.releaseAction': 'Maak er een pauze van',};export default roadtrip;diff --git a/shared/src/i18n/nl/trip.ts b/shared/src/i18n/nl/trip.tsindex 96268a1f6..cb71c8735 100644--- a/shared/src/i18n/nl/trip.ts+++ b/shared/src/i18n/nl/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Overstappen','transit.walkLabel': 'Lopen','transit.searchHint': 'Zoek echte verbindingen en voeg ze direct toe aan de dag — gegevens via Transitous.',+ 'trip.confirm.deletePlaceNight': 'De nacht geboekt bij ‘{name}’ verdwijnt met de plek.',+ 'trip.confirm.deletePlaceBooked': 'De nacht geboekt bij ‘{name}’ verdwijnt met de plek, samen met de boeking ‘{booking}’ en elke gekoppelde uitgave.',};export default trip;diff --git a/shared/src/i18n/pl/admin.ts b/shared/src/i18n/pl/admin.tsindex 487096fff..3bb2e7a57 100644--- a/shared/src/i18n/pl/admin.ts+++ b/shared/src/i18n/pl/admin.ts@@ -815,5 +815,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Do czego służy klucz','admin.mapsKeyHintShort': 'Dodaje zdjęcia, oceny i godziny otwarcia. Każde zapytanie trafia wtedy do Google.','admin.amapKeyHintShort': 'Do wyszukiwania miejsc w Chinach kontynentalnych. Wymaga klucza usługi webowej, nie klucza JS API.',+ 'admin.collab.links.subtitle': 'Udostępnione linki i zakładki',};export default admin;diff --git a/shared/src/i18n/pl/collab.ts b/shared/src/i18n/pl/collab.tsindex 36abbc523..f605554bd 100644--- a/shared/src/i18n/pl/collab.ts+++ b/shared/src/i18n/pl/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.delete': 'Usuń','collab.polls.closedSection': 'Zamknięte','collab.chat.reply': 'Odpowiedz',+ 'collab.chat.imageLimit': 'Do jednej wiadomości możesz dołączyć maksymalnie {max} obrazów',+ 'collab.chat.uploading': 'Przesyłanie {percent}%',+ 'collab.chat.attachImages': 'Dołącz obrazy',+ 'collab.chat.attachedImage': 'Załączony obraz',+ 'collab.chat.closeImage': 'Zamknij obraz',};export default collab;diff --git a/shared/src/i18n/pl/docsync.ts b/shared/src/i18n/pl/docsync.tsindex 48d3ea770..180236aa4 100644--- a/shared/src/i18n/pl/docsync.ts+++ b/shared/src/i18n/pl/docsync.ts@@ -178,6 +178,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Ten dostawca nie jest dostępny na tej instancji.','docsync.error.provider_disabled': 'Wstrzymane: administrator wyłączył tego dostawcę. Synchronizacja zostanie wznowiona, gdy znów go włączy.',+ 'docsync.binding.reconnect': 'Połącz ponownie',};export default docsync;diff --git a/shared/src/i18n/pl/map.ts b/shared/src/i18n/pl/map.tsindex 4f1619a46..6a944356c 100644--- a/shared/src/i18n/pl/map.ts+++ b/shared/src/i18n/pl/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Ukryj całą podróż','map.overview.total': 'Łączny dystans','map.attribution': 'Źródła mapy',+ 'map.overview.unrouted': 'Nie udało się wyznaczyć {count} odcinka/odcinków, więc odległości są niepełne.',+ 'map.overview.dayUnrouted': 'Nie udało się wyznaczyć {count} odcinka/odcinków tego dnia',};export default map;diff --git a/shared/src/i18n/pl/mobileTrip.ts b/shared/src/i18n/pl/mobileTrip.tsindex 102d9beff..875ae4651 100644--- a/shared/src/i18n/pl/mobileTrip.ts+++ b/shared/src/i18n/pl/mobileTrip.ts@@ -70,5 +70,7 @@ const mobileTrip: TranslationStrings = {'1 odcinek miał więcej, niż mieści się w jednej odpowiedzi. Wybierz mniej rodzajów, by zobaczyć resztę.','mobileTrip.rtTruncated.other':'Odcinki, na których było więcej, niż mieści się w jednej odpowiedzi: {count}. Wybierz mniej rodzajów, by zobaczyć resztę.',+ 'mobileTrip.rtNoDay': 'Nie wybrano dnia',+ 'mobileTrip.rtNoDayHint': 'Mapa pokazuje całą podróż. Dotknij dnia powyżej, aby zobaczyć jego trasę.',};export default mobileTrip;diff --git a/shared/src/i18n/pl/roadtrip.ts b/shared/src/i18n/pl/roadtrip.tsindex 75bd2002a..33503162d 100644--- a/shared/src/i18n/pl/roadtrip.ts+++ b/shared/src/i18n/pl/roadtrip.ts@@ -264,5 +264,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Bez oplat','roadtrip.alt.noFerry': 'Bez promu','roadtrip.summary.partial': 'Reszta trasy jest jeszcze obliczana',+ 'roadtrip.stay.releaseTitle': 'Usunąć nocleg?',+ 'roadtrip.stay.releaseBody': 'Nocleg w „{name}” zostanie usunięty. Przystanek pozostaje na trasie jako postój.',+ 'roadtrip.stay.releaseBookedBody': 'Nocleg w „{name}” zostanie usunięty razem z rezerwacją „{booking}” i powiązanymi wydatkami. Przystanek pozostaje na trasie jako postój.',+ 'roadtrip.stay.releaseAction': 'Zamień na postój',};export default roadtrip;diff --git a/shared/src/i18n/pl/trip.ts b/shared/src/i18n/pl/trip.tsindex 3e7fe6093..4410e93b6 100644--- a/shared/src/i18n/pl/trip.ts+++ b/shared/src/i18n/pl/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Przesiadki','transit.walkLabel': 'Pieszo','transit.searchHint': 'Wyszukaj prawdziwe połączenia i dodaj je od razu do dnia — dane z Transitous.',+ 'trip.confirm.deletePlaceNight': 'Nocleg zarezerwowany w „{name}” zniknie razem z miejscem.',+ 'trip.confirm.deletePlaceBooked': 'Nocleg zarezerwowany w „{name}” zniknie razem z miejscem, wraz z rezerwacją „{booking}” i powiązanymi wydatkami.',};export default trip;diff --git a/shared/src/i18n/ru/admin.ts b/shared/src/i18n/ru/admin.tsindex cd387ddba..50b9304cc 100644--- a/shared/src/i18n/ru/admin.ts+++ b/shared/src/i18n/ru/admin.ts@@ -808,5 +808,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Для чего используется ключ','admin.mapsKeyHintShort': 'Добавляет фото, оценки и часы работы. Каждый запрос тогда идёт в Google.','admin.amapKeyHintShort': 'Для поиска мест в материковом Китае. Нужен ключ веб-сервиса, а не ключ JS API.',+ 'admin.collab.links.subtitle': 'Общие ссылки и закладки',};export default admin;diff --git a/shared/src/i18n/ru/collab.ts b/shared/src/i18n/ru/collab.tsindex 6d261795b..41611e33d 100644--- a/shared/src/i18n/ru/collab.ts+++ b/shared/src/i18n/ru/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Варианты','collab.polls.delete': 'Удалить','collab.polls.closedSection': 'Закрытые',+ 'collab.chat.imageLimit': 'К одному сообщению можно прикрепить до {max} изображений',+ 'collab.chat.uploading': 'Загрузка {percent}%',+ 'collab.chat.attachImages': 'Прикрепить изображения',+ 'collab.chat.attachedImage': 'Прикреплённое изображение',+ 'collab.chat.closeImage': 'Закрыть изображение',};export default collab;diff --git a/shared/src/i18n/ru/docsync.ts b/shared/src/i18n/ru/docsync.tsindex 9f5e8d3d4..e1dcb289b 100644--- a/shared/src/i18n/ru/docsync.ts+++ b/shared/src/i18n/ru/docsync.ts@@ -179,6 +179,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Этот провайдер недоступен в этом экземпляре.','docsync.error.provider_disabled': 'Приостановлено: администратор отключил этого провайдера. Синхронизация возобновится, как только его снова включат.',+ 'docsync.binding.reconnect': 'Подключить заново',};export default docsync;diff --git a/shared/src/i18n/ru/map.ts b/shared/src/i18n/ru/map.tsindex 732143b2d..af1399212 100644--- a/shared/src/i18n/ru/map.ts+++ b/shared/src/i18n/ru/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Скрыть всю поездку','map.overview.total': 'Общее расстояние','map.attribution': 'Источники карты',+ 'map.overview.unrouted': 'Не удалось построить {count} участок(ов), поэтому расстояния неполные.',+ 'map.overview.dayUnrouted': 'Не удалось построить {count} участок(ов) этого дня',};export default map;diff --git a/shared/src/i18n/ru/mobileTrip.ts b/shared/src/i18n/ru/mobileTrip.tsindex daaf34c45..39366aab3 100644--- a/shared/src/i18n/ru/mobileTrip.ts+++ b/shared/src/i18n/ru/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'На 1 участке нашлось больше, чем помещается в один ответ. Выберите меньше видов, чтобы увидеть остальное.','mobileTrip.rtTruncated.other':'На {count} участках нашлось больше, чем помещается в один ответ. Выберите меньше видов, чтобы увидеть остальное.',+ 'mobileTrip.rtNoDay': 'День не выбран',+ 'mobileTrip.rtNoDayHint': 'На карте вся поездка. Нажмите на день выше, чтобы увидеть его маршрут.',};export default mobileTrip;diff --git a/shared/src/i18n/ru/roadtrip.ts b/shared/src/i18n/ru/roadtrip.tsindex e69bd4ab6..c5af9c272 100644--- a/shared/src/i18n/ru/roadtrip.ts+++ b/shared/src/i18n/ru/roadtrip.ts@@ -266,5 +266,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Без платных дорог','roadtrip.alt.noFerry': 'Без парома','roadtrip.summary.partial': 'Остальная часть маршрута ещё рассчитывается',+ 'roadtrip.stay.releaseTitle': 'Убрать ночёвку?',+ 'roadtrip.stay.releaseBody': 'Ночёвка в «{name}» будет удалена. Остановка останется на маршруте как пауза.',+ 'roadtrip.stay.releaseBookedBody': 'Ночёвка в «{name}» будет удалена вместе с бронированием «{booking}» и связанными с ним расходами. Остановка останется на маршруте как пауза.',+ 'roadtrip.stay.releaseAction': 'Сделать паузой',};export default roadtrip;diff --git a/shared/src/i18n/ru/trip.ts b/shared/src/i18n/ru/trip.tsindex d4af42394..deebcbb0b 100644--- a/shared/src/i18n/ru/trip.ts+++ b/shared/src/i18n/ru/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Пересадки','transit.walkLabel': 'Пешком','transit.searchHint': 'Ищите реальные маршруты и добавляйте их прямо в день — данные от Transitous.',+ 'trip.confirm.deletePlaceNight': 'Ночёвка, забронированная в «{name}», исчезнет вместе с местом.',+ 'trip.confirm.deletePlaceBooked': 'Ночёвка, забронированная в «{name}», исчезнет вместе с местом, а с ней бронирование «{booking}» и связанные расходы.',};export default trip;diff --git a/shared/src/i18n/sv/admin.ts b/shared/src/i18n/sv/admin.tsindex e5dae6795..7ed85bd3e 100644--- a/shared/src/i18n/sv/admin.ts+++ b/shared/src/i18n/sv/admin.ts@@ -809,5 +809,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Vad nyckeln används till','admin.mapsKeyHintShort': 'Lägger till foton, betyg och öppettider. Varje sökning går då till Google.','admin.amapKeyHintShort': 'För platssökning i Fastlandskina. Kräver en webbtjänstnyckel, inte en JS API-nyckel.',+ 'admin.collab.links.subtitle': 'Delade länkar och bokmärken',};export default admin;diff --git a/shared/src/i18n/sv/collab.ts b/shared/src/i18n/sv/collab.tsindex 570397814..676ca815a 100644--- a/shared/src/i18n/sv/collab.ts+++ b/shared/src/i18n/sv/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Val','collab.polls.delete': 'Ta bort','collab.polls.closedSection': 'Stängd',+ 'collab.chat.imageLimit': 'Du kan bifoga upp till {max} bilder per meddelande',+ 'collab.chat.uploading': 'Laddar upp {percent} %',+ 'collab.chat.attachImages': 'Bifoga bilder',+ 'collab.chat.attachedImage': 'Bifogad bild',+ 'collab.chat.closeImage': 'Stäng bild',};export default collab;diff --git a/shared/src/i18n/sv/docsync.ts b/shared/src/i18n/sv/docsync.tsindex 7b8541d44..f335582c2 100644--- a/shared/src/i18n/sv/docsync.ts+++ b/shared/src/i18n/sv/docsync.ts@@ -173,6 +173,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Den här leverantören är inte tillgänglig på den här instansen.','docsync.error.provider_disabled': 'Pausad: en administratör har stängt av den här leverantören. Synkroniseringen fortsätter när den slås på igen.',+ 'docsync.binding.reconnect': 'Anslut igen',};export default docsync;diff --git a/shared/src/i18n/sv/map.ts b/shared/src/i18n/sv/map.tsindex 6392be254..6a99addd4 100644--- a/shared/src/i18n/sv/map.ts+++ b/shared/src/i18n/sv/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Dölj hela resan','map.overview.total': 'Total sträcka','map.attribution': 'Kartkällor',+ 'map.overview.unrouted': '{count} delsträcka/or kunde inte beräknas, så avstånden är ofullständiga.',+ 'map.overview.dayUnrouted': '{count} delsträcka/or för den här dagen kunde inte beräknas',};export default map;diff --git a/shared/src/i18n/sv/mobileTrip.ts b/shared/src/i18n/sv/mobileTrip.tsindex d63bbf6aa..57528e21b 100644--- a/shared/src/i18n/sv/mobileTrip.ts+++ b/shared/src/i18n/sv/mobileTrip.ts@@ -69,5 +69,7 @@ const mobileTrip: TranslationStrings = {'1 sträcka hade mer än vad som får plats i ett svar. Välj färre sorter för att se resten.','mobileTrip.rtTruncated.other':'{count} sträckor hade mer än vad som får plats i ett svar. Välj färre sorter för att se resten.',+ 'mobileTrip.rtNoDay': 'Ingen dag vald',+ 'mobileTrip.rtNoDayHint': 'Kartan visar hela resan. Tryck på en dag ovanför för att se dess körning.',};export default mobileTrip;diff --git a/shared/src/i18n/sv/roadtrip.ts b/shared/src/i18n/sv/roadtrip.tsindex e0f9ba464..2c05d9463 100644--- a/shared/src/i18n/sv/roadtrip.ts+++ b/shared/src/i18n/sv/roadtrip.ts@@ -263,5 +263,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Utan vagavgifter','roadtrip.alt.noFerry': 'Utan färja','roadtrip.summary.partial': 'Resten av resan beräknas fortfarande',+ 'roadtrip.stay.releaseTitle': 'Ta bort övernattningen?',+ 'roadtrip.stay.releaseBody': 'Natten på ”{name}” tas bort. Stoppet ligger kvar på resan som en paus.',+ 'roadtrip.stay.releaseBookedBody': 'Natten på ”{name}” tas bort tillsammans med bokningen ”{booking}” och alla utgifter som hör till den. Stoppet ligger kvar på resan som en paus.',+ 'roadtrip.stay.releaseAction': 'Gör till en paus',};export default roadtrip;diff --git a/shared/src/i18n/sv/trip.ts b/shared/src/i18n/sv/trip.tsindex fdbe3a270..76fdc4c98 100644--- a/shared/src/i18n/sv/trip.ts+++ b/shared/src/i18n/sv/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Byten','transit.walkLabel': 'Gång','transit.searchHint': 'Sök verkliga förbindelser och lägg till dem direkt i dagen – data via Transitous.',+ 'trip.confirm.deletePlaceNight': 'Natten som är bokad på ”{name}” försvinner med platsen.',+ 'trip.confirm.deletePlaceBooked': 'Natten som är bokad på ”{name}” försvinner med platsen, tillsammans med bokningen ”{booking}” och alla utgifter som hör till den.',};export default trip;diff --git a/shared/src/i18n/tr/admin.ts b/shared/src/i18n/tr/admin.tsindex 614a3894c..ef76abe9b 100644--- a/shared/src/i18n/tr/admin.ts+++ b/shared/src/i18n/tr/admin.ts@@ -810,5 +810,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Anahtar ne için kullanılır','admin.mapsKeyHintShort': "Fotoğraf, puan ve çalışma saatleri ekler. Her sorgu bundan sonra Google'a gider.",'admin.amapKeyHintShort': 'Çin anakarasında yer araması için. JS API anahtarı değil, web servis anahtarı gerekir.',+ 'admin.collab.links.subtitle': 'Paylaşılan bağlantılar ve yer imleri',};export default admin;diff --git a/shared/src/i18n/tr/collab.ts b/shared/src/i18n/tr/collab.tsindex a6b9f0de2..569047ec9 100644--- a/shared/src/i18n/tr/collab.ts+++ b/shared/src/i18n/tr/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Seçenekler','collab.polls.delete': 'Sil','collab.polls.closedSection': 'Kapalı',+ 'collab.chat.imageLimit': 'Her mesaja en fazla {max} görsel ekleyebilirsiniz',+ 'collab.chat.uploading': 'Yükleniyor %{percent}',+ 'collab.chat.attachImages': 'Görsel ekle',+ 'collab.chat.attachedImage': 'Eklenen görsel',+ 'collab.chat.closeImage': 'Görseli kapat',};export default collab;diff --git a/shared/src/i18n/tr/docsync.ts b/shared/src/i18n/tr/docsync.tsindex 4166b3365..2c705d3b5 100644--- a/shared/src/i18n/tr/docsync.ts+++ b/shared/src/i18n/tr/docsync.ts@@ -177,6 +177,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Bu sağlayıcı bu kurulumda kullanılamıyor.','docsync.error.provider_disabled': 'Duraklatıldı: bir yönetici bu sağlayıcıyı kapattı. Yeniden açıldığında eşitleme kaldığı yerden devam eder.',+ 'docsync.binding.reconnect': 'Yeniden bağlan',};export default docsync;diff --git a/shared/src/i18n/tr/map.ts b/shared/src/i18n/tr/map.tsindex 74b7c22d2..46e8702ee 100644--- a/shared/src/i18n/tr/map.ts+++ b/shared/src/i18n/tr/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Tüm geziyi gizle','map.overview.total': 'Toplam mesafe','map.attribution': 'Harita kaynakları',+ 'map.overview.unrouted': '{count} etap hesaplanamadı, bu yüzden mesafeler eksik.',+ 'map.overview.dayUnrouted': 'Bu günün {count} etabı hesaplanamadı',};export default map;diff --git a/shared/src/i18n/tr/mobileTrip.ts b/shared/src/i18n/tr/mobileTrip.tsindex bb665e565..1fdc64efb 100644--- a/shared/src/i18n/tr/mobileTrip.ts+++ b/shared/src/i18n/tr/mobileTrip.ts@@ -69,5 +69,7 @@ const mobileTrip: TranslationStrings = {'1 kesimde tek bir yanıta sığandan fazlası vardı. Geri kalanı görmek için daha az tür seçin.','mobileTrip.rtTruncated.other':'{count} kesimde tek bir yanıta sığandan fazlası vardı. Geri kalanı görmek için daha az tür seçin.',+ 'mobileTrip.rtNoDay': 'Gün seçilmedi',+ 'mobileTrip.rtNoDayHint': 'Harita tüm yolculuğu gösteriyor. Günün sürüşünü görmek için yukarıdan bir güne dokunun.',};export default mobileTrip;diff --git a/shared/src/i18n/tr/roadtrip.ts b/shared/src/i18n/tr/roadtrip.tsindex c73713c6d..3100f0b7f 100644--- a/shared/src/i18n/tr/roadtrip.ts+++ b/shared/src/i18n/tr/roadtrip.ts@@ -266,5 +266,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Ucretsiz','roadtrip.alt.noFerry': 'Feribotsuz','roadtrip.summary.partial': 'Yolun geri kalanı hâlâ hesaplanıyor',+ 'roadtrip.stay.releaseTitle': 'Konaklama kaldırılsın mı?',+ 'roadtrip.stay.releaseBody': '“{name}” konumundaki gece kaldırılacak. Durak, yolculukta mola olarak kalır.',+ 'roadtrip.stay.releaseBookedBody': '“{name}” konumundaki gece, “{booking}” rezervasyonu ve ona bağlı tüm harcamalarla birlikte kaldırılacak. Durak, yolculukta mola olarak kalır.',+ 'roadtrip.stay.releaseAction': 'Molaya çevir',};export default roadtrip;diff --git a/shared/src/i18n/tr/trip.ts b/shared/src/i18n/tr/trip.tsindex 5ca806d1a..cfad4b639 100644--- a/shared/src/i18n/tr/trip.ts+++ b/shared/src/i18n/tr/trip.ts@@ -89,5 +89,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Aktarma','transit.walkLabel': 'Yürüyüş','transit.searchHint': 'Gerçek bağlantıları ara ve doğrudan güne ekle — veriler Transitous üzerinden.',+ 'trip.confirm.deletePlaceNight': '“{name}” için ayrılan gece yerle birlikte silinir.',+ 'trip.confirm.deletePlaceBooked': '“{name}” için ayrılan gece, “{booking}” rezervasyonu ve ona bağlı tüm harcamalarla birlikte yerle beraber silinir.',};export default trip;diff --git a/shared/src/i18n/uk/admin.ts b/shared/src/i18n/uk/admin.tsindex 810515091..e39577877 100644--- a/shared/src/i18n/uk/admin.ts+++ b/shared/src/i18n/uk/admin.ts@@ -805,5 +805,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Для чого використовується ключ','admin.mapsKeyHintShort': 'Додає фото, оцінки та години роботи. Кожен запит тоді йде до Google.','admin.amapKeyHintShort': 'Для пошуку місць у материковому Китаї. Потрібен ключ вебсервісу, а не ключ JS API.',+ 'admin.collab.links.subtitle': 'Спільні посилання та закладки',};export default admin;diff --git a/shared/src/i18n/uk/collab.ts b/shared/src/i18n/uk/collab.tsindex 3763095ff..f343ad14b 100644--- a/shared/src/i18n/uk/collab.ts+++ b/shared/src/i18n/uk/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Варіанти','collab.polls.delete': 'Видалити','collab.polls.closedSection': 'Закриті',+ 'collab.chat.imageLimit': 'До одного повідомлення можна додати до {max} зображень',+ 'collab.chat.uploading': 'Завантаження {percent}%',+ 'collab.chat.attachImages': 'Додати зображення',+ 'collab.chat.attachedImage': 'Додане зображення',+ 'collab.chat.closeImage': 'Закрити зображення',};export default collab;diff --git a/shared/src/i18n/uk/docsync.ts b/shared/src/i18n/uk/docsync.tsindex 7d27e03c0..f79b420d4 100644--- a/shared/src/i18n/uk/docsync.ts+++ b/shared/src/i18n/uk/docsync.ts@@ -177,6 +177,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Цей постачальник недоступний на цьому сервері.','docsync.error.provider_disabled': 'Призупинено: адміністратор вимкнув цього постачальника. Синхронізація відновиться, щойно його знову ввімкнуть.',+ 'docsync.binding.reconnect': 'Підключити знову',};export default docsync;diff --git a/shared/src/i18n/uk/map.ts b/shared/src/i18n/uk/map.tsindex fed8d2728..7bed81e37 100644--- a/shared/src/i18n/uk/map.ts+++ b/shared/src/i18n/uk/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Сховати всю подорож','map.overview.total': 'Загальна відстань','map.attribution': 'Джерела карти',+ 'map.overview.unrouted': 'Не вдалося прокласти {count} відрізок(ів), тому відстані неповні.',+ 'map.overview.dayUnrouted': 'Не вдалося прокласти {count} відрізок(ів) цього дня',};export default map;diff --git a/shared/src/i18n/uk/mobileTrip.ts b/shared/src/i18n/uk/mobileTrip.tsindex 85f95d6d8..289db9676 100644--- a/shared/src/i18n/uk/mobileTrip.ts+++ b/shared/src/i18n/uk/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'На 1 ділянці знайшлося більше, ніж уміщується в одну відповідь. Виберіть менше видів, щоб побачити решту.','mobileTrip.rtTruncated.other':'На {count} ділянках знайшлося більше, ніж уміщується в одну відповідь. Виберіть менше видів, щоб побачити решту.',+ 'mobileTrip.rtNoDay': 'День не вибрано',+ 'mobileTrip.rtNoDayHint': 'На мапі вся подорож. Торкніться дня вгорі, щоб побачити його маршрут.',};export default mobileTrip;diff --git a/shared/src/i18n/uk/roadtrip.ts b/shared/src/i18n/uk/roadtrip.tsindex 94db23627..b10dd4b16 100644--- a/shared/src/i18n/uk/roadtrip.ts+++ b/shared/src/i18n/uk/roadtrip.ts@@ -265,5 +265,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Без платних доріг','roadtrip.alt.noFerry': 'Без порома','roadtrip.summary.partial': 'Решта маршруту ще обчислюється',+ 'roadtrip.stay.releaseTitle': 'Прибрати ночівлю?',+ 'roadtrip.stay.releaseBody': 'Ночівлю в «{name}» буде вилучено. Зупинка залишиться на маршруті як пауза.',+ 'roadtrip.stay.releaseBookedBody': 'Ночівлю в «{name}» буде вилучено разом із бронюванням «{booking}» і пов’язаними витратами. Зупинка залишиться на маршруті як пауза.',+ 'roadtrip.stay.releaseAction': 'Зробити паузою',};export default roadtrip;diff --git a/shared/src/i18n/uk/trip.ts b/shared/src/i18n/uk/trip.tsindex 52056a901..8c0797a52 100644--- a/shared/src/i18n/uk/trip.ts+++ b/shared/src/i18n/uk/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Пересадки','transit.walkLabel': 'Пішки','transit.searchHint': 'Шукайте справжні маршрути та додавайте їх одразу до дня — дані від Transitous.',+ 'trip.confirm.deletePlaceNight': 'Ночівля, заброньована в «{name}», зникне разом із місцем.',+ 'trip.confirm.deletePlaceBooked': 'Ночівля, заброньована в «{name}», зникне разом із місцем, а з нею бронювання «{booking}» і пов’язані витрати.',};export default trip;diff --git a/shared/src/i18n/vi/admin.ts b/shared/src/i18n/vi/admin.tsindex b7f1444ed..cdbe91163 100644--- a/shared/src/i18n/vi/admin.ts+++ b/shared/src/i18n/vi/admin.ts@@ -749,5 +749,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': 'Khóa được dùng cho việc gì','admin.mapsKeyHintShort': 'Thêm ảnh, đánh giá và giờ mở cửa. Mọi tra cứu khi đó sẽ đi qua Google.','admin.amapKeyHintShort': 'Cho tìm kiếm địa điểm tại Trung Quốc đại lục. Cần khóa dịch vụ web, không phải khóa JS API.',+ 'admin.collab.links.subtitle': 'Liên kết chia sẻ và dấu trang',};export default admin;diff --git a/shared/src/i18n/vi/collab.ts b/shared/src/i18n/vi/collab.tsindex 429434703..603da8a4c 100644--- a/shared/src/i18n/vi/collab.ts+++ b/shared/src/i18n/vi/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': 'Tùy chọn','collab.polls.delete': 'Xóa bỏ','collab.polls.closedSection': 'Đã đóng',+ 'collab.chat.imageLimit': 'Bạn có thể đính kèm tối đa {max} ảnh cho mỗi tin nhắn',+ 'collab.chat.uploading': 'Đang tải lên {percent}%',+ 'collab.chat.attachImages': 'Đính kèm ảnh',+ 'collab.chat.attachedImage': 'Ảnh đính kèm',+ 'collab.chat.closeImage': 'Đóng ảnh',};export default collab;diff --git a/shared/src/i18n/vi/docsync.ts b/shared/src/i18n/vi/docsync.tsindex 3bcaee3ff..6295a1cfd 100644--- a/shared/src/i18n/vi/docsync.ts+++ b/shared/src/i18n/vi/docsync.ts@@ -176,6 +176,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': 'Nhà cung cấp này không khả dụng trên máy chủ này.','docsync.error.provider_disabled': 'Đã tạm dừng: quản trị viên đã tắt nhà cung cấp này. Việc đồng bộ sẽ tiếp tục khi nó được bật lại.',+ 'docsync.binding.reconnect': 'Kết nối lại',};export default docsync;diff --git a/shared/src/i18n/vi/map.ts b/shared/src/i18n/vi/map.tsindex 6c7bf8dea..e7bf7890e 100644--- a/shared/src/i18n/vi/map.ts+++ b/shared/src/i18n/vi/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': 'Ẩn toàn bộ chuyến đi','map.overview.total': 'Tổng quãng đường','map.attribution': 'Nguồn bản đồ',+ 'map.overview.unrouted': 'Không thể tính {count} chặng, nên khoảng cách chưa đầy đủ.',+ 'map.overview.dayUnrouted': 'Không thể tính {count} chặng của ngày này',};export default map;diff --git a/shared/src/i18n/vi/mobileTrip.ts b/shared/src/i18n/vi/mobileTrip.tsindex 16631f15a..5d1bf0bc4 100644--- a/shared/src/i18n/vi/mobileTrip.ts+++ b/shared/src/i18n/vi/mobileTrip.ts@@ -71,5 +71,7 @@ const mobileTrip: TranslationStrings = {'1 đoạn có nhiều hơn mức vừa trong một câu trả lời. Chọn ít loại hơn để xem phần còn lại.','mobileTrip.rtTruncated.other':'{count} đoạn có nhiều hơn mức vừa trong một câu trả lời. Chọn ít loại hơn để xem phần còn lại.',+ 'mobileTrip.rtNoDay': 'Chưa chọn ngày',+ 'mobileTrip.rtNoDayHint': 'Bản đồ đang hiển thị cả chuyến đi. Chạm vào một ngày ở trên để xem chặng lái.',};export default mobileTrip;diff --git a/shared/src/i18n/vi/roadtrip.ts b/shared/src/i18n/vi/roadtrip.tsindex 27ac64480..e521f1ee0 100644--- a/shared/src/i18n/vi/roadtrip.ts+++ b/shared/src/i18n/vi/roadtrip.ts@@ -264,5 +264,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': 'Khong thu phi','roadtrip.alt.noFerry': 'Không phà','roadtrip.summary.partial': 'Vẫn đang tính phần còn lại của chặng đường',+ 'roadtrip.stay.releaseTitle': 'Bỏ đêm nghỉ này?',+ 'roadtrip.stay.releaseBody': 'Đêm nghỉ tại “{name}” sẽ bị xóa. Điểm dừng vẫn ở trên hành trình như một điểm nghỉ.',+ 'roadtrip.stay.releaseBookedBody': 'Đêm nghỉ tại “{name}” sẽ bị xóa cùng với đặt chỗ “{booking}” và mọi chi phí liên quan. Điểm dừng vẫn ở trên hành trình như một điểm nghỉ.',+ 'roadtrip.stay.releaseAction': 'Chuyển thành điểm nghỉ',};export default roadtrip;diff --git a/shared/src/i18n/vi/trip.ts b/shared/src/i18n/vi/trip.tsindex 3d59efe1c..006e757e2 100644--- a/shared/src/i18n/vi/trip.ts+++ b/shared/src/i18n/vi/trip.ts@@ -88,5 +88,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': 'Chuyển tuyến','transit.walkLabel': 'Đi bộ','transit.searchHint': 'Tìm các kết nối thực tế và thêm thẳng vào ngày — dữ liệu qua Transitous.',+ 'trip.confirm.deletePlaceNight': 'Đêm đã đặt tại “{name}” sẽ mất cùng với địa điểm.',+ 'trip.confirm.deletePlaceBooked': 'Đêm đã đặt tại “{name}” sẽ mất cùng với địa điểm, kèm theo đặt chỗ “{booking}” và mọi chi phí liên quan.',};export default trip;diff --git a/shared/src/i18n/zh-TW/admin.ts b/shared/src/i18n/zh-TW/admin.tsindex 91b437bea..3eab64e75 100644--- a/shared/src/i18n/zh-TW/admin.ts+++ b/shared/src/i18n/zh-TW/admin.ts@@ -747,5 +747,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': '金鑰用於什麼','admin.mapsKeyHintShort': '增加照片、評分和營業時間。之後每次查詢都會送往 Google。','admin.amapKeyHintShort': '用於中國大陸的地點搜尋。需要 Web 服務金鑰,而非 JS API 金鑰。',+ 'admin.collab.links.subtitle': '共享連結和書籤',};export default admin;diff --git a/shared/src/i18n/zh-TW/collab.ts b/shared/src/i18n/zh-TW/collab.tsindex cfd448763..c26f74bff 100644--- a/shared/src/i18n/zh-TW/collab.ts+++ b/shared/src/i18n/zh-TW/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': '選項','collab.polls.delete': '刪除','collab.polls.closedSection': '已關閉',+ 'collab.chat.imageLimit': '每則訊息最多可附加 {max} 張圖片',+ 'collab.chat.uploading': '上傳中 {percent}%',+ 'collab.chat.attachImages': '附加圖片',+ 'collab.chat.attachedImage': '附加的圖片',+ 'collab.chat.closeImage': '關閉圖片',};export default collab;diff --git a/shared/src/i18n/zh-TW/docsync.ts b/shared/src/i18n/zh-TW/docsync.tsindex e1cd2c01f..0322ab6ee 100644--- a/shared/src/i18n/zh-TW/docsync.ts+++ b/shared/src/i18n/zh-TW/docsync.ts@@ -167,6 +167,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': '這個提供者在此執行個體上無法使用。','docsync.error.provider_disabled': '已暫停:管理員已停用此提供者。重新啟用後會繼續同步。',+ 'docsync.binding.reconnect': '重新連線',};export default docsync;diff --git a/shared/src/i18n/zh-TW/map.ts b/shared/src/i18n/zh-TW/map.tsindex e92a8ea71..43811c47b 100644--- a/shared/src/i18n/zh-TW/map.ts+++ b/shared/src/i18n/zh-TW/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': '隱藏整趟行程','map.overview.total': '總距離','map.attribution': '地圖來源',+ 'map.overview.unrouted': '有 {count} 段無法計算路線,因此距離不完整。',+ 'map.overview.dayUnrouted': '本日有 {count} 段無法計算路線',};export default map;diff --git a/shared/src/i18n/zh-TW/mobileTrip.ts b/shared/src/i18n/zh-TW/mobileTrip.tsindex 07b1c193e..c82e83484 100644--- a/shared/src/i18n/zh-TW/mobileTrip.ts+++ b/shared/src/i18n/zh-TW/mobileTrip.ts@@ -65,5 +65,7 @@ const mobileTrip: TranslationStrings = {'mobileTrip.rtNoneOnStage': '本段沿途沒有這類地點。','mobileTrip.rtTruncated.one': '1 段路的結果超出一次回答能容納的量。少選幾類就能看到其餘的。','mobileTrip.rtTruncated.other': '{count} 段路的結果超出一次回答能容納的量。少選幾類就能看到其餘的。',+ 'mobileTrip.rtNoDay': '未選擇日期',+ 'mobileTrip.rtNoDayHint': '地圖顯示的是整個行程。點按上方的日期查看當天路線。',};export default mobileTrip;diff --git a/shared/src/i18n/zh-TW/roadtrip.ts b/shared/src/i18n/zh-TW/roadtrip.tsindex b766e6e8b..9542e0c4d 100644--- a/shared/src/i18n/zh-TW/roadtrip.ts+++ b/shared/src/i18n/zh-TW/roadtrip.ts@@ -251,5 +251,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': '免收費','roadtrip.alt.noFerry': '不搭渡輪','roadtrip.summary.partial': '正在計算剩餘路程',+ 'roadtrip.stay.releaseTitle': '取消這次過夜?',+ 'roadtrip.stay.releaseBody': '將取消在「{name}」的過夜。該停靠點會作為休息保留在行程中。',+ 'roadtrip.stay.releaseBookedBody': '將取消在「{name}」的過夜,並同時刪除預訂「{booking}」及其關聯的費用。該停靠點會作為休息保留在行程中。',+ 'roadtrip.stay.releaseAction': '改為休息',};export default roadtrip;diff --git a/shared/src/i18n/zh-TW/trip.ts b/shared/src/i18n/zh-TW/trip.tsindex 9c7f3615b..21cb59079 100644--- a/shared/src/i18n/zh-TW/trip.ts+++ b/shared/src/i18n/zh-TW/trip.ts@@ -87,5 +87,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': '轉乘次數','transit.walkLabel': '步行','transit.searchHint': '搜尋實際交通連線,並直接加入當天行程 — 資料由 Transitous 提供。',+ 'trip.confirm.deletePlaceNight': '在「{name}」預訂的過夜會隨該地點一起刪除。',+ 'trip.confirm.deletePlaceBooked': '在「{name}」預訂的過夜會隨該地點一起刪除,同時刪除預訂「{booking}」及其關聯的費用。',};export default trip;diff --git a/shared/src/i18n/zh/admin.ts b/shared/src/i18n/zh/admin.tsindex 48d9affdd..68a7ea637 100644--- a/shared/src/i18n/zh/admin.ts+++ b/shared/src/i18n/zh/admin.ts@@ -745,5 +745,6 @@ const admin: TranslationStrings = {'admin.placesUsageTitle': '密钥用于什么','admin.mapsKeyHintShort': '增加照片、评分和营业时间。之后每次查询都会发往 Google。','admin.amapKeyHintShort': '用于中国大陆的地点搜索。需要 Web 服务密钥,而非 JS API 密钥。',+ 'admin.collab.links.subtitle': '共享链接和书签',};export default admin;diff --git a/shared/src/i18n/zh/collab.ts b/shared/src/i18n/zh/collab.tsindex f603b0815..f9ad4a001 100644--- a/shared/src/i18n/zh/collab.ts+++ b/shared/src/i18n/zh/collab.ts@@ -93,5 +93,10 @@ const collab: TranslationStrings = {'collab.polls.options': '选项','collab.polls.delete': '删除','collab.polls.closedSection': '已关闭',+ 'collab.chat.imageLimit': '每条消息最多可附加 {max} 张图片',+ 'collab.chat.uploading': '上传中 {percent}%',+ 'collab.chat.attachImages': '附加图片',+ 'collab.chat.attachedImage': '附加的图片',+ 'collab.chat.closeImage': '关闭图片',};export default collab;diff --git a/shared/src/i18n/zh/docsync.ts b/shared/src/i18n/zh/docsync.tsindex ade8bcc0f..4f14d31d5 100644--- a/shared/src/i18n/zh/docsync.ts+++ b/shared/src/i18n/zh/docsync.ts@@ -166,6 +166,7 @@ const docsync: TranslationStrings = {'docsync.error.unknown_provider': '此实例不提供该文档服务。','docsync.error.provider_disabled': '已暂停:管理员已关闭此文档服务。重新启用后将继续同步。',+ 'docsync.binding.reconnect': '重新连接',};export default docsync;diff --git a/shared/src/i18n/zh/map.ts b/shared/src/i18n/zh/map.tsindex f20075b67..fb6f4bd80 100644--- a/shared/src/i18n/zh/map.ts+++ b/shared/src/i18n/zh/map.ts@@ -26,5 +26,7 @@ const map: TranslationStrings = {'map.overview.hide': '隐藏整个行程','map.overview.total': '总距离','map.attribution': '地图来源',+ 'map.overview.unrouted': '有 {count} 段无法计算路线,因此距离不完整。',+ 'map.overview.dayUnrouted': '本日有 {count} 段无法计算路线',};export default map;diff --git a/shared/src/i18n/zh/mobileTrip.ts b/shared/src/i18n/zh/mobileTrip.tsindex 6a2f3b0ad..f6e9c4fcc 100644--- a/shared/src/i18n/zh/mobileTrip.ts+++ b/shared/src/i18n/zh/mobileTrip.ts@@ -65,5 +65,7 @@ const mobileTrip: TranslationStrings = {'mobileTrip.rtNoneOnStage': '本段沿途没有这类地点。','mobileTrip.rtTruncated.one': '1 段路的结果超出一次回答能装下的量。少选几类就能看到其余的。','mobileTrip.rtTruncated.other': '{count} 段路的结果超出一次回答能装下的量。少选几类就能看到其余的。',+ 'mobileTrip.rtNoDay': '未选择日期',+ 'mobileTrip.rtNoDayHint': '地图显示的是整个行程。点按上方的日期查看当天路线。',};export default mobileTrip;diff --git a/shared/src/i18n/zh/roadtrip.ts b/shared/src/i18n/zh/roadtrip.tsindex 718b8b8d0..54284d222 100644--- a/shared/src/i18n/zh/roadtrip.ts+++ b/shared/src/i18n/zh/roadtrip.ts@@ -252,5 +252,9 @@ const roadtrip: TranslationStrings = {'roadtrip.alt.noToll': '免收费','roadtrip.alt.noFerry': '不乘轮渡','roadtrip.summary.partial': '正在计算剩余路程',+ 'roadtrip.stay.releaseTitle': '取消这次过夜?',+ 'roadtrip.stay.releaseBody': '将取消在“{name}”的过夜。该停靠点会作为休息保留在行程中。',+ 'roadtrip.stay.releaseBookedBody': '将取消在“{name}”的过夜,并同时删除预订“{booking}”及其关联的费用。该停靠点会作为休息保留在行程中。',+ 'roadtrip.stay.releaseAction': '改为休息',};export default roadtrip;diff --git a/shared/src/i18n/zh/trip.ts b/shared/src/i18n/zh/trip.tsindex 4f70b3c6e..85c6bd094 100644--- a/shared/src/i18n/zh/trip.ts+++ b/shared/src/i18n/zh/trip.ts@@ -87,5 +87,7 @@ const trip: TranslationStrings = {'transit.transfersLabel': '换乘','transit.walkLabel': '步行','transit.searchHint': '搜索真实班次并直接添加到当天行程 — 数据来自 Transitous。',+ 'trip.confirm.deletePlaceNight': '在“{name}”预订的过夜会随该地点一起删除。',+ 'trip.confirm.deletePlaceBooked': '在“{name}”预订的过夜会随该地点一起删除,同时删除预订“{booking}”及其关联的费用。',};export default trip;diff --git a/shared/src/maps/maps.schema.ts b/shared/src/maps/maps.schema.tsindex 729343eac..f4b082631 100644--- a/shared/src/maps/maps.schema.ts+++ b/shared/src/maps/maps.schema.ts@@ -273,7 +273,12 @@ export const mapsPlaceEnrichmentRequestSchema = z.object({* again is not cheap: an Overpass lookup for a large relation was measured at* 12.8 seconds. Passing them along turns a second slow round trip into none.* Only the tags are read, and the wiki tag is re-validated before use, so a- * doctored payload can at worst mislead the user who sent it.+ * doctored payload can at worst mislead the user who sent it. That holds for+ * the cache too: an answer whose description or links were read off these+ * details is served to this caller and not written to the per-instance+ * enrichment cache, and the index's own description is fetched from the+ * index rather than taken from here, so nothing a sender puts in this record+ * reaches another user's screen.*/details: z.record(z.string(), z.unknown()).optional(),});diff --git a/wiki/Document-Sync.md b/wiki/Document-Sync.mdindex b0c64b15e..953174fd4 100644--- a/wiki/Document-Sync.md+++ b/wiki/Document-Sync.md@@ -71,7 +71,7 @@ Every connection form ends with **Accept a self-signed certificate**, off by def- **Custom field:** a document TREK uploads carries the trip's tag and a custom field named `trek_trip_id`, holding `trek-trip-` plus the trip's id. TREK creates the field on the first upload. It is a breadcrumb for whoever tidies the archive later; TREK does not filter on it. Removing the tag from a document takes it out of the trip, whatever the field says.- **Names:** Paperless-ngx keeps a title rather than a file name, so a document arrives in TREK as its title plus the extension of the original file. TREK downloads the original file, not the archived PDF Paperless-ngx makes from it.- **File types:** Paperless-ngx takes PDF, JPEG, PNG, TIFF, GIF, BMP, WebP, HEIC and HEIF images, plain text, CSV and email (`.eml`) files. Word, Excel, PowerPoint, OpenDocument and RTF files only go through on an instance that runs Tika and Gotenberg; without them Paperless-ngx refuses them and TREK lists them as *Type not allowed*.-- **Instant updates:** when the token's user may add workflows, TREK creates a workflow named `TREK document sync (link n)` that calls TREK whenever a document with the trip's tag is added or updated. **Disconnect** deletes it again. See [When TREK checks](#when-trek-checks).+- **Instant updates:** when the token's user may add workflows, TREK creates a workflow named `TREK document sync (link n)` that calls TREK whenever a document with the trip's tag is added or updated. **Disconnect** deletes it again. Without that permission the binding runs on the timer, unless a user who may add workflows pastes the binding's **Instant updates** address into a workflow by hand. See [When TREK checks](#when-trek-checks).- **Recycle bin:** a document TREK removes goes to the Paperless-ngx trash.- **Version:** Paperless-ngx 3 or newer.@@ -89,7 +89,7 @@ Every connection form ends with **Accept a self-signed certificate**, off by def- **Key permissions:** a key limited in Papra must still be allowed to work with the organisation's documents and tags. Papra answers a missing permission exactly like a wrong key, so TREK can only report *The credentials were refused.*- **Duplicates:** Papra keeps one document for identical bytes, so of two identical files in TREK only the first reaches Papra; the second is listed under **Needs a look**.- **Upload limit:** Papra's own upload limit is an instance setting TREK cannot read. A file over it is listed as *Too large*.-- **Instant updates:** none. Papra does not let an API key manage webhooks, so the binding runs on the timer.+- **Instant updates:** by hand. Papra does not let an API key manage webhooks, so TREK cannot subscribe itself; paste the binding's **Instant updates** address into a webhook in Papra, and the binding runs on the timer until then. See [When TREK checks](#when-trek-checks).- **Recycle bin:** a document TREK removes goes to Papra's trash.### Nextcloud@@ -105,7 +105,7 @@ Every connection form ends with **Accept a self-signed certificate**, off by def- **Scope:** a folder directly under the base folder. **Make a new one** creates it there, and creates the base folder too if it does not exist yet. A folder of that name that already exists is refused; pick it from the list instead.- **Only the top level** of the folder is synced. Sub-folders inside it are left alone, so moving a file into one takes it out of the trip.-- **Instant updates:** when the account may manage webhooks (an administrator account on an instance with the `webhook_listeners` app), TREK subscribes itself to files being created, written, deleted and renamed. Otherwise the binding runs on the timer.+- **Instant updates:** when the account may manage webhooks (an administrator account on an instance with the `webhook_listeners` app), TREK subscribes itself to files being created, written, deleted and renamed. Otherwise the binding runs on the timer, unless a Nextcloud administrator registers the binding's **Instant updates** address as a listener by hand.- **Recycle bin:** a document TREK removes goes to Nextcloud's *Deleted files*. **On an instance without the Deleted files app, it is deleted for good.**### OpenCloud@@ -165,7 +165,7 @@ Once bound, the dialog lists the trip's stores under **This trip** and shows theOn the phone the card opens as a sheet. The first three settings are buttons there that step through their options with each tap; the **Instant updates** address is only shown on the desktop.-**Disconnect** ends the binding and keeps every document where it is, on both sides: *Documents stay in TREK and at the store. Only the pairing between them goes.* The phone asks before it disconnects; the desktop does not. A workflow or webhook subscription TREK created for the binding is removed with it.+**Disconnect** ends the binding and keeps every document where it is, on both sides: *Documents stay in TREK and at the store. Only the pairing between them goes.* Both the desktop and the phone ask before they disconnect. A workflow or webhook subscription TREK created for the binding is removed with it.## How changes travel@@ -180,7 +180,7 @@ TREK itself has no way to rename a document or replace its content, so what travA document whose content changed in the store is downloaded again as a new document, and the copy it replaces goes to TREK's trash. Links the old copy had to bookings, places or expenses stay with the old copy.-**Renames in the store come through.** On Nextcloud, OpenCloud and Synology the TREK copy takes the new name. On Paperless-ngx and Papra a document that came from the store arrives again as a fresh copy after a rename, and on Paperless-ngx after any edit of the document, and the old copy goes to TREK's trash without its links. A document TREK itself uploaded to Paperless-ngx or Papra is renamed in place.+**Renames in the store come through.** The TREK copy takes the new name, on every store. On Paperless-ngx and Papra the listing carries a checksum of the file, so an edit that leaves the file alone, such as a rename, a new tag or a new correspondent, is not a new document either: the copy is downloaded again only when its content changed.### Deletions@@ -253,13 +253,14 @@ Where a store can tell TREK that something changed, it calls the binding's own a| Store | Instant updates ||---|---|-| Paperless-ngx | TREK creates the workflow itself when the token's user may add workflows. |-| Nextcloud | TREK subscribes itself when the account may manage webhooks (an administrator account with the `webhook_listeners` app). Nextcloud sends these from its background jobs, so they arrive as promptly as its cron runs, and a TREK on a private address is only called when Nextcloud's `allow_local_remote_servers` is on. |-| Papra, OpenCloud, Synology | Timer only. |+| Paperless-ngx | TREK creates the workflow itself when the token's user may add workflows. Otherwise a Paperless-ngx user who may add workflows can paste the **Instant updates** address into a workflow's webhook action by hand. |+| Nextcloud | TREK subscribes itself when the account may manage webhooks (an administrator account with the `webhook_listeners` app). Where it may not, a Nextcloud administrator can register the **Instant updates** address as a listener by hand. Nextcloud sends these from its background jobs, so they arrive as promptly as its cron runs, and a TREK on a private address is only called when Nextcloud's `allow_local_remote_servers` is on. |+| Papra | Paste the **Instant updates** address into a webhook in Papra by hand. Papra's webhook API is closed to API keys, so TREK cannot subscribe itself. |+| OpenCloud, Synology | Timer only. Neither can call TREK. |- **The address TREK registers** is built from the address the person binding the trip used to open TREK at that moment, including what the reverse proxy passes in `X-Forwarded-Host` and `X-Forwarded-Proto`. Bind the trip through the address the store can reach TREK under. Behind a proxy that passes no host, no address is registered and the timer carries the binding.- **Paperless-ngx refuses a callback address longer than 256 characters.** The binding then runs on the timer.-- **TREK only acts on a call that carries the binding's secret**, which TREK hands over itself when it subscribes. The **Instant updates** address under **Settings** is shown for every binding, but the secret is not shown anywhere, so pasting that address into a store by hand does not speed anything up. Those bindings run on the timer.+- **The address is the key.** A call to the **Instant updates** address under **Settings** starts a run on its own, so an address pasted into a store by hand works for Papra, for a Nextcloud where TREK could not subscribe itself and for a Paperless-ngx whose token may not add workflows. Where TREK registered the subscription itself, it also hands over a secret and only acts on a call that carries it; the secret is not shown anywhere, so pasting that binding's address somewhere else by hand adds nothing. For OpenCloud and Synology there is nowhere to paste it, and once **Test connection** on the saved connection has reported that, their bindings show no address at all.### Tuning@@ -307,7 +308,7 @@ See [MCP-Addon-Tools](MCP-Addon-Tools) and [MCP-Scopes](MCP-Scopes).| **In sync** | The last run finished with nothing left over. || **Partly synced** | The last run left something undone: more than 25 documents to move, documents listed under **Needs a look**, or the mass-delete guard. The notice line names which. || **Failed** | The store could not be used. The notice line names the reason; TREK retries with the backoff described above. |-| **Sign in again** | The store refused the stored credential while TREK was listing documents. More often a refused credential shows as **Failed** with *The credentials were refused.* The usual causes: a revoked Paperless-ngx token or Papra key, a deleted app password or app token, a changed DSM password, or TREK removed from the account's trusted devices in DSM. If the credential still exists in the store, **Sync now** tries again. The connection form only opens for a store the trip has not been connected to yet, so a replaced credential cannot be entered from the trip at the moment. |+| **Sign in again** | The store refused the stored credential while TREK was listing documents. More often a refused credential shows as **Failed** with *The credentials were refused.* The usual causes: a revoked Paperless-ngx token or Papra key, a deleted app password or app token, a changed DSM password, or TREK removed from the account's trusted devices in DSM. If the credential still exists in the store, **Sync now** tries again. A replaced credential goes in through **Reconnect**, which the trip owner finds next to the notice on the binding in both states: it opens the store's connection form again, and the binding runs as soon as the new credential is saved. **Add another** in the sidebar still lists only the stores the trip is not connected to. || **Folder is gone** | The bound tag, folder or space no longer exists. TREK does not recreate it. **Disconnect**, then pick the store again under **Add another** and bind a new, empty one; TREK's documents go up into it. || **Owner left the trip** | The person whose account the store was connected with is no longer on the trip. The binding stopped and **Sync now** is refused, also for a paused binding. Documents stay where they are on both sides. Once that person is back on the trip, switching **Sync automatically** on lets it run again; until then the switch stays off. |diff --git a/wiki/Environment-Variables.md b/wiki/Environment-Variables.mdindex ce7ace7c3..9fae0fd33 100644--- a/wiki/Environment-Variables.md+++ b/wiki/Environment-Variables.md@@ -7,7 +7,7 @@ Complete reference for all environment variables TREK reads.- **Docker Compose** — use the `environment:` block or a `.env` file alongside `docker-compose.yml`- **Docker run** — pass each variable with `-e VARIABLE=value`- **Helm** — use `env:` for plain values and `secretEnv:` for sensitive values in `values.yaml`. The chart only- passes through the keys it declares (28 in `templates/configmap.yaml`, 5 in `templates/secret.yaml`), so a variable+ passes through the keys it declares (31 in `templates/configmap.yaml`, the credentials in `templates/secret.yaml`), so a variablethat is not one of them is dropped silently — patch it onto the Deployment or add it to the chart- **Unraid** — set in the container template editor- **Proxmox Community Script** — set in `/opt/trek/server/.env`@@ -324,10 +324,10 @@ TREK's own place index, the [TREK Places API](TREK-Places-API), answers the sugg| Variable | Description | Default ||-----------------------|-------------|---------|-| `TREK_PLACES_ENABLED` | Set to `false` to stop asking the index. Search then works as it did before 4.3.0: OpenStreetMap on an install without a key, the keyed provider (Google or Amap) when one is set, the Overpass mirrors for the category buttons, and no places downloaded for offline search. Only the literal value `false` switches it off: `0`, `no`, `off` and `FALSE` pass startup validation and leave the index on, and a value that is not boolean-like aborts startup. | on |+| `TREK_PLACES_ENABLED` | Set to `false` to stop asking the index. Search then works as it did before 4.3.0: OpenStreetMap on an install without a key, the keyed provider (Google or Amap) when one is set, the Overpass mirrors for the category buttons, and no places downloaded for offline search. It is a boolean switch like the others on this page: `false`, `0`, `off` and `no` in any casing switch it off, a value that is not boolean-like aborts startup, and unset or blank leaves the index on. | on || `TREK_PLACES_URL` | Base URL of a copy of the service you run yourself; it has to answer the same `/v1` API. Unset or blank uses the public service. A trailing slash is stripped, and a value that is not a full URL aborts startup. It is configuration rather than user input and is not run through the SSRF guard, so an address on your LAN or Docker network works without `ALLOW_INTERNAL_NETWORK`. | `https://places.liketrek.com` |-Neither variable is among the keys the Helm chart declares yet, so on Helm patch them onto the Deployment (see [How to Set Variables](#how-to-set-variables)).+On Helm both go under `env:` in `values.yaml`. The chart passes `TREK_PLACES_ENABLED` through whenever it is set at all, so an unquoted `false` or `--set env.TREK_PLACES_ENABLED=false` reaches the container as well.---@@ -351,7 +351,7 @@ type **Web 服务**. A **Web 端 (JS API)** key is a different kind of credentia**Two ways to configure it**, pick one; the env var wins if both are present:-1. **Environment variable** (this page): instance-wide, ideal for Docker/Helm where you already manage config as env.+1. **Environment variable** (this page): instance-wide, ideal for Docker/Helm where you already manage config as env. In the chart the key and the secret are credentials and go under `secretEnv:`, not `env:`; only `AMAP_API_BASE` is a plain `env:` value.2. **Admin → Settings → API Keys**: paste it into the **Amap (高德地图) API Key** field. Stored encrypted at rest.Setting a key is not enough on its own: **Admin → Settings → API Keys → Place search provider** decides which keyeddiff --git a/wiki/MCP-Tools-and-Resources.md b/wiki/MCP-Tools-and-Resources.mdindex 80c54fdf3..c33b6db3b 100644--- a/wiki/MCP-Tools-and-Resources.md+++ b/wiki/MCP-Tools-and-Resources.md@@ -59,8 +59,8 @@ Requires `places:read` or `places:write` scope.| `update_place` | Update any field of an existing place including transport mode, timing, price and `stop_type`. Pass `stop_type: null` to turn a service stop back into an ordinary place. || `rate_place` | Set or clear your own 1–5 star rating on a place. Every trip member rates independently and the place shows the average. Pass `null` to clear the vote. || `bulk_update_places` | Update many places at once, applying the same field values (e.g. category, price, transport mode, `stop_type`) to every listed place in a single call. `stop_type: null` turns the listed service stops back into ordinary places. |-| `delete_place` | Remove a place from a trip. Also removes all day assignments. |-| `bulk_delete_places` | Delete multiple places by ID. Removes all day assignments. Cannot be undone. |+| `delete_place` | Remove a place from a trip. Also removes all day assignments, the expenses linked to the place and any night booked at it, together with that night's reservation and the reservation's expense. Cannot be undone, so an assistant should warn before deleting a hotel that holds a booking. |+| `bulk_delete_places` | Delete multiple places by ID. Removes all day assignments, linked expenses and any nights booked at each place, with their reservations and expenses. Cannot be undone. || `import_places_from_url` | Import all places from a publicly shared Google Maps or Naver Maps list URL. || `list_categories` | List all available place categories with id, name, icon, and color. || `create_category` | Add a category to the instance-wide palette, with name, hex colour and emoji icon. Every trip on the instance sees it, so prefer an existing one from `list_categories`. Admin only; a non-admin gets `Admin access required`. Requires `places:write`. |diff --git a/wiki/TREK-Places-API.md b/wiki/TREK-Places-API.mdindex 235e75306..b1e25dfbc 100644--- a/wiki/TREK-Places-API.md+++ b/wiki/TREK-Places-API.md@@ -88,7 +88,7 @@ services:- TREK_PLACES_ENABLED=false```-Only the value `false` switches the index off. `0`, `no`, `off` and `FALSE` pass the startup check and leave it on; a value that is not boolean-like at all aborts startup.+`false`, `0`, `off` and `no` in any casing switch the index off, as on every other boolean switch. A value that is not boolean-like at all aborts startup, and unset or blank leaves the index on.With the index off, TREK stops asking it for suggestions, searches, category buttons, the Road trip search, import geocoding and offline downloads, and place search works the way it did before 4.3.0:@@ -106,7 +106,7 @@ The card in **Admin → Settings → API Keys** stays either way: it describes tThe address is read from your own configuration and is not a URL a user can type, so it does not go through the SSRF guard: a copy on your LAN or in the same Docker network works without `ALLOW_INTERNAL_NETWORK`.-> **Helm:** the chart passes only the variables its ConfigMap declares, and `TREK_PLACES_ENABLED` and `TREK_PLACES_URL` are not among them yet. Patch them onto the Deployment; see [How to Set Variables](Environment-Variables#how-to-set-variables).+> **Helm:** both variables go under `env:` in `values.yaml`, and the chart's ConfigMap passes them through. `TREK_PLACES_ENABLED` is passed whenever it is set at all, so an unquoted `false` or `--set env.TREK_PLACES_ENABLED=false` reaches the container too; see [How to Set Variables](Environment-Variables#how-to-set-variables).### Related variables