diff --git a/client/.gitignore b/client/.gitignore
index 2530b230e..63f406cb5 100644
--- a/client/.gitignore
+++ b/client/.gitignore
@@ -6,3 +6,4 @@ playwright/.cache/
# vite-plugin-pwa dev output (devOptions.enabled)
dev-dist/
+e2e/help/media.env
diff --git a/client/e2e/dates.ts b/client/e2e/dates.ts
new file mode 100644
index 000000000..b3a57dc61
--- /dev/null
+++ b/client/e2e/dates.ts
@@ -0,0 +1,114 @@
+/**
+ * The run's calendar.
+ *
+ * The seeded trip ends on the day the pictures are taken, and every other
+ * date the seed, the fixtures and the guides use is an offset from that day.
+ * So a run on any date meets a trip that is running, with a last day that is
+ * today: the boarding pass, What's Next and the forecast all have something
+ * to show, and nobody has to bump dates in three files every few weeks.
+ *
+ * The day is `E2E_PICTURE_DAY` (YYYY-MM-DD), set once by `e2e/help/run.mjs`
+ * and `playwright.config.ts` so the seed project and every worker agree even
+ * when the run crosses midnight; without it, today in the machine's zone.
+ */
+
+const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/
+
+function localToday(): string {
+ const d = new Date()
+ const pad = (n: number) => String(n).padStart(2, '0')
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
+}
+
+const fromEnv = process.env.E2E_PICTURE_DAY
+if (fromEnv && !ISO_DAY.test(fromEnv)) throw new Error(`E2E_PICTURE_DAY must be YYYY-MM-DD, got "${fromEnv}"`)
+
+/** The picture day as YYYY-MM-DD: the trip's last day. */
+export const PICTURE_DAY_ISO: string = fromEnv || localToday()
+
+/** Noon UTC on the picture day, a safe anchor for calendar arithmetic. */
+function anchor(offset: number): Date {
+ const d = new Date(`${PICTURE_DAY_ISO}T12:00:00Z`)
+ d.setUTCDate(d.getUTCDate() + offset)
+ return d
+}
+
+/** `YYYY-MM-DD` of the picture day plus `offset` days. */
+export function day(offset: number): string {
+ return anchor(offset).toISOString().slice(0, 10)
+}
+
+/** `YYYY-MM-DDTHH:mm:00`, the shape reservations and expenses take. */
+export function at(offset: number, hhmm: string): string {
+ return `${day(offset)}T${hhmm}:00`
+}
+
+/** The calendar year of the picture day plus `years`. */
+export function year(years = 0): number {
+ return anchor(0).getUTCFullYear() + years
+}
+
+/** A day `months` months after the picture day, on the given day of the month. */
+export function monthsAhead(months: number, dayOfMonth: number): string {
+ const d = anchor(0)
+ d.setUTCDate(1)
+ d.setUTCMonth(d.getUTCMonth() + months)
+ d.setUTCDate(dayOfMonth)
+ return d.toISOString().slice(0, 10)
+}
+
+const en = (opts: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat('en-US', { timeZone: 'UTC', ...opts })
+
+// The labels the English UI prints for a date, for the guides that have to
+// find a button by its calendar text.
+
+/** `Sat, Sep 12`, the day filter's chip. */
+export function short(offset: number): string {
+ return en({ weekday: 'short', month: 'short', day: 'numeric' }).format(anchor(offset))
+}
+
+/** `Saturday, September 12`, the day filter's long form. */
+export function long(offset: number): string {
+ return en({ weekday: 'long', month: 'long', day: 'numeric' }).format(anchor(offset))
+}
+
+/** `September 25, 2026`, a date picker's cell label. */
+export function pickerLabel(offset: number): string {
+ return pickerLabelOn(day(offset))
+}
+
+/** The same label for any `YYYY-MM-DD`, e.g. one from `monthsAhead`. */
+export function pickerLabelOn(iso: string): string {
+ return en({ month: 'long', day: 'numeric', year: 'numeric' }).format(new Date(`${iso}T12:00:00Z`))
+}
+
+/** `October`: the English name of the month `months` months after the picture day's. */
+export function monthName(months: number): string {
+ return en({ month: 'long' }).format(new Date(`${monthsAhead(months, 1)}T12:00:00Z`))
+}
+
+/** `19.09.2026`, what a date input takes when typed. */
+export function dotted(offset: number): string {
+ const [y, m, d] = day(offset).split('-')
+ return `${d}.${m}.${y}`
+}
+
+/** `13th`, for prose that names a day of the month. */
+export function ordinal(offset: number): string {
+ const n = anchor(offset).getUTCDate()
+ const suffix = n % 10 === 1 && n !== 11 ? 'st' : n % 10 === 2 && n !== 12 ? 'nd' : n % 10 === 3 && n !== 13 ? 'rd' : 'th'
+ return `${n}${suffix}`
+}
+
+/** `Wednesday 16 September 2026`, the date line of a booking mail. */
+export function emlDate(offset: number): string {
+ return en({ weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' }).format(anchor(offset)).replace(/,/g, '')
+}
+
+/** `Tue, 1 Sep 2026 09:12:00 +0900`, an RFC 2822 mail header for a fixed offset. */
+export function mailHeaderDate(offset: number, hhmm: string, tz: string): string {
+ const d = anchor(offset)
+ const weekday = en({ weekday: 'short' }).format(d)
+ const month = en({ month: 'short' }).format(d)
+ return `${weekday}, ${d.getUTCDate()} ${month} ${d.getUTCFullYear()} ${hhmm}:00 ${tz}`
+}
diff --git a/client/e2e/help/README.md b/client/e2e/help/README.md
index d004ef41b..633bf1790 100644
--- a/client/e2e/help/README.md
+++ b/client/e2e/help/README.md
@@ -53,5 +53,39 @@ change the theme, the language or the zoom for a picture.
tree once (`page.locator('body').ariaSnapshot()`) instead of guessing locators.
- A plugin installed by a run lives in `server/data/plugins/`; the dev server
imports it on its next restart. Guides that install one uninstall it in `cleanup`.
-- The trip is running on the seed's dates: the plan opens on today's (empty) day;
- `openTrip` in `trip-shared.ts` selects day 1 and closes its details panel.
+- The trip's last day is the run day by construction (`e2e/dates.ts`: every
+ seeded date is an offset from `E2E_PICTURE_DAY`, which `run.mjs` fixes to today
+ once for the whole run), so the plan opens on today, the trip's last and empty
+ day; `openTrip` in `trip-shared.ts` selects day 1 and closes its details panel.
+ A guide that has to find a date by its label builds it with the same helpers
+ (`short`, `long`, `pickerLabel`, `dotted`) instead of writing a calendar date.
+
+## The guides that show another service
+
+A few guides picture TREK talking to something outside it: AirTrail (flights
+into the Transports tab), Dawarich (the recorded route on the map, countries
+and wishes in the Atlas), a document store (Nextcloud on the Files tab) and the
+booking extractor (confirmations into Bookings and Transports). Their fixtures
+in `external.ts` fill each service themselves through its API, so the pictures
+do not depend on what happens to be in it; they need its address and key from
+`e2e/help/media.env` (copy `media.env.example`, not committed). Without the
+file those guides fail loudly at their first step and every other guide runs
+as before.
+
+- Every address has to be the machine's LAN address: the server's SSRF guard
+ refuses loopback whatever `ALLOW_INTERNAL_NETWORK` says, and that flag has to
+ be `true` in the same file for a private network to be reachable at all.
+- AirTrail: any instance with one user and an API key from Settings > Security.
+ The fixture puts four flights into that account.
+- Dawarich: any 1.15 instance with a user and their API key; add the LAN address
+ to its `APPLICATION_HOSTS`, and give it a reverse geocoder (Nominatim works)
+ or the Atlas dialog finds no countries. The fixture uploads a synthetic
+ recording of the trip and of the year before it (`dawarich-track.ts`).
+- Nextcloud: an app password. The fixture keeps a folder under `/Reisen` with
+ two documents, and the guide binds the trip to it.
+- The extractor: `KITINERARY_EXTRACTOR_PATH` must point at a program the
+ server can run with one file argument. On Linux that is the package's binary
+ (`libkitinerary-bin`); on Windows, a small executable that runs it inside the
+ TREK Docker image (`docker run --rm -v
:/in:ro --entrypoint
+ /usr/local/bin/kitinerary-extractor /in/`) and answers
+ `--version` by itself.
diff --git a/client/e2e/help/admin.guide.ts b/client/e2e/help/admin.guide.ts
index 81267e54a..dca606942 100644
--- a/client/e2e/help/admin.guide.ts
+++ b/client/e2e/help/admin.guide.ts
@@ -2,6 +2,7 @@ import { test, expect, type Page, type Locator } from '@playwright/test'
import { clearNotices } from '../screenshots/shot'
import { captureGuide, captureHero, dismissReleaseNotice, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
import { ensureAdminFixtures, pluginPackage } from './fixtures'
+import { toggleAddon } from './external'
import { adminContext, adminTabContexts, adminGuides } from '../../src/help/contexts/admin'
import type { HelpGuide } from '../../src/help/types'
@@ -359,6 +360,26 @@ const SCRIPTS: Record = {
only(p => tile(p, 'Lists')),
],
},
+ 'document-providers': {
+ guide: guide('document-providers'),
+ start: opener('admin-addons'),
+ steps: [
+ // The tile with its shelf: Documents is on in the seed, so the five rows are drawn.
+ only(p => tile(p, 'Documents')),
+ {
+ // The row's switch is a ToggleSwitch whose aria-label is the row's title.
+ target: p => tile(p, 'Documents').getByRole('button', { name: 'Nextcloud', exact: true }),
+ act: async p => {
+ const toggle = tile(p, 'Documents').getByRole('button', { name: 'Nextcloud', exact: true })
+ await toggle.click()
+ await expect(toggle).toHaveAttribute('aria-pressed', 'true', { timeout: 10_000 })
+ await settle(p)
+ },
+ },
+ ],
+ // Back to the seed, where every store is off; the files run switches this one on for itself.
+ cleanup: p => toggleAddon(p.request, 'nextcloud', false),
+ },
// ── Plugins ──────────────────────────────────────────────────────────────
'install-plugin': {
diff --git a/client/e2e/help/atlas.guide.ts b/client/e2e/help/atlas.guide.ts
index ce31292a4..cbb283452 100644
--- a/client/e2e/help/atlas.guide.ts
+++ b/client/e2e/help/atlas.guide.ts
@@ -1,7 +1,10 @@
import { test, expect, type Page, type Locator } from '@playwright/test'
import { clearNotices } from '../screenshots/shot'
import { captureGuide, captureHero, dismissReleaseNotice, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
+import { year } from '../dates'
import { ensureAtlasFixtures } from './fixtures'
+import { ensureDawarichConnection, disconnectDawarich } from './external'
+import { modal } from './trip-shared'
import { atlasGuides, atlasContext } from '../../src/help/contexts/atlas'
import type { HelpGuide } from '../../src/help/types'
@@ -46,6 +49,26 @@ const panel = (page: Page) => page.getByRole('button', { name: 'Stats' }).locato
/** The detail card the panel grows for a country picked in the search. */
const detailCard = (page: Page, country: string) =>
panel(page).locator('p.text-sm.font-bold').filter({ hasText: country }).locator('xpath=../..')
+/**
+ * Dawarich's own glass panel, left of the statistics: the one panel with its
+ * name in it. Scoped this way because its two tiles, Wishlist and Countries,
+ * have namesakes in the dialog's tabs once it is open.
+ */
+const dawarichPanel = (page: Page) =>
+ page.locator('div.hidden.md\\:flex').filter({ has: page.getByText('Dawarich', { exact: true }) }).first()
+const tile = (page: Page, label: 'Wishlist' | 'Countries') =>
+ dawarichPanel(page).getByRole('button', { name: label, exact: true })
+/** The answers in the dialog: every row is one checkbox named after the country or the wish. */
+const rows = (page: Page) => modal(page).getByRole('checkbox')
+
+/** The countries the Atlas paints as visited right now, by code. */
+async function visitedCodes(page: Page): Promise> {
+ const res = await page.request.get('/api/addons/atlas/stats')
+ const { countries } = (await res.json()) as { countries: { code: string; status: string }[] }
+ return new Set(countries.filter(c => c.status === 'visited').map(c => c.code))
+}
+/** What was visited before the countries guide confirmed anything, so `cleanup` takes exactly its additions off again. */
+let visitedBefore = new Set()
async function searchCountry(page: Page, name: string): Promise {
const input = searchInput(page)
@@ -292,7 +315,7 @@ const SCRIPTS: Record = {
{
prepare: async p => {
await choose(p, unsetSelect(popup(p)), 'June')
- await choose(p, unsetSelect(popup(p)), '2027')
+ await choose(p, unsetSelect(popup(p)), String(year(1)))
},
target: p => popup(p),
act: async p => {
@@ -334,7 +357,7 @@ const SCRIPTS: Record = {
{
prepare: async p => {
await choose(p, unsetSelect(panel(p)), 'Sep')
- await choose(p, unsetSelect(panel(p)), '2027')
+ await choose(p, unsetSelect(panel(p)), String(year(1)))
},
target: p => p.getByRole('button', { name: 'Add', exact: true }),
act: async p => {
@@ -354,6 +377,109 @@ const SCRIPTS: Record = {
{ target: p => panel(p).locator('.flex.items-center.gap-4').first() },
],
},
+
+ 'dawarich-countries': {
+ guide: guide('dawarich-countries'),
+ start: async p => {
+ await openAtlas(p)
+ visitedBefore = await visitedCodes(p)
+ },
+ steps: [
+ {
+ target: p => tile(p, 'Countries'),
+ act: async p => {
+ await tile(p, 'Countries').click()
+ await expect(modal(p).getByRole('button', { name: 'Look for countries' })).toBeVisible({ timeout: 15_000 })
+ await settle(p)
+ },
+ },
+ {
+ target: p => modal(p).getByRole('button', { name: 'Look for countries' }),
+ act: async p => {
+ await modal(p).getByRole('button', { name: 'Look for countries' }).click()
+ // A year in thirteen 30-day reads, one after another, each of which
+ // Dawarich computes on the spot; the client gives it four minutes.
+ // An empty answer shows a sentence instead of rows and fails here,
+ // which is right: a dialog with nothing to add is no picture.
+ await expect(rows(p).first()).toBeVisible({ timeout: 240_000 })
+ await settle(p)
+ // The flags come from a CDN and land after the rows.
+ await p.waitForTimeout(800)
+ },
+ },
+ {
+ target: p => modal(p).getByRole('button', { name: /^Add \d+ countries$/ }),
+ act: async p => {
+ await modal(p).getByRole('button', { name: /^Add \d+ countries$/ }).click()
+ await expect(p.getByText(/\d+ countries added/)).toBeVisible({ timeout: 20_000 })
+ await p.keyboard.press('Escape')
+ await expect(modal(p)).toHaveCount(0)
+ // The Atlas re-reads itself after a write; the colours land with the answer.
+ await expect.poll(async () => (await visitedCodes(p)).size, { timeout: 20_000 }).toBeGreaterThan(visitedBefore.size)
+ await settle(p)
+ await p.waitForTimeout(900)
+ },
+ },
+ ],
+ cleanup: async p => {
+ // Off the map again, so the next run and the guides after this one start
+ // from the seed. Unmarking tombstones a country; confirming it again from
+ // the dialog lifts that, so a re-run offers the same rows.
+ const after = await visitedCodes(p)
+ for (const code of after) {
+ if (!visitedBefore.has(code)) await p.request.delete(`/api/addons/atlas/country/${code}/mark`)
+ }
+ },
+ },
+
+ 'dawarich-wishes': {
+ guide: guide('dawarich-wishes'),
+ start: openAtlas,
+ steps: [
+ {
+ target: p => tile(p, 'Wishlist'),
+ act: async p => {
+ await tile(p, 'Wishlist').click()
+ await expect(modal(p).getByRole('button', { name: 'Check wishlist' })).toBeVisible({ timeout: 15_000 })
+ await settle(p)
+ },
+ },
+ {
+ target: p => modal(p).getByRole('button', { name: 'Check wishlist' }),
+ act: async p => {
+ await modal(p).getByRole('button', { name: 'Check wishlist' }).click()
+ // One read per wish with coordinates (Fushimi Inari, Wadi Rum, Petra),
+ // fifteen seconds each at worst; New Zealand and Iceland have none and
+ // are counted in the note instead.
+ await expect(rows(p).first()).toBeVisible({ timeout: 120_000 })
+ await settle(p)
+ },
+ },
+ {
+ target: p => modal(p).getByRole('button', { name: /^Tick off \d+$/ }),
+ act: async p => {
+ await modal(p).getByRole('button', { name: /^Tick off \d+$/ }).click()
+ await expect(p.getByText(/\d+ wishes ticked off/)).toBeVisible({ timeout: 20_000 })
+ await p.keyboard.press('Escape')
+ await expect(modal(p)).toHaveCount(0)
+ // The result is the list itself: the ticked date under each wish is a
+ // button labelled Undo, there once the list has re-read itself.
+ await p.getByRole('button', { name: 'Bucket List' }).click()
+ await expect(panel(p).getByRole('button', { name: 'Undo' }).first()).toBeVisible({ timeout: 20_000 })
+ await settle(p)
+ },
+ },
+ ],
+ cleanup: async p => {
+ // Every tick that came from a recording goes back, by the route the Undo
+ // button uses, so the wishes are open again for the next run.
+ const res = await p.request.get('/api/addons/atlas/bucket-list')
+ const { items } = (await res.json()) as { items: { id: number; visited_source: string | null }[] }
+ for (const item of items) {
+ if (item.visited_source === 'dawarich') await p.request.delete(`/api/integrations/dawarich/bucket-list/${item.id}/visit`)
+ }
+ },
+ },
}
// ── Run ───────────────────────────────────────────────────────────────────────
@@ -362,6 +488,16 @@ test.describe.configure({ mode: 'serial' })
test.beforeAll(async ({ request }) => {
await ensureAtlasFixtures(request)
+ // After the Atlas fixtures: the connection adds two wishes with coordinates
+ // (Fushimi Inari Taisha, Wadi Rum) to the list the fixtures create.
+ await ensureDawarichConnection(request)
+})
+
+test.afterAll(async ({ request }) => {
+ // Instance-wide: while the addon is on, every Atlas carries the Dawarich
+ // panel left of Stats. This file's pictures show it on purpose; the files
+ // after it do not, so it goes off again here, whatever happened in between.
+ await disconnectDawarich(request)
})
test('every registered atlas guide has a script, and only those', async () => {
@@ -375,6 +511,10 @@ test('hero: atlas', async ({ page }) => {
for (const id of atlasContext.guides) {
test(`pictures: ${id}`, async ({ page }) => {
+ // The Dawarich reads are a year of countries in thirteen pieces and one
+ // look-up per wish: more waiting on another service than four minutes
+ // may hold on a slow instance.
+ if (id.startsWith('dawarich-')) test.slow()
await page.setViewportSize(VIEWPORT)
await captureGuide(page, SCRIPTS[id])
})
diff --git a/client/e2e/help/dashboard.guide.ts b/client/e2e/help/dashboard.guide.ts
index 32df705a7..d937b9b9c 100644
--- a/client/e2e/help/dashboard.guide.ts
+++ b/client/e2e/help/dashboard.guide.ts
@@ -1,6 +1,7 @@
import { test, expect, type Page } from '@playwright/test'
import { clearNotices } from '../screenshots/shot'
import { captureGuide, captureHero, dismissReleaseNotice, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
+import { monthName, monthsAhead, pickerLabelOn } from '../dates'
import { ensureExtraTrips, coverFixture, card, EXTRA_TRIPS } from './fixtures'
import { dashboardGuides, dashboardContext } from '../../src/help/contexts/dashboard'
import type { HelpGuide } from '../../src/help/types'
@@ -56,6 +57,9 @@ async function pickDate(page: Page, trigger: ReturnType, mont
/** Hover-revealed action on a card. */
const cardAction = (page: Page, title: string, name: string) => card(page, title).locator(`.trip-action-btn[aria-label="${name}"]`)
+/** The trip the create guide makes, eight months out, named after the month it lands in. */
+const NEW_TRIP = `Amalfi Coast in ${monthName(8)}`
+
const SCRIPTS: Record = {
'create-trip': {
guide: guide('create-trip'),
@@ -67,15 +71,15 @@ const SCRIPTS: Record = {
},
{
target: p => titleField(p),
- act: async p => { await typeInto(p, titleField(p), 'Amalfi Coast in May') },
+ act: async p => { await typeInto(p, titleField(p), NEW_TRIP) },
},
{
target: p => datePicker(p, 'Start Date'),
act: async p => {
- await pickDate(p, datePicker(p, 'Start Date'), 8, 'May 8, 2027')
+ await pickDate(p, datePicker(p, 'Start Date'), 8, pickerLabelOn(monthsAhead(8, 8)))
await beat(p, 500)
// The end date follows the start date, so its calendar already opens on May.
- await pickDate(p, datePicker(p, 'End Date'), 0, 'May 15, 2027')
+ await pickDate(p, datePicker(p, 'End Date'), 0, pickerLabelOn(monthsAhead(8, 15)))
},
},
{
@@ -85,7 +89,7 @@ const SCRIPTS: Record = {
target: p => modal(p).getByRole('button', { name: 'Create New Trip' }),
act: async p => {
await modal(p).getByRole('button', { name: 'Create New Trip' }).click()
- await expect(card(p, 'Amalfi Coast in May')).toBeVisible({ timeout: 15_000 })
+ await expect(card(p, NEW_TRIP)).toBeVisible({ timeout: 15_000 })
},
},
],
@@ -213,18 +217,18 @@ const SCRIPTS: Record = {
guide: guide('delete-trip'),
start: async p => {
await openDashboard(p)
- await expect(card(p, 'Amalfi Coast in May')).toBeVisible()
+ await expect(card(p, NEW_TRIP)).toBeVisible()
},
steps: [
{
- target: p => cardAction(p, 'Amalfi Coast in May', 'Delete'),
- act: async p => { await cardAction(p, 'Amalfi Coast in May', 'Delete').click() },
+ target: p => cardAction(p, NEW_TRIP, 'Delete'),
+ act: async p => { await cardAction(p, NEW_TRIP, 'Delete').click() },
},
{
target: p => dialog(p).getByRole('button', { name: 'Delete', exact: true }),
act: async p => {
await dialog(p).getByRole('button', { name: 'Delete', exact: true }).click()
- await expect(card(p, 'Amalfi Coast in May')).toBeHidden({ timeout: 15_000 })
+ await expect(card(p, NEW_TRIP)).toBeHidden({ timeout: 15_000 })
},
},
],
diff --git a/client/e2e/help/dawarich-track.ts b/client/e2e/help/dawarich-track.ts
new file mode 100644
index 000000000..6b3ec43a0
--- /dev/null
+++ b/client/e2e/help/dawarich-track.ts
@@ -0,0 +1,357 @@
+/**
+ * A synthetic Dawarich recording for the help-center pictures.
+ *
+ * TREK only ever reads from Dawarich, so the media run has to put a recording
+ * there itself. This module makes one: a phone track that follows the seeded
+ * demo trip through Tokyo and Kyoto, day by day, plus five short trips in the
+ * year before it so the Atlas has countries to offer. Everything is relative to
+ * the day the pictures are taken, so it stays inside the trip's dates whenever
+ * the run happens.
+ *
+ * The points go through Dawarich's own batch endpoint as GeoJSON features;
+ * see `ensureDawarichFixtures` in fixtures.ts for the upload.
+ */
+
+export interface TrackFeature {
+ type: 'Feature'
+ geometry: { type: 'Point'; coordinates: [number, number] }
+ properties: {
+ timestamp: string
+ horizontal_accuracy: number
+ altitude: number
+ speed: number
+ device_id: string
+ }
+}
+
+/** One place on a day: when the phone gets there (local time) and how long it stays. */
+interface Waypoint {
+ t: string
+ lat: number
+ lng: number
+ stay?: number
+}
+
+interface DayPlan {
+ offset: number
+ utcOffset: number
+ points: Waypoint[]
+}
+
+export const DAWARICH_DEVICE = 'trek-help-fixture'
+
+const JST = 9
+
+// Every place the trail visits. The trip's own places come first and match the
+// seed's coordinates, so the dashed line ends exactly on the markers.
+const P = {
+ sensoji: [35.7148, 139.7967],
+ nakamise: [35.7118, 139.7963],
+ asakusaStation: [35.7109, 139.7975],
+ toyosuStation: [35.6551, 139.7961],
+ teamlab: [35.6486, 139.79],
+ shinjukuStation: [35.6896, 139.7006],
+ gracery: [35.6946, 139.7012],
+ shibuya: [35.6595, 139.7005],
+ harajuku: [35.6702, 139.7027],
+ meiji: [35.6764, 139.6993],
+ ueno: [35.7146, 139.7714],
+ akihabara: [35.6984, 139.7731],
+ ginza: [35.6717, 139.765],
+ tsukiji: [35.6654, 139.7707],
+ tokyoTower: [35.6586, 139.7454],
+ roppongi: [35.6605, 139.7292],
+ tokyoStation: [35.6812, 139.7671],
+ shinYokohama: [35.5075, 139.6174],
+ nagoya: [35.1709, 136.8815],
+ kyotoStation: [34.9858, 135.7588],
+ kanra: [34.9942, 135.7592],
+ fushimi: [34.9671, 135.7727],
+ arashiyama: [35.017, 135.6716],
+ togetsukyo: [35.013, 135.6776],
+ nishiki: [35.005, 135.7649],
+ kiyomizu: [34.9949, 135.785],
+ gion: [35.0037, 135.7752],
+ yasaka: [35.0037, 135.7785],
+ todaiji: [34.689, 135.8398],
+ naraPark: [34.6851, 135.843],
+ ginkakuji: [35.027, 135.7982],
+ philosophersPath: [35.0227, 135.7948],
+ nanzenji: [35.0114, 135.7939],
+ heian: [35.0163, 135.7824],
+} as const
+
+type Place = readonly [number, number]
+
+const at = (t: string, [lat, lng]: Place, stay?: number): Waypoint => ({ t, lat, lng, stay })
+
+/** The trip itself: the last day is the picture day (offset 0), the first is nine days before. */
+function japanDays(): DayPlan[] {
+ const day = (offset: number, points: Waypoint[]): DayPlan => ({ offset, utcOffset: JST, points })
+ return [
+ day(-9, [
+ at('08:40', P.gracery, 10),
+ at('09:30', P.sensoji, 90),
+ at('11:05', P.nakamise, 40),
+ at('11:50', P.asakusaStation, 5),
+ at('12:40', P.ginza, 70),
+ at('13:50', P.toyosuStation, 5),
+ at('14:00', P.teamlab, 120),
+ at('16:10', P.toyosuStation, 5),
+ at('17:00', P.shinjukuStation, 10),
+ at('17:15', P.gracery, 60),
+ at('19:00', P.shinjukuStation, 90),
+ at('21:00', P.gracery, 30),
+ ]),
+ day(-8, [
+ at('09:00', P.gracery, 10),
+ at('09:40', P.shibuya, 45),
+ at('10:40', P.harajuku, 30),
+ at('11:20', P.meiji, 75),
+ at('13:00', P.harajuku, 60),
+ at('14:30', P.shibuya, 90),
+ at('16:40', P.shinjukuStation, 10),
+ at('17:00', P.gracery, 240),
+ ]),
+ day(-7, [
+ at('09:10', P.gracery, 10),
+ at('10:00', P.ueno, 120),
+ at('12:30', P.akihabara, 100),
+ at('14:40', P.ginza, 120),
+ at('17:20', P.shinjukuStation, 10),
+ at('17:40', P.gracery, 200),
+ ]),
+ day(-6, [
+ at('08:30', P.gracery, 10),
+ at('09:20', P.tsukiji, 90),
+ at('11:30', P.tokyoTower, 80),
+ at('13:30', P.roppongi, 150),
+ at('16:40', P.shinjukuStation, 10),
+ at('17:00', P.gracery, 240),
+ ]),
+ day(-5, [
+ at('07:40', P.gracery, 10),
+ at('08:15', P.tokyoStation, 15),
+ at('08:48', P.shinYokohama, 1),
+ at('10:05', P.nagoya, 1),
+ at('10:45', P.kyotoStation, 20),
+ at('11:20', P.kanra, 120),
+ at('14:00', P.gion, 90),
+ at('16:20', P.kanra, 30),
+ at('17:00', P.fushimi, 150),
+ at('20:00', P.kanra, 60),
+ ]),
+ day(-4, [
+ at('08:30', P.kanra, 10),
+ at('09:30', P.togetsukyo, 30),
+ at('10:10', P.arashiyama, 60),
+ at('11:20', P.togetsukyo, 40),
+ at('12:30', P.nishiki, 90),
+ at('14:20', P.gion, 60),
+ at('15:40', P.kanra, 240),
+ ]),
+ day(-3, [
+ at('09:00', P.kanra, 10),
+ at('09:50', P.kiyomizu, 100),
+ at('11:50', P.yasaka, 40),
+ at('12:40', P.gion, 120),
+ at('15:00', P.heian, 60),
+ at('16:30', P.kanra, 240),
+ ]),
+ day(-2, [
+ at('08:20', P.kanra, 10),
+ at('08:45', P.kyotoStation, 15),
+ at('09:45', P.naraPark, 60),
+ at('11:00', P.todaiji, 90),
+ at('12:40', P.naraPark, 120),
+ at('15:30', P.kyotoStation, 10),
+ at('16:00', P.kanra, 200),
+ ]),
+ day(-1, [
+ at('09:00', P.kanra, 10),
+ at('09:50', P.nanzenji, 60),
+ at('11:00', P.philosophersPath, 45),
+ at('11:50', P.ginkakuji, 60),
+ at('13:20', P.nishiki, 90),
+ at('15:20', P.kanra, 240),
+ ]),
+ day(0, [
+ at('08:30', P.kanra, 30),
+ at('09:30', P.gion, 60),
+ at('11:00', P.nishiki, 60),
+ at('12:30', P.kanra, 60),
+ at('14:00', P.kyotoStation, 120),
+ ]),
+ ]
+}
+
+/**
+ * Five short trips in the year before the pictures, in countries the Atlas does
+ * not have yet: Portugal, Jordan, Czechia, South Korea and Taiwan. Jordan
+ * dwells at Petra long enough for the wishlist rule (250 m, 20 minutes).
+ */
+function worldDays(): DayPlan[] {
+ const day = (offset: number, utcOffset: number, points: Waypoint[]): DayPlan => ({ offset, utcOffset, points })
+ return [
+ // Portugal, spring
+ day(-158, 1, [
+ at('09:30', [38.7077, -9.1366], 60),
+ at('11:00', [38.7114, -9.13], 120),
+ at('14:00', [38.6979, -9.2065], 90),
+ at('15:50', [38.6916, -9.216], 60),
+ at('18:00', [38.7077, -9.1366], 120),
+ ]),
+ day(-157, 1, [
+ at('10:00', [41.1407, -8.611], 90),
+ at('12:00', [41.147, -8.6149], 60),
+ at('13:30', [41.1403, -8.6094], 120),
+ at('16:00', [41.1496, -8.6109], 120),
+ ]),
+ // Jordan, late winter
+ day(-205, 3, [
+ at('09:00', [31.9544, 35.9344], 90),
+ at('11:00', [31.9539, 35.9106], 120),
+ at('15:00', [31.717, 35.587], 150),
+ ]),
+ day(-204, 3, [
+ at('08:30', [30.3285, 35.4444], 90),
+ at('10:20', [30.3222, 35.4517], 120),
+ at('13:00', [30.3285, 35.4444], 60),
+ at('15:30', [29.576, 35.42], 180),
+ ]),
+ // Czechia, early summer
+ day(-100, 2, [
+ at('09:30', [50.0875, 14.4213], 90),
+ at('11:15', [50.0865, 14.4114], 45),
+ at('12:30', [50.0911, 14.4016], 150),
+ at('16:00', [50.0645, 14.4183], 90),
+ ]),
+ day(-99, 2, [
+ at('10:00', [50.0793, 14.4275], 120),
+ at('13:00', [50.0865, 14.4114], 60),
+ at('15:00', [50.0875, 14.4213], 120),
+ ]),
+ // South Korea and Taiwan, one journey last autumn
+ day(-300, 9, [
+ at('09:30', [37.5796, 126.977], 120),
+ at('12:00', [37.5826, 126.9831], 90),
+ at('14:30', [37.5636, 126.9856], 120),
+ at('17:30', [37.5512, 126.9882], 90),
+ ]),
+ day(-299, 9, [
+ at('10:00', [37.5563, 126.9236], 150),
+ at('14:00', [37.5796, 126.977], 90),
+ ]),
+ day(-297, 8, [
+ at('10:00', [25.0372, 121.4999], 60),
+ at('11:30', [25.0421, 121.5074], 120),
+ at('15:00', [25.0339, 121.5645], 120),
+ at('18:30', [25.088, 121.5245], 120),
+ ]),
+ day(-296, 8, [
+ at('10:30', [25.1096, 121.8446], 240),
+ at('16:00', [25.0421, 121.5074], 120),
+ ]),
+ ]
+}
+
+/** Deterministic jitter, so two runs produce the same recording. */
+function noise(seed: number): number {
+ const x = Math.sin(seed * 12.9898 + 78.233) * 43758.5453
+ return x - Math.floor(x)
+}
+
+function isoAt(dayIso: string, hhmm: string, utcOffset: number, plusSeconds = 0): string {
+ const [h, m] = hhmm.split(':').map(Number)
+ const local = Date.UTC(+dayIso.slice(0, 4), +dayIso.slice(5, 7) - 1, +dayIso.slice(8, 10), h, m)
+ return new Date(local - utcOffset * 3600_000 + plusSeconds * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z')
+}
+
+function minutes(hhmm: string): number {
+ const [h, m] = hhmm.split(':').map(Number)
+ return h * 60 + m
+}
+
+function shiftDay(baseDay: string, offset: number): string {
+ const d = new Date(`${baseDay}T00:00:00Z`)
+ d.setUTCDate(d.getUTCDate() + offset)
+ return d.toISOString().slice(0, 10)
+}
+
+function feature(lng: number, lat: number, timestamp: string, speed: number, seed: number): TrackFeature {
+ return {
+ type: 'Feature',
+ geometry: { type: 'Point', coordinates: [+lng.toFixed(6), +lat.toFixed(6)] },
+ properties: {
+ timestamp,
+ horizontal_accuracy: 4 + Math.round(noise(seed) * 8),
+ altitude: 20 + Math.round(noise(seed + 1) * 30),
+ speed: +speed.toFixed(2),
+ device_id: DAWARICH_DEVICE,
+ },
+ }
+}
+
+/** Turns one day's waypoints into a track: a point a minute while moving, one every five while staying. */
+function dayFeatures(dayIso: string, plan: DayPlan, seedBase: number): TrackFeature[] {
+ const out: TrackFeature[] = []
+ const pts = plan.points
+ let seed = seedBase
+ for (let i = 0; i < pts.length; i++) {
+ const here = pts[i]
+ const stay = here.stay ?? 0
+ const arrive = minutes(here.t)
+ for (let k = 0; k <= stay; k += 5) {
+ seed++
+ const wobble = 0.00012
+ out.push(
+ feature(
+ here.lng + (noise(seed) - 0.5) * wobble,
+ here.lat + (noise(seed + 7) - 0.5) * wobble,
+ isoAt(dayIso, here.t, plan.utcOffset, k * 60),
+ 0,
+ seed,
+ ),
+ )
+ }
+ const next = pts[i + 1]
+ if (!next) break
+ const leaveAt = arrive + stay
+ const travel = minutes(next.t) - leaveAt
+ if (travel <= 0) continue
+ // Moving: straight line with a little sway, a point a minute. Long hops
+ // (the Shinkansen) get thinned out so a day never exceeds Dawarich's page.
+ const step = travel > 60 ? 2 : 1
+ const km = Math.hypot((next.lat - here.lat) * 111, (next.lng - here.lng) * 91)
+ const speed = (km * 1000) / (travel * 60)
+ for (let m = step; m < travel; m += step) {
+ seed++
+ const f = m / travel
+ const sway = Math.sin(f * Math.PI) * 0.0008 * (noise(seed) - 0.5)
+ out.push(
+ feature(
+ here.lng + (next.lng - here.lng) * f + sway,
+ here.lat + (next.lat - here.lat) * f + sway,
+ isoAt(dayIso, here.t, plan.utcOffset, (stay + m) * 60),
+ speed,
+ seed,
+ ),
+ )
+ }
+ }
+ return out
+}
+
+/** The whole recording for a picture day: the trip's ten days plus the year before. */
+export function dawarichRecording(baseDay: string): { trip: TrackFeature[]; world: TrackFeature[] } {
+ const build = (plans: DayPlan[], seedBase: number) =>
+ plans.flatMap((plan, i) => dayFeatures(shiftDay(baseDay, plan.offset), plan, seedBase + i * 10_000))
+ return { trip: build(japanDays(), 1), world: build(worldDays(), 500_000) }
+}
+
+/** The UTC window one part of the recording covers, for checking whether it is already there. */
+export function recordingWindow(baseDay: string, part: 'trip' | 'world'): { from: string; to: string } {
+ const plans = part === 'trip' ? japanDays() : worldDays()
+ const offsets = plans.map(p => p.offset)
+ return { from: shiftDay(baseDay, Math.min(...offsets) - 1), to: shiftDay(baseDay, Math.max(...offsets) + 1) }
+}
diff --git a/client/e2e/help/external.ts b/client/e2e/help/external.ts
new file mode 100644
index 000000000..34db7e2dc
--- /dev/null
+++ b/client/e2e/help/external.ts
@@ -0,0 +1,290 @@
+import type { APIRequestContext } from '@playwright/test'
+import { day, PICTURE_DAY_ISO } from '../dates'
+import { dawarichRecording, recordingWindow, type TrackFeature } from './dawarich-track'
+
+/**
+ * The services outside TREK that a few guides need: an AirTrail with flights,
+ * a Dawarich with a recording, a Nextcloud with a folder of documents. Each is
+ * reached through its own API with the address and key from the environment
+ * (`e2e/help/media.env`, see README), and each fixture puts the service into
+ * the state the guide expects before TREK is connected to it. Nothing here is
+ * silent: a missing variable or an unreachable service fails the run rather
+ * than producing a picture of an empty panel.
+ *
+ * TREK's SSRF guard refuses loopback whatever the flags say, so every address
+ * has to be the machine's LAN address, and the media backend needs
+ * ALLOW_INTERNAL_NETWORK=true to reach it at all.
+ */
+
+function env(name: string): string {
+ const value = process.env[name]
+ if (!value) throw new Error(`${name} is not set; see client/e2e/help/README.md for the media.env the external guides need`)
+ return value.replace(/\/+$/, '')
+}
+
+async function expectOk(res: Response, what: string): Promise {
+ if (!res.ok) throw new Error(`${what}: HTTP ${res.status} ${await res.text()}`)
+ return res
+}
+
+// ── AirTrail ────────────────────────────────────────────────────────────────
+
+interface AirtrailWanted {
+ flightNumber: string
+ from: string
+ to: string
+ offset: number
+ departureTime: string
+ arrivalTime: string
+ airline: string
+ aircraft: string
+ seat: 'window' | 'aisle'
+ seatNumber: string
+}
+
+/**
+ * Two flights home on the trip's last day that connect in Tokyo, so the picker
+ * offers to import them as one flight with a layover, and the flights of the
+ * Lisbon weekend in spring for its "Other flights" list. LH716 out is already
+ * in the seed and would only be skipped as a duplicate, so it stays out.
+ */
+export const AIRTRAIL_FLIGHTS: AirtrailWanted[] = [
+ { flightNumber: 'NH16', from: 'ITM', to: 'HND', offset: 0, departureTime: '08:00', arrivalTime: '09:10', airline: 'ANA', aircraft: 'B789', seat: 'window', seatNumber: '12A' },
+ { flightNumber: 'LH717', from: 'HND', to: 'FRA', offset: 0, departureTime: '12:35', arrivalTime: '18:25', airline: 'DLH', aircraft: 'A359', seat: 'aisle', seatNumber: '31C' },
+ { flightNumber: 'TP573', from: 'FRA', to: 'LIS', offset: -158, departureTime: '10:20', arrivalTime: '12:25', airline: 'TAP', aircraft: 'A320', seat: 'window', seatNumber: '7F' },
+ { flightNumber: 'TP574', from: 'LIS', to: 'FRA', offset: -156, departureTime: '13:10', arrivalTime: '17:05', airline: 'TAP', aircraft: 'A320', seat: 'aisle', seatNumber: '9C' },
+]
+
+interface AirtrailFlightRow {
+ id: number
+ flightNumber: string | null
+ date: string
+ passengers?: { id: number; userId: string | null }[]
+ seats?: { id: number; userId: string | null }[]
+}
+
+/** Puts the wanted flights into the AirTrail account the key belongs to, once. */
+export async function ensureAirtrailFlights(): Promise {
+ const base = env('HELP_MEDIA_AIRTRAIL_URL')
+ const headers = { Authorization: `Bearer ${env('HELP_MEDIA_AIRTRAIL_API_KEY')}`, 'Content-Type': 'application/json' }
+ const listed = await expectOk(await fetch(`${base}/api/flight/list`, { headers }), 'AirTrail flight list')
+ const { flights } = (await listed.json()) as { flights: AirtrailFlightRow[] }
+ for (const wanted of AIRTRAIL_FLIGHTS) {
+ const date = day(wanted.offset)
+ const existing = flights.find(f => f.flightNumber === wanted.flightNumber)
+ if (existing && existing.date === date) continue
+ const owner = (existing?.passengers ?? existing?.seats ?? []).find(p => p.userId)
+ const body = {
+ ...(existing ? { id: existing.id } : {}),
+ from: wanted.from,
+ to: wanted.to,
+ departure: date,
+ departureTime: wanted.departureTime,
+ arrival: date,
+ arrivalTime: wanted.arrivalTime,
+ airline: wanted.airline,
+ flightNumber: wanted.flightNumber,
+ aircraft: wanted.aircraft,
+ passengers: [{ ...(owner ? { id: owner.id } : {}), userId: '', seat: wanted.seat, seatNumber: wanted.seatNumber, seatClass: 'economy', flightReason: 'leisure' }],
+ }
+ await expectOk(await fetch(`${base}/api/flight/save`, { method: 'POST', headers, body: JSON.stringify(body) }), `AirTrail save ${wanted.flightNumber}`)
+ }
+}
+
+/** Switches the addon on and connects the signed-in user to the AirTrail, loudly. */
+export async function ensureAirtrailConnection(api: APIRequestContext): Promise {
+ await ensureAirtrailFlights()
+ await toggleAddon(api, 'airtrail', true)
+ const saved = await api.put('/api/integrations/airtrail/settings', {
+ data: { url: env('HELP_MEDIA_AIRTRAIL_URL'), apiKey: env('HELP_MEDIA_AIRTRAIL_API_KEY') },
+ })
+ if (!saved.ok()) throw new Error(`could not save the AirTrail connection: ${saved.status()} ${await saved.text()}`)
+ const status = await api.get('/api/integrations/airtrail/status')
+ const body = (await status.json()) as { connected: boolean; error?: string }
+ if (!body.connected) throw new Error(`AirTrail is not reachable from the media backend: ${body.error ?? status.status()} (is ALLOW_INTERNAL_NETWORK=true?)`)
+}
+
+export async function disconnectAirtrail(api: APIRequestContext): Promise {
+ await api.put('/api/integrations/airtrail/settings', { data: { url: '' } })
+ await toggleAddon(api, 'airtrail', false)
+}
+
+// ── Dawarich ────────────────────────────────────────────────────────────────
+
+/** Uploads the synthetic recording, one part at a time, unless its window already holds points. */
+export async function ensureDawarichRecording(): Promise {
+ const base = env('HELP_MEDIA_DAWARICH_URL')
+ const key = env('HELP_MEDIA_DAWARICH_API_KEY')
+ const recording = dawarichRecording(PICTURE_DAY_ISO)
+ for (const part of ['world', 'trip'] as const) {
+ const { from, to } = recordingWindow(PICTURE_DAY_ISO, part)
+ const probe = await expectOk(
+ await fetch(`${base}/api/v1/points?start_at=${from}&end_at=${to}&per_page=1`, { headers: { Authorization: `Bearer ${key}` } }),
+ `Dawarich points ${part}`,
+ )
+ if (Number(probe.headers.get('x-total-pages') ?? 0) > 0) continue
+ const features = recording[part]
+ for (let i = 0; i < features.length; i += 500) {
+ const batch: TrackFeature[] = features.slice(i, i + 500)
+ await expectOk(
+ await fetch(`${base}/api/v1/points?api_key=${key}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ locations: batch }),
+ }),
+ `Dawarich upload ${part} batch ${i / 500 + 1}`,
+ )
+ }
+ }
+}
+
+/** Two wishes the recording reaches, with coordinates so the scan can match them. */
+export const DAWARICH_WISHES = [
+ { name: 'Fushimi Inari Taisha', lat: 34.9671, lng: 135.7727, country_code: 'JP' },
+ { name: 'Wadi Rum', lat: 29.576, lng: 35.42, country_code: 'JO' },
+]
+
+/**
+ * Switches the addon on, connects the signed-in user to the Dawarich and adds
+ * the wishes. Automatic syncing stays off: a sync would seed suggestion rows
+ * that head the Places column of every later picture.
+ */
+export async function ensureDawarichConnection(api: APIRequestContext): Promise {
+ await ensureDawarichRecording()
+ await toggleAddon(api, 'dawarich', true)
+ const saved = await api.put('/api/integrations/dawarich/settings', {
+ data: { url: env('HELP_MEDIA_DAWARICH_URL'), apiKey: env('HELP_MEDIA_DAWARICH_API_KEY'), allowInsecureTls: false, syncEnabled: false },
+ })
+ if (!saved.ok()) throw new Error(`could not save the Dawarich connection: ${saved.status()} ${await saved.text()}`)
+ // The probe wants the address in its body; the key it takes from the connection just saved.
+ const test = await api.post('/api/integrations/dawarich/test', { data: { url: env('HELP_MEDIA_DAWARICH_URL'), allowInsecureTls: false } })
+ const body = (await test.json()) as { connected: boolean; error?: string; errorDetail?: string }
+ if (!body.connected) throw new Error(`Dawarich is not reachable from the media backend: ${body.error ?? ''} ${body.errorDetail ?? ''} (is ALLOW_INTERNAL_NETWORK=true?)`)
+
+ const listRes = await api.get('/api/addons/atlas/bucket-list')
+ const { items } = (await listRes.json()) as { items: { name: string }[] }
+ for (const wish of DAWARICH_WISHES) {
+ if (items.some(i => i.name === wish.name)) continue
+ const created = await api.post('/api/addons/atlas/bucket-list', { data: wish })
+ if (!created.ok()) throw new Error(`could not add the ${wish.name} wish: ${created.status()} ${await created.text()}`)
+ }
+}
+
+export async function disconnectDawarich(api: APIRequestContext): Promise {
+ await api.delete('/api/integrations/dawarich/settings')
+ await toggleAddon(api, 'dawarich', false)
+}
+
+// ── Nextcloud ───────────────────────────────────────────────────────────────
+
+export const NEXTCLOUD_BASE_PATH = '/Reisen'
+export const NEXTCLOUD_FOLDER = 'Autumn in Japan'
+export const NEXTCLOUD_DOCUMENTS = ['ryokan-invoice.pdf', 'shinkansen-eticket.pdf']
+
+function davRoot(): { url: string; auth: string } {
+ const url = `${env('HELP_MEDIA_NEXTCLOUD_URL')}/remote.php/dav/files/${env('HELP_MEDIA_NEXTCLOUD_USER')}`
+ const auth = 'Basic ' + Buffer.from(`${env('HELP_MEDIA_NEXTCLOUD_USER')}:${env('HELP_MEDIA_NEXTCLOUD_PASSWORD')}`).toString('base64')
+ return { url, auth }
+}
+
+async function dav(method: string, path: string, body?: BodyInit, extra: Record = {}): Promise {
+ const { url, auth } = davRoot()
+ const target = url + path.split('/').map(encodeURIComponent).join('/')
+ return fetch(target, { method, headers: { Authorization: auth, ...extra }, body })
+}
+
+/**
+ * The store side of the document-sync guide: a base folder with one trip
+ * folder holding two documents and nothing else, however the last run left it.
+ * `pdf` draws the documents, so this file stays free of binary fixtures.
+ */
+export async function ensureNextcloudFolder(pdf: (title: string, lines: string[]) => Buffer): Promise {
+ const folder = `${NEXTCLOUD_BASE_PATH}/${NEXTCLOUD_FOLDER}`
+ for (const dir of [NEXTCLOUD_BASE_PATH, folder]) {
+ const made = await dav('MKCOL', `${dir}/`)
+ if (![201, 405].includes(made.status)) throw new Error(`Nextcloud MKCOL ${dir}: HTTP ${made.status} ${await made.text()}`)
+ }
+ const listing = await dav('PROPFIND', `${folder}/`, undefined, { Depth: '1' })
+ if (listing.status !== 207) throw new Error(`Nextcloud PROPFIND ${folder}: HTTP ${listing.status}`)
+ const names = [...(await listing.text()).matchAll(/([^<]+)<\/d:href>/g)]
+ .map(m => decodeURIComponent(m[1]).replace(/\/$/, '').split('/').pop() ?? '')
+ .filter(n => n && n !== NEXTCLOUD_FOLDER)
+ for (const name of names) {
+ if (NEXTCLOUD_DOCUMENTS.includes(name)) continue
+ const gone = await dav('DELETE', `${folder}/${name}`)
+ if (![204, 404].includes(gone.status)) throw new Error(`Nextcloud DELETE ${name}: HTTP ${gone.status}`)
+ }
+ const documents: Record = {
+ 'ryokan-invoice.pdf': ['Hakone Ginyu, invoice 2026-0918', 'Two nights, two guests, half board', 'JPY 96,000, paid by card'],
+ 'shinkansen-eticket.pdf': ['Nozomi 21, Tokyo to Kyoto', 'Car 7, seats 12A and 12B', 'Reserved, non-smoking'],
+ }
+ for (const name of NEXTCLOUD_DOCUMENTS) {
+ if (names.includes(name)) continue
+ const bytes = pdf(name.replace(/\.pdf$/, ''), documents[name])
+ const body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer
+ const put = await dav('PUT', `${folder}/${name}`, body, { 'Content-Type': 'application/pdf' })
+ if (![201, 204].includes(put.status)) throw new Error(`Nextcloud PUT ${name}: HTTP ${put.status} ${await put.text()}`)
+ }
+}
+
+export const NEXTCLOUD_CONNECTION = () => ({
+ providerId: 'nextcloud',
+ baseUrl: env('HELP_MEDIA_NEXTCLOUD_URL'),
+ credentials: { login_name: env('HELP_MEDIA_NEXTCLOUD_USER'), app_password: env('HELP_MEDIA_NEXTCLOUD_PASSWORD'), base_path: NEXTCLOUD_BASE_PATH },
+ allowInsecureTls: false,
+})
+
+/** Takes every binding and connection off the trip, keeping the documents. */
+export async function resetDocSync(api: APIRequestContext, tripId: number): Promise {
+ const links = await api.get(`/api/trips/${tripId}/docsync/links`)
+ if (links.ok()) {
+ const body = (await links.json()) as { links?: { id: number }[] } | { id: number }[]
+ for (const link of Array.isArray(body) ? body : (body.links ?? [])) await api.delete(`/api/trips/${tripId}/docsync/links/${link.id}`)
+ }
+ const connections = await api.get(`/api/trips/${tripId}/docsync/connections`)
+ if (connections.ok()) {
+ const body = (await connections.json()) as { connections?: { id: number }[] } | { id: number }[]
+ for (const c of Array.isArray(body) ? body : (body.connections ?? [])) await api.delete(`/api/trips/${tripId}/docsync/connections/${c.id}`)
+ }
+}
+
+// ── Booking extractor ────────────────────────────────────────────────────────
+
+/**
+ * Import from file is rendered only when the server can read a confirmation.
+ * The media run gets that from the extractor named in media.env
+ * (KITINERARY_EXTRACTOR_PATH, see README). The AI Parsing addon would show
+ * the button too, but with no model behind it every parse ends in a red card,
+ * so the guides ask for the extractor and nothing else.
+ */
+export async function requireExtractor(api: APIRequestContext): Promise {
+ const res = await api.get('/api/health/features')
+ const body = (await res.json()) as { bookingImport?: boolean }
+ if (!body.bookingImport) {
+ throw new Error('the booking extractor is not available to the media backend: set KITINERARY_EXTRACTOR_PATH in e2e/help/media.env (see README)')
+ }
+}
+
+/**
+ * The review attaches the confirmation to the booking it made through the
+ * ordinary file upload, and that upload honours the administrator's Allowed
+ * File Types, which do not include a mail out of the box: the booking is
+ * saved and the .eml dropped without a word. So the list gets `eml` for the
+ * import guides and loses it again in their cleanup. Idempotent either way.
+ */
+export async function allowEmlUploads(api: APIRequestContext, allowed: boolean): Promise {
+ const current = await api.get('/api/auth/app-settings')
+ const { allowed_file_types = '' } = (await current.json()) as { allowed_file_types?: string }
+ const types = allowed_file_types.split(',').map(t => t.trim().toLowerCase()).filter(Boolean)
+ if (types.includes('eml') === allowed) return
+ const next = allowed ? [...types, 'eml'] : types.filter(t => t !== 'eml')
+ const res = await api.put('/api/auth/app-settings', { data: { allowed_file_types: next.join(',') } })
+ if (!res.ok()) throw new Error(`could not ${allowed ? 'allow' : 'disallow'} .eml uploads: ${res.status()} ${await res.text()}`)
+}
+
+// ── shared ──────────────────────────────────────────────────────────────────
+
+export async function toggleAddon(api: APIRequestContext, id: string, enabled: boolean): Promise {
+ const res = await api.put(`/api/admin/addons/${id}`, { data: { enabled } })
+ if (!res.ok()) throw new Error(`could not switch addon ${id} ${enabled ? 'on' : 'off'}: ${res.status()} ${await res.text()}`)
+}
diff --git a/client/e2e/help/fixtures.ts b/client/e2e/help/fixtures.ts
index 86c3f9caa..8fc38970c 100644
--- a/client/e2e/help/fixtures.ts
+++ b/client/e2e/help/fixtures.ts
@@ -5,6 +5,7 @@ import { gzipSync } from 'node:zlib'
import { request as apiRequest, type APIRequestContext, type Page } from '@playwright/test'
import { E2E_BASE_URL } from '../../playwright.config'
import { OUT_DIR, PICTURE_DAY } from './guide'
+import { at, day, emlDate, mailHeaderDate, short } from '../dates'
/**
* What the dashboard guides act on beyond the seeded trip.
@@ -17,8 +18,8 @@ import { OUT_DIR, PICTURE_DAY } from './guide'
*/
export const EXTRA_TRIPS = [
- { title: 'Weekend in Lisbon', description: 'Pastéis, miradouros and a day trip to Sintra.', start_date: '2026-10-16', end_date: '2026-10-18', currency: 'EUR' },
- { title: 'Norway Road Trip', description: 'Bergen to the Lofoten, fjord by fjord.', start_date: '2027-06-05', end_date: '2027-06-19', currency: 'NOK' },
+ { title: 'Weekend in Lisbon', description: 'Pastéis, miradouros and a day trip to Sintra.', start_date: day(25), end_date: day(27), currency: 'EUR' },
+ { title: 'Norway Road Trip', description: 'Bergen to the Lofoten, fjord by fjord.', start_date: day(257), end_date: day(271), currency: 'NOK' },
]
export async function ensureExtraTrips(api: APIRequestContext): Promise {
@@ -145,7 +146,7 @@ const ENTRIES = [
/** A second, future journey, so the list has a card below the banner. */
export const SECOND_JOURNEY = { title: 'Fjords and ferries', subtitle: 'Norway, next summer', trip: 'Norway Road Trip' }
/** A trip no journey has claimed, for the guide that links one. */
-export const SPARE_TRIP = { title: 'Alps by rail', description: 'Zurich to Venice over the Bernina.', start_date: '2027-02-12', end_date: '2027-02-19', currency: 'CHF' }
+export const SPARE_TRIP = { title: 'Alps by rail', description: 'Zurich to Venice over the Bernina.', start_date: day(144), end_date: day(151), currency: 'CHF' }
export async function ensureJourneyFixtures(api: APIRequestContext): Promise {
const listRes = await api.get('/api/journeys')
@@ -211,9 +212,9 @@ const SCHOOL_REGION = {
name: 'Bavaria',
revision: 0,
holidays: [
- { name: 'Autumn break', startDate: '2026-11-02', endDate: '2026-11-06' },
- { name: 'Christmas break', startDate: '2026-12-24', endDate: '2027-01-06' },
- { name: 'Easter break', startDate: '2027-03-29', endDate: '2027-04-09' },
+ { name: 'Autumn break', startDate: day(42), endDate: day(46) },
+ { name: 'Christmas break', startDate: day(94), endDate: day(107) },
+ { name: 'Easter break', startDate: day(189), endDate: day(200) },
],
}
@@ -414,7 +415,7 @@ export async function ensureDaysFixtures(api: APIRequestContext): Promise
await api.post(`/api/trips/${tripId}/reservations`, {
data: {
title: 'Lunch at Nishiki', type: 'restaurant', status: 'confirmed', day_id: dayIds[5],
- place_id: market.place_id, assignment_id: market.id, reservation_time: '2026-09-17T12:30:00', confirmation_number: 'NK-2211',
+ place_id: market.place_id, assignment_id: market.id, reservation_time: at(-4, '12:30'), confirmation_number: 'NK-2211',
},
})
}
@@ -424,11 +425,11 @@ export async function ensureDaysFixtures(api: APIRequestContext): Promise
await api.post(`/api/trips/${tripId}/reservations`, {
data: {
title: 'Nozomi 21 Tokyo → Kyoto', type: 'train', status: 'confirmed', location: 'Tokyo Station',
- reservation_time: '2026-09-16T08:30:00', reservation_end_time: '2026-09-16T10:45:00', confirmation_number: 'JR-58204',
+ reservation_time: at(-5, '08:30'), reservation_end_time: at(-5, '10:45'), confirmation_number: 'JR-58204',
metadata: { train_number: 'Nozomi 21', platform: '17', seat: '8A' },
endpoints: [
- { role: 'from', sequence: 0, name: 'Tokyo Station', lat: 35.6812, lng: 139.7671, timezone: 'Asia/Tokyo', local_date: '2026-09-16', local_time: '08:30' },
- { role: 'to', sequence: 1, name: 'Kyoto Station', lat: 34.9858, lng: 135.7588, timezone: 'Asia/Tokyo', local_date: '2026-09-16', local_time: '10:45' },
+ { role: 'from', sequence: 0, name: 'Tokyo Station', lat: 35.6812, lng: 139.7671, timezone: 'Asia/Tokyo', local_date: day(-5), local_time: '08:30' },
+ { role: 'to', sequence: 1, name: 'Kyoto Station', lat: 34.9858, lng: 135.7588, timezone: 'Asia/Tokyo', local_date: day(-5), local_time: '10:45' },
],
},
})
@@ -484,7 +485,9 @@ export async function ensureDaysFixtures(api: APIRequestContext): Promise
* What the place card needs beyond the seed: a website on one place so the
* footer offers Open Website at all, a note on the first stop so the card can
* show Notes for this day, and two other travellers' star votes so the rating
- * row has an average and a voter list rather than one lonely face.
+ * row has an average and a voter list rather than one lonely face. An
+ * OpenStreetMap id on three places, so the card shows real hours, a ring and a
+ * phone number; see OSM_PLACES.
*
* The votes are cast as the members themselves. A login on the shared context
* would set the trek_session cookie on it, and the server reads that cookie
@@ -504,9 +507,132 @@ const MEMBER_VOTES = [
{ username: 'jonas', email: 'jonas@example.com', password: 'DemoSeed12345!', rating: 4 },
]
+/**
+ * The OpenStreetMap element behind three of the seeded places, so their cards
+ * show what a place picked from the search shows: the hours, the Open or
+ * Closed ring, the phone number and the website. The seed posts bare rows, and
+ * a place with neither a Google nor an OpenStreetMap id asks no provider at
+ * all (PlaceInspector's usePlaceDetails), which is why every picture of the
+ * card had been without them.
+ *
+ * The id is looked up at run time through TREK's own autocomplete, which
+ * answers from the OpenStreetMap layer of the TREK index, so a re-mapped
+ * element does not quietly blank the picture; the id written here is the
+ * fallback for when the index is unreachable or names something else. Every
+ * candidate is then asked from the details route, the call the card makes,
+ * and only one that answers with a week of hours is written. Senso-ji is the
+ * place the read-place guide pictures, so a run that cannot get its hours and
+ * phone number fails here rather than promoting a picture of a card without
+ * the feature the text describes; the other two only make their own guides'
+ * cards look like a real place's, so a thin answer is warned about and the
+ * id kept.
+ *
+ * Nishiki Market is left out on purpose: its OpenStreetMap hours ("Mo-Su,PH
+ * 10:00-18:00+") are a shape the server's parser rejects, and Fushimi Inari
+ * and Meiji Jingu carry no hours tag at all.
+ */
+interface OsmPlace {
+ /** The seeded place's name. */
+ place: string
+ /** What the resolver types into the autocomplete. */
+ query: string
+ /** What the suggestion's name has to contain, letters and digits only. */
+ key: string
+ /** The element the last probe found, used when the index cannot say. */
+ osmId: string
+ /** Whether the answer has to carry a phone number as well as the hours. */
+ phone: boolean
+ /** Fail the run when the details do not come; otherwise warn and keep the id. */
+ strict: boolean
+}
+
+export const OSM_PLACES: OsmPlace[] = [
+ { place: 'Senso-ji Temple', query: 'Senso-ji', key: 'sensoji', osmId: 'way:173154847', phone: true, strict: true },
+ { place: 'teamLab Planets', query: 'teamLab Planets', key: 'teamlab', osmId: 'node:6291685287', phone: false, strict: false },
+ { place: 'Arashiyama Bamboo Grove', query: 'Arashiyama Bamboo Grove', key: 'bamboo', osmId: 'relation:17656638', phone: false, strict: false },
+]
+
+/** The id form the details route resolves (maps.helpers.ts OSM_PLACE_ID). */
+const OSM_PLACE_ID = /^(node|way|relation):\d+$/
+
+/** Letters and digits, diacritics dropped: "Sensō-ji" and "Senso-ji Temple" both open with "sensoji". */
+const plain = (value: string): string =>
+ value.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]/g, '')
+
+/** Metres between two pins; flat arithmetic is exact enough for a few hundred of them. */
+function metresApart(a: { lat: number; lng: number }, b: { lat: number; lng: number }): number {
+ const dLat = (b.lat - a.lat) * 111_320
+ const dLng = (b.lng - a.lng) * 111_320 * Math.cos(((a.lat + b.lat) / 2) * (Math.PI / 180))
+ return Math.hypot(dLat, dLng)
+}
+
+interface Suggestion {
+ placeId: string
+ mainText: string
+ source?: string
+ lat?: number
+ lng?: number
+}
+
+/**
+ * The element the index knows the place by: an OpenStreetMap row of TREK's own
+ * autocomplete, biased to the seed's pin, called like the place and within a
+ * few hundred metres of it. Undefined when the index is unreachable or names
+ * nothing that is this place; the caller then falls back to the written id.
+ */
+async function resolveOsmId(api: APIRequestContext, wanted: OsmPlace, pin: { lat: number; lng: number }): Promise {
+ const res = await api.post('/api/maps/autocomplete', {
+ data: {
+ input: wanted.query,
+ locationBias: { low: { lat: pin.lat - 0.02, lng: pin.lng - 0.02 }, high: { lat: pin.lat + 0.02, lng: pin.lng + 0.02 } },
+ },
+ })
+ if (!res.ok()) return undefined
+ const body = (await res.json()) as { suggestions?: Suggestion[] }
+ return (body.suggestions ?? []).find(
+ s =>
+ s.source === 'openstreetmap'
+ && OSM_PLACE_ID.test(s.placeId)
+ && plain(s.mainText).includes(wanted.key)
+ && typeof s.lat === 'number'
+ && typeof s.lng === 'number'
+ && metresApart(pin, { lat: s.lat, lng: s.lng }) < 600,
+ )?.placeId
+}
+
+interface ProviderDetails {
+ opening_hours?: string[] | null
+ phone?: string | null
+}
+
+/** Whether a details answer carries what the card is to show for this place. */
+const complete = (details: ProviderDetails | null, wanted: OsmPlace): boolean =>
+ !!details
+ && Array.isArray(details.opening_hours)
+ && details.opening_hours.length === 7
+ && (!wanted.phone || (typeof details.phone === 'string' && details.phone.length > 0))
+
+/**
+ * What the card would get for this id, asked the way the card asks it. The
+ * OpenStreetMap path has no server-side cache and Overpass is regularly
+ * overloaded, so a thin answer is asked again twice before it counts.
+ */
+async function providerDetails(api: APIRequestContext, osmId: string, wanted: OsmPlace): Promise {
+ for (let attempt = 1; ; attempt++) {
+ const res = await api.get(`/api/maps/details/${encodeURIComponent(osmId)}?lang=en`)
+ const body = res.ok() ? ((await res.json()) as { place: ProviderDetails | null; disabled?: boolean }) : null
+ if (body?.disabled) throw new Error('Place Details is switched off in the admin settings, so no card gets hours')
+ if (complete(body?.place ?? null, wanted) || attempt === 3) return body?.place ?? null
+ await new Promise(resolve => setTimeout(resolve, 2_000))
+ }
+}
+
type FixturePlace = {
id: number
name: string
+ lat?: number | null
+ lng?: number | null
+ osm_id?: string | null
website?: string | null
ratings?: { username?: string | null }[] | null
}
@@ -525,6 +651,33 @@ export async function ensurePlaceFixtures(api: APIRequestContext): Promise
if (!res.ok()) throw new Error(`could not set the website on ${PLACE_WEBSITE.place}: ${res.status()} ${await res.text()}`)
}
+ // An OpenStreetMap identity on three places, the same PUT: the card then asks
+ // the details route for the hours, the ring and the phone number.
+ for (const wanted of OSM_PLACES) {
+ const place = byName(wanted.place)
+ if (!place || typeof place.lat !== 'number' || typeof place.lng !== 'number') continue
+ const pin = { lat: place.lat, lng: place.lng }
+ const resolved = await resolveOsmId(api, wanted, pin)
+ const candidates = [...new Set([resolved, wanted.osmId].filter((id): id is string => !!id))]
+ let chosen: string | undefined
+ for (const id of candidates) {
+ if (complete(await providerDetails(api, id, wanted), wanted)) {
+ chosen = id
+ break
+ }
+ }
+ if (!chosen) {
+ const what = `${wanted.place}: the details route gives no week of opening hours${wanted.phone ? ' and no phone number' : ''} for ${candidates.join(' or ')}`
+ if (wanted.strict) throw new Error(what)
+ console.warn(`${what}; keeping the id, the card shows what there is`)
+ chosen = candidates[0]
+ }
+ if (place.osm_id !== chosen) {
+ const res = await api.put(`/api/trips/${tripId}/places/${place.id}`, { data: { osm_id: chosen } })
+ if (!res.ok()) throw new Error(`could not set the OpenStreetMap id on ${wanted.place}: ${res.status()} ${await res.text()}`)
+ }
+ }
+
// A note that belongs to the stop rather than to the place, which is the one
// box of the card no other guide reaches.
const noted = byName(STOP_NOTE.place)
@@ -616,7 +769,7 @@ export async function ensureDayDetailFixtures(api: APIRequestContext): Promise {
const created = await api.post(`/api/trips/${tripId}/reservations`, {
data: {
title: 'Nozomi 21 Tokyo → Kyoto', type: 'train', status: 'confirmed', location: 'Tokyo Station',
- reservation_time: '2026-09-16T08:30:00', reservation_end_time: '2026-09-16T10:45:00', confirmation_number: 'JR-58204',
+ reservation_time: at(-5, '08:30'), reservation_end_time: at(-5, '10:45'), confirmation_number: 'JR-58204',
metadata: { train_number: 'Nozomi 21', platform: '17', seat: '8A' },
// Both ends need coordinates or the endpoints are dropped and the booking
// draws nothing at all.
endpoints: [
- { role: 'from', sequence: 0, name: 'Tokyo Station', lat: 35.6812, lng: 139.7671, timezone: 'Asia/Tokyo', local_date: '2026-09-16', local_time: '08:30' },
- { role: 'to', sequence: 1, name: 'Kyoto Station', lat: 34.9858, lng: 135.7588, timezone: 'Asia/Tokyo', local_date: '2026-09-16', local_time: '10:45' },
+ { role: 'from', sequence: 0, name: 'Tokyo Station', lat: 35.6812, lng: 139.7671, timezone: 'Asia/Tokyo', local_date: day(-5), local_time: '08:30' },
+ { role: 'to', sequence: 1, name: 'Kyoto Station', lat: 34.9858, lng: 135.7588, timezone: 'Asia/Tokyo', local_date: day(-5), local_time: '10:45' },
],
},
})
@@ -698,11 +851,11 @@ export async function ensureTransportFixtures(api: APIRequestContext): Promise,
+ html: string[],
+): string {
const dir = path.join(process.cwd(), 'e2e', '.tmp')
mkdirSync(dir, { recursive: true })
- const file = path.join(dir, 'gracery-confirmation.eml')
- if (existsSync(file)) return file
- writeFileSync(
- file,
- [
- 'From: reservations@example-hotels.test',
- 'To: admin@trek.local',
- 'Subject: Your reservation is confirmed - Hotel Granvia Kyoto',
- 'Date: Tue, 1 Sep 2026 09:12:00 +0900',
- 'MIME-Version: 1.0',
- 'Content-Type: text/plain; charset=utf-8',
- '',
- 'Booking reference: GRK-40218',
- 'Hotel Granvia Kyoto, Shiokoji-sagaru, Karasuma-dori, Shimogyo-ku, Kyoto',
- 'Check-in: Wednesday 16 September 2026, from 15:00',
- 'Check-out: Saturday 19 September 2026, until 11:00',
- 'Guests: 2 Room: Twin, non-smoking',
- 'Total: JPY 84000',
- '',
- ].join('\r\n'),
- 'utf8',
- )
+ const file = path.join(dir, name)
+ const mail = [
+ `From: ${headers.from}`,
+ 'To: admin@trek.local',
+ `Subject: ${headers.subject}`,
+ `Date: ${headers.date}`,
+ 'MIME-Version: 1.0',
+ 'Content-Type: text/html; charset=utf-8',
+ 'Content-Transfer-Encoding: 7bit',
+ '',
+ '',
+ '',
+ `${headers.subject}`,
+ '',
+ '',
+ ...html,
+ '',
+ '',
+ ].join('\n')
+ // One line ending for the whole mail, headers and body alike.
+ writeFileSync(file, mail.replace(/\r?\n/g, '\r\n'), 'utf8')
return file
}
+/**
+ * The hotel confirmation the Bookings import guide hands to the extractor:
+ * the Granvia stay `booking-hotel` books by hand, nights 5 to 8 of the trip,
+ * as a LodgingReservation with the address, the coordinates, the phone, the
+ * website and the price, everything `mapLodging` and the review form read.
+ * The venue name is the trip place `ensureBookingsFixtures` creates, so the
+ * form pre-selects it under Accommodation.
+ */
+export function bookingEmlFixture(): string {
+ return emlFixture(
+ BOOKING_EML,
+ {
+ from: 'reservations@example-hotels.test',
+ subject: `Your reservation is confirmed - ${HOTEL_TO_BOOK.name}`,
+ date: mailHeaderDate(-20, '09:12', '+0900'),
+ },
+ {
+ '@context': 'http://schema.org',
+ '@type': 'LodgingReservation',
+ reservationNumber: 'GRK-40218',
+ reservationStatus: 'http://schema.org/ReservationConfirmed',
+ underName: { '@type': 'Person', name: 'Mira Lindberg' },
+ reservationFor: {
+ '@type': 'LodgingBusiness',
+ name: HOTEL_TO_BOOK.name,
+ address: {
+ '@type': 'PostalAddress',
+ streetAddress: 'Shiokoji-sagaru, Karasuma-dori',
+ addressLocality: 'Kyoto',
+ postalCode: '600-8216',
+ addressCountry: 'JP',
+ },
+ geo: { '@type': 'GeoCoordinates', latitude: HOTEL_TO_BOOK.lat, longitude: HOTEL_TO_BOOK.lng },
+ telephone: '+81 75 344 8888',
+ url: 'https://www.granviakyoto.example/',
+ },
+ checkinTime: `${at(-5, '15:00')}+09:00`,
+ checkoutTime: `${at(-2, '11:00')}+09:00`,
+ totalPrice: '84000',
+ priceCurrency: 'JPY',
+ },
+ [
+ '
Dear Ms Lindberg,
',
+ `
Thank you for choosing ${HOTEL_TO_BOOK.name}. Your reservation is confirmed.
`,
+ ],
+ )
+}
+
+/**
+ * The flight the Transports import guide reads: the way home on the trip's
+ * last day, Haneda to Frankfurt. The seed's own flight is LH716 out, and the
+ * AirTrail fixture brings LH717 and NH16 back, so this one is none of those.
+ * The mapper builds the title from airline and number, so a guide finds the
+ * card by the booking code, which is the fixture's own.
+ */
+export const FLIGHT_TO_IMPORT = {
+ airline: 'All Nippon Airways',
+ iata: 'NH',
+ number: '203',
+ code: 'NH9M4LT',
+ from: { iata: 'HND', name: 'Tokyo Haneda International Airport', city: 'Tokyo Haneda' },
+ to: { iata: 'FRA', name: 'Frankfurt Main Airport', city: 'Frankfurt' },
+}
+
+/**
+ * The e-ticket as a FlightReservation: both airports by IATA code, which
+ * `mapFlight` resolves through the built-in airport table, so the review opens
+ * Add transport with both ends placed; departure in Tokyo's offset, arrival
+ * in Frankfurt's, both on the last day of the trip.
+ */
+export function flightEmlFixture(): string {
+ const f = FLIGHT_TO_IMPORT
+ return emlFixture(
+ FLIGHT_EML,
+ {
+ from: 'eticket@example-airlines.test',
+ subject: `Your e-ticket itinerary - ${f.iata} ${f.number} ${f.from.city} to ${f.to.city}`,
+ date: mailHeaderDate(-30, '14:40', '+0900'),
+ },
+ {
+ '@context': 'http://schema.org',
+ '@type': 'FlightReservation',
+ reservationNumber: f.code,
+ reservationStatus: 'http://schema.org/ReservationConfirmed',
+ underName: { '@type': 'Person', name: 'Mira Lindberg' },
+ reservationFor: {
+ '@type': 'Flight',
+ flightNumber: f.number,
+ airline: { '@type': 'Airline', name: f.airline, iataCode: f.iata },
+ departureAirport: { '@type': 'Airport', name: f.from.name, iataCode: f.from.iata },
+ departureTime: `${at(0, '11:20')}+09:00`,
+ arrivalAirport: { '@type': 'Airport', name: f.to.name, iataCode: f.to.iata },
+ arrivalTime: `${at(0, '17:05')}+02:00`,
+ },
+ },
+ [
+ '
Dear Ms Lindberg,
',
+ `
Your booking ${f.code} is confirmed. This is your e-ticket itinerary.
',
+ ],
+ )
+}
+
/** One card of every type the Bookings tab can hold, by title. */
interface BookingFixture {
title: string
@@ -841,32 +1136,32 @@ const BOOKING_FIXTURES: BookingFixture[] = [
{
// No place on purpose: picking one is what `link-booking` does.
title: 'teamLab Planets timed entry', type: 'event', status: 'pending', place: null,
- reservation_time: '2026-09-12T14:00:00', reservation_end_time: '2026-09-12T16:00:00',
+ reservation_time: at(-9, '14:00'), reservation_end_time: at(-9, '16:00'),
confirmation_number: 'TL-88213', location: '6-1-16 Toyosu, Koto City, Tokyo',
url: 'https://www.teamlab.art/e/planets/',
notes: 'Barefoot from the entrance. Bring shorts, the water room is knee-deep.',
},
{
title: 'Fushimi Inari night walk', type: 'tour', status: 'confirmed', place: 'Fushimi Inari Taisha',
- reservation_time: '2026-09-16T18:30:00', reservation_end_time: '2026-09-16T21:00:00',
+ reservation_time: at(-5, '18:30'), reservation_end_time: at(-5, '21:00'),
confirmation_number: 'KY-4471', location: '68 Fukakusa Yabunouchicho, Fushimi Ward, Kyoto',
url: null, notes: null,
},
{
title: 'Kyoto Cycling Tour', type: 'tour', status: 'pending', place: null,
- reservation_time: '2026-09-18T09:30:00', reservation_end_time: '2026-09-18T13:00:00',
+ reservation_time: at(-3, '09:30'), reservation_end_time: at(-3, '13:00'),
confirmation_number: 'KCT-1177', location: 'Kyoto Station, Karasuma exit',
url: null, notes: null,
},
{
title: 'Haneda Airport P4', type: 'parking', status: 'pending', place: null,
- reservation_time: '2026-09-12T10:00:00', reservation_end_time: '2026-09-21T22:00:00',
+ reservation_time: at(-9, '10:00'), reservation_end_time: at(0, '22:00'),
confirmation_number: 'HP4-2209', location: 'Haneda Airport Terminal 3, Ota City, Tokyo',
url: null, notes: null,
},
{
title: 'Luggage forwarding to Kyoto', type: 'other', status: 'pending', place: null,
- reservation_time: '2026-09-16T09:00:00', reservation_end_time: null,
+ reservation_time: at(-5, '09:00'), reservation_end_time: null,
confirmation_number: 'YMT-30915', location: 'Takkyubin counter, Shinjuku',
url: null, notes: 'Two suitcases, delivered by 17:00 the next day.',
},
@@ -976,7 +1271,7 @@ interface ListsTodo {
}
const LISTS_TODOS: ListsTodo[] = [
- { name: 'Confirm ryokan check-in time', category: 'Before departure', due_date: '2026-09-25', priority: 3, mine: true },
+ { name: 'Confirm ryokan check-in time', category: 'Before departure', due_date: day(4), priority: 3, mine: true },
{ name: 'Buy a Suica top-up', category: 'On arrival', done: true },
]
@@ -1047,7 +1342,7 @@ const UNPAID_EXPENSE = {
category: 'transport',
total_price: 12000,
currency: 'JPY',
- expense_date: '2026-09-13',
+ expense_date: day(-8),
note: 'Nobody has booked it yet, so this is the counter fare for three.',
}
@@ -1080,7 +1375,7 @@ const FILE_PDFS = {
},
'LH716-boarding-pass': {
title: 'Boarding pass LH716',
- lines: ['Frankfurt FRA to Tokyo Haneda HND', '12 Sep 2026, boarding 12:20, gate A34', 'Seat 34K, window', 'Booking reference LH-4QK2PZ'],
+ lines: ['Frankfurt FRA to Tokyo Haneda HND', `${short(-9)}, boarding 12:20, gate A34`, 'Seat 34K, window', 'Booking reference LH-4QK2PZ'],
},
'old-draft-itinerary': {
title: 'Itinerary, first draft',
@@ -1199,11 +1494,10 @@ const tmpDir = (): string => {
* A one-page PDF, written by hand because no PDF library is a dependency here.
* Five objects and an xref table whose offsets are counted off the assembled
* buffer; everything in it is ASCII, so bytes and characters are the same thing.
+ * Exported for the document-sync guide, which puts two of these into the store
+ * (`external.ts`) rather than into the trip.
*/
-export function filesPdfFixture(id: keyof typeof FILE_PDFS): string {
- const file = path.join(tmpDir(), `${id}.pdf`)
- if (existsSync(file)) return file
- const { title, lines } = FILE_PDFS[id]
+export function drawPdf(title: string, lines: readonly string[]): Buffer {
const escape = (s: string) => s.replace(/([\\()])/g, '\\$1')
const content = [
`BT /F1 26 Tf 64 752 Td (${escape(title)}) Tj ET`,
@@ -1226,7 +1520,18 @@ export function filesPdfFixture(id: keyof typeof FILE_PDFS): string {
pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`
for (const offset of offsets) pdf += `${String(offset).padStart(10, '0')} 00000 n \n`
pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${startxref}\n%%EOF\n`
- writeFileSync(file, pdf, 'latin1')
+ return Buffer.from(pdf, 'latin1')
+}
+
+/**
+ * One of the trip's PDFs as a file in `e2e/.tmp`. Drawn on every call: the
+ * boarding pass names its day, which is relative to the picture day, so a
+ * file left over from an earlier run would carry that run's date.
+ */
+export function filesPdfFixture(id: keyof typeof FILE_PDFS): string {
+ const file = path.join(tmpDir(), `${id}.pdf`)
+ const { title, lines } = FILE_PDFS[id]
+ writeFileSync(file, drawPdf(title, lines))
return file
}
@@ -1389,8 +1694,8 @@ export async function ensureCollabFixtures(api: APIRequestContext): Promise {
diff --git a/client/e2e/help/media.env.example b/client/e2e/help/media.env.example
new file mode 100644
index 000000000..39d0bdf8d
--- /dev/null
+++ b/client/e2e/help/media.env.example
@@ -0,0 +1,30 @@
+# Copy to e2e/help/media.env (not committed). Only the guides that show
+# another service need these; every other guide runs without the file.
+#
+# The addresses must be the machine's LAN address: TREK's SSRF guard refuses
+# loopback whatever the flags say, and the two lines at the bottom let the
+# media backend reach a private network and find the booking extractor.
+
+# AirTrail (Transports: Import from AirTrail). Key from Settings > Security.
+HELP_MEDIA_AIRTRAIL_URL=http://192.168.1.10:3020
+HELP_MEDIA_AIRTRAIL_API_KEY=
+
+# Dawarich (Map: recorded route; Atlas: countries and wishes). Key from Account > API key.
+HELP_MEDIA_DAWARICH_URL=http://192.168.1.10:3000
+HELP_MEDIA_DAWARICH_API_KEY=
+
+# Nextcloud (Files: Document sync). An app password, not the account password.
+HELP_MEDIA_NEXTCLOUD_URL=http://192.168.1.10:8803
+HELP_MEDIA_NEXTCLOUD_USER=admin
+HELP_MEDIA_NEXTCLOUD_PASSWORD=
+
+# For the media backend (client/e2e/server-launch.mjs passes the environment on).
+ALLOW_INTERNAL_NETWORK=true
+# The booking extractor. On Linux the package's binary; on Windows a small
+# program that runs it in the TREK Docker image (see README).
+KITINERARY_EXTRACTOR_PATH=/usr/lib/x86_64-linux-gnu/libexec/kf6/kitinerary-extractor
+
+# Optional: the day the seed and the pictures are relative to (YYYY-MM-DD).
+# Unset, every run takes today. Pin it while a picture set is made over
+# several runs, so every run shows the same calendar.
+# E2E_PICTURE_DAY=
diff --git a/client/e2e/help/run.mjs b/client/e2e/help/run.mjs
index 87029dc70..e4ecaa7d3 100644
--- a/client/e2e/help/run.mjs
+++ b/client/e2e/help/run.mjs
@@ -6,12 +6,47 @@
// Extra arguments go straight to Playwright, e.g.
// npm run help:media -- --grep "pictures"
import { spawnSync } from 'node:child_process'
+import { existsSync, readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
+import path from 'node:path'
+// The guides that show another service (AirTrail, Dawarich, a document store,
+// the booking extractor) take its address and key from e2e/help/media.env,
+// KEY=VALUE per line, which is not committed. media.env.example lists them.
+// The file is read here so the backend inherits it too (server-launch.mjs
+// spreads this environment): ALLOW_INTERNAL_NETWORK and the extractor path
+// live in the same place.
+function mediaEnv() {
+ const file = path.join(process.cwd(), 'e2e', 'help', 'media.env')
+ if (!existsSync(file)) return {}
+ const out = {}
+ for (const raw of readFileSync(file, 'utf8').split(/\r?\n/)) {
+ const line = raw.trim()
+ if (!line || line.startsWith('#')) continue
+ const eq = line.indexOf('=')
+ if (eq < 1) continue
+ out[line.slice(0, eq).trim()] = line.slice(eq + 1).trim().replace(/^"(.*)"$/, '$1')
+ }
+ return out
+}
+
+// The day the pictures are taken on, fixed once for the whole run so the seed
+// project and every worker agree even across midnight (see e2e/dates.ts).
+function today() {
+ const d = new Date()
+ const pad = n => String(n).padStart(2, '0')
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
+}
+
+const fromFile = mediaEnv()
const env = {
+ ...fromFile,
...process.env,
E2E_WEB_PORT: process.env.E2E_WEB_PORT || '5183',
E2E_API_PORT: process.env.E2E_API_PORT || '3011',
+ // The shell wins, then media.env (a day pinned there keeps a picture set
+ // consistent across several runs), then today.
+ E2E_PICTURE_DAY: process.env.E2E_PICTURE_DAY || fromFile.E2E_PICTURE_DAY || today(),
}
// The CLI's own entry, run by this node: no shell in between, so a --grep
// pattern with a `|` reaches Playwright untouched.
diff --git a/client/e2e/help/trip-bookings.guide.ts b/client/e2e/help/trip-bookings.guide.ts
index 8e619cf26..c034c4ed6 100644
--- a/client/e2e/help/trip-bookings.guide.ts
+++ b/client/e2e/help/trip-bookings.guide.ts
@@ -1,7 +1,9 @@
import { test, expect, type Locator, type Page } from '@playwright/test'
import { captureGuide, captureHero, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
-import { seededTrip, ensureBookingsFixtures, bookingPdfFixture, bookingEmlFixture, HOTEL_TO_BOOK, UNATTACHED_FILE } from './fixtures'
-import { openTrip, modal, portalDialog } from './trip-shared'
+import { dotted } from '../dates'
+import { seededTrip, ensureBookingsFixtures, bookingPdfFixture, bookingEmlFixture, BOOKING_EML, HOTEL_TO_BOOK, UNATTACHED_FILE } from './fixtures'
+import { openTrip, modal, dialog, portalDialog, importSteps, importTask, dismissImportTask, deleteTripFiles } from './trip-shared'
+import { requireExtractor, allowEmlUploads } from './external'
import { tripBookingsContext, tripBookingsGuides } from '../../src/help/contexts/tripBookings'
import type { HelpGuide } from '../../src/help/types'
@@ -55,10 +57,6 @@ const travellers = (page: Page) => page.locator('[aria-label="Travelers"]')
/** The card's delete question is its own portal, with no backdrop class to find it by. */
const deleteAsk = (page: Page) => portalDialog(page, page.getByText('Delete booking?', { exact: true }))
-/** BookingImportModal is another bare portal; the heading is what tells it apart. */
-const importDialog = (page: Page) => portalDialog(page, page.getByText('Import booking confirmations', { exact: true }))
-/** The background widget's card for the running parse. */
-const importTask = (page: Page) => page.locator('.bg-surface-card').filter({ hasText: 'gracery-confirmation.eml' }).last()
/** Open the CustomSelect that belongs to a label and take one option out of it. */
async function chooseIn(page: Page, field: RegExp, option: RegExp, search?: string): Promise {
@@ -128,15 +126,6 @@ async function clearPanelState(page: Page): Promise {
}, tripId)
}
-/**
- * Import from file is rendered only when the server can read a confirmation,
- * which here means the AI Parsing addon: no extractor binary is installed.
- */
-async function setAiParsing(page: Page, enabled: boolean): Promise {
- const res = await page.request.put('/api/admin/addons/llm_parsing', { data: { enabled } })
- if (!res.ok()) throw new Error(`could not switch AI Parsing ${enabled ? 'on' : 'off'}: ${res.status()} ${await res.text()}`)
-}
-
const closeModal = async (page: Page): Promise => {
if (await modal(page).isVisible().catch(() => false)) {
await page.keyboard.press('Escape')
@@ -179,9 +168,9 @@ const SCRIPTS: Record = {
},
{
prepare: async p => {
- await setDate(p, 0, '19.09.2026')
+ await setDate(p, 0, dotted(-2))
await timeBox(p).nth(0).fill('16:30')
- await setDate(p, 1, '19.09.2026')
+ await setDate(p, 1, dotted(-2))
await timeBox(p).nth(1).fill('20:00')
await settle(p)
},
@@ -503,58 +492,54 @@ const SCRIPTS: Record = {
},
'import-booking-file': {
guide: guide('import-booking-file'),
+ // The extractor, and no addon: with it answering, the dialog sends mode
+ // no-ai and no model is asked. The mail has to be an allowed file type or
+ // the review would save the booking and drop the document without a word.
start: async p => {
- await setAiParsing(p, true)
+ await requireExtractor(p.request)
+ await allowEmlUploads(p.request, true)
await openBookings(p)
},
steps: [
- {
- target: p => p.getByRole('button', { name: 'Import from file' }),
- act: async p => {
- await p.getByRole('button', { name: 'Import from file' }).click()
- await expect(importDialog(p)).toBeVisible()
- await settle(p)
- },
- },
+ ...importSteps(bookingEmlFixture, BOOKING_EML),
{
prepare: async p => {
- await importDialog(p).locator('input[type="file"]').setInputFiles(bookingEmlFixture())
- await expect(importDialog(p).getByText('gracery-confirmation.eml')).toBeVisible()
+ // The card is there at once, spinning. The picture wants it finished:
+ // the tick and the Import it offers. The extractor has 30 s in the
+ // backend, and on a Windows media host that is a docker run, so the
+ // wait is generous rather than tight.
+ await expect(importTask(p, BOOKING_EML).getByRole('button', { name: 'Import', exact: true })).toBeVisible({ timeout: 90_000 })
await settle(p)
},
- target: p => importDialog(p).getByText('gracery-confirmation.eml').locator('xpath=ancestor::button[1]'),
- act: settle,
- },
- {
- target: p => importDialog(p).getByRole('button', { name: 'Import', exact: true }),
+ target: p => importTask(p, BOOKING_EML),
act: async p => {
- await importDialog(p).getByRole('button', { name: 'Import', exact: true }).click()
- await expect(importDialog(p)).toHaveCount(0, { timeout: 20_000 })
+ await importTask(p, BOOKING_EML).getByRole('button', { name: 'Import', exact: true }).click()
+ await expect(modal(p).getByRole('heading', { name: 'New Reservation' })).toBeVisible({ timeout: 20_000 })
+ await expect(titleBox(p)).toHaveValue(HOTEL_TO_BOOK.name)
+ await expect(codeBox(p)).toHaveValue('GRK-40218')
+ await expect(modal(p).getByText(BOOKING_EML)).toBeVisible()
await settle(p)
},
},
{
- prepare: async p => {
- await expect(importTask(p)).toBeVisible({ timeout: 30_000 })
+ target: dialog,
+ act: async p => {
+ await saveButton(p, 'Add').click()
+ await expect(modal(p)).toHaveCount(0, { timeout: 20_000 })
+ await expect(bookingCard(p, HOTEL_TO_BOOK.name)).toBeVisible({ timeout: 20_000 })
await settle(p)
},
- target: importTask,
- act: settle,
},
],
cleanup: async p => {
- // The widget only offers its Close once the run has stopped, and a card
- // left standing would sit in the corner of every later guide's pictures.
- // The wait is bounded well inside the 150 s a help-media test gets
- // (playwright.config.ts): the four steps take about 40 s of it, so a
- // longer one would fail the whole guide over a card nobody can close.
- const close = importTask(p).getByRole('button', { name: 'Close' })
- await close.waitFor({ state: 'visible', timeout: 45_000 }).catch(() => {})
- if (await close.isVisible().catch(() => false)) await close.click()
- await setAiParsing(p, false)
+ await closeModal(p)
+ await dismissImportTask(p, BOOKING_EML)
+ await allowEmlUploads(p.request, false)
await clearPanelState(p)
- // A parse that did produce something would have left its bookings behind.
- await deleteBookings(p, 'Hotel Granvia Kyoto')
+ // The route takes the stay and the expense with the booking; the mail it
+ // attached stays behind in Files like any unlinked document.
+ await deleteBookings(p, HOTEL_TO_BOOK.name)
+ await deleteTripFiles(p, BOOKING_EML)
},
},
'edit-booking': {
diff --git a/client/e2e/help/trip-collab.guide.ts b/client/e2e/help/trip-collab.guide.ts
index 61efa1776..027d426ac 100644
--- a/client/e2e/help/trip-collab.guide.ts
+++ b/client/e2e/help/trip-collab.guide.ts
@@ -1,5 +1,7 @@
import { test, expect, type Locator, type Page } from '@playwright/test'
import { captureGuide, captureHero, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
+import { ordinal, short } from '../dates'
+import { SEED_CHAT } from '../screenshots/seed'
import { seededTrip, ensureCollabFixtures, COLLAB_SPARE_POLL, WHATS_NEXT_STOPS } from './fixtures'
import { openTrip } from './trip-shared'
import { tripCollabContext, tripCollabGuides } from '../../src/help/contexts/tripCollab'
@@ -34,7 +36,7 @@ const POLL = {
// Plain text on purpose: a bold run in the question would wrap the paragraph
// in one more element and move the card away from `pollCard`'s ancestor depth.
question: 'Which evening do we keep for the kaiseki dinner?',
- options: ['Wed 16th, after Fushimi Inari', 'Thu 17th, after Arashiyama', 'Either, decide on the day'],
+ options: [`${short(-5).split(',')[0]} ${ordinal(-5)}, after Fushimi Inari`, `${short(-4).split(',')[0]} ${ordinal(-4)}, after Arashiyama`, 'Either, decide on the day'],
}
/** The seeded poll nobody has voted on yet. */
const SEEDED_POLL = 'Ryokan or city hotel in Hakone?'
@@ -45,7 +47,7 @@ const CHAT = {
flag: '🎌',
theirs: 'Drop bags. I want to be at Senso-ji before the crowds.',
answer: 'Agreed, bags at the hotel first, then Asakusa.',
- reactTo: 'Booked the teamLab slot for the 13th, 14:00.',
+ reactTo: SEED_CHAT.teamlab,
reaction: '👍',
}
diff --git a/client/e2e/help/trip-costs.guide.ts b/client/e2e/help/trip-costs.guide.ts
index 23fc08c7d..ed22a466a 100644
--- a/client/e2e/help/trip-costs.guide.ts
+++ b/client/e2e/help/trip-costs.guide.ts
@@ -1,5 +1,6 @@
import { test, expect, type Locator, type Page } from '@playwright/test'
import { captureGuide, captureHero, beat, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
+import { day, long, short } from '../dates'
import { seededTrip, ensureCostsFixtures } from './fixtures'
import { openTrip, modal, dialog } from './trip-shared'
import { tripCostsContext, tripCostsGuides } from '../../src/help/contexts/tripCosts'
@@ -28,7 +29,7 @@ const SEEDED_EUR = 'Flights FRA → HND'
const BOOKING = 'LH716 FRA → HND'
const DINNER = 'Kaiseki dinner in Gion'
const UPGRADE = 'Shinkansen seat upgrade'
-const LUNCH = { name: 'Nishiki Market lunch', category: 'food', total_price: 4800, currency: 'JPY', expense_date: '2026-09-17' }
+const LUNCH = { name: 'Nishiki Market lunch', category: 'food', total_price: 4800, currency: 'JPY', expense_date: day(-4) }
/** The Costs tab, waited out: its panel is lazy and its figures come from the server. */
const openCosts = async (p: Page): Promise => {
@@ -391,16 +392,16 @@ const SCRIPTS: Record = {
prepare: async p => {
await p.getByRole('button', { name: 'All days' }).first().click()
await beat(p, 300)
- await dropdown(p).getByRole('button', { name: 'Sat, Sep 12' }).click()
- await expect(p.getByText(/^Saturday, September 12$/)).toBeVisible()
+ await dropdown(p).getByRole('button', { name: short(-9) }).click()
+ await expect(p.getByText(new RegExp(`^${long(-9)}$`))).toBeVisible()
await settle(p)
},
- target: p => p.getByText(/^Saturday, September 12$/).locator('xpath=../..'),
+ target: p => p.getByText(new RegExp(`^${long(-9)}$`)).locator('xpath=../..'),
act: async p => {
- await p.getByRole('button', { name: 'Sat, Sep 12' }).first().click()
+ await p.getByRole('button', { name: short(-9) }).first().click()
await beat(p, 300)
await dropdown(p).getByRole('button', { name: 'All days' }).click()
- await expect(p.getByText(/^Saturday, September 12$/)).toHaveCount(0)
+ await expect(p.getByText(new RegExp(`^${long(-9)}$`))).toHaveCount(0)
await settle(p)
},
},
diff --git a/client/e2e/help/trip-files.guide.ts b/client/e2e/help/trip-files.guide.ts
index d02492da9..226a3ca18 100644
--- a/client/e2e/help/trip-files.guide.ts
+++ b/client/e2e/help/trip-files.guide.ts
@@ -1,7 +1,8 @@
import { test, expect, type Page, type Locator } from '@playwright/test'
-import { captureGuide, captureHero, typeInto, settle, VIEWPORT, type GuideScript } from './guide'
-import { seededTrip, ensureFilesFixtures, filesPdfFixture, filesImageFixture } from './fixtures'
-import { openTrip, portalDialog } from './trip-shared'
+import { captureGuide, captureHero, typeInto, beat, settle, VIEWPORT, type GuideScript } from './guide'
+import { seededTrip, ensureFilesFixtures, filesPdfFixture, filesImageFixture, drawPdf } from './fixtures'
+import { openTrip, portalDialog, modal, dialog } from './trip-shared'
+import { ensureNextcloudFolder, NEXTCLOUD_CONNECTION, NEXTCLOUD_DOCUMENTS, NEXTCLOUD_FOLDER, resetDocSync, toggleAddon } from './external'
import { tripFilesContext, tripFilesGuides } from '../../src/help/contexts/tripFiles'
import type { HelpGuide } from '../../src/help/types'
@@ -24,7 +25,6 @@ const STARRED = 'JR-Pass-voucher.pdf'
const LINKED = 'LH716-boarding-pass.pdf'
const DOOMED = 'old-draft-itinerary.pdf'
const PHOTO = 'nishiki-market.jpg'
-const DOCUMENT = 'travel-notes.md'
/** What the upload guide brings in; these two names exist nowhere else, so cleanup can take them out. */
const UPLOADED_PDF = 'kyoto-bus-pass.pdf'
const UPLOADED_PHOTO = 'arashiyama.jpg'
@@ -66,14 +66,40 @@ const noteBox = (page: Page) => assignDialog(page).getByPlaceholder('Add a note.
*/
const lightbox = (page: Page) =>
page.locator('div[role="presentation"]').filter({ has: page.getByRole('button', { name: 'Open in new tab' }) }).first()
-/** The preview for everything that is not a picture; markdown renders in `.collab-note-md`. */
-const docPreview = (page: Page) => portalDialog(page, page.locator('.collab-note-md'))
+/**
+ * The preview for everything that is not a picture. For a PDF it is the card
+ * around the browser's embedded viewer, found by the one `