Compare commits

..

165 Commits

Author SHA1 Message Date
Maurice 8d947cc900 chore(lint): read the rule test's parser from typescript-eslint and drop a stale knip entry 2026-11-17 22:40:27 +01:00
Maurice a0f4a8791e test(journey): a NUL inside a share token is dropped before the lookup 2026-11-17 22:40:27 +01:00
Maurice 8b3c251e73 test(memories): answer the SSRF album case by API, not by call order 2026-11-17 22:40:26 +01:00
Maurice 43611b3c7f test(db): give the stand-in migration storage the master transaction calls 2026-11-17 22:40:26 +01:00
Maurice 3c3f985d99 fix(db): type the cleaned cookies for the strict compiler 2026-11-17 22:40:26 +01:00
Maurice a8f3a586dd docs(db): describe the layers that hold plugin SQL on Postgres and the NUL rule for plugin data
The plugin-sdk README, the Postgres wiki page and server/CLAUDE.md now name
the layers as the code enforces them: the refusal on a privileged role and
the boot log line, the guard (the reg* types, INTO after the statement's
own INSERT or MERGE only, TEMP only where it makes a temporary object), the
targets Postgres resolves before an ALTER, DROP, REFRESH, TRUNCATE or
CREATE INDEX, one statement per round trip, pg_temp last, and the quota over
every relation with the object cap. They also say that a plugin argument
holding NUL is refused on Postgres and bound exactly on SQLite.
2026-11-17 22:28:44 +01:00
Maurice 64df2117dc fix(db): hold plugin SQL on Postgres in layers the database enforces
The token guard kept leaking: on a superuser connection an unqualified
`alter type int4 rename to int4x` renamed pg_catalog's type for the whole
server, sequences and catalog-only objects grew the database past the quota,
regtype/regconfig/regdictionary looked TREK's objects up by name, and a
column alias named insert or merge in front of INTO made a table. Instead
of a longer word list, the store now asks the database:

- No plugin SQL while TREK's role is privileged in the sense of the restore
  check (PRIVILEGED_ROLE_SQL, imported from server-checks.ts): every db:own
  call fails with PRIVILEGED_ROLE_PLUGIN_REFUSAL, read once per pool
  connection, and the boot log says why.
- The objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX ... ON
  changes, and the tables a CREATE or ALTER TABLE ties to its own, are
  resolved with to_regclass/to_regtype in the transaction right before the
  statement, and it is refused unless each one found lies in the plugin's
  schema. An unqualified int4, text or box is pg_catalog's and refused even
  with the role check off.
- The quota counts every relation of the schema with its TOAST table, and a
  schema holds at most PLUGIN_SCHEMA_MAX_OBJECTS catalog objects (relations,
  types, constraints, enum labels).
- The guard refuses every reg* type and its array in every spelling, the
  has_*_privilege functions, currtid2 and the BRIN/GIN maintenance
  functions; INTO only after the INSERT or MERGE that is the statement's
  verb or a WITH body's; TEMP only where it makes a temporary object
  (CREATE TEMP/TEMPORARY, SELECT ... INTO TEMP), so a column named temp
  works again; a base type; and a NUL anywhere in the SQL text.
- A bound value or a migration id holding NUL is refused with the reason
  instead of being stripped, so the plugin's keys never change meaning.

Every bypass from the re-review is a test on the real database, on the
role the plugin data is meant to run as and on a superuser connection with
the role check off.
2026-11-17 22:28:38 +01:00
Maurice 2b14fe1a2a fix(plugins): bind a plugin's own SQLite arguments exactly again, NUL included
5ff5e7660 stripped U+0000 from every argument a plugin bound to its own
SQLite file, but left the rows it had stored alone. A key written with a
NUL (through a bound arg or char(0) in the plugin's SQL) could no longer be
found by the same key, upserts added duplicates, and keys that differ only
in where a NUL sits ('a\0bc', 'ab\0c') collapsed into one and collided.

A plugin's data is the plugin's, so its file binds the arguments exactly as
sent again, as before that commit. TREK's own data still holds no NUL; the
Postgres store, whose text cannot hold the character, refuses it instead.
2026-11-17 22:28:26 +01:00
Maurice 28f93f2539 fix(db): refuse restores for CREATEROLE members, server file grants and parameter grants
The privileged-role check missed three ways a role can reach the database
host from SQL. Before PostgreSQL 16 a member of a CREATEROLE role sets its
role to it and grants itself pg_execute_server_program, since role
attributes are not inherited but the grant checks the role in effect. A role
granted EXECUTE on lo_export, lo_import, pg_read_file, pg_ls_dir and their
siblings reads or writes server files, and lo_export keeps the file after the
transaction rolls back. From PostgreSQL 15 on a role can be granted ALTER
SYSTEM on a setting or SET on a superuser-only one.

PRIVILEGED_ROLE_SQL now counts all three. The parameter grants are read
through query_to_xml inside a CASE taken only on 15 or later, because a
statement naming pg_parameter_acl does not parse on 14. A SET grant on a
setting every role may change anyway, and pg_monitor, stay ordinary. The
lane test creates each kind of role and shows the escalation the check is
for on the server it runs against.
2026-11-17 22:08:53 +01:00
Maurice 9f4c8e106c fix(db): drop NUL from every request value before any logic runs
The database stores no NUL on either engine, but the application still held
the value a client sent. A key or a check made from it was then a different
value from the one the database compared: `victim@x.test` followed by NUL
was a fresh key for the per-email password-reset throttle while the lookup
found the victim's row, so every spelling mailed a new link and voided the
last one.

Every input now loses its NUL where it enters TREK: the nulFreeRequest
middleware after the body parsers (path, query string, body, cookies), the
first global pipe for what a route parses itself (a multipart body), the
websocket adapter for every frame, and the MCP registry through a new
host-supplied input mapper, since /mcp keeps its raw body. Headers need
nothing: Node refuses a NUL in one with a 400. A string under a key naming a
password stays as sent: it is only ever hashed, and stripping it would lock
out an account whose password was set with one. The stripping in the
database layer stays as the backstop for what does not come from a request.
2026-11-17 22:08:45 +01:00
Maurice f47490dd9f docs(db): drop the pg_restore rollback that fails and name the client tool directories the code searches
Updating offered a second way to roll back a Postgres update: drop the
database, create it again and pg_restore the pre-migrate copy into it. TREK's
copy is a dump of its schema by name, so pg_restore creates public again,
stops at "schema public already exists" and rolls the load back, leaving an
empty database in the middle of a rollback. The page now says so and keeps the
steps that clear the schema instead.

Environment-Variables listed /usr/lib/postgresql/17 to 14 as the default
search path for the client tools; the code and the image start at 18.
2026-11-17 21:59:11 +01:00
Maurice 620f5a94f6 fix(db): leave nothing behind when a first Postgres boot fails, so RESTORE_FROM_BACKUP still runs
createFromBaseline created the migration history's table through MikroORM's
storage before, and outside, the transaction that runs the baseline. Without a
master transaction MikroORM commits that table on its own, so a first boot that
failed in the baseline (a server without ICU, a timeout, a dropped connection)
left an empty mikro_orm_migrations behind. The next start with
RESTORE_FROM_BACKUP took that for a database in use, skipped the restore with a
warning and brought up an empty instance, after which the restore never ran.

The table is now created on the baseline's own transaction, so a failed first
boot leaves the database empty. The boot restore also treats a lone migration
history that records nothing as no database, which a restore clears anyway; any
other answer keeps it, so the check fails closed. Database-Postgres says both.
2026-11-17 21:59:03 +01:00
Maurice 57a3c732f2 test(db): read the raw-SQL exemptions without awaiting in a loop
The two checks over every file under src/ awaited ESLint's config file by
file, which lint:warnings counts as no-await-in-loop. They read the configs
with Promise.all instead.
2026-11-17 21:58:30 +01:00
Maurice e95127c945 docs(db): describe plugin SQL on its own pool client instead of the marker hook
The guard's header, server/CLAUDE.md and the Postgres wiki page named
extended-query.ts and a hook on every pool connection. They now say that the
store sends each plugin statement over the extended protocol on a client it
checks out per call, and drops that client's temporary tables and session
state before handing it back.
2026-11-17 21:50:36 +01:00
Maurice ccad725b29 fix(db): run plugin SQL on a pool client of its own instead of patching the pool
Plugin statements on Postgres went over the extended query protocol through a
marker parameter and a hook that replaced query() on every client of TREK's
pool. That kept a plugin to one statement per round trip, but it changed
TREK's own hot path for a concern only plugin data has.

The plugin data store now checks a pg client out of the ORM's pool for each
transaction, through MikroORM's getNativeClient, and runs the transaction on
it directly. Every plugin write goes as a query with queryMode 'extended' and
every read through a pg-cursor on that client, so Postgres parses exactly one
statement either way. The settings the transaction makes are local, and
before the client goes back to the pool the store drops temporary tables,
cursors, listeners, session advisory locks and sequence state, or closes a
client it cannot bring back to that state. The row cap, quota, time budget,
untimed migrate, per-plugin queue, pool share and script commits are as
before, and plugin args are still sent without NUL.

The marker, the hook and its install in the Postgres driver are gone.
2026-11-17 21:50:30 +01:00
Maurice b5cdf3d48f fix(db): refuse raw SQL everywhere under src/, not only in the repositories
The ESLint walls against raw(), the sql tag and SQL text handed to
execute/run/all/get applied to src/db/repositories and src/db/seeders only. A
service, job, guard or MCP tool could send its own SQLite-only SQL through
em.getConnection().execute(...), which the Postgres probe never runs, since it
only calls the repositories. The walls now cover all of src/. The dialect layer,
the engines and the migrations stay the homes of raw SQL, and the four boot-time
lifecycle files that hold SQL text today are named and pinned to their count.
2026-11-17 21:44:32 +01:00
Maurice 1054d79f9e fix(db): pass the chunk size and the abort options through the NUL-free connection
The wrapper took the chunk size of a stream as optional, which lint:strict refuses, and dropped the abort options Kysely hands executeQuery and streamQuery, so a cancelled query kept running.
2026-11-17 21:42:10 +01:00
Maurice 459c4454ad test: import vi in the trip members suite and type the move's SQLite ORM options 2026-11-17 21:42:09 +01:00
Maurice 0460b08a79 test: send the reset and seeding steps one by one or together, not awaited in a loop
resetDatabase empties tables and puts back the default categories one after another through the repo's oneByOne helper, where the order can matter, and the default addons and photo providers together; the MCP suites switch their addons on together and create ordered stops through oneByOne. The warnings this brings below the baseline, and the no-explicit-any and no-unused-vars counts earlier commits lowered, are lowered in scripts/eslint-baseline.json.
2026-11-17 21:42:09 +01:00
Maurice 9327dc309a fix(db): refuse to regenerate a frozen Postgres baseline and check its trigger ports once frozen
gen:pg-baseline rewrote the baseline with its cut at the newest migration on
disk, so after a migration landed after the cut, running it moved the cut over
that migration while Postgres installs created from the old baseline would
still run it through the migrator. It now refuses while a migration follows the
committed cut, names those migrations and the routine, and moves the cut only
with --move-cut (lint:dialect keeps such a migration under the post-cut rules
either way).

check:pg-baseline stopped comparing SQLite triggers with POSTGRES_TRIGGERS once
the baseline was frozen, so a trigger a later migration created on SQLite went
unnoticed. The comparison now runs in both states, with advice that points at
the migration when the baseline is frozen.
2026-11-17 21:39:27 +01:00
Maurice f4a6411511 fix(db): hold SQLite-only functions, LIKE and the sqlite member of a post-cut migration in lint:dialect
lint:dialect missed several classes of SQL that SQLite reads and Postgres does
not, or reads differently:

- group_concat, ifnull, instr, iif, printf, typeof, total(), changes() and
  json_object/json_array/json_valid/json_type/json_quote, as calls in SQL text
  and as the bare name handed to eb.fn.
- LIKE in SQL text, Kysely's 'like' operator and MikroORM's $like, which ignore
  case on SQLite only. A LIKE that is exact on purpose now says so in a
  like-exact comment; the six existing ones (setting keys, storage paths, the
  lowercased reference search, sqlite_master) carry it.
- The sqlite member of engineDdl was not read at all, so a trigger or a data
  backfill put there never reached Postgres. It may now hold only the schema
  change and a rebuild's copy and sqlite_sequence bookkeeping, and SQLite
  statements with an empty postgres member need a sqlite-only reason.
- execBestEffort, bestEffort and execUnlessTableMissing in a post-cut
  migration: on Postgres a swallowed failure aborts the migration transaction.
- The post-cut rules follow POSTGRES_FIRST_CUT as well as the manifest, so
  regenerating the baseline over a new migration no longer releases it.

src/db/engine/sqlite/ is SQLite's own code and is no longer scanned.
2026-11-17 21:36:21 +01:00
Maurice dc75c200b1 fix(db): count every spelling of an engine check in lint:engine-dispatch
The gate matched only isSqlite(/isPostgres(, instanceof on a platform class
and a comparison on a property named engine or id. A destructured engine name,
the literal on the left, a switch over the engine, instanceof on a driver class
and a comparison with a driver class all passed with an empty baseline, and
standalone-orm.ts already held one such check. The regex now matches every one
of them, the guard in standalone-orm.ts moves into the engine port as
assertSqliteOrmConfig, and the advice names where a check belongs.
2026-11-17 21:27:41 +01:00
Maurice 56a1a832b2 test(db): list the carry-over migration among the ones without a legacy step 2026-11-17 21:27:13 +01:00
Maurice 7d4b150859 docs(db): describe the NUL, whole-number and calendar-date rules
server/CLAUDE.md names where NUL is dropped, INTCOL and the .int() rule
for integer columns, and the calendar-date check for a bound date, and no
longer lists the places NUL suite as SQLite-only. The Postgres wiki says
the move drops a NUL instead of refusing it.
2026-11-17 21:25:13 +01:00
Maurice 5ff5e76603 fix(db): store no NUL character on either engine
Postgres text cannot hold U+0000, so any write or filter carrying one (a
request body, a query string, an import, a feed, a forwarded mail, a
plugin's own SQL) answered a 500 on Postgres while SQLite stored it. Both
engines now drop the character where every value leaves for the database
(src/db/nul-free.ts): the MikroORM platforms when they inline a string or
serialize a JSON value, the Kysely dialects for every parameter, a
plugin's own SQLite file for its arguments, and the move from SQLite,
which used to refuse such text. The same request now answers the same
status and leaves the same row on both engines, so the places NUL suite
runs on Postgres as well and leaves SQLITE_ONLY.
2026-11-17 21:24:00 +01:00
Maurice 685506d067 fix(storage): find a stored reference in any case on Postgres too
The release queue narrows each owner's rows with LIKE '%run%' before it
parses them, and relied on SQLite's LIKE ignoring ASCII case. On Postgres
LIKE is exact, so a row naming an object in uppercase was not found and
the release deleted an object that row still names. likeAny now matches
LOWER(column) against the lowercase run, which reads alike on both
engines. RELI-010 fails on Postgres without it.
2026-11-17 21:23:39 +01:00
Maurice 143e2ae447 fix(db): find no nearest day for a date the calendar does not have
The nearest-day fallback of a booking's time cast the bound date to a
timestamp on Postgres, which refuses 2024-02-30 with a 500, while SQLite's
JULIANDAY rolled it over into March and placed the booking there.
dayDistance now refuses anything but a calendar date on both engines
(isCalendarDate), so a caller that forgets the check fails on SQLite too,
and findNearestDayId answers no day for such a date. The size baseline of
Reservations.repository.ts drops by one line.
2026-11-17 21:23:31 +01:00
Maurice 1b216d8f48 fix(db): keep a carried-over half day as a half on both engines
A vacation day can be taken as a half day, so what a year carries into
the next can end in a half. vacay_user_years.carried_over was an INTEGER
column: SQLite stored 29.5 as a REAL, Postgres (bigint) rounded it to 30,
and the move refused such a SQLite value. The column becomes REAL on
SQLite (a table rebuild that keeps every id and the AUTOINCREMENT counter)
and double precision on Postgres, through the first migration after the
Postgres baseline's cut. VACAY-046 books a half day and reads the
carry-over on both engines.
2026-11-17 21:23:23 +01:00
Maurice 6304cb2e6a test(memories): answer the session retry cases by API, not by call order
The album list asks three sources at once; which call reaches the fake first
depends on how database reads interleave, which differs between the engines.
The fake now answers by API and category and the cases assert the retry with
a fresh session itself.
2026-11-17 21:18:27 +01:00
Maurice f9877d0694 test(share): write the place photo cache through the app's own ORM
The suite built the cache over a second SQLite ORM, so on Postgres its rows
went to a database the app never reads.
2026-11-17 21:18:27 +01:00
Maurice e22210aca8 fix(db): refuse a fraction for an integer column at the request boundary
Every integer column is bigint on Postgres. SQLite stored a fraction sent
to one (a packing quantity of 1.5, a budget item for 2.5 days, an id of
3.5) as a REAL, while Postgres rounded it in a statement MikroORM renders
and refused it with a 500 in a Kysely statement, so the engines held
different data for the same request.

The request schemas of those fields now take whole numbers only, and
INTCOL (tests/unit/contracts/integer-columns.test.ts) holds the class: it
reads the integer columns from the entities and fails on any DTO field or
inline MCP tool field of that name that takes any number.
2026-11-17 21:02:25 +01:00
Maurice 563fef0521 docs(db): describe the plugin SQL layers and the refused restore roles
The Postgres wiki page and the plugin author guide list what the plugin
SQL guard now refuses and the two layers behind it, and the wiki and
server/CLAUDE.md name every kind of role a restore refuses, including
CREATEROLE on PostgreSQL 14 and 15, which the managed postgres role on
such a server holds.
2026-11-17 20:45:53 +01:00
Maurice 8cfd18e6da fix(db): refuse restores for every role that can reach the database host
The privileged-role check looked only at the role's own rolsuper and at
pg_execute_server_program and pg_write_server_files. A role that is no
superuser itself but a member of one passed it and could SET ROLE to the
superuser from a crafted archive; on PostgreSQL 14 and 15 a role with
CREATEROLE could grant itself pg_execute_server_program; and
pg_read_server_files let COPY read the server's files into TREK's tables.

The check now counts membership in any superuser role, the three
predefined server roles, and CREATEROLE before 16. The boot warning and
the restore refusal describe the same list from one constant. A Postgres
lane suite creates each kind of role and evaluates the check as it, and
shows on the server it runs against whether CREATEROLE can grant itself
pg_execute_server_program.
2026-11-17 20:45:53 +01:00
Maurice f19aae6821 fix(db): read plugin SQL the way the Postgres lexer does and refuse INTO and TEMP anywhere
The guard ended a -- comment at LF only, while Postgres ends it at CR as
well, so "select 1 --\rfrom public.users" hid a qualified name from the
guard that Postgres then read, and with no args a second statement after
the CR ran as TREK's role. It also only looked for INTO at the top level
of a SELECT, so "(select ... into temp users)" made a temporary table that
shadowed TREK's own users table on the pooled connection.

The tokenizer now skips exactly what Postgres skips as whitespace, ends a
line comment at CR or LF, and refuses any character the two read
differently (other control characters, non-ASCII whitespace such as
U+00A0, U+FEFF and U+2028, and the non-decimal and underscored numbers
Postgres before 16 reads another way) instead of guessing. INTO is refused
anywhere but after INSERT or MERGE, at any depth, and the words TEMP and
TEMPORARY anywhere outside a string or quoted name.

The guard tests carry both payloads and their variants; the Postgres lane
runs them against the real database, proves a second statement in one
text is refused by Postgres over the extended protocol, and that a
temporary table never shadows TREK's or a plugin's tables.
2026-11-17 20:45:46 +01:00
Maurice 861f6ba789 fix(db): run plugin SQL one statement at a time and search pg_temp last
The plugin SQL guard was the only thing between a plugin and TREK's tables
on Postgres, and two gaps in it were enough to leave the plugin schema.
Two layers now hold even when the guard is fooled.

A plugin write with no bound args went over the simple query protocol,
which runs every statement in its text. Plugin statements now go through
extendedQuery, which pg sends over the extended protocol whatever the
args, so a second statement is a syntax error instead of a statement that
runs. A marker parameter carries the request to the pool's clients, and a
client without the hook binds one value too many, so it fails closed.

pg_temp is searched before the search_path unless the path names it, and
a temporary table lives as long as its pooled connection, so one left
behind would stand in for users, sessions and every other table for the
next caller. Every connection of TREK's pool now puts pg_temp last on the
search_path the role configured, and a plugin transaction sets its schema
with pg_temp last.
2026-11-17 20:45:39 +01:00
Maurice fcddde71a7 test(db): run the notifications and advanced packing MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The tag notification case waits for the fire-and-forget row with
vi.waitFor instead of one turn of the event loop: on SQLite the insert
lands within that turn, on Postgres it needs a few round trips more.
2026-11-17 20:13:29 +01:00
Maurice 280e9ab0d9 test(realtime): run the websocket wire envelope suite on the real database module
It takes the ORM from the app buildApp boots, seeds through the factories
and resets through resetDatabase instead of the SQLite snapshot mock, so
it runs in the Postgres lane as well.
2026-11-17 20:07:53 +01:00
Maurice 4284a90b03 test(db): run the trips and vacay MCP suites and the route inventory on the real database module
The MCP suites seed through the booted container's ORM instead of the
SQLite snapshot mock and reset through resetDatabase. The route inventory
never touched the database and only mocked it; without the mock it
compiles AppModule over the real module, so it runs in the Postgres lane
as well.
2026-11-17 20:06:54 +01:00
Maurice 475597a6d7 test(db): run the transports, trip members and trip warnings MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The trip warnings suite seeded through the factories but only closed
the snapshot handle; it now boots the container to reach the ORM the reset
needs.
2026-11-17 19:56:40 +01:00
Maurice 4f8ae98e7d test(db): run the share, tags, maps and weather, and transit MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The transit suite saves its permission levels through the
container's PermissionsService in a request context instead of one built
by hand over the SQLite handle.
2026-11-17 19:46:27 +01:00
Maurice 65d55add5a test(db): run the reservations, road trip and settings MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The road trip suite saves its permission levels through the
container's PermissionsService in a request context instead of one built
by hand over the SQLite handle.
2026-11-17 19:36:14 +01:00
Maurice 17fff1a152 test(db): run the packing, places and plugin MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The plugin search suite seeded nothing through the snapshot handle
and only closed it; it now boots the container to reach the ORM the reset
needs.
2026-11-17 19:26:01 +01:00
Maurice f795508fcb test(db): run the feeds and invite, journey, leg transport mode, memories and notes MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well.
2026-11-17 19:09:36 +01:00
Maurice 8254ffd23b test(db): run the days, accommodations, files and help MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The collab sub-feature case in the help suite toggles through the
container's AddonsService in a request context instead of one built by
hand over the SQLite handle.
2026-11-17 18:49:07 +01:00
Maurice b6618eac73 test(db): run the budget and collections MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The settlement parity cases call the
container's BudgetController in a request context instead of one built by
hand over the SQLite handle, and the collections suite drops its raw
per-table DELETE for the same reset.
2026-11-17 18:30:12 +01:00
Maurice f13d60e7e9 test(db): run the AirTrail, atlas expanded, collab and categories MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The PermissionsService the AirTrail cases save
through and the CategoriesMcp and DemoService the categories write
harness attaches are the container's own, called in a request context,
instead of instances built by hand over the SQLite handle.

include_coords compares the coordinates as a set: getTravelStats reads
them through a SELECT DISTINCT without an order, and Postgres returns
them in hash order.
2026-11-17 18:30:05 +01:00
Maurice 1b16fd1683 test(db): run the demo tool gate, addon gating, atlas and assignments MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The tour the assignment cases put on a day is
made with makeTour instead of a raw insert.
2026-11-17 18:20:16 +01:00
Maurice 965a7f2ea8 test(db): merge the factory imports of the newly ported integration suites
One import per module, and the resetTestDb import that no longer has a
caller dropped.
2026-11-17 18:15:31 +01:00
Maurice 88c2b8b991 test(db): run the trips and vacay suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 18:14:09 +01:00
Maurice 3764efde7a test(db): run the share, system notices and trip access primitives suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 18:10:13 +01:00
Maurice 11013711d6 test(db): run the security, settings, tags and todo suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 18:06:52 +01:00
Maurice e083e2d480 test(db): run the scheduler gate, storage health context and uploads suites on the real database module
They drop the SQLite snapshot mock and, where they seed, reset through
resetDatabase and seed through the ORM factories, so they run in the
Postgres lane as well.
2026-11-17 18:03:33 +01:00
Maurice 59adaf2f0c test(db): keep the legacy upgrade suites on SQLite by name
They boot on a SQLite file the retired positional runner built, which no
Postgres database ever came from, so they belong in SQLITE_ONLY rather
than in the snapshot baseline. The lane scan now tells such a suite apart
from the snapshot mock: it mocks src/db/database onto a database of its
own, never names createSnapshotTestDb, and is named in SQLITE_ONLY with
its reason. A snapshot suite added to SQLITE_ONLY stays in the baseline.
2026-11-17 17:55:42 +01:00
Maurice a09d16d6f7 test(db): run the Immich, Synology and unified memories suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.

IMMICH-057 and SYNO-035 need a shared photo row whose trip is gone, which
the foreign key's cascade rules out on a database that enforces it; they
write it with SQLite's foreign keys off as before and are skipped on
Postgres, which has no such switch.
2026-11-17 17:54:16 +01:00
Maurice e1677e7d17 test(db): run the MCP and OAuth suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well. The OAuth service they drove by hand over a second ORM on the
SQLite handle is now the container's own, called in a request context.

The MCP audit cases wait for the mcp.tool_call row: the transport writes
it without awaiting it, so on Postgres it can land after the response.
2026-11-17 17:44:13 +01:00
Maurice 7b0f75a3a4 test(db): run the places and incoming leg mode suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.

The two cases about a NUL byte in a place name move to
places-nul-sqlite.test.ts, listed in SQLITE_ONLY: they pin SQLite's value
quoting, and Postgres text cannot hold U+0000. The control characters
0x01 to 0x1F stay in places.test.ts and run on both engines.
2026-11-17 17:44:07 +01:00
Maurice 8a31a71e1a test(db): run the packing, reservations and journey suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 17:19:20 +01:00
Maurice 741bb651e5 test(db): run the OIDC, passkey, profile, notifications and ORM request context seam suites on the real database module
They reset through resetDatabase (the seam suite needs no reset) and seed
through the ORM factories instead of the SQLite snapshot mock, so they run
in the Postgres lane as well.
2026-11-17 17:00:56 +01:00
Maurice 97bafd3ab3 test(db): run the journey place order, maps, misc and local OIDC provider suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 16:47:38 +01:00
Maurice 27c043be09 test(db): run the admin and auth suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well, the user erasure cases included.
2026-11-17 16:35:24 +01:00
Maurice 6159cb9011 test(db): run the files and collab suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 16:25:48 +01:00
Maurice 6d2bf31bb6 test(db): run the atlas and backup suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 16:18:55 +01:00
Maurice 62228af0d5 test(db): run the assignments, day notes and async closure guard suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 16:13:02 +01:00
Maurice 3572058917 test(db): run the feeds, atlas geocode, collections and Immich suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 16:06:58 +01:00
Maurice cfab220015 test(db): run the boot, boot sweep, demo seed, AirTrail and doc sync context suites on the real database module
They boot the app without the SQLite snapshot mock, so they run in the
Postgres lane as well. The demo seed suite spies on the real runDemoSeed
export instead of replacing the database module to wrap it.
2026-11-17 15:59:20 +01:00
Maurice b377c3656c fix(oauth): narrow the refused registration for the strict compiler 2026-11-17 15:58:02 +01:00
Maurice b11d8d492c test(db): run the session revocation, api docs, app config and help suites on the real database module
They boot the app without the SQLite snapshot mock, so they run in the
Postgres lane as well. sessionRowsOf reads a user's session rows through
a booted app's ORM, next to sessionRows for the suites that still hand in
a better-sqlite3 handle.
2026-11-17 15:50:49 +01:00
Maurice 53ab10afdc test(realtime): run the websocket connection suite on the real database module
Seeds through the ORM factories, resets through resetDatabase and mints
ws-tokens through the container's TokenService instead of one built by hand
over the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 15:40:08 +01:00
Maurice 9631a59c2b test(todo): run the todo MCP tool suite on the real database module
Seeds through the booted container's ORM instead of a second ORM over the
SQLite snapshot mock, and resets through resetDatabase, so it runs in the
Postgres lane as well.
2026-11-17 15:36:13 +01:00
Maurice 40385267fc fix(db): keep the stay filter inside src/db and cover the flag type's missing read
src/db may not import src/nest, so the '<id>.0' shape is spelled where the
filter is. The flag type's undefined read had no test, which left the types
folder below its branch threshold.
2026-11-17 15:33:15 +01:00
Maurice 13b896f384 test(days): run the days suite on the real database module
Seeds through the ORM factories and resets through resetDatabase instead of
the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 15:32:00 +01:00
Maurice 7bbeec9d9a test(budget): run the budget suite on the real database module
Seeds through the ORM factories and resets through resetDatabase instead of
the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 15:27:49 +01:00
Maurice 33f777bcf8 test(categories): run the categories suite on the real database module
It resets through resetDatabase instead of the SQLite snapshot mock, so it
runs in the Postgres lane as well.
2026-11-17 15:24:54 +01:00
Maurice 6010694c08 test(db): reset a suite's database between tests on either engine
resetTestDb needs the SQLite snapshot mock's better-sqlite3 handle, so a
suite resetting with it can only run on SQLite. resetDatabase takes the
booted app's ORM and leaves the same state on SQLite and Postgres: every
table but the kept ones emptied (read from the live schema), sequences left
counting, seedDefaults' rows back through the ORM, and on the first call the
users sequence restarted as the snapshot mock normalises it.
2026-11-17 15:22:48 +01:00
Maurice 03ee902c3d fix(db): type the move's value conversion and client for the server's compiler
Formats the two files the format gate listed.
2026-11-17 15:15:48 +01:00
Maurice 59f0c206bf fix(db): match a stay's bookings by the stored '<id>.0' text, as SQLite did
Reading the TEXT column as an integer also matched '14', ' 14' and '14abc',
which the legacy REAL-bound compare never did (AC37/AC40). Comparing with the
'<id>.0' text the services store keeps that contract on both engines.
2026-11-17 15:15:48 +01:00
Maurice 6a9c1c287f test(auth): a plugin table missing from the schema fails the user erasure
The erasure no longer skips a missing plugin table in a savepoint of its own (61ea6b648); USER-CLEANUP-005 still expected the skip.
2026-11-17 14:57:24 +01:00
Maurice 4b0986e2c6 style(plugins): keep the runtime and the SDK within their size baselines
The plugin data engine added three lines to each; six comments that wrapped past 120 columns now fit in one.
2026-11-17 14:53:24 +01:00
Maurice d253267e49 test(db): the move command's own output and target ORM 2026-11-17 14:49:42 +01:00
Maurice 373d272968 fix(db): set no deferred references once the move refused a value
Nothing is inserted after the first refused value, so the self-references held back had no rows to land on, and the move failed on them instead of listing the values (MOVE-006).
2026-11-17 14:49:41 +01:00
Maurice ebf2a94fd6 style(db): format postgresTarget as Prettier does 2026-11-17 14:43:44 +01:00
Maurice ac5f8ad67e chore(lint): lower the server's no-console baseline to 231
AuthService no longer warns through console when an invite's last use was taken: the registration now refuses it inside its transaction.
2026-11-17 14:43:14 +01:00
Maurice a72f4936e9 fix(db): open the move's SQLite source through openDatabase, keep the drop failure as the cause
ESLint refused both: better-sqlite3 is imported only in src/db/connection.ts and its named neighbours, and an error thrown in a catch carries what that catch caught.
2026-11-17 14:43:02 +01:00
Maurice b931b92fc0 test(realtime): read each parity case after its notification sends have settled
On Postgres a fire-and-forget notification still ran when the case read its recording, so it landed in the next case. The harness now waits for NotificationsService.settled() after each write and each exemption; a late send of any other kind still fails the next case.
2026-11-17 14:33:07 +01:00
Maurice da7d4ff237 feat(notifications): know when the sends a write left running have finished
Most writes start their notification without waiting for it. NotificationsService now tracks each send until it settles, and settled() resolves once every send started before it has finished. The channel check moves to channel-gate.ts, which keeps the service under the size limit.
2026-11-17 14:33:07 +01:00
Maurice f508e0b4c2 test(demo): read the baseline refusal from the logger 2026-11-17 14:33:06 +01:00
Maurice 7e4561b469 test(db): name the restore's plugin schemas as plugin ids allow 2026-11-17 14:24:27 +01:00
Maurice 40e904e237 test(integrations): give the AirTrail suites' UnitOfWork its engine 2026-11-17 14:24:09 +01:00
Maurice c848429820 test(db): no await inside a loop in the Postgres tests 2026-11-17 14:23:13 +01:00
Maurice c46e34dc3a test(db): stand-in pg tools write --file=- to their own stdout
The CI runner gives a child process a socket for stdout, which /dev/stdout cannot open, so every case whose pg_restore streams its script failed there. The COPY terminators in PGTOOLS-020 are spelled as a dump spells them.
2026-11-17 14:23:12 +01:00
Maurice 4e07de492b fix(db): log the demo baseline refusal through the logger, read the tool versions at once 2026-11-17 14:23:12 +01:00
Maurice fa193a400e docs(db): every transaction goes through UnitOfWork, checks read inside it 2026-11-17 14:14:49 +01:00
Maurice 203c7dee7e feat(lint): refuse a transaction outside UnitOfWork under src/
trek/transactions-through-unit-of-work reads the receiver's type and reports
transactional() on anything but a UnitOfWork (an untyped receiver
included), and begin() or transaction() on an EntityManager, a connection
or Kysely. src/db/engine/ and the two boot-time schema files are left out.
It runs with the rest of the server's ESLint, so lint:warnings fails on a
new one, and its message names UnitOfWork, writeTransaction and the rule in
server/CLAUDE.md.
2026-11-17 14:14:49 +01:00
Maurice 0eeee1e884 fix(db): read the checks a write relies on in the transaction that writes
On Postgres a check read before a transaction, or outside one, no longer
holds at the write that follows: the pool runs other requests' writes in
between. Moved into the unit of work that writes:

- the last-admin guard of an admin's role edit and of an account deletion
  (deleteUserCompletely takes a precondition run in its transaction)
- the login lockout guards of the auth settings save and the SSO settings
  save
- the first-account check of an SSO sign-up, which starts over as an
  ordinary sign-up when another account won
- the OAuth client caps, the token cap and the mail intake limits
- the year check before a vacay year is opened, and the label name check of
  a rename

A password sign-up that loses the last use of an invite is now refused, as
the SSO sign-up already was, and a reset link is burned by one conditional
update, so two resets with one link cannot both change the password.
2026-11-17 14:14:40 +01:00
Maurice 61ea6b648c fix(db): take the write lock in every transaction that writes
UnitOfWork took the engine's write lock, but four repositories opened
transactions of their own: the demo addon set, the plugin user erasure's
savepoints, and the plugin metadata and scheduler cap checks. On Postgres
those ran beside the others on the pool.

writeTransaction (src/db/engine/write-transaction.ts) is now the one
transaction that writes: UnitOfWork wraps it, and the demo seed and reset,
which run outside the container, call it with the engine the environment
names. The capped plugin writes run in their caller's unit of work instead
of a transaction of their own, and the plugin erasure runs in the erasure's
transaction without savepoints, since its three tables come with the
migrations on both engines. lint:tx counts writeTransaction as a
transaction.
2026-11-17 14:14:29 +01:00
Maurice 981052224c docs(db): rotating the encryption key on Postgres 2026-11-17 13:54:25 +01:00
Maurice f311fed5c9 test(db): the key rotation on Postgres, and its refusals before a key is asked 2026-11-17 13:54:25 +01:00
Maurice 7065f87dc0 fix(db): rotate the encryption key on Postgres through the server's engine
The rotation ran on the SQLite file only and refused when TREK_DB_URL was
set. Its statements now go through a small store per engine: better-sqlite3
for the file, unchanged, and on Postgres the server's own MikroORM
connection, in one transaction that takes the engine's write lock first. The
Postgres path checks that it reaches a database holding TREK's tables and
that the data directory is writable before it asks for a key, writes a
pg_dump copy before it changes anything, refuses DB_PATH or TREK_DB_FILE
beside the URL, and reads the jsonb addon config the driver hands back
parsed. The SQLite transaction is now BEGIN IMMEDIATE, since better-sqlite3
takes no async function.
2026-11-17 13:54:25 +01:00
Maurice 4eb2c3be58 docs(db): moving an existing install to Postgres, and the refusal of an empty database beside one 2026-11-17 13:41:21 +01:00
Maurice 6d8721ee82 test(db): move a factory-seeded SQLite install into Postgres and read it back through the app 2026-11-17 13:41:21 +01:00
Maurice 36f64c51c8 feat(db): move a SQLite install into an empty Postgres database
npm run db:move-to-postgres (dist/move-to-postgres.js in the image) copies
a SQLite file at this build's migration level into an empty Postgres
database. It refuses a file at another level, rows whose references point
at nothing and a target holding any table or plugin schema, creates the
schema with the engine's own bootstrap, then in one transaction copies every
table in foreign key order (setting a self-reference once its rows are in),
converts each value to its column's type and refuses one Postgres cannot
hold exactly, copies each plugin's plugin.db into its schema, moves the
sequences past the copied ids and compares every table's row count and an
order-free checksum over all rows before it commits. A failure drops the
schema again. The SQLite files and the uploads are never written.
2026-11-17 13:41:20 +01:00
Maurice d177227519 fix(db): refuse a Postgres boot that would leave a SQLite install behind
Setting TREK_DB_URL on an existing SQLite install booted a new, empty
instance beside its data. The Postgres bootstrap now refuses an empty
database, or a migrated one without a single account, while the data
directory's travel.db holds accounts, and names the move command. A file
that cannot be read counts as holding them. TREK_DB_IGNORE_SQLITE_FILE=true
starts anyway, with a warning; the file is opened read-only and only when
the database holds no TREK data.
2026-11-17 13:41:12 +01:00
Maurice a6bc71787e fix(db): find a stay's bookings on Postgres
reservations.accommodation_id is TEXT and holds '14.0'. Compared with a bare
number, Postgres binds the number as the text '14' and finds nothing, so
deleting a stay, a day or a place left its bookings behind with no error. The
three filters read the column as an integer, as the joins already do.
2026-11-17 13:13:26 +01:00
Maurice 5f372fa17f fix(db): type the integer flag and the owner literal for the server's compiler
The server compiles without strictNullChecks, where a narrowed value returned
as is keeps its full type, and two literal arms of one UNION column must share
a type.
2026-11-17 13:11:27 +01:00
Maurice 9f7efd49ea test(db): the Postgres plugin data store against a stand-in client
Covers what every call sets up, the schema check before plugin SQL runs, the
row cap, the time budget between chunks and at statement_timeout, the quota,
a script committed statement by statement, the tx and migrate shapes and one
call at a time per plugin, without a database. The Postgres lane runs the
same store on a real one.
2026-11-17 13:02:48 +01:00
Maurice 8e85fb1c2c docs(db): plugin data on Postgres, its SQL rules and one TREK per database
The plugin-sdk README says what dialect a plugin writes when TREK runs on
Postgres, what the guard refuses and how the limits hold there. The wiki's
Postgres page describes the plugin schemas, their backup and restore and
the one-instance-per-database limit, and its key rotation path now names
the file where it is.
2026-11-17 13:00:55 +01:00
Maurice b82cd03a28 fix(db): carry the plugin data schemas in Postgres backups and restores
pg_dump now names the trek_plugin_ schemas TREK's role owns beside its own
schema. A restore reads the dump's plugin schemas from its table of
contents, drops the plugin schemas the role owns, creates the dump's and
loads them with TREK's schema, all in the one psql transaction. Schemas of
another role and every other schema of the database are never read or
dropped.

The dump's migration history is read from TREK's mikro_orm_migrations only,
so a plugin table of that name cannot pass for it.
2026-11-17 13:00:55 +01:00
Maurice 3460511fa4 feat(plugins): store plugin data on the engine TREK runs on
PLUGIN_DATA binds the plugin data backend to the engine (the same
{ sqlite, postgres }[engine.id] binding the backup port uses): the SQLite
file per plugin, unchanged, or the Postgres schema per plugin. The host
opens a plugin's store through it and an uninstall that deletes data erases
through it, which drops the schema on Postgres. Nothing outside db/engine
asks which engine runs.

A plugin's SQL is passed through as written, so a plugin needs to know the
dialect: db.engine (db:own) answers 'sqlite' or 'postgres', and the SDK
exposes it as ctx.db.engine(), in the mock host (dbEngine option) and in
dev. The plugin facts are regenerated and the SDK goes to 1.10.0.

The Postgres lane's PGPLUG suite installs, uses and erases plugin data on
Postgres and shows that a plugin reaches neither TREK's users table nor
another plugin's schema.
2026-11-17 13:00:47 +01:00
Maurice b345c92493 feat(db): keep a plugin's own data in a Postgres schema of its own
A plugin with db:own got a SQLite WAL file in the data volume whatever the
engine, so a Postgres install still needed a local disk (discussion #386).
This adds the plugin data port (db/engine/plugin-data.ts) and its Postgres
side: one schema per plugin, trek_plugin_<id>, reached through TREK's pool.

Every call runs in a transaction that creates the schema if missing, puts
only it on the search_path and sets statement_timeout to the call's budget.
Reads stream through a cursor and stop at the row cap, a write that grows
the schema past the quota rolls back, and the calls of one plugin run one at
a time on at most half of the pool.

TREK's role may read every table, and a role per plugin would need
CREATEROLE, so plugin-sql-guard.ts checks each statement first: it lexes the
SQL as Postgres does and refuses another schema as a qualifier, the pg_
catalogs and functions, functions that run SQL from a string or reach an
object by a name in one, temporary tables, and every statement but DML and
DDL on tables, indexes, views, sequences and types.
2026-11-17 13:00:39 +01:00
Maurice 7a9a7c1831 refactor(db): keep the touched files within their size baselines
The users identity guard moves to repositories/_shared/user-identity.ts
(Users.repository.ts re-exports UserIdentityTakenError), the flag text pass
of the entity generator to scripts/generate-entities-flags.ts, and the
Wallet pass query takes the repository's EntityManager. The size baseline
of Users.repository.ts is lowered to what it holds now (1445 to 1421); a
few exports only their own file used are no longer exported.
2026-11-17 12:24:08 +01:00
Maurice 99c3c670a5 fix(demo): keep a demo baseline per engine and check it before every reset
The baseline was travel-baseline.db on both engines and went straight into
the swap, so a SQLite baseline left in the data directory made every hourly
reset of a Postgres demo fail inside pg_restore, and never got replaced. It
is now named after the engine's archive entry (travel-baseline.db on
SQLite, travel-baseline.pgdump on Postgres), and the backup port's new
checkCopy refuses one the engine cannot restore before the swap; the reset
then saves a fresh baseline and logs the reason instead of failing hourly.
2026-11-17 12:24:08 +01:00
Maurice 7a99190550 fix(db): reset the admin on Postgres and keep the key rotation off it
reset-admin.js opened data/travel.db with better-sqlite3 whatever the
engine, so on a Postgres install it created a stray SQLite file or reset
the admin in a leftover one. With TREK_DB_URL set it now resets the account
in Postgres through the built server's engine (its pool, SSL and write
lock, in one transaction), and refuses a TREK_DB_FILE beside the URL; the
SQLite branch is unchanged. migrate-encryption.ts cannot re-encrypt the
secrets in Postgres yet, so it now stops before it opens or writes any file
when TREK_DB_URL is set. The wiki says what each does on Postgres.
2026-11-17 12:24:08 +01:00
Maurice 7e8c74b8ff fix(db): sort NULLs where SQLite sorts them on Postgres
SQLite takes NULL as the smallest value and Postgres as the largest, so any
list ordered by a nullable column (bookings without a time, trips without
dates) came back in another order on Postgres. Instead of every ORDER BY
spelling its NULL position, the Postgres engine renders SQLite's wherever a
statement names none: a Kysely query compiler for this.kysely() statements
and a MikroORM platform for find() and the query builder. An explicit
position is kept.

A new Postgres-lane suite checks the answers the probe cannot see: the NULL
order, a stay linked as '14.0' in the public reads, the traveller owner
flag, the identity errors for a lost race, and the plugin caps under a race
on the pool.
2026-11-17 12:24:07 +01:00
Maurice 7bde1ec9d4 fix(plugins): hold the write lock for the plugin cap checks on Postgres
meta.set and scheduler.set checked their caps in a transaction of the
repository's own, which keeps check and write together on SQLite's single
writer but not on Postgres, where two pool connections both read the same
count. Both RPCs now run the capped write inside UnitOfWork.transactional,
which takes the engine's write lock; the repository's transaction becomes a
savepoint of it.
2026-11-17 12:24:07 +01:00
Maurice ec733fc927 fix(db): store addons.enabled as the integer flag on Postgres too
addons.enabled was the one flag MikroORM's boolean type declared as a
Postgres boolean, while SQLite and every other flag hold 0/1, so an addon
migration's usual SET enabled = 1 would fail there and a Kysely read would
answer true instead of 1. The column now uses IntegerFlagType: the entity
still reads a boolean, both engines store 0/1, and the regenerated Postgres
baseline declares it bigint default 0. The entity generator renders the
type for the columns in BOOLEAN_COLUMNS.
2026-11-17 12:24:07 +01:00
Maurice 20fb054d27 docs(db): Postgres 14 to 18, the database role, restore limits and the manual rollback
- Database-Postgres: supported versions, the version 18 client and the tool
  search order, sslrootcert with a client before 16, how to create a role
  that is not a superuser and move an older compose install to one, a
  current schema other than public, and the space a restore needs.
- Updating: the manual rollback clears the whole schema and loads the copy
  in one transaction, as TREK's restore does; dropping only the tables left
  the collation, the trigger functions and the sequences behind. A unit
  test keeps the printed statement equal to CLEAR_SCHEMA_SQL, and the boot's
  rollback hint points at that section.
- Troubleshooting, Install-Docker-Compose, Environment-Variables, README
  and server/CLAUDE.md follow.
2026-11-17 12:24:07 +01:00
Maurice 90e74f4dd8 fix(deploy): run TREK as a role that is not a superuser in the Postgres compose file
The compose file let the postgres image create TREK's role as the
superuser, so a crafted backup restored by TREK could run commands in the
database container. The superuser is now postgres, with a password of its
own, and an init script creates the role trek that owns TREK's database and
nothing more. The Helm values say the same about the role in the URL.
2026-11-17 12:23:51 +01:00
Maurice 9c14f941ba build(docker): ship the PostgreSQL 18 client tools from the PGDG repository
A client handles every server up to its own major and refuses a newer one,
so the image needs the newest supported major, 18, which Debian 13 does not
ship. The PGDG repository is added with its signing key kept in the
repository and its component pinned to 18.
2026-11-17 12:23:51 +01:00
Maurice 6f4dfc486f fix(db): check the Postgres server and tools before a dump or a restore
- The client tools are looked for newest first, from 18 down: a client
  handles every server up to its own major and refuses a newer one. A dump
  or a restore now refuses a client older than the server up front, naming
  both versions, and the boot refuses a server outside PostgreSQL 14 to 18.
- sslrootcert=system is used only by a client from libpq 16 on; an older
  client is refused with a message that names sslrootcert and the bin dir.
- The restore's CVE-2025-8714 table covers 18.
- A restore refuses a role that is a superuser or may run programs or write
  files on the database host, since the archive's SQL runs as that role;
  the boot warns about such a role.
- pg_restore's script is streamed to its work file and stopped once it
  passes BACKUP_MAX_DECOMPRESSED_MB, so a small dump can no longer expand
  without limit on the data volume.
- A failed tool's error keeps only the summarized stderr; its cause names
  the exit code and signal instead of carrying the process error, whose
  message and stderr quoted row data into the log.
- The migration history is looked for in the current schema, where the
  tables and the backups are, so a role whose search_path is not public
  boots a second time.
2026-11-17 12:23:51 +01:00
Maurice ce1c3cf62d fix(db): read unique violations and missing tables the same way on both engines
guardIdentity matched only SQLite's message text, so on Postgres a lost
race for an email or a username escaped as a 500 instead of a 409. The new
dialect module driver-errors.ts reads a unique violation by Postgres's
SQLSTATE 23505 and constraint name, or by SQLite's message, and the users
repository maps the key names of both engines. isMissingTableError moves
there too and also knows Postgres's 42P01 for an unconverted error.
2026-11-17 12:23:50 +01:00
Maurice 28ce04d866 fix(db): return the traveller owner flag as a number on Postgres
The owner and member branches of listTravellerUsernames selected bound
values, which Postgres resolves to text in a UNION column, so the public
API reported every traveller as owner: false. The literals are written into
the statement as integers now.
2026-11-17 12:23:37 +01:00
Maurice 22973036b5 fix(db): match a stay-linked booking on Postgres in the public stay check
publicStayExists cast reservations.accommodation_id straight to integer,
which Postgres refuses for the stored '14.0', so the calendar feed and the
share links failed for every trip once any booking was linked to a stay.
The correlation now goes through accommodationIdMatches, which compares
through the new dialect helper integerTextEqualsKysely, and the Wallet pass
context uses the same helper instead of its own numeric cast.
2026-11-17 12:23:36 +01:00
Maurice 40f6efbf5b docs(db): describe the discovered Postgres lane and the 14/18 job 2026-11-17 12:05:17 +01:00
Maurice e4b990b75e ci(db): run the Postgres probe and lane on Postgres 14 and 18
TREK supports Postgres 14 to 18, and CI tested 17 only. One server-postgres
job per major now runs the probe and then the lane against the same service,
so the change keeps the job count of the two jobs it replaces. The lane's
global setup refuses a service whose major is not TREK_TEST_PG_MAJOR, and
the image's Postgres boot moves to 18, the major its client tools target.

scripts/ci/workflow-jobs.test.mjs fails when a job other than the scan is
missing from ci-ok's needs, and changed-areas pins that migrations,
repositories, the engine and the lane's files always run the job.
2026-11-17 12:04:45 +01:00
Maurice 3b6d7238fe test(db): find the Postgres lane's suites instead of listing them
The lane ran a hand-kept list of 26 suites that had already missed
trip-tags-mcp and the broadcast-parity suites, and listed two that never
touch a database. tests/postgres/lane.ts now takes every test file that
reaches src/bootstrap.ts or src/nest/app.module.ts through its imports and
does not vi.mock src/db/database, minus a named SQLITE_ONLY map with the
reason for each.

tests/unit/postgres-lane.test.ts (PGLANE, in the SQLite lane) fails on a
suite that names a boot entry point the discovery does not see, on a stale
exclusion, and on a new suite that boots the app over the SQLite snapshot
mock; the 105 that still do are held in snapshot-suites-baseline.json,
which only shrinks.
2026-11-17 12:04:45 +01:00
Maurice 16da5dd685 docs(db): the routine for a migration after the Postgres cut 2026-11-17 11:48:18 +01:00
Maurice 53d875aecb fix(db): keep check:pg-baseline speaking once the baseline is frozen
A frozen baseline still has its manifest verified, and the check now lists the
migrations that run on Postgres after the cut and what holds them. Every
problem it reports says what to do about it.
2026-11-17 11:48:18 +01:00
Maurice a748d6c554 feat(db): hold migrations after the Postgres cut to engineDdl in lint:dialect
A migration newer than the baseline's through (read from
assets/postgres/baseline.json) fails on a schema statement outside engineDdl,
a plain string column for addColumnIfMissing or a SQLite-only helper, and on a
SQLite spelling in an engineDdl postgres member. The advice names the two
steps, and the baseline cannot hold an allowance for these rules.
2026-11-17 11:48:17 +01:00
Maurice 90f1f1977d feat(db): print the Postgres side of a new migration with gen:pg-migration
The script builds a scratch database the way a boot does (the baseline, then
the migrations after its cut) up to the target migration, compares it with the
entities by PARITY-PG's rules and prints the remaining statements as the
postgres member of engineDdl. The scratch database is always dropped.
2026-11-17 11:48:17 +01:00
Maurice 8c5e138150 refactor(db): move PARITY-PG's schema comparison into the Postgres engine
Which comparator statements change nothing (drop not null on a live primary
key, spelling-only defaults and checks proven by a rolled-back fingerprint, the
hand-ported triggers) is now one module the parity test and the migration
generator share, with unit tests for the sorting and the rollback.
2026-11-17 11:48:17 +01:00
Maurice 1bf0670566 feat(db): write a migration's schema change once per engine
A migration after the Postgres baseline's cut runs on both engines, but its DDL
is not one language. engineDdl(this, { sqlite, postgres }) queues the statements
of the engine the migration runs on, like addSql, and addColumnIfMissing takes a
column definition per engine, both picked in the dialect layer so a migration
never branches on the engine itself.
2026-11-17 11:48:16 +01:00
Maurice 29cdc594d3 fix(db): cut the Postgres baseline at the newest migration again
The merge with dev brought eight migrations written for SQLite (DATETIME,
INTEGER PRIMARY KEY without identity); run verbatim on Postgres they stop the
first boot. No Postgres install has been released, so the baseline moves to
the newest migration and those tables come from the entities.
2026-11-17 11:31:04 +01:00
Maurice a2d00111ca merge dev into feat/postgres-support 2026-11-17 11:10:01 +01:00
Isaias Tavares 944ab3d29a docs(db): drop a historical note from the reservation join row docstring
"unchanged from the legacy split" describes how the code got here rather
than what it does, and the fold it names is stated in the same sentence.
2026-11-05 01:47:28 -03:00
Isaias Tavares dc4972977c test(probe): pin the presence label the sampler matches
The probe samples a presenceSet pair's flag as true by matching the
tuple label "present" by name, so a rename in the repository helper
would silently stop every partial update from reaching its SQL. The
label is now exported from arg-samples.ts, and a probe test reads the
real presence-set.ts and fails if no named tuple member carries it.
2026-11-05 01:47:28 -03:00
Isaias Tavares 2318308674 fix(db): fail plugin-data erasure on errors other than a missing table
deletePluginUserData swallowed every error from its three DELETEs, so a
lost connection or a refused statement on Postgres looked like success
and left the user's plugin rows behind. It now skips only a table that
does not exist, the case its comment described (a slimmed-down schema),
and rethrows anything else. The missing-table test moves to
isMissingTableError in migration-utils, which already decided this for
the migrations: the ORM maps SQLite's "no such table" and Postgres's
42P01 to TableNotFoundException. The docstring keeps the intent and drops
the plan history.
2026-11-05 01:47:28 -03:00
Isaias Tavares 1551f6d474 refactor(db): group duplicate emails by pushing into each group
The duplicate-email report rebuilt each group's array with a spread on
every row. Pushing into the group that the map already holds says the
same thing without the copies.
2026-11-05 01:47:28 -03:00
Isaias Tavares 783ad5c0f1 refactor(places): read the list's category and tag ids through one helper
The list filter turned its two query-string ids with a destructured
[...].map(), and the null-means-no-match convention (a non-canonical id
matches no place) was carried by a comment and two checks on the
result. placeListIdFilters in places.helpers.ts owns that convention and
returns null when the list must be empty, so the service reads as three
lines. The MCP tool passes the same strings to the same service method,
so it is unchanged.
2026-11-05 01:47:28 -03:00
Isaias Tavares c0bae97a14 refactor(db): comment the qualified upsert targets the same way
RouteUsageDaily and GoogleApiUsage both qualify the target row's columns in
ON CONFLICT ... DO UPDATE, because Postgres reads a bare name there as
ambiguous between the target and excluded (42702). Both now carry the same
comment above the upsert, and GoogleApiUsage's one-column chain sits on one
line like its neighbours. No change to the statements.
2026-11-05 01:47:28 -03:00
Isaias Tavares e82968d66c refactor(db): name the reservation-to-stay join condition once
The TEXT-against-INTEGER join between reservations.accommodation_id and
day_accommodations.id was spelled out eight times across Reservations and
DayAccommodations, each with its own cast and comment. accommodationIdMatches
in _shared/ is the one place that spells it, and it documents why the cast is
there: SQLite coerces the bare comparison and Postgres refuses it. The call
sites now read as what they test. The SQL is unchanged.

The size baseline is lowered to the new line counts.
2026-11-05 01:47:28 -03:00
Isaias Tavares 98533f3dbe refactor(db): type the database settings and inject one engine
The settings for the database were one flat record whose url and pool size
were meaningful only for Postgres, so every reader had to re-check the URL.
They are now a discriminated union per engine (DbEngineSettings): the
Postgres arm carries its URL and a pool size already capped at the ceiling,
and the SQLite arm carries nothing else. The env schema uses the same ceiling
constant, so the boot check and the derivation cannot drift apart.

The engine was resolved from the environment by every caller that needed it
(the lifecycle, the unit of work, the backup adapters), each building its own
instance. The engine is now provided once per container by
DatabaseEngineModule and injected everywhere, so the state an engine keeps
(Postgres's reopen hook) is the same wherever it is used. resolveEngine stays
for the MikroORM CLI config and the DI factory, and nothing else calls it.

The engine's reopen no longer carries a `reopenSwapsConnection` flag. The
engine itself decides what a reopen needs: SQLite closes and reconnects the
ORM's connection before the schema bootstrap (its handle is swapped under
Kysely's cache), and Postgres only migrates, because a restore replaces the
contents of the database the pool already reaches. The Postgres pool is never
closed on a reopen, since ending it waits for connections lent out during the
restore.

The backup ports answer every method the same way. verify() now throws a
DomainError for a refused archive on both engines, and the restore path maps
it back to the same { success: false, error, status } result, so the HTTP
response of a refused restore (status and body) is unchanged. The restore
step that swaps the database and then always reopens it is shared in
nest/backup/database-swap.ts, with the error-description helper in
nest/common, instead of two copies that could drift.
2026-11-05 01:04:21 -03:00
Isaias Tavares 1c3dc93716 refactor(db): keep the SQLite-only helpers and the Postgres number parsers explicit
createStandaloneOrm builds the SQLite schema snapshot, so it now refuses a
config that names another driver instead of silently building a snapshot of
the wrong engine. runSchemaBootstrap takes its snapshot flag as a required
argument: the reopen after a restore is the only caller that skips the copy,
and an omitted flag should not be able to pick a default for it.

The Postgres driver's number parsers say which values they refuse: NaN and
the infinities are reported as not finite instead of as beyond 2^53, which
was the wrong reason. The driver's header comment is folded into the constant
docs it described.
2026-11-05 01:02:04 -03:00
Isaias Tavares b8c9184dff test(db): move the backup, boot-restore and bootstrap tests onto the fake-tool helper
The backup, boot-restore and bootstrap tests stopped hand-writing their
stand-in tools and use tests/helpers/fake-pg-tools.ts, so one definition of
what a stand-in logs and answers covers all four files. The assertions about
adapter behaviour are unchanged.

PGBACKUP-002's refusals become it.each, each keeping its own message check:
a missing archive keeps its exact status test (PGBACKUP-002a), and the
accepted dump is PGBACKUP-002. Five refusals are covered in all: missing,
SQLite, newer, no history, and not a dump; the prompt counted six.

boot-restore hands its tables to the psql stand-in directly rather than
through a file the test writes after the plan is built. The bootstrap test
moves its Logger spy into beforeEach.
2026-11-05 00:42:11 -03:00
Isaias Tavares f3e6480606 test(db): drive the Postgres tool tests from one fake-tool helper
Four test files hand-wrote the stand-in pg_dump, pg_restore and psql
scripts, each in its own shape, and read their arguments by position ($4,
$6, args[3], slice(0, 5)). A change to what the tools are handed would have
meant finding every one of them.

tests/helpers/fake-pg-tools.ts installs the stand-ins: each logs its call,
and what it does is a named snippet (answersSchema, answersTables,
writesFile, writesRestrictedScript, listsMigrations, failsWith, touches,
copiesFileEndingWith). The output file is found by its --file= argument.
readToolCall and flagValues read a call back by name.

pg-tools.test.ts moves onto it. Argument checks use arrayContaining and
named flags; order is asserted only where it is the subject (the clear
script runs before the load, `--` precedes the dump path). PGTOOLS-007 and
PGTOOLS-009 split their scenarios into it.each, keeping their IDs as
suffixes.
2026-11-05 00:42:11 -03:00
Isaias Tavares 5503db4883 refactor(db): generate the Postgres baseline in one pass, check it in two modes
--check migrated a temporary SQLite database twice: once inside the
generation and again to read the triggers for the port check. The generation
now returns the triggers it already read, so a check is one migration.

main is split into writeMode and checkMode, and the frozen-or-not decision
lives in one place, checkBaseline. A baseline whose `through` is the newest
migration must match the entities and port every SQLite trigger; a baseline
frozen behind a newer migration is only checked by its manifest. The old
code made the same decision twice, once for the match and once for the
triggers, and the two could drift apart.

The migrated-database read is split into listing the objects and reading
them, so the temporary file is removed in one place.

Manifest parsing uses a type guard, isBaselineManifest, instead of casts
after a check, and PGBASE-004 pins what it refuses.
2026-11-05 00:36:42 -03:00
Isaias Tavares 33a18f29dd refactor(db): split the Postgres schema adjustments by concern
schema-adjust.ts mixed the statement splitter, the trigger ports and the
column adjustments, and every caller repeated `meta.props as EntityProperty[]
as ColumnMeta[]` to reach them. Now:

- sql-split.ts holds splitStatements. Its scope is written down: `;` outside
  quotes, '/" quoted text and the $$ body, and the session-setting lines it
  drops. A tagged dollar quote ($tag$) is refused with an error instead of
  being split inside, which the splitter could not do correctly.
- postgres-triggers.ts holds the hand-written trigger ports, which the
  baseline and the parity test read by name.
- schema-adjust.ts holds the column adjustments. applyPostgresColumnAdjustments
  (renamed from adjustColumns, which hid that it mutates its input) takes an
  entity's props directly: ColumnMeta now reads customType as unknown, so
  the entity's property metadata satisfies it without a cast. Each adjustment
  is a small function that returns whether it changed the column.

The timestamp check is now `instanceof DbTimestampType` rather than a compare
on the constructor's name, which would have broken silently on a rename.
2026-11-05 00:32:18 -03:00
Isaias Tavares d498fe2bea refactor(db): read the Postgres bootstrap as inspect, create or verify, migrate
bootstrapPostgresSchema did three jobs in one 35-line body, and the safety
net's label came from an `as string` cast on the last executed migration.

It now reads in three steps: inspect what the database holds, then create
the schema from the baseline (createFromBaseline) or verify the recorded
history against this build (refuseNewerHistory), then run the pending
migrations. The label is read from the list with `.at(-1)` and only when
there is one: a database the baseline just created has no history to label
its copy by, which is the case the old `created` flag tested.

The deps keep baseline as a thunk on purpose: the committed baseline is read
only on the create path, so a database already at its head never touches it.
2026-11-05 00:23:08 -03:00
Isaias Tavares 0e93df378f refactor(db): define the "TREK's tables" catalog query once
The bootstrap's currentTables and the client tools' pgTableNames each wrote
the same information_schema query for the current schema, so a change to
which tables count as TREK's would have had to land twice. It is now
CURRENT_SCHEMA_TABLES_SQL in dialect/catalog.ts, beside the other catalog
statements, and both read it.

pgTableNames now lists its names in name order too, as the bootstrap
already did. Nothing reads that order for meaning; the boot-restore refusal
names the first few tables, and that list was already sorted.
2026-11-05 00:21:55 -03:00
Isaias Tavares 1c73ac4c35 refactor(db): split the Postgres client-tool module by concern
pg-tools.ts held six concerns in 366 lines: tool resolution and process
running, the libpq connection environment, the CVE-2025-8714 version policy,
the CLEAR-SCHEMA SQL and the operations themselves. Each now has its own
module, and pg-tools.ts keeps only the operations the backup and the boot
restore call, so their import paths do not change.

- pg-process.ts: PgTool, resolvePgTool, pgConnectionEnv, PgToolMissingError
  and run (stderr is summarized there, as before).
- restore-safety.ts: hasRestrictFix and the refusal. The minimum versions in
  the error are built from the RESTRICT_SINCE table, so the message cannot
  drift from the policy.
- clear-schema.ts: the SQL that empties the schema before a load, unchanged.

The version floor also no longer keeps its own OLDEST_MAJOR and
LAST_MAJOR_WITHOUT_IT constants: both are read from the table. Behaviour is
unchanged. The literal /dev/null is os.devNull, and the COPY parsing of a
dump's migration history is its own function.
2026-11-05 00:20:22 -03:00
Isaias Tavares ae005fc582 fix(db): check the restore script for TREK's tables line by line
pgRestore read the whole pg_restore --file script into one string to find
TREK's migration table before clearing the schema. The script carries every
COPY row of the dump, so a large database made the read exceed V8's maximum
string length before the check ran, and the restore failed with an
unhelpful error instead of loading or refusing.

The check now streams the script with readline and stops at the first
matching line. The match itself is unchanged: the same CREATE TABLE line for
the same quoted schema, so a dump without TREK's history is still refused
before anything is cleared. The regex's escaping is a named helper.

PGTOOLS-005b pins that the script is never read whole.
2026-11-05 00:13:04 -03:00
Isaias Tavares 293cdbc353 fix(assistant): record an unrun change as failed before the stream ends
A decision whose change never ran was written as failed only after the response stream had closed, so a client reading the thread again at once could still find it approved. On the in-memory SQLite database the write won the race; the Postgres lane lost it (ASTE2E-014). The failure is now recorded before the close, in both decision paths, and the stream still closes when that write fails. ASTE2E-026 slows the write down to pin it.
2026-11-04 23:56:09 -03:00
Isaias Tavares 63a2c9db00 docs(db): drop a migration count and a planning reference from comments
The baseline's count went stale with the first migration after the cut, and the lane test pointed at a document outside the repository.
2026-11-04 23:40:13 -03:00
Isaias Tavares e848f343b5 refactor(db): keep the reservations join in its repository
The joined read moved out to reservation-join.ts as a free function, unlike the other files beside the repositories, which hold row types and leave the statements to the repository. joinedQuery() is back in ReservationsRepository with the cast; the row types it answers with move to reservation-rows.ts, which depends on nothing but the Kysely tables.
2026-11-04 23:31:03 -03:00
Isaias Tavares 4325c145ce feat(db): cut the Postgres baseline at the newest migration
The two migrations that landed on dev since the cut were written for SQLite: the longitude wrap subtracts a comparison from an integer, which Postgres refuses. No Postgres database exists yet, so the baseline now stands for both, and a new Postgres install starts with Journey and Collections on, as a new SQLite one does.
2026-11-04 22:54:14 -03:00
Isaias Tavares 53bd8505cd fix(db): read the current schema without SQLite's concatenation spelling
lint:dialect counts every || in src/db as SQLite-only, the psql query that names TREK's schema included. concat_ws gives the same tab-separated line.
2026-11-04 22:54:14 -03:00
Isaias Tavares 298f0409d5 docs(db): record the Supabase checks in the Postgres page
The checklist ran against a Supabase project over the direct connection. The page now says what it found: the CA to verify the server with, the IPv6-only direct host, the postgres role creating the collation, backups holding only TREK's schema, and the latency of a distant region.
2026-11-04 22:46:18 -03:00
Isaias Tavares e0013bc077 docs(db): document running TREK on Postgres, with compose and Helm support
- wiki/Database-Postgres.md: requirements (PostgreSQL 14 to 17, an empty
  database of its own, a role that is not a superuser, ICU), configuration
  and SSL, first boot, upgrades and the .pgdump copy, backups and restore,
  limitations (no SQLite to Postgres move yet, one replica), notes for
  Supabase, and the manual checklist still to run against it.
- docker-compose.postgres.yml: TREK beside a postgres:17 service.
- Helm: database.url (written into the chart's Secret) or
  database.existingSecret supplies TREK_DB_URL; replicas stay at one, now
  for the state TREK keeps in memory.
- Environment variables, backups, updating, troubleshooting, the Docker
  Compose and Helm install pages, the sidebar and the README point at it.
2026-11-04 22:45:32 -03:00
Isaias Tavares 526437926a test(db): run the suites that boot the app on Postgres in their own lane
npm run test:pg --workspace=server (vitest.pg.config.ts) runs every suite
that boots the app through buildApp() on the real database module against
Postgres, each test file on its own copy of one template database the
engine's bootstrap migrates once per run. TREK_TEST_DB_URL names the server;
without it the lane fails instead of passing on nothing. The CI job
'Server: Postgres Tests' runs it on a postgres:17 service and is part of
ci-ok.

tests/postgres/ holds what only Postgres needs proving:
- PARITY-PG: MikroORM's comparator finds nothing between the bootstrapped
  database and the entities. What it reports that changes nothing (key
  columns it would make nullable, defaults and checks Postgres spells its
  own way, the hand-ported triggers) is proven so: the spelling statements
  run in a rolled-back transaction and every default and check must read
  the same after, and every ported trigger must exist.
- the write lock: concurrent read-then-insert units of work never see the
  same count, and counts are numbers; a search ignores case.

tours-hike and tours-plan-types stay on SQLite only: they move a faked
setTimeout on until a tool call ends, which a database over the network
does not finish within.
2026-11-04 22:45:32 -03:00
Isaias Tavares 3f1a786313 fix(db): keep the Postgres pool across a restore
The reopen after a restore closed the ORM's pool and waited for it to end.
Ending a pg pool waits for every connection it has lent out, and one lent
to a job while the restore ran was never handed back, so the restore
request never returned and every later query failed on a destroyed driver.
A Postgres restore replaces the contents of the same database, so the pool
now stays and the reopen only migrates; SQLite still reconnects around its
swapped file.
2026-11-04 22:45:31 -03:00
Isaias Tavares c72b680fec fix(db): keep Postgres backups and restores inside TREK's schema
pg_dump copied every schema of the database, so on a hosted Postgres such
as Supabase a backup carried its auth and storage schemas too, and a
restore failed on them. A dump now holds the current schema only, a
restore loads only that schema, and a dump without TREK's tables in it is
refused before anything is replaced.
2026-11-04 22:45:31 -03:00
Isaias Tavares fc9e634d86 feat(db): back up, restore and copy a Postgres database before migrating it
On Postgres the backup port dumps with pg_dump and restores by turning the
dump into a script with pg_restore and having psql clear the current schema
and run it in one transaction. A dump only recreates what it holds, so a
plain pg_restore --clean would leave a later migration's tables behind and
break the migrations the reopen runs; a restore that fails leaves the
database as it was. A restore refuses a pg_restore or psql older than
17.6/16.10/15.14/14.19, whose script would lack the \restrict line that
keeps a psql meta-command smuggled into an uploaded dump from running
(CVE-2025-8714). A restore
refuses a SQLite archive, a dump without TREK's migration history or one a
newer TREK wrote before anything is replaced, and keeps a dump of the
database it replaces.

RESTORE_FROM_BACKUP loads the archive's dump the same way into a database
that holds no table yet, and is ignored with a warning once it holds one.

Before pending migrations the boot now takes a pg_dump copy to
data/pre-migrate-<last migration>-<time>.pgdump under the same
TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP) policy as the SQLite file, instead of
refusing; a copy that cannot be written refuses the boot.

The tools run by absolute path (TREK_DB_PG_BIN_DIR, or the usual
directories), never through PATH, with the password in PGPASSWORD; an
sslmode that asks for SSL verifies the certificate as the app pool does.
Dumps are written beside their target and renamed into place, readable by
their owner only, and a tool's stderr reaches errors without the lines that
quote SQL or rows. The image installs postgresql-client-17 from Debian 13.
2026-11-04 22:45:31 -03:00
Isaias Tavares 515caffa79 feat(db): keep SQLite's write and search semantics on Postgres
- UnitOfWork transactions take one advisory lock for the database on
  Postgres (DatabaseEngine.serializeWrites, pg_advisory_xact_lock), so a
  MAX(...) + 1 read inside one cannot race another, as with SQLite's single
  writer. SQLite needs nothing.
- ilike(platform, refs) builds the case-insensitive search condition: LIKE
  on SQLite, ILIKE on Postgres, where LIKE is exact. The place searches use it.
- Plugin data erasure runs each statement in its own savepoint: on Postgres a
  failed statement would abort the user's whole erasure transaction.
2026-11-04 22:45:14 -03:00
Isaias Tavares a77705984e feat(db): create and migrate the schema on a Postgres database
With TREK_DB_URL set, TREK now boots on Postgres; without it nothing changes.

- The database engine contract gains open, close, reopen and the schema
  bootstrap; DatabaseLifecycle delegates to the engine resolveEngine() picks.
- An empty Postgres database gets server/assets/postgres/baseline.sql
  (generated from the entities by gen:pg-baseline, with the reference rows
  the migrations up to its cut insert: tour types, provider catalogues,
  addons, app settings) and every migration up to its cut recorded as
  executed, in one transaction. A database holding tables
  without TREK's history is refused before anything is written; a migrated one
  runs the newer-database refusal and its pending migrations, which refuse
  without a copy unless TREK_DB_PRE_MIGRATE_SNAPSHOT=false.
- INTEGER columns are bigint on Postgres (SQLite's INTEGER is 64-bit: an
  epoch-millisecond column overflowed int4), and the engine's driver reads
  bigint and numeric back as numbers, refusing values past 2^53.
- The two SQLite triggers are ported to PL/pgSQL; check:pg-baseline fails
  while a SQLite trigger has no port, and while the baseline drifts from the
  entities before a later migration freezes it.
- Backups and restores on Postgres refuse until they can dump and load one.
- Migration helpers read the catalog per engine (dialect/catalog.ts), and
  the email case index no longer needs group_concat.
- CI runs check:pg-baseline and boots the image on postgres:17 twice.
2026-11-04 22:45:02 -03:00
Isaias Tavares 25f5e34558 feat(db): choose the database engine from TREK_DB_URL
A port for the engine TREK runs on, without changing what it runs on.
src/db/engine/ names the engine (SqliteEngine, PostgresEngine) and builds
the MikroORM config from it; src/mikro-orm.config.ts exports that config for
the CLI and the Nest container alike. Without TREK_DB_URL the config is the
one it was: the shared SQLite driver on TREK_DB_FILE or data/travel.db.

- TREK_DB_URL takes a postgres:// or postgresql:// URL and is masked in the
  boot report; TREK_DB_POOL_MAX sizes the pool (1 to 100, default 10).
  TREK_DB_URL beside TREK_DB_FILE, TREK_DB_JOURNAL_MODE or
  TREK_DB_SYNCHRONOUS refuses the boot as an ambiguous configuration.
- MikroORM builds the pg pool from the URL's host, port, user, password and
  database and drops the rest of the query, so the engine reads sslmode and
  sslrootcert itself. require, verify-ca and verify-full all verify the
  server's certificate, as the pg driver reads them; a mode that would not
  verify, or a misspelt one, refuses.
- Postgres cannot run TREK yet, so a boot with TREK_DB_URL is refused with
  that reason, in the boot check and again where the config is built, before
  anything connects.
- @mikro-orm/postgresql moves to dependencies; pg is plain JavaScript.
- lint:engine-dispatch (CI) holds the engine checks outside src/db/dialect/
  and src/db/engine/ (isSqlite(, isPostgres(, an instanceof on a platform, a
  comparison on the engine's name) to a baseline that starts and stays empty.
2026-11-04 22:45:02 -03:00
Isaias Tavares 62912e5db1 fix(db): run every repository statement the Postgres probe reaches
The probe's baseline is empty now: no repository method Postgres refuses,
none it cannot measure.

- reservations.accommodation_id (TEXT) is cast where it is compared with
  day_accommodations.id (INTEGER), in the four reservation reads and the two
  stay reads; SQLite coerced the bare comparison, Postgres refuses it. The
  joined RS18/RR1 read moves to reservation-join.ts beside the repository.
- The usage counters qualify the target row's column in DO UPDATE SET, which
  Postgres reads as ambiguous with `excluded` otherwise.
- ReservationDayPositions.upsertScoped upserts on its primary key instead of
  INSERT OR REPLACE; position is the only other column and nothing references
  the table, so the row left behind is the same.
- PRAGMA wal_checkpoint and VACUUM INTO move from MaintenanceRepository to
  SqliteMaintenance under src/db/engine/sqlite/, the SQLite engine's folder,
  where lint:dialect allows PRAGMA.
- The places list takes category and tag ids as numbers: the service converts
  the query text with toRowId and answers an empty list for one that is no
  id, instead of binding the text to an integer column.
- The probe samples the `present` flag of a partial update's pair as true, so
  the four update methods that sent no SQL are measured, and it now holds
  SQLSTATE class 22 too: a value of the wrong type reaching a column is the
  code's, since the sampler sends what each parameter declares.
2026-11-04 22:10:18 -03:00
918 changed files with 5777 additions and 33814 deletions
-156
View File
@@ -1,156 +0,0 @@
name: Set up Node and the workspaces
description: >-
Node from .nvmrc, the workspace dependencies from an exact cache or npm ci,
and optionally shared/dist from a cache or a build. Runs after checkout.
# A local action, so it is versioned with the workflow that calls it and needs
# no SHA pin. scripts/ci/changed-areas.mjs counts .github/actions/ like
# test.yml: a change here runs everything.
#
# node_modules is restored only on an exact key: the runner image, the scope,
# the Node ABI, the lockfile and every workspace package.json. There are no
# restore-keys, so a hit is the tree npm ci would build and a miss is a plain
# npm ci. The package.json files are in the key because npm ci is also the
# check that they agree with the lockfile: an edited range without a fresh
# lockfile misses the cache and fails the install, as it did when every job
# ran npm ci. Only pushes to dev and main save, the npm download cache
# included, so pull requests read what their base left and cannot evict it or
# fill the repository's cache quota with entries of their own.
inputs:
scope:
description: >-
Which workspaces to install: full (npm ci), client (shared and client)
or shared (shared alone).
required: true
build-shared:
description: "'true' to restore shared/dist, or build it on a miss."
required: false
default: 'false'
runs:
using: composite
steps:
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
# ImageOS and ImageVersion name the runner image, whose system libraries
# the native modules were built against. They live in the runner's
# environment, not in the env context, so the key is put together here. A
# job in a container has neither; the container's OS release stands in,
# and that job's tree is kept apart from the runner's.
- name: Work out the cache keys
id: keys
shell: bash
env:
SCOPE: ${{ inputs.scope }}
DEPS: ${{ hashFiles('.nvmrc', 'package-lock.json', 'package.json', 'client/package.json', 'server/package.json', 'shared/package.json') }}
SHARED: ${{ hashFiles('shared/src/**', 'shared/package.json', 'shared/tsconfig*.json', 'shared/tsdown.config.ts', 'package-lock.json') }}
run: |
set -euo pipefail
case "$SCOPE" in
full | client | shared) ;;
*) echo "::error::scope must be full, client or shared, not '$SCOPE'"; exit 1 ;;
esac
if [ -n "${ImageOS:-}" ]; then
image="$ImageOS-${ImageVersion:-unknown}"
else
image="container-$(. /etc/os-release && echo "$ID$VERSION_ID")"
fi
abi="$(node -p process.versions.modules)"
echo "nm=nm-$RUNNER_OS-$image-$SCOPE-node$abi-$DEPS" >> "$GITHUB_OUTPUT"
echo "sd=sd-$RUNNER_OS-$SHARED" >> "$GITHUB_OUTPUT"
echo "save=${{ github.event_name == 'push' && (github.ref == 'refs/heads/dev' || github.ref == 'refs/heads/main') }}" >> "$GITHUB_OUTPUT"
- name: Restore node_modules
id: nm
uses: actions/cache/restore@v6
with:
path: |
node_modules
server/node_modules
client/node_modules
shared/node_modules
key: ${{ steps.keys.outputs.nm }}
# The npm download cache only matters when npm ci runs, so it is restored
# only then. It may fall back to an older lockfile's cache: npm ci checks
# every tarball against the lockfile's integrity hash and fetches what is
# missing, so a stale entry only costs downloads.
- name: Restore the npm download cache
id: npm
if: steps.nm.outputs.cache-hit != 'true'
uses: actions/cache/restore@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: npm-${{ runner.os }}-
- name: Install dependencies
if: steps.nm.outputs.cache-hit != 'true'
shell: bash
env:
SCOPE: ${{ inputs.scope }}
run: |
set -euo pipefail
# better-sqlite3 ships no prebuilt binary and compiles on install. The
# hosted runners carry a compiler; the Playwright container of the e2e
# jobs does not, so on a cache miss there it gets one first. A hit,
# the usual case once a push to dev has saved the container's key,
# never reaches this step.
if ! command -v make >/dev/null || ! command -v g++ >/dev/null; then
export DEBIAN_FRONTEND=noninteractive
timeout 300 apt-get update -qq
timeout 300 apt-get install -y -qq --no-install-recommends make g++
fi
case "$SCOPE" in
full) npm ci ;;
# The scoped install keeps @testing-library/dom (a peer of
# @testing-library/react) in the tree.
client) npm ci --workspace shared --workspace client ;;
shared) npm ci --workspace shared ;;
esac
- name: Save node_modules
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
uses: actions/cache/save@v6
with:
path: |
node_modules
server/node_modules
client/node_modules
shared/node_modules
key: ${{ steps.keys.outputs.nm }}
# Only a full install saves the download cache, so the entry holds every
# tarball; a scoped job that finished first would otherwise claim the key
# with part of the tree and no later run would fill it.
- name: Save the npm download cache
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true' && steps.npm.outputs.cache-hit != 'true' && inputs.scope == 'full'
uses: actions/cache/save@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
# The key holds every input of the build: the sources, the package and
# build configs, and the lockfile that pins tsdown and zod.
- name: Restore shared/dist
id: sd
if: inputs.build-shared == 'true'
uses: actions/cache/restore@v6
with:
path: shared/dist
key: ${{ steps.keys.outputs.sd }}
- name: Build shared
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true'
shell: bash
run: npm run build --workspace=shared
- name: Save shared/dist
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
uses: actions/cache/save@v6
with:
path: shared/dist
key: ${{ steps.keys.outputs.sd }}
+1 -4
View File
@@ -7,11 +7,8 @@
# enforce-target-branch.yml moves those onto dev.
#
# Every PR runs test.yml like any other, so ci-ok decides whether it can
# merge. Dependabot runs get no Actions secrets, so server-s3 and the Sonar
# merge. Dependabot runs get no Actions secrets, so s3-contract and the Sonar
# scan skip themselves on these PRs and ci-ok counts the skip as passed.
# A bump of @playwright/test also needs the Playwright container tag and
# digest in test.yml's client-e2e moved by hand; workflow-jobs.test.mjs
# fails the PR until they match.
version: 2
updates:
# The root lockfile covers the client, server and shared workspaces.
+1 -8
View File
@@ -18,16 +18,9 @@ jobs:
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: package-lock.json
# shared's ESLint and Prettier plugins are its own devDependencies, and
# the format ratchet in scripts/lib/ resolves prettier from the root, so
# shared plus the root is the whole tree these checks read. npm ci
# installs exactly what the lockfile says, where npm install could
# resolve anew.
- name: Install dependencies
run: npm ci --workspace shared --include-workspace-root
run: npm install
- name: Run lint & format check
# Both are check-only: lint used to run eslint --fix, which rewrote the
+29 -7
View File
@@ -10,13 +10,6 @@ permissions:
#
# Unsigned on purpose: signing and store uploads need secrets that fork PRs do
# not get, and belong in a release workflow of their own.
#
# package-lock.json is not a trigger: every dependency bump touches it, and a
# Mac build per bump only held the queue. The shells link nothing but the
# @capacitor/* packages, all declared in client/package.json, and a Dependabot
# bump of one of them raises the range there too, so it still runs. The client
# typecheck and the watch and widget snapshot tests run in test.yml on every
# change under client/.
on:
pull_request:
paths:
@@ -31,6 +24,7 @@ on:
- 'client/scripts/check-store-metadata.mjs'
- 'client/fastlane/**'
- 'client/package.json'
- 'package-lock.json'
- 'shared/src/i18n/*/native.ts'
- '.github/workflows/native.yml'
workflow_dispatch:
@@ -188,6 +182,34 @@ jobs:
path: client/ios/WidgetPreviews/out
retention-days: 14
# The watch's half in the UI (client/src/native/watch.ts): the snapshot it
# builds and the ticks it takes back, typechecked and tested here as well,
# so a change to the bridge is checked next to the Swift that reads it.
watch-bridge:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
- name: Install
run: npm ci --workspace=shared --workspace=client
- name: Build shared
run: npm run build --workspace=shared
- name: Typecheck the client
working-directory: client
run: npm run typecheck
- name: Test the widget and watch snapshots
working-directory: client
run: npx vitest run src/native/watch.test.ts src/native/widgets.test.ts src/native/widgetExtras.test.ts
# The watch app on watchOS simulators in its screenshot mode (DemoMode.swift):
# every screen on the largest and the smallest watch, the main ones in every
# language, and the complications, as PNGs to look at without a watch.
+1 -1
View File
@@ -13,7 +13,7 @@ name: Security Scan
# - scout scans the built image, base image packages included. It needs
# the Docker Hub login, so it runs on PRs and pushes into main only and
# skips fork PRs. Whether the image builds at all is test.yml's
# docker job, which a red scan cannot hide.
# docker-image job, which a red scan cannot hide.
on:
pull_request:
branches: [main, dev]
+835 -905
View File
File diff suppressed because it is too large Load Diff
+4 -9
View File
@@ -137,18 +137,13 @@ These principles come out of a full-repo audit and shape all new code:
## Quality gates in CI
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in server-lint-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18: first the Postgres probe, every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18 (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
- **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name.
- **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
- **Tests run beside the gates, in shards.** The client and server suites run in ten slices each on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), the Postgres lane in three per major, and the end-to-end flows in two, and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold. A sliced job states its slice count in its matrix's shard axis, the `i/n` in its name and its `--shard=i/n`; `scripts/ci/workflow-jobs.test.mjs` fails until all three agree, and on any job naming `matrix.shard` or `--shard` whose axis is not the one-line `shard: [1, ..., n]` it reads.
- **Job names read "package: what"** (`Server: Types`, `Client: Tests 3/7`), and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list, and the job-count note there says when a long job needs a slot freed first.
- **Tests run beside the gates, in shards.** The client and server suites run in slices on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold.
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`, and `scripts/ci/workflow-jobs.test.mjs` (in `test:ci-scripts`) fails while a job other than the scan is missing there.
- **The release pull request mirrors the push run.** On the pull request from `dev` into `main` (head branch in this repository), `changes` sets `mirror` and turns every area off (`scripts/ci/changed-areas.mjs`), so no test, gate or scan job runs, and `ci-ok` runs `scripts/ci/mirror-push-run.mjs`: it waits for the `ci-ok` of the push run of `test.yml` on `dev` for exactly the PR's head commit and passes or fails with it. No such push run, one that ended without a verdict, or a wait past 17 minutes fails with a re-run hint, never passes. A push to `dev` lists its changes against the merge base with `main`, not against the previous push, so the run it mirrors covers every area the pull request brings in, even when an earlier push's run was cancelled or red. Testing that commit twice doubled the jobs past the 60 slots.
- **Guides name paths that exist**: the `changes` job runs `scripts/ci/doc-paths.mjs`, which resolves every backtick path in the CLAUDE.md files, `README.md`, `server/src/nest/README.md` and the wiki against the tracked files; the missing ones are listed in `scripts/ci/doc-paths-baseline.json`, which only shrinks (`--update` after a fix).
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there. A change to `test.yml`, to `scripts/ci/` or to a local action under `.github/actions/` runs everything.
- **Setup goes through one local action.** Every job that installs dependencies uses `.github/actions/setup/action.yml` (`scope` full, client or shared; `build-shared`) instead of its own `npm ci`; `workflow-jobs.test.mjs` fails on a job that installs on its own (plugin-sdk's own install in its directory excepted). The action restores node_modules on an exact key (runner image, scope, Node ABI, `.nvmrc`, the lockfile and every workspace `package.json`, so npm ci still refuses a `package.json` out of step with the lockfile; no restore-keys) and shared/dist on a key over shared's sources and build config, and runs `npm ci` or the shared build on a miss. Only pushes to dev and main save, the npm download cache included; pull requests only read.
- **End-to-end runs in the Playwright container**, `mcr.microsoft.com/playwright:v<version>-noble` pinned by digest, so no step installs browsers or system libraries. Dependabot bumps only the lockfile: on every Playwright PR move the tag and its digest in `client-e2e` by hand (`docker buildx imagetools inspect mcr.microsoft.com/playwright:v<version>-noble`); `workflow-jobs.test.mjs` fails until the tag names the lockfile's `@playwright/test` version.
- **Budget: `ci-ok` within ten minutes.** One code run starts at most about 35 long jobs (gates, slices, Postgres, e2e, Docker), so two PR runs fit in the organisation's 60 concurrent jobs. Every job sets `timeout-minutes` of at most 20 (15 for the long ones, 10 for the short ones), which `workflow-jobs.test.mjs` holds. A new long job, slice or shard needs a reason that outweighs its slot; the job-count note at the top of `test.yml` has the numbers.
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there.
- **Runners and Node**: jobs run on `ubuntu-24.04`, not `ubuntu-latest`, and every `setup-node` reads `.nvmrc`. Third-party actions (anything outside `actions/*`) are pinned by commit SHA with the tag in a comment; Dependabot keeps both current.
- **Security scans are advisory.** `security.yml` runs `npm audit` (what the image installs, plus `plugin-sdk`) on every PR and push into dev and main, and Docker Scout on the built image for main. Neither is required: a newly published advisory would turn every open PR red at once. Fixes are held as floors in the root `package.json` `overrides`; npm ignores an `overrides` block in a workspace `package.json`, so never put one there.
- **Releases** are dispatched by hand and refuse a commit whose `ci-ok` is not green. `docker-dev.yml` (any branch, usually dev) is the canary: it builds the dispatched commit as the next minor or major `-pre.N` and moves only `:latest-pre` and `:<major>-pre`. `docker.yml` (main only) bumps the version, commits and tags it, builds both platforms from exactly that commit and moves `:latest`, `:<major>`, `:<major>.<minor>` and `:<version>`. Its `bump=auto` only finalizes a prerelease in flight; without one it stops and asks for patch, minor or major. Ship a release that migrates or changes a lot as a prerelease first, and as a minor, so installs pinned to `:<major>.<minor>` can wait it out.
+5 -5
View File
@@ -94,8 +94,8 @@ RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/p
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
chown -R node:node /app
# gosu rebuilt with a current Go toolchain (stage 0). The entrypoint drops to node
# with setpriv since #3135; gosu stays in the image for anyone who calls it by hand.
# gosu rebuilt with a current Go toolchain (stage 0) — the entrypoint script uses
# it to drop to node.
COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
ENV XDG_CACHE_HOME=/tmp/kf6-cache
@@ -120,7 +120,7 @@ COPY --chown=node:node wiki ./wiki
# tsconfig-paths/register reads this at runtime to resolve MCP SDK paths.
COPY --chown=node:node server/tsconfig.json ./server/
# Encryption-key rotation is run on demand via tsx (a prod dep) straight from the
# raw .ts source (the command and its stores module). They never enter dist, so they must be copied in explicitly or
# raw .ts source (the command and its stores module) — they never enter dist, so they must be copied in explicitly or
# `node --import tsx scripts/migrate-encryption.ts` fails with module-not-found.
COPY --chown=node:node server/scripts/migrate-encryption.ts server/scripts/migrate-encryption-stores.ts ./server/scripts/
# Admin recovery script (node server/reset-admin.js) for locked-out installs.
@@ -173,8 +173,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
# carrying quotes does not survive that round-trip (the container then dies with
# a shell syntax error before Node starts). A CMD of one bare token does.
COPY server/scripts/entrypoint.sh /usr/local/bin/trek-entrypoint
# Root-owned on purpose: it runs as root and drops to node itself, with setpriv.
# chmod is explicit because a checkout on Windows carries no exec bit.
# Root-owned on purpose — this is what calls gosu, so it runs before the drop to
# node. chmod is explicit because a checkout on Windows carries no exec bit.
RUN chmod 0755 /usr/local/bin/trek-entrypoint
ENTRYPOINT ["dumb-init", "--"]
+2 -2
View File
@@ -188,8 +188,8 @@ env:
# under existingSecretKey and the chart writes nothing. existingSecret wins over url. The
# variable is required when either is set: a missing Secret key stops the pod instead of
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
# (nor a member of one, nor hold a right that reaches the server's files or programs): a
# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
# (nor hold pg_execute_server_program or pg_write_server_files): a restore runs the backup's
# SQL as that role and refuses one that could reach the database host. The wiki page shows the
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database:
@@ -1,60 +0,0 @@
package com.liketrek.trek;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The log line for a page of the server that came back with an error status.
* "HTTP 503" on the address screen cannot tell the server, a proxy in front of
* it and something on the phone apart, so the line names the page and the
* headers that say who answered (#3014).
*/
final class PageErrorLog {
/** The headers that name whoever answered a page, in the order they are logged. */
private static final String[] SENDER_HEADERS = { "Server", "Via", "CF-Ray", "Content-Type" };
private PageErrorLog() {}
/**
* For example "Page answered HTTP 503 Service Unavailable for
* https://trek.example.com/login (server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA)".
* The address goes without its query and fragment, where a sign-in page
* carries a challenge or a code. A header the answer did not have is left
* out, and an answer with none of them says so: no server sends a page
* without at least its type, so that points at something on the phone.
*/
static String describe(String url, int status, String reason, Map<String, String> headers) {
StringBuilder line = new StringBuilder("Page answered HTTP ").append(status);
if (reason != null && !reason.trim().isEmpty()) line.append(' ').append(reason.trim());
line.append(" for ").append(withoutQuery(url));
List<String> senders = new ArrayList<>();
for (String name : SENDER_HEADERS) {
String value = header(headers, name);
if (value != null && !value.trim().isEmpty()) senders.add(name.toLowerCase(Locale.ROOT) + ": " + value.trim());
}
line.append(senders.isEmpty() ? " (no server headers)" : " (" + String.join(", ", senders) + ")");
return line.toString();
}
/** A header by name, whatever case the answer wrote it in. */
private static String header(Map<String, String> headers, String name) {
if (headers == null) return null;
for (Map.Entry<String, String> entry : headers.entrySet()) {
if (name.equalsIgnoreCase(entry.getKey())) return entry.getValue();
}
return null;
}
private static String withoutQuery(String url) {
if (url == null) return "";
int end = url.length();
int query = url.indexOf('?');
if (query >= 0) end = query;
int fragment = url.indexOf('#');
if (fragment >= 0 && fragment < end) end = fragment;
return url.substring(0, end);
}
}
@@ -202,23 +202,14 @@ class TrekWebViewClient extends BridgeWebViewClient {
* none, as Cloudflare does with a 403, sends the app to the address screen,
* which says so and offers to add one. Any other 4xx page (a proxy's block
* page, a certificate it refused) stays up with the bar and its way out, so
* the app is never stuck on a page without TREK's UI. Each one is logged
* with its address and whoever answered it (PageErrorLog).
* the app is never stuck on a page without TREK's UI.
*/
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
int status = errorResponse.getStatusCode();
if (!request.isForMainFrame()) {
super.onReceivedHttpError(view, request, errorResponse);
return;
}
Log.w("TrekShell", PageErrorLog.describe(
request.getUrl().toString(),
status,
errorResponse.getReasonPhrase(),
errorResponse.getResponseHeaders()
));
if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
} else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
TrekServerStore.setFailure(view.getContext(), "HTTP " + status);
onUnreachable.run();
} else if (status >= 400) {
@@ -82,12 +82,10 @@ abstract class TrekWidget : GlanceAppWidget() {
// Read inside the composition: a session outlives one update, and every
// write (the dashboard's, then each trip's) must reach it.
val version by WidgetStore.version.collectAsState()
val stored = remember(version) {
val snapshot = remember(version) {
val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO
WidgetStore.load(context, tripId)
}
// The day of the trip is today's on every update, not the one the app last wrote.
val snapshot = stored?.on(LocalDate.now())
TrekWidgetTheme.Themed { Content(snapshot) }
}
}
@@ -27,28 +27,7 @@ data class WidgetSnapshot(
val labels: Labels,
/** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */
val flight: Flight? = null,
/**
* The trip's days from the day the app wrote this on, each with its date, so
* the widget turns to the next day itself (see [on]); empty from an app
* that predates them.
*/
val days: List<Today> = emptyList(),
) {
/**
* The snapshot as it reads on [date]: that date's trip day out of [days],
* none before or after the trip, and only the bookings from that date on.
* The app writes its snapshot only while it runs, so without this a widget
* showed the day it last ran. A snapshot without [days] reads as written.
*/
fun on(date: LocalDate): WidgetSnapshot {
if (days.isEmpty()) return this
val key = date.toString()
return copy(
today = days.firstOrNull { it.date == key },
bookings = bookings.filter { (it.date ?: key) >= key },
)
}
data class Trip(
val title: String,
val start: String,
@@ -73,8 +52,7 @@ data class WidgetSnapshot(
val symbol: String?,
)
/** A trip day; [date] (yyyy-MM-dd) is absent from an app that predates the days ahead. */
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?, val date: String? = null)
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?)
data class Weather(
val temp: Int,
@@ -234,16 +212,6 @@ data class WidgetSnapshot(
null
}
private fun dayOf(t: JSONObject): Today = Today(
dayLabel = t.optString("dayLabel"),
stops = t.optJSONArray("stops").objects().map {
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
},
index = t.int("index"),
total = t.int("total"),
date = t.str("date"),
)
fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot(
trip = o.optJSONObject("trip")?.let {
Trip(
@@ -258,8 +226,16 @@ data class WidgetSnapshot(
memberCount = it.int("memberCount"),
)
},
today = o.optJSONObject("today")?.let(::dayOf),
days = o.optJSONArray("days").objects().map(::dayOf),
today = o.optJSONObject("today")?.let { t ->
Today(
dayLabel = t.optString("dayLabel"),
stops = t.optJSONArray("stops").objects().map {
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
},
index = t.int("index"),
total = t.int("total"),
)
},
weather = o.optJSONObject("weather")?.let {
Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain"))
},
@@ -1,51 +0,0 @@
package com.liketrek.trek
import org.junit.Assert.assertEquals
import org.junit.Test
/** The log line for a page that came back with an error status (#3014). */
class PageErrorLogTest {
@Test
fun namesThePageItsStatusAndWhoAnswered() {
val line = PageErrorLog.describe(
"https://trek.example.com/login?redirect=%2F#top",
503,
"Service Unavailable",
mapOf(
"server" to "cloudflare",
"CF-RAY" to "8f1a2b3c4d5e6f70-FRA",
"content-type" to "text/html; charset=UTF-8",
"Set-Cookie" to "session=secret",
),
)
// Any case of a header name is read, only the naming headers are logged,
// and the query with its sign-in state is left off.
assertEquals(
"Page answered HTTP 503 Service Unavailable for https://trek.example.com/login " +
"(server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA, content-type: text/html; charset=UTF-8)",
line,
)
}
@Test
fun anAnswerWithoutHeadersSaysSo() {
assertEquals(
"Page answered HTTP 503 for https://trek.example.com/ (no server headers)",
PageErrorLog.describe("https://trek.example.com/", 503, null, emptyMap()),
)
assertEquals(
"Page answered HTTP 502 Bad Gateway for (no server headers)",
PageErrorLog.describe(null, 502, "Bad Gateway", null),
)
}
@Test
fun aFragmentBeforeAQuestionMarkEndsTheAddressThere() {
assertEquals(
"Page answered HTTP 500 for https://trek.example.com/trips/4 (via: 1.1 proxy)",
PageErrorLog.describe("https://trek.example.com/trips/4#a?b", 500, " ", mapOf("Via" to "1.1 proxy")),
)
}
}
@@ -99,34 +99,4 @@ class WidgetSnapshotTest {
assertEquals("ferry.fill", TrekIcons.booking("cruise").first)
assertEquals("bookmark.fill", TrekIcons.booking("something").first)
}
@Test
fun turnsToTheDayOfTheDateItIsReadOn() {
val json = """{"trip":{"title":"T","start":"2026-11-06","end":"2026-11-08","path":"/trips/1"},
"today":{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
"days":[
{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
{"date":"2026-11-07","dayLabel":"Day 2 of 3","stops":[{"time":"10:00","name":"Harbour","minutes":600}]}
],
"bookings":[
{"title":"Hotel","kind":"hotel","date":"2026-11-06","confirmed":true,"path":"/trips/1"},
{"title":"Train","kind":"train","date":"2026-11-07","confirmed":true,"path":"/trips/1"}
],
"labels":{}}"""
val snapshot = WidgetSnapshot.parse(json)!!
assertEquals("Day 1 of 3", snapshot.on(LocalDate.of(2026, 11, 6)).today!!.dayLabel)
val second = snapshot.on(LocalDate.of(2026, 11, 7))
assertEquals("Day 2 of 3", second.today!!.dayLabel)
assertEquals("Harbour", second.today!!.stops.single().name)
assertEquals(listOf("Train"), second.bookings.map { it.title })
// A day the app wrote nothing for (the trip is over) shows no day.
assertNull(snapshot.on(LocalDate.of(2026, 11, 9)).today)
}
@Test
fun aSnapshotWithoutDaysReadsAsWritten() {
val snapshot = WidgetSnapshot.parse(WidgetSamples.json(running = true, now = today))!!
assertTrue(snapshot.days.isEmpty())
assertEquals(snapshot, snapshot.on(today.plusDays(3)))
}
}
@@ -121,9 +121,6 @@ class TrekBridgeViewController: CAPBridgeViewController {
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
)
let corner = cornerElement(in: frame, window: window)
if corner != .zero, cornerWindowSizes.insert(sizeKey(window.bounds.size)).inserted {
setNeedsStatusBarAppearanceUpdate()
}
if !force, insets == publishedSafeArea, corner == publishedCorner { return }
publishedSafeArea = insets
publishedCorner = corner
@@ -142,36 +139,15 @@ class TrekBridgeViewController: CAPBridgeViewController {
private var publishedCorner: UIEdgeInsets?
// MARK: - The status bar beside a corner element
/// The window sizes on which a corner element was seen. On an iPhone Duo
/// that element is the status capsule, so the app hides the status bar
/// there to take the capsule away; whatever still covers the corner stays
/// in the safe area the page keeps clear of. A size stays in the set
/// once seen: with the bar hidden the next measure may find no corner, and
/// showing the bar again would bring the capsule back and start over. The
/// folded and the unfolded display differ in size, so each keeps its own
/// answer, and a device without such an element never hides its bar.
private var cornerWindowSizes = Set<String>()
private func sizeKey(_ size: CGSize) -> String {
"\(Int(size.width.rounded()))x\(Int(size.height.rounded()))"
}
override var prefersStatusBarHidden: Bool {
if super.prefersStatusBarHidden { return true }
guard let size = view.window?.bounds.size else { return false }
return cornerWindowSizes.contains(sizeKey(size))
}
/// An element in a top corner of the screen, such as the status capsule of
/// an iPhone Duo: how far down it reaches (top) and how wide it is on its
/// side (left/right), in the web view's coordinates; zero where there is
/// none. iOS 26 tells a corner apart from a whole edge: the safe area with
/// the corner avoided vertically reaches lower than the one avoiding it
/// horizontally, which in turn is wider on the corner's side. The page
/// counts it into its safe area (mobile.css): upright its content starts
/// below the element, on a wide window it leaves the element's side free.
/// horizontally, which in turn is wider on the corner's side. The page puts
/// its top bar beside the element and starts its content below it, using
/// the full width (mobile.css), instead of giving up a strip of the whole
/// height.
private func cornerElement(in frame: CGRect, window: UIWindow) -> UIEdgeInsets {
guard #available(iOS 26.0, *) else { return .zero }
let vertical = view.edgeInsets(for: .safeArea(cornerAdaptation: .vertical))
+2 -21
View File
@@ -686,8 +686,9 @@ extension TrekShellPlugin {
/// know are left out, so the shell offers only what can really be bought.
@objc func storeProducts(_ call: CAPPluginCall) {
let ids = call.getArray("ids", String.self) ?? []
// TestFlight, App Review and Xcode builds buy in the sandbox; their receipt says so.
let sandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
Task {
let sandbox = await Self.buysInSandbox()
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
call.resolve(["products": [], "sandbox": sandbox])
return
@@ -696,26 +697,6 @@ extension TrekShellPlugin {
}
}
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
/// The signed app transaction names its environment; the receipt's file name,
/// which App Review builds do not always carry, is only the fallback where the
/// app transaction is missing (iOS 15) or cannot be read.
static func buysInSandbox() async -> Bool {
let receiptSaysSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
guard #available(iOS 16.0, *), let result = try? await AppTransaction.shared else {
return receiptSaysSandbox
}
// An unverified transaction still names the environment it was signed in;
// it only decides whether the button shows, the cloud checks every purchase itself.
let transaction: AppTransaction
switch result {
case .verified(let signed), .unverified(let signed, _):
transaction = signed
}
return transaction.environment != .production || receiptSaysSandbox
}
/// Feature storeKit: runs the App Store purchase sheet. Resolves with `kind`
/// bought (with the signed transaction the control plane verifies), cancelled,
/// pending (Ask to Buy, a payment the bank still has to approve) or failed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 104 KiB

@@ -21,14 +21,12 @@ struct TrekProvider: TimelineProvider {
func getSnapshot(in context: Context, completion: @escaping (TrekEntry) -> Void) {
let stored = WidgetSnapshot.load()
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
let now = Date()
completion(TrekEntry(date: now, snapshot: snapshot?.on(now)))
completion(TrekEntry(date: Date(), snapshot: snapshot))
}
/// An entry every quarter hour for the next six hours, so the now line and
/// the next stop move on without the app, each with the trip day of its own
/// date: the one at midnight turns to the next day. The app reloads the
/// timeline whenever it writes a new snapshot, WidgetKit when it runs out.
/// the next stop move on without the app; the app reloads the timeline
/// whenever it writes a new snapshot.
func getTimeline(in context: Context, completion: @escaping (Timeline<TrekEntry>) -> Void) {
completion(TrekProvider.timeline(WidgetSnapshot.load()))
}
@@ -38,11 +36,10 @@ struct TrekProvider: TimelineProvider {
let calendar = Calendar.current
let minute = calendar.component(.minute, from: now)
let firstStep = calendar.date(byAdding: .minute, value: 15 - minute % 15, to: now) ?? now
var entries = [TrekEntry(date: now, snapshot: snapshot?.on(now))]
var entries = [TrekEntry(date: now, snapshot: snapshot)]
for step in 0..<24 {
if let date = calendar.date(byAdding: .minute, value: step * 15, to: firstStep) {
let at = calendar.date(bySetting: .second, value: 0, of: date) ?? date
entries.append(TrekEntry(date: at, snapshot: snapshot?.on(at)))
entries.append(TrekEntry(date: calendar.date(bySetting: .second, value: 0, of: date) ?? date, snapshot: snapshot))
}
}
return Timeline(entries: entries, policy: .atEnd)
+10 -29
View File
@@ -512,8 +512,8 @@ struct StopList: View {
ForEach(Array(window.enumerated()), id: \.offset) { offset, stop in
let past = (stop.minutes ?? Int.max) < nowMinutes
let isNext = !past && (offset == 0 || (window[offset - 1].minutes ?? Int.max) < nowMinutes)
if isNext && offset > 0, let nowLabel { nowLine(nowLabel, in: window) }
row(stop, in: window, past: past, isNext: isNext, last: offset == window.count - 1)
if isNext && offset > 0, let nowLabel { nowLine(nowLabel) }
row(stop, past: past, isNext: isNext, last: offset == window.count - 1)
}
}
}
@@ -528,33 +528,13 @@ struct StopList: View {
private var ink: Color { onPhoto ? .white : Trek.ink(scheme) }
/// The time column, as wide as the longest time in the window (and the now
/// marker's label): every row lays all of them over each other, hidden, so
/// "5:45 AM" fits as well as "09:30" and the dots still stand in one line.
private func timeColumn<Label: View>(_ window: [WidgetSnapshot.Stop], @ViewBuilder label: () -> Label) -> some View {
ZStack(alignment: .leading) {
ForEach(Array(window.enumerated()), id: \.offset) { _, stop in
Text(stop.time ?? "–").font(Trek.number(11.5, .heavy)).hidden()
}
if let nowLabel { nowText(nowLabel).hidden() }
label()
}
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
.frame(minWidth: 38, alignment: .leading)
}
private func nowText(_ label: String) -> some View {
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
}
private func row(_ stop: WidgetSnapshot.Stop, in window: [WidgetSnapshot.Stop], past: Bool, isNext: Bool, last: Bool) -> some View {
private func row(_ stop: WidgetSnapshot.Stop, past: Bool, isNext: Bool, last: Bool) -> some View {
let color = Color(css: stop.color) ?? (onPhoto ? .white : Trek.info)
return HStack(alignment: .top, spacing: 8) {
timeColumn(window) {
Text(stop.time ?? "–").font(Trek.number(11.5, isNext ? .heavy : .semibold))
}
.padding(.top, 1)
Text(stop.time ?? "–")
.font(Trek.number(11.5, isNext ? .heavy : .semibold))
.frame(width: 38, alignment: .leading)
.padding(.top, 1)
VStack(spacing: 0) {
ZStack {
Circle().fill(color).frame(width: isNext ? 11 : 8, height: isNext ? 11 : 8)
@@ -582,9 +562,10 @@ struct StopList: View {
.frame(height: 24, alignment: .top)
}
private func nowLine(_ label: String, in window: [WidgetSnapshot.Stop]) -> some View {
private func nowLine(_ label: String) -> some View {
HStack(spacing: 5) {
timeColumn(window) { nowText(label) }
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
.frame(width: 38, alignment: .leading)
Circle().fill(Trek.danger).frame(width: 5, height: 5).frame(width: 15)
Rectangle().fill(Trek.danger).frame(height: 1.2)
}
+1 -2
View File
@@ -63,8 +63,7 @@ struct TrekTripProvider: AppIntentTimelineProvider {
func snapshot(for configuration: SelectTripIntent, in context: Context) async -> TrekEntry {
let stored = WidgetSnapshot.load(trip: configuration.trip?.id)
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
let now = Date()
return TrekEntry(date: now, snapshot: snapshot?.on(now))
return TrekEntry(date: Date(), snapshot: snapshot)
}
func timeline(for configuration: SelectTripIntent, in context: Context) async -> Timeline<TrekEntry> {
@@ -35,8 +35,6 @@ struct WidgetSnapshot: Codable {
}
struct Today: Codable {
/// The calendar day it is, yyyy-MM-dd (absent from an app that predates `days`).
var date: String?
var dayLabel: String
var stops: [Stop]
/// 1-based position of today in the trip.
@@ -247,9 +245,6 @@ struct WidgetSnapshot: Codable {
var trip: Trip?
var today: Today?
/// The trip's days from the day the app wrote this on, each with its date,
/// so the widget turns to the next day itself (see `on(_:)`).
var days: [Today]?
var weather: Weather?
var bookings: [Booking]?
var todos: Todos?
@@ -311,26 +306,6 @@ struct WidgetSnapshot: Codable {
return days + 1
}
/// The snapshot as it reads on `date`: that date's trip day out of `days`,
/// none before or after the trip, and only the bookings from that date on.
/// The app writes its snapshot only while it runs, so without this a widget
/// showed the day it last ran (TestFlight feedback: "stuck on day 1"). A
/// snapshot from an app without `days` reads as it was written.
func on(_ date: Date) -> WidgetSnapshot {
guard let days, !days.isEmpty else { return self }
let key = WidgetSnapshot.key(date)
var snapshot = self
snapshot.today = days.first { $0.date == key }
snapshot.bookings = bookings?.filter { ($0.date ?? key) >= key }
return snapshot
}
/// A date as the app writes one, yyyy-MM-dd in the device's calendar day.
static func key(_ date: Date) -> String {
let parts = Calendar.current.dateComponents([.year, .month, .day], from: date)
return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
}
static func daysBetween(_ from: Date, _ to: Date) -> Int? {
let calendar = Calendar.current
return calendar.dateComponents([.day], from: calendar.startOfDay(for: from), to: calendar.startOfDay(for: to)).day
+5 -5
View File
@@ -3,16 +3,16 @@
"@typescript-eslint/no-non-null-assertion": 367,
"@typescript-eslint/no-misused-promises": 820,
"no-console": 88,
"complexity": 216,
"@typescript-eslint/no-explicit-any": 138,
"trek/no-swallowed-catch": 126,
"complexity": 217,
"@typescript-eslint/no-explicit-any": 143,
"trek/no-swallowed-catch": 127,
"max-params": 31,
"trek/store-without-selector": 66,
"react-hooks/refs": 534,
"react-hooks/set-state-in-effect": 189,
"@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 113,
"@typescript-eslint/no-unused-vars": 117,
"@typescript-eslint/no-unused-vars": 121,
"react-hooks/immutability": 28,
"max-lines-per-function": 127,
"react-hooks/static-components": 50,
@@ -35,7 +35,7 @@
},
"tests": {
"@typescript-eslint/no-explicit-any": 489,
"@typescript-eslint/no-non-null-assertion": 1872,
"@typescript-eslint/no-non-null-assertion": 1875,
"@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 51,
"@typescript-eslint/no-floating-promises": 33,
+3 -3
View File
@@ -190,7 +190,7 @@
{
"feature": "Booking mail import: admin card",
"hooks": ["src/components/Admin/mailIngest/useMailIngestAdmin.ts", "src/components/Admin/mailIngest/mailIngestAdminModel.ts"],
"desktop": ["src/components/Admin/mailIngest/MailIngestAddonTile.tsx"],
"desktop": ["src/components/Admin/mailIngest/MailIngestAdminCard.tsx"],
"mobile": ["src/mobile/screens/admin/MMailIngestAdminCard.tsx"]
},
{
@@ -1113,8 +1113,8 @@
"mobile": ["src/mobile/screens/admin/MAdminSchoolHolidayCatalog.tsx"]
},
{
"feature": "Trip settings: members, guests, public and invite link, the trip's own addons",
"hooks": ["src/components/Trips/useTripShare.ts", "src/components/Trips/useTripAddonRows.ts"],
"feature": "Trip settings: members, guests, public and invite link",
"hooks": ["src/components/Trips/useTripShare.ts"],
"desktop": ["src/components/Trips/TripShareDialog.tsx"],
"mobile": ["src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx"]
}
+1
View File
@@ -1542,6 +1542,7 @@
"src/pages/journeyDetail/useJourneyDetail.ts",
"src/pages/journeyDetail/useProviderPhotoAdds.test.tsx",
"src/pages/journeyDetail/useProviderPhotoAdds.ts",
"src/pages/journeyPublic/journeyPublicModel.ts",
"src/pages/journeyPublic/useJourneyPublic.ts",
"src/pages/journeyStudio/useJourneyStudio.test.tsx",
"src/pages/journeyStudio/useJourneyStudio.ts",
+1 -1
View File
@@ -27,7 +27,7 @@
"pdf.ts": 1,
"perm.ts": 4,
"places.ts": 9,
"planner.ts": 52,
"planner.ts": 53,
"reservations.ts": 21,
"roadtrip.ts": 36,
"settings.ts": 37,
+1
View File
@@ -35,6 +35,7 @@
"components/Map/nightPauseMarker.ts": 4,
"components/Map/ratingBadge.ts": 1,
"components/Map/switcherRow.ts": 1,
"components/PDF/TripPDF.tsx": 7,
"components/PDF/tripMapImage.ts": 1,
"components/Packing/PackingListPanelBagCard.tsx": 1,
"components/Packing/PackingListPanelCategoryGroup.tsx": 3,
+1 -1
View File
@@ -22,6 +22,6 @@
"src/pages/TripPlannerPage.tsx": 1128,
"src/pages/atlas/useAtlas.ts": 1207,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3269,
"src/styles/studio.css": 1918
}
+3 -2
View File
@@ -43,7 +43,7 @@
"src/components/Map/ReservationOverlay.test.tsx": 1,
"src/components/Map/transitGeometry.ts": 1,
"src/components/Map/useMarkerThumbs.ts": 1,
"src/components/PDF/TripPDF.tsx": 1,
"src/components/PDF/TripPDF.tsx": 38,
"src/components/Planner/DayPlanSidebar.constants.ts": 1,
"src/components/Planner/DayPlanSidebar.tsx": 52,
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
@@ -113,6 +113,7 @@
"src/pages/AtlasPage.tsx": 6,
"src/pages/FilesPage.tsx": 1,
"src/pages/JourneyDetailPage.tsx": 1,
"src/pages/JourneyPublicPage.test.tsx": 1,
"src/pages/LoginPage.tsx": 1,
"src/pages/VacayPage.tsx": 1,
"src/pages/admin/useAdmin.ts": 4,
@@ -129,7 +130,7 @@
"src/pages/tripPlanner/usePlaceEdits.ts": 2,
"src/pages/tripPlanner/usePlaceFormOpeners.test.ts": 2,
"src/pages/tripPlanner/usePlaceFormOpeners.ts": 1,
"src/pages/tripPlanner/useTripPlanner.ts": 1,
"src/pages/tripPlanner/useTripPlanner.ts": 2,
"src/repo/tripRepo.ts": 2,
"src/store/slices/budgetSlice.test.ts": 1,
"src/utils/formatters.test.ts": 1,
+2 -1
View File
@@ -72,6 +72,7 @@
"components/Map/ratingBadge.ts": 2,
"components/Map/reservationsMapbox.ts": 1,
"components/Map/switcherRow.ts": 1,
"components/PDF/TripPDF.tsx": 44,
"components/Packing/PackingListPanelBagModal.tsx": 2,
"components/Packing/PackingListPanelCategoryGroup.tsx": 5,
"components/Packing/PackingListPanelHeader.tsx": 3,
@@ -145,7 +146,7 @@
"mobile/components/MToastHost.tsx": 2,
"mobile/components/MUserPickerList.tsx": 1,
"mobile/screens/admin/MAdmin.tsx": 8,
"mobile/screens/admin/MAdminAddonManager.tsx": 3,
"mobile/screens/admin/MAdminAddonManager.tsx": 4,
"mobile/screens/admin/MAdminAuditLogPanel.tsx": 15,
"mobile/screens/admin/MAdminBackupPanel.tsx": 7,
"mobile/screens/admin/MAdminCategoryManager.tsx": 8,
-2
View File
@@ -30,7 +30,6 @@ import { takeResumeRoute, useRememberRoute } from './utils/resumeRoute'
import { usePermissionsStore, PermissionLevel } from './store/permissionsStore'
import { useInAppNotificationListener } from './hooks/useInAppNotificationListener.ts'
import { useRoadtripPreferencesSync } from './hooks/useRoadtripPreferencesSync'
import { useTripAddonsSync } from './hooks/useTripAddonsSync'
import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTriggers'
import OfflineBanner from './components/Layout/OfflineBanner'
import NewVersionNotice from './components/Layout/NewVersionNotice'
@@ -380,7 +379,6 @@ export default function App() {
useInAppNotificationListener()
useRoadtripPreferencesSync()
useTripAddonsSync()
useEffect(() => {
if (isAuthenticated) {
-10
View File
@@ -1,10 +0,0 @@
import type { TripAddonsResponse, TripAddonUpdateRequest } from '@trek/shared';
import apiClient from './client';
/** The trip addons of one trip, each on or off for it: every member reads them, only the owner switches one. */
export const tripAddonsApi = {
list: (tripId: number): Promise<TripAddonsResponse> => apiClient.get(`/trips/${tripId}/addons`).then((r) => r.data),
/** `enabled: null` drops the trip's own choice, so the instance setting applies again. */
update: (tripId: number, addonId: string, body: TripAddonUpdateRequest): Promise<TripAddonsResponse> =>
apiClient.put(`/trips/${tripId}/addons/${encodeURIComponent(addonId)}`, body).then((r) => r.data),
};
-4
View File
@@ -46,10 +46,6 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
'roadtripVia:changed',
'roadtripTrack:changed',
'roadtripPreferences:changed',
// Per-trip addons: store/tripAddonsStore (watchTripAddons, mounted by App through
// hooks/useTripAddonsSync) puts the trip's list into the store and the device's copy, so the
// tabs and panels a trip switched off disappear for every member at once.
'tripAddons:changed',
// components/Roadtrip/useDayBoundaries reloads the shared boundaries.
'roadtripBoundary:changed',
// In-app notifications: hooks/useInAppNotificationListener, which also keeps
@@ -7,7 +7,6 @@ import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useAddonStore } from '../../store/addonStore';
import { ToastContainer } from '../shared/Toast';
import { mailIngestRepo } from '../../repo/mailIngestRepo';
import AddonManager from './AddonManager';
function buildAddon(overrides = {}) {
@@ -692,40 +691,4 @@ describe('AddonManager', () => {
expect(roadtrip.querySelector('svg.lucide-car-front')).toBeInTheDocument();
expect(tours.querySelector('svg.lucide-puzzle')).not.toBeInTheDocument();
});
it('FE-ADMIN-ADDON-045: live flight status is a row of the trip card, switched there and locked by the environment', async () => {
server.use(addonsRoute([buildAddon({ id: 'packing', name: 'Lists', icon: 'ListChecks', type: 'trip', enabled: true })]));
const onToggle = vi.fn();
const { unmount } = render(<AddonManager flightLive={{ on: false, locked: false, managed: false, onToggle }} />);
const trip = (await screen.findByRole('heading', { name: 'Trip' })).closest('section') as HTMLElement;
await userEvent.click(within(trip).getByRole('button', { name: 'Follow booked flights live' }));
expect(onToggle).toHaveBeenCalledTimes(1);
// The count stays the addons': the flight row is an instance option beside them.
expect(within(trip).getByText('1/1')).toBeInTheDocument();
unmount();
render(<AddonManager flightLive={{ on: true, locked: true, managed: false, onToggle }} />);
expect(await screen.findByRole('button', { name: 'Follow booked flights live' })).toBeDisabled();
});
it('FE-ADMIN-ADDON-046: the booking mail import is a row of the integration card whose setup opens in a dialog', async () => {
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
vi.spyOn(mailIngestRepo, 'adminSettings').mockResolvedValue({ mail_ingest_enabled: 'true' });
vi.spyOn(mailIngestRepo, 'adminStatus').mockRejectedValue(new Error('no status'));
render(<AddonManager mailImport />);
const integration = (await screen.findByRole('heading', { name: 'Integration' })).closest('section') as HTMLElement;
expect(within(integration).getByText('Booking mail import')).toBeInTheDocument();
await userEvent.click(await within(integration).findByRole('button', { name: 'Set up mail import' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('How mail arrives')).toBeInTheDocument();
});
it('FE-ADMIN-ADDON-047: without the mail option the integration card has no mail row and nothing is loaded', async () => {
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
const load = vi.spyOn(mailIngestRepo, 'adminSettings');
render(<AddonManager />);
await screen.findByRole('heading', { name: 'Integration' });
expect(screen.queryByText('Booking mail import')).not.toBeInTheDocument();
expect(load).not.toHaveBeenCalled();
});
});
+8 -47
View File
@@ -1,6 +1,6 @@
import type { ComponentType } from 'react'
import type { ComponentType, ReactNode } from 'react'
import { useTranslation } from '../../i18n'
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar } from 'lucide-react'
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront } from 'lucide-react'
import EmptyState from '../shared/EmptyState'
import DawarichIcon from '../shared/DawarichIcon'
import AirTrailIcon from '../shared/AirTrailIcon'
@@ -12,9 +12,6 @@ import { SettingsCard, SettingsColumns, StatusPill } from '../Settings/settingsK
import { type Addon, type CollabFeatures, COLLAB_SUB_FEATURES, getAddonLabel } from './addons/addonModel'
import { useAddonManager } from './addons/useAddonManager'
import AiAddonTile from './addons/AiAddonTile'
import MailIngestAddonTile from './mailIngest/MailIngestAddonTile'
import PaddleRegionsPanel from './paddle/PaddleRegionsPanel'
import ToggleSwitch from '../Settings/ToggleSwitch'
import { ImmichIcon, SynologyIcon } from './addons/PhotoProviderIcons'
import WandererMark from '../Tours/wanderer/WandererMark'
@@ -68,24 +65,13 @@ const TYPE_META: Record<string, { icon: ComponentType<{ size?: number }>; labelK
integration: { icon: Link2, labelKey: 'admin.addons.type.integration', hintKey: 'admin.addons.integrationHint' },
}
/** The live flight status switch, an instance setting that sits with the trip addons. */
export interface FlightLiveOption {
on: boolean
/** The server environment (FLIGHT_LIVE_ENABLED) holds it; the switch shows the state and says why. */
locked: boolean
managed: boolean
onToggle: () => void
}
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, flightLive, mailImport = false }: {
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, aside }: {
bagTrackingEnabled?: boolean
onToggleBagTracking?: () => void
collabFeatures?: CollabFeatures
onToggleCollabFeature?: (key: string) => void
/** Live flight status, a row of the trip card: it follows the trips' booked flights. */
flightLive?: FlightLiveOption
/** Booking mail import, a row of the integration card with its setup dialog; off on a managed install. */
mailImport?: boolean
/** Cards that set up what the integrations reach (flight status, booking mails), under them in the right column. */
aside?: ReactNode
}) {
const { t } = useTranslation()
const {
@@ -195,8 +181,6 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
onToggle={() => void toggle()}
/>
)),
// The paddle water data the tour planner reads, set up in a dialog of its own.
<PaddleRegionsPanel key="paddle-regions" />,
]
}
return null
@@ -218,9 +202,6 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
)
}
/** Whether a card holds rows beside its own addons: the AI tile, an instance option. */
const extraRows = (key: string) =>
(key === 'trip' && !!flightLive) || (key === 'integration' && (aiAddons.length > 0 || mailImport))
/* A card per type, the way every other admin tab sets its cards: Trip in the
left column, Global and Integration in the right one, each card with the
dialogs' head band carrying the type, its count and what it means. */
@@ -228,14 +209,14 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
{ key: 'trip', addons: tripAddons },
{ key: 'global', addons: globalAddons },
{ key: 'integration', addons: integrationAddons },
].filter(g => g.addons.length > 0 || extraRows(g.key))
].filter(g => g.addons.length > 0 || (g.key === 'integration' && aiAddons.length > 0))
const card = (g: (typeof groups)[number]) => {
const meta = TYPE_META[g.key]
const all = g.key === 'integration' ? [...aiAddons, ...g.addons] : g.addons
const visible = g.addons
const ai = g.key === 'integration' && aiAddons.length > 0
if (!visible.length && !ai && !extraRows(g.key)) return null
if (!visible.length && !ai) return null
const on = all.filter(a => a.enabled).length
return (
<SettingsCard
@@ -254,10 +235,6 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
{/* The AI addons share a connection and a settings dialog, so they head the card as one tile. */}
{ai && <AiAddonTile addons={aiAddons} onToggle={handleToggle} />}
{visible.map(tile)}
{/* Not addons but instance options of the same kind, as rows of the same card;
the count above stays the addons'. */}
{g.key === 'trip' && flightLive && <FlightLiveTile option={flightLive} />}
{g.key === 'integration' && mailImport && <MailIngestAddonTile />}
</div>
</SettingsCard>
)
@@ -274,21 +251,5 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
)
}
return <SettingsColumns start={cards.start} end={cards.end} />
}
/** Live flight status as a trip row: on, it follows every booked flight on its day. */
function FlightLiveTile({ option }: { option: FlightLiveOption }) {
const { t } = useTranslation()
const name = t('flightLive.adminTitle')
const hint = option.managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')
return (
<AddonTile
icon={<Radar size={18} />}
name={name}
description={option.locked ? `${hint} ${t('flightLive.envLocked')}` : hint}
enabled={option.on}
trailing={<ToggleSwitch on={option.on} label={t('flightLive.adminToggle')} disabled={option.locked} onToggle={option.onToggle} />}
/>
)
return <SettingsColumns start={cards.start} end={<>{cards.end}{aside}</>} />
}
@@ -1,68 +0,0 @@
import React, { useId, type ReactNode } from 'react';
import { useTranslation } from '../../i18n';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
} from '../shared/DialogShell';
/**
* The dialog an addon's setup row opens: the icon tile, the addon it belongs
* to above the title, what it sets up below, and one Close, since everything
* inside saves on its own (booking mails, paddle water data).
*/
export default function AddonSetupDialog({
icon,
eyebrow,
title,
sub,
onClose,
blocked = false,
children,
}: {
icon: ReactNode;
eyebrow: string;
title: string;
sub: string;
onClose: () => void;
/** A confirmation stacked on top holds the dialog while it is open. */
blocked?: boolean;
children: ReactNode;
}): React.ReactElement {
const { t } = useTranslation();
const labelId = useId();
return (
<DialogShell
onClose={onClose}
labelledBy={labelId}
width="detail"
blocked={blocked}
header={
<DialogHeader
tile={<DialogTile>{icon}</DialogTile>}
tint={NEUTRAL_TINT}
labelId={labelId}
eyebrow={eyebrow}
title={title}
sub={sub}
subWraps
onClose={onClose}
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton variant="primary" onClick={onClose}>
{t('common.close')}
</DialogButton>
</DialogFooter>
}
>
{children}
</DialogShell>
);
}
@@ -1,38 +0,0 @@
import { ChevronRight, Settings2 } from 'lucide-react';
import React, { type ReactNode } from 'react';
import { fs } from '../shared/DialogShell';
/**
* The last row of an addon's shelf that opens its settings dialog: a gear, what
* the dialog sets up, and a chevron. It keeps a card of addons as short as its
* switches and puts the long forms behind one tap (AI, booking mails, paddle
* water data). A badge says what waits inside, such as requests to look at.
*/
export default function AddonSetupRow({
label,
onOpen,
badge,
}: {
label: string;
onOpen: () => void;
badge?: ReactNode;
}): React.ReactElement {
return (
<li>
<button
type="button"
onClick={onOpen}
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
>
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
<Settings2 size={14} />
</span>
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
{label}
</span>
{badge}
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
</button>
</li>
);
}
@@ -1,9 +1,8 @@
import { Sparkles } from 'lucide-react';
import { ChevronRight, Settings2, Sparkles } from 'lucide-react';
import React from 'react';
import { useTranslation } from '../../../i18n';
import { StatusPill } from '../../Settings/settingsKit';
import { fs } from '../../shared/DialogShell';
import AddonSetupRow from '../AddonSetupRow';
import AddonSubRow from '../AddonSubRow';
import AddonTile from '../AddonTile';
import { type Addon, getAddonLabel } from './addonModel';
@@ -55,7 +54,23 @@ export default function AiAddonTile({
/>
);
})}
{tile.canSetUp && <AddonSetupRow label={t('admin.addons.ai.setup')} onOpen={tile.openDialog} />}
{tile.canSetUp && (
<li>
<button
type="button"
onClick={tile.openDialog}
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
>
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
<Settings2 size={14} />
</span>
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
{t('admin.addons.ai.setup')}
</span>
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
</button>
</li>
)}
</AddonTile>
{tile.dialogOpen && <AiSettingsDialog addons={addons} onClose={tile.closeDialog} />}
</>
@@ -1,17 +1,22 @@
import { AlertTriangle, CheckCircle, Copy, Loader2, Mail, PlugZap, Save, XCircle } from 'lucide-react';
import { useState, type ReactNode } from 'react';
import type { ReactNode } from 'react';
import { useTranslation } from '../../../i18n';
import type { TranslationFn } from '../../../types';
import { copyText } from '../../../utils/clipboard';
import { relativeTime } from '../../../utils/relativeTime';
import { HintMark, SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, StatusPill } from '../../Settings/settingsKit';
import {
HintMark,
SETTINGS_BUTTON,
SETTINGS_BUTTON_PRIMARY,
SettingRow,
SettingRows,
SettingsCard,
StatusPill,
} from '../../Settings/settingsKit';
import ToggleSwitch from '../../Settings/ToggleSwitch';
import CustomSelect from '../../shared/CustomSelect';
import { EditorField, GRID_2, INPUT, READONLY_BOX } from '../../shared/dialogParts';
import { useToast } from '../../shared/Toast';
import AddonSetupDialog from '../AddonSetupDialog';
import AddonSetupRow from '../AddonSetupRow';
import AddonTile from '../AddonTile';
import {
TRANSPORTS,
problemText,
@@ -301,46 +306,32 @@ function Setup({ admin, form, t, locale }: { admin: MailIngestAdmin; form: MailA
}
/**
* The booking mail import as a row of the integration card: its switch, and
* while it is on one row to the dialog that sets it up (how mail arrives, the
* forwarding address template, the AI allowance per person and day, a
* connection test and the status in counts). Not shown on a managed install,
* where the operator runs the TREK Cloud relay.
* The booking mail import in the admin settings of a self-hosted install: the
* instance switch, how mail arrives (IMAP or a signed webhook), the forwarding
* address template, the AI allowance per person and day, a connection test and
* the status in counts. Not shown on a managed install, where the operator
* runs the TREK Cloud relay.
*/
export default function MailIngestAddonTile() {
export default function MailIngestAdminCard() {
const { t, locale } = useTranslation();
const admin = useMailIngestAdmin(true);
const [open, setOpen] = useState(false);
const name = t('mailAdmin.title');
return (
<>
<AddonTile
icon={<Mail size={15} />}
name={name}
description={`${t('mailAdmin.hint')} ${t('mailAdmin.enabledHint')}`}
enabled={admin.enabled}
trailing={
<ToggleSwitch
on={admin.enabled}
label={t('mailAdmin.enabled')}
disabled={!admin.loaded}
onToggle={() => admin.toggle(!admin.enabled)}
/>
}
>
{admin.enabled && admin.form && <AddonSetupRow label={t('mailAdmin.setup')} onOpen={() => setOpen(true)} />}
</AddonTile>
{open && admin.enabled && admin.form && (
<AddonSetupDialog
icon={<Mail size={20} strokeWidth={2} />}
eyebrow={name}
title={t('mailAdmin.setup')}
sub={t('mailAdmin.hint')}
onClose={() => setOpen(false)}
>
<Setup admin={admin} form={admin.form} t={t} locale={locale} />
</AddonSetupDialog>
)}
</>
<SettingsCard icon={Mail} title={t('mailAdmin.title')} hint={t('mailAdmin.hint')}>
<SettingRows>
<SettingRow
label={t('mailAdmin.enabled')}
hint={t('mailAdmin.enabledHint')}
control={
<ToggleSwitch
on={admin.enabled}
label={t('mailAdmin.enabled')}
disabled={!admin.loaded}
onToggle={() => admin.toggle(!admin.enabled)}
/>
}
/>
</SettingRows>
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
</SettingsCard>
);
}
@@ -78,22 +78,17 @@ function adminState(overrides: Partial<Admin> = {}, search: Partial<Admin['searc
};
}
/** The panel as the Tours shelf shows it: a setup row, opened into its dialog unless asked not to. */
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}, { open = true } = {}) {
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}) {
const state = adminState(overrides, search);
hook.usePaddleRegionsAdmin.mockReturnValue(state);
const view = render(
<ul>
<PaddleRegionsPanel />
</ul>
);
if (open && state.toursOn) fireEvent.click(setupRow());
return { state, ...view };
return { state, ...render(<PaddleRegionsPanel />) };
}
/** The shelf row that opens the dialog, where the count of requests or regions sits beside the title. */
function setupRow(): HTMLElement {
return screen.getAllByRole('button', { name: /^Paddle water data/ })[0];
/** The card's title row, where the number of regions sits beside the title. */
function titleRow(): HTMLElement {
const row = screen.getByRole('heading', { name: 'Paddle water data' }).parentElement;
if (!row) throw new Error('no title row');
return row;
}
function rowOf(name: string): HTMLElement {
@@ -105,7 +100,7 @@ function rowOf(name: string): HTMLElement {
describe('PaddleRegionsPanel', () => {
it('FE-ADMIN-PADDLEREG-001: renders nothing while the Tours addon is off', () => {
const { container } = show({ toursOn: false, regions: [READY] });
expect(container.querySelector('ul')).toBeEmptyDOMElement();
expect(container).toBeEmptyDOMElement();
});
it('FE-ADMIN-PADDLEREG-002: shows the card with its hint, the attribution and the empty state', () => {
@@ -115,7 +110,7 @@ describe('PaddleRegionsPanel', () => {
expect(screen.getByText(EMPTY)).toBeInTheDocument();
expect(screen.getByText(ATTRIBUTION)).toBeInTheDocument();
// No count beside the title while there is no region.
expect(setupRow()).toHaveTextContent(/^Paddle water data$/);
expect(titleRow()).toHaveTextContent(/^Paddle water data$/);
const search = screen.getByRole('searchbox', { name: 'Add a region' });
expect(search).toBeEnabled();
expect(search).toHaveAttribute('placeholder', 'Search Geofabrik, for example Oberpfalz');
@@ -282,31 +277,12 @@ describe('PaddleRegionsPanel', () => {
}
});
it('FE-ADMIN-PADDLEREG-019: the setup row carries the open requests, else the number of regions', () => {
it('FE-ADMIN-PADDLEREG-019: the title carries the number of regions', () => {
show({ regions: [READY, WAITING, FAILED_FIRST] });
expect(within(setupRow()).getByText('3')).toBeInTheDocument();
expect(within(titleRow()).getByText('3')).toBeInTheDocument();
expect(screen.getAllByTestId('paddle-region-row')).toHaveLength(3);
});
it('FE-ADMIN-PADDLEREG-019b: an open request outranks the region count, a declined one does not count', () => {
const base = { bytes: 1, requested_by: 'elmo', requested_at: '2026-10-18T09:00:00Z' };
show(
{
regions: [READY, WAITING],
requests: [
{ ...base, id: 'norway', name: 'Norway', reason: 'too_large', declined: true },
{ ...base, id: 'saale', name: 'Saale', reason: 'limit', declined: false },
],
},
{},
{ open: false }
);
expect(within(setupRow()).getByText('1')).toBeInTheDocument();
expect(within(setupRow()).queryByText('2')).toBeNull();
// Closed until the row is opened.
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ADMIN-PADDLEREG-020: removing asks first, naming the region, and confirming hands it to the hook', () => {
const { state } = show({ regions: [READY], removing: READY });
const message = 'Oberpfalz and its obstacle data are removed. Paddle tours there then show no data.';
@@ -1,6 +1,6 @@
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
import { Check, ChevronRight, Loader2, Plus, RefreshCw, Search, Trash2, Waves, WifiOff } from 'lucide-react';
import { useId, useState } from 'react';
import { useId } from 'react';
import { useDateFormat } from '../../../hooks/useDateFormat';
import { useTranslation } from '../../../i18n';
import { formatDisplayDate } from '../../../utils/dateFormat';
@@ -8,6 +8,7 @@ import {
SettingRows,
SETTINGS_BUTTON,
SETTINGS_ICON_BUTTON,
SettingsCard,
SettingsHint,
StatusPill,
} from '../../Settings/settingsKit';
@@ -16,8 +17,6 @@ import { EditorField, INPUT } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell';
import ErrorBoundary from '../../shared/ErrorBoundary';
import { Tooltip } from '../../shared/Tooltip';
import AddonSetupDialog from '../AddonSetupDialog';
import AddonSetupRow from '../AddonSetupRow';
import { AutoLoadSettings, AutoOriginPill, RequestList } from './PaddleAutoLoadParts';
import { progressPercent, regionStatusTone } from './paddleRegionsModel';
import { usePaddleRegionsAdmin } from './usePaddleRegionsAdmin';
@@ -28,10 +27,8 @@ type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
* PAD-05A in the admin area: the regions TREK reads paddle obstacles for,
* picked from Geofabrik's list, and (PAD-11C) how TREK loads the region of a
* place a paddler plans in by itself, with the regions that wait for an admin.
* The desktop admin shows it as a row of the Tours addon that opens it as a
* dialog while the addon is on; the row counts what waits for the admin (the
* requests) or else the regions. The phone has MAdminPaddleRegionsPanel on
* the same hook.
* The desktop admin shows this card under the addons while the Tours addon
* is on; the phone has MAdminPaddleRegionsPanel on the same hook.
*/
export default function PaddleRegionsPanel() {
return (
@@ -44,42 +41,14 @@ export default function PaddleRegionsPanel() {
function Panel() {
const { t } = useTranslation();
const admin = usePaddleRegionsAdmin();
const [open, setOpen] = useState(false);
if (!admin.toursOn) return null;
const title = t('admin.paddleRegions.title');
// A declined request no longer waits for anyone; only the open ones ask for a look.
const waiting = admin.requests.filter((r) => !r.declined).length;
const badge =
waiting > 0 ? (
<StatusPill tone="warning">{waiting}</StatusPill>
) : admin.regions.length > 0 ? (
<StatusPill>{admin.regions.length}</StatusPill>
) : undefined;
const close = () => setOpen(false);
return (
<>
<AddonSetupRow label={title} onOpen={() => setOpen(true)} badge={badge} />
{open && (
<AddonSetupDialog
icon={<Waves size={20} strokeWidth={2} />}
eyebrow={t('admin.addons.catalog.tours.name')}
title={title}
sub={t('admin.paddleRegions.hint')}
onClose={close}
blocked={admin.removing !== null}
>
<PanelBody admin={admin} />
</AddonSetupDialog>
)}
</>
);
}
/** What the dialog holds: the state of the list, the settings, the requests, the search and the regions. */
function PanelBody({ admin }: { admin: Admin }) {
const { t } = useTranslation();
return (
<div className="flex flex-col gap-4">
<SettingsCard
icon={Waves}
title={t('admin.paddleRegions.title')}
hint={t('admin.paddleRegions.hint')}
badge={admin.regions.length > 0 ? <StatusPill>{admin.regions.length}</StatusPill> : undefined}
>
{admin.offline && (
<p
role="status"
@@ -117,7 +86,7 @@ function PanelBody({ admin }: { admin: Admin }) {
message={t('admin.paddleRegions.removeMessage', { name: admin.removing?.name ?? '' })}
confirmLabel={t('common.remove')}
/>
</div>
</SettingsCard>
);
}
@@ -47,6 +47,7 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
photoId: 7,
video: false,
photoCount: 1,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: 0,
@@ -85,15 +86,13 @@ afterEach(() => {
describe('the journal entries card', () => {
it('FE-AI-JOURNEY-001: one entry reads as a row with its photo, facts, marks and text under the journal', () => {
// A card stored while entries carried a visibility: it reads, and says nothing of it.
const stored = { ...look({ draft: true, photoCount: 4, video: true }), visibility: 'public' };
const { container } = block([card([stored])]);
const { container } = block([card([look({ visibility: 'public', draft: true, photoCount: 4, video: true })])]);
expect(screen.getByRole('region', { name: 'Journal entries' })).toBeInTheDocument();
expect(screen.getByText('Sunset at the Spree')).toBeInTheDocument();
expect(screen.getByText('14:30')).toBeInTheDocument();
expect(screen.getByText('Berlin')).toBeInTheDocument();
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
expect(screen.queryByText('Public')).toBeNull();
expect(screen.getByText('Public')).toBeInTheDocument();
expect(screen.getByText('Draft')).toBeInTheDocument();
expect(screen.getByText('4 photos')).toBeInTheDocument();
expect(screen.getByText('Opens with a video')).toBeInTheDocument();
@@ -226,12 +225,13 @@ describe('a change row of a journal entry', () => {
}
it('FE-AI-JOURNEY-008: a waiting delete shows the photo, the text and that it goes back to a suggestion; a receipt opens it', () => {
const entry = look({ fromTripPlace: true });
const entry = look({ fromTripPlace: true, visibility: 'shared' });
const held = card([entry], { change: 'willDelete', tripJournal: true });
const onOpen = vi.fn();
const first = inView(<AssistantChangeCard items={[item('pending', held)]} />, { onOpen });
expect(screen.getByText('Delete the journal entry')).toBeInTheDocument();
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
expect(screen.getByText('Shared')).toBeInTheDocument();
expect(screen.getByText('Goes back to a suggestion')).toBeInTheDocument();
expect(screen.getByText('Tue, Oct 21')).toBeInTheDocument();
expect(screen.getByText('Museum Island')).toBeInTheDocument();
@@ -255,6 +255,7 @@ describe('a change row of a journal entry', () => {
{ op: 'change', labelKey: 'name', before: 'Sunset', after: 'Sunset at the Spree' },
{ op: 'change', labelKey: 'time', before: '14:30', after: '' },
{ op: 'change', labelKey: 'text', before: 'Old story', after: 'New story' },
{ op: 'change', labelKey: 'field', field: 'visibility', before: 'private', after: 'public' },
{ op: 'change', labelKey: 'field', field: 'mood', before: 'good', after: '' },
{ op: 'change', labelKey: 'field', field: 'weather', before: 'sunny', after: 'Drizzle' },
{ op: 'change', labelKey: 'field', field: 'is_draft', before: '✓', after: '✗' },
@@ -266,6 +267,8 @@ describe('a change row of a journal entry', () => {
expect(screen.getByText('14:30')).toHaveClass('line-through');
expect(screen.getByText('Old story')).toHaveClass('line-through');
expect(screen.getByText('New story')).toBeInTheDocument();
expect(screen.getByText('Private')).toHaveClass('line-through');
expect(screen.getByText('Public')).toBeInTheDocument();
expect(screen.getByText('Good')).toHaveClass('line-through');
expect(screen.getByText('Sunny')).toHaveClass('line-through');
expect(screen.getByText('Drizzle')).toBeInTheDocument();
@@ -28,6 +28,7 @@ const ENTRY: JourneyEntryLook = {
photoId: null,
video: false,
photoCount: 0,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: null,
@@ -1,5 +1,5 @@
import type { JourneyEntryLook } from '@trek/shared';
import { CalendarDays, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp } from 'lucide-react';
import { CalendarDays, Globe, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp, Users } from 'lucide-react';
import { useTranslation } from '../../../../i18n';
import { cardDateLabel, cardPlace } from '../../../Journey/journeyCard';
@@ -12,8 +12,8 @@ import { moodOf, weatherOf } from './journeyTones';
/**
* The pieces a journal entry is drawn from in the chat, the same in an
* answer, a change row and a receipt: its photo, the facts of when and where
* as the planner's badges, the marks of how it reads (draft, mood, weather,
* more photos) and the start of its text. Every fact wraps, none is
* as the planner's badges, the marks of how it reads (shared, draft, mood,
* weather, more photos) and the start of its text. Every fact wraps, none is
* cut.
*/
@@ -63,6 +63,19 @@ export function EntryWhen({ look }: { look: JourneyEntryLook }) {
);
}
/** Shared or public; nothing for a private entry. */
function VisibilityMark({ visibility }: { visibility: JourneyEntryLook['visibility'] }) {
const { t } = useTranslation();
if (visibility === 'private') return null;
const shared = visibility === 'shared';
const Icon = shared ? Users : Globe;
return (
<SoftPill tone="info" icon={<Icon size={10} strokeWidth={2.2} aria-hidden="true" />}>
{shared ? t('journey.visibility.shared') : t('journey.visibility.public')}
</SoftPill>
);
}
/** A mood the journal knows, in its own colour; nothing for any other. */
function MoodMark({ id }: { id: string | null }) {
const { t } = useTranslation();
@@ -116,16 +129,17 @@ function ListMarks({ look }: { look: JourneyEntryLook }) {
);
}
/** How the entry reads: a draft, its mood and weather, its photos past the first, its tags and verdict. */
/** How the entry reads: shared or public, a draft, its mood and weather, its photos past the first, its tags and verdict. */
export function EntryMarks({ look }: { look: JourneyEntryLook }) {
const { t } = useTranslation();
const mood = moodOf(look.mood) !== null;
const lists = (look.tags?.length ?? 0) > 0 || !!look.verdict;
if (!look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
if (look.visibility === 'private' && !look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
return null;
}
return (
<CardFacts>
<VisibilityMark visibility={look.visibility} />
{look.draft && <SoftPill tone="warning">{t('journey.entry.draft')}</SoftPill>}
<MoodMark id={look.mood} />
<WeatherMark weather={look.weather} />
@@ -31,6 +31,7 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
photoId: null,
video: false,
photoCount: 0,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: null,
@@ -96,13 +97,12 @@ describe('journeyCardModel', () => {
});
it('FE-AI-JOURNEY-MODEL-009: the states an update sets are named by field, flags by on and off', () => {
// The stored visibility keeps nothing off the share link, so it has no name to show.
expect(stateOf('visibility', 'private')).toBeNull();
expect(stateOf('visibility', 'public')?.labelKey).toBe('journey.visibility.public');
expect(stateOf('type', 'skeleton')?.labelKey).toBe('journey.entry.suggestion');
expect(stateOf('mood', 'good')?.labelKey).toBe('journey.mood.good');
expect(stateOf('weather', 'cold')?.labelKey).toBe('journey.weather.cold');
expect(stateOf('weather', 'Drizzle')).toBeNull();
expect(stateOf('type', 'toString')).toBeNull();
expect(stateOf('visibility', 'toString')).toBeNull();
expect(stateOf(undefined, 'public')).toBeNull();
expect(flagOf('is_draft', '✓')?.labelKey).toBe('journey.entry.draft');
expect(flagOf('is_draft', '✗')?.labelKey).toBe('assistant.card.journey.notDraft');
@@ -7,6 +7,8 @@ import {
Eye,
EyeOff,
Frown,
Globe,
Lock,
type LucideIcon,
MapPinCheck,
Meh,
@@ -17,13 +19,14 @@ import {
Snowflake,
Sparkles,
Sun,
Users,
} from 'lucide-react';
/**
* How the states of a journal entry read in the chat, the way the journal
* draws them: its moods with the glyphs of its tiles, its weathers, and the
* words for what an update sets beyond the text (its kind, a draft, the
* route, a waved-away suggestion).
* words for what an update sets beyond the text (who sees the entry, its
* kind, a draft, the route, a waved-away suggestion).
*/
/** How a state is drawn: its glyph and the key of its name. */
@@ -54,6 +57,12 @@ const WEATHERS: Readonly<Record<string, EntryTone>> = {
cold: { Icon: Snowflake, labelKey: 'journey.weather.cold' },
};
const VISIBILITIES: Readonly<Record<string, EntryTone>> = {
private: { Icon: Lock, labelKey: 'journey.visibility.private' },
shared: { Icon: Users, labelKey: 'journey.visibility.shared' },
public: { Icon: Globe, labelKey: 'journey.visibility.public' },
};
const TYPES: Readonly<Record<string, EntryTone>> = {
entry: { Icon: BookOpenText, labelKey: 'assistant.card.journey.typeEntry' },
checkin: { Icon: MapPinCheck, labelKey: 'assistant.card.journey.typeCheckin' },
@@ -110,6 +119,7 @@ export function flagOf(field: string | undefined, value: string): EntryTone | nu
export function stateOf(field: string | undefined, value: string | null): EntryTone | null {
if (field === 'mood') return moodOf(value);
if (field === 'weather') return weatherOf(value);
if (field === 'visibility') return own(VISIBILITIES, value);
if (field === 'type') return own(TYPES, value);
return null;
}
@@ -8,7 +8,6 @@ import { OnlineOnlyError } from '../../repo/onlineOnly';
import { useAddonStore } from '../../store/addonStore';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useCanDo } from '../../store/permissionsStore';
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
import { useTripStore } from '../../store/tripStore';
import { useToast } from '../shared/Toast';
import { chatTextOf } from './assistantShare';
@@ -36,10 +35,7 @@ export function useAssistantShare(tripId: number, message: AssistantMessage, wri
const { offline } = useNetworkMode();
const can = useCanDo();
const trip = useTripStore((s) => (s.trip?.id === tripId ? s.trip : null));
// The chat is an instance-wide part of Collab, which this trip may have on or off.
const chatFeatureOn = useAddonStore((s) => s.collabChat);
const collabOn = useTripAddonEnabled(tripId, 'collab');
const chatOn = chatFeatureOn && collabOn;
const chatOn = useAddonStore((s) => s.collabChat && s.addons.some((a) => a.id === 'collab' && a.enabled));
const threadId = useAssistantStore((s) => chatOf(s, tripId).threadId);
const [previewing, setPreviewing] = useState(false);
const [includeChanges, setIncludeChanges] = useState(true);
@@ -1,115 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render, waitFor } from '../../../tests/helpers/render';
import { offlineDb } from '../../db/offlineDb';
import type { Day, Trip } from '../../types';
const published = vi.hoisted(() => ({ calls: [] as unknown[][] }));
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(async () => ({ remove: vi.fn() })) } }));
vi.mock('../../native/capabilities', () => ({ useNativeCapabilities: () => ({ caps: {} }) }));
vi.mock('../../native/watch', () => ({
applyWatchActions: vi.fn(async () => []),
buildWatchSnapshot: vi.fn(),
publishWatch: vi.fn(async () => {}),
takeWatchActions: vi.fn(async () => []),
watchActive: () => false,
}));
vi.mock('../../native/widgetMedia', () => ({
widgetCover: vi.fn(async () => null),
widgetWeather: vi.fn(async () => null),
}));
vi.mock('../../native/widgetOnline', () => ({
atlasSummary: vi.fn(async () => null),
collabSummary: vi.fn(async () => null),
packingDetail: vi.fn(async () => null),
}));
vi.mock('../../native/widgets', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../native/widgets')>();
return {
...actual,
widgetsActive: () => true,
publishWidgets: vi.fn(async (...args: unknown[]) => {
published.calls.push(args);
}),
};
});
import { collabSummary, packingDetail } from '../../native/widgetOnline';
import NativeWidgetsSync from './NativeWidgetsSync';
const trip = {
id: 7,
title: 'Lisbon',
start_date: '2026-11-06',
end_date: '2026-11-08',
is_archived: 0,
} as unknown as Trip;
const day = (id: number, n: number, date: string, name: string) =>
({
id,
trip_id: 7,
day_number: n,
date,
assignments: [{ id: id * 10, order_index: 0, place: { name, place_time: '10:00' } }],
}) as unknown as Day;
describe('NativeWidgetsSync', () => {
beforeEach(async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 10, 7, 9, 0));
published.calls = [];
await offlineDb.trips.put(trip as never);
await offlineDb.days.bulkPut([
day(1, 1, '2026-11-06', 'Castle'),
day(2, 2, '2026-11-07', 'Harbour'),
day(3, 3, '2026-11-08', 'Market'),
] as never);
});
afterEach(async () => {
vi.useRealTimers();
await offlineDb.trips.clear();
await offlineDb.days.clear();
await offlineDb.todoItems.clear();
await offlineDb.tripAddons.clear();
});
it('FE-NATIVE-WSYNC-001: writes today and every day ahead, so the widgets turn the day without the app', async () => {
render(<NativeWidgetsSync />);
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
const snapshot = published.calls[0][0] as {
today: { date: string; stops: { name: string }[] } | null;
days: { date: string; stops: { name: string }[] }[];
};
expect(snapshot.today).toMatchObject({ date: '2026-11-07', stops: [{ name: 'Harbour' }] });
expect(snapshot.days.map((d) => [d.date, d.stops[0]?.name])).toEqual([
['2026-11-07', 'Harbour'],
['2026-11-08', 'Market'],
]);
});
it('FE-NATIVE-WSYNC-002: a trip with Lists and Collab switched off shows neither its todos nor its chat', async () => {
await offlineDb.todoItems.put({ id: 70, trip_id: 7, name: 'Book ferry', checked: 0 } as never);
const off = (id: string) => ({ id, name: id, icon: null, enabled: false, instanceEnabled: true, overridden: true });
await offlineDb.tripAddons.put({ tripId: 7, addons: [off('packing'), off('collab')] });
vi.mocked(packingDetail).mockClear();
vi.mocked(collabSummary).mockClear();
render(<NativeWidgetsSync />);
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
const snapshot = published.calls[0][0] as { todos?: unknown; collab?: unknown };
expect(snapshot.todos).toBeUndefined();
expect(snapshot.collab).toBeUndefined();
expect(vi.mocked(packingDetail)).not.toHaveBeenCalled();
expect(vi.mocked(collabSummary)).not.toHaveBeenCalled();
});
it('FE-NATIVE-WSYNC-003: a trip the device never read the addons of shows its todos, as before', async () => {
await offlineDb.todoItems.put({ id: 71, trip_id: 7, name: 'Book ferry', checked: 0 } as never);
render(<NativeWidgetsSync />);
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
const snapshot = published.calls[0][0] as { todos?: { items?: unknown[] } };
expect(snapshot.todos).toBeDefined();
});
});
@@ -25,22 +25,20 @@ import {
liveFlightOf,
pickTrip,
publishWidgets,
snapshotDays,
todayOf,
tripDayState,
widgetTripChoices,
widgetsActive,
withBookings,
type TripWidgetSnapshot,
type WidgetLabels,
} from '../../native/widgets';
import { cachedTripAddons } from '../../repo/tripAddonsRepo';
import { instanceAddonOn, useAddonStore } from '../../store/addonStore';
import { useAuthStore } from '../../store/authStore';
import { useFlightLiveStore } from '../../store/flightLiveStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore';
import type { Day, Place, Reservation, TranslationFn, Trip } from '../../types';
import { formatTime } from '../../utils/formatters';
import { tripAddonEnabled } from '../../utils/tripAddons';
import { localDateStr } from '../../vacay/monthGrid';
const REFRESH_MS = 15 * 60 * 1000;
@@ -123,31 +121,15 @@ async function flightOf(trip: Trip, reservations: Reservation[], path: string, c
return widgetFlight(legs, Date.now(), path, { locale: context.language, timeFormat: context.timeFormat });
}
/**
* Whether the trip has Lists and Collab on, from the list the device kept for it
* (the sync reads it with the trip). A trip it never read follows the instance,
* and while that is not known either the widgets show both, as they always did.
*/
async function tripSections(tripId: number): Promise<{ lists: boolean; collab: boolean }> {
const own = await cachedTripAddons(tripId);
const instance = useAddonStore.getState();
const on = (id: string) => tripAddonEnabled(own, id, instanceAddonOn(instance, id, true));
return { lists: on('packing'), collab: on('collab') };
}
async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
const { today, language, unit, time } = context;
const [places, reservations, todoRows, packingRows, memberRows, sections] = await Promise.all([
const [places, reservations, todos, packing, memberRows] = await Promise.all([
offlineDb.places.where('trip_id').equals(trip.id).toArray(),
offlineDb.reservations.where('trip_id').equals(trip.id).toArray(),
offlineDb.todoItems.where('trip_id').equals(trip.id).toArray(),
offlineDb.packingItems.where('trip_id').equals(trip.id).toArray(),
offlineDb.tripMembers.where('tripId').equals(trip.id).toArray(),
tripSections(trip.id),
]);
// A trip with Lists off shows no todos or packing, on the widgets and the watch alike.
const todos = sections.lists ? todoRows : [];
const packing = sections.lists ? packingRows : [];
const members = memberRows.length;
const names = [trip.owner_username, ...memberRows.map((m) => m.username)].filter((n): n is string => !!n);
const path = `/trips/${trip.id}`;
@@ -163,15 +145,13 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
const [weather, cover, bags, collab, flight] = await Promise.all([
spot && inRange ? widgetWeather(spot, { date: weatherDate, lang: language, unit, place }) : Promise.resolve(null),
widgetCover(trip.cover_image),
sections.lists ? packingDetail(trip.id, packing) : Promise.resolve(null),
sections.collab
? collabSummary(
trip.id,
`/trips/${trip.id}?tab=collab`,
[...new Set(names)],
useAuthStore.getState().user?.id ?? null
)
: Promise.resolve(null),
packingDetail(trip.id, packing),
collabSummary(
trip.id,
`/trips/${trip.id}?tab=collab`,
[...new Set(names)],
useAuthStore.getState().user?.id ?? null
),
flightOf(trip, reservations, path, context),
]);
const packed = packingSummary(packing, `/trips/${trip.id}?tab=listen`);
@@ -187,7 +167,7 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
memberCount: members > 0 ? members + 1 : 0,
weather,
bookings: bookingsAhead(reservations, { dayDates, today, tripPath: path, formatTime: time }),
todos: sections.lists ? todosSummary(todos, `${path}?tab=listen`) : undefined,
todos: todosSummary(todos, `${path}?tab=listen`),
packing: packed && bags ? { ...packed, ...bags } : packed,
collab,
flight,
@@ -211,15 +191,11 @@ export default function NativeWidgetsSync(): null {
const tripSnapshot = async (trip: Trip | null, context: SyncContext, atlas: WidgetAtlas | null) => {
const days = trip ? await offlineDb.days.where('trip_id').equals(trip.id).toArray() : [];
const extra = trip ? await tripExtras(trip, days, context) : null;
// Today and the days after it: the widgets turn to the next day at midnight by themselves.
const { today: day, ahead } = snapshotDays(trip, days, {
reservations: extra?.reservations ?? [],
from: context.today,
dayLabel: (n, m) => t('native.widget.dayOf', { n, m }),
formatTime: context.time,
});
const snapshot = buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas, days: ahead });
return { day, days, extra, snapshot };
const plain = trip
? todayOf(trip, days, context.today, (n, m) => t('native.widget.dayOf', { n, m }), context.time)
: null;
const day = plain ? withBookings(plain, extra?.reservations ?? [], context.today, context.time) : null;
return { day, days, extra, snapshot: buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas }) };
};
/** The hero trip in full for the watch, with the ticks from it applied so far. */
@@ -5,7 +5,7 @@ import {
type TripRouteAnswers, type TripRouteSummary,
} from './tripRouteGeometry'
import { useSettingsStore } from '../../store/settingsStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import { useAddonStore } from '../../store/addonStore'
import type { RoadtripVia } from '@trek/shared'
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
import type { TourStageStops } from './dayTourProjection'
@@ -51,7 +51,7 @@ export function useTripRouteOverview(
tourStageStops?: TourStageStops,
): TripRouteOverview {
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
// Leg text is formatted at compute time, so a km↔mi switch has to re-run (#1300).
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
const [result, setResult] = useState<TripRouteOverview>(EMPTY)
@@ -245,7 +245,7 @@ describe('trip route map in the PDF', () => {
expect(html).toContain('<svg class="trip-map-svg"')
// Between the cover and the days, which is where it is meant to read.
expect(html.indexOf('class="trip-map"')).toBeGreaterThan(html.indexOf('class="cover"'))
expect(html.indexOf('class="trip-map"')).toBeLessThan(html.indexOf('class="day-section'))
expect(html.indexOf('class="trip-map"')).toBeLessThan(html.indexOf('class="day-section"'))
})
it('FE-COMP-TRIPPDF-MAP-011: prefers the real basemap when it renders', async () => {
+57 -118
View File
@@ -37,41 +37,6 @@ function plannedStat(html: string): number | null {
return match ? Number(match[1]) : null
}
/** The days of the document, without the cover and the overview's booking list before them. */
function daysOf(html: string): string {
return html.slice(html.indexOf('<table class="day-section'))
}
const textOf = (el: Element | null | undefined) => el?.textContent?.trim() ?? ''
/**
* Each booking on the days' timelines, read the way it prints: the span label over the
* title, the start and end in the time column, one line per leg (its route, then its
* facts, then its own code, as one string) and the codes of the whole booking.
*/
function bookingsOf(html: string) {
const doc = new DOMParser().parseFromString(html, 'text/html')
return [...doc.querySelectorAll('.timeline .tl-booking')].map(item => ({
kicker: textOf(item.querySelector('.note-kicker')),
title: textOf(item.querySelector('.note-text')),
start: textOf(item.querySelector('.tl-start')),
end: textOf(item.querySelector('.tl-end')),
lines: [...item.querySelectorAll('.note-line')].map(line =>
[...line.children].map(part => textOf(part)).filter(Boolean).join(' · ')),
codes: [...item.querySelectorAll('.note-extra .code-chip')].map(code => textOf(code)),
}))
}
/** Every line printed under the bookings' titles, across the days. */
const bookingLines = (html: string) => bookingsOf(html).flatMap(b => b.lines)
/** The booking of that title and span label, as bookingsOf reads it. */
function bookingCard(html: string, title: string, kicker = '') {
const card = bookingsOf(html).find(b => b.title === title && b.kicker === kicker)
if (!card) throw new Error(`no booking "${title}" labelled "${kicker}"`)
return card
}
// ── Setup ─────────────────────────────────────────────────────────────────────
beforeEach(() => {
@@ -210,8 +175,8 @@ describe('downloadTripPDF', () => {
expect(srcdoc).toContain('<table class="day-section')
expect(srcdoc).toContain('<thead class="day-header">')
expect(srcdoc).toContain('<tbody class="day-body-group">')
// The header (number, date, title, figures) lives in an inner wrapper inside the thead.
expect(srcdoc).toContain('<thead class="day-header"><tr><td><div class="day-head">')
// The dark bar (background/padding/flex) lives in an inner wrapper inside the thead.
expect(srcdoc).toContain('class="day-header-bar"')
// Day content still renders inside the new structure.
expect(srcdoc).toContain('Rome Day')
expect(srcdoc).toContain('Colosseum')
@@ -223,10 +188,10 @@ describe('downloadTripPDF', () => {
const srcdoc = iframe!.srcdoc
// The thead is repeated on every overflow page, so the spacing below the header bar
// must be declared on its cell...
expect(srcdoc).toContain('.day-header > tr > td { padding: 0 var(--gutter) 5mm; }')
expect(srcdoc).toContain('.day-header > tr > td { padding-bottom: 12px; }')
// ...and not as a block-start padding on .day-body, which the print engine only paints
// on the first fragment of the (fragmented) body cell.
expect(srcdoc).toContain('.day-body { padding: 0 var(--gutter) 4mm; }')
expect(srcdoc).toContain('.day-body { padding: 0 28px 6px; }')
})
it('FE-COMP-TRIPPDF-006: escHtml prevents XSS in trip title', async () => {
@@ -290,27 +255,8 @@ describe('downloadTripPDF', () => {
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('Flight to Rome')
expect(iframe!.srcdoc).toContain('ABC123')
// Single-leg flight keeps its full route, then airline and number as badges.
expect(bookingLines(iframe!.srcdoc)).toContain('CDG → FCO · Air Italia · AI123')
})
it('FE-COMP-TRIPPDF-013s: a flight prints its seat, a direct one and each leg of one with a stop alike', async () => {
const direct = { ...transportReservation, metadata: JSON.stringify({ airline: 'Air Italia', flight_number: 'AI123', seat: '31A', departure_airport: 'CDG', arrival_airport: 'FCO' }) }
const stopover = {
...multiLegFlight,
metadata: JSON.stringify({
legs: [
{ from: 'FRA', to: 'BER', airline: 'Lufthansa', flight_number: 'LH1' },
{ from: 'BER', to: 'HND', airline: 'Lufthansa', flight_number: 'LH2', seat: '14C' },
],
departure_airport: 'FRA', arrival_airport: 'HND', airline: 'Lufthansa', flight_number: 'LH1',
}),
}
await downloadTripPDF({ ...richArgs, reservations: [direct, stopover] })
const lines = bookingLines(getIframe()?.srcdoc ?? '')
expect(lines).toContain('CDG → FCO · Air Italia · AI123 · reservations.meta.seat 31A')
expect(lines).toContain('BER → HND · Lufthansa · LH2 · reservations.meta.seat 14C')
expect(lines).toContain('FRA → BER · Lufthansa · LH1')
// Single-leg flight keeps its full-route subtitle.
expect(iframe!.srcdoc).toContain('Air Italia · AI123 · CDG → FCO')
})
it('FE-COMP-TRIPPDF-013f: the stop a booked night wrote is not listed, so a morning flight prints before the hotel (#2434)', async () => {
@@ -364,14 +310,15 @@ describe('downloadTripPDF', () => {
const iframe = getIframe()
// Without the landing time the reader cannot tell what is left of the day.
expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '16:45' })
expect(iframe!.srcdoc).toContain('14:30 – 16:45')
})
it('FE-COMP-TRIPPDF-013d: a flight without a landing time still shows its departure', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '' })
expect(iframe!.srcdoc).toContain('14:30')
expect(iframe!.srcdoc).not.toContain('14:30 –')
})
it('FE-COMP-TRIPPDF-013e: an overnight flight keeps its arrival on the arrival day (#1310)', async () => {
@@ -385,16 +332,16 @@ describe('downloadTripPDF', () => {
})
const iframe = getIframe()
const html = iframe!.srcdoc
expect(bookingCard(html, 'Flight to Rome', 'reservations.span.departure')).toMatchObject({ start: '14:30', end: '' })
expect(bookingCard(html, 'Flight to Rome', 'reservations.span.arrival')).toMatchObject({ start: '06:15' })
expect(iframe!.srcdoc).not.toContain('14:30 – 06:15')
expect(iframe!.srcdoc).toContain('06:15')
})
it('FE-COMP-TRIPPDF-013b: renders every flight number for a multi-leg flight', async () => {
await downloadTripPDF({ ...richArgs, reservations: [multiLegFlight] })
const iframe = getIframe()
// One line per leg, each with its own flight number and segment route.
expect(bookingLines(iframe!.srcdoc)).toEqual(['FRA → BER · Lufthansa · LH1', 'BER → HND · Lufthansa · LH2'])
// One subtitle line per leg, each with its own flight number and segment route.
expect(iframe!.srcdoc).toContain('Lufthansa · LH1 · FRA → BER')
expect(iframe!.srcdoc).toContain('Lufthansa · LH2 · BER → HND')
})
it('FE-COMP-TRIPPDF-014: renders cover image when trip has cover_image', async () => {
@@ -794,9 +741,11 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.start').start).toBe('09:00')
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.ongoing').start).toBe('')
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.end').start).toBe('18:00')
expect(html).toContain('reservations.span.start: Nordic Cruise')
expect(html).toContain('reservations.span.ongoing: Nordic Cruise')
expect(html).toContain('reservations.span.end: Nordic Cruise')
expect(html).toContain('09:00')
expect(html).toContain('18:00')
})
it('FE-W5PDF-002: a multi-day flight uses departure/arrival wording', async () => {
@@ -807,8 +756,8 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(bookingCard(html, 'Red Eye', 'reservations.span.departure').start).toBe('23:00')
expect(bookingCard(html, 'Red Eye', 'reservations.span.arrival').start).toBe('06:00')
expect(html).toContain('reservations.span.departure: Red Eye')
expect(html).toContain('reservations.span.arrival: Red Eye')
})
it('FE-W5PDF-003: a multi-day car hire is labelled pickup/return and skips the middle day', async () => {
@@ -818,10 +767,8 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(bookingsOf(html).map(b => [b.kicker, b.title])).toEqual([
['reservations.span.pickup', 'Rental'],
['reservations.span.return', 'Rental'],
])
expect(html).toContain('reservations.span.pickup: Rental')
expect(html).toContain('reservations.span.return: Rental')
expect(html).not.toContain('reservations.span.active')
})
@@ -832,10 +779,8 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(bookingsOf(html).map(b => [b.kicker, b.title])).toEqual([
['reservations.span.dropOff', 'Airport Parking'],
['reservations.span.pickup', 'Airport Parking'],
])
expect(html).toContain('reservations.span.dropOff: Airport Parking')
expect(html).toContain('reservations.span.pickup: Airport Parking')
expect(html).not.toContain('reservations.span.ongoing')
// Day B holds nothing else, so it prints the empty-day hint rather than the booking.
expect(html).toContain('dayplan.emptyDay')
@@ -864,7 +809,7 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(bookingLines(html)).toEqual(['FRA → BER · ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A'])
expect(html).toContain('ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A · FRA → BER')
})
it('FE-W5PDF-006: a multi-leg train renders one line per leg', async () => {
@@ -879,7 +824,8 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(bookingLines(html)).toEqual(['BER → MUC · IC 1 · reservations.meta.platform 3', 'MUC → ZRH · EC 2'])
expect(html).toContain('IC 1 · reservations.meta.platform 3 · BER → MUC')
expect(html).toContain('EC 2 · MUC → ZRH')
})
it('FE-W5PDF-007: restaurant, event, tour and unknown types get their own subtitles', async () => {
@@ -891,8 +837,7 @@ describe('downloadTripPDF remaining branches', () => {
]))
const html = srcdoc()
// The party size needs no word: it prints beside the people icon.
expect(bookingCard(html, 'Dinner').lines).toEqual(['4'])
expect(html).toContain('4 guests')
expect(html).toContain('Arena')
expect(html).toContain('GuideCo')
expect(html).toContain('Mystery')
@@ -925,7 +870,8 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(bookingLines(html)).toEqual(['AirX · X1', 'AAA → BBB · AirX · X2'])
expect(html).toContain('AirX · X1')
expect(html).toContain('AirX · X2 · AAA → BBB')
})
it('FE-W5PDF-030: a stopover flight prints the booking code of each segment that has one (#1943)', async () => {
@@ -940,12 +886,11 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
// Each leg is its own card, the way the day plan shows it, with its own line.
const legs = bookingsOf(html).filter(b => b.title === 'Layover')
expect(legs.map(leg => leg.lines)).toEqual([['FRA → BER · LH · LH1 · ABC123'], ['BER → HND · ANA · NH2']])
expect(html).toContain('LH · LH1 · FRA → BER · ABC123')
// A segment without one keeps the line it had before, and the booking's own
// reference still prints on its card.
expect(legs[0].codes).toEqual(['BOOK1'])
// reference still prints once for the whole card.
expect(html).toContain('ANA · NH2 · BER → HND')
expect(html).toContain('Code: BOOK1')
})
it('FE-W5PDF-010: a single-leg flight with waypoints joins the whole route', async () => {
@@ -955,7 +900,7 @@ describe('downloadTripPDF remaining branches', () => {
metadata: { airline: 'LH', flight_number: 'LH7' },
}]))
expect(bookingLines(srcdoc())).toEqual(['FRA → Berlin → HND · LH · LH7'])
expect(srcdoc()).toContain('LH · LH7 · FRA → Berlin → HND')
})
it('FE-W5PDF-011: an assignment without a place contributes nothing', async () => {
@@ -1039,11 +984,9 @@ describe('downloadTripPDF remaining branches', () => {
await downloadTripPDF(spanArgs([]))
const html = srcdoc()
const days = daysOf(html)
expect(days.indexOf('Earlier Inn')).toBeGreaterThan(-1)
expect(days.indexOf('Earlier Inn')).toBeLessThan(days.indexOf('Later Inn'))
expect(html.indexOf('Earlier Inn')).toBeLessThan(html.indexOf('Later Inn'))
// the shared days list two hotels, so they lose the single-column class
expect(html).toContain('class="day-accommodations"')
expect(html).toContain('class="day-accommodations "')
})
it('FE-W5PDF-017: a trip without dated days prints no date range and no day dates', async () => {
@@ -1056,7 +999,7 @@ describe('downloadTripPDF remaining branches', () => {
expect(html).not.toContain('class="cover-dates"')
expect(html).not.toContain('class="day-date"')
expect(html).toContain('<section class="cover cover-plain">')
expect(html).toContain('class="cover-circle-ph"')
})
it('FE-W5PDF-018: the print button asks the preview frame to print', async () => {
@@ -1083,7 +1026,7 @@ describe('downloadTripPDF remaining branches', () => {
trip: { id: 1, title: 'Cover Trip', description: null, cover_image: '/uploads/cover.svg' } as any,
})
expect(srcdoc()).not.toContain('/uploads/cover.svg')
expect(srcdoc()).toContain('<section class="cover cover-plain">')
expect(srcdoc()).toContain('class="cover-circle-ph"')
})
it('FE-W5PDF-020: plugin sections render their paragraphs and tables', async () => {
@@ -1119,7 +1062,7 @@ describe('downloadTripPDF defaults', () => {
// no translator, no days, no places, no notes
expect(html).toContain('pdf.travelPlan')
expect(html).toContain('<h1 class="cover-title">My Trip</h1>')
expect(html).toContain('<div class="cover-title">My Trip</div>')
expect(html).toContain('<div class="cover-stat-num">0</div>')
})
@@ -1184,9 +1127,11 @@ describe('downloadTripPDF defaults', () => {
reservations: [{ id: 1, title: 'Overnight Bus', type: 'bus', day_id: 1, end_day_id: 2, reservation_time: '22:00', reservation_end_time: null }] as any[],
})
const html = srcdoc()
const endSection = html.slice(html.indexOf('End Day'))
expect(bookingCard(html, 'Overnight Bus', 'reservations.span.start').start).toBe('22:00')
expect(bookingCard(html, 'Overnight Bus', 'reservations.span.end')).toMatchObject({ start: '', end: '' })
expect(html).toContain('reservations.span.start: Overnight Bus')
expect(endSection).toContain('reservations.span.end: Overnight Bus')
expect(endSection).not.toContain('22:00')
})
it('FE-W5PDF-027: an export without a locale still renders, with lang="en"', async () => {
@@ -1253,16 +1198,12 @@ describe('page breaks between days (#1292)', () => {
expect(toggle()!.style.background).toContain('--border-primary')
})
// The first day opens the plan after the cover and the overview, so it always starts a
// sheet; the switch decides only whether the days after it do.
it('FE-PDF-BREAK-003: the first day never carries the switchable break', async () => {
it('FE-PDF-BREAK-003: the first day never carries a break of its own', async () => {
await downloadTripPDF(twoDays)
const html = getIframe()!.srcdoc
expect(html.indexOf('<table class="day-section day-first"')).toBeGreaterThan(-1)
expect(html.indexOf('<table class="day-section">')).toBeGreaterThan(-1)
expect(html.match(/day-section day-break/g)).toHaveLength(1)
expect(html).toContain('.day-first { break-before: page; }')
expect(html).toContain('.pdf-flow .day-break { break-before: auto; }')
})
it('FE-PDF-BREAK-004: turning the breaks off is remembered and shown at once', async () => {
@@ -1345,8 +1286,8 @@ describe('a printed day follows the plan (#1978)', () => {
const d2 = { id: 22, day_number: 2, title: 'Day Two', date: '2025-06-02' } as any
const srcdoc = () => getIframe()!.srcdoc
/** Where each needle first appears in the days, so order can be asserted without parsing. */
const positions = (html: string, needles: string[]) => needles.map(n => daysOf(html).indexOf(n))
/** Where each needle first appears, so order can be asserted without parsing. */
const positions = (html: string, needles: string[]) => needles.map(n => html.indexOf(n))
it('orders the day by the clock, not by the order the API sent rows in', async () => {
await downloadTripPDF({
@@ -1430,7 +1371,7 @@ describe('a printed day follows the plan (#1978)', () => {
dayId: 21,
}).map(item => (item.type === 'place' ? item.data.place.name : item.data.title))
const seen = expected.map(name => daysOf(html).indexOf(name))
const seen = expected.map(name => html.indexOf(name))
for (const at of seen) expect(at).toBeGreaterThan(-1)
expect(seen).toEqual([...seen].sort((a, b) => a - b))
})
@@ -1513,20 +1454,18 @@ describe('downloadTripPDF — large text', () => {
expect(html).not.toContain('pdf-large-text"')
expect(largeToggle().getAttribute('aria-checked')).toBe('false')
// One scale and one set of greys, at today's values unless the class is on.
expect(html).toContain('--t: 1;')
expect(html).toContain('--pdf-text: 1;')
expect(html).toContain('body.pdf-large-text {')
expect(html).toContain('.place-name { flex: 1; font-size: calc(12px * var(--t));')
expect(html).toContain('.note-text { font-size: calc(9.5px * var(--t)); color: var(--ink);')
expect(html).toContain('.place-name { font-size: calc(11.5px * var(--pdf-text));')
expect(html).toContain('.note-text { font-size: calc(9.5px * var(--pdf-text)); color: var(--pdf-ink);')
})
it('FE-PDF-LARGE-002: the clock and the booking code of a transport scale with the rest', async () => {
await downloadTripPDF(richArgs)
const html = previewFrame().srcdoc
// The clock sits in the time column and the code in its chip, both on the scale.
expect(bookingCard(html, 'Flight to Rome')).toMatchObject({ start: '14:30', codes: ['ABC123'] })
expect(html).toContain('.tl-start { display: block; font-size: calc(9.5px * var(--t));')
expect(html).toContain('font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.04em;')
expect(html).toContain('<span class="note-clock">')
expect(html).toContain('<div class="note-time note-code">Code: ABC123</div>')
expect(html).not.toContain('font-size:10px;')
})
@@ -1591,14 +1530,14 @@ describe('downloadTripPDF — photos at thumbnail size', () => {
await downloadTripPDF(withImage('/uploads/colosseum.jpg'))
const html = previewFrame().srcdoc
expect(html).toContain(`<img class="place-thumb" src="${JPEG}" alt="" />`)
expect(html).toContain(`<img class="place-thumb" src="${JPEG}" />`)
expect(html).not.toContain('colosseum.jpg')
})
it('FE-PDF-THUMB-002: a photo from another origin keeps its URL', async () => {
await downloadTripPDF(withImage('https://images.example.com/colosseum.jpg'))
expect(previewFrame().srcdoc).toContain('<img class="place-thumb" src="https://images.example.com/colosseum.jpg" alt="" />')
expect(previewFrame().srcdoc).toContain('<img class="place-thumb" src="https://images.example.com/colosseum.jpg" />')
})
it('FE-PDF-THUMB-003: a closed export dialog stops the photos and opens nothing', async () => {
File diff suppressed because it is too large Load Diff
+5 -53
View File
@@ -8,15 +8,13 @@ import { http, HttpResponse } from 'msw';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { bakePdfCover, shrinkPdfImages, STRIP_PX } from './pdfImages';
import { shrinkPdfImages } from './pdfImages';
const origin = window.location.origin;
const JPEG = 'data:image/jpeg;base64,c21hbGw=';
let bitmapSize = { width: 1200, height: 800 };
let drawn: { width: number; height: number }[] = [];
let drawCalls: unknown[][] = [];
let stops: [number, string][] = [];
let inFlight = 0;
let mostInFlight = 0;
@@ -26,11 +24,7 @@ function fakeContext(this: HTMLCanvasElement, type: string) {
return {
fillStyle: '',
fillRect: vi.fn(),
drawImage: vi.fn((...args: unknown[]) => {
drawCalls.push(args);
drawn.push({ width: this.width, height: this.height });
}),
createLinearGradient: vi.fn(() => ({ addColorStop: (at: number, colour: string) => stops.push([at, colour]) })),
drawImage: vi.fn(() => drawn.push({ width: this.width, height: this.height })),
};
}
@@ -41,8 +35,6 @@ function imageResponse(type = 'image/jpeg') {
beforeEach(() => {
bitmapSize = { width: 1200, height: 800 };
drawn = [];
drawCalls = [];
stops = [];
inFlight = 0;
mostInFlight = 0;
vi.stubGlobal(
@@ -72,27 +64,19 @@ afterEach(() => {
});
describe('shrinkPdfImages', () => {
it('FE-PDFIMAGES-001: a same-origin photo comes back as a JPEG with its short side at 222 px', async () => {
it('FE-PDFIMAGES-001: a same-origin photo comes back as a JPEG with its short side at 156 px', async () => {
const url = `${origin}/uploads/places/a.jpg`;
const shrunk = await shrinkPdfImages([url]);
expect(shrunk.get(url)).toBe(JPEG);
expect(drawn).toEqual([{ width: 333, height: 222 }]);
expect(drawn).toEqual([{ width: 234, height: 156 }]);
expect(HTMLCanvasElement.prototype.toDataURL).toHaveBeenCalledWith('image/jpeg', expect.any(Number));
});
it('FE-PDFIMAGES-001b: a photo is decoded near thumbnail size, not in full', async () => {
await shrinkPdfImages([`${origin}/uploads/places/a.jpg`]);
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 444, resizeQuality: 'medium' });
});
it('FE-PDFIMAGES-001c: the photo strip of a day asks for a larger copy, decoded at twice its size', async () => {
const url = `${origin}/uploads/places/a.jpg`;
await shrinkPdfImages([url], undefined, STRIP_PX);
expect(drawn).toEqual([{ width: 720, height: 480 }]);
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 960, resizeQuality: 'medium' });
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 312, resizeQuality: 'medium' });
});
it('FE-PDFIMAGES-002: a photo from another origin keeps its URL and is never fetched', async () => {
@@ -151,35 +135,3 @@ describe('shrinkPdfImages', () => {
expect(shrunk.has(url)).toBe(false);
});
});
describe('bakePdfCover', () => {
it('FE-PDFIMAGES-010: the photo is cropped to the page and the shade painted into one JPEG', async () => {
bitmapSize = { width: 4000, height: 2252 };
const url = `${origin}/uploads/places/cover.jpg`;
const baked = await bakePdfCover(url, [
[0, 0.35],
[0.92, 0.82],
]);
expect(baked).toBe(JPEG);
// Decoded at the page's height, not in full.
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 1754, resizeQuality: 'medium' });
// A4 at 150 dpi, the landscape photo scaled to the page height and centred.
expect(drawn).toEqual([{ width: 1240, height: 1754 }]);
const [, x, y, width, height] = drawCalls[0] as number[];
expect(height).toBeCloseTo(1754, 0);
expect(width).toBeCloseTo((4000 * 1754) / 2252, 0);
expect(x).toBeCloseTo((1240 - width) / 2, 3);
expect(y).toBeCloseTo(0, 3);
expect(stops).toEqual([
[0, 'rgba(10, 10, 14, 0.35)'],
[0.92, 'rgba(10, 10, 14, 0.82)'],
]);
});
it('FE-PDFIMAGES-011: a cover from another origin or one that cannot be read is left to print as before', async () => {
expect(await bakePdfCover('https://elsewhere.example/cover.jpg', [[0, 0.5]])).toBeNull();
expect(await bakePdfCover(`${origin}/uploads/missing.jpg`, [[0, 0.5]])).toBeNull();
expect(drawn).toEqual([]);
});
});
+19 -81
View File
@@ -12,16 +12,16 @@
* than FETCH_TIMEOUT_MS.
*/
/** The short side of a place card's copy: three times its 74 px photo, sharp at print resolution. */
const THUMB_PX = 222;
/** The short side of a copy for the photo strip that opens a day, which runs the width of the page. */
export const STRIP_PX = 480;
/** The short side of a copy: three times the 52 px thumbnail, sharp at print resolution. */
const THUMB_PX = 156;
const JPEG_QUALITY = 0.72;
/**
* Photos in flight at once: a trip of hundreds should neither queue one by one nor
* decode all at once. Kept low for the phone, where each decode costs memory.
*/
const CONCURRENCY = 3;
/** Height a photo is decoded at: twice THUMB_PX, so a portrait one still has room to shrink. */
const DECODE_PX = THUMB_PX * 2;
const FETCH_TIMEOUT_MS = 10_000;
/** Anything larger is not read into memory for a thumbnail; it keeps its URL. */
const MAX_BYTES = 20 * 1024 * 1024;
@@ -31,18 +31,14 @@ const MAX_BYTES = 20 * 1024 * 1024;
* missing from the result prints as it is. Stops starting new photos once
* `signal` aborts, and returns what it has.
*/
export async function shrinkPdfImages(
urls: Iterable<string>,
signal?: AbortSignal,
shortSide = THUMB_PX
): Promise<Map<string, string>> {
export async function shrinkPdfImages(urls: Iterable<string>, signal?: AbortSignal): Promise<Map<string, string>> {
const shrunk = new Map<string, string>();
const queue = [...new Set(urls)].filter(isSameOrigin);
if (queue.length === 0 || !canShrink()) return shrunk;
const worker = async () => {
for (let url = queue.shift(); url !== undefined && !signal?.aborted; url = queue.shift()) {
const copy = await shrinkImage(url, shortSide, signal);
const copy = await shrinkImage(url, signal);
if (copy) shrunk.set(url, copy);
}
};
@@ -65,24 +61,7 @@ function canShrink(): boolean {
return typeof createImageBitmap === 'function' && document.createElement('canvas').getContext('2d') !== null;
}
async function shrinkImage(url: string, shortSide: number, signal?: AbortSignal): Promise<string | null> {
// Decoded at twice the short side, so a portrait photo still has room to shrink.
const bitmap = await fetchBitmap(url, shortSide * 2, signal);
if (!bitmap) return null;
try {
return toJpeg(bitmap, shortSide);
} finally {
bitmap.close();
}
}
/**
* The photo at `url` decoded at `height` pixels, or null when it cannot be had. Decoded
* near the size it is drawn at: a 48 MP phone photo decoded in full holds about 190 MB,
* which can end the web view on a phone. Browsers without the option decode in full and
* the canvas scales down as before.
*/
async function fetchBitmap(url: string, height: number, signal?: AbortSignal): Promise<ImageBitmap | null> {
async function shrinkImage(url: string, signal?: AbortSignal): Promise<string | null> {
// A controller and a timer rather than AbortSignal.timeout/any, which Safari only
// has from 16 and 17.4 on; a throw there would cost the whole export.
const fetching = new AbortController();
@@ -94,7 +73,15 @@ async function fetchBitmap(url: string, height: number, signal?: AbortSignal): P
if (!res.ok || Number(res.headers.get('content-length') ?? 0) > MAX_BYTES) return null;
const blob = await res.blob();
if (!blob.type.startsWith('image/') || blob.size > MAX_BYTES) return null;
return await createImageBitmap(blob, { resizeHeight: height, resizeQuality: 'medium' });
// Decoded near thumbnail size: a 48 MP phone photo decoded in full holds about
// 190 MB, which can end the web view on a phone. Browsers without the option
// decode in full and toJpeg scales down as before.
const bitmap = await createImageBitmap(blob, { resizeHeight: DECODE_PX, resizeQuality: 'medium' });
try {
return toJpeg(bitmap);
} finally {
bitmap.close();
}
} catch {
// Offline, timed out, aborted or undecodable: the photo prints from its URL.
return null;
@@ -104,58 +91,9 @@ async function fetchBitmap(url: string, height: number, signal?: AbortSignal): P
}
}
/** The cover page in pixels: A4 at 150 dpi, enough for a photo behind the type. */
const COVER_W = 1240;
const COVER_H = 1754;
const COVER_QUALITY = 0.82;
/** One stop of the shade over the cover photo: how far down the page, 0 to 1, and how dark. */
export type ShadeStop = readonly [at: number, alpha: number];
/**
* The cover photo cropped to the page with its shade painted in, as one JPEG at print
* size. A page-sized photo under a translucent gradient is composited again by every
* viewer on every redraw, which made the first pages stutter in the preview and in the
* saved file; one flat picture is drawn once. Null for a photo from another origin or
* one that cannot be read: the cover then prints the photo and the shade as before.
*/
export async function bakePdfCover(
url: string,
shade: readonly ShadeStop[],
signal?: AbortSignal
): Promise<string | null> {
if (!isSameOrigin(url) || !canShrink()) return null;
const bitmap = await fetchBitmap(url, COVER_H, signal);
if (!bitmap) return null;
try {
const canvas = document.createElement('canvas');
canvas.width = COVER_W;
canvas.height = COVER_H;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
// Cropped the way background-size: cover crops it, around the middle.
const scale = Math.max(COVER_W / bitmap.width, COVER_H / bitmap.height);
const width = bitmap.width * scale;
const height = bitmap.height * scale;
ctx.drawImage(bitmap, (COVER_W - width) / 2, (COVER_H - height) / 2, width, height);
const gradient = ctx.createLinearGradient(0, 0, 0, COVER_H);
for (const [at, alpha] of shade) gradient.addColorStop(at, `rgba(10, 10, 14, ${alpha})`);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, COVER_W, COVER_H);
const baked = canvas.toDataURL('image/jpeg', COVER_QUALITY);
return baked.startsWith('data:image/jpeg') ? baked : null;
} catch {
// A canvas the browser will not draw or encode (out of memory on a phone, say):
// the cover then prints the photo and its shade as separate layers, as before.
return null;
} finally {
bitmap.close();
}
}
/** The bitmap with its short side at `shortSide`, or null when it is that small already. */
function toJpeg(bitmap: ImageBitmap, shortSide: number): string | null {
const scale = shortSide / Math.min(bitmap.width, bitmap.height);
/** The bitmap with its short side at THUMB_PX, or null when it is that small already. */
function toJpeg(bitmap: ImageBitmap): string | null {
const scale = THUMB_PX / Math.min(bitmap.width, bitmap.height);
if (!Number.isFinite(scale) || scale >= 1) return null;
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
+2 -54
View File
@@ -1,21 +1,12 @@
/**
* FE-PDFPREVIEW-001 to FE-PDFPREVIEW-009: the trip PDF's preview and the control
* FE-PDFPREVIEW-001 to FE-PDFPREVIEW-007: the trip PDF's preview and the control
* that saves it. An iPhone or iPad ignores print() in the Home Screen app, so
* there the preview hands the export to Safari instead of offering a button that
* does nothing.
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
COORDINATES_KEY,
DETAILS_KEY,
LARGE_TEXT_KEY,
OVERVIEW_KEY,
PAGE_BREAK_KEY,
PHOTOS_KEY,
openPdfPreview,
type PdfPreviewOptions,
} from './pdfPreview';
import { LARGE_TEXT_KEY, PAGE_BREAK_KEY, openPdfPreview, type PdfPreviewOptions } from './pdfPreview';
const tr = (key: string) => key;
@@ -29,10 +20,6 @@ function open(overrides: Partial<PdfPreviewOptions> = {}) {
showTransportNotes: true,
hasTransportNotes: false,
largeText: false,
photos: true,
overview: true,
coordinates: true,
details: true,
...overrides,
});
}
@@ -124,43 +111,4 @@ describe('openPdfPreview', () => {
}
expect(document.getElementById('pdf-large-text-toggle')?.getAttribute('aria-checked')).toBe('true');
});
it('FE-PDFPREVIEW-008: the switches sit in a row of their own under the title and the actions', () => {
open({ hasTransportNotes: true });
const row = document.getElementById('pdf-settings-row');
const ids = [...(row?.querySelectorAll('[role="switch"]') ?? [])].map((toggle) => toggle.id);
expect(ids).toEqual([
'pdf-daybreak-toggle',
'pdf-large-text-toggle',
'pdf-overview-toggle',
'pdf-photos-toggle',
'pdf-coordinates-toggle',
'pdf-details-toggle',
'pdf-transport-notes-toggle',
]);
// The header keeps only the title and its two actions.
expect(row?.previousElementSibling?.querySelector('[role="switch"]')).toBeNull();
expect(row?.previousElementSibling?.querySelector('#pdf-print-btn')).not.toBeNull();
});
it.each([
['pdf-overview-toggle', OVERVIEW_KEY, 'pdf-no-overview'],
['pdf-photos-toggle', PHOTOS_KEY, 'pdf-no-photos'],
['pdf-coordinates-toggle', COORDINATES_KEY, 'pdf-no-coords'],
['pdf-details-toggle', DETAILS_KEY, 'pdf-no-details'],
])('FE-PDFPREVIEW-009: %s hides its part of the open document at once and is remembered', (id, key, hidden) => {
open();
const toggle = document.getElementById(id);
const body = document.querySelector<HTMLIFrameElement>('#pdf-preview-overlay iframe')?.contentDocument?.body;
expect(toggle?.getAttribute('aria-checked')).toBe('true');
toggle?.click();
expect(toggle?.getAttribute('aria-checked')).toBe('false');
expect(localStorage.getItem(key)).toBe('0');
if (body) expect(body.classList.contains(hidden)).toBe(true);
toggle?.click();
expect(localStorage.getItem(key)).toBe('1');
if (body) expect(body.classList.contains(hidden)).toBe(false);
});
});
+16 -50
View File
@@ -25,17 +25,6 @@ export const TRANSPORT_NOTES_KEY = 'trek_pdf_transport_notes';
*/
export const LARGE_TEXT_KEY = 'trek_pdf_large_text';
/**
* What the document shows besides the plan itself, each on by default and each a
* switch in the preview: the photos of the places and stays, the overview pages
* (route map, the days at a glance, bookings and stays), the coordinates under the
* addresses, and the contact lines, opening hours and companions of a place.
*/
export const PHOTOS_KEY = 'trek_pdf_photos';
export const OVERVIEW_KEY = 'trek_pdf_overview';
export const COORDINATES_KEY = 'trek_pdf_coordinates';
export const DETAILS_KEY = 'trek_pdf_details';
/* The overlay is imperative DOM, so the switch from Settings/ToggleSwitch is
rebuilt here rather than rendered — as static markup it would carry no
behaviour. Same geometry and the same tokens, so it reads as the same control. */
@@ -63,10 +52,6 @@ export interface PdfPreviewOptions {
/** The transport-notes switch only shows when there is a note to hide. */
hasTransportNotes: boolean;
largeText: boolean;
photos: boolean;
overview: boolean;
coordinates: boolean;
details: boolean;
}
/**
@@ -99,10 +84,6 @@ export function openPdfPreview({
showTransportNotes,
hasTransportNotes,
largeText,
photos,
overview,
coordinates,
details,
}: PdfPreviewOptions): void {
// Open in modal with srcdoc iframe (no URL loading = no X-Frame-Options issue)
const overlay = document.createElement('div');
@@ -123,7 +104,10 @@ export function openPdfPreview({
'display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;padding:10px 16px;border-bottom:1px solid var(--border-primary);flex-shrink:0;';
header.innerHTML = `
<span style="font-size:13px;font-weight:600;color:var(--text-primary);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escapeHtml(title)}</span>
<div style="display:flex;align-items:center;justify-content:flex-end;gap:8px">
<div style="display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:8px">
${hasTransportNotes ? previewSwitch('pdf-transport-notes-toggle', tr('pdf.transportNotes'), showTransportNotes) : ''}
${previewSwitch('pdf-daybreak-toggle', tr('pdf.pageBreakPerDay'), breaksPerDay)}
${previewSwitch('pdf-large-text-toggle', tr('pdf.largeText'), largeText)}
${save.html}
<button type="button" id="pdf-close-btn" style="background:none;border:none;cursor:pointer;color:var(--text-faint);display:flex;padding:4px;border-radius:6px">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
@@ -131,23 +115,6 @@ export function openPdfPreview({
</div>
`;
// The document's switches in a row of their own under the header: the layout first,
// then what it shows, so the header keeps only the title and the actions.
const settings = document.createElement('div');
settings.id = 'pdf-settings-row';
settings.style.cssText =
'display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;padding:8px 16px;border-bottom:1px solid var(--border-primary);background:var(--bg-secondary);flex-shrink:0;';
settings.innerHTML = [
previewSwitch('pdf-daybreak-toggle', tr('pdf.pageBreakPerDay'), breaksPerDay),
previewSwitch('pdf-large-text-toggle', tr('pdf.largeText'), largeText),
'<span aria-hidden="true" style="width:1px;align-self:stretch;background:var(--border-primary)"></span>',
previewSwitch('pdf-overview-toggle', tr('pdf.showOverview'), overview),
previewSwitch('pdf-photos-toggle', tr('pdf.showPhotos'), photos),
previewSwitch('pdf-coordinates-toggle', tr('collections.coordinates'), coordinates),
previewSwitch('pdf-details-toggle', tr('pdf.showDetails'), details),
hasTransportNotes ? previewSwitch('pdf-transport-notes-toggle', tr('pdf.transportNotes'), showTransportNotes) : '',
].join('');
const iframe = document.createElement('iframe');
iframe.style.cssText = 'flex:1;width:100%;border:none;';
// No script runs inside the document (print is parent-initiated), so withhold
@@ -156,7 +123,6 @@ export function openPdfPreview({
iframe.srcdoc = html;
card.appendChild(header);
card.appendChild(settings);
if (save.hint) {
const hint = document.createElement('p');
hint.id = 'pdf-safari-hint';
@@ -179,18 +145,18 @@ export function openPdfPreview({
// Each choice differs by one class on <body>, so switching is instant in the
// preview and there is no need to re-fetch photos or rebuild the document.
const bodyClass = (id: string, key: string, className: string, addWhenOn: boolean) =>
wirePreviewSwitch(settings, id, (on) => {
rememberPdfSwitch(key, on);
iframe.contentDocument?.body.classList.toggle(className, addWhenOn ? on : !on);
});
bodyClass('pdf-daybreak-toggle', PAGE_BREAK_KEY, 'pdf-flow', false);
bodyClass('pdf-transport-notes-toggle', TRANSPORT_NOTES_KEY, 'pdf-no-transport-notes', false);
bodyClass('pdf-large-text-toggle', LARGE_TEXT_KEY, 'pdf-large-text', true);
bodyClass('pdf-overview-toggle', OVERVIEW_KEY, 'pdf-no-overview', false);
bodyClass('pdf-photos-toggle', PHOTOS_KEY, 'pdf-no-photos', false);
bodyClass('pdf-coordinates-toggle', COORDINATES_KEY, 'pdf-no-coords', false);
bodyClass('pdf-details-toggle', DETAILS_KEY, 'pdf-no-details', false);
wirePreviewSwitch(header, 'pdf-daybreak-toggle', (on) => {
rememberPdfSwitch(PAGE_BREAK_KEY, on);
iframe.contentDocument?.body.classList.toggle('pdf-flow', !on);
});
wirePreviewSwitch(header, 'pdf-transport-notes-toggle', (on) => {
rememberPdfSwitch(TRANSPORT_NOTES_KEY, on);
iframe.contentDocument?.body.classList.toggle('pdf-no-transport-notes', !on);
});
wirePreviewSwitch(header, 'pdf-large-text-toggle', (on) => {
rememberPdfSwitch(LARGE_TEXT_KEY, on);
iframe.contentDocument?.body.classList.toggle('pdf-large-text', on);
});
}
/**
+1 -23
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { buildTripMapSvg, drawnPoints } from './tripMapSvg'
import { buildTripMapSvg } from './tripMapSvg'
import type { TripOverviewDay } from '../Map/tripRouteGeometry'
const day = (over: Partial<TripOverviewDay> = {}): TripOverviewDay => ({
@@ -78,25 +78,3 @@ describe('buildTripMapSvg', () => {
expect(svg).toContain('width="720"')
})
})
// A routed road carries a point every few metres; drawn as it came, a trip map held
// tens of thousands of them and stuttered in every viewer.
describe('drawnPoints', () => {
// One degree is one map pixel, so the tolerance reads in degrees here.
const flat = (lat: number, lng: number): [number, number] => [lng, -lat]
it('FE-PDF-MAPSVG-020: a dense straight road keeps only its ends', () => {
const road = Array.from({ length: 5000 }, (_, i) => [0, i / 10] as [number, number])
expect(drawnPoints(road, flat)).toBe('0,0 499.9,0')
})
it('FE-PDF-MAPSVG-021: a turn is kept, a wobble under the tolerance is not', () => {
const road: [number, number][] = [[0, 0], [-0.1, 50], [0, 100], [-60, 100], [-0.2, 100.1]]
expect(drawnPoints(road, flat)).toBe('0,0 100,0 100,60 100.1,0.2')
})
it('FE-PDF-MAPSVG-022: points that round onto the same pixel are drawn once', () => {
const road: [number, number][] = [[0, 0], [0, 0.01], [0, 0.02], [0, 0.04]]
expect(drawnPoints(road, flat)).toBe('0,0')
})
})
+2 -51
View File
@@ -125,55 +125,6 @@ export interface RouteOverlayOptions {
formatDistance: (km: number) => string
}
/** How far, in map pixels, a point may sit off the line its neighbours make before it is kept. */
const SIMPLIFY_TOLERANCE = 0.35
/**
* A run projected onto the map and thinned for drawing. A routed road carries a point
* every few metres: at the scale of a trip map that is tens of thousands of points, most
* rounding onto the same pixel, each drawn twice (casing and line) and drawn again by
* every viewer on every scroll, which made the page stutter. Points that round onto the
* one before are dropped, then every point closer than SIMPLIFY_TOLERANCE to the line
* through the points kept around it (Douglas-Peucker). The shape on paper is the same.
*/
export function drawnPoints(line: [number, number][], project: (lat: number, lng: number) => [number, number]): string {
const round = (n: number) => Math.round(n * 10) / 10
const pts: [number, number][] = []
for (const [lat, lng] of line) {
const [x, y] = project(lat, lng)
const point: [number, number] = [round(x), round(y)]
const prev = pts[pts.length - 1]
if (!prev || prev[0] !== point[0] || prev[1] !== point[1]) pts.push(point)
}
const keep = new Uint8Array(pts.length)
keep[0] = 1
keep[pts.length - 1] = 1
const ranges: [number, number][] = [[0, pts.length - 1]]
for (let range = ranges.pop(); range; range = ranges.pop()) {
const [from, to] = range
if (to - from < 2) continue
const [ax, ay] = pts[from]
const [bx, by] = pts[to]
const dx = bx - ax
const dy = by - ay
const length = Math.hypot(dx, dy)
let farthest = -1
let distance = 0
for (let i = from + 1; i < to; i++) {
const [px, py] = pts[i]
const d = length === 0 ? Math.hypot(px - ax, py - ay) : Math.abs(dy * px - dx * py + bx * ay - by * ax) / length
if (d > distance) {
distance = d
farthest = i
}
}
if (farthest < 0 || distance <= SIMPLIFY_TOLERANCE) continue
keep[farthest] = 1
ranges.push([from, farthest], [farthest, to])
}
return pts.filter((_, i) => keep[i]).map(p => p.join(',')).join(' ')
}
/**
* The routes, their stops and the scale bar — everything drawn *over* the ground.
*
@@ -187,7 +138,7 @@ export function buildRouteOverlay(days: TripOverviewDay[], opts: RouteOverlayOpt
const drawn = days.filter(d => [...d.lines, ...(d.tourLines ?? [])].some(line => line.length > 1))
const routes = drawn.flatMap(day => day.lines.filter(l => l.length > 1).map(line => {
const pts = drawnPoints(line, project)
const pts = line.map(([lat, lng]) => project(lat, lng).map(round).join(',')).join(' ')
// The day's own darkened casing rather than a flat white one: it is what keeps a
// warm colour readable over water and forest, and it matches what the map draws.
return `<polyline points="${pts}" fill="none" stroke="${strokeColour(day.color.casing)}" stroke-width="5.5" stroke-linecap="round" stroke-linejoin="round"/>`
@@ -196,7 +147,7 @@ export function buildRouteOverlay(days: TripOverviewDay[], opts: RouteOverlayOpt
// Where each run starts and ends — the stops, rather than every vertex of the road.
const tours = drawn.flatMap(day => (day.tourLines ?? []).filter(line => line.length > 1).map(line => {
const pts = drawnPoints(line, project)
const pts = line.map(([lat, lng]) => project(lat, lng).map(round).join(',')).join(' ')
return `<polyline points="${pts}" fill="none" stroke="#ffffff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>`
+ `<polyline points="${pts}" fill="none" stroke="#14805e" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/>`
}))
@@ -1,264 +0,0 @@
/**
* FE-PDFDAY-001 to FE-PDFDAY-012: one day of the trip PDF, built piece by piece.
* The whole export is covered by TripPDF.test.ts; these pin what each card prints
* from the data it is given, the trip's full place included.
*/
import { describe, expect, it } from 'vitest';
import type { Accommodation, Assignment, Category, Day, DayNote, Place } from '../../types';
import { dayHeader, noteItem, photoStrip, placeItem, staysBlock, type PdfDayContext } from './tripPdfDay';
const day = { id: 10, day_number: 3, title: 'Kyoto', date: '2026-05-06' } as Day; // a Wednesday
const category = { id: 4, name: 'Temple', icon: 'landmark', color: '#c2410c' } as Category;
/** Monday first, like the stored week; Wednesday has hours, Thursday is closed. */
const week = JSON.stringify([
{ closed: false, open: '08:00', close: '18:00' },
{ closed: false, open: '08:00', close: '18:00' },
{ closed: false, open: '09:00', close: '17:30' },
{ closed: true },
{ closed: false, open: '08:00', close: '18:00' },
{ closed: false, open: '08:00', close: '18:00' },
{ closed: false, open: '08:00', close: '18:00' },
]);
const fullPlace = {
id: 7,
name: 'Kiyomizu-dera',
category_id: 4,
address: '1 Chome-294 Kiyomizu, Kyoto',
lat: 34.994856,
lng: 135.785046,
rating_avg: 4.64,
rating_count: 12,
email: 'info@kiyomizudera.or.jp',
phone: '+81 75-551-1234',
website: 'https://www.kiyomizudera.or.jp/en/',
opening_hours: week,
reservation_notes: 'Tickets at the west gate',
tags: [{ name: 'Must see', color: '#16a34a' }],
} as unknown as Place;
function context(over: Partial<PdfDayContext> = {}): PdfDayContext {
return {
tr: (key, params) => (params ? `${key}:${JSON.stringify(params)}` : key),
fmtTime: (value) => value ?? '',
locale: 'en-US',
tripCurrency: 'JPY',
categories: [category],
placesById: new Map([[fullPlace.id, fullPlace]]),
photoOf: () => null,
markdown: (text) => `<p>${text}</p>`,
...over,
};
}
/** The assignment as the API hands it over: a projection of its place, without the rating, e-mail or hours. */
function assignment(over: Record<string, unknown> = {}): Assignment {
return {
id: 200,
day_id: 10,
order_index: 0,
notes: 'Go early',
participants: [
{ user_id: 1, username: 'mia' },
{ user_id: 2, username: 'leo' },
],
place: {
id: 7,
name: 'Kiyomizu-dera',
category_id: 4,
address: '1 Chome-294 Kiyomizu, Kyoto',
lat: 34.994856,
lng: 135.785046,
place_time: '09:30',
end_time: '11:00',
duration_minutes: 90,
price: 500,
currency: null,
description: 'Wooden **stage** over the hill',
notes: null,
tags: [{ name: 'Must see', color: '#16a34a' }],
...over,
},
} as unknown as Assignment;
}
const parse = (html: string) => new DOMParser().parseFromString(html, 'text/html');
const texts = (doc: Document, selector: string) =>
[...doc.querySelectorAll(selector)].map((el) => el.textContent?.replace(/\s+/g, ' ').trim());
describe('placeItem', () => {
it('FE-PDFDAY-001: prints the stop with its number, times, facts, address and coordinates', () => {
const doc = parse(placeItem(assignment(), 2, day, context()));
expect(texts(doc, '.tl-marker')).toEqual(['2']);
expect(texts(doc, '.tl-start')).toEqual(['09:30']);
expect(texts(doc, '.tl-end')).toEqual(['11:00']);
expect(texts(doc, '.place-name')).toEqual(['Kiyomizu-dera']);
expect(texts(doc, '.cat-badge')).toEqual(['Temple']);
const facts = texts(doc, '.facts .chip');
expect(facts[0]).toBe('1 h 30 min');
expect(facts[1]).toMatch(/500/);
expect(facts.slice(2)).toEqual(['4.6 (12)', 'Must see']);
expect(texts(doc, '.info-row .info-text')).toEqual(['1 Chome-294 Kiyomizu, Kyoto', '34.99486, 135.78505']);
expect(doc.querySelector('.coords')).not.toBeNull();
});
it('FE-PDFDAY-002: reads the rating, e-mail, hours and reservation note off the trip place', () => {
const doc = parse(placeItem(assignment(), 1, day, context()));
// The day is a Wednesday: its hours, not Monday's.
expect(texts(doc, '.details .detail')).toEqual([
'inspector.openingHours 09:00 – 17:30',
'+81 75-551-1234',
'kiyomizudera.or.jp',
'info@kiyomizudera.or.jp',
'inspector.participants: mia, leo',
]);
expect(texts(doc, '.place-note')).toEqual(['Tickets at the west gate', 'Go early']);
expect(doc.querySelector('.place-text')?.innerHTML).toBe('<p>Wooden **stage** over the hill</p>');
});
it('FE-PDFDAY-003: a day the place is closed says so', () => {
const thursday = { ...day, date: '2026-05-07' } as Day;
const doc = parse(placeItem(assignment(), 1, thursday, context()));
expect(texts(doc, '.details .detail')[0]).toBe('inspector.openingHours inspector.closed');
});
it('FE-PDFDAY-004: a place with neither photo nor extras prints its category tile and nothing empty', () => {
const bare = {
id: 201,
day_id: 10,
order_index: 0,
place: { id: 99, name: 'Corner shop', category_id: 4, lat: null, lng: null },
} as unknown as Assignment;
const doc = parse(placeItem(bare, 1, { ...day, date: null } as Day, context()));
expect(doc.querySelector('.place-thumb-fallback')).not.toBeNull();
expect(doc.querySelector('.place-card')?.getAttribute('style')).toBe('--cat:#c2410c');
for (const empty of ['.facts', '.info-row', '.details', '.place-note', '.place-text', '.tl-start', '.tl-end']) {
expect(doc.querySelector(empty)).toBeNull();
}
});
it('FE-PDFDAY-005: the photo the export picked prints, and a hostile name and tag colour stay inert', () => {
const hostile = assignment({
name: '<img src=x onerror=alert(1)>',
tags: [{ name: 'x', color: 'red;background:url(x)' }],
});
const html = placeItem(hostile, 1, day, context({ photoOf: () => 'data:image/jpeg;base64,AAA' }));
const doc = parse(html);
expect(doc.querySelector('img.place-thumb')?.getAttribute('src')).toBe('data:image/jpeg;base64,AAA');
expect(doc.querySelectorAll('img')).toHaveLength(1);
expect(texts(doc, '.place-name')).toEqual(['<img src=x onerror=alert(1)>']);
expect(doc.querySelector('.chip-tag')?.getAttribute('style')).toBe('--tag:#6b6b75');
});
});
describe('noteItem', () => {
it('FE-PDFDAY-006: a coloured note carries its colour as the edge, an unknown colour none', () => {
const note = {
id: 1,
day_id: 10,
text: 'Buy <tickets>',
time: '08:00',
icon: 'Ticket',
color: '#2563eb',
} as DayNote;
const tinted = parse(noteItem(note));
expect(tinted.querySelector('.note-card')?.className).toBe('note-card note-tinted');
expect(tinted.querySelector('.note-card')?.getAttribute('style')).toBe('--note:#2563eb');
expect(texts(tinted, '.note-text')).toEqual(['Buy <tickets>']);
// The note's time field is its free second line, kept in the card, not a clock.
expect(texts(tinted, '.note-time')).toEqual(['08:00']);
expect(tinted.querySelector('.tl-start')).toBeNull();
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote));
expect(plain.querySelector('.note-card')?.className).toBe('note-card');
expect(plain.querySelector('.note-time')).toBeNull();
});
});
describe('staysBlock', () => {
const stay = {
id: 1,
start_day_id: 10,
end_day_id: 12,
place_name: 'Hotel Gion',
place_address: 'Gion 1',
check_in: '15:00',
check_out: '10:00',
confirmation: 'HX-42',
notes: 'Late arrival',
place_image: null,
} as unknown as Accommodation;
it('FE-PDFDAY-007: the arrival day gets the full card with time, address, notes and code', () => {
const doc = parse(staysBlock([stay], day, context()));
expect(doc.querySelector('.day-accommodations')?.className).toBe('day-accommodations single');
expect(texts(doc, '.stay-kicker')).toEqual(['reservations.meta.checkIn 15:00']);
expect(texts(doc, '.stay-name')).toEqual(['Hotel Gion']);
expect(texts(doc, '.stay-line')).toEqual(['Gion 1', 'Late arrival']);
expect(texts(doc, '.code-chip')).toEqual(['HX-42']);
});
it('FE-PDFDAY-008: a night in between is one quiet line, the leaving day the check-out', () => {
const middle = parse(staysBlock([stay], { ...day, id: 11 } as Day, context()));
expect(middle.querySelector('.stay-quiet')).not.toBeNull();
expect(texts(middle, '.stay-kicker')).toEqual(['reservations.meta.linkAccommodation']);
expect(middle.querySelector('.stay-line')).toBeNull();
const leaving = parse(staysBlock([stay], { ...day, id: 12 } as Day, context()));
expect(texts(leaving, '.stay-kicker')).toEqual(['reservations.meta.checkOut 10:00']);
expect(leaving.querySelector('.code-chip')).toBeNull();
});
it('FE-PDFDAY-009: no stay prints nothing, two drop the single-column class', () => {
expect(staysBlock([], day, context())).toBe('');
const doc = parse(staysBlock([stay, { ...stay, id: 2, place_name: 'Ryokan' } as Accommodation], day, context()));
expect(doc.querySelector('.day-accommodations')?.className).toBe('day-accommodations');
});
});
describe('dayHeader', () => {
it('FE-PDFDAY-010: the number, date and title, with only the figures the day has', () => {
const doc = parse(dayHeader(day, { stops: 4, distance: '12 km', cost: '¥3,000' }, context()));
expect(texts(doc, '.day-tag-lbl')).toEqual(['pdf.day']);
expect(texts(doc, '.day-tag-num')).toEqual(['3']);
expect(texts(doc, '.day-date')[0]).toMatch(/May/);
expect(texts(doc, '.day-title')).toEqual(['Kyoto']);
expect(texts(doc, '.meta-pill, .day-cost')).toEqual(['4', '12 km', '¥3,000']);
const untitled = parse(
dayHeader({ ...day, title: null, date: null } as Day, { stops: 0, distance: null, cost: null }, context())
);
expect(texts(untitled, '.day-title')).toEqual(['dayplan.dayN:{"n":3}']);
expect(untitled.querySelector('.day-date')).toBeNull();
expect(untitled.querySelector('.day-meta')).toBeNull();
});
});
describe('photoStrip', () => {
it('FE-PDFDAY-011: up to three photos, each named on its label; none prints nothing', () => {
expect(photoStrip([])).toBe('');
const doc = parse(
photoStrip([
{ url: 'https://a.example/1.jpg', caption: 'Gate <one>' },
{ url: 'https://a.example/2.jpg', caption: 'Stage' },
])
);
expect(doc.querySelector('.day-strip')?.className).toBe('day-strip day-strip-2');
expect(texts(doc, '.glass-label')).toEqual(['Gate <one>', 'Stage']);
expect([...doc.querySelectorAll('img')].map((img) => img.getAttribute('src'))).toEqual([
'https://a.example/1.jpg',
'https://a.example/2.jpg',
]);
});
});
-434
View File
@@ -1,434 +0,0 @@
import { parsePlaceHours } from '@trek/shared';
import type { Accommodation, Assignment, Category, Day, DayNote, Place, Reservation } from '../../types';
import { getDisplayTimeForDay, getSpanPhase } from '../../utils/dayMerge';
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../utils/flightLegs';
import { formatMoney, splitReservationDateTime } from '../../utils/formatters';
import type { TransportLegDetail } from '../Planner/transportDetailModel';
import { escHtml, hexColour, safeImg, shortDate, websiteHost } from './tripPdfHtml';
import { bookingIcon, bookingTint, categoryIcon, glyph, noteIcon } from './tripPdfIcons';
/*
* One day of the trip PDF: its header, where the night is spent, and the day's plan
* as a timeline, times on the left, a rail in the day's colour, and a card for every
* stop, booking and note.
*/
type Translate = (key: string, params?: Record<string, string | number>) => string;
/** A booking as the day merge hands it over, a leg of a multi-leg booking included. */
export type PdfBooking = Reservation & { __leg?: TransportLegDetail & { total?: number } };
/** What the day's markup needs from the export around it. */
export interface PdfDayContext {
tr: Translate;
fmtTime: (value?: string | null) => string;
locale: string | undefined;
tripCurrency: string;
categories: readonly Category[];
/** The trip's full places by id: an assignment carries only a projection of its place. */
placesById: ReadonlyMap<number, Place>;
/** The picture to print for a place, already shrunk where it could be; null for none. */
photoOf: (place: Assignment['place']) => string | null;
/** A place's description or notes as sanitized markdown. */
markdown: (text: string) => string;
}
const NEUTRAL = '#6b6b75';
function metadataOf(r: PdfBooking): Record<string, unknown> {
if (!r.metadata) return {};
try {
const parsed: unknown = typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata;
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};
} catch {
return {};
}
}
const text = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' ? String(value) : '');
/** "1 h 30 min", or null for no duration at all. */
function durationLabel(minutes: number | null | undefined): string | null {
if (typeof minutes !== 'number' || !Number.isFinite(minutes) || minutes <= 0) return null;
const whole = Math.round(minutes);
const h = Math.floor(whole / 60);
const m = whole % 60;
if (h === 0) return `${m} min`;
return m === 0 ? `${h} h` : `${h} h ${m} min`;
}
function timeColumn(start: string, end: string): string {
return `<div class="tl-time">${start ? `<span class="tl-start">${escHtml(start)}</span>` : ''}${
end ? `<span class="tl-end">${escHtml(end)}</span>` : ''
}</div>`;
}
function item(kind: string, time: string, marker: string, body: string, style = ''): string {
return `<li class="tl-item tl-${kind}"${style ? ` style="${style}"` : ''}>${time}<div class="tl-rail"><span class="tl-marker">${marker}</span></div><div class="tl-body">${body}</div></li>`;
}
// ── Bookings ──────────────────────────────────────────────────────────────
/** "Departure", "Pick-up" and the like, for a booking that spans days; null on its single day. */
function spanLabel(r: PdfBooking, phase: string, tr: Translate): string | null {
if (phase === 'single') return null;
// Each key spelled out, so the key check can follow every branch to its string.
const start = phase === 'start';
const end = phase === 'end';
if (r.type === 'flight') return tr(`reservations.span.${start ? 'departure' : end ? 'arrival' : 'inTransit'}`);
if (r.type === 'car') return tr(`reservations.span.${start ? 'pickup' : end ? 'return' : 'active'}`);
// Parking reuses span.pickup for its end day: you drop the car off and collect it
// again later, so the rental car's wording carries over without a second key.
if (r.type === 'parking') return tr(`reservations.span.${start ? 'dropOff' : end ? 'pickup' : 'ongoing'}`);
return tr(`reservations.span.${start ? 'start' : end ? 'end' : 'ongoing'}`);
}
function stopsOf(r: PdfBooking, label: 'code' | 'name'): string[] {
return (r.endpoints || [])
.slice()
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
.map((e) => (label === 'code' ? e.code || e.name : e.name) || '')
.filter(Boolean);
}
/** One line under a booking's title: the way it goes, its facts as badges and its own booking code. */
interface BookingLine {
route: string;
facts: string[];
code: string;
/** A table's party size, printed with the people icon so it needs no word. */
people?: string;
}
/**
* The lines under a booking's title. A multi-leg flight or train gets one per leg, each
* with its own number and booking code, since that is the code the gate asks for
* (#1943); a leg row prints its own leg; everything else gets one line or none.
*/
function bookingLines(r: PdfBooking, tr: Translate): BookingLine[] {
const meta = metadataOf(r);
const route = (from?: string | null, to?: string | null) =>
from || to ? [from, to].filter(Boolean).join(' → ') : '';
const seat = (value: unknown) => (text(value) ? `${tr('reservations.meta.seat')} ${text(value)}` : '');
const platform = (value: unknown) => (text(value) ? `${tr('reservations.meta.platform')} ${text(value)}` : '');
const line = (way: string, facts: unknown[], code: unknown = ''): BookingLine => ({
route: way,
facts: facts.map(text).filter(Boolean),
code: text(code),
});
const filled = (lines: BookingLine[]) => lines.filter((l) => l.route || l.facts.length || l.code);
if (r.__leg) {
const l = r.__leg;
const source = (usesStationRoute(r.type) ? getTrainLegs(r) : getFlightLegs(r))[l.index];
return filled([
line(
route(l.from, l.to),
[l.airline, l.flight_number, l.train_number, platform(l.platform), seat(l.seat)],
source?.confirmation_number
),
]);
}
if (r.type === 'flight') {
const legs = getFlightLegs(r);
if (legs.length > 1) {
return filled(
legs.map((l) => line(route(l.from, l.to), [l.airline, l.flight_number, seat(l.seat)], l.confirmation_number))
);
}
const stops = stopsOf(r, 'code');
const way = stops.length >= 2 ? stops.join(' → ') : route(text(meta.departure_airport), text(meta.arrival_airport));
return filled([line(way, [meta.airline, meta.flight_number, seat(meta.seat)])]);
}
if (r.type === 'train') {
const legs = getTrainLegs(r);
if (legs.length > 1) {
return filled(
legs.map((l) =>
line(route(l.from, l.to), [l.train_number, platform(l.platform), seat(l.seat)], l.confirmation_number)
)
);
}
const stops = stopsOf(r, 'code');
return filled([
line(stops.length >= 2 ? stops.join(' → ') : '', [meta.train_number, platform(meta.platform), seat(meta.seat)]),
]);
}
if (r.type === 'car') {
// A rental with stops is a drive, and the printout is what people take into the car
// (#1797). Consecutive repeats collapse, and a chain of one place is no route: the
// ordinary rental is picked up and returned at the same desk.
const stops = stopsOf(r, 'name').filter((name, i, all) => name !== all[i - 1]);
return new Set(stops).size >= 2 ? [line(stops.join(' → '), [])] : [];
}
if (r.type === 'restaurant') return text(meta.party_size) ? [{ ...line('', []), people: text(meta.party_size) }] : [];
if (r.type === 'event') return filled([line('', [meta.venue])]);
if (r.type === 'tour') return filled([line('', [meta.operator])]);
return [];
}
function bookingLineHtml(l: BookingLine): string {
return `<div class="note-line">${l.route ? `<span class="route">${escHtml(l.route)}</span>` : ''}${
l.people ? `<span class="chip">${glyph('people', 9)}${escHtml(l.people)}</span>` : ''
}${l.facts
.map((fact) => `<span class="chip">${escHtml(fact)}</span>`)
.join('')}${l.code ? `<span class="code-chip">${glyph('key', 9)}${escHtml(l.code)}</span>` : ''}</div>`;
}
/** A booking's lines on their own, for the booking list of the overview. */
export function bookingLinesHtml(r: PdfBooking, tr: Translate): string {
return bookingLines(r, tr).map(bookingLineHtml).join('');
}
/** A booking on the day's timeline. Sets `flags.transportNote` when it prints a note. */
export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags: { transportNote: boolean }): string {
const { tr, fmtTime } = ctx;
const phase = getSpanPhase(r, day.id);
const span = spanLabel(r, phase, tr);
// Start and end the way the day plan draws them (#1310). The landing time only on a
// booking that begins and ends this day: across a span the arrival belongs to the
// arrival day, which shows it as its own time.
const start = fmtTime(splitReservationDateTime(getDisplayTimeForDay(r, day.id)).time);
const end = phase === 'single' ? fmtTime(splitReservationDateTime(r.reservation_end_time).time) : '';
const note = typeof r.notes === 'string' ? r.notes.trim() : '';
if (note) flags.transportNote = true;
const meta = metadataOf(r);
const location = r.location || text(meta.location);
const status =
r.status === 'confirmed' ? tr('reservations.confirmed') : r.status === 'pending' ? tr('reservations.pending') : '';
const tint = hexColour(bookingTint(r.type), NEUTRAL);
const extras = [
r.confirmation_number
? `<span class="code-chip note-code">${glyph('key', 9)}${escHtml(r.confirmation_number)}</span>`
: '',
status ? `<span class="chip">${escHtml(status)}</span>` : '',
].filter(Boolean);
const card = `<div class="note-card booking-card">
<span class="note-icon">${bookingIcon(r.type)}</span>
<div class="note-body">
${span ? `<div class="note-kicker">${escHtml(span)}</div>` : ''}
<div class="note-text">${escHtml(r.title)}</div>
${bookingLines(r, tr).map(bookingLineHtml).join('')}
${location ? `<div class="note-time">${escHtml(location)}</div>` : ''}
${extras.length ? `<div class="note-extra">${extras.join('')}</div>` : ''}
${note ? `<div class="note-time transport-note">${escHtml(note)}</div>` : ''}
</div>
</div>`;
return item('booking', timeColumn(start, end), bookingIcon(r.type, 11), card, `--kind:${tint}`);
}
// ── Notes ─────────────────────────────────────────────────────────────────
/**
* A day note. A coloured note carries its colour as the rule along its edge and its
* icon (#1629), not as a fill: a tint costs ink and reads as grey on a mono printer.
*/
export function noteItem(note: DayNote): string {
const colour = note.color ? hexColour(note.color, '') : '';
// A note's `time` is the free line the day plan prints under its text, not a clock,
// so it stays in the card and the time column stays empty.
const subtitle = typeof note.time === 'string' ? note.time.trim() : '';
const card = `<div class="note-card${colour ? ' note-tinted' : ''}"${colour ? ` style="--note:${colour}"` : ''}>
<span class="note-icon">${noteIcon(note.icon)}</span>
<div class="note-body"><div class="note-text">${escHtml(note.text)}</div>${
subtitle ? `<div class="note-time">${escHtml(subtitle)}</div>` : ''
}</div>
</div>`;
return item('note', timeColumn('', ''), '', card);
}
// ── Places ────────────────────────────────────────────────────────────────
/** The day's opening hours of a place, Monday first like the stored week; null when unknown. */
function hoursOnDay(place: Partial<Place>, day: Day, ctx: PdfDayContext): string | null {
const week = parsePlaceHours(place.opening_hours);
if (!week || !day.date) return null;
const weekday = (new Date(day.date + 'T00:00:00Z').getUTCDay() + 6) % 7;
const hours = week[weekday];
if (!hours) return null;
if (hours.closed) return ctx.tr('inspector.closed');
if (!hours.open && !hours.close) return null;
return [ctx.fmtTime(hours.open), ctx.fmtTime(hours.close)].filter(Boolean).join(' – ');
}
function placeFacts(place: Assignment['place'] & Partial<Place>, ctx: PdfDayContext): string[] {
const facts: string[] = [];
const duration = durationLabel(place.duration_minutes);
if (duration) facts.push(`<span class="chip">${glyph('duration', 9)}${escHtml(duration)}</span>`);
const price = Number(place.price);
if (Number.isFinite(price) && price > 0) {
facts.push(
`<span class="chip chip-green">${glyph('price', 9)}${escHtml(formatMoney(price, place.currency || ctx.tripCurrency, ctx.locale || 'en'))}</span>`
);
}
if (typeof place.rating_avg === 'number' && place.rating_avg > 0) {
const count = place.rating_count ? ` (${place.rating_count})` : '';
facts.push(`<span class="chip chip-rating">${glyph('star', 9)}${place.rating_avg.toFixed(1)}${count}</span>`);
}
for (const tag of place.tags || []) {
if (!tag.name) continue;
facts.push(
`<span class="chip chip-tag" style="--tag:${hexColour(tag.color, NEUTRAL)}">${escHtml(tag.name)}</span>`
);
}
return facts;
}
function placeDetails(
place: Assignment['place'] & Partial<Place>,
assignment: Assignment,
day: Day,
ctx: PdfDayContext
): string[] {
const details: string[] = [];
const hours = hoursOnDay(place, day, ctx);
if (hours)
details.push(
`<span class="detail">${glyph('hours', 9)}${escHtml(ctx.tr('inspector.openingHours'))} ${escHtml(hours)}</span>`
);
if (place.phone) details.push(`<span class="detail">${glyph('phone', 9)}${escHtml(place.phone)}</span>`);
if (place.website)
details.push(`<span class="detail">${glyph('web', 9)}${escHtml(websiteHost(place.website))}</span>`);
if (place.email) details.push(`<span class="detail">${glyph('mail', 9)}${escHtml(place.email)}</span>`);
const people = (assignment.participants || []).map((p) => p.username).filter(Boolean);
if (people.length) {
details.push(
`<span class="detail">${glyph('people', 9)}${escHtml(ctx.tr('inspector.participants'))}: ${escHtml(people.join(', '))}</span>`
);
}
return details;
}
/** A planned place on the day's timeline, numbered like the stops on the map. */
export function placeItem(assignment: Assignment, number: number, day: Day, ctx: PdfDayContext): string {
// The assignment carries a projection of its place; the rating, the e-mail, the
// hours and the reservation note are only on the trip's own place.
const place: Assignment['place'] & Partial<Place> = {
...ctx.placesById.get(assignment.place.id),
...assignment.place,
};
const category = ctx.categories.find((c) => c.id === place.category_id);
const catColour = hexColour(category?.color, NEUTRAL);
const photo = ctx.photoOf(assignment.place);
const media = photo
? `<img class="place-thumb" src="${escHtml(photo)}" alt="" />`
: `<div class="place-thumb-fallback">${categoryIcon(category?.icon)}</div>`;
const facts = placeFacts(place, ctx);
const details = placeDetails(place, assignment, day, ctx);
const hasPosition = place.lat != null && place.lng != null;
const notes = [place.notes, place.reservation_notes, assignment.notes].filter(
(value): value is string => typeof value === 'string' && value.trim() !== ''
);
const card = `<div class="place-card" style="--cat:${catColour}">
${media}
<div class="place-info">
<div class="place-name-row">
<span class="place-name">${escHtml(place.name)}</span>
${category ? `<span class="cat-badge">${escHtml(category.name)}</span>` : ''}
</div>
${facts.length ? `<div class="facts">${facts.join('')}</div>` : ''}
${place.address ? `<div class="info-row">${glyph('pin')}<span class="info-text">${escHtml(place.address)}</span></div>` : ''}
${
hasPosition
? `<div class="info-row coords">${glyph('coords')}<span class="info-text muted">${Number(place.lat).toFixed(5)}, ${Number(place.lng).toFixed(5)}</span></div>`
: ''
}
${place.description ? `<div class="place-text">${ctx.markdown(place.description)}</div>` : ''}
${notes.map((note) => `<div class="place-note">${ctx.markdown(note)}</div>`).join('')}
${details.length ? `<div class="details">${details.join('')}</div>` : ''}
</div>
</div>`;
const start = ctx.fmtTime(place.place_time);
const end = ctx.fmtTime(place.end_time);
return item('place', timeColumn(start, end), String(number), card);
}
// ── Stays ─────────────────────────────────────────────────────────────────
/**
* Where the day's night is spent. The day of arrival and the day of leaving get the
* full card with the time, the address and the booking code; the nights in between a
* quiet line, since the same hotel on every page is the plan's least news.
*/
export function staysBlock(stays: readonly Accommodation[], day: Day, ctx: PdfDayContext): string {
if (!stays.length) return '';
const cards = stays.map((stay) => {
const isCheckIn = day.id === stay.start_day_id;
const isCheckOut = day.id === stay.end_day_id;
const name = stay.place_name || stay.reservation_title || '';
const photo = safeImg(stay.place_image);
const media = `<span class="stay-media">${photo ? `<img src="${escHtml(photo)}" alt="" />` : glyph(isCheckOut ? 'checkOut' : isCheckIn ? 'checkIn' : 'bed', 16)}</span>`;
if (!isCheckIn && !isCheckOut) {
return `<div class="day-accommodation stay-quiet">${media}<div class="stay-main">
<div class="stay-kicker">${escHtml(ctx.tr('reservations.meta.linkAccommodation'))}</div>
<div class="stay-name">${escHtml(name)}</div>
</div></div>`;
}
const label = ctx.tr(isCheckIn ? 'reservations.meta.checkIn' : 'reservations.meta.checkOut');
const time = ctx.fmtTime(isCheckIn ? stay.check_in : stay.check_out);
const extras = [
isCheckIn && stay.confirmation
? `<span class="code-chip">${glyph('key', 9)}${escHtml(stay.confirmation)}</span>`
: '',
].filter(Boolean);
return `<div class="day-accommodation">${media}<div class="stay-main">
<div class="stay-kicker">${escHtml(label)}${time ? ` <span class="num">${escHtml(time)}</span>` : ''}</div>
<div class="stay-name">${escHtml(name)}</div>
${stay.place_address ? `<div class="stay-line">${escHtml(stay.place_address)}</div>` : ''}
${stay.notes ? `<div class="stay-line">${escHtml(stay.notes)}</div>` : ''}
${extras.length ? `<div class="stay-extra">${extras.join('')}</div>` : ''}
</div></div>`;
});
return `<div class="day-accommodations${stays.length === 1 ? ' single' : ''}">${cards.join('')}</div>`;
}
// ── Header ────────────────────────────────────────────────────────────────
interface DayHeaderFacts {
stops: number;
distance: string | null;
cost: string | null;
}
/** The day's header: its number in the day's colour, the date, the title and its figures. */
export function dayHeader(day: Day, facts: DayHeaderFacts, ctx: PdfDayContext): string {
const n = day.day_number ?? 0;
const pills = [
facts.stops > 0 ? `<span class="meta-pill">${glyph('pin', 9)}${facts.stops}</span>` : '',
facts.distance ? `<span class="meta-pill">${glyph('route', 9)}${escHtml(facts.distance)}</span>` : '',
facts.cost ? `<span class="day-cost">${glyph('price', 9)}${facts.cost}</span>` : '',
].filter(Boolean);
return `<div class="day-head">
<span class="day-tag"><span class="day-tag-lbl">${escHtml(ctx.tr('pdf.day'))}</span><span class="day-tag-num">${n}</span></span>
<div class="day-head-main">
${day.date ? `<div class="day-date">${escHtml(shortDate(day.date, ctx.locale))}</div>` : ''}
<div class="day-title">${escHtml(day.title || ctx.tr('dayplan.dayN', { n }))}</div>
</div>
${pills.length ? `<div class="day-meta">${pills.join('')}</div>` : ''}
</div>`;
}
// ── Photo strip ───────────────────────────────────────────────────────────
interface StripPhoto {
url: string;
caption: string;
}
/**
* The strip that opens a day: up to three of its photographed stops side by side, the
* first one widest, each named on a frosted label. Nothing for a day without photos.
*/
export function photoStrip(photos: readonly StripPhoto[]): string {
if (!photos.length) return '';
return `<div class="day-strip day-strip-${photos.length}">${photos
.map(
(p) =>
`<figure class="day-strip-photo"><img src="${escHtml(p.url)}" alt="" /><figcaption class="glass-label">${escHtml(p.caption)}</figcaption></figure>`
)
.join('')}</div>`;
}
-82
View File
@@ -1,82 +0,0 @@
/*
* The small text and URL helpers every part of the trip PDF builds its markup with.
* The document is an HTML string assembled outside React, so every value that comes
* from the trip goes through escHtml before it lands in it.
*/
/** Text for element content or a double-quoted attribute. */
export function escHtml(value: unknown): string {
if (value === null || value === undefined || value === '') return '';
return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
/**
* The style attribute is decoded back into raw quotes before the CSS is parsed, so
* escHtml alone cannot stop a cover_image from closing the url() and appending its own
* declaration. Percent-encoding is transparent to the fetch.
*/
export function cssUrl(url: string): string {
return url.replace(/["'()\\\s]/g, (c) => '%' + (c.codePointAt(0) ?? 0).toString(16).padStart(2, '0'));
}
/**
* A colour that goes into a style attribute built by string concatenation. Anything
* that is not a plain hex triple is not a colour and gets the fallback instead of a
* chance to close the declaration.
*/
export function hexColour(value: unknown, fallback: string): string {
return /^#[0-9a-f]{6}$/i.test(String(value)) ? String(value) : fallback;
}
/** A path on this server as an absolute URL, so the print frame can load it. */
export function absUrl(url: string | null | undefined): string | null {
if (!url) return null;
if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) return url;
return window.location.origin + (url.startsWith('/') ? '' : '/') + url;
}
/**
* A picture the document may load: any web URL, the in-app place-photo proxy (it
* streams a JPEG under a path without an extension) and uploaded files with an image
* extension. Anything else prints as the fallback tile.
*/
export function safeImg(url: string | null | undefined): string | null {
if (!url) return null;
if (url.startsWith('https://') || url.startsWith('http://')) return url;
if (url.startsWith('/api/maps/place-photo/')) return absUrl(url);
return /\.(jpe?g|png|gif|webp|bmp|tiff?)(\?.*)?$/i.test(url) ? absUrl(url) : null;
}
/** "Mon, 5 May" in the reader's language; empty for a day without a date. */
export function shortDate(date: string | null | undefined, locale: string | undefined): string {
if (!date) return '';
return new Date(date + 'T00:00:00Z').toLocaleDateString(locale, {
weekday: 'short',
day: 'numeric',
month: 'short',
timeZone: 'UTC',
});
}
/** "3 May – 24 May 2026" over the dated days, or null when none has a date. */
export function longDateRange(
days: readonly { date?: string | null; day_number?: number }[],
locale: string | undefined
): string | null {
const dated = days.filter((d) => d.date).sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0));
if (!dated.length) return null;
const first = new Date(dated[0].date + 'T00:00:00Z');
const last = new Date(dated[dated.length - 1].date + 'T00:00:00Z');
const from = first.toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' });
const to = last.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' });
return `${from} – ${to}`;
}
/** The host of a website, which is what fits on a printed line. */
export function websiteHost(url: string): string {
try {
return new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`).host.replace(/^www\./, '');
} catch {
return url;
}
}
-165
View File
@@ -1,165 +0,0 @@
import { createElement } from 'react';
import { renderIconMarkup } from '../../utils/iconMarkup';
import { getCategoryIcon } from '../shared/categoryIcons';
import {
AlertTriangle,
BedDouble,
Bike,
Bookmark,
Bus,
CableCar,
Camera,
Car,
CarTaxiFront,
Clock,
Coffee,
Crosshair,
FileText,
Flag,
Globe,
Heart,
Hourglass,
Info,
KeyRound,
Lightbulb,
LogIn,
LogOut,
Mail,
MapPin,
Navigation,
ParkingSquare,
Phone,
Plane,
Route,
Sailboat,
Ship,
ShoppingBag,
Star,
StickyNote,
Store,
Tag,
Ticket,
Train,
Users,
Utensils,
Wallet,
type LucideIcon,
} from 'lucide-react';
/*
* Every icon of the trip PDF as SVG markup. They draw in currentColor, so the
* stylesheet decides their colour, which keeps the palette in one place.
*/
function iconSvg(Icon: LucideIcon, size: number, strokeWidth = 1.9): string {
return renderIconMarkup(createElement(Icon, { size, strokeWidth, color: 'currentColor', 'aria-hidden': 'true' }));
}
/** The small glyphs of the facts, contact lines and stay rows. */
const GLYPHS = {
pin: MapPin,
coords: Crosshair,
clock: Clock,
duration: Hourglass,
price: Wallet,
star: Star,
phone: Phone,
web: Globe,
mail: Mail,
hours: Store,
people: Users,
note: StickyNote,
tag: Tag,
route: Route,
bed: BedDouble,
checkIn: LogIn,
checkOut: LogOut,
key: KeyRound,
} satisfies Record<string, LucideIcon>;
type PdfGlyph = keyof typeof GLYPHS;
export function glyph(name: PdfGlyph, size = 10): string {
return iconSvg(GLYPHS[name], size);
}
const NOTE_ICONS: Record<string, LucideIcon> = {
FileText,
Info,
Clock,
MapPin,
Navigation,
Train,
Plane,
Bus,
Car,
Ship,
Coffee,
Ticket,
Star,
Heart,
Camera,
Flag,
Lightbulb,
AlertTriangle,
ShoppingBag,
Bookmark,
};
/** A day note's own icon, the note icon for one that names none. */
export function noteIcon(iconId: string | null | undefined, size = 13): string {
return iconSvg((iconId && NOTE_ICONS[iconId]) || FileText, size);
}
const BOOKING_ICONS: Record<string, LucideIcon> = {
flight: Plane,
train: Train,
bus: Bus,
car: Car,
taxi: CarTaxiFront,
bicycle: Bike,
cruise: Ship,
ferry: Sailboat,
cable_car: CableCar,
transport_other: Route,
restaurant: Utensils,
event: Ticket,
tour: Users,
parking: ParkingSquare,
other: FileText,
};
/** A booking's type icon; a type the export does not know gets the ticket. */
export function bookingIcon(type: string | null | undefined, size = 14): string {
return iconSvg((type && BOOKING_ICONS[type]) || Ticket, size);
}
/** The tint of each booking type, the same hues the day plan gives them. */
const BOOKING_TINTS: Record<string, string> = {
flight: '#3b82f6',
train: '#0891b2',
bus: '#059669',
car: '#64748b',
taxi: '#ca8a04',
bicycle: '#65a30d',
cruise: '#0284c7',
ferry: '#0d9488',
cable_car: '#dc2626',
transport_other: '#64748b',
restaurant: '#e11d48',
event: '#d97706',
tour: '#059669',
parking: '#2563eb',
other: '#64748b',
};
export function bookingTint(type: string | null | undefined): string {
return (type && BOOKING_TINTS[type]) || BOOKING_TINTS.flight;
}
/** A category's icon for the tile a place without a photo prints. */
export function categoryIcon(iconName: string | null | undefined, size = 22): string {
return iconSvg(getCategoryIcon(iconName), size, 1.7);
}
@@ -1,196 +0,0 @@
/**
* FE-PDFOVERVIEW-001 to FE-PDFOVERVIEW-005: the trip PDF's cover and overview pages,
* built from the figures the export hands them.
*/
import { describe, expect, it } from 'vitest';
import { coverHtml, coverRouteSvg, glanceHtml, ledgerHtml, type GlanceRow, type LedgerRow } from './tripPdfOverview';
const tr = (key: string) => key;
const parse = (html: string) => new DOMParser().parseFromString(html, 'text/html');
const texts = (doc: Document, selector: string) =>
[...doc.querySelectorAll(selector)].map((el) => el.textContent?.replace(/\s+/g, ' ').trim());
describe('coverHtml', () => {
const base = {
title: 'Autumn <in> Japan',
description: 'Temples and trains',
range: '1 November – 22 November 2026',
logo: 'https://trek.example/logo-light.svg',
stats: [
{ value: '22', label: 'days' },
{ value: '1,234 km', label: 'pdf.distanceLabel' },
],
route: [],
ribbon: [],
ribbonEnds: null,
tr,
};
it('FE-PDFOVERVIEW-001: the photo, the escaped title, the dates and a tile per figure', () => {
const doc = parse(coverHtml({ ...base, image: 'https://cdn.example/cover.jpg' }));
expect(doc.querySelector('section')?.className).toBe('cover');
expect(doc.querySelector('.cover-bg')?.getAttribute('style')).toBe(
"background-image:url('https://cdn.example/cover.jpg')"
);
expect(texts(doc, '.cover-title')).toEqual(['Autumn <in> Japan']);
expect(texts(doc, '.cover-dates')).toEqual(['1 November – 22 November 2026']);
expect(texts(doc, '.cover-desc')).toEqual(['Temples and trains']);
expect(texts(doc, '.cover-stat-num')).toEqual(['22', '1,234 km']);
expect(texts(doc, '.cover-top .eyebrow')).toEqual(['pdf.travelPlan']);
});
it('FE-PDFOVERVIEW-002: without a photo the cover is plain, and a hostile url cannot leave url()', () => {
const plain = parse(coverHtml({ ...base, image: null, description: null, range: null }));
expect(plain.querySelector('section')?.className).toBe('cover cover-plain');
expect(plain.querySelector('.cover-bg')?.hasAttribute('style')).toBe(false);
expect(plain.querySelector('.cover-desc')).toBeNull();
expect(plain.querySelector('.cover-dates')).toBeNull();
const hostile = parse(coverHtml({ ...base, image: "https://a/x.jpg');background:url('https://b/leak.jpg" }));
const style = hostile.querySelector('.cover-bg')?.getAttribute('style') ?? '';
expect(style.match(/url\(/g)).toHaveLength(1);
expect(style).not.toContain("');");
});
});
describe('the cover route and day band', () => {
const base = { title: 'Japan', description: null, range: null, image: null, logo: null, stats: [], tr };
it('FE-PDFOVERVIEW-006: the route is drawn day by day in its colours, the band has a segment per day', () => {
const doc = parse(
coverHtml({
...base,
route: [
{
colour: '#ff0000',
lines: [
[
[35.68, 139.76],
[35.0, 135.77],
],
],
},
{
colour: '#00ff00',
lines: [
[
[35.0, 135.77],
[34.69, 135.5],
],
],
},
],
ribbon: ['#ff0000', '#00ff00', '#0000ff'],
ribbonEnds: ['Sun, Nov 1', 'Tue, Nov 3'],
})
);
const coloured = [...doc.querySelectorAll('.cover-route-svg path[stroke]')].map((p) => p.getAttribute('stroke'));
expect(coloured).toEqual(['#ff0000', '#00ff00']);
expect(doc.querySelectorAll('.cover-route-glow path')).toHaveLength(2);
expect(texts(doc, '.cover-route-lbl')).toEqual(['pdf.mapTitle']);
expect(doc.querySelectorAll('.cover-ribbon span')).toHaveLength(3);
expect(texts(doc, '.cover-ribbon-ends span')).toEqual(['Sun, Nov 1', 'Tue, Nov 3']);
// Every point lands inside the drawing.
const numbers = [...doc.querySelectorAll('.cover-route-svg path[stroke]')].flatMap((p) =>
(p.getAttribute('d') ?? '').split(/[ML ]/).filter(Boolean).map(Number)
);
for (const n of numbers) expect(n).toBeGreaterThanOrEqual(0);
for (const n of numbers) expect(n).toBeLessThanOrEqual(240);
});
it('FE-PDFOVERVIEW-007: nothing routed, one point or one spot draws no card, one day no band', () => {
expect(coverRouteSvg([])).toBe('');
expect(coverRouteSvg([{ colour: '#ff0000', lines: [[[1, 1]]] }])).toBe('');
expect(
coverRouteSvg([
{
colour: '#ff0000',
lines: [
[
[1, 1],
[1, 1],
],
],
},
])
).toBe('');
const doc = parse(coverHtml({ ...base, route: [], ribbon: ['#ff0000'], ribbonEnds: null }));
expect(doc.querySelector('.cover-route')).toBeNull();
expect(doc.querySelector('.cover-ribbon')).toBeNull();
});
it('FE-PDFOVERVIEW-008: a long road is thinned to a drawable number of points', () => {
const road = Array.from({ length: 20000 }, (_, i) => [45 + i / 20000, 7 + i / 10000] as [number, number]);
const svg = coverRouteSvg([{ colour: '#ff0000', lines: [road] }]);
const d = /<path d="([^"]+)" stroke=/.exec(svg)?.[1] ?? '';
expect(d.split('L').length).toBeLessThanOrEqual(1700);
});
});
describe('glanceHtml', () => {
const row = (over: Partial<GlanceRow> = {}): GlanceRow => ({
number: 1,
colour: '#0a84ff',
date: 'Sun, Nov 1',
title: 'Tokyo',
stops: 3,
stay: 'Hotel Gracery',
cost: null,
...over,
});
it('FE-PDFOVERVIEW-003: one row per day in its colour, the cost column only when a day has one', () => {
const without = parse(glanceHtml([row(), row({ number: 2, stops: 0 })], tr));
expect(texts(without, 'thead th')).toEqual(['pdf.day', 'common.date', 'pdf.plan', 'pdf.stay', '']);
expect(texts(without, 'tbody tr:first-child td')).toEqual(['1', 'Sun, Nov 1', 'Tokyo', 'Hotel Gracery', '3']);
// A day without stops leaves the cell empty rather than printing a zero.
expect(texts(without, 'tbody tr:last-child td').slice(-1)[0]).toBe('');
expect(without.querySelector('tbody tr')?.getAttribute('style')).toBe('--day:#0a84ff');
const withCost = parse(glanceHtml([row(), row({ number: 2, cost: '¥3,000' })], tr));
expect(texts(withCost, 'thead th').slice(-1)[0]).toBe('pdf.costLabel');
expect(texts(withCost, 'tbody tr:last-child td').slice(-1)[0]).toBe('¥3,000');
expect(glanceHtml([], tr)).toBe('');
});
});
describe('ledgerHtml', () => {
it('FE-PDFOVERVIEW-004: each booking and stay with its date and the code to show', () => {
const rows: LedgerRow[] = [
{
icon: '<svg></svg>',
tint: '#3b82f6',
title: 'LH716 <FRA>',
sub: '<span>FRA → HND</span>',
when: 'Sat, Oct 31',
code: 'ABC123',
},
{
icon: '<svg></svg>',
tint: '#17171c',
title: 'Hotel Gracery',
sub: '',
when: 'Sun, Nov 1 – Wed, Nov 4',
code: null,
},
];
const doc = parse(ledgerHtml(rows, tr));
expect(texts(doc, '.sec-title')).toEqual(['pdf.bookings']);
expect(texts(doc, '.ledger-title')).toEqual(['LH716 <FRA>', 'Hotel Gracery']);
expect(texts(doc, '.ledger-sub')).toEqual(['FRA → HND']);
expect(texts(doc, '.ledger-when .code-chip')).toEqual(['ABC123']);
expect(doc.querySelectorAll('.ledger-when')[1]?.textContent).toBe('Sun, Nov 1 – Wed, Nov 4');
expect(doc.querySelectorAll('.code-chip')).toHaveLength(1);
expect(doc.querySelector('.ledger-row')?.getAttribute('style')).toBe('--kind:#3b82f6');
});
it('FE-PDFOVERVIEW-005: a trip without bookings or stays prints no list at all', () => {
expect(ledgerHtml([], tr)).toBe('');
});
});
@@ -1,239 +0,0 @@
import type { ShadeStop } from './pdfImages';
import { cssUrl, escHtml } from './tripPdfHtml';
import { glyph } from './tripPdfIcons';
/*
* The trip PDF's first pages: the cover, then the overview with the route map, every
* day at a glance and the list of bookings and stays with their codes.
*/
type Translate = (key: string, params?: Record<string, string | number>) => string;
export interface CoverStat {
value: string;
label: string;
}
/** One day of the route as the cover draws it: its colour and its roads, `[lat, lng]`. */
interface CoverRouteDay {
colour: string;
lines: readonly (readonly [number, number])[][];
}
interface CoverInput {
title: string;
description: string | null;
range: string | null;
/** The cover photo, already checked to be one the document may load. */
image: string | null;
/** Whether the shade is already painted into `image`, so none is laid over it. */
baked?: boolean;
/** The light TREK logo, absolute. */
logo: string | null;
stats: readonly CoverStat[];
/** The routed days, drawn as the trip's shape; empty when nothing was routed. */
route: readonly CoverRouteDay[];
/** Every day's colour in trip order, for the band under the title. */
ribbon: readonly string[];
/** The first and the last day's short date, under the band's ends. */
ribbonEnds: readonly [string, string] | null;
tr: Translate;
}
/**
* The shade over the cover photo, top to bottom: a little at the top for the logo, clear
* through the middle, dark at the foot for the title and the figures. Painted into the
* photo when the export could bake it, laid over it as a gradient when not.
*/
export const COVER_SHADE: readonly ShadeStop[] = [
[0, 0.35],
[0.22, 0],
[0.36, 0],
[0.92, 0.82],
];
/** The cover shade as a CSS gradient, for a photo the export could not bake. */
export function coverShadeCss(): string {
return `linear-gradient(180deg, ${COVER_SHADE.map(([at, alpha]) => `rgba(10, 10, 14, ${alpha}) ${at * 100}%`).join(', ')})`;
}
const ROUTE_W = 240;
const ROUTE_H = 170;
const ROUTE_PAD = 14;
/** Points drawn at most: a road trip routes to tens of thousands, the shape needs far fewer. */
const ROUTE_MAX_POINTS = 1600;
type LatLng = readonly [number, number];
/**
* The trip's roads as one small drawing, each day in its colour on a soft glow, with a
* ring where the trip starts and a dot where it ends. Projected flat with the longitude
* scaled to the middle latitude, which is true enough at the size of a trip. Empty when
* there is no shape to draw.
*/
export function coverRouteSvg(days: readonly CoverRouteDay[]): string {
const lines = days.flatMap((d) => d.lines.filter((l) => l.length > 1).map((l) => ({ colour: d.colour, points: l })));
const points = lines.flatMap((l) => l.points);
if (!lines.length) return '';
const lats = points.map((p) => p[0]);
const midLat = (Math.min(...lats) + Math.max(...lats)) / 2;
const k = Math.cos((midLat * Math.PI) / 180);
const xs = points.map((p) => p[1] * k);
const ys = points.map((p) => -p[0]);
const minX = Math.min(...xs);
const minY = Math.min(...ys);
const w = Math.max(...xs) - minX;
const h = Math.max(...ys) - minY;
const scale = Math.min(
w > 0 ? (ROUTE_W - 2 * ROUTE_PAD) / w : Infinity,
h > 0 ? (ROUTE_H - 2 * ROUTE_PAD) / h : Infinity
);
if (!Number.isFinite(scale)) return '';
const offX = (ROUTE_W - w * scale) / 2;
const offY = (ROUTE_H - h * scale) / 2;
const x = (p: LatLng) => (offX + (p[1] * k - minX) * scale).toFixed(1);
const y = (p: LatLng) => (offY + (-p[0] - minY) * scale).toFixed(1);
const step = Math.max(1, Math.ceil(points.length / ROUTE_MAX_POINTS));
const path = (line: readonly LatLng[]) =>
line
.filter((_, i) => i % step === 0 || i === line.length - 1)
.map((p, i) => `${i ? 'L' : 'M'}${x(p)} ${y(p)}`)
.join('');
const drawn = lines.map((l) => ({ colour: l.colour, d: path(l.points) }));
const first = lines[0];
const last = lines[lines.length - 1];
const start = first.points[0];
const end = last.points[last.points.length - 1];
return `<svg class="cover-route-svg" viewBox="0 0 ${ROUTE_W} ${ROUTE_H}" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
<g class="cover-route-glow" fill="none" stroke="currentColor" stroke-width="4.6" stroke-linecap="round" stroke-linejoin="round">${drawn
.map((l) => `<path d="${l.d}"/>`)
.join('')}</g>
<g fill="none" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">${drawn
.map((l) => `<path d="${l.d}" stroke="${l.colour}"/>`)
.join('')}</g>
<circle class="cover-route-start" cx="${x(start)}" cy="${y(start)}" r="4.2" stroke="${first.colour}" stroke-width="2.2"/>
<circle class="cover-route-end" cx="${x(end)}" cy="${y(end)}" r="4.2" fill="${last.colour}" stroke-width="1.6"/>
</svg>`;
}
/** The cover: the trip's photo left bright, the title, the dates and its figures. */
export function coverHtml({
title,
description,
range,
image,
baked = false,
logo,
stats,
route,
ribbon,
ribbonEnds,
tr,
}: CoverInput): string {
const routeSvg = coverRouteSvg(route);
const routeCard = routeSvg
? `<div class="cover-route"><div class="cover-route-lbl">${escHtml(tr('pdf.mapTitle'))}</div>${routeSvg}</div>`
: '';
const ends = ribbonEnds
? `<div class="cover-ribbon-ends"><span>${escHtml(ribbonEnds[0])}</span><span>${escHtml(ribbonEnds[1])}</span></div>`
: '';
const band =
ribbon.length > 1
? `<div class="cover-ribbon">${ribbon.map((c) => `<span style="background:${c}"></span>`).join('')}</div>${ends}`
: '';
return `<section class="cover${image ? '' : ' cover-plain'}">
<div class="cover-bg"${image ? ` style="background-image:url('${escHtml(cssUrl(image))}')"` : ''}></div>
${baked ? '' : '<div class="cover-shade"></div>'}
<div class="cover-top">
${logo ? `<img src="${escHtml(logo)}" alt="TREK" />` : '<span></span>'}
<span class="eyebrow">${escHtml(tr('pdf.travelPlan'))}</span>
</div>
<div class="cover-body">
<div class="cover-main">
<div class="cover-head">
${range ? `<div class="cover-dates">${escHtml(range)}</div>` : ''}
<h1 class="cover-title">${escHtml(title)}</h1>
${description ? `<p class="cover-desc">${escHtml(description)}</p>` : ''}
</div>
${routeCard}
</div>
${band}
<div class="cover-stats">${stats
.map(
(s) =>
`<div class="cover-stat"><div class="cover-stat-num">${escHtml(s.value)}</div><div class="cover-stat-lbl">${escHtml(s.label)}</div></div>`
)
.join('')}</div>
</div>
</section>`;
}
export interface GlanceRow {
number: number;
colour: string;
date: string;
title: string;
stops: number;
stay: string;
cost: string | null;
}
/** Every day in one table: its colour, date and title, where the night is spent and what it costs. */
export function glanceHtml(rows: readonly GlanceRow[], tr: Translate): string {
if (!rows.length) return '';
const withCost = rows.some((r) => r.cost);
return `<div class="sec-block">
<div class="sec-head"><span class="sec-title">${escHtml(tr('pdf.atAGlance'))}</span></div>
<table class="glance">
<thead><tr>
<th>${escHtml(tr('pdf.day'))}</th>
<th>${escHtml(tr('common.date'))}</th>
<th>${escHtml(tr('pdf.plan'))}</th>
<th>${escHtml(tr('pdf.stay'))}</th>
<th class="glance-stops">${glyph('pin', 9)}</th>
${withCost ? `<th class="glance-end">${escHtml(tr('pdf.costLabel'))}</th>` : ''}
</tr></thead>
<tbody>${rows
.map(
(r) => `<tr style="--day:${r.colour}">
<td><span class="glance-day">${r.number}</span></td>
<td class="num glance-date">${escHtml(r.date)}</td>
<td class="glance-title">${escHtml(r.title)}</td>
<td>${escHtml(r.stay)}</td>
<td class="num glance-stops">${r.stops || ''}</td>
${withCost ? `<td class="num">${r.cost ?? ''}</td>` : ''}
</tr>`
)
.join('')}</tbody>
</table>
</div>`;
}
export interface LedgerRow {
/** The type's icon, already markup. */
icon: string;
/** The type's tint, a checked hex colour. */
tint: string;
title: string;
/** Markup under the title: the route, the address or the booking's facts. */
sub: string;
when: string;
code: string | null;
}
/** The trip's bookings and stays in date order, each with the code to show at the desk. */
export function ledgerHtml(rows: readonly LedgerRow[], tr: Translate): string {
if (!rows.length) return '';
return `<div class="sec-block ledger-block">
<div class="sec-head"><span class="sec-title">${escHtml(tr('pdf.bookings'))}</span></div>
<div class="ledger">${rows
.map(
(r) => `<div class="ledger-row" style="--kind:${r.tint}">
<span class="ledger-icon">${r.icon}</span>
<div><div class="ledger-title">${escHtml(r.title)}</div>${r.sub ? `<div class="ledger-sub">${r.sub}</div>` : ''}</div>
<div class="ledger-when">${escHtml(r.when)}${r.code ? `<div><span class="code-chip">${glyph('key', 9)}${escHtml(r.code)}</span></div>` : ''}</div>
</div>`
)
.join('')}</div>
</div>`;
}
-411
View File
@@ -1,411 +0,0 @@
import geist400 from '@fontsource/geist-sans/files/geist-sans-latin-400-normal.woff2?url';
import geist500 from '@fontsource/geist-sans/files/geist-sans-latin-500-normal.woff2?url';
import geist600 from '@fontsource/geist-sans/files/geist-sans-latin-600-normal.woff2?url';
import { PDF_MARKDOWN_CSS } from './pdfMarkdown';
import { coverShadeCss } from './tripPdfOverview';
/*
* The trip PDF's stylesheet. A print document has a fixed palette rather than the
* reader's scheme, so its colours are declared once, as the custom properties at the
* top, and every rule below names them. The type follows the app: Poppins for words,
* Geist for figures, times and the small capitals.
*
* Every switch of the preview is one class on <body> (pdfPreview.ts), so turning one
* over is instant and needs no rebuild:
* pdf-flow days run on instead of each starting a page
* pdf-large-text larger type and darker greys
* pdf-no-transport-notes the notes of flights, trains and rentals left out
* pdf-no-photos no photos on the places and stays
* pdf-no-overview no route map, day overview or booking list
* pdf-no-coords no coordinates under the addresses
* pdf-no-details no contact lines, opening hours or companions
*/
export function tripPdfCss(): string {
return `
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 400; src: url('/fonts/Poppins-Regular.ttf') format('truetype'); }
@font-face { font-family: 'Poppins'; font-style: italic; font-weight: 400; src: url('/fonts/Poppins-Italic.ttf') format('truetype'); }
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 500; src: url('/fonts/Poppins-Medium.ttf') format('truetype'); }
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 600; src: url('/fonts/Poppins-SemiBold.ttf') format('truetype'); }
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 700; src: url('/fonts/Poppins-Bold.ttf') format('truetype'); }
@font-face { font-family: 'Geist PDF'; font-weight: 400; src: url('${geist400}') format('woff2'); }
@font-face { font-family: 'Geist PDF'; font-weight: 500; src: url('${geist500}') format('woff2'); }
@font-face { font-family: 'Geist PDF'; font-weight: 600; src: url('${geist600}') format('woff2'); }
:root {
--ink: #17171c;
--ink-2: #3e3e47;
--ink-3: #6a6a74;
--ink-4: #9a9aa4;
--hair: #e7e5e0;
--paper: #ffffff;
--wash: #f6f5f2;
--wash-2: #eeede8;
--night: #141418;
--glass: rgba(255, 255, 255, 0.13);
--glass-edge: rgba(255, 255, 255, 0.22);
--glass-dark: rgba(14, 14, 18, 0.42);
--glass-tile: rgba(18, 18, 24, 0.34);
--glass-deep: rgba(12, 12, 16, 0.5);
--on-night: rgba(255, 255, 255, 0.78);
--on-night-2: rgba(255, 255, 255, 0.56);
--gold: #b7791f;
--day: var(--ink);
--t: 1;
--sans: 'Poppins', system-ui, -apple-system, 'Segoe UI', sans-serif;
--num: 'Geist PDF', 'Poppins', system-ui, sans-serif;
--gutter: 14mm;
}
body.pdf-large-text {
--t: 1.3;
--ink-2: #2b2b33;
--ink-3: #4b4b55;
--ink-4: #62626c;
}
@page { size: A4; margin: 12mm 0 14mm; }
@page :first { margin: 0; }
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body { background: var(--paper); }
body {
font-family: var(--sans); color: var(--ink);
font-size: calc(9.5px * var(--t)); line-height: 1.5;
-webkit-print-color-adjust: exact; print-color-adjust: exact;
}
img { display: block; }
svg { flex-shrink: 0; }
.num { font-family: var(--num); font-variant-numeric: tabular-nums; }
.eyebrow {
font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600;
letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-3);
}
.page-break { break-before: page; }
/* ── Cover ───────────────────────────────────────────────── */
.cover {
position: relative; height: 297mm; overflow: hidden;
background: var(--night); color: var(--paper); break-after: page;
}
.cover-bg { position: absolute; inset: 0; background-size: cover; background-position: center; }
.cover-plain .cover-bg {
background: radial-gradient(120% 80% at 85% 10%, var(--ink-2) 0%, var(--night) 60%);
}
.cover-shade {
position: absolute; inset: 0;
background: ${coverShadeCss()};
}
.cover-top {
position: absolute; inset-block-start: 14mm; inset-inline: var(--gutter);
display: flex; align-items: center; justify-content: space-between;
}
.cover-top img { height: 22px; }
.cover-top .eyebrow { color: var(--on-night); }
.cover-body { position: absolute; inset-inline: var(--gutter); inset-block-end: 15mm; }
.cover-main { display: flex; align-items: flex-end; gap: 8mm; }
.cover-head { flex: 1; min-width: 0; }
.cover-dates {
display: inline-block; font-family: var(--num); font-size: 9px; font-weight: 600; letter-spacing: 0.16em;
text-transform: uppercase; color: var(--paper); padding: 5px 11px; border-radius: 99px;
background: var(--glass-tile); border: 1px solid var(--glass-edge);
}
.cover-title { font-size: 54px; font-weight: 700; line-height: 1; letter-spacing: -0.025em; margin: 5mm 0 3.5mm; }
.cover-desc { max-width: 120mm; font-size: 12px; line-height: 1.6; color: var(--on-night); }
.cover-route {
flex: 0 0 66mm; padding: 9px 10px 6px; border-radius: 18px;
background: var(--glass-deep); border: 1px solid var(--glass-edge);
}
.cover-route-lbl {
font-family: var(--num); font-size: 7px; font-weight: 600; letter-spacing: 0.16em;
text-transform: uppercase; color: var(--on-night-2);
}
.cover-route-svg { display: block; width: 100%; height: auto; }
.cover-route-glow { color: var(--paper); }
.cover-route-start { fill: var(--paper); }
.cover-route-end { stroke: var(--paper); }
.cover-ribbon { display: flex; gap: 2px; height: 5px; margin-block-start: 8mm; }
.cover-ribbon span { flex: 1; border-radius: 3px; }
.cover-ribbon-ends {
display: flex; justify-content: space-between; margin-block-start: 5px;
font-family: var(--num); font-size: 7.5px; font-weight: 600; letter-spacing: 0.12em;
text-transform: uppercase; color: var(--on-night-2);
}
.cover-stats { display: flex; flex-wrap: wrap; gap: 8px; margin-block-start: 6mm; }
.cover-stat {
flex: 1 1 0; min-width: max-content;
background: var(--glass-tile); border: 1px solid var(--glass-edge); border-radius: 16px;
padding: 12px 14px 11px;
}
.cover-stat-num {
font-family: var(--num); font-size: 19px; font-weight: 600; line-height: 1.1;
white-space: nowrap; font-variant-numeric: tabular-nums;
}
.cover-stat-lbl {
font-family: var(--num); font-size: 7.5px; font-weight: 500; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--on-night-2); margin-block-start: 5px;
}
/* The glass is a tinted fill, not a backdrop blur: print engines leave a blur out, and
in the preview a blur over the full-page photo had to be redrawn on every scroll. */
/* ── Overview: route map, the days at a glance, bookings and stays ─────── */
.overview { padding: 2mm var(--gutter) 0; }
.pdf-no-overview .overview { display: none; }
.sec-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-block-end: 4mm; }
.sec-title { font-size: calc(17px * var(--t)); font-weight: 600; letter-spacing: -0.01em; }
.sec-block { break-inside: avoid; margin-block-end: 9mm; }
.trip-map { margin-block-end: 9mm; }
.trip-map-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin-block-end: 4mm; }
.trip-map-title { font-size: calc(17px * var(--t)); font-weight: 600; letter-spacing: -0.01em; }
.trip-map-total {
font-family: var(--num); font-size: calc(9px * var(--t)); font-weight: 600; color: var(--ink-2);
background: var(--wash); border-radius: 99px; padding: 4px 10px;
}
.trip-map-note { font-size: 9px; font-weight: 600; color: var(--gold); margin: -2mm 0 3mm; }
.trip-map-svg { width: 100%; height: auto; border-radius: 16px; border: 1px solid var(--hair); display: block; overflow: hidden; }
.trip-map-legend { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 5px 14px; margin-block-start: 4mm; }
.trip-map-leg { display: flex; align-items: center; gap: 6px; min-width: 0; font-size: calc(8.5px * var(--t)); color: var(--ink-2); }
.trip-map-leg-name { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.trip-map-dot { width: 8px; height: 8px; border-radius: 50%; }
.trip-map-leg-dist { font-family: var(--num); color: var(--ink-4); white-space: nowrap; }
.trip-map-credit { font-size: 7px; color: var(--ink-4); margin-block-start: 3mm; }
.glance { width: 100%; border-collapse: collapse; font-size: calc(8.5px * var(--t)); }
.glance th {
font-family: var(--num); font-size: calc(7px * var(--t)); font-weight: 600; letter-spacing: 0.12em;
text-transform: uppercase; color: var(--ink-4); text-align: start; padding: 0 6px 6px;
border-block-end: 1px solid var(--hair);
}
.glance td { padding: 6px; border-block-end: 1px solid var(--wash-2); vertical-align: top; color: var(--ink-2); }
.glance tr { break-inside: avoid; }
.glance-day { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 18px; padding: 0 5px; border-radius: 6px; background: var(--day); color: var(--paper); font-family: var(--num); font-weight: 600; font-size: calc(8px * var(--t)); }
.glance-title { color: var(--ink); font-weight: 500; }
.glance .num, .glance-end { text-align: end; white-space: nowrap; }
.glance .glance-stops { text-align: center; }
.glance .glance-date { text-align: start; }
.glance th.glance-stops svg { display: inline-block; vertical-align: -1px; }
.ledger { display: grid; gap: 5px; }
.ledger-row {
display: grid; grid-template-columns: 26px 1fr auto; gap: 10px; align-items: center;
padding: 7px 10px; border: 1px solid var(--hair); border-radius: 12px; break-inside: avoid;
}
.ledger-icon {
width: 26px; height: 26px; border-radius: 8px; display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--kind) 14%, var(--paper)); color: var(--kind);
}
.ledger-title { font-weight: 600; font-size: calc(9.5px * var(--t)); }
.ledger-sub { font-size: calc(8px * var(--t)); color: var(--ink-3); }
.ledger-when { font-family: var(--num); font-size: calc(8px * var(--t)); color: var(--ink-3); text-align: end; white-space: nowrap; }
/* ── Day ─────────────────────────────────────────────────── */
/* A real <table>, so the browser repeats the <thead> day header on every page an
overflowing day spills onto (#1471); CSS table-header-group on a <div> is not
repeated by Chromium's print engine. */
.day-section { width: 100%; border-collapse: collapse; table-layout: fixed; }
.day-break { break-before: page; }
/* The first day always opens a page of its own, after the cover or the overview. */
.day-first { break-before: page; }
.pdf-flow .day-break { break-before: auto; }
.pdf-flow .day-section + .day-section { margin-block-start: 8mm; }
/* Hold a flowing day together where it fits, so a header is never stranded at the
foot of a sheet with its content on the next one (#1471). */
.pdf-flow .day-section { break-inside: avoid; page-break-inside: avoid; }
/* The gap under the header sits inside the repeated cell: a block-start padding on the
body is only painted on its first fragment (#1531). */
.day-header > tr > td { padding: 0 var(--gutter) 5mm; }
.day-head {
display: flex; align-items: center; gap: 12px; padding-block: 3mm 3.5mm;
border-block-end: 1px solid var(--hair); position: relative;
}
.day-head::after {
content: ''; position: absolute; inset-inline-start: 0; inset-block-end: -1px;
width: 26mm; height: 2px; border-radius: 2px; background: var(--day);
}
.day-tag {
width: 42px; height: 42px; border-radius: 13px; background: var(--day); color: var(--paper);
display: flex; flex-direction: column; align-items: center; justify-content: center; flex-shrink: 0;
}
.day-tag-lbl { font-family: var(--num); font-size: 6.5px; font-weight: 600; letter-spacing: 0.14em; opacity: 0.85; }
.day-tag-num { font-family: var(--num); font-size: 17px; font-weight: 600; line-height: 1; }
.day-head-main { flex: 1; min-width: 0; }
.day-date { font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-3); }
.day-title { font-size: calc(17px * var(--t)); font-weight: 600; line-height: 1.25; letter-spacing: -0.01em; }
.day-meta { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 5px; max-width: 70mm; }
.meta-pill, .day-cost {
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; color: var(--ink-2);
background: var(--wash); border-radius: 99px; padding: 4px 9px;
}
.meta-pill svg, .day-cost svg { color: var(--ink-4); }
.day-body { padding: 0 var(--gutter) 4mm; }
.day-intro {
margin-block-end: 4mm; padding: 9px 12px; border-radius: 12px; background: var(--wash);
font-size: calc(9px * var(--t)); color: var(--ink-2); white-space: pre-line;
}
/* ── Photo strip ─────────────────────────────────────────── */
.day-strip { display: grid; gap: 4px; height: 48mm; margin-block-end: 5mm; border-radius: 16px; overflow: hidden; }
.day-strip-1 { grid-template-columns: 1fr; }
.day-strip-2 { grid-template-columns: 3fr 2fr; }
.day-strip-3 { grid-template-columns: 2fr 1fr 1fr; }
.day-strip-photo { position: relative; min-width: 0; overflow: hidden; background: var(--wash-2); }
.day-strip-photo img { width: 100%; height: 100%; object-fit: cover; }
.glass-label {
position: absolute; inset-inline-start: 8px; inset-block-end: 8px; max-width: calc(100% - 16px);
padding: 4px 10px; border-radius: 99px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
font-size: calc(8px * var(--t)); font-weight: 500; color: var(--paper);
background: var(--glass-dark); border: 1px solid var(--glass-edge);
}
.pdf-no-photos .day-strip { display: none; }
/* ── Stays ───────────────────────────────────────────────── */
.day-accommodations { display: grid; grid-template-columns: repeat(auto-fit, minmax(80mm, 1fr)); gap: 6px; margin-block-end: 5mm; }
.day-accommodation {
display: flex; gap: 10px; align-items: center; padding: 8px 10px;
border: 1px solid var(--hair); border-radius: 14px; break-inside: avoid;
}
.day-accommodation.stay-quiet { padding: 6px 10px; background: var(--wash); border-color: transparent; }
.stay-media {
width: 40px; height: 40px; border-radius: 11px; overflow: hidden; flex-shrink: 0;
display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--day) 12%, var(--paper)); color: var(--day);
}
.stay-quiet .stay-media { width: 26px; height: 26px; border-radius: 8px; }
.stay-media img { width: 100%; height: 100%; object-fit: cover; }
.pdf-no-photos .stay-media img { display: none; }
.stay-main { flex: 1; min-width: 0; }
.stay-kicker { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; color: var(--day); }
.stay-name { font-size: calc(10.5px * var(--t)); font-weight: 600; line-height: 1.35; }
.stay-quiet .stay-name { font-size: calc(9px * var(--t)); font-weight: 500; }
.stay-line { font-size: calc(8.5px * var(--t)); color: var(--ink-3); }
.stay-extra { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 4px; }
/* ── Timeline ────────────────────────────────────────────── */
.timeline { list-style: none; }
.tl-item { display: grid; grid-template-columns: 13mm 22px minmax(0, 1fr); column-gap: 8px; break-inside: avoid; }
.tl-time { text-align: end; padding-block-start: 11px; font-family: var(--num); font-variant-numeric: tabular-nums; }
.tl-start { display: block; font-size: calc(9.5px * var(--t)); font-weight: 600; color: var(--ink); }
.tl-end { display: block; font-size: calc(8px * var(--t)); color: var(--ink-4); }
.tl-rail { position: relative; display: flex; justify-content: center; }
.tl-rail::before {
content: ''; position: absolute; inset-block: 0; inset-inline-start: calc(50% - 0.75px); width: 1.5px;
background: color-mix(in srgb, var(--day) 26%, var(--paper));
}
.tl-item:first-child .tl-rail::before { inset-block-start: 14px; }
.tl-item:last-child .tl-rail::before { inset-block-end: auto; height: 14px; }
.tl-item:only-child .tl-rail::before { display: none; }
.tl-marker {
position: relative; margin-block-start: 8px; width: 22px; height: 22px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
background: var(--paper); border: 1.5px solid var(--day); color: var(--day);
font-family: var(--num); font-size: calc(8.5px * var(--t)); font-weight: 600;
}
.tl-place .tl-marker { background: var(--day); color: var(--paper); }
.tl-booking .tl-marker { border-color: var(--kind); color: var(--kind); }
.tl-note .tl-marker { width: 10px; height: 10px; margin-block-start: 13px; background: var(--wash-2); border-color: var(--wash-2); }
.tl-body { padding-block: 3px 7px; min-width: 0; }
.empty-day { padding: 10mm 0; text-align: center; color: var(--ink-4); font-size: calc(9px * var(--t)); }
/* ── Place ───────────────────────────────────────────────── */
.place-card {
display: flex; gap: 11px; padding: 10px; border: 1px solid var(--hair); border-radius: 14px;
background: var(--paper); break-inside: avoid;
}
.place-thumb, .place-thumb-fallback { width: 74px; height: 74px; border-radius: 11px; flex-shrink: 0; }
.place-thumb { object-fit: cover; }
.place-thumb-fallback {
display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--cat) 14%, var(--paper)); color: var(--cat);
}
.pdf-no-photos .place-thumb, .pdf-no-photos .place-thumb-fallback { display: none; }
.place-info { flex: 1; min-width: 0; }
.place-name-row { display: flex; align-items: flex-start; gap: 8px; }
.place-name { flex: 1; font-size: calc(12px * var(--t)); font-weight: 600; line-height: 1.3; letter-spacing: -0.005em; }
.cat-badge {
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; flex-shrink: 0;
font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600;
border-radius: 99px; padding: 3px 8px;
background: color-mix(in srgb, var(--cat) 13%, var(--paper));
color: color-mix(in srgb, var(--cat) 78%, var(--ink));
}
.facts { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 5px; }
.chip {
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 500; color: var(--ink-2);
background: var(--wash); border-radius: 99px; padding: 2px 8px;
}
.chip svg { color: var(--ink-4); }
.chip-rating { color: var(--gold); }
.chip-rating svg { color: var(--gold); fill: var(--gold); }
.chip-tag { background: color-mix(in srgb, var(--tag) 12%, var(--paper)); color: color-mix(in srgb, var(--tag) 75%, var(--ink)); }
.chip-tag::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--tag); }
.code-chip {
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.04em;
color: var(--ink); background: var(--wash-2); border-radius: 6px; padding: 2px 7px;
}
.code-chip svg { color: var(--ink-3); }
.info-row { display: flex; align-items: flex-start; gap: 5px; margin-block-start: 4px; }
.info-row svg { color: var(--ink-4); margin-block-start: 1px; }
.info-text { font-size: calc(8.5px * var(--t)); color: var(--ink-2); line-height: 1.5; min-width: 0; }
.info-text.muted { color: var(--ink-3); }
.info-spacer { display: none; }
.coords { font-family: var(--num); color: var(--ink-4); font-size: calc(8px * var(--t)); }
.pdf-no-coords .coords { display: none; }
.place-text { margin-block-start: 5px; font-size: calc(9px * var(--t)); color: var(--ink-2); line-height: 1.55; }
.place-text .info-row { margin: 0; }
.place-text .info-text { font-size: inherit; color: inherit; }
.place-note {
margin-block-start: 6px; padding: 6px 9px; border-radius: 9px; background: var(--wash);
font-size: calc(8.5px * var(--t)); color: var(--ink-2);
}
.place-note .info-row { margin: 0; }
.place-note .info-text { color: inherit; }
.details { display: flex; flex-wrap: wrap; gap: 3px 12px; margin-block-start: 6px; }
.detail { display: inline-flex; align-items: center; gap: 4px; font-size: calc(8px * var(--t)); color: var(--ink-3); }
.detail svg { color: var(--ink-4); }
.pdf-no-details .details { display: none; }
${PDF_MARKDOWN_CSS}
/* ── Bookings and notes ──────────────────────────────────── */
.note-card {
display: flex; gap: 10px; align-items: flex-start; padding: 9px 11px; border-radius: 14px;
break-inside: avoid; background: var(--wash);
}
.booking-card {
background: color-mix(in srgb, var(--kind) 6%, var(--paper));
border: 1px solid color-mix(in srgb, var(--kind) 20%, var(--paper));
}
.note-icon {
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
display: flex; align-items: center; justify-content: center; color: var(--ink-3); background: var(--paper);
}
.booking-card .note-icon { background: var(--kind); color: var(--paper); }
.note-tinted { border-inline-start: 3px solid var(--note); }
.note-tinted .note-icon { color: var(--note); }
.note-body { flex: 1; min-width: 0; }
.note-kicker { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; color: var(--kind, var(--ink-3)); }
.note-text { font-size: calc(9.5px * var(--t)); color: var(--ink); line-height: 1.5; }
.booking-card .note-text { font-size: calc(11px * var(--t)); font-weight: 600; line-height: 1.35; }
.note-time { font-size: calc(8.5px * var(--t)); color: var(--ink-3); margin-block-start: 2px; white-space: pre-line; }
.note-line { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-block-start: 4px; }
.note-line .route { font-family: var(--num); font-size: calc(9px * var(--t)); font-weight: 600; color: var(--ink); margin-inline-end: 2px; }
.booking-card .chip { background: var(--paper); }
.note-extra { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 5px; }
.transport-note { font-style: italic; white-space: pre-line; }
.pdf-no-transport-notes .transport-note { display: none; }
/* ── Plugin sections ─────────────────────────────────────── */
.plugin-sections { padding: 2mm var(--gutter) 4mm; }
.plugin-section { margin-block-end: 6mm; break-inside: avoid; }
.plugin-section-title { font-size: calc(13px * var(--t)); font-weight: 600; margin-block-end: 2mm; padding-block-end: 2mm; border-block-end: 1px solid var(--hair); }
.plugin-section-text { font-size: calc(9.5px * var(--t)); color: var(--ink-2); line-height: 1.55; margin-block-end: 5px; }
.plugin-section-table { width: 100%; border-collapse: collapse; margin-block-start: 6px; }
.plugin-section-table th { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; color: var(--ink-4); text-transform: uppercase; letter-spacing: 0.1em; text-align: start; padding: 4px 8px; border-block-end: 1px solid var(--hair); }
.plugin-section-table td { font-size: calc(9px * var(--t)); color: var(--ink-2); padding: 4px 8px; border-block-end: 1px solid var(--wash-2); }
.doc-end { display: flex; align-items: center; justify-content: center; gap: 6px; padding: 8mm 0 4mm; color: var(--ink-4); font-size: 7.5px; letter-spacing: 0.06em; }
.doc-end img { height: 10px; opacity: 0.55; }
`;
}
@@ -33,7 +33,6 @@ import { useTripStore } from '../../store/tripStore'
import { useCanDo } from '../../store/permissionsStore'
import { useSettingsStore } from '../../store/settingsStore'
import { useAddonStore } from '../../store/addonStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import { openSaveToCollection } from '../Collections/saveTarget'
import { computeMultiDayMove as computeMultiDayMoveIn, getDayOrder as getDayOrderIn, type SpanPhase } from './DayPlanSidebar.multiDayMove'
import { useTranslation } from '../../i18n'
@@ -42,6 +41,7 @@ import { Tooltip } from '../shared/Tooltip'
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { BarButton, MoreButton, SoftPill, TimePill, tintOf } from './planParts'
import './dayPlanRows.css'
import { TypeTile } from './bookings/bookingParts'
import { typeInfo } from './bookings/bookingsModel'
import { transportSubtitle } from './transportDetailModel'
@@ -218,7 +218,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const toast = useToast()
const { t, locale } = useTranslation()
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
const tripActions = useRef(useTripStore.getState()).current
const { noteUi, setNoteUi, noteInputRef, dayNotes, openAddNote: _openAddNote, openEditNote: _openEditNote, cancelNote, saveNote, deleteNote: _deleteNote, moveNote: _moveNote } = useDayNotes(tripId)
@@ -1098,7 +1098,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// Total Cost reads the expenses in Costs when it is on (#2551).
const budgetItems = useTripStore(s => s.budgetItems)
const costsEnabled = useTripAddonEnabled(tripId, 'budget')
const costsEnabled = useAddonStore(s => s.isEnabled('budget'))
const totalCostLabel = useMemo(() => {
return formatMoneySum(planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency, displayCurrency: costBase }).total, costBase, locale, fxRates)
}, [days, assignments, reservations, budgetItems, costsEnabled, currency, costBase, locale, fxRates])
@@ -1276,7 +1276,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
const dateFirst = useSettingsStore(s => s.settings.day_date_first === true)
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
// Plugin time contributions in the day plan (dayScheduleProvider hook).
const daySchedule = usePluginDaySchedule(tripId)
// Per-day colours from the dayTintProvider hook — e.g. which leg of the trip a
@@ -1,4 +1,4 @@
// FE-PLANNER-DPTRANSPORT-001 to FE-PLANNER-DPTRANSPORT-024
// FE-PLANNER-DPTRANSPORT-001 to FE-PLANNER-DPTRANSPORT-021
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
@@ -329,29 +329,4 @@ describe('DayPlanSidebarTransportDetailModal', () => {
await user.click(screen.getByRole('button', { name: 'Close' }))
expect(setTransportDetail).toHaveBeenCalledWith(null)
})
// #3122: a transport holding only times showed them without the day they fall on.
it('FE-PLANNER-DPTRANSPORT-022: a booking holding only times names the date of its linked day', () => {
seedStore(useTripStore, { days: [{ id: 4, trip_id: 1, day_number: 2, date: '2025-06-16' }] as never })
const res = { ...flight(), day_id: 4, reservation_time: '09:15', reservation_end_time: '11:00', endpoints: [] } as Reservation
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
expect(screen.getByText('09:15 → 11:00').parentElement).toHaveTextContent(/Mon, Jun 16/)
})
it('FE-PLANNER-DPTRANSPORT-023: an overnight booking names the arrival date too', () => {
const res = { ...flight(), reservation_time: '2025-06-15T22:30:00', reservation_end_time: '2025-06-16T06:05:00' } as Reservation
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
expect(screen.getByText('22:30 → 06:05').parentElement).toHaveTextContent(/Sun, Jun 15 → Mon, Jun 16/)
})
it('FE-PLANNER-DPTRANSPORT-024: in a right-to-left UI the overnight days read in order', () => {
document.documentElement.dir = 'rtl'
try {
const res = { ...flight(), reservation_time: '2025-06-15T22:30:00', reservation_end_time: '2025-06-16T06:05:00' } as Reservation
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
expect(screen.getByText('22:30 → 06:05').parentElement).toHaveTextContent('⁨Sun, Jun 15⁩ ← ⁨Mon, Jun 16⁩')
} finally {
document.documentElement.dir = ''
}
})
})
@@ -8,15 +8,13 @@ import { BlurredCode } from '../shared/BookingCode'
import { DialogButton, DialogFooter, DialogSection, DialogShell, FooterSpacer, PILL } from '../shared/DialogShell'
import { useTripStore } from '../../store/tripStore'
import { formatTime, splitReservationDateTime } from '../../utils/formatters'
import { parseReservationMetadata, seatCells } from '../../utils/flightLegs'
import { parseReservationMetadata } from '../../utils/flightLegs'
import { BookingDialogHeader } from './bookings/BookingDialogShell'
import { BOX, Eyebrow, Field, fs, toneColor, toneOf } from './bookings/bookingParts'
import { filesFor } from '../../utils/reservationFiles'
import { bookingDayLabel, segmentCodeLabel } from './transportDetailModel'
import { TransitLegs, transitSummary } from './bookings/transitParts'
import { bookingDates } from './bookings/bookingsModel'
import { flowText } from '../../utils/flowText'
import type { Day, Reservation } from '../../types'
import type { Reservation } from '../../types'
type Translate = (key: string, params?: Record<string, string | number>) => string
@@ -52,12 +50,11 @@ export function DayPlanSidebarTransportDetailModal({ transportDetail, ...rest }:
function TransportDetailDialog({ res, setTransportDetail, onNavigateToFiles, onEdit, t, locale, timeFormat }: Omit<DayPlanSidebarTransportDetailModalProps, 'transportDetail'> & { res: Reservation }) {
const titleId = useId()
const allFiles = useTripStore(s => s.files)
const days = useTripStore(s => s.days)
const close = () => setTransportDetail(null)
const meta = parseReservationMetadata(res)
const transit = transitSummary(meta)
const files = filesFor(res, allFiles || [])
const when = whenOf(res, days, locale, timeFormat)
const when = whenOf(res, locale, timeFormat)
const cells = detailCells(res, meta, t)
const confirmed = res.status === 'confirmed'
@@ -175,13 +172,11 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
add(t('reservations.meta.flightNumber'), meta.flight_number)
add(t('reservations.meta.from'), meta.departure_airport)
add(t('reservations.meta.to'), meta.arrival_airport)
add(t('reservations.meta.seat'), meta.seat)
} else if (res.type === 'train') {
add(t('reservations.meta.trainNumber'), meta.train_number)
add(t('reservations.meta.platform'), meta.platform)
}
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
if (res.type === 'flight' || res.type === 'train') {
for (const c of seatCells(res, t('reservations.meta.seat'))) add(c.label, c.value)
add(t('reservations.meta.seat'), meta.seat)
}
add(t('reservations.confirmationCode'), res.confirmation_number, true)
// A stopover booking can carry its own reference per segment (#1943); the
@@ -197,18 +192,11 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
return cells
}
/**
* The booking's calendar day (both, when it arrives on a later one) and its time or
* time range, each empty when the booking has none. A booking holding only times
* takes the date of the day it is linked to (#3122).
*/
function whenOf(res: Reservation, days: Day[], locale: string, timeFormat: string): { day: string; time: string } {
const { time } = splitReservationDateTime(res.reservation_time)
/** The booking's day and its time or time range, each empty when the booking has none. */
function whenOf(res: Reservation, locale: string, timeFormat: string): { day: string; time: string } {
const { date, time } = splitReservationDateTime(res.reservation_time)
const { time: endTime } = splitReservationDateTime(res.reservation_end_time)
const dates = bookingDates(res, days || [])
// An arrival date alone would read as the departure, so it only joins a start date.
const span = dates.start ? [dates.start, dates.end !== dates.start ? dates.end : null].filter((d): d is string => !!d) : []
const day = span.length > 0 ? flowText(span.map(d => bookingDayLabel(d, locale))) : ''
const day = date ? bookingDayLabel(date, locale) : ''
const start = time ? formatTime(time, locale, timeFormat) : ''
const end = endTime ? formatTime(endTime, locale, timeFormat) : ''
return { day, time: start && end ? `${start} → ${end}` : start }
@@ -2,7 +2,6 @@ import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNod
import type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'
import { useAuthStore } from '../../store/authStore'
import { useAddonStore } from '../../store/addonStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import { useCanDo } from '../../store/permissionsStore'
import { useTripStore } from '../../store/tripStore'
import { useSettingsStore } from '../../store/settingsStore'
@@ -121,7 +120,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
const tripObj = useTripStore((s) => s.trip)
const canUploadFiles = can('file_upload', tripObj)
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))
const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')
const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)
const {
form, setForm, autoFilledRef, pendingFiles, addFilesFromInput, removeFile, handlePaste, isSaving, setIsSaving,
@@ -1,7 +1,7 @@
import { useEffect, useRef, useMemo, useId } from 'react'
import { useParams } from 'react-router'
import { useTripStore } from '../../store/tripStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import { useAddonStore } from '../../store/addonStore'
import CustomSelect from '../shared/CustomSelect'
import { BookingCodeInput } from '../shared/BookingCode'
import { buildAssignmentOptions } from './assignmentOptions'
@@ -71,7 +71,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
const fileInputRef = useRef(null)
const titleId = useId()
const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
// Set right before submit when the user clicked create/edit expense.
const expense = useBookingExpenseIntent(() => handleSubmit(), {
@@ -357,7 +357,7 @@ describe('TransitSearchPanel', () => {
await user.click(fromInput)
const picks = (await screen.findAllByRole('button', { name: /Hotel Adlon|Stop \d|Hostel/ })).map(b => b.textContent)
expect(picks[0]).toBe('Hotel Adlon')
expect(picks.slice(1)).toEqual([...places.map(p => p.name), 'Later Hostel'])
expect(picks.slice(1)).toEqual(['Stop 1', 'Stop 2', 'Stop 3', 'Stop 4', 'Stop 5', 'Stop 6', 'Stop 7', 'Stop 8'])
await user.click(screen.getByRole('button', { name: 'Hotel Adlon' }))
expect(fromInput).toHaveValue('Hotel Adlon')
@@ -744,7 +744,7 @@ describe('quick picks from the bookings of the day (#1506)', () => {
const places = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 100 + i, name: `P${i}`, lat: 52 + i / 100, lng: 13 }))
const picks = buildQuickPicks(day, [day], places as any, [], dayBookingStops(day, [flight] as any))
expect(picks.slice(0, 2).map(p => p.name)).toEqual(['FRA', 'BER Airport'])
expect(picks).toHaveLength(2 + places.length)
expect(picks).toHaveLength(2 + 8)
})
})
@@ -8,8 +8,7 @@ import { transitApi } from '../../api/client'
import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { getDayBookendHotels, isDayInAccommodationRange } from '../../utils/dayOrder'
import { orderTransitStaysByDate } from './transitStayOrder'
import { getDayBookendHotels } from '../../utils/dayOrder'
import type { Day, Place, Accommodation, Reservation } from '../../types'
import { useTripStore } from '../../store/tripStore'
import { isCarrierTransport } from '../../utils/dayMerge'
@@ -111,11 +110,7 @@ function fmtDuration(seconds: number, t: (k: string, p?: Record<string, string |
// ── quick picks ──────────────────────────────────────────────────────────────
const MAX_OTHER_DAY_STAYS = 8
function pickedPlaceKey(p: PickedPlace): string {
return JSON.stringify([p.name.trim().toLowerCase(), p.lat, p.lng])
}
const MAX_QUICK_PICKS = 8
function stayPick(a: Accommodation): PickedPlace | null {
return a.place_lat != null && a.place_lng != null && a.place_name ? { name: a.place_name, lat: a.place_lat, lng: a.place_lng } : null
@@ -148,30 +143,28 @@ export function dayBookingStops(day: Pick<Day, 'id' | 'date'>, reservations: Res
* starts in and the one it ends in come first and are never cut, since most
* connections of a day begin or end there (#2538); the day's airports and
* stations follow and are not cut either (#1506); then the day's own located
* places and remaining stays covering the day, without a limit. Only stays
* outside the selected day's range are capped, nearest in nights first.
* places and the trip's other stays, up to MAX_QUICK_PICKS.
*/
export function buildQuickPicks(day: Day, days: Day[], places: Place[], accommodations: Accommodation[], bookingStops: PickedPlace[] = []): PickedPlace[] {
const { morning, evening } = getDayBookendHotels(day, days, accommodations)
const bookendStays = [morning, evening].filter((a): a is Accommodation => a != null)
const dayStays = accommodations.filter(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days))
const dayStays = [morning, evening].filter((a): a is Accommodation => a != null)
const seen = new Set<string>()
const unique = (p: PickedPlace | null): p is PickedPlace => {
if (!p) return false
const k = pickedPlaceKey(p)
const k = `${p.name}:${p.lat}`
if (seen.has(k)) return false
seen.add(k)
return true
}
const stays = bookendStays.map(stayPick).filter(unique)
const stays = dayStays.map(stayPick).filter(unique)
const stations = bookingStops.filter(unique)
const dayPlaces = places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)).filter(unique)
const remainingDayStays = dayStays.map(stayPick).filter(unique)
const otherStays = orderTransitStaysByDate(day, days, accommodations.filter(a => !dayStays.includes(a)))
.map(stayPick).filter(unique).slice(0, MAX_OTHER_DAY_STAYS)
return [...stays, ...stations, ...dayPlaces, ...remainingDayStays, ...otherStays]
const rest = [
...places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)),
...accommodations.filter(a => !dayStays.includes(a)).map(stayPick),
].filter(unique)
return [...stays, ...stations, ...rest.slice(0, MAX_QUICK_PICKS)]
}
// ── from/to stop picker ──────────────────────────────────────────────────────
@@ -228,8 +221,6 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
const [results, setResults] = useState<TransitPlaceResult[]>([])
const [open, setOpen] = useState(false)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
// Ignore lookups superseded by another query, a saved pick, or leaving this day.
const requestId = useRef(0)
const rootRef = useRef<HTMLDivElement>(null)
const fieldRef = useRef<HTMLDivElement>(null)
const listRef = useRef<HTMLDivElement>(null)
@@ -244,45 +235,21 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
return () => document.removeEventListener('mousedown', close)
}, [])
useEffect(() => () => {
requestId.current += 1
if (debounceRef.current) clearTimeout(debounceRef.current)
}, [])
useEffect(() => () => { if (debounceRef.current) clearTimeout(debounceRef.current) }, [])
const search = (q: string) => {
const id = ++requestId.current
setText(q)
setResults([])
onPick(null)
if (debounceRef.current) clearTimeout(debounceRef.current)
if (q.trim().length < 2) return
if (q.trim().length < 2) { setResults([]); return }
debounceRef.current = setTimeout(() => {
transitApi.geocode(q, { lang: language, near: near || undefined })
.then((d: { results: TransitPlaceResult[] }) => { if (id === requestId.current) setResults(d.results || []) })
.catch(() => { if (id === requestId.current) setResults([]) })
.then((d: { results: TransitPlaceResult[] }) => setResults(d.results || []))
.catch(() => setResults([]))
}, 300)
}
const display = value ? value.name : text
const query = text.trim().toLowerCase()
const saved = quickPicks.filter(p => p.name.toLowerCase().includes(query))
const seen = new Set(saved.map(pickedPlaceKey))
const external = results.filter(p => {
const key = pickedPlaceKey(p)
if (seen.has(key)) return false
seen.add(key)
return true
})
const suggestions: (PickedPlace & { area?: string | null })[] = value ? [] : [...saved, ...external]
const pick = (p: PickedPlace) => {
requestId.current += 1
if (debounceRef.current) clearTimeout(debounceRef.current)
onPick({ name: p.name, lat: p.lat, lng: p.lng })
setText('')
setResults([])
setOpen(false)
}
return (
<div ref={rootRef} style={{ position: 'relative', flex: 1, minWidth: 0 }}>
@@ -300,23 +267,34 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }}
/>
</div>
{open && listPos && suggestions.length > 0 && createPortal(
{open && listPos && (results.length > 0 || (!value && text.trim().length < 2 && quickPicks.length > 0)) && createPortal(
// On the page rather than inside the dialog, so a dialog that scrolls or clips
// its content cannot cut the list off before anything is typed.
<div ref={listRef} className="bg-surface-card border border-edge z-[var(--z-toast)]" style={{ position: 'fixed', left: listPos.left, width: listPos.width, ...(listPos.above ? { bottom: listPos.bottom } : { top: listPos.top }), borderRadius: 10, boxShadow: 'var(--shadow-dropdown)', overflow: 'hidden', maxHeight: listPos.maxHeight, overflowY: 'auto' }}>
{suggestions.map(r => (
<button type="button" key={pickedPlaceKey(r)} onClick={() => pick(r)}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{r.name}
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
</span>
</button>
))}
{results.length > 0
? results.map((r, i) => (
<button type="button" key={i} onClick={() => { onPick({ name: r.name, lat: r.lat, lng: r.lng }); setText(''); setResults([]); setOpen(false) }}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{r.name}
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
</span>
</button>
))
: quickPicks.map((p, i) => (
<button type="button" key={i} onClick={() => { onPick(p); setText(''); setOpen(false) }}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
</button>
))}
</div>,
document.body,
)}
@@ -1,684 +0,0 @@
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAssignment, buildDay, buildPlace, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { buildPlanner } from '../../../tests/helpers/mobileTrip';
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n';
import MTransportFormSheet from '../../mobile/screens/trip/sheets/MTransportFormSheet';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import type { Accommodation, AssignmentsMap, Day, Place } from '../../types';
import type { TransitPrefill } from './transitLeg';
import { TransportModal } from './TransportModal';
// Keep the real day selectors, wrappers and shared stop picker. Only the external
// geocoder is controlled: a saved private place need not exist in that service.
const { geocode, plan } = vi.hoisted(() => ({ geocode: vi.fn(), plan: vi.fn() }));
vi.mock('../../api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('../../api/client')>()),
transitApi: { geocode, plan },
}));
type Surface = 'desktop' | 'phone';
interface Fixture {
days: Day[];
places: Place[];
assignments: AssignmentsMap;
accommodations: Accommodation[];
transitPrefill?: TransitPrefill;
selectedDayId?: number;
}
function fixture(): Fixture {
const days = [
buildDay({ id: 101, trip_id: 1, day_number: 1, date: '2027-06-01', title: 'First day' }),
buildDay({ id: 205, trip_id: 1, day_number: 2, date: '2027-06-02', title: 'Second day' }),
buildDay({ id: 309, trip_id: 1, day_number: 3, date: '2027-06-03', title: 'Empty day' }),
];
const places = ['First private stop', 'Second private stop', 'Shared private stop'].map((name, i) =>
buildPlace({ id: 11 + i, trip_id: 1, name, lat: 52.5 + i / 100, lng: 13.4 })
);
const visit = (dayId: number, p: Place, order: number) =>
buildAssignment({ day_id: dayId, place_id: p.id, place: p, order_index: order });
return {
days,
places,
assignments: {
'101': [visit(101, places[0], 0), visit(101, places[2], 1)],
'205': [visit(205, places[1], 0), visit(205, places[2], 1)],
'309': [],
},
accommodations: [],
};
}
function buildStay(id: number, name: string, start: number, end: number): Accommodation {
return {
id,
trip_id: 1,
place_id: 1000 + id,
start_day_id: start,
end_day_id: end,
place_name: name,
place_lat: 52 + id / 1000,
place_lng: 13,
} as Accommodation;
}
function longTripFixture(): Fixture {
const days = Array.from({ length: 30 }, (_, i) =>
buildDay({
id: 5000 - i * 97,
trip_id: 1,
day_number: i + 1,
date: new Date(Date.UTC(2027, 2, i + 1)).toISOString().slice(0, 10),
title: `Day ${i + 1}`,
})
);
days[28] = { ...days[28], date: null };
const stay = (id: number, name: string, start: number, end: number) =>
buildStay(id, name, days[start - 1].id, days[end - 1].id);
const nearby = Array.from({ length: 4 }, (_, i) => [
stay(10 + i * 2, `Nearby before ${i + 1}`, 18 - i, 20 - i),
stay(11 + i * 2, `Nearby after ${i + 1}`, 22 + i, 24 + i),
]).flat();
return {
days,
places: [],
assignments: {},
selectedDayId: days[20].id,
accommodations: [
stay(1, 'First-week hotel created first', 1, 7),
stay(2, 'Undated hotel', 29, 30),
...nearby.slice().reverse(),
{ ...nearby[0], id: 99 },
stay(100, 'Morning hotel', 20, 21),
stay(101, 'Evening hotel', 21, 22),
...Array.from({ length: 10 }, (_, i) => stay(200 + i, `Current stay ${i + 1}`, 19, 23)),
],
};
}
function Harness({ surface, data }: { surface: Surface; data: Fixture }) {
const { t } = useTranslation();
if (surface === 'phone') {
const planner = buildPlanner({
t,
trip: buildTrip({ id: 1 }),
days: data.days,
places: data.places,
assignments: data.assignments,
storedAssignments: data.assignments,
tripAccommodations: data.accommodations,
showTransportModal: true,
transportModalDayId: data.selectedDayId ?? 101,
transportModalAutomated: true,
transitPrefill: data.transitPrefill ?? null,
});
return <MTransportFormSheet planner={planner} onOpenExpense={vi.fn()} />;
}
return (
<TransportModal
isOpen
onClose={vi.fn()}
onSave={vi.fn()}
reservation={null}
days={data.days}
selectedDayId={data.selectedDayId ?? 101}
initialAutomated
places={data.places}
assignments={data.assignments}
accommodations={data.accommodations}
transitPrefill={data.transitPrefill}
/>
);
}
const inputs = () => screen.getAllByPlaceholderText('Search stop or station…');
async function switchDay(user: ReturnType<typeof userEvent.setup>, current: string, next: string) {
await user.click(screen.getByText(current));
await user.click(screen.getByRole('button', { name: new RegExp(`^${next}`) }));
}
const pickNames = () => screen.queryAllByRole('button', { name: /private stop/ }).map((b) => b.textContent);
beforeEach(() => {
resetAllStores();
geocode.mockReset().mockResolvedValue({ results: [] });
plan.mockReset();
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), reservations: [] });
});
describe.each<Surface>(['desktop', 'phone'])('Automated transport day selection: %s', (surface) => {
beforeEach(() => {
Object.defineProperty(window, 'innerWidth', { configurable: true, value: surface === 'phone' ? 390 : 1440 });
fireEvent(window, new Event('resize'));
});
it('scopes both pickers by day id and keeps a shared place when switching back and forth', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[1]);
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
await switchDay(user, 'Second day', 'First day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
});
it('keeps all nine eligible day places available in the dropdown', async () => {
const user = userEvent.setup();
const data = fixture();
const stops = Array.from({ length: 9 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
data.places.push(...stops);
data.assignments['101'] = stops.map((p, i) =>
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
);
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.queryAllByRole('button', { name: /^Day stop/ }).map((b) => b.textContent)).toEqual(
stops.map((p) => p.name)
);
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
});
it('finds an assigned private place when the geocoder has no result', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await user.click(inputs()[0]);
await user.type(inputs()[0], 'First private');
await waitFor(() => expect(geocode).toHaveBeenCalled());
await act(async () => {
await Promise.resolve();
});
expect(screen.queryByRole('button', { name: 'First private stop' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
});
it('ranks matching saved places before external matches and deduplicates by name and both coordinates', async () => {
const user = userEvent.setup();
const data = fixture();
const saved = data.places[0];
const other = { name: 'External private stop', lat: 52.8, lng: 13.8, area: 'Berlin' };
geocode.mockResolvedValue({
results: [
other,
{ name: saved.name.toUpperCase(), lat: saved.lat, lng: saved.lng, area: 'Duplicate' },
{ ...other },
{ name: saved.name, lat: saved.lat, lng: 13.9, area: 'Other longitude' },
],
});
render(<Harness surface={surface} data={data} />);
await user.type(inputs()[0], 'private');
await screen.findByRole('button', { name: /External private stop/ });
const rows = screen.getAllByRole('button', { name: /private stop/i });
expect(rows.map((row) => row.textContent)).toEqual([
'First private stop',
'Shared private stop',
'External private stopBerlin',
'First private stopOther longitude',
]);
expect(geocode).toHaveBeenCalledTimes(1);
await user.click(rows[0]);
expect(inputs()[0]).toHaveValue(saved.name);
});
it('limits only other-day stays, keeping current hotels, terminals and every selected-day place first', async () => {
const user = userEvent.setup();
const data = fixture();
const stops = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
// A same-name stop at a different longitude must not be dropped as a duplicate.
stops.push(buildPlace({ id: 62, name: stops[0].name, lat: stops[0].lat, lng: 10 }));
data.places.push(...stops);
data.assignments['101'] = stops.map((p, i) =>
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
);
data.accommodations = Array.from(
{ length: 12 },
(_, i) =>
({
id: 70 + i,
trip_id: 1,
place_id: 70 + i,
start_day_id: i === 0 ? 101 : 205,
end_day_id: i === 0 ? 101 : 205,
place_name: i === 0 ? 'Current hotel' : `Other hotel ${i}`,
place_lat: 52 + i / 100,
place_lng: 13,
}) as Accommodation
);
// Duplicate stays must not consume another slot of the other-day allowance.
data.accommodations.splice(2, 0, { ...data.accommodations[1], id: 90 });
seedStore(useTripStore, {
reservations: [
{
id: 81,
trip_id: 1,
type: 'train',
day_id: 101,
end_day_id: 101,
endpoints: [{ role: 'from', name: 'Current terminal', lat: 52, lng: 13, local_date: '2027-06-01' }],
},
] as ReturnType<typeof useTripStore.getState>['reservations'],
});
render(<Harness surface={surface} data={data} />);
for (const input of inputs()) {
await user.click(input);
const rows = screen.getAllByRole('button', { name: /Current hotel|Current terminal|Day stop|Other hotel/ });
expect(rows.map((row) => row.textContent)).toEqual([
'Current hotel',
'Current terminal',
...stops.map((p) => p.name),
...Array.from({ length: 8 }, (_, i) => `Other hotel ${i + 1}`),
]);
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
}
});
it('keeps more than eight current-day hotels selectable and searchable despite earlier other-day stays', async () => {
const user = userEvent.setup();
const data = fixture();
const current = Array.from({ length: 12 }, (_, i) => buildStay(200 + i, `Current day hotel ${i + 1}`, 101, 101));
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Other day hotel ${i + 1}`, 205, 205));
data.accommodations = [
...other,
...current,
{ ...current[8], id: 999 },
{ ...buildStay(300, 'Unlocated current hotel', 101, 101), place_lat: null },
];
render(<Harness surface={surface} data={data} />);
for (const input of inputs()) {
await user.click(input);
expect(screen.getAllByRole('button', { name: /^Current day hotel/ }).map((b) => b.textContent)).toEqual(
current.map((a) => a.place_name)
);
expect(screen.getAllByRole('button', { name: /^Other day hotel/ }).map((b) => b.textContent)).toEqual(
other.slice(0, 8).map((a) => a.place_name)
);
expect(screen.queryByRole('button', { name: 'Unlocated current hotel' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
}
await user.type(inputs()[1], 'current day hotel 12');
await user.click(screen.getByRole('button', { name: 'Current day hotel 12' }));
expect(inputs()[1]).toHaveValue('Current day hotel 12');
});
it('offers Hotel 09 on Day 3 for the manual-review booking pattern without using mirrored day places', async () => {
const user = userEvent.setup();
const data = fixture();
const a = buildStay(1, 'Hotel A — first night', 101, 205);
const b = buildStay(2, 'Hotel B — second night', 205, 309);
const sameDay = Array.from({ length: 9 }, (_, i) =>
buildStay(3 + i, `Other night hotel ${String(i + 1).padStart(2, '0')}`, 309, 309)
);
data.accommodations = [a, b, ...sameDay];
// Days hides accommodation-owned mirror assignments: hotels must come from the stays themselves.
data.assignments['309'] = [];
render(<Harness surface={surface} data={data} />);
await switchDay(user, 'First day', 'Empty day');
for (const input of inputs()) {
await user.click(input);
expect(
screen.getAllByRole('button', { name: /Hotel A|Hotel B|Other night hotel/ }).map((row) => row.textContent)
).toEqual([b.place_name, ...sameDay.map((stay) => stay.place_name), a.place_name]);
}
await user.click(screen.getByRole('button', { name: 'Other night hotel 09' }));
expect(inputs()[1]).toHaveValue('Other night hotel 09');
});
it('keeps multi-night stays and checkout-day stays uncapped, with bookends before the other current stays', async () => {
const user = userEvent.setup();
const data = fixture();
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Future hotel ${i + 1}`, 309, 309));
const spanning = Array.from({ length: 10 }, (_, i) => buildStay(200 + i, `Multi-night hotel ${i + 1}`, 101, 309));
const checkout = buildStay(300, 'Checks out today', 101, 205);
const checkin = buildStay(301, 'Checks in today', 205, 309);
data.accommodations = [...other, ...spanning, checkout, checkin];
render(<Harness surface={surface} data={data} />);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(
screen
.getAllByRole('button', { name: /Multi-night hotel|Checks (in|out) today|Future hotel/ })
.map((row) => row.textContent)
).toEqual([
spanning[0].place_name,
checkin.place_name,
...spanning.slice(1).map((stay) => stay.place_name),
checkout.place_name,
...other.slice(0, 8).map((stay) => stay.place_name),
]);
expect(screen.queryByRole('button', { name: 'Future hotel 9' })).not.toBeInTheDocument();
});
it('does not let a first-week hotel take a Day 21 slot from eight closer stays on a 30-day trip', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={longTripFixture()} />);
for (const input of inputs()) {
await user.click(input);
expect(screen.queryByRole('button', { name: 'First-week hotel created first' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Undated hotel' })).not.toBeInTheDocument();
expect(
screen
.getAllByRole('button', { name: /Morning hotel|Evening hotel|Current stay|Nearby/ })
.map((row) => row.textContent)
).toEqual([
'Morning hotel',
'Evening hotel',
...Array.from({ length: 10 }, (_, i) => `Current stay ${i + 1}`),
...Array.from({ length: 4 }, (_, i) => [`Nearby before ${i + 1}`, `Nearby after ${i + 1}`]).flat(),
]);
}
});
it('puts undated stays last and orders identical dated intervals by stay id independently of input order', async () => {
const user = userEvent.setup();
const data = longTripFixture();
const dated = data.accommodations.find((stay) => stay.place_name === 'Nearby after 1');
if (!dated) throw new Error('Missing dated fixture');
const undated = data.accommodations.find((stay) => stay.place_name === 'Undated hotel');
if (!undated) throw new Error('Missing undated fixture');
data.accommodations = [
undated,
{ ...dated, id: 90, place_name: 'Same dates higher id', place_lng: 14 },
{ ...dated, id: 80, place_name: 'Same dates lower id', place_lng: 15 },
];
const view = render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
const names = () =>
screen.getAllByRole('button', { name: /Same dates|Undated hotel/ }).map((row) => row.textContent);
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
view.rerender(
<Harness surface={surface} data={{ ...data, accommodations: data.accommodations.slice().reverse() }} />
);
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
});
it('refreshes an open dropdown after places are added, removed and reordered', async () => {
const user = userEvent.setup();
const data = fixture();
const view = render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
const added = buildPlace({ id: 99, name: 'Added private stop' });
const next = {
...data,
places: [...data.places, added],
assignments: {
...data.assignments,
'101': [
{ ...data.assignments['101'][1], order_index: 2 },
buildAssignment({ day_id: 101, place_id: added.id, place: added, order_index: 0 }),
],
},
};
view.rerender(<Harness surface={surface} data={next} />);
expect(pickNames()).toEqual(['Added private stop', 'Shared private stop']);
});
it('keeps place membership tied to ids when days and their dates are reordered', async () => {
const user = userEvent.setup();
const data = fixture();
const view = render(<Harness surface={surface} data={data} />);
const reordered = {
...data,
days: [
{ ...data.days[1], day_number: 1, date: data.days[0].date },
{ ...data.days[0], day_number: 2, date: data.days[1].date },
data.days[2],
],
};
view.rerender(<Harness surface={surface} data={reordered} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
});
it('does not retain endpoints from an unrelated day after selecting from and to', async () => {
const user = userEvent.setup();
const data = fixture();
// Make the first day's two endpoints exclusive to that day.
data.assignments['205'] = [data.assignments['205'][0]];
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
await user.click(screen.getByRole('button', { name: 'First private stop' }));
await user.click(inputs()[1]);
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
await switchDay(user, 'First day', 'Second day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('clears search state when changing days so the next day offers its own places', async () => {
const user = userEvent.setup();
geocode.mockResolvedValue({ results: [{ name: 'Old external station', lat: 52, lng: 13, area: null }] });
render(<Harness surface={surface} data={fixture()} />);
await user.type(inputs()[0], 'Old station');
await screen.findByRole('button', { name: 'Old external station' });
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(screen.queryByRole('button', { name: 'Old external station' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('scopes day-plan endpoint, time and walk prefills to the opening day', async () => {
const user = userEvent.setup();
const data = fixture();
data.transitPrefill = {
from: { name: 'Walk end', lat: 52.5, lng: 13.4 },
to: { name: 'Next walk start', lat: 52.6, lng: 13.5 },
time: '12:15',
walk: {
dayId: 101,
fromWalk: 'Old town',
toWalk: 'Harbour',
ends: '12:15',
endsNextDay: false,
endsAtLeast: false,
nextStarts: '13:00',
},
};
render(<Harness surface={surface} data={data} />);
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
expect(screen.getByDisplayValue('12:15')).toBeInTheDocument();
await switchDay(user, 'First day', 'Second day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
expect(screen.queryByTestId('transit-walk-end')).not.toBeInTheDocument();
expect(screen.queryByDisplayValue('12:15')).not.toBeInTheDocument();
await switchDay(user, 'Second day', 'First day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
});
it('drops old itineraries when changing the day', async () => {
const user = userEvent.setup();
const data = fixture();
const stop = (name: string, time: string) => ({
name,
lat: 52.5,
lng: 13.4,
time,
scheduledTime: null,
track: null,
});
plan.mockResolvedValue({
itineraries: [
{
startTime: '2027-06-01T07:00:00Z',
endTime: '2027-06-01T07:30:00Z',
duration: 1800,
transfers: 0,
walkSeconds: 0,
legs: [
{
mode: 'SUBWAY',
from: stop('A', '2027-06-01T07:00:00Z'),
to: stop('B', '2027-06-01T07:30:00Z'),
duration: 1800,
distance: null,
headsign: null,
line: 'U88',
lineColor: null,
lineTextColor: null,
agency: null,
intermediateStops: 0,
},
],
},
],
});
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
await user.click(screen.getByRole('button', { name: 'First private stop' }));
await user.click(inputs()[1]);
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
await user.click(screen.getByRole('button', { name: /^Search$/ }));
await screen.findByText('U88');
await switchDay(user, 'First day', 'Second day');
expect(screen.queryByText('U88')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Add to day' })).not.toBeInTheDocument();
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('ignores an old geocoder response after the day changes', async () => {
const user = userEvent.setup();
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
throw new Error('lookup not started');
};
geocode.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
})
);
render(<Harness surface={surface} data={fixture()} />);
await user.type(inputs()[0], 'Old station');
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
await act(async () => {
finish({ results: [{ name: 'Late old station', lat: 52, lng: 13, area: null }] });
});
expect(screen.queryByRole('button', { name: 'Late old station' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
expect(inputs()[0]).toHaveValue('');
});
it('keeps the newest search results when an older lookup answers last', async () => {
type Answer = { results: { name: string; lat: number; lng: number; area: null }[] };
const pending: ((value: Answer) => void)[] = [];
geocode.mockImplementation(() => new Promise<Answer>((resolve) => pending.push(resolve)));
render(<Harness surface={surface} data={fixture()} />);
fireEvent.focus(inputs()[0]);
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
fireEvent.change(inputs()[0], { target: { value: 'New' } });
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(2));
await act(async () => {
pending[1]({ results: [{ name: 'New station', lat: 52.5, lng: 13.4, area: null }] });
});
await act(async () => {
pending[0]({ results: [{ name: 'Old station', lat: 52.6, lng: 13.5, area: null }] });
});
expect(screen.getByRole('button', { name: 'New station' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Old station' })).not.toBeInTheDocument();
});
it('ignores a superseded geocoder response after a saved place is picked', async () => {
const user = userEvent.setup();
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
throw new Error('lookup not started');
};
geocode.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
})
);
render(<Harness surface={surface} data={fixture()} />);
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
fireEvent.change(inputs()[0], { target: { value: 'First private' } });
fireEvent.focus(inputs()[0]);
fireEvent.click(screen.getByRole('button', { name: 'First private stop' }));
await act(async () => {
finish({ results: [{ name: 'Superseded station', lat: 52, lng: 13, area: null }] });
});
await user.clear(inputs()[0]);
expect(screen.queryByRole('button', { name: 'Superseded station' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
expect(geocode).toHaveBeenCalledTimes(1);
});
it('offers no unrelated regular places on an empty day', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await switchDay(user, 'First day', 'Empty day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual([]);
});
it('offers the active stay and other trip stays intentionally, even on a booking-only day', async () => {
const user = userEvent.setup();
const data = fixture();
data.assignments['101'] = [];
const stay = (id: number, name: string, dayId: number): Accommodation =>
({
id,
trip_id: 1,
place_id: id,
start_day_id: dayId,
end_day_id: dayId,
place_name: name,
place_lat: 52 + id / 100,
place_lng: 13,
}) as Accommodation;
data.accommodations = [stay(70, 'Current hotel', 101), stay(71, 'Later hotel', 205)];
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'Current hotel' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Later hotel' })).toBeInTheDocument();
expect(pickNames()).toEqual([]);
});
it('offers only the selected day transport terminals on a transport-only day', async () => {
const user = userEvent.setup();
const data = fixture();
data.assignments['101'] = [];
const endpoint = (role: 'from' | 'to', name: string, date: string) => ({
role,
name,
lat: 52,
lng: 13,
local_date: date,
});
seedStore(useTripStore, {
reservations: [
{
id: 81,
trip_id: 1,
type: 'train',
day_id: 101,
end_day_id: 205,
endpoints: [
endpoint('from', 'First terminal', '2027-06-01'),
endpoint('to', 'Second terminal', '2027-06-02'),
],
},
] as ReturnType<typeof useTripStore.getState>['reservations'],
});
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'First terminal' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second terminal' })).not.toBeInTheDocument();
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'Second terminal' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'First terminal' })).not.toBeInTheDocument();
});
});
@@ -12,7 +12,7 @@ import { toLocationPicks } from './locationPicks'
import { useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
import { useTripStore } from '../../store/tripStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import { useAddonStore } from '../../store/addonStore'
import type { Day, Place, Accommodation, Reservation, TripFile, AssignmentsMap } from '../../types'
import { BookingNotesFilesCosts } from './BookingNotesFilesCosts'
import { TravelerPicker } from './TravelerPicker'
@@ -20,7 +20,6 @@ import type { TripMember } from '../Budget/BudgetPanelMemberChips'
import type { BookingExpenseRequest } from './BookingCostsSection.types'
import type { BookingReviewDraft } from './parsedItemToDraft'
import TransitSearchPanel from './TransitSearchPanel'
import { getTransitDayPlaces } from './transitDayPlaces'
import type { TransitPrefill } from './transitLeg'
import { BookingDialogHeader, StatusPill } from './bookings/BookingDialogShell'
import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton } from '../shared/DialogShell'
@@ -83,10 +82,10 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
const toast = useToast()
// The trip's places, offered by every location field of the manual tab (#2468).
const locationPicks = useMemo(() => toLocationPicks(places), [places])
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
const budgetItems = useTripStore(s => s.budgetItems)
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
const { id: tripId } = useParams<{ id: string }>()
const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')
// Set right before submitting when the user clicked "create/edit expense", so
// the post-save handler knows to open the Costs editor for the saved booking.
const expense = useBookingExpenseIntent(() => handleSubmit(), {
@@ -288,20 +287,22 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
const transitSearch = () => {
const transitDay = days.find(d => d.id === Number(form.start_day_id))
if (!transitDay) return <p className="m-0 text-content-faint" style={fs(13, 'body')}>{t('transit.pickDay')}</p>
const dayPlaces = getTransitDayPlaces(transitDay.id, assignments, places)
const dayPrefill = transitDay.id === selectedDayId ? transitPrefill : null
// Quick picks offer the chosen day's itinerary, not the whole trip (#1460).
const dayPlaces = (assignments[String(transitDay.id)] || [])
.slice().sort((a, b) => a.order_index - b.order_index)
.map(a => places.find(p => p.id === a.place_id))
.filter((p): p is Place => p != null)
return (
<TransitSearchPanel
key={transitDay.id}
day={transitDay}
days={days}
places={dayPlaces}
accommodations={accommodations}
onAdd={(payload) => onSave(payload as Record<string, any> & { title: string })}
initialFrom={dayPrefill?.from ?? null}
initialTo={dayPrefill?.to ?? null}
initialTime={dayPrefill?.time ?? null}
walk={dayPrefill?.walk ?? null}
initialFrom={transitPrefill?.from ?? null}
initialTo={transitPrefill?.to ?? null}
initialTime={transitPrefill?.time ?? null}
walk={transitPrefill?.walk ?? null}
/>
)
}
@@ -118,19 +118,6 @@ describe('BookingDetailDialog', () => {
expect(screen.getByText('#SEG2')).toBeInTheDocument();
});
it('FE-PLANNER-BKDETAIL-015: a flight with a stop shows the seat booked on its second leg, once, under that leg', () => {
const r = buildReservation({
title: 'MXP to JFK', type: 'flight',
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
});
renderDetail(r);
const dialog = screen.getByRole('dialog', { name: 'MXP to JFK' });
expect(within(dialog).getByText('14C')).toBeInTheDocument();
expect(within(dialog).getByText('Seat IST → JFK')).toBeInTheDocument();
// The tile stands for it; the field grid does not repeat it.
expect(within(dialog).queryByText('14C, Economy')).toBeNull();
});
it('FE-PLANNER-BKDETAIL-006: place, accommodation, linked stop, link, travelers and notes', () => {
const place = buildPlace({ name: 'Kinkaku-ji', place_time: '10:00' });
const a = buildAssignment({ id: 4401, day_id: 1302, place });
@@ -27,7 +27,7 @@ import { BookingDialogHeader, StatusPill, TypePill } from './BookingDialogShell'
import { DeleteButton, DialogButton, DialogFooter, DialogSection as Section, DialogShell, FooterSpacer, PILL } from '../../shared/DialogShell'
import FlightLiveCard from '../flightLive/FlightLiveCard'
import { useFlightLiveCardLegs } from '../flightLive/useFlightLiveCard'
import { bookingSeats, getFlightLegs, seatLabel } from '../../../utils/flightLegs'
import { getFlightLegs } from '../../../utils/flightLegs'
export interface BookingDetailDialogProps {
r: Reservation
@@ -84,7 +84,6 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
const subParts = [meta.airline, meta.flight_number, meta.train_number, facts.endpoints.length >= 2 ? facts.endpoints.map(e => e.code || e.name).join(' → ') : null].filter(Boolean)
const sub = subParts.length ? subParts.join(' ') : null
const seats = bookingSeats(r)
const stats: { value: string; label: string }[] = []
if (facts.isHotel) {
stats.push(...stayStats(facts, meta, t, locale))
@@ -101,8 +100,7 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
// Under a minute of walking is not worth a tile.
if (transit && transit.walk > 59) stats.push({ value: t('transit.min', { count: Math.round(transit.walk / 60) }), label: t('transit.walkLabel') })
if (meta.platform) stats.push({ value: meta.platform, label: t('reservations.meta.platform') })
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
for (const s of seats) stats.push({ value: s.seat, label: seatLabel(t('reservations.meta.seat'), s.route) })
if (meta.seat) stats.push({ value: meta.seat, label: t('reservations.meta.seat') })
}
// Cells already shown as a stat stay out of the field grid below.
const shownAsStat = new Set([t('reservations.meta.platform'), t('reservations.meta.seat'), t('reservations.meta.checkIn'), t('reservations.meta.checkOut')])
@@ -4,7 +4,6 @@ import type { Reservation } from '../../../types'
import { useTranslation } from '../../../i18n'
import { BlurredCode } from '../../shared/BookingCode'
import { formatMoney } from '../../../utils/formatters'
import { bookingSeats } from '../../../utils/flightLegs'
import { TransitLegChips } from '../transitDisplay'
import { displayTitle, parseMeta, type BookingGroup, type CostTotal } from './bookingsModel'
import type { BookingFacts } from './bookingFacts'
@@ -83,7 +82,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
const sub = facts.endpoints.length >= 2
? facts.endpoints.map(e => e.code || e.name).join(' → ')
: facts.accommodation || facts.place || ''
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, ...bookingSeats(r).map(s => s.seat), meta.platform].filter(Boolean)
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, meta.seat, meta.platform].filter(Boolean)
return (
<div
@@ -231,14 +231,3 @@ describe('bookingFacts: codes, links and places', () => {
expect(bookingFacts(buildReservation({ url: 'javascript:alert(1)' }), ctx()).url?.href).toBeNull();
});
});
describe('bookingFacts: seats of a flight with a stop', () => {
it('FE-PLANNER-BKFACTS-025: the Seat cell holds the seat booked only on the second leg', () => {
const r = buildReservation({
type: 'flight',
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
});
const facts = bookingFacts(r, ctx());
expect(cell(facts, 'reservations.meta.seat')).toBe('14C, Economy');
});
});
@@ -1,8 +1,8 @@
import type { Day, Reservation, ReservationEndpoint } from '../../../types'
import { formatPriceText, formatTime, splitReservationDateTime } from '../../../utils/formatters'
import { getFlightLegs, getTrainLegs, seatCells, usesStationRoute } from '../../../utils/flightLegs'
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../../utils/flightLegs'
import { safeExternalHref } from '../../../utils/safeUrl'
import { bookingDates, daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
import { daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
export interface FactsContext {
t: (key: string, params?: Record<string, string | number>) => string
@@ -84,7 +84,6 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
const eps = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
const from = eps.find(e => e.role === 'from')
const to = eps.find(e => e.role === 'to')
const dates = bookingDates(r, c.days)
const startTime = startDt.time || from?.local_time || null
const endTime = endDt.time || to?.local_time || null
// A stay backed by an accommodation says its times as check-in and check-out;
@@ -102,8 +101,7 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
if (!hasEndpoints && meta.arrival_airport) cells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
if (meta.train_number) cells.push({ label: t('reservations.meta.trainNumber'), value: meta.train_number })
if (meta.platform) cells.push({ label: t('reservations.meta.platform'), value: meta.platform })
// One seat per leg on a booking with a stop, each under its route; otherwise the booking's own.
cells.push(...seatCells(r, t('reservations.meta.seat'), meta.class ? `, ${meta.class}` : ''))
if (meta.seat) cells.push({ label: t('reservations.meta.seat'), value: meta.class ? `${meta.seat}, ${meta.class}` : meta.seat })
if (!c.hasLinkedCost && meta.price != null && meta.price !== '') {
cells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, c.tripCurrency, locale) })
}
@@ -126,8 +124,8 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
return {
day, time, startTime, endTime,
startDate: dates.start,
endDate: dates.end,
startDate: startDt.date || from?.local_date || span.start?.date || null,
endDate: endDt.date || to?.local_date || span.end?.date || null,
cells, endpoints: eps.length >= 2 ? eps : [], legCodes,
place: r.location || r.place_name || null,
accommodation: r.accommodation_name || null,
@@ -132,23 +132,6 @@ export function daySpan(r: Reservation, days: Day[]): DaySpan {
return { start: byId(r.day_id), end: byId(r.end_day_id) }
}
/**
* The calendar dates a booking starts and ends on, as "YYYY-MM-DD", or null where it
* knows none: its own date first, then the local date of its first or last stop,
* then the date of the day it is linked to. A day-linked transport often carries
* only times, so its day stands in.
*/
export function bookingDates(r: Reservation, days: Day[]): { start: string | null; end: string | null } {
const span = daySpan(r, days)
const eps = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
const from = eps.find(e => e.role === 'from')
const to = eps.find(e => e.role === 'to')
return {
start: splitReservationDateTime(r.reservation_time).date || from?.local_date || span.start?.date || null,
end: splitReservationDateTime(r.reservation_end_time).date || to?.local_date || span.end?.date || null,
}
}
/**
* The moment a booking starts, as "YYYY-MM-DDTHH:MM" in its own local time, or null
* without any date. A day-linked transport often carries no date in reservation_time,
@@ -54,14 +54,6 @@ describe('TransitLegs', () => {
expect(screen.getByText('BVG')).toBeInTheDocument();
});
it('FE-PLANNER-BKTRANSIT-009: stop names and a walk target wrap instead of being cut off (#3139)', () => {
render(<TransitLegs legs={[ride, walk]} compact />);
for (const text of ['Alexanderplatz', 'Eberswalder Str.', 'Walk to Mauerpark']) {
expect(screen.getByText(text)).not.toHaveClass('truncate');
expect(screen.getByText(text)).toHaveClass('break-words');
}
});
it('FE-PLANNER-BKTRANSIT-006: a walk reads as one and leaves out the ride facts', () => {
render(<TransitLegs legs={[walk]} compact />);
expect(screen.getByText('Walk to Mauerpark')).toBeInTheDocument();
@@ -48,11 +48,9 @@ export function TransitLegs({ legs, compact = false }: { legs: TransitLegDisplay
}}>{leg.line || leg.mode}</span>
)}
<div className={`flex min-w-0 flex-1 flex-col ${compact ? 'gap-1' : 'gap-1.5'}`}>
{/* Detail views show a stop name whole: the names wrap and the
arrow moves to the next line with them when it has to (#3139). */}
<div className="flex min-w-0 flex-wrap items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
{walk ? <span className="min-w-0 break-words text-content-muted [overflow-wrap:anywhere]">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
<><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span></>
<div className="flex min-w-0 items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
{walk ? <span className="truncate text-content-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
<><span className="truncate">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span className="truncate">{leg.to?.name}</span></>
)}
</div>
<TransitMetaBadges size={compact ? 'sm' : 'md'} items={[
@@ -1,10 +0,0 @@
import type { AssignmentsMap, Place } from '../../types';
/** Resolve the chosen day's places by day id, in itinerary order (#1460). */
export function getTransitDayPlaces(dayId: number, assignments: AssignmentsMap, places: Place[]): Place[] {
return (assignments[String(dayId)] ?? [])
.slice()
.sort((a, b) => a.order_index - b.order_index)
.map((a) => places.find((p) => p.id === a.place_id))
.filter((p): p is Place => p != null);
}
@@ -1,47 +0,0 @@
// FE-PLANNER-TRANSITDISPLAY-001 to FE-PLANNER-TRANSITDISPLAY-003
import { describe, expect, it } from 'vitest';
import { render, screen } from '../../../tests/helpers/render';
import type { TransitLegDisplay } from './transitDisplay';
import { TransitItineraryInline, TransitWalkDivider } from './transitDisplay';
const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}:${Object.values(params).join(',')}` : key;
const ride: TransitLegDisplay = {
mode: 'RAIL',
line: 'XC',
duration: 1260,
from: { name: 'Basingstoke', time: '12:48' },
to: { name: 'Reading', time: '13:09' },
};
const walk: TransitLegDisplay = { mode: 'WALK', duration: 240, to: { name: 'Reading station, Station Approach' } };
/** Whether a rendered element clips its text to one line. */
function clipsToOneLine(el: HTMLElement): boolean {
return el.style.whiteSpace === 'nowrap' || el.style.textOverflow === 'ellipsis';
}
describe('TransitItineraryInline (#3139)', () => {
it('FE-PLANNER-TRANSITDISPLAY-001: a ride shows both stop names in full', () => {
render(<TransitItineraryInline legs={[ride]} t={t} />);
for (const name of ['Basingstoke', 'Reading']) {
const el = screen.getByText(name);
expect(clipsToOneLine(el)).toBe(false);
expect(el.style.overflowWrap).toBe('anywhere');
}
});
it('FE-PLANNER-TRANSITDISPLAY-002: a ride shows its arrival time under its departure', () => {
render(<TransitItineraryInline legs={[ride, { ...ride, to: { name: 'Oxford' } }]} t={t} />);
expect(screen.getByText('13:09')).toBeInTheDocument();
expect(screen.getAllByText('12:48')).toHaveLength(2);
});
});
describe('TransitWalkDivider (#3139)', () => {
it('FE-PLANNER-TRANSITDISPLAY-003: the walk target wraps instead of being cut off', () => {
render(<TransitWalkDivider leg={walk} t={t} size="sm" />);
const text = screen.getByText(/transit\.walkTo:Reading station, Station Approach/);
expect(clipsToOneLine(text)).toBe(false);
});
});
@@ -41,14 +41,14 @@ export function TransitWalkDivider({ leg, t, size = 'md' }: {
background: `linear-gradient(to ${dir}, var(--text-faint), transparent)`,
opacity: 0.55,
})
// On phones the minutes lead, so they stay on the first line when a long stop name wraps.
// On phones the minutes lead so a long stop name only ever clips the name.
const text = isMobile
? `${mins ? `${t('transit.min', { count: mins })} · ` : ''}${t('transit.walkTo', { name: leg.to?.name || '' })}`
: `${t('transit.walkTo', { name: leg.to?.name || '' })}${mins ? ` · ${t('transit.min', { count: mins })}` : ''}`
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: size === 'sm' ? '1px 0' : '2px 0' }}>
<span style={rule('left')} />
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, textAlign: 'center', overflowWrap: 'anywhere', maxWidth: isMobile ? '85%' : '75%' }}>
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: isMobile ? '85%' : '75%' }}>
<Footprints size={size === 'sm' ? 11 : 12} style={{ flexShrink: 0 }} />
{text}
</span>
@@ -72,10 +72,8 @@ export function TransitItineraryInline({ legs, t }: {
const mins = leg.duration ? Math.round(leg.duration / 60) : null
return (
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
{/* Departure beside the stops, arrival under it (#3139). */}
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
<span>{leg.from?.time || ''}</span>
{leg.to?.time && <span className="text-content-faint">{leg.to.time}</span>}
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
{leg.from?.time || ''}
</span>
<span style={{
display: 'inline-flex', alignItems: 'center', borderRadius: 4, padding: '0 5px',
@@ -86,11 +84,10 @@ export function TransitItineraryInline({ legs, t }: {
{leg.line || leg.mode}
</span>
<div style={{ flex: 1, minWidth: 0 }}>
{/* The folded-out itinerary is where a journey is read in full: stop names wrap (#3139). */}
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: 4, minWidth: 0 }}>
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.from?.name}</span>
<MoveRight size={10} className="text-content-faint" style={{ flexShrink: 0 }} />
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.to?.name}</span>
</div>
<div className="text-content-faint" style={{ fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', marginTop: 1 }}>
{[
@@ -1,89 +0,0 @@
import { describe, expect, it } from 'vitest';
import { buildDay } from '../../../tests/helpers/factories';
import type { Accommodation } from '../../types';
import { orderTransitStaysByDate } from './transitStayOrder';
const day = buildDay({ id: 500, date: '2027-03-21', day_number: 21 });
const stay = (id: number, start: number, end = start) =>
({ id, start_day_id: start, end_day_id: end }) as Accommodation;
const refs = [
buildDay({ id: 900, date: '2027-03-01', day_number: 1 }),
buildDay({ id: 700, date: '2027-03-19', day_number: 19 }),
buildDay({ id: 600, date: '2027-03-20', day_number: 20 }),
day,
buildDay({ id: 400, date: '2027-03-22', day_number: 22 }),
buildDay({ id: 300, date: '2027-03-23', day_number: 23 }),
];
const ids = (stays: Accommodation[]) => stays.map((a) => a.id);
describe('orderTransitStaysByDate', () => {
it('uses the whole interval: an early check-in with a nearby checkout is close', () => {
const spanning = stay(1, 900, 600);
const future = stay(2, 400, 300);
const farther = stay(3, 700);
expect(ids(orderTransitStaysByDate(day, refs, [farther, future, spanning]))).toEqual([1, 2, 3]);
});
it('puts the earlier interval first at equal distance, then earlier checkout and stable stay id', () => {
const list = [stay(90, 400, 300), stay(2, 600), stay(80, 400, 300), stay(100, 400)];
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 100, 80, 90]);
expect(ids(orderTransitStaysByDate(day, refs, list.slice().reverse()))).toEqual([2, 100, 80, 90]);
});
it('places missing, incomplete and invalid calendar dates after dated stays', () => {
const dates = [
...refs,
buildDay({ id: 10, date: null }),
buildDay({ id: 11, date: '2027-02-30' }),
buildDay({ id: 12, date: 'not-a-date' }),
];
const list = [stay(4, 10), stay(3, 11), stay(2, 12), stay(5, 600, 10), stay(6, 99999), stay(9, 900)];
expect(ids(orderTransitStaysByDate(day, dates, list))).toEqual([9, 2, 3, 4, 5, 6]);
});
it('handles leap days without accepting a normalized invalid date', () => {
const selected = buildDay({ id: 1, date: '2028-03-01' });
const dates = [selected, buildDay({ id: 2, date: '2028-02-29' }), buildDay({ id: 3, date: '2027-02-29' })];
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
});
it('uses updated calendar dates after days are reordered, regardless of array order or numeric ids', () => {
const before = stay(1, 600);
const after = stay(2, 400);
const reordered = refs
.map((d) =>
d.id === 600
? { ...d, date: '2027-03-22', day_number: 22 }
: d.id === 400
? { ...d, date: '2027-03-20', day_number: 20 }
: d
)
.reverse();
expect(ids(orderTransitStaysByDate(day, refs, [after, before]))).toEqual([1, 2]);
expect(ids(orderTransitStaysByDate(day, reordered, [before, after]))).toEqual([2, 1]);
});
it('counts calendar nights equally across the spring DST boundary', () => {
const selected = buildDay({ id: 1, date: '2027-03-29' });
const dates = [selected, buildDay({ id: 2, date: '2027-03-28' }), buildDay({ id: 3, date: '2027-03-30' })];
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
});
it('normalizes reversed interval endpoints consistently with day-range membership', () => {
expect(ids(orderTransitStaysByDate(day, refs, [stay(1, 700), stay(2, 300, 600)]))).toEqual([2, 1]);
});
it('keeps dated stays ahead of undated ones when the selected day has no usable date', () => {
const selected = { ...day, date: null };
expect(ids(orderTransitStaysByDate(selected, refs, [stay(1, 99999), stay(3, 300), stay(2, 900)]))).toEqual([
2, 3, 1,
]);
});
it('does not mutate the caller list', () => {
const list = Object.freeze([stay(1, 300), stay(2, 600)]);
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 1]);
expect(ids([...list])).toEqual([1, 2]);
});
});
@@ -1,37 +0,0 @@
import type { Accommodation, Day } from '../../types';
/** A strict calendar date as a UTC day number, so DST never changes the number of nights. */
function nightNumber(value: string | null | undefined): number | null {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const time = Date.parse(`${value}T00:00:00Z`);
if (!Number.isFinite(time) || new Date(time).toISOString().slice(0, 10) !== value) return null;
return time / 86_400_000;
}
/** Rank other-day stays by the closest boundary of their complete booking interval. */
export function orderTransitStaysByDate(
day: Pick<Day, 'date'>,
days: readonly Pick<Day, 'id' | 'date'>[],
stays: readonly Accommodation[]
): Accommodation[] {
const selected = nightNumber(day.date);
const dates = new Map(days.map((d) => [d.id, nightNumber(d.date)]));
return stays
.map((stay) => {
const start = dates.get(stay.start_day_id);
const end = dates.get(stay.end_day_id);
// A partial or invalid interval has no usable proximity and follows every dated stay.
const lo = start != null && end != null ? Math.min(start, end) : Infinity;
const hi = start != null && end != null ? Math.max(start, end) : Infinity;
const distance = selected != null && lo !== Infinity ? Math.max(lo - selected, selected - hi, 0) : Infinity;
// Earlier check-in, then earlier check-out, then stable booking identity break ties.
return { stay, rank: [distance, lo, hi, stay.id] };
})
.sort((a, b) => {
for (let i = 0; i < a.rank.length; i++) {
if (a.rank[i] !== b.rank[i]) return a.rank[i] < b.rank[i] ? -1 : 1;
}
return 0;
})
.map((row) => row.stay);
}
@@ -1,12 +1,11 @@
// FE-PLANNER-TRIPEXPORT-001 to -015: the trip exports behind the desktop export
// FE-PLANNER-TRIPEXPORT-001 to -014: the trip exports behind the desktop export
// dialog and the phone's export sheet.
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import { buildAssignment, buildReservation, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { useTripAddonsStore } from '../../store/tripAddonsStore';
import type { DayNote } from '../../types';
import { downloadTripPDF } from '../PDF/TripPDF';
import { flatDayNotes, saveBlob, useTripExport, type TripExportOptions } from './useTripExport';
@@ -134,17 +133,6 @@ describe('useTripExport', () => {
expect(vi.mocked(downloadTripPDF).mock.calls[1][0]).toMatchObject({ onlyUserId: 9 });
});
it('FE-PLANNER-TRIPEXPORT-015: the PDF prints costs and tours as the trip has them, not the instance', async () => {
seedInstanceAddons(['budget']);
useTripAddonsStore.getState().publish(3, [
{ id: 'budget', name: 'Costs', icon: null, enabled: false, instanceEnabled: true, overridden: true },
{ id: 'tours', name: 'Tours', icon: null, enabled: true, instanceEnabled: false, overridden: true },
]);
const { result } = renderHook(() => useTripExport(options()));
await act(() => result.current.exportPdf());
expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({ costsEnabled: false, toursEnabled: true });
});
it('FE-PLANNER-TRIPEXPORT-005: the phone stays open after the PDF and prints nothing without a trip', async () => {
const opts = options(PHONE);
const { result } = renderHook(() => useTripExport(opts));
@@ -3,7 +3,6 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
import type { AssignmentsMap, Category, Day, DayNote, Place, Reservation, Trip } from '../../types';
import { importChunk } from '../../utils/chunkReload';
import type { ViasByDay } from '../../utils/dayRouteVias';
@@ -145,9 +144,6 @@ export function useTripExport({
// them, so it needs the same switch the plan reads.
const showServiceStops = useRoadtripSettings((s) => s.roadtrip_service_stops_in_days !== false, tripId);
const myId = useAuthStore((s) => s.user?.id);
// The sections the trip has on, as the plan shows them: costs in the figures, tours on the route.
const costsEnabled = useTripAddonEnabled(tripId, 'budget');
const toursEnabled = useTripAddonEnabled(tripId, 'tours');
const offerMine = myId != null && hasPersonalPlan(data.assignments, data.reservations);
const fileBase = data.trip?.title || 'trip';
@@ -189,8 +185,6 @@ export function useTripExport({
timeFormat,
distanceUnit,
showServiceStops,
costsEnabled,
toursEnabled,
onlyUserId: mine ? myId : undefined,
route: { viasByDay: data.viasByDay, tourStageStops: data.tourStageStops, ...routing },
signal: givenUp,
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest'
import { dayColor } from './dayColors'
import { stageConnectionIds, stageMapData, stagePlaceIds, stagePoints } from './stageMap'
import { stageMapData, stagePlaceIds, stagePoints } from './stageMap'
import type { AccessSpur, RoadtripDay, RoadtripRoutes, RoadtripStop } from '@trek/shared/roadtrip'
// FE-RTSTAGE-001 to FE-RTSTAGE-023
// FE-RTSTAGE-001 to FE-RTSTAGE-021
function stop(name: string, over: Partial<RoadtripStop> = {}): RoadtripStop {
return {
@@ -125,15 +125,14 @@ describe('stageMapData with a stage', () => {
expect(stageMapData(routes(), stage, true).lines).toEqual([LINES[1], LINES[2]])
})
it('FE-RTSTAGE-016: the drive in from the day before is left off the stage', () => {
// With "connect the days" on, that leg is drawn as the day it arrives on (#3123), so
it('FE-RTSTAGE-016: the drive into the next day is left off the stage', () => {
// With "connect the days" on, that leg is drawn in the colour of the day it leaves, so
// filtering by day number alone handed the stage a line running off it to a place the
// day never visits. On a phone, where the stage IS the map, it was the longest thing
// on screen and read as the day's own route. The assembler emits it first among the
// lines of the day it reaches, ahead of that day's own legs.
const withJoin = routes({ lineJoins: [false, true, false, false] })
// on screen and read as the day's own route.
const withJoin = routes({ lineJoins: [false, false, true, false] })
expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[2]])
expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[1]])
})
it('FE-RTSTAGE-020: a day that is nothing but driving keeps its connection rather than going blank', () => {
@@ -145,7 +144,7 @@ describe('stageMapData with a stage', () => {
})
it('FE-RTSTAGE-017: the colours still line up once a join has been dropped', () => {
const data = stageMapData(routes({ lineJoins: [false, true, false, false] }), stage, true)
const data = stageMapData(routes({ lineJoins: [false, false, true, false] }), stage, true)
expect(data.lineColors).toHaveLength(data.lines.length)
expect(data.lineColors).toEqual([dayColor(2)])
@@ -154,7 +153,7 @@ describe('stageMapData with a stage', () => {
it('FE-RTSTAGE-018: the all-days view keeps the joins, which is the view they are for', () => {
// The setting draws the whole drive as one connected line; that is what it is for, and
// on this map the connection has the other days beside it.
expect(stageMapData(routes({ lineJoins: [false, true, false, false] }), null, true).lines).toEqual(LINES)
expect(stageMapData(routes({ lineJoins: [false, false, true, false] }), null, true).lines).toEqual(LINES)
})
it('FE-RTSTAGE-019: routes from before the flag existed are drawn as they were', () => {
@@ -268,23 +267,3 @@ describe('a stage that starts or ends at a booked night', () => {
expect(data.accessLines).toEqual([walk])
})
})
describe('stageConnectionIds', () => {
const flight = (reservationId: number, role: 'arrival' | 'departure') =>
stop('Airport', { carrier: { reservationId, type: 'flight', role, title: 'Flight', code: null, at: null } })
it("FE-RTSTAGE-022: a stage draws its own rides, not the drive's ride home from a later day", () => {
// The flight in (31) seams this stage; the flight home (32) belongs to a stage days later
// and is not on this one at all.
const stage = day([flight(31, 'arrival'), stop('Ubud')])
expect(stageConnectionIds(stage, [], () => true)).toEqual([31])
})
it('FE-RTSTAGE-023: of the bookings switched on by hand only those running on the stage day stay', () => {
const stage = day([stop('Ubud')])
const onThisDay = new Set([40])
expect(stageConnectionIds(stage, [40, 41], id => onThisDay.has(id))).toEqual([40])
// A ride that seams the stage stays even when it was booked on another day.
expect(stageConnectionIds(day([flight(31, 'arrival')]), [31], () => false)).toEqual([31])
})
})
+8 -23
View File
@@ -1,5 +1,4 @@
import { dayColor } from './dayColors'
import { carrierReservationIds } from '@trek/shared/roadtrip'
import type { AccessSpur, RoadtripDay, RoadtripRoutes } from '@trek/shared/roadtrip'
/**
@@ -51,15 +50,15 @@ export function stageMapData(
}
if (!routes.lines.length) return { ...EMPTY, placeIds: stagePlaceIds(stage), focusPoints: stagePoints(stage) }
// A stage is ONE day, so the drive in from the day before is left off it.
// A stage is ONE day, so the drive into the next day is left off it.
//
// With "connect the days" on, that leg is drawn as the day it arrives on, the day whose
// distance counts it. Filtering by day number alone therefore handed a stage a line
// that runs off it to a place the day never visits: on a phone, where the stage IS the
// map, that read as the day's own route and was the longest thing on screen. The
// desktop has the same connection, but it has it beside every other day, which is the
// view the setting exists for; here that view is the "all days" one, a tap away on the
// same map.
// With "connect the days" on, that leg is drawn in the colour of the day it leaves, so
// on the whole-drive map it reads as that day carrying on. Filtering by day number
// alone therefore handed a stage a line that runs off it to a place the day never
// visits: on a phone, where the stage IS the map, that read as the day's own route and
// was the longest thing on screen. The desktop has the same connection, but it has it
// beside every other day, which is the view the setting exists for; here that view is
// the "all days" one, a tap away on the same map.
const ofDay: number[] = []
routes.lineDays.forEach((n, i) => { if (n === stage.dayNumber) ofDay.push(i) })
const own = ofDay.filter(i => !routes.lineJoins?.[i])
@@ -89,20 +88,6 @@ export function stagePlaceIds(stage: RoadtripDay): Set<number> {
return new Set(stage.stops.filter(s => !s.automaticNight).map(s => s.placeId))
}
/**
* The bookings the map draws as arcs on ONE stage: the rides that seam this stage's
* drive, whatever day they were booked on, and of the ones switched on by hand only
* those that run on the stage's day. Taking the rides of the whole drive put a flight
* home across every stage before it, as if it were part of that day.
*/
export function stageConnectionIds(
stage: RoadtripDay,
switchedOn: readonly number[],
runsOnStageDay: (reservationId: number) => boolean,
): number[] {
return [...new Set([...switchedOn.filter(runsOnStageDay), ...carrierReservationIds([stage])])]
}
/** The stage's stops as coordinates, for the fit. */
export function stagePoints(stage: RoadtripDay): [number, number][] {
return stage.stops
@@ -631,7 +631,7 @@ describe('useRoadtripRoutes', () => {
expect(result.current.totalDistance).toBe(300000)
})
it('FE-ROADTRIP-ROUTES-022: the joining stroke wears the day it reaches, like its kilometres (#3123)', async () => {
it('FE-ROADTRIP-ROUTES-022: the joining stroke wears the day it leaves, its kilometres the day it reaches', async () => {
setting({ roadtrip_connect_days: true })
const { days: daysList, assignments } = twoDays()
const { result } = renderHook(() => useRoadtripRoutes(7, daysList, assignments))
@@ -639,9 +639,10 @@ describe('useRoadtripRoutes', () => {
// Same length and same order as `lines`, or a colour lands on the wrong day.
expect(result.current.lineDays).toHaveLength(result.current.lines.length)
// Day 1 ends at its last stop, so the drive on to day 2 is driven on day 2: its
// kilometres are counted there, and drawn in day 1's colour the map said otherwise.
expect(result.current.lineDays).toEqual([1, 2, 2])
// The stroke starts at a stop on day 1, so drawing it as day 2 would make day 2
// look like it begins somewhere it has no stop.
expect(result.current.lineDays).toEqual([1, 1, 2])
// The kilometres go the other way: they are driven on the day they arrive.
expect(result.current.days.map(d => d.distance)).toEqual([100000, 200000])
})
@@ -665,8 +666,7 @@ describe('useRoadtripRoutes', () => {
setting({ roadtrip_connect_days: true })
expect(result.current.lines).toHaveLength(3)
// The drive past midnight lands on day 2 and is drawn there, like day 2's own legs.
expect(result.current.lineDays).toEqual([2, 2, 2])
expect(result.current.lineDays).toEqual([1, 2, 2])
expect(result.current.days[0].distance).toBe(300000)
})
@@ -447,28 +447,7 @@ describe('CollectionToursSection', () => {
expect(await screen.findByTestId('kept-tour-preview')).toBeInTheDocument();
unmount();
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
const off = { response: { status: 404, data: { error: 'Tours addon is not enabled' } } };
list.mockRejectedValue(off);
render(<CollectionToursSection collectionId={3} canRemove />);
await waitFor(() => expect(list).toHaveBeenLastCalledWith(3));
expect(screen.queryByTestId('collection-tours')).toBeNull();
expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();
});
it('FE-COLLECTION-TOURS-021: with Tours off for the instance, the tours show once the server hands them over', async () => {
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
// A trip of the user switched Tours on for itself, so the server answers.
vi.spyOn(collectionToursRepo, 'list').mockResolvedValue({ tours: [kept()] });
render(<CollectionToursSection collectionId={3} canRemove />);
expect(await screen.findByTestId('kept-tour-4')).toHaveTextContent('Ridge');
});
it('FE-COLLECTION-TOURS-022: with Tours off for the instance, a failed read shows nothing, as it always did', async () => {
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
const list = vi.spyOn(collectionToursRepo, 'list').mockRejectedValue(new Error('500'));
render(<CollectionToursSection collectionId={3} canRemove />);
await waitFor(() => expect(list).toHaveBeenCalled());
expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();
expect(screen.queryByTestId('collection-tours')).toBeNull();
});
@@ -13,26 +13,23 @@ import { useToast } from '../../shared/Toast';
/**
* LIB-03: the tours a collection keeps, for the collection's page. Read when
* the collection opens and kept current while its members keep or remove one;
* nothing at all while the Tours addon is off. Tours counts as on while the
* instance has it on or any of the user's trips switched it on for itself;
* only the server knows the second, so with the instance off the tours are
* read all the same and its refusal hides them. Removing asks first and says
* nothing at all while the Tours addon is off. Removing asks first and says
* how it went.
*/
export function useCollectionTours(collectionId: number) {
const { t } = useTranslation();
const toast = useToast();
const instanceOn = useAddonStore((state) => state.isEnabled('tours'));
const enabled = useAddonStore((state) => state.isEnabled('tours'));
const { tours, status, shownFor } = useCollectionTourStore(
useShallow((state) => ({ tours: state.tours, status: state.status, shownFor: state.collectionId }))
);
const [removing, setRemoving] = useState<CollectionTourItem | null>(null);
// Read again when the instance switch flips, since the answer may change with it.
useEffect(() => {
if (!enabled) return undefined;
void useCollectionTourStore.getState().load(collectionId);
return watchCollectionTours();
}, [collectionId, instanceOn]);
}, [collectionId, enabled]);
const confirmRemove = async () => {
const tour = removing;
@@ -47,9 +44,6 @@ export function useCollectionTours(collectionId: number) {
};
const current = shownFor === collectionId;
// With the instance on nothing changes; with it off only tours the server handed over show,
// so an install without a trip of its own choice shows nothing, as it always did.
const enabled = instanceOn ? !(current && status === 'off') : current && status === 'ready';
return {
enabled,
tours: enabled && current ? tours : [],
@@ -9,7 +9,7 @@ import {
import { useCallback, useEffect, useMemo, useState } from 'react';
import { translateApiError, useTranslation } from '../../../i18n';
import { tourPackingLinkRepo } from '../../../repo/tourPackingLinkRepo';
import { useTripAddonEnabled } from '../../../store/tripAddonsStore';
import { useAddonStore } from '../../../store/addonStore';
import { useTripStore } from '../../../store/tripStore';
import type { PackingItem } from '../../../types';
import { packingCategoryOrder, packingViewItems } from '../../Packing/packingListModel';
@@ -42,7 +42,7 @@ interface TourPackingCategory extends PackingCategoryChoice {
export function useTourPackingLink({ tripId, tour }: { tripId: number; tour: TourListItem }) {
const { t } = useTranslation();
const toast = useToast();
const packingEnabled = useTripAddonEnabled(tripId, 'packing');
const packingEnabled = useAddonStore((state) => state.isEnabled('packing'));
const items = useTripStore((state) => state.packingItems);
const placeId = tour.place_id;
const key = `${tripId}:${placeId}`;
@@ -23,7 +23,7 @@ const state = vi.hoisted(() => ({
}))
vi.mock('../../store/tripStore', () => ({ useTripStore: (selector: (store: unknown) => unknown) => selector({ trip: state.trip, loadTrip: state.loadTrip, refreshPlaces: state.refreshPlaces, places: [], packingItems: state.packingItems }) }))
vi.mock('../../store/authStore', () => ({ useAuthStore: Object.assign((selector: (store: unknown) => unknown) => selector({ user: state.user }), { getState: () => ({ user: state.user }) }) }))
vi.mock('../../store/authStore', () => ({ useAuthStore: (selector: (store: unknown) => unknown) => selector({ user: state.user }) }))
vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (selector: (store: unknown) => unknown) => selector({ settings: { distance_unit: 'metric' } }) }))
vi.mock('../Map/MapViewAuto', () => ({ MapViewAuto: () => null }))
vi.mock('../../repo/tourRepo', () => ({ tourRepo: { importGpx: state.importGpx, previewGpx: state.previewGpx, create: state.create, update: state.update, detail: state.detail } }))
@@ -7,7 +7,7 @@ import { server } from '../../../tests/helpers/msw/server';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import { usePermissionsStore } from '../../store/permissionsStore';
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser, buildTrip } from '../../../tests/helpers/factories';
import TripMembersModal from './TripMembersModal';
@@ -101,8 +101,6 @@ beforeEach(() => {
);
seedStore(useAuthStore, { user: ownerUser, isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1, title: 'Test Trip' }) });
// The instance has the three addons a link section belongs to; the trip names none of its own.
seedInstanceAddons(['packing', 'budget', 'collab']);
addToast = vi.fn<AddToast>(() => 0);
window.__addToast = addToast;
});
@@ -1133,34 +1131,4 @@ describe('TripMembersModal', () => {
expect(await screen.findByText('owner')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Edit Trip' })).toBeNull();
});
it('FE-COMP-MEMBERS-064: the owner switches the trip addons in an area of their own', async () => {
const user = userEvent.setup();
const bodies: unknown[] = [];
const list = [
{ id: 'budget', name: 'Budget', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true },
];
server.use(
http.get('/api/trips/1/addons', () => HttpResponse.json({ tripId: 1, addons: list })),
http.put('/api/trips/1/addons/:addonId', async ({ request }) => {
bodies.push(await request.json());
return HttpResponse.json({ tripId: 1, addons: list });
}),
);
render(<TripMembersModal {...defaultProps} />);
const nav = await screen.findByRole('navigation', { name: 'Trip settings' });
await user.click(await within(nav).findByRole('button', { name: 'Addons' }));
expect(await screen.findByText('This trip only')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Costs' }));
await waitFor(() => expect(bodies).toEqual([{ enabled: null }]));
});
it('FE-COMP-MEMBERS-065: a member who is not the owner gets no Addons area', async () => {
seedStore(useAuthStore, { user: memberUser, isAuthenticated: true });
render(<TripMembersModal {...defaultProps} />);
expect(await screen.findByText('owner')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Addons' })).toBeNull();
});
});
@@ -1,9 +1,8 @@
import { useId, useState, type ComponentProps, type ReactNode } from 'react'
import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Puzzle, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'
import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'
import { useTranslation } from '../../i18n'
import CustomSelect from '../shared/CustomSelect'
import ConfirmDialog from '../shared/ConfirmDialog'
import ToggleSwitch from '../Settings/ToggleSwitch'
import { Tooltip } from '../shared/Tooltip'
import { DialogButton, DialogHeader, DialogSection, DialogShell, DialogTile, NEUTRAL_TINT, PILL, fs } from '../shared/DialogShell'
import { AddRowButton, CardHead, INPUT, LABEL, PANEL } from '../shared/dialogParts'
@@ -13,8 +12,7 @@ import TripFormModal from './TripFormModal'
import { TripJournalLinkSection } from './TripJournalLinkSection'
import { TripMemberAvatar } from './TripMemberAvatar'
import { useTripJournalSectionVisible } from './useTripJournalLink'
import { useTripAddonRows } from './useTripAddonRows'
import { SHARE_OPTIONS, useShareLink, useTripInviteLink, useTripMembers, type TripMembersState } from './useTripShare'
import { SHARE_OPTIONS, SHARE_SECTIONS, useShareLink, useTripInviteLink, useTripMembers, type TripMembersState } from './useTripShare'
interface TripShareDialogProps {
isOpen: boolean
@@ -59,21 +57,19 @@ const NAV_ENTRY_OFF = 'text-content-muted hover:bg-surface-hover hover:text-cont
/**
* The trip's Settings on the desktop: who is on the trip, its guests, the two
* links that let others in, the journal the trip shows, and for the owner
* which addons the trip uses.
* links that let others in, and the journal the trip shows.
*/
export default function TripShareDialog(props: TripShareDialogProps) {
return props.isOpen ? <OpenDialog {...props} /> : null
}
type Area = 'people' | 'sharing' | 'journal' | 'addons' | 'trip'
type Area = 'people' | 'sharing' | 'journal' | 'trip'
/** The areas of the dialog, each with its icon, its name and the line under the name. */
const AREAS: { id: Area; icon: (on: boolean) => ReactNode; labelKey: string; hintKey: string }[] = [
{ id: 'people', icon: () => <Users size={16} strokeWidth={2} />, labelKey: 'trip.settings.people', hintKey: 'trip.settings.peopleHint' },
{ id: 'sharing', icon: () => <Link2 size={16} strokeWidth={2} />, labelKey: 'trip.settings.sharing', hintKey: 'trip.settings.sharingHint' },
{ id: 'journal', icon: () => <LinkedJournalIcon size={16} />, labelKey: 'trip.journal.title', hintKey: 'trip.journal.hint' },
{ id: 'addons', icon: () => <Puzzle size={16} strokeWidth={2} />, labelKey: 'trip.settings.addons', hintKey: 'trip.settings.addonsHint' },
{ id: 'trip', icon: () => <Pencil size={16} strokeWidth={2} />, labelKey: 'dashboard.editTrip', hintKey: 'trip.settings.editTripHint' },
]
@@ -85,7 +81,7 @@ function OpenDialog({ onClose, tripId, tripTitle, onMembersChanged, editTrip }:
const [area, setArea] = useState<Area>('people')
const [tripReviewing, setTripReviewing] = useState(false)
const journalSection = useTripJournalSectionVisible(tripId)
const shows: Record<Area, boolean> = { people: true, sharing: m.canManageShare, journal: journalSection, addons: m.isCurrentOwner, trip: !!editTrip }
const shows: Record<Area, boolean> = { people: true, sharing: m.canManageShare, journal: journalSection, trip: !!editTrip }
const areas = AREAS.filter(a => shows[a.id])
const current = areas.find(a => a.id === area) ?? areas[0]
const panelOf = (id: Area) => areas.find(a => a.id === id)
@@ -136,11 +132,6 @@ function OpenDialog({ onClose, tripId, tripTitle, onMembersChanged, editTrip }:
<TripJournalLinkSection tripId={tripId} framed={false} />
</AreaPanel>
)}
{m.isCurrentOwner && (
<AreaPanel area={panelOf('addons')} shown={current.id === 'addons'} titled>
<TripAddonsList tripId={tripId} />
</AreaPanel>
)}
{editTrip && (
<AreaPanel area={panelOf('trip')} shown={current.id === 'trip'} titled>
<TripFormModal embedded isOpen onClose={onClose} onReviewChange={setTripReviewing} {...editTrip} />
@@ -427,32 +418,6 @@ function PermChip({ on, disabled, label, hint, onToggle }: { on: boolean; disabl
return hint ? <Tooltip label={hint}>{chip}</Tooltip> : chip
}
/** The trip addons, each with its switch; a badge marks the ones the owner set apart from the instance. */
function TripAddonsList({ tripId }: { tripId: number }) {
const { t } = useTranslation()
const { rows, loading } = useTripAddonRows(tripId)
if (loading) return <div className="h-[120px] animate-pulse rounded-[14px] bg-surface-secondary" />
return (
<div className={ROWS}>
{rows.map(row => (
<div key={row.id} className={ROW}>
<span className={`flex h-8 w-8 flex-none items-center justify-center rounded-[10px] bg-surface-tertiary ${row.enabled ? 'text-content' : 'text-content-faint'}`}>
<row.Icon size={16} strokeWidth={2} />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="truncate font-semibold text-content" style={fs(13.5, 'body')}>{row.name}</span>
{row.ownChoice && <span className={`${BADGE} bg-surface-tertiary text-content-muted`} style={fs(10.5, 'caption')}>{t('trip.addons.thisTripOnly')}</span>}
</div>
{row.description && <p className="m-0 truncate text-content-muted" style={fs(12, 'caption')}>{row.description}</p>}
</div>
<ToggleSwitch on={row.enabled} onToggle={row.toggle} label={row.name} disabled={row.busy} />
</div>
))}
</div>
)
}
/** The read-only public link, and which parts of the trip it shows. */
function PublicLink({ tripId }: { tripId: number }) {
const { t } = useTranslation()
@@ -464,7 +429,7 @@ function PublicLink({ tripId }: { tripId: number }) {
<div>
<span className={LABEL}>{t('share.options')}</span>
<div className="flex flex-wrap gap-1.5">
{link.sections.map(opt => (
{SHARE_SECTIONS.map(opt => (
<PermChip key={opt.key} on={link.perms[opt.key]} disabled={opt.always} label={t(opt.label)}
onToggle={() => void link.setPerm(opt.key, !link.perms[opt.key])} />
))}
@@ -1,84 +0,0 @@
// FE-TRIPADDONROWS-001 to FE-TRIPADDONROWS-003: the rows of the trip settings' Addons area,
// shared by the desktop dialog and the phone sheet.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { TripAddon } from '@trek/shared';
import 'fake-indexeddb/auto';
import { CarFront, ListChecks, Puzzle } from 'lucide-react';
import { http, HttpResponse } from 'msw';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { clearAll } from '../../db/offlineDb';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore } from '../../store/authStore';
import { useTripAddonRows } from './useTripAddonRows';
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
const LIST: TripAddon[] = [
{ id: 'packing', name: 'Packing', icon: 'ListChecks', enabled: true, instanceEnabled: true, overridden: false },
{ id: 'roadtrip', name: 'Road trip', icon: 'Route', enabled: false, instanceEnabled: true, overridden: true },
{ id: 'someplugin', name: 'Some plugin', icon: 'Unknown', enabled: true, instanceEnabled: false, overridden: true },
];
function wrapper({ children }: { children: ReactNode }) {
return <TranslationProvider>{children}</TranslationProvider>;
}
let bodies: unknown[] = [];
beforeEach(async () => {
await clearAll();
resetAllStores();
bodies = [];
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });
server.use(
http.get('/api/trips/4/addons', () => HttpResponse.json({ tripId: 4, addons: LIST })),
http.put('/api/trips/4/addons/:addonId', async ({ request }) => {
bodies.push(await request.json());
return HttpResponse.json({ tripId: 4, addons: LIST });
})
);
});
describe('useTripAddonRows', () => {
it('FE-TRIPADDONROWS-001: names each addon from the catalog, with its icon and whether the trip chose it', async () => {
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
expect(result.current.loading).toBe(true);
await waitFor(() => expect(result.current.rows).toHaveLength(3));
const [packing, roadtrip, plugin] = result.current.rows;
expect(packing).toMatchObject({ name: 'Lists', Icon: ListChecks, enabled: true, ownChoice: false });
expect(packing.description).not.toBe('');
expect(roadtrip).toMatchObject({ Icon: CarFront, enabled: false, ownChoice: true });
// An addon the catalog does not know keeps the server's name, no description and the fallback icon.
expect(plugin).toMatchObject({ name: 'Some plugin', description: '', Icon: Puzzle });
expect(result.current.loading).toBe(false);
});
it('FE-TRIPADDONROWS-002: a switch away from the instance stores the choice, back to it drops the choice', async () => {
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
await waitFor(() => expect(result.current.rows).toHaveLength(3));
act(() => result.current.rows[0].toggle());
await waitFor(() => expect(bodies).toEqual([{ enabled: false }]));
await waitFor(() => expect(result.current.rows[0].busy).toBe(false));
act(() => result.current.rows[1].toggle());
await waitFor(() => expect(bodies).toEqual([{ enabled: false }, { enabled: null }]));
});
it('FE-TRIPADDONROWS-003: a second switch while one is saving is ignored', async () => {
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
await waitFor(() => expect(result.current.rows).toHaveLength(3));
act(() => result.current.rows[0].toggle());
expect(result.current.rows[0].busy).toBe(true);
act(() => result.current.rows[2].toggle());
await waitFor(() => expect(result.current.rows[0].busy).toBe(false));
expect(bodies).toEqual([{ enabled: false }]);
});
});

Some files were not shown because too many files have changed in this diff Show More