Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

Merge dev into feat/tours and port Tours onto MikroORM

Mauricec956fe92ba78
diff --cc server/src/db/dialect/sql-functions.ts
index 000000000,e3859062f..b20e4d807
mode 000000,100644..100644
--- a/server/src/db/dialect/sql-functions.ts
+++ b/server/src/db/dialect/sql-functions.ts
@@@ -1,0 -1,981 +1,997 @@@
+ import { raw, type Platform, type RawQueryFragment } from '@mikro-orm/core';
+ import { SqlitePlatform } from '@mikro-orm/sql';
+ import { sql, type Expression, type ExpressionBuilder, type ExpressionWrapper, type RawBuilder, type ReferenceExpression, type SqlBool, type StringReference } from 'kysely';
+
+ /**
+ * The only place a repository may spell a database function.
+ *
+ * Every helper takes the MikroORM `Platform` the caller's EntityManager is
+ * running on (`em.getPlatform()`) plus an already-qualified column reference
+ * (`'t.created_at'`), and dispatches on that platform at runtime. TREK ships
+ * one binary and the database is chosen by configuration, so the dialect is a
+ * runtime property of the live connection, not a build-time swap: when the
+ * Postgres driver arrives this file grows a second branch and no repository
+ * changes. An unknown platform fails closed rather than guessing a spelling.
+ *
+ * Values are never interpolated — the day count in `dateAdd` is checked to be
+ * an integer before it is spelled.
+ */
+
+ function column(ref: string): string {
+ if (!/^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/i.test(ref)) {
+ throw new Error(`sql-functions: not a column reference: ${ref}`);
+ }
+ return ref;
+ }
+
+ function unsupported(platform: Platform): never {
+ throw new Error(`sql-functions: no implementation for platform ${platform.constructor.name}`);
+ }
+
+ /** The calendar date (`YYYY-MM-DD`) of a timestamp column. */
+ export function dateOf(platform: Platform, ref: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw(`date(${column(ref)})`);
+ return unsupported(platform);
+ }
+
+ /** The timestamp column shifted by whole days, as a calendar date. */
+ export function dateAdd(platform: Platform, ref: string, days: number): RawQueryFragment {
+ if (!Number.isInteger(days)) throw new Error(`sql-functions: dateAdd needs an integer day count, got ${days}`);
+ if (platform instanceof SqlitePlatform) {
+ const sign = days < 0 ? '-' : '+';
+ return raw(`date(${column(ref)}, '${sign}${Math.abs(days)} days')`);
+ }
+ return unsupported(platform);
+ }
+
+ /** The database clock, in the same text the column defaults produce. */
+ export function currentTimestamp(platform: Platform): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw('CURRENT_TIMESTAMP');
+ return unsupported(platform);
+ }
+
+ /**
+ * A bare reference to another column of the same row, for a filter or update
+ * value that must compare against or combine with a sibling column instead
+ * of a bound parameter (e.g. `used_count < max_uses` — `InviteTokensRepository
+ * .incrementUsedCount`'s capacity guard). Portable across dialects on its own,
+ * but still routed through this file (not spelled with `raw()` in a
+ * repository) so every escape hatch stays in one place ESLint's
+ * `no-restricted-syntax` rule for `src/db/repositories/**` can enforce.
+ */
+ export function columnRef(platform: Platform, ref: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw(column(ref));
+ return unsupported(platform);
+ }
+
+ /** A column shifted by a signed integer amount: `<col> + n` / `<col> - n`. */
+ export function columnIncrementedBy(platform: Platform, ref: string, amount: number): RawQueryFragment {
+ if (!Number.isInteger(amount)) {
+ throw new Error(`sql-functions: columnIncrementedBy needs an integer amount, got ${amount}`);
+ }
+ if (platform instanceof SqlitePlatform) {
+ const sign = amount < 0 ? '-' : '+';
+ return raw(`${column(ref)} ${sign} ${Math.abs(amount)}`);
+ }
+ return unsupported(platform);
+ }
+
+ /**
+ * A case-insensitive column reference, for use as a filter's object key:
+ * `{ [lower(platform, 'email')]: <value-side> }` produces
+ * `WHERE LOWER(email) = <value-side>`.
+ *
+ * **SQLite's `LOWER()` is ASCII-only; JavaScript's `String.prototype
+ * .toLowerCase()` is full-Unicode.** They do NOT agree on every input this
+ * codebase stores — a locally-registered e-mail can carry any non-whitespace
+ * character (`EMAIL_REGEX`), including non-ASCII letters (program rule 18;
+ * Plan 3b Task 7 review, H1: `JOSÉ@x.com` proved a live login lockout). Two
+ * value-side shapes are legitimate, and they are NOT interchangeable:
+ *
+ * - `LOWER(col) = LOWER(?)` — pair with `lowerParam()` below, binding the
+ * RAW value. Both sides are folded by the SAME engine (SQLite's), so they
+ * agree on every input. This is the shape for every legacy
+ * `LOWER(col) = LOWER(?)` statement (AU9, AU12, UP5, UP6, O12).
+ * - `LOWER(col) = ?` — pair with a value the CALLER has already lowered in
+ * JS (`value.toLowerCase()`) as a plain string, matching a legacy
+ * `LOWER(col) = ?` statement exactly (only O4 today —
+ * `OidcService.findOrCreateUser` JS-lowers the email once upfront and the
+ * legacy statement it replaced never re-lowered it in SQL). Do not use
+ * this shape for a value the caller has not already lowered.
+ *
+ * Typed `RawQueryFragment & symbol` (not the bare `RawQueryFragment` the
+ * other helpers in this file return): TypeScript only accepts a
+ * `string | number | symbol` as a computed property name, and a raw
+ * fragment is only usable as an object key because `raw()`'s default
+ * generic already brands it with a `[Symbol.toPrimitive]`. The other
+ * helpers here are only ever used as VALUES, where that brand isn't needed.
+ */
+ export function lower(platform: Platform, ref: string): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw(`LOWER(${column(ref)})`);
+ return unsupported(platform);
+ }
+
+ /**
+ * The value-side twin of `lower()`: `LOWER(?)` bound with the RAW,
+ * untransformed value, for the right-hand side of a `lower(platform, col)`
+ * filter key. Together they render `LOWER(<column>) = LOWER(?)`,
+ * byte-for-byte a legacy `LOWER(col) = LOWER(?)` statement, because SQLite
+ * folds BOTH sides with the same (ASCII-only) engine — proven directly
+ * against `better-sqlite3`: `SELECT LOWER(?)` on `'JOSÉ@x.com'` yields
+ * `'josÉ@x.com'` (only the ASCII letters fold; the `É` is untouched), the
+ * same transform SQLite would apply to a stored column. Do NOT pre-lower
+ * the value in JS before calling this (program rule 18) — that reintroduces
+ * the mixed-engine bug this helper exists to close.
+ */
+ export function lowerParam(platform: Platform, value: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw('LOWER(?)', [value]);
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 0b (R6) — no consumer yet: Tasks 1–8 wire these in as each
+ // converts the statement that needs them (`place-shadow.service.ts:192`,
+ // `places.service.ts:642,651-652`, the ~16 `COALESCE` sites across
+ // `days`/`assignments`/`trip-members`/`places`). Added here, with their own
+ // SQLF-0xx tests pinning the SQLite text against a raw statement, so a later
+ // task imports a tested helper instead of writing one inline.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `datetime('now', '-N days')` — the SQLite clock shifted backwards by whole
+ * days, as TEXT (not a stored column's value — `dateAdd` above is the wrong
+ * shape for this: it shifts a *column*, not "now"). `days` is validated to be
+ * a non-negative integer and spelled directly into the fragment rather than
+ * bound: the legacy statement (`place-shadow.service.ts:192`) binds the
+ * WHOLE modifier string (`'-30 days'`) as one parameter, and MikroORM's raw
+ * fragments do not accept a placeholder inside the modifier argument of a
+ * SQLite date/time function — `datetime('now', ?)` with `'-30 days'` bound
+ * does work in raw SQLite, but composing that shape through a `raw()`
+ * fragment used as a QueryBuilder value needs the modifier already in the
+ * SQL text, the same way `dateAdd` above spells its own day count.
+ */
+ export function nowMinusDays(platform: Platform, days: number): RawQueryFragment {
+ if (!Number.isInteger(days) || days < 0) {
+ throw new Error(`sql-functions: nowMinusDays needs a non-negative integer day count, got ${days}`);
+ }
+ if (platform instanceof SqlitePlatform) return raw(`datetime('now', '-${days} days')`);
+ return unsupported(platform);
+ }
+
+ /**
+ * `TRIM(<col>)`, standalone. **Does NOT compose with `lower()`** to build
+ * `LOWER(TRIM(name))` (Task 0b review M3): `lower()`'s `ref` argument goes
+ * through `column()`, whose regex rejects anything but a bare
+ * `alias.column` reference — `TRIM(name)` fails it — and even if it didn't,
+ * `coalesce()`'s own docstring in this file documents that a
+ * `RawQueryFragment` cannot be nested inside another one (`raw()`'s
+ * `[Symbol.toPrimitive]` only implements the `'string'` coercion hint, which
+ * is the object-key position, not template-literal interpolation). Use
+ * `lowerTrim()` below for the composed shape.
+ */
+ export function trim(platform: Platform, ref: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw(`TRIM(${column(ref)})`);
+ return unsupported(platform);
+ }
+
+ /**
+ * `LOWER(TRIM(<col>))` as one fragment — the shape `places.service.ts:642`
+ * (`lower(trim(name))`, PL26) actually needs; `lower()`/`trim()` above
+ * cannot be composed to build it (see `trim()`'s docstring, Task 0b review
+ * M3). Typed `RawQueryFragment & symbol`, the same brand `lower()` carries,
+ * for use as a filter KEY: `{ [lowerTrim(platform, 'name')]: lowerParam(...) }`.
+ * SQLite's `LOWER()` is ASCII-only (program rule 18) — unchanged by the
+ * `TRIM()`.
+ */
+ export function lowerTrim(platform: Platform, ref: string): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw(`LOWER(TRIM(${column(ref)}))`);
+ return unsupported(platform);
+ }
+
+ /**
+ * `COALESCE(<col>, <fallbackCol>)` — both sides column references, for the
+ * `COALESCE(a, b)` SELECT-projection shape (`days.service.ts:93-94`,
+ * `assignments.service.ts:103-104`, `trip-members.service.ts:116-143`, …).
+ *
+ * Not composed by nesting a `RawQueryFragment` inside this one: MikroORM's
+ * `RawQueryFragment[Symbol.toPrimitive]` only returns a usable value for the
+ * `'string'` coercion hint (object-key position) — a template-literal
+ * `${fragment}` embed uses the `'default'` hint and throws
+ * (`node_modules/@mikro-orm/core/utils/RawQueryFragment.js`, verified
+ * directly, not assumed). So `coalesce`'s second argument is a second
+ * `column()`-validated identifier, spelled into the same fragment as the
+ * first — two columns, one statement, matching `lower`/`lowerParam`'s
+ * two-function split for the same reason (a filter KEY vs a bound VALUE
+ * are different shapes).
+ */
+ export function coalesce(platform: Platform, ref: string, fallbackRef: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw(`COALESCE(${column(ref)}, ${column(fallbackRef)})`);
+ return unsupported(platform);
+ }
+
+ /**
+ * `COALESCE(<col>, ?)` — the value-side twin of `coalesce()` above, for the
+ * `COALESCE(col, ?)` UPDATE-SET shape (`places.service.ts:344,351,363,…`).
+ * `value` is bound as a genuine parameter, never interpolated.
+ *
+ * Typed `RawQueryFragment & symbol` (widened from a bare `RawQueryFragment`
+ * in Plan 3d Task 0, R3 — `_shared/reservation-visibility.ts`'s
+ * `publicReservationCondition` needs `COALESCE(alias.ingest_state, 'live')`
+ * as a `.where({...})` filter KEY, `{ [coalesceParam(...)]: { $ne: 'staged'
+ * } }`, the same brand `lower()`/`lowerTrim()`/`castInteger()` carry for
+ * that use): every existing UPDATE-SET caller (`Places.repository.ts`'s six
+ * `coalesceParam(...)` assignments into a loosely-typed `data` object) keeps
+ * typechecking unchanged — `RawQueryFragment & symbol` is assignable
+ * anywhere a plain `RawQueryFragment` is expected, a strict widening with no
+ * behaviour change (the function body is untouched).
+ */
+ export function coalesceParam(platform: Platform, ref: string, value: string | number | null): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw(`COALESCE(${column(ref)}, ?)`, [value]);
+ return unsupported(platform);
+ }
+
+ /**
+ * `COALESCE(?, <col>)` — the MIRROR-IMAGE value-side shape of
+ * {@link coalesceParam} above: the bound value goes FIRST, the column is
+ * the fallback. NOT interchangeable with `coalesceParam` — that one keeps
+ * the EXISTING column unless it is NULL (`places.service.ts`'s own legacy
+ * shape); this one prefers the NEW value unless IT is null, keeping the
+ * existing column only then. `doc-sync.service.ts`'s DS23/DS24
+ * (`upsertItem`'s `file_id=COALESCE(?,file_id)`,
+ * `remote_id=COALESCE(?,remote_id)`, … eight columns, both the plain
+ * `nativeUpdate` and the Kysely `ON CONFLICT` forms) is the shape this
+ * exists for — confirmed genuinely the opposite direction from
+ * `coalesceParam`'s own doc'd precedent by reading the legacy SQL text
+ * literally, not assumed from the function name alone (a same-named
+ * "coalesce" helper reused in the wrong direction silently drops every
+ * incoming update — verified directly against a live row: a `recordAttempt`
+ * call passing a genuinely new `remote_version`/`content_sha256` left both
+ * columns exactly as they were before, since `coalesceParam`'s `COALESCE(col,
+ * ?)` always preferred the non-null existing value).
+ */
+ export function coalesceOverride(platform: Platform, value: string | number | null, ref: string): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw(`COALESCE(?, ${column(ref)})`, [value]);
+ return unsupported(platform);
+ }
+
+ /**
+ * `ABS(<col> - ?)`, for use as a filter KEY (the `'string'`-hint coercion
+ * `lower()` above relies on) so it composes with `$lte`/`$gte`:
+ * `{ [absDifference(platform, 'lat', targetLat)]: { $lte: tolerance } }`
+ * renders `WHERE ABS(lat - ?) <= ?`, matching `places.service.ts:651-652`'s
+ * `abs(lat - ?) <= ?` (and the sibling `lng` comparison at `:652`) exactly.
+ * Typed `RawQueryFragment & symbol`, same reason `lower()` is: only a
+ * `string | number | symbol` is a valid computed property name, and the
+ * brand only lives on that typing for values meant to be used as a key.
+ */
+ export function absDifference(platform: Platform, ref: string, value: number): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw(`ABS(${column(ref)} - ?)`, [value]);
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 1 — aggregate SELECT projections (`PlaceShadowPicksRepository
+ // .totals`/`countBySource`/`countByLiveRank`, `place-shadow.service.ts:144,
+ // 149, 157`). `alias` is a hand-written literal at every call site today
+ // (never user input), validated the same way `column()` validates a column
+ // reference, so a future caller cannot smuggle SQL through it either.
+ // ---------------------------------------------------------------------------
+
+ function alias(name: string): string {
+ if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {
+ throw new Error(`sql-functions: not an alias: ${name}`);
+ }
+ return name;
+ }
+
+ /** `COUNT(*) as <alias>`, for a single-row totals read or a `GROUP BY` count column. */
+ export function countAll(platform: Platform, aliasName: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw(`COUNT(*) as ${alias(aliasName)}`);
+ return unsupported(platform);
+ }
+
+ /** `MIN(<col>) as <alias>`. */
+ export function minOf(platform: Platform, ref: string, aliasName: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw(`MIN(${column(ref)}) as ${alias(aliasName)}`);
+ return unsupported(platform);
+ }
+
+ /** `MAX(<col>) as <alias>`. */
+ export function maxOf(platform: Platform, ref: string, aliasName: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw(`MAX(${column(ref)}) as ${alias(aliasName)}`);
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 6 — `TripMembersRepository.listWithUserAndInviter`
+ // (`trip-members.service.ts:117`, TM2): the `role` column, a `CASE WHEN`
+ // comparing the joined user's id against the trip's owner id.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `CASE WHEN <col> = ? THEN ? ELSE ? END`, for use as a `.select()` value
+ * (chain `.as(aliasName)` at the call site, the same way `coalesce()`'s
+ * callers do — this file does not bake the alias into the SQL text itself
+ * for this one, unlike `countAll`/`minOf`/`maxOf`, because `.as()` already
+ * covers it and a `value`-bearing fragment cannot reuse `alias()`'s bare
+ * identifier validation the same way an aggregate's literal alias does).
+ * `value`/`whenTrue`/`whenFalse` are all passed through `raw()`'s own
+ * parameter escaping, never spliced into the SQL text by this function —
+ * even though today's only caller (TM2's owner/member role label) passes
+ * fixed literal strings, parity is by VALUE, not by whether the string
+ * happens to be a source-code literal at the call site. (Task 6 review's
+ * I1: downstream, MikroORM still formats the FINAL query with every
+ * parameter inlined as an escaped literal in the SQL text it hands
+ * better-sqlite3 — not as a separate bound-params array — so a non-finite
+ * `value` renders as the bare token `NaN`/`Infinity` and fails at PREPARE
+ * time regardless of this function's own escaping; callers must guard a
+ * non-finite `value` before calling.)
+ */
+ export function caseWhenEquals(platform: Platform, ref: string, value: number, whenTrue: string, whenFalse: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw(`CASE WHEN ${column(ref)} = ? THEN ? ELSE ? END`, [value, whenTrue, whenFalse]);
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 1 fix round (review M1) — `PlaceShadowPicksRepository
+ // .countBySource` (PS5): `.orderBy()` on `countAll()`'s aliased column throws
+ // ("Trying to query by not existing property" — `raw()`'s alias carries no
+ // literal type for `ExtractRawAliases` to register), and sorting the fetched
+ // rows in JS is NOT equivalent to the legacy `ORDER BY count DESC`: SQLite's
+ // own sorter is not stable, so on a tie it orders descending by GROUP BY key,
+ // while `Array.prototype.sort` (stable) leaves ties in the rows' incoming
+ // (ascending) order — verified directly (five sources, two tied pairs).
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `COUNT(*)` as an ORDER BY EXPRESSION (not an alias — `.orderBy()` cannot
+ * order by `countAll()`'s aliased column; ordering by the expression itself
+ * works and reproduces the legacy `ORDER BY count DESC` tie order exactly).
+ * Typed `RawQueryFragment & symbol`, the same brand `lower()`/`lowerTrim()`
+ * carry, so it is usable as an `.orderBy()` object key:
+ * `.orderBy({ [countAllRef(platform)]: 'desc' })`.
+ */
+ export function countAllRef(platform: Platform): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw('COUNT(*)');
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3d Task 0 (R6) — no consumer yet: Tasks 2/4 wire these in as each
+ // converts the statement that needs them (`reservations.service.ts` RS11 and
+ // RS20 `listUpcoming`, `reservation-visibility.ts` RV2, DY23 in
+ // `days.service.ts`). Added here, with their own SQLF-0xx tests pinning the
+ // SQLite text against a raw statement on seeded rows, so Tasks 1-6 import a
+ // tested helper instead of writing one inline.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `<col> GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'` — "does this
+ * column's TEXT value start with an ISO calendar date (`YYYY-MM-DD`)?", the
+ * legacy `DATED` constant (`reservations.service.ts:120`:
+ * `` `r.reservation_time GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'` ``,
+ * used at `:453-454` inside RS20's two `CASE WHEN` arms). Spelled with
+ * SQLite's `[0-9]` character-class glob syntax, NOT the plan's shorthand
+ * `'????-??-??*'` — verified directly against the legacy source, not
+ * assumed: a `?` in SQLite GLOB matches any single character (letters
+ * included), so `????-??-??*` is a strictly WIDER, non-equivalent pattern
+ * (it would also match `abcd-ef-gh...`); only the digit-class form matches
+ * the legacy's actual behaviour byte-for-byte.
+ *
+ * A full boolean expression, not a bare value — pair with a `CASE WHEN`
+ * builder or a QB/Kysely raw condition, never nest inside another raw
+ * fragment (see `coalesce()`'s docstring on why nesting doesn't work).
+ * Kysely has no `GLOB` comparison operator (`operator-node.d.ts`'s
+ * `ComparisonOperator` union omits it — verified against the installed
+ * 0.29.6 typings, per the inventory's §19 MikroORM/Kysely capability table)
+ * — this helper's SQLite-only reach is therefore the only portable spelling
+ * for this shape until a second platform is added.
+ */
+ export function startsWithIsoDate(platform: Platform, ref: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) {
+ return raw(`${column(ref)} GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'`);
+ }
+ return unsupported(platform);
+ }
+
+ /**
+ * `substr(<col>, <start>[, <length>])`, 1-based on both ends — the legacy
+ * shape at `reservations.service.ts:453` (`substr(r.reservation_time, 1,
+ * 10)`, three-arg), `:454` (`substr(r.reservation_time, 12)`, two-arg — "from
+ * position 12 to the end of the string") and `days.service.ts` DY23
+ * (`SUBSTR(reservation_time, 11)`, same two-arg shape, spelled uppercase in
+ * that statement — SQL function names are case-insensitive, so this helper's
+ * lowercase spelling is behaviourally identical). `length` is optional,
+ * matching SQLite's own two-arg `substr(X, Y)` form (everything from `Y` to
+ * the end) — passing it renders the three-arg form instead. `start` and
+ * `length` are validated integers and spelled directly (not bound): they are
+ * always source-code constants at every known call site (`1`, `10`, `11`,
+ * `12`), never user input, the same trust boundary `dateAdd`'s day count and
+ * `columnIncrementedBy`'s amount already rely on in this file.
+ */
+ export function substring(platform: Platform, ref: string, start: number, length?: number): RawQueryFragment {
+ if (!Number.isInteger(start) || start < 1) {
+ throw new Error(`sql-functions: substring needs a 1-based integer start, got ${start}`);
+ }
+ if (length !== undefined && (!Number.isInteger(length) || length < 0)) {
+ throw new Error(`sql-functions: substring needs a non-negative integer length, got ${length}`);
+ }
+ if (platform instanceof SqlitePlatform) {
+ if (length === undefined) return raw(`substr(${column(ref)}, ${start})`);
+ return raw(`substr(${column(ref)}, ${start}, ${length})`);
+ }
+ return unsupported(platform);
+ }
+
+ /**
+ * A part of a `concat()` expression: either a column reference (rendered
+ * through `column()`, the same identifier validation every other helper in
+ * this file applies) or a plain value bound as a genuine parameter (`?`) —
+ * never interpolated, even for what today's only legacy caller spells as a
+ * literal (`'T'` in `d.date || 'T' || a.check_in`,
+ * `reservations.service.ts:475, :493`): a bound constant and an interpolated
+ * one produce byte-identical SQLite behaviour for a plain string, and
+ * binding is the shape every other value-side helper in this file already
+ * prefers (`coalesceParam`, `lowerParam`, `absDifference`).
+ */
+ export type ConcatPart = { column: string } | { value: string };
+
+ /**
+ * `<part> || <part> || …` — SQLite (and Postgres) string concatenation, the
+ * legacy shape at `reservations.service.ts:475, :493`
+ * (`d.date || 'T' || a.check_in`, RS20's two check-in/check-out arms) and
+ * `days.service.ts` DY23 (`:date || SUBSTR(reservation_time, 11)`, inside an
+ * `UPDATE … SET`). Needs at least two parts — a one-part "concatenation" is
+ * a caller bug, not a legitimate call. Each part is a `ConcatPart` (see its
+ * own docstring) rather than a bare string, so a column reference and a
+ * bound literal can never be confused with each other the way an untyped
+ * `...parts: string[]` would invite (a plain string could mean either).
+ *
+ * Deliberately does NOT accept a nested `RawQueryFragment` as a part (e.g.
+ * the output of `substring()` above) — the same limitation `coalesce()`'s
+ * docstring documents: `RawQueryFragment`'s `[Symbol.toPrimitive]` only
+ * implements the `'string'` coercion hint (the object-key position), not the
+ * `'default'` hint a template-literal embed or an array-join would need, so
+ * composing `concat(platform, substring(...), ...)` throws at the `raw()`
+ * boundary rather than rendering silently wrong SQL. A caller that needs
+ * `SUBSTR(...)` as one side of a `||` builds that one statement directly
+ * (Kysely's `'||'` binary operator, per the inventory's §17a/§19), the same
+ * way RS20's own CASE/CTE shape is built outside this file's helpers.
+ */
+ export function concat(platform: Platform, ...parts: readonly ConcatPart[]): RawQueryFragment {
+ if (parts.length < 2) {
+ throw new Error(`sql-functions: concat needs at least two parts, got ${parts.length}`);
+ }
+ if (platform instanceof SqlitePlatform) {
+ const bindings: string[] = [];
+ const sql = parts
+ .map((part) => {
+ if ('column' in part) return column(part.column);
+ bindings.push(part.value);
+ return '?';
+ })
+ .join(' || ');
+ return raw(sql, bindings);
+ }
+ return unsupported(platform);
+ }
+
+ /**
+ * `CAST(<col> AS INTEGER)` — the legacy shape at `reservations.service.ts:471,
+ * :489` (inside RS20's correlated `stay_first_reservation_id`/title
+ * subqueries: `CAST(res.accommodation_id AS INTEGER) = a.id`) and
+ * `reservation-visibility.ts:106-107` (RV2's `publicStaySql`:
+ * `CAST(vr.accommodation_id AS INTEGER) = ${alias}.id`). Exists specifically
+ * for `reservations.accommodation_id`, a TEXT column holding integer ids
+ * with no FK (§18.1 of the inventory — some rows read back as `"14.0"`):
+ * casting it to INTEGER before comparing against a genuine INTEGER column
+ * (`day_accommodations.id`) applies numeric affinity to BOTH sides, matching
+ * `"14"` and `"14.0"` alike, the same way the legacy statement does.
+ *
+ * Typed `RawQueryFragment & symbol`, the same brand `lower()`/`lowerTrim()`
+ * carry: both known legacy call sites compare the cast against ANOTHER
+ * COLUMN, not a bound value (`= a.id`, `= ${alias}.id`) — the shape is
+ * `{ [castInteger(platform, 'vr.accommodation_id')]: columnRef(platform,
+ * 'a.id') }`, pairing this helper's filter-KEY brand with `columnRef()`'s
+ * existing VALUE-side column reference. The brand also lets it appear in a
+ * `.select()` projection via `.as(alias)` (the `lowerTrim`/SQLF-027 dual-use
+ * precedent) for a caller that only needs the cast INTEGER value itself.
+ */
+ export function castInteger(platform: Platform, ref: string): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw(`CAST(${column(ref)} AS INTEGER)`);
+ return unsupported(platform);
+ }
+
+ /**
+ * `ABS(JULIANDAY(<col>) - JULIANDAY(?))` — the legacy shape at
+ * `reservations.service.ts:307` (RS11, `resolveDayIdFromTime`'s
+ * nearest-day fallback: `ORDER BY ABS(JULIANDAY(date) - JULIANDAY(?)) ASC,
+ * date ASC LIMIT 1`), which clamps an imported booking's date to the
+ * closest day row in the trip when no exact match exists. `isoDate` is
+ * bound as a genuine parameter (never interpolated), matching the legacy
+ * statement's own bind. Distinct from `absDifference()` above:
+ * `absDifference` is `ABS(<col> - ?)` on plain NUMERIC values (for a
+ * lat/lng tolerance filter); this helper compares two `JULIANDAY(...)`
+ * calendar values. Typed `RawQueryFragment & symbol`, the same brand
+ * `countAllRef()` carries, so it is usable as an `.orderBy()` object key —
+ * `.orderBy({ [dayDistance(platform, 'date', isoDate)]: 'asc' })` —
+ * matching the legacy's own `ORDER BY ABS(JULIANDAY(...) - JULIANDAY(?)) ASC`
+ * shape exactly (an aliased column cannot be ordered by, the same
+ * `ExtractRawAliases` limitation `countAllRef`'s own docstring / SQLF-024's
+ * comment documents; ordering by the EXPRESSION itself is what works).
+ */
+ export function dayDistance(platform: Platform, ref: string, isoDate: string): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw(`ABS(JULIANDAY(${column(ref)}) - JULIANDAY(?))`, [isoDate]);
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3d Task 0 review (H1/L1) — the five helpers above return a MikroORM
+ // `RawQueryFragment`. Handed into a Kysely statement, a `RawQueryFragment`
+ // stringifies through its own `[Symbol.toPrimitive]('string')` coercion into
+ // the literal text `?` (its parameter-placeholder marker, meant for the
+ // MikroORM QueryBuilder's OWN parameter interpolation, not Kysely's) — Kysely
+ // binds it as an actual `?` value parameter and the statement fails at
+ // execution (verified directly, not assumed: `db.selectFrom(...).where(...,
+ // startsWithIsoDate(platform, 'col'))` throws `SqliteError: near "?": syntax
+ // error` the first time it runs). Task 2 absorbed this finding (its report,
+ // H1/L1) — these are genuinely separate functions, not a wrapper over the
+ // ones above, because a Kysely `Expression` and a MikroORM `RawQueryFragment`
+ // are different types with no conversion between them. Each takes the
+ // caller's own `ExpressionBuilder<DB, TB>` (the same "no consumer-facing
+ // generic DB" shape `_shared/reservation-visibility.ts`'s `publicStayExists`
+ // documents is the only one that survives `tsc` for a shared Kysely helper —
+ // unlike that one, these ARE fully generic over `<DB, TB>`, because they only
+ // ever call `eb.fn`/`eb.cast`/`eb(...)`, none of which hit the QueryBuilder
+ // method-chaining inference limit that forced `publicStayExists` to fix its
+ // shape). Platform-dispatched and fail-closed like every helper above; each
+ // has an SQLF-0xx test pinning its compiled `{sql, parameters}` AND a
+ // raw-statement equivalence on seeded rows (`tests/unit/db/dialect/sql-functions.test.ts`).
+ // ---------------------------------------------------------------------------
+
+ /**
+ * The Kysely-expression twin of {@link startsWithIsoDate}: `<ref> GLOB
+ * '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'`, spelled through SQLite's
+ * function form (`glob(X, Y)` is exactly `Y GLOB X` — the inventory's own
+ * §19 finding, since Kysely's `ComparisonOperator` union has no `GLOB`
+ * entry). Returns a boolean `Expression<SqlBool>`, usable in a `.where()`
+ * or inside a `CASE WHEN` condition. Same digit-class pattern as the
+ * MikroORM version — NOT the wider `'????-??-??*'` shorthand (a `?` in
+ * SQLite GLOB matches any character, letters included).
+ */
+ export function startsWithIsoDateKysely<DB, TB extends keyof DB>(
+ platform: Platform,
+ eb: ExpressionBuilder<DB, TB>,
+ ref: ReferenceExpression<DB, TB>,
+ ): ExpressionWrapper<DB, TB, SqlBool> {
+ if (platform instanceof SqlitePlatform) {
+ return eb.fn<SqlBool>('glob', [eb.val('[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*'), ref]);
+ }
+ return unsupported(platform);
+ }
+
+ /**
+ * The Kysely-expression twin of {@link substring}: `substr(<ref>,
+ * <start>[, <length>])`, 1-based on both ends. `start`/`length` are
+ * validated integers, the same guard `substring()` above applies, and bound
+ * as genuine parameters here (`eb.val`) rather than spelled into the SQL
+ * text — Kysely's `fn()` takes `ReferenceExpression`s, not a raw text
+ * fragment, so there is no equivalent "spell a constant into the SQL"
+ * shape to match; a bound integer literal renders identically.
+ */
+ export function substringKysely<DB, TB extends keyof DB>(
+ platform: Platform,
+ eb: ExpressionBuilder<DB, TB>,
+ ref: ReferenceExpression<DB, TB>,
+ start: number,
+ length?: number,
+ ): ExpressionWrapper<DB, TB, string> {
+ if (!Number.isInteger(start) || start < 1) {
+ throw new Error(`sql-functions: substringKysely needs a 1-based integer start, got ${start}`);
+ }
+ if (length !== undefined && (!Number.isInteger(length) || length < 0)) {
+ throw new Error(`sql-functions: substringKysely needs a non-negative integer length, got ${length}`);
+ }
+ if (platform instanceof SqlitePlatform) {
+ const args: ReferenceExpression<DB, TB>[] = length === undefined
+ ? [ref, eb.val(start)]
+ : [ref, eb.val(start), eb.val(length)];
+ return eb.fn<string>('substr', args);
+ }
+ return unsupported(platform);
+ }
+
+ /** A part of a `concatKysely()` expression — a column reference, a bound value, or a nested Kysely `Expression<string>` (composes freely, unlike `concat()`'s MikroORM `RawQueryFragment` form). */
+ export type KyselyConcatPart<DB, TB extends keyof DB> =
+ | { column: StringReference<DB, TB> }
+ | { value: string }
+ | { expression: Expression<string> };
+
+ /**
+ * The Kysely-expression twin of {@link concat}: `<part> || <part> || …`,
+ * SQLite's/Postgres's string concatenation operator, built through the
+ * expression builder's own binary-operator call (`eb(lhs, '||', rhs)`) so
+ * it composes with {@link substringKysely}/{@link castIntegerKysely} —
+ * exactly the composition `concat()`'s MikroORM form cannot do (its
+ * docstring explains why).
+ */
+ export function concatKysely<DB, TB extends keyof DB>(
+ platform: Platform,
+ eb: ExpressionBuilder<DB, TB>,
+ ...parts: readonly KyselyConcatPart<DB, TB>[]
+ ): ExpressionWrapper<DB, TB, string> {
+ if (parts.length < 2) {
+ throw new Error(`sql-functions: concatKysely needs at least two parts, got ${parts.length}`);
+ }
+ if (!(platform instanceof SqlitePlatform)) return unsupported(platform);
+ const operand = (part: KyselyConcatPart<DB, TB>): Expression<string> =>
+ 'column' in part ? eb.ref(part.column).$castTo<string>() : 'value' in part ? eb.val(part.value) : part.expression;
+ let acc: Expression<string> = operand(parts[0]!);
+ for (const part of parts.slice(1)) {
+ acc = eb(acc, '||', operand(part));
+ }
+ // The loop above always runs at least once (the `parts.length < 2` guard
+ // above throws otherwise), so `acc` is always the result of the `eb(...)`
+ // binary-operator call — a real `ExpressionWrapper`, not the bare
+ // `Expression` interface `operand()`'s own return type declares.
+ return acc as ExpressionWrapper<DB, TB, string>;
+ }
+
+ /**
+ * The Kysely-expression twin of {@link castInteger}: `CAST(<ref> AS
+ * INTEGER)`, for `reservations.accommodation_id` (TEXT) compared against an
+ * INTEGER column inside a Kysely statement (RS20/RV2's join shape — a
+ * correlated `EXISTS`/scalar-subquery context the MikroORM QueryBuilder
+ * cannot express, per the inventory's own T6 ruling).
+ */
+ export function castIntegerKysely<DB, TB extends keyof DB>(
+ platform: Platform,
+ eb: ExpressionBuilder<DB, TB>,
+ ref: ReferenceExpression<DB, TB>,
+ ): ExpressionWrapper<DB, TB, number> {
+ if (platform instanceof SqlitePlatform) return eb.cast<number>(ref, 'integer');
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3f Task 0 (R9) — no consumer yet: Task 2 (`collateNoCase`, SH9's
+ // `school-holidays.service.ts#checkName` duplicate-name guard) and Task 4
+ // (`nowMinusHours`, RJ4's `reminder-jobs.service.ts#todoTick`
+ // `datetime('now', '-20 hours')`) wire these in when each converts the
+ // statement that needs them. `lowerTrimParam` (AT31's value side, atlas's
+ // bucket-list dedup) is Task 1's. Added here, with their own SQLF-0xx tests
+ // pinning the SQLite text against a raw statement on seeded rows, so each
+ // task imports a tested helper instead of writing one inline.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * A case-insensitive column reference via SQLite's `NOCASE` collating
+ * sequence, for use as a filter's object key — the same `{ [collateNoCase(
+ * platform, 'name')]: value }` shape `lower()` documents, rendering `WHERE
+ * name COLLATE NOCASE = <value-side>`. The legacy statement this replaces
+ * (`school-holidays.service.ts:50`, SH9) spells the COLLATE on the VALUE
+ * side instead (`name = ? COLLATE NOCASE`) — textually different, but SQLite
+ * resolves a binary comparison's collating sequence from the FIRST operand
+ * that carries an explicit `COLLATE`, scanning left to right, so `col
+ * COLLATE NOCASE = ?` and `col = ? COLLATE NOCASE` select the same collation
+ * (NOCASE) for the whole comparison either way — verified directly
+ * (SQLF-060: both forms select the identical row set on a mixed-case
+ * fixture), not assumed from the operator's documented precedence alone.
+ *
+ * **Not the same helper as `lower()`, and not reusable in its place.**
+ * SQLite's built-in `NOCASE` collation is documented to fold ONLY the 26
+ * ASCII letters, exactly like `LOWER()`'s own ASCII-only fold (program rule
+ * 18) — verified directly against `better-sqlite3` (SQLF-061): on every
+ * non-ASCII fixture this file's own `LOWER()` test (SQLF-014) already
+ * carries, `x = y COLLATE NOCASE` and `LOWER(x) = LOWER(y)` agree, letter for
+ * letter — neither engine folds a non-ASCII case pair. So `collateNoCase`
+ * does NOT diverge from `lower()` on any input constructed here; it is a
+ * NEW helper anyway (per R9's own instruction) because the two are
+ * textually different SQL constructs matching two textually different
+ * legacy statements (`COLLATE NOCASE` vs `LOWER(...)`), and because a
+ * `COLLATE`-based comparison lets SQLite use an index on the un-wrapped
+ * column in a way `LOWER(col) = ?` cannot — a real, if not row-visible,
+ * difference between the two shapes.
+ */
+ export function collateNoCase(platform: Platform, ref: string): RawQueryFragment & symbol {
+ if (platform instanceof SqlitePlatform) return raw(`${column(ref)} COLLATE NOCASE`);
+ return unsupported(platform);
+ }
+
+ /**
+ * `datetime('now', '-N hours')` — the hour-granularity sibling of
+ * `nowMinusDays()` above, for `reminder-jobs.service.ts#todoTick`'s
+ * `datetime('now', '-20 hours')` (RJ4) — 20 hours is not expressible as
+ * `nowMinusDays` with a fractional day. Same validation shape as
+ * `nowMinusDays` (a non-negative integer, spelled directly into the
+ * fragment rather than bound — MikroORM's raw fragments do not accept a
+ * placeholder inside a SQLite date/time function's modifier argument, the
+ * same reasoning `nowMinusDays`'s own docstring gives).
+ */
+ export function nowMinusHours(platform: Platform, hours: number): RawQueryFragment {
+ if (!Number.isInteger(hours) || hours < 0) {
+ throw new Error(`sql-functions: nowMinusHours needs a non-negative integer hour count, got ${hours}`);
+ }
+ if (platform instanceof SqlitePlatform) return raw(`datetime('now', '-${hours} hours')`);
+ return unsupported(platform);
+ }
+
+ /**
+ * The value-side twin of `lowerTrim()`: `LOWER(TRIM(?))` bound with the RAW,
+ * untransformed value — confirmed genuinely missing by reading this file's
+ * full export list before adding it (R9), not assumed from the inventory's
+ * own flag. Pairs with `lowerTrim()` as a filter KEY for the composed
+ * `LOWER(TRIM(<column>)) = LOWER(TRIM(?))` shape
+ * `atlas.service.ts:876-877`'s AT31 needs (`lower(trim(name)) =
+ * lower(trim(?))`), the same "bind the raw value, let SQL apply the SAME
+ * transform to both sides" reasoning `lowerParam()`'s own docstring gives —
+ * do NOT pre-trim/pre-lower the value in JS before calling this (program
+ * rule 18: mixing engines is the bug this pairing exists to avoid).
+ */
+ export function lowerTrimParam(platform: Platform, value: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) return raw('LOWER(TRIM(?))', [value]);
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3g Task 0 (R1) — no consumer yet: Task 1 (`getJourneyFull`'s gallery
+ // read) and Task 3 (`getPublicJourney`'s gallery read) each fold this into
+ // their own rebuild of `journey-gallery-order.ts`'s `GALLERY_CHRONOLOGICAL_ORDER`
+ // text (a `COALESCE(NULLIF(tp.taken_at, ''), <correlated MIN+concat subquery>,
+ // <this>)` ORDER BY, worked out in full in Task 0's report for both to paste
+ // in verbatim, neither re-deriving it). Added here, Kysely-only (no MikroORM
+ // `raw()` sibling): the shape it exists for is genuinely Kysely-only (a
+ // correlated scalar subquery cannot be expressed through the MikroORM
+ // QueryBuilder — the same "T6 ruling" `castIntegerKysely`'s own docstring
+ // cites for RS20/RV2), and nothing else in this plan's inventory needs a
+ // MikroORM-form epoch-to-ISO conversion (§6: "no other strftime/julianday
+ // sites found elsewhere in this cluster"). A raw twin can be added later,
+ // same as every other helper here, the moment a real consumer needs one.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `strftime('%Y-%m-%dT%H:%M:%SZ', <ref> / 1000, 'unixepoch')` — the last of
+ * `GALLERY_CHRONOLOGICAL_ORDER`'s three fallback tiers (R1): when a gallery
+ * photo has neither a capture time (`tp.taken_at`) nor a linked entry to
+ * borrow a date from, the moment it was added is what is left to order by.
+ * `<ref>` is an epoch-MILLISECONDS column (`journey_photos.created_at`, like
+ * every other `*_at` epoch column in this codebase) — SQLite's `unixepoch`
+ * modifier expects whole SECONDS, so the division is load-bearing, not
+ * decorative, and matches the legacy text's own `gp.created_at / 1000`
+ * exactly. SQLite's `/` on two integers truncates instead of rounding; that
+ * sub-second loss is the legacy statement's own behaviour, preserved here
+ * rather than "fixed" into a float divide that would render a different ISO
+ * string for any timestamp not an exact multiple of 1000ms.
+ *
+ * Named for what it computes, not the SQL function it spells — matching
+ * every other `*Kysely` twin in this file (`castIntegerKysely`, not
+ * `castKysely`; `startsWithIsoDateKysely`, not `globKysely`).
+ */
+ export function unixEpochToIsoKysely<DB, TB extends keyof DB>(
+ platform: Platform,
+ eb: ExpressionBuilder<DB, TB>,
+ ref: ReferenceExpression<DB, TB>,
+ ): ExpressionWrapper<DB, TB, string> {
+ if (platform instanceof SqlitePlatform) {
+ const seconds = eb(ref, '/', eb.val(1000));
+ return eb.fn<string>('strftime', [eb.val('%Y-%m-%dT%H:%M:%SZ'), seconds, eb.val('unixepoch')]);
+ }
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3h Task 0 — no consumer yet: Task 3 (`dawarich-sync.service.ts`'s
+ // `listTripsToSync`, DSY2 — `date('now','-400 days')` / `date('now','+1
+ // day')`) and Task 4 (`route-usage.service.ts`'s `purgeExpired`, RU4 —
+ // `date('now', ?)` bound with the modifier `-${RETENTION_DAYS} days`, and
+ // RETENTION_DAYS (`route-usage.service.ts:13`) is a compile-time module
+ // constant (`400`), not a runtime value — so RU4's "bound parameter" and
+ // DSY2's "literal" are the SAME shape at the call site once the modifier is
+ // known, confirmed directly against both files' actual source rather than
+ // assumed from the legacy SQL's own binding style) wire `nowDateOffset` in
+ // when each converts its own statement.
+ //
+ // Plan 3f's own four `date('now')` sites (atlas.service.ts AT39/AT42/AT44/
+ // AT45 — 3g's inventory's own open question, inherited from 3f and never
+ // resolved until now) do NOT go through a dialect helper at all: `todayUtc()`
+ // (a `@trek/shared` JS function) resolves the calendar date once in the
+ // CALLING SERVICE (`atlas.service.ts:912`, `const trip = await
+ // this.trips.lastStartedTrip(userId, todayUtc())`) and the repository binds
+ // it as a plain parameter (`Trips.repository.ts#lastStartedTrip`:
+ // `.where((eb) => eb(eb.fn.coalesce('t.start_date', 't.end_date'), '<=',
+ // today))`) — confirmed by reading the actual converted code at HEAD, not
+ // the plan document's description of it. That pattern covers a BARE
+ // `date('now')` (no offset) cleanly, and needs no new helper here. It does
+ // not extend to an OFFSET the way DSY2/RU4 need without every call site
+ // re-deriving day arithmetic in JS by hand, so this file instead grows the
+ // sibling `nowMinusDays`/`nowMinusHours` already establish for exactly this
+ // family (Plan 3c Task 0b/Plan 3f Task 0 R9): a signed day-count offset from
+ // "now", spelled into the fragment after integer validation, the same
+ // reasoning those two helpers give (MikroORM's raw fragments do not accept a
+ // placeholder inside a SQLite date/time function's modifier argument).
+ // `PlaceShadowPicksRepository.expireStale` (Plan 3c Task 1) is this shape's
+ // own closest working precedent — a retention-window purge built on
+ // `nowMinusDays` exactly the way `RouteUsageDailyRepository`'s own purge
+ // (RU4) will be built on `nowDateOffset` below.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `date('now', '<sign>N days')` — the SQLite clock's CALENDAR DATE (`date()`,
+ * not `datetime()` — `nowMinusDays` above is the wrong shape for this: it
+ * targets `datetime()`, and only ever subtracts), shifted by a signed whole
+ * day count. Unlike `nowMinusDays`, `days` may be POSITIVE (forward),
+ * NEGATIVE (backward) or zero — `dawarich-sync.service.ts`'s
+ * `listTripsToSync` (DSY2) needs both directions in the SAME statement
+ * (`date('now','-400 days')` for the trailing edge, `date('now','+1 day')`
+ * for the leading one). `days` is spelled directly into the fragment (not
+ * bound), the same reasoning `nowMinusDays`'s own docstring gives.
+ *
+ * Verified directly (not assumed) that SQLite's modifier keyword tolerates
+ * the singular/plural mismatch between the two legacy texts (`'+1 day'`
+ * singular, `'-400 days'` plural): `date('now','+1 day')` and
+ * `date('now','+1 days')` render the identical result against a live
+ * `better-sqlite3` connection, so this helper's always-plural spelling is
+ * behaviourally identical to both legacy statements, not just the plural one.
+ */
+ export function nowDateOffset(platform: Platform, days: number): RawQueryFragment {
+ if (!Number.isInteger(days)) {
+ throw new Error(`sql-functions: nowDateOffset needs an integer day count, got ${days}`);
+ }
+ if (platform instanceof SqlitePlatform) {
+ const sign = days < 0 ? '-' : '+';
+ return raw(`date('now', '${sign}${Math.abs(days)} days')`);
+ }
+ return unsupported(platform);
+ }
+
+ /**
+ * `datetime('now', '+N seconds')` — the seconds-granularity, ADDING sibling
+ * of `nowMinusDays`/`nowMinusHours` above: the shape `doc-sync.service.ts`'s
+ * `upsertItem` (DS23, inside an `ON CONFLICT DO UPDATE`'s `CASE WHEN`; DS26,
+ * inside the sibling `INSERT ... VALUES`) and `recordLinkFailure` (a third,
+ * structurally identical call site found re-reading the file at HEAD —
+ * `next_attempt_at = datetime('now', '+' || ? || ' seconds')`,
+ * `doc-sync.service.ts:967`, not individually numbered in the plan's own
+ * inventory) all need: a caller-computed backoff window (`backoffSeconds(
+ * ...)`, a genuine RUNTIME value, never a source-code constant the way
+ * `nowMinusDays`'s callers' day counts are) added to the database clock.
+ * `seconds` is validated non-negative-integer and spelled directly into the
+ * fragment — the same reasoning (and the same MikroORM raw-fragment
+ * placeholder limitation) `nowMinusDays`'s own docstring gives; every known
+ * call site's `seconds` argument is already a JS-computed `number`, never
+ * user input, the same trust boundary this file relies on elsewhere
+ * (`dateAdd`'s day count, `substring`'s start/length).
+ */
+ export function nowPlusSeconds(platform: Platform, seconds: number): RawQueryFragment {
+ if (!Number.isInteger(seconds) || seconds < 0) {
+ throw new Error(`sql-functions: nowPlusSeconds needs a non-negative integer second count, got ${seconds}`);
+ }
+ if (platform instanceof SqlitePlatform) return raw(`datetime('now', '+${seconds} seconds')`);
+ return unsupported(platform);
+ }
+
+ /**
+ * The Kysely-expression twin of {@link nowPlusSeconds}: DS23/DS24's
+ * `ON CONFLICT ... DO UPDATE` / `INSERT ... VALUES` (R3) is a hand-typed
+ * Kysely statement — MikroORM's `em.upsert` cannot express a
+ * partial-unique-index conflict target (R3's own ruling) — so the
+ * `next_attempt_at` computation inside its `CASE WHEN` needs a Kysely
+ * `Expression`, not a MikroORM `RawQueryFragment` (SQLF-048: a
+ * `RawQueryFragment` throws when handed into a Kysely statement). Same
+ * validation, same always-non-negative-integer trust boundary as the
+ * MikroORM form above.
+ */
+ export function nowPlusSecondsKysely<DB, TB extends keyof DB>(
+ platform: Platform,
+ eb: ExpressionBuilder<DB, TB>,
+ seconds: number,
+ ): ExpressionWrapper<DB, TB, string> {
+ if (!Number.isInteger(seconds) || seconds < 0) {
+ throw new Error(`sql-functions: nowPlusSecondsKysely needs a non-negative integer second count, got ${seconds}`);
+ }
+ if (platform instanceof SqlitePlatform) {
+ return eb.fn<string>('datetime', [eb.val('now'), eb.val(`+${seconds} seconds`)]);
+ }
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3h Task 5 (doc-sync) — `FOUND_AGAIN` (`doc-sync.service.ts:53-54`), the
+ // module-level SQL-text CASE constant reused by four legacy UPDATEs (DS2
+ // `relocate`, DS3 `rename_remote`, DS5 `rename_local`, DS12 `touch`). Unlike
+ // every other CASE in this file's DS2-DS12 neighbourhood — whose WHEN
+ // condition binds a value already known in JS at the call site (a boolean
+ // flag, a state string), so the whole CASE collapses to a plain JS ternary
+ // deciding which field to include in a `nativeUpdate` call — this one
+ // compares the ROW'S OWN CURRENT `state`/`file_id` columns, which are not
+ // knowable until the UPDATE executes. That is genuinely SQL-level, and the
+ // four call sites share one method (`DocumentSyncItemsRepository`'s private
+ // `foundAgain` builder) rather than four independent re-derivations, per the
+ // task's own instruction to keep `FOUND_AGAIN` "a reusable typed CASE
+ // expression ... consumed by all four".
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `CASE WHEN <stateRef> = 'remote_missing' AND <fileIdRef> IS NOT NULL THEN
+ * 'synced' ELSE <stateRef> END` — doc-sync's `FOUND_AGAIN` clause, for the
+ * `state` column of an UPDATE `document_sync_items` SET list. Only a copy
+ * that is BOTH on record as missing AND still paired to a file recovers this
+ * way; every other state (`error`, `conflict`, a row with no file at all)
+ * passes through unchanged. `remote_missing_at` is cleared unconditionally
+ * by the SAME UPDATE's own `remote_missing_at = NULL` (a plain value, not
+ * part of this fragment — the caller sets it alongside).
+ */
+ export function foundAgainState(platform: Platform, stateRef: string, fileIdRef: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) {
+ return raw(
+ `CASE WHEN ${column(stateRef)} = 'remote_missing' AND ${column(fileIdRef)} IS NOT NULL THEN 'synced' ELSE ${column(stateRef)} END`,
+ );
+ }
+ return unsupported(platform);
+ }
+
+ /**
+ * The Kysely-expression twin of {@link currentTimestamp}: the bare
+ * `CURRENT_TIMESTAMP` keyword, for a value position inside a hand-typed
+ * Kysely statement (DS24's `ON CONFLICT ... DO UPDATE SET last_seen_at =
+ * CURRENT_TIMESTAMP` — R3's partial-index upsert). Verified directly against
+ * `better-sqlite3` that SQLite accepts the bare keyword (`SELECT
+ * CURRENT_TIMESTAMP`) but rejects it called as a function
+ * (`SELECT CURRENT_TIMESTAMP()` → `near "(": syntax error`), so
+ * `eb.fn('current_timestamp', [])` — every other helper in this file's
+ * usual Kysely shape — is not an option here; the whole point of a keyword
+ * literal is that it takes no parentheses. This is this file's one
+ * Kysely-side use of the `sql` template tag — confined here, the sanctioned
+ * escape hatch this file already is for every raw-SQL spelling in the
+ * codebase (the MikroORM helpers above use `raw()` for the identical
+ * reason), never inline in a repository (the TRAP list's "Kysely `sql`
+ * banned under repositories" is about repository FILES, not this one).
+ */
+ export function currentTimestampKysely(platform: Platform): RawBuilder<string> {
+ if (platform instanceof SqlitePlatform) return sql<string>`CURRENT_TIMESTAMP`;
+ return unsupported(platform);
+ }
+
+ // ---------------------------------------------------------------------------
+ // `UsersRepository.setImmichSettings` (IM4, #2475): the self-signed switch is
+ // trusted for ONE server, so whether a null incoming value may keep the stored
+ // choice depends on whether the URL written in the same SET list is the URL
+ // already stored. Like `foundAgainState` above, the WHEN condition reads the
+ // ROW'S OWN CURRENT column, which is not knowable in JS before the UPDATE runs
+ // — a read-then-write would be two statements where the legacy SQL had one.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `CASE WHEN <keyRef> IS ? THEN COALESCE(?, <ref>) ELSE COALESCE(?, 0) END` —
+ * {@link coalesceOverride}'s "new value wins unless it is null" shape, but the
+ * stored column is only a valid fallback WHILE the key column still holds
+ * `keyValue` (the value the same UPDATE writes to it). Once the key changes,
+ * a null `value` falls back to the column's default `0` instead of a choice
+ * made for a different key. SET expressions see the row as it was before the
+ * UPDATE, so `<keyRef> IS ?` compares the STORED key with the new one even
+ * though the same statement overwrites it. `value` is bound twice on purpose:
+ * the fragment has two value slots and `raw()` binds positionally.
+ */
+ export function coalesceOverrideWhileSame(platform: Platform, value: number | null, ref: string, keyRef: string, keyValue: string): RawQueryFragment {
+ if (platform instanceof SqlitePlatform) {
+ return raw(`CASE WHEN ${column(keyRef)} IS ? THEN COALESCE(?, ${column(ref)}) ELSE COALESCE(?, 0) END`, [keyValue, value, value]);
+ }
+ return unsupported(platform);
+ }
+
++
++// ---------------------------------------------------------------------------
++// Tours (#2586): `DayAssignmentsRepository`'s assignment projection carries a
++// place's route geometry only when the place is a Tour, so the day list never
++// hauls an ordinary track's geometry along with every stop.
++// ---------------------------------------------------------------------------
++
++/**
++ * `CASE WHEN <testRef> IS NOT NULL THEN <thenRef> END`, for use as a
++ * `.select()` value (chain `.as(aliasName)` at the call site). The missing
++ * ELSE is deliberate: a null test column yields SQL NULL.
++ */
++export function caseWhenNotNull(platform: Platform, testRef: string, thenRef: string): RawQueryFragment {
++ if (platform instanceof SqlitePlatform) return raw(`CASE WHEN ${column(testRef)} IS NOT NULL THEN ${column(thenRef)} END`);
++ return unsupported(platform);
++}
diff --cc server/src/db/entities/Places.entity.ts
index 000000000,2f867ab74..6bb49853a
mode 000000,100644..100644
--- a/server/src/db/entities/Places.entity.ts
+++ b/server/src/db/entities/Places.entity.ts
@@@ -1,0 -1,127 +1,130 @@@
+ import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
+ import { PlacesRepository } from '../repositories/Places.repository';
+ import { DbTimestampType } from '../types';
+ import { BudgetItems } from './BudgetItems.entity';
+ import { Categories } from './Categories.entity';
+ import { DawarichVisitSuggestions } from './DawarichVisitSuggestions.entity';
+ import { DayAccommodations } from './DayAccommodations.entity';
+ import { DayAssignments } from './DayAssignments.entity';
+ import { FileLinks } from './FileLinks.entity';
+ import { JourneyEntries } from './JourneyEntries.entity';
+ import { Photos } from './Photos.entity';
+ import { PlaceRatings } from './PlaceRatings.entity';
+ import { PlaceRegions } from './PlaceRegions.entity';
+ import { Reservations } from './Reservations.entity';
+ import { RoadtripDayTracks } from './RoadtripDayTracks.entity';
+ import { Tags } from './Tags.entity';
++import { Tours } from './Tours.entity';
+ import { TripFiles } from './TripFiles.entity';
+ import { Trips } from './Trips.entity';
+
+ export class Places {
+ [EntityRepositoryType]?: PlacesRepository;
+ id!: number & Opt;
+ trip!: Ref<Trips>;
+ trip_id!: number;
+ name!: string;
+ description?: string | null;
+ lat?: number | null;
+ lng?: number | null;
+ address?: string | null;
+ category?: Ref<Categories> | null;
+ category_id?: number | null;
+ price?: number | null;
+ currency?: string | null;
+ reservation_status?: string | null = 'none';
+ reservation_notes?: string | null;
+ reservation_datetime?: string | null;
+ place_time?: string | null;
+ end_time?: string | null;
+ duration_minutes?: number | null = 60;
+ notes?: string | null;
+ image_url?: string | null;
+ google_place_id?: string | null;
+ google_ftid?: string | null;
+ website?: string | null;
+ phone?: string | null;
+ transport_mode?: string | null = 'walking';
+ created_at?: string | null;
+ updated_at?: string | null;
+ osm_id?: string | null;
+ route_geometry?: string | null;
+ route_color?: string | null;
+ stop_type?: string | null;
+ fill_percent?: number | null;
+ amap_poi_id?: string | null;
+ source?: string | null;
+ email?: string | null;
+ opening_hours?: string | null;
+ place_tags = new Collection<Tags>(this);
+ budget_items_collection = new Collection<BudgetItems>(this);
+ dawarich_visit_suggestions_collection = new Collection<DawarichVisitSuggestions>(this);
+ day_accommodations_collection = new Collection<DayAccommodations>(this);
+ day_assignments_collection = new Collection<DayAssignments>(this);
+ file_links_collection = new Collection<FileLinks>(this);
+ journey_entries_collection = new Collection<JourneyEntries>(this);
+ photos_collection = new Collection<Photos>(this);
+ place_ratings_collection = new Collection<PlaceRatings>(this);
+ place_regions: Ref<PlaceRegions> | null = null;
+ reservations_collection = new Collection<Reservations>(this);
+ roadtrip_day_tracks_collection = new Collection<RoadtripDayTracks>(this);
++ tours: Ref<Tours> | null = null;
+ trip_files_collection = new Collection<TripFiles>(this);
+ }
+
+ export const PlacesSchema = defineEntity({
+ class: Places,
+ repository: () => PlacesRepository,
+ properties: {
+ id: p.integer().primary(),
+ trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_places_trip_id'),
+ trip_id: p.integer().persist(false).index('idx_places_trip_id'),
+ name: p.text(),
+ description: p.text().nullable(),
+ lat: p.double().nullable(),
+ lng: p.double().nullable(),
+ address: p.text().nullable(),
+ category: () => p.manyToOne(Categories).ref().nullable().hidden().index('idx_places_category_id'),
+ category_id: p.integer().nullable().persist(false).index('idx_places_category_id'),
+ price: p.double().nullable(),
+ currency: p.text().nullable(),
+ reservation_status: p.text().nullable(),
+ reservation_notes: p.text().nullable(),
+ reservation_datetime: p.text().nullable(),
+ place_time: p.text().nullable(),
+ end_time: p.text().nullable(),
+ duration_minutes: p.integer().nullable(),
+ notes: p.text().nullable(),
+ image_url: p.text().nullable(),
+ google_place_id: p.text().nullable(),
+ google_ftid: p.text().nullable(),
+ website: p.text().nullable(),
+ phone: p.text().nullable(),
+ transport_mode: p.text().nullable(),
+ created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
+ updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
+ osm_id: p.text().nullable(),
+ route_geometry: p.text().nullable(),
+ route_color: p.text().nullable(),
+ stop_type: p.text().nullable(),
+ fill_percent: p.integer().nullable(),
+ amap_poi_id: p.text().nullable(),
+ source: p.text().nullable(),
+ email: p.text().nullable(),
+ opening_hours: p.text().nullable(),
+ place_tags: () => p.manyToMany(Tags).pivotTable('place_tags').joinColumn('place_id').inverseJoinColumn('tag_id').hidden(),
+ budget_items_collection: () => p.oneToMany(BudgetItems).mappedBy('place').hidden(),
+ dawarich_visit_suggestions_collection: () => p.oneToMany(DawarichVisitSuggestions).mappedBy('acceptedPlace').hidden(),
+ day_accommodations_collection: () => p.oneToMany(DayAccommodations).mappedBy('place').hidden(),
+ day_assignments_collection: () => p.oneToMany(DayAssignments).mappedBy('place').hidden(),
+ file_links_collection: () => p.oneToMany(FileLinks).mappedBy('place').hidden(),
+ journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('sourcePlace').hidden(),
+ photos_collection: () => p.oneToMany(Photos).mappedBy('place').hidden(),
+ place_ratings_collection: () => p.oneToMany(PlaceRatings).mappedBy('place').hidden(),
+ place_regions: () => p.oneToOne(PlaceRegions).ref().mappedBy('place').hidden(),
+ reservations_collection: () => p.oneToMany(Reservations).mappedBy('place').hidden(),
+ roadtrip_day_tracks_collection: () => p.oneToMany(RoadtripDayTracks).mappedBy('place').hidden(),
++ tours: () => p.oneToOne(Tours).ref().mappedBy('place').hidden(),
+ trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('place').hidden(),
+ },
+ });
diff --cc server/src/db/entities/TourTypes.entity.ts
index 000000000,000000000..abf6573b5
new file mode 100644
--- /dev/null
+++ b/server/src/db/entities/TourTypes.entity.ts
@@@ -1,0 -1,0 +1,33 @@@
++import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
++import { TourTypesRepository } from '../repositories/TourTypes.repository';
++import { Tours } from './Tours.entity';
++
++export class TourTypes {
++ [EntityRepositoryType]?: TourTypesRepository;
++ [PrimaryKeyProp]?: 'key';
++ key?: string | null;
++ label_key!: string;
++ icon!: string;
++ color!: string;
++ routing_profile?: string | null;
++ is_sport: number & Opt = 1;
++ enabled: number & Opt = 1;
++ sort_order: number & Opt = 0;
++ tours_collection = new Collection<Tours>(this);
++}
++
++export const TourTypesSchema = defineEntity({
++ class: TourTypes,
++ repository: () => TourTypesRepository,
++ properties: {
++ key: p.text().primary().nullable(),
++ label_key: p.text(),
++ icon: p.text(),
++ color: p.text(),
++ routing_profile: p.text().nullable(),
++ is_sport: p.integer().default(1),
++ enabled: p.integer().default(1),
++ sort_order: p.integer().default(0),
++ tours_collection: () => p.oneToMany(Tours).mappedBy('tourTypeRef').hidden(),
++ },
++});
diff --cc server/src/db/entities/TourWaypoints.entity.ts
index 000000000,000000000..0f6a6ab80
new file mode 100644
--- /dev/null
+++ b/server/src/db/entities/TourWaypoints.entity.ts
@@@ -1,0 -1,0 +1,29 @@@
++import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
++import { TourWaypointsRepository } from '../repositories/TourWaypoints.repository';
++import { Tours } from './Tours.entity';
++
++export class TourWaypoints {
++ [EntityRepositoryType]?: TourWaypointsRepository;
++ id!: number & Opt;
++ place!: Ref<Tours>;
++ place_id!: number;
++ lat!: number;
++ lng!: number;
++ role!: string;
++ sequence!: number;
++}
++
++export const TourWaypointsSchema = defineEntity({
++ class: TourWaypoints,
++ repository: () => TourWaypointsRepository,
++ uniques: [{ properties: ['place', 'sequence'] }],
++ properties: {
++ id: p.integer().primary(),
++ place: () => p.manyToOne(Tours).ref().name('place_id').deleteRule('cascade').hidden(),
++ place_id: p.integer().persist(false),
++ lat: p.double(),
++ lng: p.double(),
++ role: p.text(),
++ sequence: p.integer(),
++ },
++});
diff --cc server/src/db/entities/Tours.entity.ts
index 000000000,000000000..beedbaad7
new file mode 100644
--- /dev/null
+++ b/server/src/db/entities/Tours.entity.ts
@@@ -1,0 -1,0 +1,47 @@@
++import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
++import { ToursRepository } from '../repositories/Tours.repository';
++import { Places } from './Places.entity';
++import { TourTypes } from './TourTypes.entity';
++import { TourWaypoints } from './TourWaypoints.entity';
++
++export class Tours {
++ [EntityRepositoryType]?: ToursRepository;
++ [PrimaryKeyProp]?: 'place';
++ place?: Ref<Places> | null;
++ place_id?: number | null;
++ tour_type!: string;
++ distance?: number | null;
++ elevation_gain?: number | null;
++ elevation_loss?: number | null;
++ duration?: number | null;
++ difficulty?: string | null;
++ wanderer_ref?: string | null;
++ match_confidence?: number | null;
++ tour_group_id?: number | null;
++ created_at?: string | null;
++ max_hiking_difficulty: number & Opt = 2;
++ tourTypeRef!: Ref<TourTypes>;
++ tour_waypoints_collection = new Collection<TourWaypoints>(this);
++}
++
++export const ToursSchema = defineEntity({
++ class: Tours,
++ repository: () => ToursRepository,
++ properties: {
++ place: () => p.oneToOne(Places).primary().ref().deleteRule('cascade').nullable().hidden(),
++ place_id: p.integer().nullable().persist(false),
++ tour_type: p.text().persist(false).index('idx_tours_tour_type'),
++ distance: p.double().nullable(),
++ elevation_gain: p.double().nullable(),
++ elevation_loss: p.double().nullable(),
++ duration: p.double().nullable(),
++ difficulty: p.text().nullable(),
++ wanderer_ref: p.text().nullable(),
++ match_confidence: p.double().nullable(),
++ tour_group_id: p.integer().nullable(),
++ created_at: p.text().nullable().defaultRaw(`CURRENT_TIMESTAMP`),
++ max_hiking_difficulty: p.integer().default(2),
++ tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
++ tour_waypoints_collection: () => p.oneToMany(TourWaypoints).mappedBy('place').hidden(),
++ },
++});
diff --cc server/src/db/entities/index.ts
index 000000000,adde2a392..60958f950
mode 000000,100644..100644
--- a/server/src/db/entities/index.ts
+++ b/server/src/db/entities/index.ts
@@@ -1,0 -1,258 +1,264 @@@
+ import type { EntitySchema } from '@mikro-orm/core';
+ import { AddonsSchema } from './Addons.entity';
+ import { AppSettingsSchema } from './AppSettings.entity';
+ import { AssignmentParticipantsSchema } from './AssignmentParticipants.entity';
+ import { AuditLogSchema } from './AuditLog.entity';
+ import { BucketListSchema } from './BucketList.entity';
+ import { BudgetCategoryOrderSchema } from './BudgetCategoryOrder.entity';
+ import { BudgetItemMembersSchema } from './BudgetItemMembers.entity';
+ import { BudgetItemPayersSchema } from './BudgetItemPayers.entity';
+ import { BudgetItemsSchema } from './BudgetItems.entity';
+ import { BudgetSettlementsSchema } from './BudgetSettlements.entity';
+ import { CategoriesSchema } from './Categories.entity';
+ import { CollabLinksSchema } from './CollabLinks.entity';
+ import { CollabMessageReactionsSchema } from './CollabMessageReactions.entity';
+ import { CollabMessagesSchema } from './CollabMessages.entity';
+ import { CollabNotesSchema } from './CollabNotes.entity';
+ import { CollabPollVotesSchema } from './CollabPollVotes.entity';
+ import { CollabPollsSchema } from './CollabPolls.entity';
+ import { CollectionLabelsSchema } from './CollectionLabels.entity';
+ import { CollectionMembersSchema } from './CollectionMembers.entity';
+ import { CollectionPlaceRatingsSchema } from './CollectionPlaceRatings.entity';
+ import { CollectionPlacesSchema } from './CollectionPlaces.entity';
+ import { CollectionsSchema } from './Collections.entity';
+ import { DawarichConnectionsSchema } from './DawarichConnections.entity';
+ import { DawarichVisitSuggestionsSchema } from './DawarichVisitSuggestions.entity';
+ import { DayAccommodationsSchema } from './DayAccommodations.entity';
+ import { DayAssignmentsSchema } from './DayAssignments.entity';
+ import { DayNotesSchema } from './DayNotes.entity';
+ import { DaysSchema } from './Days.entity';
+ import { DocumentConnectionsSchema } from './DocumentConnections.entity';
+ import { DocumentProviderFieldsSchema } from './DocumentProviderFields.entity';
+ import { DocumentProvidersSchema } from './DocumentProviders.entity';
+ import { DocumentSyncItemsSchema } from './DocumentSyncItems.entity';
+ import { FileLinksSchema } from './FileLinks.entity';
+ import { GoogleApiUsageSchema } from './GoogleApiUsage.entity';
+ import { GooglePlacePhotoMetaSchema } from './GooglePlacePhotoMeta.entity';
+ import { HiddenCountriesSchema } from './HiddenCountries.entity';
+ import { HiddenRegionsSchema } from './HiddenRegions.entity';
+ import { IdempotencyKeysSchema } from './IdempotencyKeys.entity';
+ import { InviteTokensSchema } from './InviteTokens.entity';
+ import { JourneyBooksSchema } from './JourneyBooks.entity';
+ import { JourneyContributorsSchema } from './JourneyContributors.entity';
+ import { JourneyEntriesSchema } from './JourneyEntries.entity';
+ import { JourneyEntryPhotosSchema } from './JourneyEntryPhotos.entity';
+ import { JourneyPhotosSchema } from './JourneyPhotos.entity';
+ import { JourneyShareTokensSchema } from './JourneyShareTokens.entity';
+ import { JourneyTripsSchema } from './JourneyTrips.entity';
+ import { JourneysSchema } from './Journeys.entity';
+ import { McpTokensSchema } from './McpTokens.entity';
+ import { MigrationsSchema } from './Migrations.entity';
+ import { NotificationChannelPreferencesSchema } from './NotificationChannelPreferences.entity';
+ import { NotificationsSchema } from './Notifications.entity';
+ import { OauthClientsSchema } from './OauthClients.entity';
+ import { OauthConsentsSchema } from './OauthConsents.entity';
+ import { OauthTokensSchema } from './OauthTokens.entity';
+ import { PackingBagsSchema } from './PackingBags.entity';
+ import { PackingCategoryAssigneesSchema } from './PackingCategoryAssignees.entity';
+ import { PackingItemContributorsSchema } from './PackingItemContributors.entity';
+ import { PackingItemsSchema } from './PackingItems.entity';
+ import { PackingTemplateCategoriesSchema } from './PackingTemplateCategories.entity';
+ import { PackingTemplateItemsSchema } from './PackingTemplateItems.entity';
+ import { PackingTemplatesSchema } from './PackingTemplates.entity';
+ import { PasswordResetTokensSchema } from './PasswordResetTokens.entity';
+ import { PhotoProviderFieldsSchema } from './PhotoProviderFields.entity';
+ import { PhotoProvidersSchema } from './PhotoProviders.entity';
+ import { PhotosSchema } from './Photos.entity';
+ import { PlaceDetailsCacheSchema } from './PlaceDetailsCache.entity';
+ import { PlaceRatingsSchema } from './PlaceRatings.entity';
+ import { PlaceRegionsSchema } from './PlaceRegions.entity';
+ import { PlaceShadowPicksSchema } from './PlaceShadowPicks.entity';
+ import { PlacesSchema } from './Places.entity';
+ import { PluginActionsSchema } from './PluginActions.entity';
+ import { PluginCapabilityAuditSchema } from './PluginCapabilityAudit.entity';
+ import { PluginEgressHostsSchema } from './PluginEgressHosts.entity';
+ import { PluginEntityMetadataSchema } from './PluginEntityMetadata.entity';
+ import { PluginErrorLogSchema } from './PluginErrorLog.entity';
+ import { PluginMetaMigrationsSchema } from './PluginMetaMigrations.entity';
+ import { PluginOauthStateSchema } from './PluginOauthState.entity';
+ import { PluginOauthTokensSchema } from './PluginOauthTokens.entity';
+ import { PluginScheduledTasksSchema } from './PluginScheduledTasks.entity';
+ import { PluginSettingsFieldsSchema } from './PluginSettingsFields.entity';
+ import { PluginUserConfigSchema } from './PluginUserConfig.entity';
+ import { PluginUserErasureQueueSchema } from './PluginUserErasureQueue.entity';
+ import { PluginsSchema } from './Plugins.entity';
+ import { PushSubscriptionsSchema } from './PushSubscriptions.entity';
+ import { ReservationDayPositionsSchema } from './ReservationDayPositions.entity';
+ import { ReservationEndpointsSchema } from './ReservationEndpoints.entity';
+ import { ReservationTravelersSchema } from './ReservationTravelers.entity';
+ import { ReservationsSchema } from './Reservations.entity';
+ import { RoadtripDayBoundariesSchema } from './RoadtripDayBoundaries.entity';
+ import { RoadtripDayTracksSchema } from './RoadtripDayTracks.entity';
+ import { RoadtripPreferencesSchema } from './RoadtripPreferences.entity';
+ import { RoadtripViasSchema } from './RoadtripVias.entity';
+ import { RouteUsageDailySchema } from './RouteUsageDaily.entity';
+ import { SchemaVersionSchema } from './SchemaVersion.entity';
+ import { SchoolHolidayCountriesSchema } from './SchoolHolidayCountries.entity';
+ import { SchoolHolidayPeriodsSchema } from './SchoolHolidayPeriods.entity';
+ import { SchoolHolidayRegionsSchema } from './SchoolHolidayRegions.entity';
+ import { SettingsSchema } from './Settings.entity';
+ import { ShareTokensSchema } from './ShareTokens.entity';
+ import { TagsSchema } from './Tags.entity';
+ import { TodoCategoryAssigneesSchema } from './TodoCategoryAssignees.entity';
+ import { TodoItemsSchema } from './TodoItems.entity';
++import { TourTypesSchema } from './TourTypes.entity';
++import { TourWaypointsSchema } from './TourWaypoints.entity';
++import { ToursSchema } from './Tours.entity';
+ import { TrekPhotoCacheMetaSchema } from './TrekPhotoCacheMeta.entity';
+ import { TrekPhotosSchema } from './TrekPhotos.entity';
+ import { TripAlbumLinksSchema } from './TripAlbumLinks.entity';
+ import { TripDocumentLinksSchema } from './TripDocumentLinks.entity';
+ import { TripFilesSchema } from './TripFiles.entity';
+ import { TripInviteTokensSchema } from './TripInviteTokens.entity';
+ import { TripMembersSchema } from './TripMembers.entity';
+ import { TripPhotosSchema } from './TripPhotos.entity';
+ import { TripsSchema } from './Trips.entity';
+ import { UserNoticeDismissalsSchema } from './UserNoticeDismissals.entity';
+ import { UsersSchema } from './Users.entity';
+ import { VacayCompanyHolidaysSchema } from './VacayCompanyHolidays.entity';
+ import { VacayEntriesSchema } from './VacayEntries.entity';
+ import { VacayHolidayCalendarsSchema } from './VacayHolidayCalendars.entity';
+ import { VacayPlanMembersSchema } from './VacayPlanMembers.entity';
+ import { VacayPlansSchema } from './VacayPlans.entity';
+ import { VacaySharesSchema } from './VacayShares.entity';
+ import { VacayUserColorsSchema } from './VacayUserColors.entity';
+ import { VacayUserSettingsSchema } from './VacayUserSettings.entity';
+ import { VacayUserYearsSchema } from './VacayUserYears.entity';
+ import { VacayYearsSchema } from './VacayYears.entity';
+ import { VisitedCountriesSchema } from './VisitedCountries.entity';
+ import { VisitedRegionsSchema } from './VisitedRegions.entity';
+ import { WebauthnChallengesSchema } from './WebauthnChallenges.entity';
+ import { WebauthnCredentialsSchema } from './WebauthnCredentials.entity';
+
+ export const ALL_ENTITIES: readonly EntitySchema[] = [
+ AddonsSchema,
+ AppSettingsSchema,
+ AssignmentParticipantsSchema,
+ AuditLogSchema,
+ BucketListSchema,
+ BudgetCategoryOrderSchema,
+ BudgetItemMembersSchema,
+ BudgetItemPayersSchema,
+ BudgetItemsSchema,
+ BudgetSettlementsSchema,
+ CategoriesSchema,
+ CollabLinksSchema,
+ CollabMessageReactionsSchema,
+ CollabMessagesSchema,
+ CollabNotesSchema,
+ CollabPollVotesSchema,
+ CollabPollsSchema,
+ CollectionLabelsSchema,
+ CollectionMembersSchema,
+ CollectionPlaceRatingsSchema,
+ CollectionPlacesSchema,
+ CollectionsSchema,
+ DawarichConnectionsSchema,
+ DawarichVisitSuggestionsSchema,
+ DayAccommodationsSchema,
+ DayAssignmentsSchema,
+ DayNotesSchema,
+ DaysSchema,
+ DocumentConnectionsSchema,
+ DocumentProviderFieldsSchema,
+ DocumentProvidersSchema,
+ DocumentSyncItemsSchema,
+ FileLinksSchema,
+ GoogleApiUsageSchema,
+ GooglePlacePhotoMetaSchema,
+ HiddenCountriesSchema,
+ HiddenRegionsSchema,
+ IdempotencyKeysSchema,
+ InviteTokensSchema,
+ JourneyBooksSchema,
+ JourneyContributorsSchema,
+ JourneyEntriesSchema,
+ JourneyEntryPhotosSchema,
+ JourneyPhotosSchema,
+ JourneyShareTokensSchema,
+ JourneyTripsSchema,
+ JourneysSchema,
+ McpTokensSchema,
+ MigrationsSchema,
+ NotificationChannelPreferencesSchema,
+ NotificationsSchema,
+ OauthClientsSchema,
+ OauthConsentsSchema,
+ OauthTokensSchema,
+ PackingBagsSchema,
+ PackingCategoryAssigneesSchema,
+ PackingItemContributorsSchema,
+ PackingItemsSchema,
+ PackingTemplateCategoriesSchema,
+ PackingTemplateItemsSchema,
+ PackingTemplatesSchema,
+ PasswordResetTokensSchema,
+ PhotoProviderFieldsSchema,
+ PhotoProvidersSchema,
+ PhotosSchema,
+ PlaceDetailsCacheSchema,
+ PlaceRatingsSchema,
+ PlaceRegionsSchema,
+ PlaceShadowPicksSchema,
+ PlacesSchema,
+ PluginActionsSchema,
+ PluginCapabilityAuditSchema,
+ PluginEgressHostsSchema,
+ PluginEntityMetadataSchema,
+ PluginErrorLogSchema,
+ PluginMetaMigrationsSchema,
+ PluginOauthStateSchema,
+ PluginOauthTokensSchema,
+ PluginScheduledTasksSchema,
+ PluginSettingsFieldsSchema,
+ PluginUserConfigSchema,
+ PluginUserErasureQueueSchema,
+ PluginsSchema,
+ PushSubscriptionsSchema,
+ ReservationDayPositionsSchema,
+ ReservationEndpointsSchema,
+ ReservationTravelersSchema,
+ ReservationsSchema,
+ RoadtripDayBoundariesSchema,
+ RoadtripDayTracksSchema,
+ RoadtripPreferencesSchema,
+ RoadtripViasSchema,
+ RouteUsageDailySchema,
+ SchemaVersionSchema,
+ SchoolHolidayCountriesSchema,
+ SchoolHolidayPeriodsSchema,
+ SchoolHolidayRegionsSchema,
+ SettingsSchema,
+ ShareTokensSchema,
+ TagsSchema,
+ TodoCategoryAssigneesSchema,
+ TodoItemsSchema,
++ TourTypesSchema,
++ TourWaypointsSchema,
++ ToursSchema,
+ TrekPhotoCacheMetaSchema,
+ TrekPhotosSchema,
+ TripAlbumLinksSchema,
+ TripDocumentLinksSchema,
+ TripFilesSchema,
+ TripInviteTokensSchema,
+ TripMembersSchema,
+ TripPhotosSchema,
+ TripsSchema,
+ UserNoticeDismissalsSchema,
+ UsersSchema,
+ VacayCompanyHolidaysSchema,
+ VacayEntriesSchema,
+ VacayHolidayCalendarsSchema,
+ VacayPlanMembersSchema,
+ VacayPlansSchema,
+ VacaySharesSchema,
+ VacayUserColorsSchema,
+ VacayUserSettingsSchema,
+ VacayUserYearsSchema,
+ VacayYearsSchema,
+ VisitedCountriesSchema,
+ VisitedRegionsSchema,
+ WebauthnChallengesSchema,
+ WebauthnCredentialsSchema,
+ ];
diff --cc server/src/db/migrations/Migration20200101042000_tours.ts
index 000000000,000000000..585a65e51
new file mode 100644
--- /dev/null
+++ b/server/src/db/migrations/Migration20200101042000_tours.ts
@@@ -1,0 -1,0 +1,71 @@@
++import { Migration } from '@mikro-orm/migrations';
++
++/**
++ * Tours: a facet on `places` for hikes and other single-day routes.
++ *
++ * `tours` is keyed on the owning place, so deleting the place drops the facet
++ * and, through it, the ordered `tour_waypoints` the route editor saved.
++ * `tour_types` is the controlled vocabulary the facet points at; the `hike`
++ * row is reference data that FK needs, so it is written here rather than left
++ * to a seeder.
++ *
++ * Every statement is guarded: a test instance that ran the pre-ORM Tours
++ * branch already holds these tables and its rows must survive. That branch
++ * also created `idx_tour_waypoints_place`, which duplicates the autoindex
++ * behind `UNIQUE(place_id, sequence)`, so it is dropped to converge on the
++ * fresh-install shape.
++ */
++export class Migration20200101042000_tours extends Migration {
++ override name = 'Migration20200101042000_tours';
++
++ override up(): void {
++ this.addSql(`
++ CREATE TABLE IF NOT EXISTS tour_types (
++ key TEXT PRIMARY KEY,
++ label_key TEXT NOT NULL,
++ icon TEXT NOT NULL,
++ color TEXT NOT NULL,
++ routing_profile TEXT,
++ is_sport INTEGER NOT NULL DEFAULT 1,
++ enabled INTEGER NOT NULL DEFAULT 1,
++ sort_order INTEGER NOT NULL DEFAULT 0
++ )
++ `);
++
++ this.addSql(`
++ INSERT OR IGNORE INTO tour_types (key, label_key, icon, color, routing_profile, is_sport, enabled, sort_order)
++ VALUES ('hike', 'tourTypes.hike', 'Mountain', '#16a34a', 'pedestrian', 1, 1, 0)
++ `);
++
++ this.addSql(`
++ CREATE TABLE IF NOT EXISTS tours (
++ place_id INTEGER PRIMARY KEY REFERENCES places(id) ON DELETE CASCADE,
++ tour_type TEXT NOT NULL REFERENCES tour_types(key),
++ distance REAL,
++ elevation_gain REAL,
++ elevation_loss REAL,
++ duration REAL,
++ difficulty TEXT,
++ wanderer_ref TEXT,
++ match_confidence REAL,
++ tour_group_id INTEGER,
++ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
++ max_hiking_difficulty INTEGER NOT NULL DEFAULT 2 CHECK(max_hiking_difficulty BETWEEN 1 AND 6)
++ )
++ `);
++ this.addSql('CREATE INDEX IF NOT EXISTS idx_tours_tour_type ON tours(tour_type)');
++
++ this.addSql(`
++ CREATE TABLE IF NOT EXISTS tour_waypoints (
++ id INTEGER PRIMARY KEY AUTOINCREMENT,
++ place_id INTEGER NOT NULL REFERENCES tours(place_id) ON DELETE CASCADE,
++ lat REAL NOT NULL CHECK(lat >= -90 AND lat <= 90),
++ lng REAL NOT NULL CHECK(lng >= -180 AND lng <= 180),
++ role TEXT NOT NULL CHECK(role IN ('start', 'via', 'end')),
++ sequence INTEGER NOT NULL CHECK(sequence >= 0),
++ UNIQUE(place_id, sequence)
++ )
++ `);
++ this.addSql('DROP INDEX IF EXISTS idx_tour_waypoints_place');
++ }
++}
diff --cc server/src/db/repositories/DayAssignments.repository.ts
index 000000000,ca893d5c1..c34afb833
mode 000000,100644..100644
--- a/server/src/db/repositories/DayAssignments.repository.ts
+++ b/server/src/db/repositories/DayAssignments.repository.ts
@@@ -1,0 -1,989 +1,1019 @@@
+ import type { Platform } from '@mikro-orm/core';
+ import type { DayAssignments } from '../entities/DayAssignments.entity';
-import { coalesce, columnIncrementedBy, columnRef } from '../dialect/sql-functions';
++import { caseWhenNotNull, coalesce, columnIncrementedBy, columnRef } from '../dialect/sql-functions';
+ import { type AssertRowKeys } from './_shared/rows';
+ import { TrekRepository } from './_shared/trek-repository';
+
+ /**
+ * The DY1/DY3/AS1/AS3 assignment-with-place projection row (Plan 3c Task 2's
+ * report is the contract for Task 3, which consumes this unchanged):
+ *
+ * ```sql
+ * SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
+ * p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
+ * COALESCE(da.assignment_time, p.place_time) as place_time,
+ * COALESCE(da.assignment_end_time, p.end_time) as end_time,
+ * p.duration_minutes, p.notes as place_notes,
+ * p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.osm_id, p.amap_poi_id,
+ * p.website, p.phone, p.stop_type, p.fill_percent,
++ * t.place_id AS tour_place_id,
++ * CASE WHEN t.place_id IS NOT NULL THEN p.route_geometry END AS tour_route_geometry,
+ * c.name as category_name, c.color as category_color, c.icon as category_icon
+ * FROM day_assignments da
+ * JOIN places p ON da.place_id = p.id
++ * LEFT JOIN tours t ON t.place_id = p.id
+ * LEFT JOIN categories c ON p.category_id = c.id
+ * WHERE <da.id = ? | da.day_id = ? | da.day_id IN (...)>
+ * [ORDER BY da.order_index ASC, da.created_at ASC]
+ * ```
+ *
+ * `da.*` selects every scalar column of `DayAssignments` (`place_id` among
+ * them, the physical FK column) and then `p.id as place_id` selects it again
+ * under the same output key — the legacy statement did this too, and
+ * better-sqlite3's row object keeps the LAST column with a given name, so
+ * `place_id` on the wire is always `p.id`, not `da.place_id` (they agree by
+ * the JOIN condition regardless). Nullability here is the physical column's,
+ * not `AssignmentRow`'s (types.ts) narrower claims (rule 16) — a place with
+ * no category genuinely nulls `category_name`/`category_color`/
+ * `category_icon` through the LEFT JOIN even though `Categories.name` itself
+ * is NOT NULL.
+ */
+ export interface AssignmentWithPlaceRow extends DayAssignmentRow {
+ place_name: string;
+ place_description: string | null;
+ lat: number | null;
+ lng: number | null;
+ address: string | null;
+ category_id: number | null;
+ price: number | null;
+ place_currency: string | null;
+ place_time: string | null;
+ end_time: string | null;
+ duration_minutes: number | null;
+ place_notes: string | null;
+ image_url: string | null;
+ transport_mode: string | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ osm_id: string | null;
+ amap_poi_id: string | null;
+ website: string | null;
+ phone: string | null;
+ stop_type: string | null;
+ fill_percent: number | null;
++ /** The place's id when it is a Tour (its `tours` facet row), else null. */
++ tour_place_id: number | null;
++ /** The place's `route_geometry`, but only for a Tour; null for every other place. */
++ tour_route_geometry: string | null;
+ category_name: string | null;
+ category_color: string | null;
+ category_icon: string | null;
+ }
+
+ /**
+ * {@link DayAssignmentsRepository.listPublicForShare}'s projection (SH9) —
+ * {@link AssignmentWithPlaceRow} minus the six columns a public share link
- * must not leak.
++ * must not leak, and minus the two Tour facet columns the share projection
++ * never selected.
+ */
+ export type SharePublicAssignmentRow = Omit<
+ AssignmentWithPlaceRow,
+ 'google_place_id' | 'google_ftid' | 'osm_id' | 'amap_poi_id' | 'stop_type' | 'fill_percent'
++ | 'tour_place_id' | 'tour_route_geometry'
+ >;
+
+ /**
+ * A `day_assignments` row exactly as `AS12` (`AssignmentsService
+ * .getAssignmentForTrip`) re-selects it — every scalar column of the entity
+ * (`da.*`), scoped by a two-hop join to `days` for the trip check (Task 3).
+ */
+ export interface DayAssignmentRow {
+ id: number;
+ day_id: number;
+ place_id: number;
+ order_index: number | null;
+ notes: string | null;
+ reservation_status: string | null;
+ reservation_notes: string | null;
+ reservation_datetime: string | null;
+ created_at: string | null;
+ assignment_time: string | null;
+ assignment_end_time: string | null;
+ leg_transport_mode: string | null;
+ incoming_leg_transport_mode: string | null;
+ end_day: number;
+ accommodation_id: number | null;
+ route_excluded: number;
+ }
+
+ const _dayAssignmentRowKeys: AssertRowKeys<DayAssignmentRow, DayAssignments> = true;
+
+ /** AS18's stop, exactly as `AssignmentsService.sortDayByTime`/`chronoOrder` read it. */
+ export interface DayStopRow {
+ id: number;
+ order_index: number | null;
+ effective_time: string | null;
+ located: number;
+ }
+
+ /** AC7's row ({@link DayAssignmentsRepository.listSeatRows}), `night-seat.ts`'s `SeatRow`. */
+ export interface DaySeatRow {
+ id: number;
+ order_index: number | null;
+ at: string | null;
+ night_id: number | null;
+ located: number;
+ }
+
+ /**
+ * `day_assignments`/`places`/`day_accommodations`'s shape for AS16
+ * (`effectiveStart`) and AS18 (`listForTimeSort`), an explicit `TDB` type
+ * argument for `this.kysely()` (per `WebauthnChallengesRepository
+ * .claimChallenge`'s docstring — entity-metadata inference is not what a
+ * hand-written statement wants). There is no MikroORM relation from
+ * `DayAssignments` to `DayAccommodations` — `accommodation_id` is a plain
+ * `p.integer()` column on this entity, not a `manyToOne` (`day_accommodations`
+ * is Plan 3d's table; adding the relation means touching
+ * `src/db/entities/DayAssignments.entity.ts`, out of this task's scope) — so
+ * the QueryBuilder's relation-path `.join()` cannot express the LEFT JOIN at
+ * all. Kysely joining the physical table name directly is the sanctioned
+ * next step down D3's escape-hatch order (`find/findOne → nativeUpdate →
+ * qb() → em.getKysely()`).
+ */
+ interface AssignmentTimeSortKyselyDB {
+ day_assignments: {
+ id: number;
+ day_id: number;
+ place_id: number;
+ order_index: number | null;
+ assignment_time: string | null;
+ accommodation_id: number | null;
+ created_at: string | null;
+ };
+ places: {
+ id: number;
+ place_time: string | null;
+ lat: number | null;
+ lng: number | null;
+ };
+ day_accommodations: {
+ id: number;
+ check_in: string | null;
+ };
+ }
+
+ /**
+ * RPL2's row, exactly as `RoadtripPlanService.context`'s old local `VisitRow`
+ * interface declared it — the stay the visit stands for on its check-in day
+ * (never `a.accommodation_id`, see the method docstring), and the checkout
+ * day's `day_number`, both `null` for a visit with no linked stay.
+ * `accommodation_id` is the stay whose booking wrote this stop (null for one
+ * the traveller placed), and `order_index` is the stop's slot in the day plan
+ * the carrier terminals are seated against.
+ */
+ export interface RoadtripVisitRow {
+ id: number;
+ day_id: number;
+ order_index: number;
+ place_id: number;
+ name: string;
+ lat: number | null;
+ lng: number | null;
+ time: string | null;
+ end_time: string | null;
+ duration_minutes: number | null;
+ end_day: number;
+ leg_transport_mode: string | null;
+ incoming_leg_transport_mode: string | null;
+ stop_type: string | null;
+ fill_percent: number | null;
+ accommodation_id: number | null;
+ stay_id: number | null;
+ check_in: string | null;
+ check_out: string | null;
+ checkout_day: number | null;
+ }
+
+ /**
+ * `day_assignments`/`days`/`places`/`day_accommodations`'s shape for RPL2
+ * (`listRoadtripVisits`), the same Kysely-typed-DB-interface shape
+ * `AssignmentTimeSortKyselyDB` above uses. `days` is joined twice under two
+ * aliases (`d`, `checkout`) — both resolve against this one `days` entry.
+ */
+ interface RoadtripVisitsKyselyDB {
+ day_assignments: {
+ id: number;
+ day_id: number;
+ place_id: number;
+ order_index: number | null;
+ accommodation_id: number | null;
+ created_at: string | null;
+ assignment_time: string | null;
+ assignment_end_time: string | null;
+ end_day: number;
+ leg_transport_mode: string | null;
+ incoming_leg_transport_mode: string | null;
+ };
+ days: {
+ id: number;
+ trip_id: number;
+ day_number: number;
+ };
+ places: {
+ id: number;
+ name: string;
+ lat: number | null;
+ lng: number | null;
+ place_time: string | null;
+ end_time: string | null;
+ duration_minutes: number | null;
+ stop_type: string | null;
+ fill_percent: number | null;
+ };
+ day_accommodations: {
+ id: number;
+ place_id: number;
+ start_day_id: number;
+ end_day_id: number | null;
+ check_in: string | null;
+ check_out: string | null;
+ };
+ }
+
+ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
+ /** The DY1/DY3/AS1/AS3 projection's SELECT list, shared by all three query shapes below. */
+ private assignmentWithPlaceSelect(platform: Platform) {
+ return [
+ 'da.*',
+ 'p.id as place_id',
+ 'p.name as place_name',
+ 'p.description as place_description',
+ 'p.lat',
+ 'p.lng',
+ 'p.address',
+ // `category_id` is `persist(false)` on `Places` — a bare `'p.category_id'`
+ // string selects nothing (not a real property name), and `'p.category'`
+ // (the owning relation) is ALSO the joined alias here (`c`), so MikroORM
+ // absorbs the select into the join and returns `c__id`, not `category_id`
+ // (`McpTokensRepository.listAllWithUsername`'s `t.user`/`user_id`
+ // docstring is the same trap, one join away from this one). `columnRef`
+ // selects the literal physical column, keyed `category_id`.
+ columnRef(platform, 'p.category_id'),
+ 'p.price',
+ 'p.currency as place_currency',
+ coalesce(platform, 'da.assignment_time', 'p.place_time').as('place_time'),
+ coalesce(platform, 'da.assignment_end_time', 'p.end_time').as('end_time'),
+ 'p.duration_minutes',
+ 'p.notes as place_notes',
+ 'p.image_url',
+ 'p.transport_mode',
+ 'p.google_place_id',
+ 'p.google_ftid',
+ 'p.osm_id',
+ 'p.amap_poi_id',
+ 'p.website',
+ 'p.phone',
+ 'p.stop_type',
+ 'p.fill_percent',
++ // `place_id` on `Tours` is the `persist(false)` twin of its primary-key
++ // relation, the same trap as `category_id` above, so `columnRef` again.
++ columnRef(platform, 't.place_id').as('tour_place_id'),
++ caseWhenNotNull(platform, 't.place_id', 'p.route_geometry').as('tour_route_geometry'),
+ 'c.name as category_name',
+ 'c.color as category_color',
+ 'c.icon as category_icon',
+ ] as const;
+ }
+
+ /**
+ * AS1 (`assignments.service.ts::getAssignmentWithPlace`, Task 3): the
+ * projection filtered to one assignment, no ORDER BY (a single row).
+ */
+ async findWithPlaceAndCategory(id: number): Promise<AssignmentWithPlaceRow | null> {
+ const platform = this.getEntityManager().getPlatform();
+ const row = await this.qb('da')
+ .join('da.place', 'p')
++ .leftJoin('p.tours', 't')
+ .leftJoin('p.category', 'c')
+ .select(this.assignmentWithPlaceSelect(platform))
+ .where({ 'da.id': id })
+ .execute<AssignmentWithPlaceRow | undefined>('get', false);
+ return row ?? null;
+ }
+
+ /**
+ * DY1 (`days.service.ts::getAssignmentsForDay`) and AS3
+ * (`assignments.service.ts::listDayAssignments`, Task 3): the projection
+ * for one day, `ORDER BY da.order_index ASC, da.created_at ASC`.
+ */
+ async listForDay(day_id: number): Promise<AssignmentWithPlaceRow[]> {
+ const platform = this.getEntityManager().getPlatform();
+ return await this.qb('da')
+ .join('da.place', 'p')
++ .leftJoin('p.tours', 't')
+ .leftJoin('p.category', 'c')
+ .select(this.assignmentWithPlaceSelect(platform))
+ .where({ 'da.day': day_id })
+ .orderBy({ 'da.order_index': 'asc', 'da.created_at': 'asc' })
+ .execute<AssignmentWithPlaceRow[]>('all', false);
+ }
+
+ /**
+ * DY3 (`days.service.ts::list`): the same projection for several days at
+ * once (`WHERE da.day_id IN (...)`), same ORDER BY. Empty-array
+ * short-circuit before any query, as the legacy dynamic-`IN` builder did.
+ */
+ async listWithPlaceAndCategory(day_ids: number[]): Promise<AssignmentWithPlaceRow[]> {
+ if (day_ids.length === 0) return [];
+ const platform = this.getEntityManager().getPlatform();
+ return await this.qb('da')
+ .join('da.place', 'p')
++ .leftJoin('p.tours', 't')
+ .leftJoin('p.category', 'c')
+ .select(this.assignmentWithPlaceSelect(platform))
+ .where({ 'da.day': { $in: day_ids } })
+ .orderBy({ 'da.order_index': 'asc', 'da.created_at': 'asc' })
+ .execute<AssignmentWithPlaceRow[]>('all', false);
+ }
+
+ /**
+ * `share.service.ts:288` SH9 (`getSharedTripData`'s share_map assignment
+ * read) — the SAME projection {@link assignmentWithPlaceSelect} builds,
+ * minus six internal-id/routing columns a public share link must never
+ * leak (`google_place_id`, `google_ftid`, `osm_id`, `amap_poi_id`,
+ * `stop_type`, `fill_percent`) — never widen this list to match the
+ * private `listWithPlaceAndCategory` projection above.
+ */
+ private publicAssignmentSelect(platform: Platform) {
+ return [
+ 'da.*',
+ 'p.id as place_id',
+ 'p.name as place_name',
+ 'p.description as place_description',
+ 'p.lat',
+ 'p.lng',
+ 'p.address',
+ columnRef(platform, 'p.category_id'),
+ 'p.price',
+ 'p.currency as place_currency',
+ coalesce(platform, 'da.assignment_time', 'p.place_time').as('place_time'),
+ coalesce(platform, 'da.assignment_end_time', 'p.end_time').as('end_time'),
+ 'p.duration_minutes',
+ 'p.notes as place_notes',
+ 'p.image_url',
+ 'p.transport_mode',
+ 'p.website',
+ 'p.phone',
+ 'c.name as category_name',
+ 'c.color as category_color',
+ 'c.icon as category_icon',
+ ] as const;
+ }
+
+ /** SH9 — same WHERE/ORDER BY shape as {@link listWithPlaceAndCategory}, narrower projection. */
+ async listPublicForShare(day_ids: number[]): Promise<SharePublicAssignmentRow[]> {
+ if (day_ids.length === 0) return [];
+ const platform = this.getEntityManager().getPlatform();
+ return await this.qb('da')
+ .join('da.place', 'p')
+ .leftJoin('p.category', 'c')
+ .select(this.publicAssignmentSelect(platform))
+ .where({ 'da.day': { $in: day_ids } })
+ .orderBy({ 'da.order_index': 'asc', 'da.created_at': 'asc' })
+ .execute<SharePublicAssignmentRow[]>('all', false);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 3 (`AssignmentsService`) — appended after Task 2's own
+ // methods above, per this task's file-ownership rule.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * AS9 (`assignmentExistsInDay`) — `SELECT da.id FROM day_assignments da
+ * JOIN days d ON da.day_id = d.id WHERE da.id = ? AND da.day_id = ? AND
+ * d.trip_id = ?`.
+ *
+ * **`id: number`, not `number | string` (Task 3 review H1, absorbed in
+ * Task 4 — `task-3-review.md` §9.1):** this method's ONLY caller
+ * (`AssignmentsService.assignmentExistsInDay`) now runs `toRowId` on the
+ * route's raw `id` BEFORE calling this — a non-canonical id (`"3 "`,
+ * `"3.0"`) must resolve to "not found" in the SERVICE gate, not pass this
+ * statement's own SQLite text/integer affinity match and then disagree
+ * with `deleteAssignment`'s `toRowId(id)!` downstream (the H1 regression).
+ * `day_id`/`trip_id` keep their `number | string` raw-bind scoping —
+ * `deleteAssignment` never reads either back, so there is no gate-vs-write
+ * id to protect there.
+ */
+ async existsInDay(id: number, day_id: number | string, trip_id: number | string): Promise<boolean> {
+ const row = await this.qb('da')
+ .join('da.day', 'd')
+ .select(['da.id'])
+ .where('da.id = ? AND da.day_id = ? AND d.trip_id = ?', [id, day_id, trip_id])
+ .execute<{ id: number } | undefined>('get', false);
+ return !!row;
+ }
+
+ /**
+ * AS12 (`getAssignmentForTrip`) — `SELECT da.* FROM day_assignments da
+ * JOIN days d ON da.day_id = d.id WHERE da.id = ? AND d.trip_id = ?`.
+ *
+ * **`id: number`, not `number | string` (Task 3 review H1, absorbed in
+ * Task 4 — `task-3-review.md` §9.1):** this method's ONLY caller
+ * (`AssignmentsService.getAssignmentForTrip`) now runs `toRowId` on the
+ * route/tool's raw `id` BEFORE calling this, the same H1 fix
+ * `existsInDay` above applies — every mutation behind this gate
+ * (`updateTime`/`setEndDay`/`updateNotes`/`setLegTransportMode`/
+ * `setIncomingLegTransportMode`/`setParticipants`/`moveAssignment`)
+ * converts `id` with its own `toRowId(id)!`, and `ItineraryRpc.unassign`
+ * reads `existing.day_id` off THIS result (a genuine re-select, not only
+ * an existence guard) — so the id this read resolves must be the same one
+ * every one of those writes uses. `trip_id` keeps its `number | string`
+ * raw-bind scoping, unchanged.
+ */
+ async findInTrip(id: number, trip_id: number | string): Promise<DayAssignmentRow | undefined> {
+ const row = await this.qb('da')
+ .join('da.day', 'd')
+ .select(['da.*'])
+ .where('da.id = ? AND d.trip_id = ?', [id, trip_id])
+ .execute<DayAssignmentRow | undefined>('get', false);
+ return row ?? undefined;
+ }
+
+ /**
+ * AS6 (`createAssignment`'s append-position read) — `SELECT
+ * MAX(order_index) as max FROM day_assignments WHERE day_id = ?`, read as
+ * the highest row by an ordered `limit(1)` (`DaysRepository.maxDayNumber`'s
+ * precedent — SQLite sorts `NULL` last under `DESC`, so an all-NULL or
+ * empty table folds the same way `MAX()` ignoring every `NULL` does).
+ * Returns the raw nullable value, NOT folded to `0`/`-1` here: the
+ * service's explicit `maxOrder !== null ? maxOrder : -1` check (AS6's
+ * ruling) needs to tell "no rows" from a stored `0` order_index, which a
+ * `?? -1` fold would collapse identically — unlike `DaysRepository
+ * .maxDayNumber`, this repository method must NOT pre-fold the null case.
+ */
+ async maxOrderIndex(day_id: number): Promise<number | null> {
+ const row = await this.qb('da')
+ .select('da.order_index')
+ .where({ day: day_id })
+ .orderBy({ order_index: 'desc' })
+ .limit(1)
+ .execute<{ order_index: number | null } | undefined>('get', false);
+ return row?.order_index ?? null;
+ }
+
+ /**
+ * AS7 — `UPDATE day_assignments SET order_index = order_index + 1 WHERE
+ * day_id = ? AND order_index >= ?`, a column-from-column update
+ * (`InviteTokensRepository.incrementUsedCount`'s `columnIncrementedBy`
+ * precedent — `nativeUpdate`'s `EntityData` shape doesn't accept a raw
+ * fragment value, so this goes through `qb().update()` instead).
+ */
+ async shiftOrderFrom(day_id: number, from: number): Promise<void> {
+ const platform = this.getEntityManager().getPlatform();
+ await this.qb()
+ .update({ order_index: columnIncrementedBy(platform, 'order_index', 1) })
+ .where({ day: day_id, order_index: { $gte: from } })
+ .execute('run');
+ }
+
+ /**
+ * AS8 — `INSERT INTO day_assignments (day_id, place_id, order_index,
+ * notes, accommodation_id) VALUES (?, ?, ?, ?, ?)`. The caller passes
+ * already-decided values (the `notes || null`/`accommodationId ?? null`
+ * coercions and the clamped `orderIndex` stay in the service, the same
+ * split `DaysRepository.createDay`'s docstring describes) — `em.insert()`
+ * returns the generated PK (R6's `lastInsertRowid` replacement).
+ */
+ async insertAssignment(input: {
+ day_id: number;
+ place_id: number;
+ order_index: number;
+ notes: string | null;
+ accommodation_id: number | null;
+ }): Promise<number> {
+ return await this.insert({
+ day: input.day_id,
+ place: input.place_id,
+ order_index: input.order_index,
+ notes: input.notes,
+ accommodation_id: input.accommodation_id,
+ });
+ }
+
+ /** AS10 — `DELETE FROM day_assignments WHERE id = ?`. */
+ async deleteById(id: number): Promise<void> {
+ await this.nativeDelete({ id });
+ }
+
+ /**
+ * AS11 (`reorderAssignments`, day-scoped: `UPDATE day_assignments SET
+ * order_index = ? WHERE id = ? AND day_id = ?`) and AS19
+ * (`sortDayByTime`'s per-row write, NOT day-scoped: `UPDATE
+ * day_assignments SET order_index = ? WHERE id = ?`) — one method, both
+ * signatures, per the inventory's ruling ("keep both signatures"):
+ * `day_id` omitted (`undefined`) reproduces AS19's unscoped statement.
+ */
+ async setOrderIndex(id: number, day_id: number | undefined, order_index: number): Promise<void> {
+ const where = day_id !== undefined ? { id, day: day_id } : { id };
+ await this.nativeUpdate(where, { order_index });
+ }
+
+ /** AS13 (`moveAssignment`'s source-day read) — `SELECT day_id FROM day_assignments WHERE id = ?`. */
+ async getDayId(id: number): Promise<number | undefined> {
+ const platform = this.getEntityManager().getPlatform();
+ // `day_id` is `persist(false)` (the physical FK mirror of the `day`
+ // relation) — a bare `'da.day_id'` select hits the same trap
+ // `assignmentWithPlaceSelect`'s `category_id` comment documents;
+ // `columnRef` selects the literal physical column instead.
+ const row = await this.qb('da')
+ .select([columnRef(platform, 'da.day_id').as('day_id')])
+ .where({ id })
+ .execute<{ day_id: number } | undefined>('get', false);
+ return row?.day_id;
+ }
+
++ /**
++ * `moveAssignment`'s Tour check: `SELECT place_id FROM day_assignments
++ * WHERE id = ?`, `columnRef` for the same `persist(false)` reason as
++ * {@link getDayId} above.
++ */
++ async getPlaceId(id: number): Promise<number | undefined> {
++ const platform = this.getEntityManager().getPlatform();
++ const row = await this.qb('da')
++ .select([columnRef(platform, 'da.place_id').as('place_id')])
++ .where({ id })
++ .execute<{ place_id: number } | undefined>('get', false);
++ return row?.place_id;
++ }
++
+ /** AS14 — `UPDATE day_assignments SET day_id = ?, order_index = ? WHERE id = ?`. */
+ async moveToDay(id: number, day_id: number, order_index: number): Promise<void> {
+ await this.nativeUpdate({ id }, { day: day_id, order_index });
+ }
+
+ /**
+ * AS16 (`updateTime`'s pre-write read) — `SELECT da.day_id,
+ * COALESCE(da.assignment_time, p.place_time, acc.check_in) AS start FROM
+ * day_assignments da JOIN places p ON da.place_id = p.id LEFT JOIN
+ * day_accommodations acc ON acc.id = da.accommodation_id WHERE da.id = ?`.
+ * Kysely (see `AssignmentTimeSortKyselyDB`'s docstring for why: no ORM
+ * relation to `day_accommodations` exists to `.join()` through).
+ */
+ async effectiveStart(id: number): Promise<{ day_id: number; start: string | null } | undefined> {
+ const row = await this.kysely<AssignmentTimeSortKyselyDB>()
+ .selectFrom('day_assignments as da')
+ .innerJoin('places as p', 'p.id', 'da.place_id')
+ .leftJoin('day_accommodations as acc', 'acc.id', 'da.accommodation_id')
+ .select((eb) => ['da.day_id as day_id', eb.fn.coalesce('da.assignment_time', 'p.place_time', 'acc.check_in').as('start')])
+ .where('da.id', '=', id)
+ .executeTakeFirst();
+ return row as { day_id: number; start: string | null } | undefined;
+ }
+
+ /**
+ * AS17 — `UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ? WHERE id = ?`.
+ * The falsy-clears-to-null coercion (`placeTime || null`) stays in the
+ * service (AS17's ruling); this writes the already-decided values.
+ */
+ async setTimes(id: number, assignment_time: string | null, assignment_end_time: string | null): Promise<void> {
+ await this.nativeUpdate({ id }, { assignment_time, assignment_end_time });
+ }
+
+ /**
+ * AS18 (`sortDayByTime`'s day-wide read) — `SELECT da.id, da.order_index,
+ * COALESCE(da.assignment_time, p.place_time, acc.check_in) as
+ * effective_time, (p.lat IS NOT NULL AND p.lng IS NOT NULL) as located
+ * FROM day_assignments da JOIN places p ON da.place_id = p.id LEFT JOIN
+ * day_accommodations acc ON acc.id = da.accommodation_id WHERE da.day_id
+ * = ? ORDER BY da.order_index ASC, da.created_at ASC, da.id ASC`. Same
+ * Kysely escape hatch as `effectiveStart`. The computed boolean column is
+ * expressed with the expression builder's own comparison/`.and()`
+ * combinators — never the banned `sql` tag — and SQLite returns it as the
+ * same `0`/`1` integer the legacy raw statement did.
+ */
+ async listForTimeSort(day_id: number): Promise<DayStopRow[]> {
+ const rows = await this.kysely<AssignmentTimeSortKyselyDB>()
+ .selectFrom('day_assignments as da')
+ .innerJoin('places as p', 'p.id', 'da.place_id')
+ .leftJoin('day_accommodations as acc', 'acc.id', 'da.accommodation_id')
+ .select((eb) => [
+ 'da.id as id',
+ 'da.order_index as order_index',
+ eb.fn.coalesce('da.assignment_time', 'p.place_time', 'acc.check_in').as('effective_time'),
+ eb.and([eb('p.lat', 'is not', null), eb('p.lng', 'is not', null)]).as('located'),
+ ])
+ .where('da.day_id', '=', day_id)
+ .orderBy('da.order_index', 'asc')
+ .orderBy('da.created_at', 'asc')
+ .orderBy('da.id', 'asc')
+ // `$castTo` (Task 9 fix wave, B-L1): Kysely infers `located` as its own
+ // `SqlBool` type from `eb.and(...)`, not the `0`/`1` integer
+ // `DayStopRow.located` declares (the value SQLite actually returns for
+ // a boolean expression) — a straight `as DayStopRow[]` is rejected as
+ // an unrelated-type cast, which is what forced the `as unknown as`
+ // bridge. `$castTo` retypes the builder itself before `execute()`
+ // runs, so the result is `DayStopRow[]` with no intermediate `unknown`.
+ .$castTo<DayStopRow>()
+ .execute();
+ return rows;
+ }
+
+ /** AS24 — `UPDATE day_assignments SET end_day = ? WHERE id = ?`. */
+ async setEndDay(id: number, end_day: number): Promise<void> {
+ await this.nativeUpdate({ id }, { end_day });
+ }
+
+ /** AS25 — `UPDATE day_assignments SET notes = ? WHERE id = ?`. */
+ async setNotes(id: number, notes: string | null): Promise<void> {
+ await this.nativeUpdate({ id }, { notes });
+ }
+
+ /** AS26 — `UPDATE day_assignments SET leg_transport_mode = ? WHERE id = ?`. */
+ async setLegMode(id: number, mode: string | null): Promise<void> {
+ await this.nativeUpdate({ id }, { leg_transport_mode: mode });
+ }
+
+ /** AS27 — `UPDATE day_assignments SET incoming_leg_transport_mode = ? WHERE id = ?`. */
+ async setIncomingLegMode(id: number, mode: string | null): Promise<void> {
+ await this.nativeUpdate({ id }, { incoming_leg_transport_mode: mode });
+ }
+
+ /**
+ * AS32 (`AssignmentsService.clearDay`, #2470) — `SELECT id FROM
+ * day_assignments WHERE day_id = ?`, no ORDER BY (unlike AC1's
+ * {@link listIdsForDay}).
+ */
+ async listIdsToClear(day_id: number): Promise<number[]> {
+ const rows = await this.qb('da')
+ .select(['da.id'])
+ .where({ day: day_id })
+ .execute<{ id: number }[]>('all', false);
+ return rows.map((r) => r.id);
+ }
+
+ /** AS33 (`AssignmentsService.clearDay`, #2470) — `DELETE FROM day_assignments WHERE day_id = ?`. */
+ async deleteForDay(day_id: number): Promise<void> {
+ await this.nativeDelete({ day: day_id });
+ }
+
+ /** AS34 (`AssignmentsService.setRouteExcluded`, #2532) — `UPDATE day_assignments SET route_excluded = ? WHERE id = ?`. */
+ async setRouteExcluded(id: number, route_excluded: number): Promise<void> {
+ await this.nativeUpdate({ id }, { route_excluded });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 4 (`PlacesService.exportGpx`) — appended per the task-4
+ // brief's "task-3-report.md" pointer ("DayAssignmentsRepository for the
+ // PL30 GPX itinerary read if it fits there"). Unlike AS16/AS18, this join
+ // (`day_assignments` -> `days`, `day_assignments` -> `places`) is fully
+ // expressible through the entity's own declared relations (`da.day`,
+ // `da.place`) — no `day_accommodations`-shaped gap — so the QueryBuilder is
+ // used directly rather than Kysely.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * PL30 (`places.service.ts::exportGpx`) — `SELECT d.day_number, d.date,
+ * d.title, p.name, p.lat, p.lng FROM days d JOIN day_assignments da ON
+ * da.day_id = d.id JOIN places p ON p.id = da.place_id WHERE d.trip_id = ?
+ * AND p.lat IS NOT NULL AND p.lng IS NOT NULL ORDER BY d.day_number,
+ * da.order_index` — rooted here on `day_assignments` instead of `days`
+ * (the legacy statement's own `FROM` root) because both joins the legacy
+ * statement needs (`day_assignments -> days`, `day_assignments -> places`)
+ * are single hops FROM this entity, while `days` has no direct relation to
+ * `places`. Same result set, same ordering; the root alias choice is not
+ * observable from the row shape.
+ */
+ async listItineraryForGpx(trip_id: string | number): Promise<{
+ day_number: number; date: string | null; title: string | null;
+ name: string; lat: number; lng: number;
+ }[]> {
+ return this.qb('da')
+ .join('da.day', 'd')
+ .join('da.place', 'p')
+ .select(['d.day_number', 'd.date', 'd.title', 'p.name', 'p.lat', 'p.lng'])
+ .where('d.trip_id = ? AND p.lat IS NOT NULL AND p.lng IS NOT NULL', [trip_id])
+ .orderBy({ 'd.day_number': 'asc', 'da.order_index': 'asc' })
+ .execute<{ day_number: number; date: string | null; title: string | null; name: string; lat: number; lng: number }[]>('all', false);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 8 (`TripsService.copy`) — additive.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * TP48 (`trips.service.ts::copy`'s assignments read) — `SELECT da.* FROM
+ * day_assignments da JOIN days d ON d.id = da.day_id WHERE d.trip_id = ?`,
+ * no `ORDER BY` (matching the legacy statement, which relies on SQLite's
+ * own rowid-ascending scan order — the copy loop's insertion order tracks
+ * the source's own, same reasoning as `PlacesRepository.listAllForTrip`).
+ */
+ async listAllForTrip(trip_id: number | string): Promise<DayAssignmentRow[]> {
+ return this.qb('da')
+ .join('da.day', 'd')
+ .select(['da.*'])
+ .where('d.trip_id = ?', [trip_id])
+ .execute<DayAssignmentRow[]>('all', false);
+ }
+
+ /**
+ * TP49 (`trips.service.ts::copy`'s assignment INSERT) — the 10-column
+ * `INSERT INTO day_assignments (day_id, place_id, order_index, notes,
+ * reservation_status, reservation_notes, reservation_datetime,
+ * assignment_time, assignment_end_time, end_day) VALUES (...)`. A
+ * different column set from AS8's `insertAssignment` (5 columns: `day_id`,
+ * `place_id`, `order_index`, `notes`, `accommodation_id` — no reservation/
+ * time/end_day fields, and `accommodation_id` is stamped separately here,
+ * AFTER the bookings loop, via {@link setAccommodation} below, TP57) — the
+ * copy carries a source assignment's reservation snapshot and timing
+ * verbatim, values already fully resolved by the caller (`a.end_day ?? 0`
+ * stays the service's own decision, `DaysRepository.createDay`'s split).
+ */
+ async insertAssignmentCopy(input: {
+ day_id: number;
+ place_id: number;
+ order_index: number | null;
+ notes: string | null;
+ reservation_status: string | null;
+ reservation_notes: string | null;
+ reservation_datetime: string | null;
+ assignment_time: string | null;
+ assignment_end_time: string | null;
+ end_day: number;
+ }): Promise<number> {
+ return await this.insert({
+ day: input.day_id,
+ place: input.place_id,
+ order_index: input.order_index,
+ notes: input.notes,
+ reservation_status: input.reservation_status,
+ reservation_notes: input.reservation_notes,
+ reservation_datetime: input.reservation_datetime,
+ assignment_time: input.assignment_time,
+ assignment_end_time: input.assignment_end_time,
+ end_day: input.end_day,
+ });
+ }
+
+ /**
+ * TP57 (`trips.service.ts::copy`'s post-bookings-loop stamp) — `UPDATE
+ * day_assignments SET accommodation_id = ? WHERE id = ?`. Run once per
+ * copied stay-stop, AFTER the `day_accommodations` bookings are copied
+ * (Plan 3d's own table — the bookings loop itself stays raw, `// TPn —
+ * Plan 3d`), because only then does the copied accommodation's id exist
+ * to stamp on. `accommodation_id` is a plain `p.integer()` column on this
+ * entity, not a relation (`AssignmentTimeSortKyselyDB`'s docstring), so a
+ * typed `nativeUpdate` partial reaches it directly.
+ */
+ async setAccommodation(id: number, accommodation_id: number): Promise<void> {
+ await this.nativeUpdate({ id }, { accommodation_id });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3d Task 1 (`RoadtripPlanService`) — additive, per this task's own
+ // file-ownership rule ("all additive methods on Days/Places/DayAssignments
+ // repositories").
+ // ---------------------------------------------------------------------------
+
+ /**
+ * RPL2 (`roadtrip-plan.service.ts::context`'s `visits` read) — the
+ * cluster's most dialect-specific SELECT (inventory §17b):
+ *
+ * ```sql
+ * SELECT a.id, a.day_id, a.order_index, a.place_id, p.name, p.lat, p.lng,
+ * COALESCE(a.assignment_time, p.place_time) AS time,
+ * COALESCE(a.assignment_end_time, p.end_time) AS end_time,
+ * p.duration_minutes, a.end_day,
+ * a.leg_transport_mode, a.incoming_leg_transport_mode, p.stop_type, p.fill_percent,
+ * a.accommodation_id, stay.id AS stay_id, stay.check_in, stay.check_out, checkout.day_number AS checkout_day
+ * FROM day_assignments a
+ * JOIN days d ON d.id = a.day_id
+ * JOIN places p ON p.id = a.place_id
+ * LEFT JOIN day_accommodations stay
+ * ON stay.id = (SELECT id FROM day_accommodations WHERE place_id = p.id AND start_day_id = d.id ORDER BY id LIMIT 1)
+ * LEFT JOIN days checkout ON checkout.id = stay.end_day_id
+ * WHERE d.trip_id = ?
+ * ORDER BY d.day_number, a.order_index, a.created_at
+ * ```
+ *
+ * A correlated scalar subquery INSIDE a `LEFT JOIN … ON` clause — no
+ * QueryBuilder shape expresses this (§17b), and no MikroORM relation
+ * connects a place+check-in-day pair to its `day_accommodations` row (the
+ * stay is matched by `place_id`+`start_day_id`, not by
+ * `a.accommodation_id` — deliberately: the inventory's own RPL2 note),
+ * so this is `this.kysely()` from the start, same escape-hatch order as
+ * `effectiveStart`/`listForTimeSort` above. `days` is
+ * joined twice under two different aliases (`d`, `checkout`) — ordinary
+ * Kysely self-join aliasing, no separate interface entry needed since both
+ * resolve against the same `days` table shape.
+ */
+ async listRoadtripVisits(trip_id: number): Promise<RoadtripVisitRow[]> {
+ const rows = await this.kysely<RoadtripVisitsKyselyDB>()
+ .selectFrom('day_assignments as a')
+ .innerJoin('days as d', 'd.id', 'a.day_id')
+ .innerJoin('places as p', 'p.id', 'a.place_id')
+ .leftJoin('day_accommodations as stay', (join) =>
+ join.on('stay.id', '=', (eb) =>
+ eb
+ .selectFrom('day_accommodations as da2')
+ .select('da2.id')
+ .whereRef('da2.place_id', '=', 'p.id')
+ .whereRef('da2.start_day_id', '=', 'd.id')
+ .orderBy('da2.id', 'asc')
+ .limit(1),
+ ),
+ )
+ .leftJoin('days as checkout', 'checkout.id', 'stay.end_day_id')
+ .select((eb) => [
+ 'a.id as id',
+ 'a.day_id as day_id',
+ 'a.order_index as order_index',
+ 'a.place_id as place_id',
+ 'p.name as name',
+ 'p.lat as lat',
+ 'p.lng as lng',
+ eb.fn.coalesce('a.assignment_time', 'p.place_time').as('time'),
+ eb.fn.coalesce('a.assignment_end_time', 'p.end_time').as('end_time'),
+ 'p.duration_minutes as duration_minutes',
+ 'a.end_day as end_day',
+ 'a.leg_transport_mode as leg_transport_mode',
+ 'a.incoming_leg_transport_mode as incoming_leg_transport_mode',
+ 'p.stop_type as stop_type',
+ 'p.fill_percent as fill_percent',
+ 'a.accommodation_id as accommodation_id',
+ 'stay.id as stay_id',
+ 'stay.check_in as check_in',
+ 'stay.check_out as check_out',
+ 'checkout.day_number as checkout_day',
+ ])
+ .where('d.trip_id', '=', trip_id)
+ .orderBy('d.day_number', 'asc')
+ .orderBy('a.order_index', 'asc')
+ .orderBy('a.created_at', 'asc')
+ .$castTo<RoadtripVisitRow>()
+ .execute();
+ return rows;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3d Task 3 (`AccommodationsService`) — additive, per this task's own
+ // file-ownership rule ("additive methods on Days/Places/DayAssignments/
+ // Reservations repositories where a read belongs there").
+ // ---------------------------------------------------------------------------
+
+ /** AC1 (`AccommodationsService.announceMirror`) — `SELECT id FROM day_assignments WHERE day_id = ? ORDER BY order_index`, once per touched day. */
+ async listIdsForDay(day_id: number): Promise<number[]> {
+ const rows = await this.qb('da')
+ .select(['da.id'])
+ .where({ day: day_id })
+ .orderBy({ order_index: 'asc' })
+ .execute<{ id: number }[]>('all', false);
+ return rows.map((r) => r.id);
+ }
+
+ /**
+ * AC7 (`night-seat.ts`'s `SeatRow`, read by `AccommodationsService` and
+ * `DaysService` through `seatIndexWith`/`seatHolds`; `reseat-booked-nights.ts`
+ * runs the same statement raw inside migration 242) — `SELECT da.id,
+ * da.order_index, CASE WHEN other.id IS NULL THEN
+ * COALESCE(da.assignment_time, p.place_time) ELSE other.check_in END AS at,
+ * other.id AS night_id, (p.lat IS NOT NULL AND p.lng IS NOT NULL) AS
+ * located FROM day_assignments da JOIN places p ON p.id = da.place_id LEFT
+ * JOIN day_accommodations other ON other.id = da.accommodation_id WHERE
+ * da.day_id = ? ORDER BY da.order_index ASC, da.created_at ASC, da.id ASC`.
+ * `locatedStopIdsWith` reads the via positions off these same rows
+ * (`located`), so a night and its vias are measured by one statement.
+ * Same Kysely escape hatch as {@link effectiveStart}/{@link listForTimeSort}
+ * (no ORM relation to `day_accommodations`); `located` and the `$castTo`
+ * follow `listForTimeSort`.
+ */
+ async listSeatRows(day_id: number): Promise<DaySeatRow[]> {
+ const rows = await this.kysely<AssignmentTimeSortKyselyDB>()
+ .selectFrom('day_assignments as da')
+ .innerJoin('places as p', 'p.id', 'da.place_id')
+ .leftJoin('day_accommodations as other', 'other.id', 'da.accommodation_id')
+ .select((eb) => [
+ 'da.id as id',
+ 'da.order_index as order_index',
+ eb
+ .case()
+ .when('other.id', 'is', null)
+ .then(eb.fn.coalesce('da.assignment_time', 'p.place_time'))
+ .else(eb.ref('other.check_in'))
+ .end()
+ .as('at'),
+ 'other.id as night_id',
+ eb.and([eb('p.lat', 'is not', null), eb('p.lng', 'is not', null)]).as('located'),
+ ])
+ .where('da.day_id', '=', day_id)
+ .orderBy('da.order_index', 'asc')
+ .orderBy('da.created_at', 'asc')
+ .orderBy('da.id', 'asc')
+ .$castTo<DaySeatRow>()
+ .execute();
+ return rows;
+ }
+
+ /**
+ * AC18/AC24 (`AccommodationsService.relocateOwnStop`/`mirrorStay`) — one
+ * method, two call shapes (D4): `SELECT id FROM day_assignments WHERE
+ * day_id = ? AND place_id = ? AND id != ?` (AC18, with `exclude_id`) and
+ * `SELECT id FROM day_assignments WHERE day_id = ? AND place_id = ?`
+ * (AC24, without).
+ */
+ async existsForDayAndPlace(day_id: number, place_id: number, exclude_id?: number): Promise<boolean> {
+ const query = this.qb('da').select(['da.id']).where({ day: day_id, place: place_id });
+ if (exclude_id !== undefined) query.andWhere({ id: { $ne: exclude_id } });
+ const row = await query.execute<{ id: number } | undefined>('get', false);
+ return !!row;
+ }
+
+ /**
+ * AC19 (`AccommodationsService.relocateOwnStop`) — `UPDATE day_assignments
+ * SET order_index = order_index - 1 WHERE day_id = ? AND order_index > ?`,
+ * a column-from-column update (`columnIncrementedBy`, {@link shiftOrderFrom}'s
+ * precedent).
+ */
+ async closeGap(day_id: number, from_index: number): Promise<void> {
+ const platform = this.getEntityManager().getPlatform();
+ await this.qb()
+ .update({ order_index: columnIncrementedBy(platform, 'order_index', -1) })
+ .where({ day: day_id, order_index: { $gt: from_index } })
+ .execute('run');
+ }
+
+ /**
+ * AC20 (`AccommodationsService.relocateOwnStop`) — `SELECT MAX(order_index)
+ * AS max FROM day_assignments WHERE day_id = ? AND id != ?`, read the same
+ * way {@link maxOrderIndex} is (an ordered `limit(1)`, null NOT pre-folded —
+ * the caller's own `max.max !== null ? max.max : -1` check needs to tell
+ * "no rows" from a stored `0`).
+ */
+ async maxOrderIndexExcluding(day_id: number, exclude_id: number): Promise<number | null> {
+ const row = await this.qb('da')
+ .select('da.order_index')
+ .where({ day: day_id, id: { $ne: exclude_id } })
+ .orderBy({ order_index: 'desc' })
+ .limit(1)
+ .execute<{ order_index: number | null } | undefined>('get', false);
+ return row?.order_index ?? null;
+ }
+
+ /** AC21 (`AccommodationsService.relocateOwnStop`) — `UPDATE day_assignments SET day_id = ?, place_id = ?, order_index = ? WHERE id = ?`. */
+ async relocate(id: number, day_id: number, place_id: number, order_index: number): Promise<void> {
+ await this.nativeUpdate({ id }, { day: day_id, place: place_id, order_index });
+ }
+
+ /**
+ * AC22 (`AccommodationsService.relocateOwnStop`) — `UPDATE day_assignments
+ * SET order_index = order_index + 1 WHERE day_id = ? AND order_index >= ?
+ * AND id != ?`, the same column-from-column shape as {@link shiftOrderFrom}
+ * with an extra exclusion.
+ */
+ async shiftFromExcluding(day_id: number, from_index: number, exclude_id: number): Promise<void> {
+ const platform = this.getEntityManager().getPlatform();
+ await this.qb()
+ .update({ order_index: columnIncrementedBy(platform, 'order_index', 1) })
+ .where({ day: day_id, order_index: { $gte: from_index }, id: { $ne: exclude_id } })
+ .execute('run');
+ }
+
+ /** AC25 (`AccommodationsService.ownStops`) — `SELECT id, day_id, place_id, order_index FROM day_assignments WHERE accommodation_id = ?`. `day_id`/`place_id` are `persist(false)` relation mirrors — `columnRef`, the same trap {@link getDayId} documents. */
+ async listOwnedByStay(accommodation_id: number): Promise<{ id: number; day_id: number; place_id: number; order_index: number | null }[]> {
+ const platform = this.getEntityManager().getPlatform();
+ return await this.qb('da')
+ .select(['da.id', columnRef(platform, 'da.day_id').as('day_id'), columnRef(platform, 'da.place_id').as('place_id'), 'da.order_index'])
+ .where({ accommodation_id })
+ .execute<{ id: number; day_id: number; place_id: number; order_index: number | null }[]>('all', false);
+ }
+
+ /** AC26 (`AccommodationsService.releaseStops`, `keepStop` branch) — `UPDATE day_assignments SET accommodation_id = NULL WHERE id = ?`. */
+ async clearStay(id: number): Promise<void> {
+ await this.nativeUpdate({ id }, { accommodation_id: null });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3e Task 1 (`FilesService.findForeignLinkTarget`, R12) — additive,
+ // append-only per that task's own file-ownership rule.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * FL3 (`FilesService.findForeignLinkTarget`'s assignment branch) — `SELECT
+ * 1 FROM day_assignments a JOIN days d ON a.day_id = d.id WHERE a.id = ?
+ * AND d.trip_id = ?`, re-expressed as "what trip does this row belong to"
+ * via its `day` relation (R12 — "DayAssignmentsRepository.findTripId via
+ * its days join"; `day_assignments` has no `trip_id` column of its own).
+ * The same join shape `ReservationsRepository.getAssignmentTripId`
+ * (RS22) already used from a DIFFERENT repository before this file was
+ * this task's own to append to — this copy lives here instead, per R12's
+ * "one method per target table, on that table's own repository" ruling.
+ */
+ async findTripId(id: number): Promise<number | undefined> {
+ const platform = this.getEntityManager().getPlatform();
+ const row = await this.qb('da')
+ .join('da.day', 'd')
+ .select([columnRef(platform, 'd.trip_id').as('trip_id')])
+ .where({ id })
+ .execute<{ trip_id: number } | undefined>('get', false);
+ return row?.trip_id;
+ }
+ }
diff --cc server/src/db/repositories/Places.repository.ts
index 000000000,3cb1695eb..668ffb1d7
mode 000000,100644..100644
--- a/server/src/db/repositories/Places.repository.ts
+++ b/server/src/db/repositories/Places.repository.ts
@@@ -1,0 -1,1387 +1,1455 @@@
+ import type { Places } from '../entities/Places.entity';
+ import { absDifference, coalesceParam, columnRef, currentTimestamp, lowerTrim } from '../dialect/sql-functions';
+ import { type AssertRowKeys } from './_shared/rows';
+ import { TrekRepository } from './_shared/trek-repository';
+ // Task 9 fix wave (B-L2): `TagRow` is Tags.repository.ts's own row type,
+ // byte-identical to what used to be hand-mirrored here — a second
+ // declaration of the same shape is exactly the duplication Sonar flags and
+ // the program's "single source of truth" rule (root CLAUDE.md) forbids.
+ import type { TagRow } from './Tags.repository';
+
+ /** A `places` row as the API emits it — every scalar column of the entity. */
+ export interface PlaceRow {
+ id: number;
+ trip_id: number;
+ name: string;
+ description: string | null;
+ lat: number | null;
+ lng: number | null;
+ address: string | null;
+ category_id: number | null;
+ price: number | null;
+ currency: string | null;
+ reservation_status: string | null;
+ reservation_notes: string | null;
+ reservation_datetime: string | null;
+ place_time: string | null;
+ end_time: string | null;
+ duration_minutes: number | null;
+ notes: string | null;
+ image_url: string | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ website: string | null;
+ phone: string | null;
+ transport_mode: string | null;
+ created_at: string | null;
+ updated_at: string | null;
+ osm_id: string | null;
+ route_geometry: string | null;
+ route_color: string | null;
+ stop_type: string | null;
+ fill_percent: number | null;
+ amap_poi_id: string | null;
+ source: string | null;
+ email: string | null;
+ opening_hours: string | null;
+ }
+
+ const _placeRowKeys: AssertRowKeys<PlaceRow, Places> = true;
+
+ /** PL3 (`PlacesService.list`) — a `places` row joined with its category's flat columns. */
+ export interface PlaceWithCategoryRow extends PlaceRow {
+ category_name: string | null;
+ category_color: string | null;
+ category_icon: string | null;
+ }
+
+ /** {@link PlacesRepository.listForTrip}'s row: the category join plus the atlas' cached region (#2537), null when none resolved yet. */
+ export interface PlaceListRow extends PlaceWithCategoryRow {
+ country_code: string | null;
+ region_name: string | null;
++ /** The place's own id when it is a Tour (it has a `tours` facet row), else null. */
++ tour_place_id: number | null;
+ }
+
+ /** {@link PlacesRepository.findActiveTripFile}'s narrow `trip_files` shape. */
+ interface PlacesTripFileKyselyDB {
+ trip_files: { id: number; trip_id: number; filename: string; original_name: string; mime_type: string | null; file_size: number | null; deleted_at: string | null };
+ }
+
+ /**
+ * {@link PlacesRepository.listPublicForShare}'s projection (SH12) — the
+ * `PUBLIC_PLACE_COLUMNS` allow-list plus the category join, picked out of
+ * {@link PlaceWithCategoryRow} rather than re-derived (never independently
+ * widen this list — see that method's docstring).
+ */
+ export type SharePublicPlaceRow = Pick<
+ PlaceWithCategoryRow,
+ | 'id' | 'trip_id' | 'name' | 'description' | 'lat' | 'lng' | 'address' | 'category_id' | 'price' | 'currency'
+ | 'place_time' | 'end_time' | 'duration_minutes' | 'notes' | 'image_url' | 'website' | 'phone' | 'transport_mode'
+ | 'created_at' | 'updated_at' | 'category_name' | 'category_color' | 'category_icon'
+ >;
+
+ interface SharePublicPlaceKyselyDB {
+ places: Pick<PlaceRow,
+ | 'id' | 'trip_id' | 'name' | 'description' | 'lat' | 'lng' | 'address' | 'category_id' | 'price' | 'currency'
+ | 'place_time' | 'end_time' | 'duration_minutes' | 'notes' | 'image_url' | 'website' | 'phone' | 'transport_mode'
+ | 'created_at' | 'updated_at'
+ >;
+ categories: { id: number; name: string; color: string | null; icon: string | null };
+ }
+
+ interface PlaceRatingRow {
+ user_id: number;
+ username: string;
+ avatar: string | null;
+ rating: number;
+ }
+
+ /**
+ * `getPlaceWithTags` (`db/database.ts:146-197`, 0b's Concern for Task 4):
+ * the 11 `PlacesService` call sites move in Task 4, so `DatabaseService
+ * .getPlaceWithTags` keeps its own name/shape and delegates to this method
+ * NOW — no caller beyond `DatabaseService` changes in this task.
+ */
+ export interface PlaceWithTagsRow extends PlaceRow {
+ category: { id: number; name: string; color: string; icon: string } | null;
+ tags: TagRow[];
+ ratings: PlaceRatingRow[];
+ rating_avg: number | null;
+ rating_count: number;
+ }
+
+ export class PlacesRepository extends TrekRepository<Places> {
+ /**
+ * The legacy `getPlaceWithTags`'s three statements, byte-for-byte in intent
+ * (`mapResults: false` on every read, matching `TripsRepository
+ * .findAccessible`/`InviteTokensRepository.listWithCreatorAndTrip`):
+ *
+ * ```sql
+ * SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon
+ * FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?
+ *
+ * SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?
+ *
+ * SELECT pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr
+ * JOIN users u ON pr.user_id = u.id WHERE pr.place_id = ? ORDER BY pr.created_at
+ * ```
+ *
+ * `p.category`/`p.place_tags`/`p.place_ratings_collection` are the entity's
+ * own relation properties for these three joins (`Places.entity.ts`), so no
+ * hand-spelled join condition is needed; `pr.user` resolves to the
+ * `place_ratings.user_id` FK column the same way `TripsRepository
+ * .findAccessible`'s `t.user` resolves to `trips.user_id`.
+ */
+ async findWithTagsAndRatings(place_id: number | string): Promise<PlaceWithTagsRow | null> {
+ // Raw conditions (D4's T5 escape hatch), not `.where({ 'p.id': place_id })`:
+ // MikroORM's typed filter rejects a `string` against `p.id`'s branded
+ // `number` type — matching `TripsRepository.findAccessible`'s own
+ // raw-bind seam (`legacy getPlaceWithTags(placeId: number | string)`
+ // bound the raw value with no `Number()` conversion). `p.id` is the
+ // physical column name.
+ const place = await this.qb('p')
+ .leftJoin('p.category', 'c')
+ .select(['p.*', 'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon'])
+ .where('p.id = ?', [place_id])
+ .execute<PlaceWithCategoryRow | undefined>('get', false);
+ if (!place) return null;
+
+ const tags = await this.qb('p')
+ .join('p.place_tags', 't')
+ .select(['t.*'])
+ .where('p.id = ?', [place_id])
+ .execute<TagRow[]>('all', false);
+
+ // Task 0b review B1 (HIGH, live regression): `.select(['pr.user', ...])`
+ // makes MikroORM resolve `pr.user` through the ACTIVE `join('pr.user',
+ // 'u')` and emit the joined entity's own PK under its join alias
+ // (`u__id`), not the FK scalar (`user_id`) — `ratings[].user_id` never
+ // existed at runtime, silently breaking the client's
+ // `ratings.find(r => r.user_id === currentUserId)` own-rating lookup.
+ // `columnRef(...).as('user_id')` routes the FK column through the
+ // dialect layer and aliases it back explicitly; `'pr.user_id'` (the
+ // `persist(false)` scalar mirror) was tried and silently drops the
+ // column, `'pr.user as user_id'` was tried and is still `u__id` — both
+ // verified directly, not assumed (same finding independently reproduced
+ // in `PlaceRatingsRepository.listForPlaces`'s docstring, Plan 3c Task 1).
+ const platform = this.getEntityManager().getPlatform();
+ const ratings = await this.qb('p')
+ .join('p.place_ratings_collection', 'pr')
+ .join('pr.user', 'u')
+ .select([columnRef(platform, 'pr.user_id').as('user_id'), 'u.username', 'u.avatar', 'pr.rating'])
+ .where('p.id = ?', [place_id])
+ .orderBy({ 'pr.created_at': 'asc' })
+ .execute<PlaceRatingRow[]>('all', false);
+
+ // Task 0b review B2 (HIGH, live regression): the legacy `getPlaceWithTags`
+ // returned `{ ...place, category: ... }` over the raw driver row of
+ // `SELECT p.*, c.name as category_name, c.color as category_color, c.icon
+ // as category_icon` — the three alias columns ride along on the wire
+ // body (map popups, dashboard, shared-trip page all read them flat, per
+ // the review's blast-radius list). Read them, don't strip them: spread
+ // `place` whole, not `placeRest`.
+ const { category_name, category_color, category_icon } = place;
+ return {
+ ...place,
+ category: place.category_id
+ ? { id: place.category_id, name: category_name!, color: category_color!, icon: category_icon! }
+ : null,
+ tags,
+ ratings,
+ rating_avg: ratings.length > 0 ? ratings.reduce((s, r) => s + r.rating, 0) / ratings.length : null,
+ rating_count: ratings.length,
+ };
+ }
+
+ /**
+ * `SELECT 1 FROM places WHERE google_place_id = ? OR image_url = ? LIMIT 1`
+ * — the `places`-owned half of `PlacePhotoCacheService.isReferenced`
+ * (`place-photo-cache.service.ts:205-211`, PP6), split per the Plan 3c
+ * Task 1 PP6 ruling (option 2): the legacy single `UNION ALL … LIMIT 1`
+ * statement spans this table AND `collection_places` (Plan 3h's), so the
+ * service evaluates this half first and only runs the `collection_places`
+ * half when this one is `false` — reproducing the legacy `UNION ALL …
+ * LIMIT 1`'s short-circuit by evaluation order rather than by SQL.
+ */
+ async existsByGoogleIdOrImageUrl(googlePlaceId: string, imageUrl: string): Promise<boolean> {
+ const row = await this.qb('p')
+ .select(['p.id'])
+ .where({ $or: [{ google_place_id: googlePlaceId }, { image_url: imageUrl }] })
+ .limit(1)
+ .execute<{ id: number } | undefined>('get', false);
+ return !!row;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 4 (`PlacesService` core) — every method below is additive;
+ // `findWithTagsAndRatings`/`existsByGoogleIdOrImageUrl` above are Task 0b's
+ // and Task 1's, unchanged.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * PL0/PL7/PL49/AS5 — `SELECT id FROM places WHERE id = ? AND trip_id = ?`.
+ *
+ * **`id: number`, not `number | string` (Task 3 review H1, absorbed
+ * here — `task-3-review.md` §9.1):** the legacy raw-bind seam other
+ * guard-shaped methods in this cluster preserve (`TripsRepository
+ * .findAccessible`'s precedent) is the WRONG shape for a method whose
+ * caller then writes with `toRowId(placeId)!`. A non-canonical id
+ * (`"3 "`, `"3.0"`, `"+3"`) matches this statement via SQLite's own
+ * loose text/integer affinity — `existsInTrip` would answer `true` — while
+ * `toRowId` (`/^\d+$/` + `Number.isSafeInteger`, program rule 15) rejects
+ * the same string and returns `null`, so the write downstream runs
+ * `toRowId(placeId)!` on a value the gate just vouched for and gets
+ * `null` — exactly Task 3's H1 (`AssignmentsService.dayExists`/
+ * `placeExists`/`assignmentExistsInDay`/`getAssignmentForTrip`, all four
+ * kept on this seam, all four reproducing it). This method's only two
+ * callers (`PlacesService.get`/`applyUpdate`'s existence half — via
+ * `applyUpdate` calling `findInTrip` below — and `AssignmentsService
+ * .placeExists`, once Task 4 repoints it) now run `toRowId` FIRST and
+ * pass the validated `number` in, matching `DaysService.getDay`'s shape
+ * (the review's cited correct precedent) — so `id` here is narrowed to
+ * match what every caller actually has after its own gate, and a second
+ * `toRowId(...)!` downstream can never disagree with this one.
+ */
+ async existsInTrip(id: number, trip_id: number): Promise<boolean> {
+ const row = await this.qb('p')
+ .select(['p.id'])
+ .where({ 'p.id': id, 'p.trip_id': trip_id })
+ .execute<{ id: number } | undefined>('get', false);
+ return !!row;
+ }
+
+ /**
+ * PL9/PL48 — `SELECT * FROM places WHERE id = ? AND trip_id = ?`, byte-
+ * identical statements at both legacy sites (`applyUpdate`'s pre-image
+ * read and `searchImage`'s existence-plus-name read) — one method for
+ * both rather than two identically-bodied ones.
+ *
+ * `id: number`, same H1 fix and reasoning as `existsInTrip` above: both
+ * callers write with the SAME already-`toRowId`'d id this read returns
+ * (`applyUpdate` feeds it straight into `updatePlace`/`tagsRepo`;
+ * `searchImage` only reads, but takes the same gate shape for
+ * consistency — one rule for every place-id gate in this service, not
+ * one per call site).
+ */
+ async findInTrip(id: number, trip_id: number): Promise<PlaceRow | undefined> {
+ return this.qb('p')
+ .select(['p.*'])
+ .where({ 'p.id': id, 'p.trip_id': trip_id })
+ .execute<PlaceRow | undefined>('get', false);
+ }
+
+ /**
+ * Plan 3g Task 2 (JG44) — `journey-domain.service.ts#onPlaceUpdated`'s
+ * `SELECT * FROM places WHERE id = ?`, unscoped (no `trip_id` — the sync
+ * engine already resolved the place from its own `journey_entries.source_place_id`
+ * column, so the id alone is trusted here the same way `TripsRepository
+ * .findRaw` trusts a bare trip id). ONE append to this file for JG44 per
+ * the 3g plan's task split — every other method here belongs to Plan 3c.
+ */
+ async findRaw(id: number): Promise<PlaceRow | undefined> {
+ return this.qb('p')
+ .select(['p.*'])
+ .where({ 'p.id': id })
+ .execute<PlaceRow | undefined>('get', false);
+ }
+
+ /**
+ * PL17/PL20 — `SELECT google_place_id, image_url FROM places WHERE id = ?
+ * AND trip_id = ?`, the reclaim-candidate projection `remove`/`removeMany`
+ * read BEFORE their delete transaction. `id: number`, same H1 fix: both
+ * callers immediately follow a `true` result with `deleteById(id)` on the
+ * SAME numeric id.
+ */
+ async reclaimInputs(id: number, trip_id: number): Promise<{ google_place_id: string | null; image_url: string | null } | undefined> {
+ return this.qb('p')
+ .select(['p.google_place_id', 'p.image_url'])
+ .where({ 'p.id': id, 'p.trip_id': trip_id })
+ .execute<{ google_place_id: string | null; image_url: string | null } | undefined>('get', false);
+ }
+
++ /**
++ * `SELECT 1 FROM tours WHERE place_id = ?`, read through the place's
++ * `tours` facet so the Places domain answers it without the Tours
++ * repository. `remove`/`removeMany` call it inside their delete
++ * transaction to report which deleted places were Tours; the facet row and
++ * its waypoints go with the place through `ON DELETE CASCADE`.
++ */
++ async isTour(id: number): Promise<boolean> {
++ const row = await this.qb('p')
++ .join('p.tours', 't')
++ .select(['p.id'])
++ .where({ 'p.id': id })
++ .execute<{ id: number } | undefined>('get', false);
++ return !!row;
++ }
++
+ /** PL19/PL21 — `DELETE FROM places WHERE id = ?`, unscoped: every caller proved trip access first. */
+ async deleteById(id: number): Promise<void> {
+ await this.nativeDelete({ id });
+ }
+
+ /**
+ * PL23 — `` SELECT id FROM places WHERE trip_id = ? AND id IN (${…}) ``,
+ * narrowed to the caller's own INPUT ORDER (not SQL result order — SQLite
+ * makes no ordering promise for an `IN (...)` scan and the legacy code
+ * re-filters the original `ids` array through a `Set` built from the row
+ * set for exactly this reason). `$in` for the dynamic list (rule 17b, "the
+ * good kind").
+ */
+ async scopedIds(trip_id: string | number, ids: number[]): Promise<number[]> {
+ if (ids.length === 0) return [];
+ const rows = await this.qb('p')
+ .select(['p.id'])
+ .where('p.trip_id = ?', [trip_id])
+ .andWhere({ id: { $in: ids } })
+ .execute<{ id: number }[]>('all', false);
+ const owned = new Set(rows.map((r) => r.id));
+ return ids.filter((id) => owned.has(id));
+ }
+
+ /**
+ * PL4 — the 27-column `INSERT INTO places (...)` the service's `create`
+ * builds. Every value here is already fully coerced by the caller (the
+ * `?? null` vs `|| null` split PL4's own legacy comment documents — 0 is
+ * legitimate for `lat`/`lng`/`price`/`fill_percent`, and
+ * `duration_minutes` defaults to 60 — stays the service's decision, this
+ * writes exactly what it is handed, `DaysRepository.createDay`'s split).
+ * `em.insert()` returns the generated PK (R6's `lastInsertRowid`
+ * replacement).
+ */
+ async insertPlace(input: {
+ trip_id: number;
+ name: string;
+ description: string | null;
+ lat: number | null;
+ lng: number | null;
+ address: string | null;
+ category_id: number | null;
+ price: number | null;
+ currency: string | null;
+ place_time: string | null;
+ end_time: string | null;
+ duration_minutes: number;
+ notes: string | null;
+ image_url: string | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ osm_id: string | null;
+ amap_poi_id: string | null;
+ website: string | null;
+ phone: string | null;
+ transport_mode: string;
+ route_geometry: string | null;
+ route_color: string | null;
+ stop_type: string | null;
+ fill_percent: number | null;
+ email: string | null;
+ opening_hours: string | null;
+ }): Promise<number> {
+ return await this.insert({
+ trip: input.trip_id,
+ name: input.name,
+ description: input.description,
+ lat: input.lat,
+ lng: input.lng,
+ address: input.address,
+ category: input.category_id,
+ price: input.price,
+ currency: input.currency,
+ place_time: input.place_time,
+ end_time: input.end_time,
+ duration_minutes: input.duration_minutes,
+ notes: input.notes,
+ image_url: input.image_url,
+ google_place_id: input.google_place_id,
+ google_ftid: input.google_ftid,
+ osm_id: input.osm_id,
+ amap_poi_id: input.amap_poi_id,
+ website: input.website,
+ phone: input.phone,
+ transport_mode: input.transport_mode,
+ route_geometry: input.route_geometry,
+ route_color: input.route_color,
+ stop_type: input.stop_type,
+ fill_percent: input.fill_percent,
+ email: input.email,
+ opening_hours: input.opening_hours,
+ });
+ }
+
+ /**
+ * PL11 — `UPDATE places SET name = COALESCE(?, name), description = ?,
+ * lat = ?, lng = ?, address = ?, category_id = ?, price = ?, currency =
+ * COALESCE(?, currency), place_time = ?, end_time = ?, duration_minutes =
+ * ?, notes = ?, image_url = ?, google_place_id = ?, google_ftid = ?,
+ * osm_id = ?, amap_poi_id = ?, website = ?, phone = ?, email = ?,
+ * opening_hours = ?, transport_mode = COALESCE(?, transport_mode),
+ * route_color = ?, stop_type = ?, fill_percent = ?,
+ * updated_at = CURRENT_TIMESTAMP WHERE id = ?` — ONE
+ * `nativeUpdate` with a typed full partial (the ruling): the SQL
+ * `COALESCE(?, col)` keep-if-null semantics (`name`/`currency`/
+ * `transport_mode`) and the twenty-two `!== undefined ? x : existing.x`
+ * pre-image fallbacks are both already resolved to their FINAL value by
+ * the caller (`PlacesService.applyUpdate`, which reads the pre-image via
+ * `findInTrip` first) — this method writes exactly what it is handed,
+ * plus the timestamp stamp every write gets.
+ */
+ async updatePlace(id: number, write: {
+ // Task 9 fix wave (B-L10): `places.name` is `NOT NULL` (`PlaceRow.name:
+ // string`); the caller's `(name || null) ?? existingPlace.name` fold
+ // always resolves to a real string before this is called — `string |
+ // null` here was a widened lie the type checker could never catch a
+ // real NULL write through.
+ name: string;
+ description: string | null;
+ lat: number | null;
+ lng: number | null;
+ address: string | null;
+ category_id: number | null;
+ price: number | null;
+ currency: string | null;
+ place_time: string | null;
+ end_time: string | null;
+ duration_minutes: number | null;
+ notes: string | null;
+ image_url: string | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ osm_id: string | null;
+ amap_poi_id: string | null;
+ website: string | null;
+ phone: string | null;
+ transport_mode: string | null;
+ route_color: string | null;
+ stop_type: string | null;
+ fill_percent: number | null;
+ email: string | null;
+ opening_hours: string | null;
+ }): Promise<void> {
+ const platform = this.getEntityManager().getPlatform();
+ await this.nativeUpdate({ id }, {
+ name: write.name,
+ description: write.description,
+ lat: write.lat,
+ lng: write.lng,
+ address: write.address,
+ category: write.category_id,
+ price: write.price,
+ currency: write.currency,
+ place_time: write.place_time,
+ end_time: write.end_time,
+ duration_minutes: write.duration_minutes,
+ notes: write.notes,
+ image_url: write.image_url,
+ google_place_id: write.google_place_id,
+ google_ftid: write.google_ftid,
+ osm_id: write.osm_id,
+ amap_poi_id: write.amap_poi_id,
+ website: write.website,
+ phone: write.phone,
+ transport_mode: write.transport_mode,
+ route_color: write.route_color,
+ stop_type: write.stop_type,
+ fill_percent: write.fill_percent,
+ email: write.email,
+ opening_hours: write.opening_hours,
+ updated_at: currentTimestamp(platform),
+ });
+ }
+
+ /**
+ * PL25 (`findDuplicatePlace`'s `externalId` strategy) — `SELECT id,
+ * google_ftid FROM places WHERE trip_id = ? AND (google_place_id = ? OR
+ * google_ftid = ? OR osm_id = ? OR amap_poi_id = ?) ORDER BY id ASC LIMIT
+ * 1` — the same candidate id bound in all four positions, exactly as the
+ * legacy statement does.
+ */
+ async findDuplicateByExternalId(trip_id: string, external_id: string): Promise<{ id: number; google_ftid: string | null } | undefined> {
+ return this.qb('p')
+ .select(['p.id', 'p.google_ftid'])
+ .where('p.trip_id = ?', [trip_id])
+ .andWhere({
+ $or: [
+ { google_place_id: external_id },
+ { google_ftid: external_id },
+ { osm_id: external_id },
+ { amap_poi_id: external_id },
+ ],
+ })
+ .orderBy({ 'p.id': 'asc' })
+ .limit(1)
+ .execute<{ id: number; google_ftid: string | null } | undefined>('get', false);
+ }
+
+ /**
+ * PL26 (`findDuplicatePlace`'s `name` strategy) — `SELECT id, google_ftid
+ * FROM places WHERE trip_id = ? AND lower(trim(name)) = ? ORDER BY id ASC
+ * LIMIT 1`. Rule 18's documented-disagreement exception clause: the legacy
+ * statement's OWN bound value is already JS-lowered+trimmed
+ * (`normalizePlaceName`, `@trek/shared/place/place-match.ts`, Unicode-
+ * aware), so `lowered_trimmed_name` here must be passed in ALREADY
+ * lowered — never re-lowered through `lowerParam` (that would apply
+ * SQLite's ASCII-only `LOWER()` a second time, on a value the caller
+ * already folded fully). `lowerTrim(platform, 'p.name')` renders
+ * `LOWER(TRIM(name))` (SQLite `LOWER()` is ASCII-only, program rule 18 —
+ * the documented divergence PL26's legacy comment (`places.service.ts
+ * :609-619`) already accepts and this repository reproduces literally,
+ * not fixes).
+ */
+ async findDuplicateByName(trip_id: string, lowered_trimmed_name: string): Promise<{ id: number; google_ftid: string | null } | undefined> {
+ const platform = this.getEntityManager().getPlatform();
+ return this.qb('p')
+ .select(['p.id', 'p.google_ftid'])
+ .where('p.trip_id = ?', [trip_id])
+ .andWhere({ [lowerTrim(platform, 'p.name')]: lowered_trimmed_name })
+ .orderBy({ 'p.id': 'asc' })
+ .limit(1)
+ .execute<{ id: number; google_ftid: string | null } | undefined>('get', false);
+ }
+
+ /**
+ * PL27 (`findDuplicatePlace`'s `coords` strategy) — `SELECT id,
+ * google_ftid FROM places WHERE trip_id = ? AND lat IS NOT NULL AND lng IS
+ * NOT NULL AND abs(lat - ?) <= ? AND abs(lng - ?) <= ? ORDER BY id ASC
+ * LIMIT 1`. `absDifference(platform, ref, value)` renders `ABS(<col> - ?)`
+ * with `value` already bound inside the fragment (`sql-functions.ts`'s own
+ * docstring) — used as a filter KEY paired with `{ $lte: tolerance }`, so
+ * the emitted SQL and bind order match the legacy statement exactly:
+ * `ABS(lat - ?) <= ?` then `ABS(lng - ?) <= ?`, the SAME `tolerance` value
+ * on both.
+ */
+ async findDuplicateByCoords(trip_id: string, lat: number, lng: number, tolerance: number): Promise<{ id: number; google_ftid: string | null } | undefined> {
+ const platform = this.getEntityManager().getPlatform();
+ return this.qb('p')
+ .select(['p.id', 'p.google_ftid'])
+ .where('p.trip_id = ?', [trip_id])
+ .andWhere({
+ lat: { $ne: null },
+ lng: { $ne: null },
+ [absDifference(platform, 'p.lat', lat)]: { $lte: tolerance },
+ [absDifference(platform, 'p.lng', lng)]: { $lte: tolerance },
+ })
+ .orderBy({ 'p.id': 'asc' })
+ .limit(1)
+ .execute<{ id: number; google_ftid: string | null } | undefined>('get', false);
+ }
+
+ /**
+ * PL29 (`exportGpx`'s waypoint read) — `SELECT p.name, p.description,
+ * p.address, p.lat, p.lng, p.route_geometry, c.name AS category FROM
+ * places p LEFT JOIN categories c ON c.id = p.category_id WHERE p.trip_id
+ * = ? ORDER BY p.id`. PL30 (the `days`/`day_assignments` itinerary half)
+ * is `DayAssignmentsRepository.listItineraryForGpx` — a different table
+ * root, kept there per the task-4 brief's own pointer.
+ */
+ async listForGpx(trip_id: string): Promise<{
+ name: string; description: string | null; address: string | null;
+ lat: number | null; lng: number | null; route_geometry: string | null;
+ category: string | null;
+ }[]> {
+ return this.qb('p')
+ .leftJoin('p.category', 'c')
+ .select(['p.name', 'p.description', 'p.address', 'p.lat', 'p.lng', 'p.route_geometry', 'c.name as category'])
+ .where('p.trip_id = ?', [trip_id])
+ .orderBy({ 'p.id': 'asc' })
+ .execute<{ name: string; description: string | null; address: string | null; lat: number | null; lng: number | null; route_geometry: string | null; category: string | null }[]>('all', false);
+ }
+
+ /**
+ * PL24 (`PlacesService.buildDedupSet`'s read) — `SELECT name, lat, lng,
+ * google_place_id, google_ftid, osm_id, amap_poi_id FROM places WHERE
+ * trip_id = ?`, the exact projection the legacy statement named. Task 4's
+ * ruling left this raw under `PlacesService` because the dedup semantics
+ * (names lowercased+trimmed in JS, coordinates collected only for unnamed
+ * rows, provider ids collected for every row) are a JS decision, not a SQL
+ * one — Task 5 review L6 pointed out that leaving the SQL itself raw
+ * still contradicted the deliverable's "PL15/16/18/22 + PI2 are the only
+ * allowed survivors" grep. This method is the additive repository seam
+ * that resolves that: it carries only the projection, none of the JS
+ * folding logic, which stays in `PlacesService.buildDedupSet` exactly as
+ * it was.
+ */
+ async listDedupInputs(trip_id: string): Promise<{
+ name: string | null; lat: number | null; lng: number | null;
+ google_place_id: string | null; google_ftid: string | null; osm_id: string | null; amap_poi_id: string | null;
+ }[]> {
+ return this.qb('p')
+ .select(['p.name', 'p.lat', 'p.lng', 'p.google_place_id', 'p.google_ftid', 'p.osm_id', 'p.amap_poi_id'])
+ .where('p.trip_id = ?', [trip_id])
+ .execute<{
+ name: string | null; lat: number | null; lng: number | null;
+ google_place_id: string | null; google_ftid: string | null; osm_id: string | null; amap_poi_id: string | null;
+ }[]>('all', false);
+ }
+
+ /**
+ * PI1 (`place-image.ts:27`) — `SELECT 1 FROM places WHERE image_url = ?
+ * LIMIT 1`. Trip-agnostic on purpose (an uploaded image is ref-counted
+ * across every trip, not just the one it was uploaded from — a place
+ * copied or shared across trips can share the file).
+ */
+ async existsByImageUrl(imageUrl: string): Promise<boolean> {
+ const row = await this.qb('p')
+ .select(['p.id'])
+ .where({ image_url: imageUrl })
+ .limit(1)
+ .execute<{ id: number } | undefined>('get', false);
+ return !!row;
+ }
+
+ /**
+ * PL3 (`PlacesService.list`) — the trip's places, joined with their
+ * category's flat columns, filtered by up to four optional fragments
+ * built as conditional `andWhere`s rather than a hand-assembled SQL
+ * string (§18.3's surprise: the legacy statement's own text is not
+ * knowable from the source without tracing four `if`s — this makes each
+ * fragment a single, separately readable `andWhere` call instead).
+ *
+ * `filters.searchPattern` arrives PRE-BUILT (`%${escapeLikePattern(term)}%`,
+ * the service's job, matching every other "coercions stay in the service"
+ * split in this program) — this binds it verbatim into all three `LIKE …
+ * ESCAPE '\'` fragments, matching the legacy's one-param-three-times bind.
+ * The `ESCAPE '\'` clause is written into the raw fragment text because
+ * MikroORM's `$like` operator does not add one (§18.3).
+ *
+ * `filters.category`/`filters.tag` bind their raw string values with no
+ * `Number()` conversion (matching the legacy statement's own untyped
+ * bind); the two `assignment` fragments reference `place_tags`/
+ * `day_assignments`/`days` by physical table name in a subquery (neither
+ * has, or needs, an entity-relation path for this shape) — the same
+ * raw-SQL-subquery shape `PlacesService.list`'s own legacy string used.
+ *
+ * `DISTINCT` kept via `.select([...], true)` even though a place has at
+ * most one category row (so it changes nothing about THIS join) — parity
+ * with the legacy statement's own `SELECT DISTINCT`, not a functional
+ * requirement.
+ */
+ async listForTrip(trip_id: string, filters: {
+ searchPattern?: string;
+ category?: string;
+ tag?: string;
+ assignment?: 'all' | 'unassigned' | 'assigned';
+ }): Promise<PlaceListRow[]> {
++ const platform = this.getEntityManager().getPlatform();
+ const qb = this.qb('p')
+ .leftJoin('p.category', 'c')
+ // #2537: the atlas' cached region rides along (`LEFT JOIN place_regions pr ON pr.place_id = p.id`).
+ .leftJoin('p.place_regions', 'pr')
++ // Tours: `LEFT JOIN tours t ON t.place_id = p.id` marks the Tour-backed
++ // places. `columnRef`, because the bare `t.place_id` twin is
++ // persist(false) and selects nothing.
++ .leftJoin('p.tours', 't')
+ .select([
- 'p.*', 'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon',
++ 'p.*', columnRef(platform, 't.place_id').as('tour_place_id'),
++ 'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon',
+ 'pr.country_code as country_code', 'pr.region_name as region_name',
+ ], true)
+ .where('p.trip_id = ?', [trip_id]);
+
+ if (filters.searchPattern) {
+ qb.andWhere(
+ "(p.name LIKE ? ESCAPE '\\' OR p.address LIKE ? ESCAPE '\\' OR p.description LIKE ? ESCAPE '\\')",
+ [filters.searchPattern, filters.searchPattern, filters.searchPattern],
+ );
+ }
+ if (filters.category) {
+ qb.andWhere('p.category_id = ?', [filters.category]);
+ }
+ if (filters.tag) {
+ qb.andWhere('p.id IN (SELECT place_id FROM place_tags WHERE tag_id = ?)', [filters.tag]);
+ }
+ if (filters.assignment === 'unassigned') {
+ qb.andWhere(
+ 'p.id NOT IN (SELECT da.place_id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE d.trip_id = ?)',
+ [trip_id],
+ );
+ } else if (filters.assignment === 'assigned') {
+ qb.andWhere(
+ 'p.id IN (SELECT da.place_id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE d.trip_id = ?)',
+ [trip_id],
+ );
+ }
+
+ qb.orderBy({ 'p.created_at': 'desc' });
+
+ return qb.execute<PlaceListRow[]>('all', false);
+ }
+
+ /**
+ * PL53 (`PlacesService.setImageFromFile`, #1242) — `SELECT filename,
+ * original_name, mime_type, file_size FROM trip_files WHERE id = ? AND
+ * trip_id = ? AND deleted_at IS NULL`: the attachment a place takes its
+ * picture from, trash excluded.
+ */
+ async findActiveTripFile(id: number, trip_id: number): Promise<{ filename: string; original_name: string; mime_type: string | null; file_size: number | null } | undefined> {
+ return await this.kysely<PlacesTripFileKyselyDB>()
+ .selectFrom('trip_files')
+ .select(['filename', 'original_name', 'mime_type', 'file_size'])
+ .where('id', '=', id)
+ .where('trip_id', '=', trip_id)
+ .where('deleted_at', 'is', null)
+ .executeTakeFirst();
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 5 (`PlacesService` import paths) — every method below is
+ // additive: `insertPlace`/`updatePlace`/`findWithTagsAndRatings`/the
+ // `findDuplicateBy*` trio above are Task 4's, unchanged and reused verbatim
+ // by the four importers (GPX/KML/Google/Naver) this task converts.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * PL36 (`colorizeImportedTracks`'s read half) — `SELECT DISTINCT
+ * route_color AS c FROM places WHERE trip_id = ? AND route_color IS NOT
+ * NULL`. `DISTINCT` via `.select([...], true)` (the same shape
+ * `listForTrip`/PL3 uses for its own `SELECT DISTINCT`), not `$ne: null`
+ * folded into a single-object filter, so the emitted `WHERE` clause reads
+ * in the legacy's own `trip_id = ? AND route_color IS NOT NULL` order.
+ *
+ * Called and its result acted on inside the SAME `uow.transactional(...)`
+ * block `setRouteColor` below writes in (the service's own PL36+PL37
+ * pairing) — read and write share one transaction so two concurrent
+ * imports can never both observe the same set of free colours.
+ */
+ async distinctRouteColors(trip_id: string | number): Promise<string[]> {
+ const rows = await this.qb('p')
+ .select(['p.route_color as c'], true)
+ .where('p.trip_id = ? AND p.route_color IS NOT NULL', [trip_id])
+ .execute<{ c: string }[]>('all', false);
+ return rows.map((r) => r.c);
+ }
+
+ /**
+ * PL37 (`colorizeImportedTracks`'s write half) — `UPDATE places SET
+ * route_color = ? WHERE id = ?`. No `updated_at` stamp — the legacy
+ * statement never wrote one for this column (#776's own deliberate
+ * omission, restated in `PlacesService`'s class docstring), and this
+ * method reproduces exactly that, not the "every write stamps
+ * `updated_at`" shape `updatePlace`/`backfillFtid`/`fillIfEmpty` below
+ * follow.
+ */
+ async setRouteColor(id: number, route_color: string): Promise<void> {
+ await this.nativeUpdate({ id }, { route_color });
+ }
+
+ /**
+ * PL39 (`storeGooglePlaces`'s dedup-backfill half) — `UPDATE places SET
+ * google_ftid = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, unscoped
+ * by `trip_id` (matching the legacy statement exactly — the candidate id
+ * was already resolved against this trip by the `findDuplicatePlace` call
+ * immediately before it).
+ */
+ async backfillFtid(id: number, google_ftid: string): Promise<void> {
+ const platform = this.getEntityManager().getPlatform();
+ await this.nativeUpdate({ id }, { google_ftid, updated_at: currentTimestamp(platform) });
+ }
+
+ /**
+ * PL43/PL44/PL46 (`enrichOne`'s two `UPDATE`s and
+ * `backfillMissingAddresses`'s one) — three legacy statements, one shape:
+ * `UPDATE places SET <col> = COALESCE(<col>, ?), ..., updated_at =
+ * CURRENT_TIMESTAMP WHERE id = ? AND trip_id = ?`. One `nativeUpdate` per
+ * CALL, built from whichever of the six columns the caller passes
+ * (`fields`'s keys are all optional — a key left OFF `fields` entirely is
+ * not touched at all, not even COALESCE'd against itself); every key
+ * that IS present renders `COALESCE(<col>, ?)` through `coalesceParam`
+ * (never an inline `raw()`), so a column already holding a value is never
+ * overwritten and an empty one is filled from `fields`'s value.
+ * `updated_at` is stamped unconditionally — all three legacy statements
+ * stamp it, none of them conditionally.
+ *
+ * The three call shapes this serves (Task 5's "×3 shapes"):
+ * - PL43 (`enrichOne`'s main update) — `google_place_id`, `google_ftid`,
+ * `address`, `website`, `phone` all at once.
+ * - PL44 (`enrichOne`'s photo update) — `image_url` alone.
+ * - PL46 (`backfillMissingAddresses`) — `address` alone.
+ */
+ async fillIfEmpty(id: number, trip_id: number, fields: {
+ google_place_id?: string | null;
+ google_ftid?: string | null;
+ address?: string | null;
+ website?: string | null;
+ phone?: string | null;
+ image_url?: string | null;
+ }): Promise<void> {
+ const platform = this.getEntityManager().getPlatform();
+ const data: {
+ google_place_id?: ReturnType<typeof coalesceParam>;
+ google_ftid?: ReturnType<typeof coalesceParam>;
+ address?: ReturnType<typeof coalesceParam>;
+ website?: ReturnType<typeof coalesceParam>;
+ phone?: ReturnType<typeof coalesceParam>;
+ image_url?: ReturnType<typeof coalesceParam>;
+ updated_at: ReturnType<typeof currentTimestamp>;
+ } = { updated_at: currentTimestamp(platform) };
+ if (fields.google_place_id !== undefined) data.google_place_id = coalesceParam(platform, 'google_place_id', fields.google_place_id);
+ if (fields.google_ftid !== undefined) data.google_ftid = coalesceParam(platform, 'google_ftid', fields.google_ftid);
+ if (fields.address !== undefined) data.address = coalesceParam(platform, 'address', fields.address);
+ if (fields.website !== undefined) data.website = coalesceParam(platform, 'website', fields.website);
+ if (fields.phone !== undefined) data.phone = coalesceParam(platform, 'phone', fields.phone);
+ if (fields.image_url !== undefined) data.image_url = coalesceParam(platform, 'image_url', fields.image_url);
+ await this.nativeUpdate({ id, trip: trip_id }, data);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 7 (`trips.rpc.ts`) — additive (per `task-4-report.md`'s own
+ // note that this method "may not exist"): every column above is Task 4/5's,
+ // unchanged.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * RP2 (`trips.rpc.ts::getPlaces`) — `SELECT * FROM places WHERE trip_id = ?
+ * ORDER BY created_at DESC`. The trip's place POOL has no itinerary
+ * position of its own (`day_id`/`order_index` live on `day_assignments`),
+ * so this orders by `created_at` like the REST list does — the RPC
+ * method's own comment (`trips.rpc.ts`).
+ */
+ async listForTripOrdered(trip_id: number): Promise<PlaceRow[]> {
+ return await this.qb('p')
+ .select(['p.*'])
+ .where({ trip: trip_id })
+ .orderBy({ 'p.created_at': 'desc' })
+ .execute<PlaceRow[]>('all', false);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3h Task 6 (`share.service.ts`) — additive.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `share.service.ts:340` SH12 (`getSharedTripData`'s share_map place-pool
+ * read) — **SECURITY-CRITICAL (#2320)**: a named 20-column allow-list,
+ * never `p.*`. Withheld on purpose (matching `PUBLIC_PLACE_COLUMNS`'s own
+ * doc comment in `share.service.ts`): the owner's booking-status columns
+ * (`reservation_status`/`reservation_notes`/`reservation_datetime`), every
+ * routing/dedup id (`google_place_id`, `google_ftid`, `osm_id`,
+ * `amap_poi_id`), `route_geometry`/`route_color`/`stop_type`/
+ * `fill_percent`, and `source`. Kysely, not `qb()`+`columnRef`: this read
+ * joins `p.category` under alias `c`, and both `trip_id`/`category_id` are
+ * `persist(false)` mirror columns — the exact trap
+ * `DayAssignmentsRepository.assignmentWithPlaceSelect`'s docstring
+ * documents. `ORDER BY p.created_at DESC`, matching the legacy statement.
+ */
+ async listPublicForShare(trip_id: number | string): Promise<SharePublicPlaceRow[]> {
+ return await this.kysely<SharePublicPlaceKyselyDB>()
+ .selectFrom('places as p')
+ .leftJoin('categories as c', 'c.id', 'p.category_id')
+ .select([
+ 'p.id', 'p.trip_id', 'p.name', 'p.description', 'p.lat', 'p.lng', 'p.address', 'p.category_id',
+ 'p.price', 'p.currency', 'p.place_time', 'p.end_time', 'p.duration_minutes', 'p.notes',
+ 'p.image_url', 'p.website', 'p.phone', 'p.transport_mode', 'p.created_at', 'p.updated_at',
+ 'c.name as category_name', 'c.color as category_color', 'c.icon as category_icon',
+ ])
+ .where('p.trip_id', '=', trip_id as number)
+ .orderBy('p.created_at', 'desc')
+ .execute();
+ }
+
+ /**
+ * `share.service.ts:461` SH18 (`getSharedPlacePhotoKey`) —
+ * **SECURITY-CRITICAL**: the anonymous photo-serving ownership gate.
+ * `SELECT 1 FROM places WHERE trip_id = ? AND image_url = ?` — both must
+ * match, proving the requested proxy URL belongs to a place on the SAME
+ * trip the share token covers, never just any place anywhere with that
+ * `image_url`.
+ */
+ async existsByTripAndImageUrl(trip_id: number | string, imageUrl: string): Promise<boolean> {
+ const row = await this.kysely<{ places: { id: number; trip_id: number; image_url: string | null } }>()
+ .selectFrom('places')
+ .select('id')
+ .where('trip_id', '=', trip_id as number)
+ .where('image_url', '=', imageUrl)
+ .limit(1)
+ .executeTakeFirst();
+ return !!row;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 8 (`TripsService.copy`) — additive.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * TP40 (`trips.service.ts::copy`'s places read) — `SELECT * FROM places
+ * WHERE trip_id = ?`, no `ORDER BY` at all (unlike RP2's `listForTripOrdered`
+ * above, which adds `ORDER BY created_at DESC` for the RPC list view). The
+ * legacy statement relies on SQLite's own rowid-ascending scan order for a
+ * plain, unindexed `WHERE trip_id = ?` — reproduced here the same way, by
+ * NOT adding an `ORDER BY`, so the copy's places are inserted (and so
+ * relatively ordered) the same way the legacy loop did.
+ */
+ async listAllForTrip(trip_id: number | string): Promise<PlaceRow[]> {
+ return await this.qb('p')
+ .select(['p.*'])
+ .where('p.trip_id = ?', [trip_id])
+ .execute<PlaceRow[]>('all', false);
+ }
+
+ /**
+ * TP41 (`trips.service.ts::copy`'s place INSERT) — the 28-column
+ * `INSERT INTO places (...)` the copy loop builds, three columns wider
+ * than PL4's `insertPlace` (`reservation_status`, `reservation_notes`,
+ * `reservation_datetime` — a copy carries the source place's reservation
+ * fields verbatim; `PlacesService.create` never sets them at creation
+ * time, which is why PL4's own column set omits them). Every value here
+ * is copied straight off the source row with no coercion of its own — the
+ * copy loop's job is to remap `trip_id`, nothing else.
+ */
+ async insertPlaceCopy(input: {
+ trip_id: number;
+ name: string;
+ description: string | null;
+ lat: number | null;
+ lng: number | null;
+ address: string | null;
+ category_id: number | null;
+ price: number | null;
+ currency: string | null;
+ reservation_status: string | null;
+ reservation_notes: string | null;
+ reservation_datetime: string | null;
+ place_time: string | null;
+ end_time: string | null;
+ duration_minutes: number | null;
+ notes: string | null;
+ image_url: string | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ website: string | null;
+ phone: string | null;
+ transport_mode: string | null;
+ osm_id: string | null;
+ amap_poi_id: string | null;
+ route_geometry: string | null;
+ route_color: string | null;
+ stop_type: string | null;
+ fill_percent: number | null;
+ }): Promise<number> {
+ return await this.insert({
+ trip: input.trip_id,
+ name: input.name,
+ description: input.description,
+ lat: input.lat,
+ lng: input.lng,
+ address: input.address,
+ category: input.category_id,
+ price: input.price,
+ currency: input.currency,
+ reservation_status: input.reservation_status,
+ reservation_notes: input.reservation_notes,
+ reservation_datetime: input.reservation_datetime,
+ place_time: input.place_time,
+ end_time: input.end_time,
+ duration_minutes: input.duration_minutes,
+ notes: input.notes,
+ image_url: input.image_url,
+ google_place_id: input.google_place_id,
+ google_ftid: input.google_ftid,
+ website: input.website,
+ phone: input.phone,
+ transport_mode: input.transport_mode,
+ osm_id: input.osm_id,
+ amap_poi_id: input.amap_poi_id,
+ route_geometry: input.route_geometry,
+ route_color: input.route_color,
+ stop_type: input.stop_type,
+ fill_percent: input.fill_percent,
+ });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3d Task 1 (`RoadtripService`/`ChargingService`) — additive, per this
+ // task's own file-ownership rule ("all additive methods on Days/Places/
+ // DayAssignments repositories").
+ // ---------------------------------------------------------------------------
+
+ /**
+ * RT13 (`RoadtripService.trackExists`) — `SELECT id FROM places WHERE id =
+ * ? AND trip_id = ? AND route_geometry IS NOT NULL AND route_geometry !=
+ * ''`. Two `.andWhere()` calls (rule 23 — typed conditions, not an inline
+ * SQL string) rather than one `$and` array: the two operators (`$ne: null`
+ * for `IS NOT NULL`, `$ne: ''` for `!= ''`) target the SAME property, so a
+ * single filter object literal cannot carry both keys.
+ */
+ async isTrackInTrip(id: number, trip_id: number): Promise<boolean> {
+ const row = await this.qb('p')
+ .select(['p.id'])
+ .where({ id, trip: trip_id })
+ .andWhere({ route_geometry: { $ne: null } })
+ .andWhere({ route_geometry: { $ne: '' } })
+ .execute<{ id: number } | undefined>('get', false);
+ return !!row;
+ }
+
+ /** CH1 (`ChargingService.read`) — `SELECT name, lat, lng, stop_type FROM places WHERE id = ? AND trip_id = ?`. */
+ async findChargingProbe(id: number, trip_id: number): Promise<{ name: string; lat: number | null; lng: number | null; stop_type: string | null } | undefined> {
+ const row = await this.qb('p')
+ .select(['p.name', 'p.lat', 'p.lng', 'p.stop_type'])
+ .where({ id, trip: trip_id })
+ .execute<{ name: string; lat: number | null; lng: number | null; stop_type: string | null } | undefined>('get', false);
+ return row ?? undefined;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3d Task 3 (`AccommodationsService`) — additive, per this task's own
+ // file-ownership rule ("additive methods on Days/Places/DayAssignments/
+ // Reservations repositories where a read belongs there").
+ // ---------------------------------------------------------------------------
+
+ /** AC9 (`AccommodationsService.stampLodging`) — `SELECT stop_type FROM places WHERE id = ?`. */
+ async getStopType(id: number): Promise<{ stop_type: string | null } | undefined> {
+ return await this.qb('p')
+ .select(['p.stop_type'])
+ .where({ id })
+ .execute<{ stop_type: string | null } | undefined>('get', false);
+ }
+
+ /** AC10 (`AccommodationsService.stampLodging`) — `UPDATE places SET stop_type = 'hotel' WHERE id = ?`. Does NOT stamp `places.updated_at` (matches the legacy statement, R7 class — flagged, not fixed). */
+ async stampHotel(id: number): Promise<void> {
+ await this.nativeUpdate({ id }, { stop_type: 'hotel' });
+ }
+
+ /** AC31 (`AccommodationsService.createAccommodation`) — `SELECT name FROM places WHERE id = ?`, the auto-created partner booking's title source. */
+ async getName(id: number): Promise<{ name: string } | undefined> {
+ return await this.qb('p')
+ .select(['p.name'])
+ .where({ id })
+ .execute<{ name: string } | undefined>('get', false);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3e Task 1 (`FilesService.findForeignLinkTarget`, R12) — additive,
+ // append-only per that task's own file-ownership rule.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * FL2 (`FilesService.findForeignLinkTarget`'s place branch) — `SELECT 1
+ * FROM places WHERE id = ? AND trip_id = ?`, re-expressed as "what trip
+ * does this row belong to" (R12, the same shape as
+ * `ReservationsRepository.findTripId`'s docstring).
+ */
+ async findTripId(id: number): Promise<number | undefined> {
+ const platform = this.getEntityManager().getPlatform();
+ const row = await this.qb('p')
+ .select([columnRef(platform, 'p.trip_id').as('trip_id')])
+ .where({ id })
+ .execute<{ trip_id: number } | undefined>('get', false);
+ return row?.trip_id;
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3e Task 2 (budget) — additive, append-only per that task's own
+ // file-ownership rule.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * BG20 (`BudgetService.rebaseTripCurrency`'s `pinPlaces`) — `UPDATE places
+ * SET currency = ?, updated_at = CURRENT_TIMESTAMP WHERE trip_id = ? AND
+ * price IS NOT NULL AND (currency IS NULL OR currency = '')`. Only priced
+ * places are denominated; `updated_at` doubles as the optimistic-
+ * concurrency token (#1135).
+ */
+ async pinCurrencyForTrip(trip_id: number | string, prev_currency: string): Promise<void> {
+ const platform = this.getEntityManager().getPlatform();
+ await this.nativeUpdate(
+ { trip: trip_id as number, price: { $ne: null }, $or: [{ currency: null }, { currency: '' }] },
+ { currency: prev_currency, updated_at: currentTimestamp(platform) },
+ );
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3f Task 1 (`AtlasService`) — additive, append-only per that task's
+ // own file-ownership rule.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * AT2 (`AtlasService#getPlacesForTrips`) — `SELECT * FROM places WHERE
+ * trip_id IN (...)`. Dynamic `IN`, empty-array short-circuit (the
+ * `listAllForTrip`/single-id precedent above, widened to a batch of trip
+ * ids — every atlas read that resolves a user's trips first passes the
+ * whole id list through here in one call rather than one query per trip).
+ */
+ async listForTripIds(trip_ids: number[]): Promise<PlaceRow[]> {
+ if (trip_ids.length === 0) return [];
+ return await this.qb('p')
+ .select(['p.*'])
+ .where({ trip: { $in: trip_ids } })
+ .execute<PlaceRow[]>('all', false);
+ }
+
+ /**
+ * AT41 (`AtlasService#getTravelStats`) — `SELECT DISTINCT p.address,
+ * p.lat, p.lng, pr.region_name FROM places p JOIN trips t ON p.trip_id =
+ * t.id LEFT JOIN trip_members tm ON t.id = tm.trip_id LEFT JOIN
+ * place_regions pr ON pr.place_id = p.id WHERE t.user_id = ? OR tm.user_id
+ * = ?`. The resolved region rides along so `cityFromAddress` can tell the
+ * city apart from the region sitting right above it in the same address
+ * (#1115) — unchanged from the legacy projection.
+ */
+ async listAddressesForUser(user_id: number): Promise<{ address: string | null; lat: number | null; lng: number | null; region_name: string | null }[]> {
+ return await this.kysely<PlacesAddressesForUserKyselyDB>()
+ .selectFrom('places as p')
+ .innerJoin('trips as t', 't.id', 'p.trip_id')
+ .leftJoin('trip_members as tm', 'tm.trip_id', 't.id')
+ .leftJoin('place_regions as pr', 'pr.place_id', 'p.id')
+ .select(['p.address', 'p.lat', 'p.lng', 'pr.region_name'])
+ .distinct()
+ .where((eb) => eb.or([eb('t.user_id', '=', user_id), eb('tm.user_id', '=', user_id)]))
+ .execute();
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3h Task 3 (`DawarichSuggestionsService`) — additive.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * DWS7 (`dawarich-suggestions.service.ts::acceptAsPlace`) — `UPDATE places
+ * SET source = 'dawarich' WHERE id = ?`. No `updated_at` stamp — the
+ * legacy statement never wrote one for this column (same "no stamp"
+ * shape {@link setRouteColor} above already documents for a different
+ * column). Cross-domain write from the Dawarich integration (3h) into
+ * this 3c-owned table.
+ */
+ async setSource(id: number, source: string): Promise<void> {
+ await this.nativeUpdate({ id }, { source });
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3h Task 2 (`CollectionsService`) — additive, cross-domain. Flagged in
+ // the task's own report per its brief: these touch `places`, a 3c-owned
+ // table, from the collections cluster's own copy/import surface.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * CL45 (`importablePlaces`) — the trip's places as offered to the
+ * collection import dialog, one row per place with two correlated scalar
+ * subqueries resolving the EARLIEST day it is assigned to (a place can
+ * sit on several days): `SELECT p.id AS place_id, p.name, p.address,
+ * p.lat, p.lng, p.category_id, p.image_url, p.google_place_id,
+ * p.google_ftid, p.osm_id, (SELECT MIN(d.day_number) FROM day_assignments
+ * da JOIN days d ON d.id=da.day_id WHERE da.place_id=p.id AND
+ * d.trip_id=p.trip_id) AS day_number, (SELECT d.date FROM day_assignments
+ * da JOIN days d ON d.id=da.day_id WHERE da.place_id=p.id AND
+ * d.trip_id=p.trip_id ORDER BY d.day_number ASC LIMIT 1) AS date FROM
+ * places p WHERE p.trip_id=? ORDER BY p.name COLLATE NOCASE`. Kysely — a
+ * correlated scalar subquery has no MikroORM QueryBuilder expression
+ * (`JourneysRepository.listForUser`'s own `eb.selectFrom(...).whereRef
+ * (...).as(...)` precedent, the closest analog: five correlated
+ * subqueries over a `LEFT JOIN`). `ORDER BY ... COLLATE NOCASE` is
+ * Kysely's own native `OrderByItemBuilder.collate('nocase')` — a portable
+ * Kysely API, not a raw SQLite fragment, so it needs no
+ * `sql-functions.ts` dialect wrapper (rule 5 covers dialect FUNCTIONS,
+ * not Kysely's own builder surface).
+ */
+ async listImportable(tripId: number): Promise<ImportablePlaceRow[]> {
+ return await this.kysely<ImportablePlacesKyselyDB>()
+ .selectFrom('places as p')
+ .select((eb) => [
+ 'p.id as place_id', 'p.name', 'p.address', 'p.lat', 'p.lng', 'p.category_id', 'p.image_url',
+ 'p.google_place_id', 'p.google_ftid', 'p.osm_id',
+ eb
+ .selectFrom('day_assignments as da')
+ .innerJoin('days as d', 'd.id', 'da.day_id')
+ .select((eb2) => eb2.fn.min<number | null>('d.day_number').as('m'))
+ .whereRef('da.place_id', '=', 'p.id')
+ .whereRef('d.trip_id', '=', 'p.trip_id')
+ .as('day_number'),
+ eb
+ .selectFrom('day_assignments as da2')
+ .innerJoin('days as d2', 'd2.id', 'da2.day_id')
+ .select('d2.date')
+ .whereRef('da2.place_id', '=', 'p.id')
+ .whereRef('d2.trip_id', '=', 'p.trip_id')
+ .orderBy('d2.day_number', 'asc')
+ .limit(1)
+ .as('date'),
+ ])
+ .where('p.trip_id', '=', tripId)
+ .orderBy('p.name', (ob) => ob.collate('nocase').asc())
+ .execute();
+ }
+
+ /**
+ * CL57 (`setStatusFromTrip`) — `SELECT id, name, lat, lng,
+ * google_place_id, google_ftid, osm_id FROM places WHERE trip_id=? AND id
+ * IN (...)`. `$in` for the dynamic list (rule 17b), the same
+ * `scopedIds`-shaped raw `trip_id` condition above.
+ */
+ async listByTripAndIds(trip_id: number, ids: number[]): Promise<PlaceMatchRow[]> {
+ if (ids.length === 0) return [];
+ return await this.qb('p')
+ .select(['p.id', 'p.name', 'p.lat', 'p.lng', 'p.google_place_id', 'p.google_ftid', 'p.osm_id'])
+ .where({ 'p.trip_id': trip_id })
+ .andWhere({ id: { $in: ids } })
+ .execute<PlaceMatchRow[]>('all', false);
+ }
+
+ /**
+ * CL63 (`copyToTrip`'s trip dedup set) — `SELECT name, lat, lng,
+ * google_place_id, google_ftid, osm_id FROM places WHERE trip_id=?`.
+ */
+ async dedupCandidatesForTrip(trip_id: number): Promise<Omit<PlaceMatchRow, 'id'>[]> {
+ return await this.qb('p')
+ .select(['p.name', 'p.lat', 'p.lng', 'p.google_place_id', 'p.google_ftid', 'p.osm_id'])
+ .where({ trip: trip_id })
+ .execute<Omit<PlaceMatchRow, 'id'>[]>('all', false);
+ }
+
+ /**
+ * CL64 (`copyToTrip`, PREPARED/looped, TX) — `INSERT INTO places (trip_id,
+ * name, description, lat, lng, address, category_id, price, currency,
+ * notes, image_url, google_place_id, google_ftid, website, phone,
+ * osm_id) VALUES (...)` — a genuinely NARROWER 16-column insert than
+ * {@link insertPlace}'s full 27-column shape (no `place_time`/`end_time`/
+ * `duration_minutes`/`transport_mode`/`route_geometry`/`route_color`/
+ * `stop_type`/`fill_percent`/`amap_poi_id`): the legacy statement leaves
+ * those to the table's own `DEFAULT` clauses
+ * (`Migration20200101000000_baseline_schema.ts`: `duration_minutes
+ * INTEGER DEFAULT 60`, `transport_mode TEXT DEFAULT 'walking'`,
+ * `reservation_status TEXT DEFAULT 'none'`), unlike `insertPlace`'s own
+ * caller (`PlacesService.create`), which always resolves and writes every
+ * one of those columns itself. Kysely (a narrower insert-only interface,
+ * `CollectionsRepository`'s own `CollectionPlacesWriteKyselyDB`
+ * precedent for the identical "narrower than the full entity" shape) so
+ * this genuinely different column set never widens `insertPlace`'s own
+ * required-field list. Returns the generated id.
+ */
+ async insertFromCollectionPlace(row: {
+ trip_id: number;
+ name: string;
+ description: string | null;
+ lat: number | null;
+ lng: number | null;
+ address: string | null;
+ category_id: number | null;
+ price: number | null;
+ currency: string | null;
+ notes: string | null;
+ image_url: string | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ website: string | null;
+ phone: string | null;
+ osm_id: string | null;
+ }): Promise<number> {
+ const result = await this.kysely<PlacesNarrowInsertKyselyDB>().insertInto('places').values(row).executeTakeFirstOrThrow();
+ return Number(result.insertId);
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 3h Task 4 (`maps.service.ts`'s photo-fetch method, MAP9) — additive,
+ // per this task's own file-ownership rule ("additive methods on
+ // Reservations/ReservationEndpoints/Days/Places/Users repositories").
+ // ---------------------------------------------------------------------------
+
+ /**
+ * MAP9 — `UPDATE places SET image_url = ?, updated_at = CURRENT_TIMESTAMP
+ * WHERE google_place_id = ? AND (image_url IS NULL OR image_url = '')`.
+ * **SECURITY/PARITY**: the `$or` guard is what stops this from ever
+ * clobbering a place's already-set/custom image — preserved exactly.
+ * Unscoped by `trip_id`/`id` (matching the legacy statement): a
+ * `google_place_id` can appear on more than one place row across
+ * different trips, and every empty-image row sharing it is filled in one
+ * statement.
+ */
+ async setImageUrlIfUnset(google_place_id: string, image_url: string): Promise<number> {
+ const platform = this.getEntityManager().getPlatform();
+ return this.nativeUpdate(
+ { google_place_id, $or: [{ image_url: null }, { image_url: '' }] },
+ { image_url, updated_at: currentTimestamp(platform) },
+ );
+ }
+
+ // ---------------------------------------------------------------------------
+ // Plan 4 Task 1 (`public-api.service.ts::placesByDay`) — additive.
+ // ---------------------------------------------------------------------------
+
+ /**
+ * `SELECT da.day_id, p.name, p.address, p.lat, p.lng, p.place_time,
+ * p.end_time, p.duration_minutes, p.notes, p.transport_mode, c.name AS
+ * category FROM day_assignments da JOIN places p ON p.id = da.place_id
+ * LEFT JOIN categories c ON c.id = p.category_id WHERE p.trip_id = ? AND
+ * da.accommodation_id IS NULL ORDER BY da.day_id ASC, da.order_index ASC`.
+ * Kysely — the SAME cross-table-read escape hatch `ReservationsRepository
+ * .listUnplannedPlacesForPublicApi`'s precedent (3d Task 4) uses for this
+ * exact `public-api.service.ts` surface; landed on `PlacesRepository`
+ * rather than grouped there because the projection is place-shaped, per
+ * this domain plan's own ruling.
+ */
+ async listAssignedForPublicApi(trip_id: number): Promise<PublicApiAssignedPlaceRow[]> {
+ const rows = await this.kysely<PublicApiAssignedPlacesKyselyDB>()
+ .selectFrom('day_assignments as da')
+ .innerJoin('places as p', 'p.id', 'da.place_id')
+ .leftJoin('categories as c', 'c.id', 'p.category_id')
+ .select([
+ 'da.day_id',
+ 'p.name', 'p.address', 'p.lat', 'p.lng', 'p.place_time', 'p.end_time',
+ 'p.duration_minutes', 'p.notes', 'p.transport_mode', 'c.name as category',
+ ])
+ .where('p.trip_id', '=', trip_id)
+ .where('da.accommodation_id', 'is', null)
+ .orderBy('da.day_id', 'asc')
+ .orderBy('da.order_index', 'asc')
+ .execute();
+ return rows as PublicApiAssignedPlaceRow[];
+ }
++
++ /**
++ * TO10 (`ToursService.createTour`) — `INSERT INTO places (trip_id, name,
++ * lat, lng, transport_mode, route_geometry) VALUES (?, ?, ?, ?, 'walking',
++ * ?)`. The place a drawn tour lives on starts at the route's first point;
++ * every other column keeps its default. Returns the generated id.
++ */
++ async insertTourPlace(input: { trip_id: number; name: string; lat: number; lng: number; route_geometry: string }): Promise<number> {
++ return await this.insert({
++ trip: input.trip_id,
++ name: input.name,
++ lat: input.lat,
++ lng: input.lng,
++ transport_mode: 'walking',
++ route_geometry: input.route_geometry,
++ });
++ }
++
++ /**
++ * TO11 (`ToursService.updateTour`) — `UPDATE places SET name = ?, lat = ?,
++ * lng = ?, transport_mode = 'walking', route_geometry = ?, updated_at =
++ * CURRENT_TIMESTAMP WHERE id = ? AND trip_id = ?`. Returns whether a place
++ * of that trip was updated, so a tour deleted or moved between the check
++ * and the write answers 404 instead of writing nothing.
++ */
++ async updateTourRoute(
++ id: number,
++ trip_id: number,
++ input: { name: string; lat: number; lng: number; route_geometry: string },
++ ): Promise<boolean> {
++ const platform = this.getEntityManager().getPlatform();
++ const updated = await this.nativeUpdate(
++ { id, trip: trip_id },
++ {
++ name: input.name,
++ lat: input.lat,
++ lng: input.lng,
++ transport_mode: 'walking',
++ route_geometry: input.route_geometry,
++ updated_at: currentTimestamp(platform),
++ },
++ );
++ return updated > 0;
++ }
+ }
+
+ /** The `places` columns {@link PlacesRepository.listAssignedForPublicApi} selects, typed off {@link PlaceRow}. */
+ type PublicApiPlaceColumns = Pick<
+ PlaceRow,
+ 'name' | 'address' | 'lat' | 'lng' | 'place_time' | 'end_time' | 'duration_minutes' | 'notes' | 'transport_mode'
+ >;
+
+ /** {@link PlacesRepository.listAssignedForPublicApi}'s projection. */
+ export interface PublicApiAssignedPlaceRow extends PublicApiPlaceColumns {
+ day_id: number;
+ category: string | null;
+ }
+
+ /** {@link PlacesRepository.listAssignedForPublicApi}'s narrow `day_assignments`/`places`/`categories` shape. */
+ interface PublicApiAssignedPlacesKyselyDB {
+ day_assignments: { day_id: number; place_id: number; accommodation_id: number | null; order_index: number | null };
+ places: PublicApiPlaceColumns & Pick<PlaceRow, 'id' | 'trip_id' | 'category_id'>;
+ categories: { id: number; name: string };
+ }
+
+ /** {@link PlacesRepository.listImportable}'s row shape (CL45). */
+ export interface ImportablePlaceRow {
+ place_id: number;
+ name: string;
+ address: string | null;
+ lat: number | null;
+ lng: number | null;
+ category_id: number | null;
+ image_url: string | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ osm_id: string | null;
+ day_number: number | null;
+ date: string | null;
+ }
+
+ /** {@link PlacesRepository.listByTripAndIds}/{@link PlacesRepository.dedupCandidatesForTrip}'s shared narrow projection (CL57/CL63). */
+ export interface PlaceMatchRow {
+ id: number;
+ name: string;
+ lat: number | null;
+ lng: number | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ osm_id: string | null;
+ }
+
+ /** {@link PlacesRepository.listImportable}'s narrow `places`/`day_assignments`/`days` shape (CL45). */
+ interface ImportablePlacesKyselyDB {
+ places: { id: number; trip_id: number; name: string; address: string | null; lat: number | null; lng: number | null; category_id: number | null; image_url: string | null; google_place_id: string | null; google_ftid: string | null; osm_id: string | null };
+ day_assignments: { place_id: number; day_id: number };
+ days: { id: number; trip_id: number; day_number: number; date: string };
+ }
+
+ /** {@link PlacesRepository.insertFromCollectionPlace}'s narrow insert-only shape (CL64). */
+ interface PlacesNarrowInsertKyselyDB {
+ places: {
+ trip_id: number;
+ name: string;
+ description: string | null;
+ lat: number | null;
+ lng: number | null;
+ address: string | null;
+ category_id: number | null;
+ price: number | null;
+ currency: string | null;
+ notes: string | null;
+ image_url: string | null;
+ google_place_id: string | null;
+ google_ftid: string | null;
+ website: string | null;
+ phone: string | null;
+ osm_id: string | null;
+ };
+ }
+
+ /** {@link PlacesRepository.listAddressesForUser}'s narrow `places`/`trips`/`trip_members`/`place_regions` shape. */
+ interface PlacesAddressesForUserKyselyDB {
+ places: { id: number; trip_id: number; address: string | null; lat: number | null; lng: number | null };
+ trips: { id: number; user_id: number };
+ trip_members: { trip_id: number; user_id: number };
+ place_regions: { place_id: number; region_name: string | null };
+ }
diff --cc server/src/db/repositories/TourTypes.repository.ts
index 000000000,000000000..49c5c9314
new file mode 100644
--- /dev/null
+++ b/server/src/db/repositories/TourTypes.repository.ts
@@@ -1,0 -1,0 +1,9 @@@
++import type { TourTypes } from '../entities/TourTypes.entity';
++import { TrekRepository } from './_shared/trek-repository';
++
++/**
++ * `tour_types` — the controlled vocabulary `tours.tour_type` points at. Only
++ * `hike` exists, written by the migration that creates the table; nothing
++ * reads the catalogue yet, so this repository has no methods of its own.
++ */
++export class TourTypesRepository extends TrekRepository<TourTypes> {}
diff --cc server/src/db/repositories/TourWaypoints.repository.ts
index 000000000,000000000..b5112ab44
new file mode 100644
--- /dev/null
+++ b/server/src/db/repositories/TourWaypoints.repository.ts
@@@ -1,0 -1,0 +1,70 @@@
++import type { TourWaypoints } from '../entities/TourWaypoints.entity';
++import { TrekRepository } from './_shared/trek-repository';
++
++/** One saved routing control point of a tour, in route order. */
++export interface TourWaypointRow {
++ lat: number;
++ lng: number;
++ role: 'start' | 'via' | 'end';
++ sequence: number;
++}
++
++/** {@link TourWaypointRow} plus the tour it belongs to, as the trip copy reads it. */
++export interface TourWaypointWithPlaceRow extends TourWaypointRow {
++ place_id: number;
++}
++
++interface TourWaypointsKyselyDB {
++ tour_waypoints: { id: number; place_id: number; lat: number; lng: number; role: TourWaypointRow['role']; sequence: number };
++ places: { id: number; trip_id: number };
++}
++
++/**
++ * `tour_waypoints` — the start, via and end points the route editor saved
++ * for a tour, so reopening it restores the controls rather than only the
++ * derived line. Rows hang off `tours(place_id)` and go with the tour.
++ */
++export class TourWaypointsRepository extends TrekRepository<TourWaypoints> {
++ private db() {
++ return this.kysely<TourWaypointsKyselyDB>();
++ }
++
++ /** TW1 — `SELECT lat, lng, role, sequence FROM tour_waypoints WHERE place_id = ? ORDER BY sequence`. */
++ async listForPlace(place_id: number): Promise<TourWaypointRow[]> {
++ return await this.db()
++ .selectFrom('tour_waypoints')
++ .select(['lat', 'lng', 'role', 'sequence'])
++ .where('place_id', '=', place_id)
++ .orderBy('sequence', 'asc')
++ .execute();
++ }
++
++ /** TW2 — every waypoint of a trip's tours, for the trip copy to remap by place. */
++ async listForTrip(trip_id: number): Promise<TourWaypointWithPlaceRow[]> {
++ return await this.db()
++ .selectFrom('tour_waypoints as tw')
++ .innerJoin('places as p', 'p.id', 'tw.place_id')
++ .select(['tw.place_id', 'tw.lat', 'tw.lng', 'tw.role', 'tw.sequence'])
++ .where('p.trip_id', '=', trip_id)
++ .orderBy('tw.place_id', 'asc')
++ .orderBy('tw.sequence', 'asc')
++ .execute();
++ }
++
++ /**
++ * TW3 — `INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence)
++ * VALUES (...)` for each point. The caller owns the transaction: a create
++ * writes the tour first, an edit clears the old points first.
++ */
++ async insertForPlace(place_id: number, waypoints: readonly TourWaypointRow[]): Promise<void> {
++ if (waypoints.length === 0) return;
++ await this.insertMany(
++ waypoints.map((w) => ({ place: place_id, lat: w.lat, lng: w.lng, role: w.role, sequence: w.sequence })),
++ );
++ }
++
++ /** TW4 — `DELETE FROM tour_waypoints WHERE place_id = ?`. */
++ async deleteForPlace(place_id: number): Promise<void> {
++ await this.nativeDelete({ place: place_id });
++ }
++}
diff --cc server/src/db/repositories/Tours.repository.ts
index 000000000,000000000..7e3b34acf
new file mode 100644
--- /dev/null
+++ b/server/src/db/repositories/Tours.repository.ts
@@@ -1,0 -1,0 +1,221 @@@
++import type { AssertRowKeys } from './_shared/rows';
++import type { Tours } from '../entities/Tours.entity';
++import { TrekRepository } from './_shared/trek-repository';
++
++/**
++ * A tour as the Tours list and detail read it: the `tours` facet joined with
++ * its owning place's name, plus two read-model flags (`planned`: the place
++ * sits on at least one day; `has_waypoints`: the route editor saved control
++ * points for it). SQLite hands both flags back as 0/1.
++ */
++export interface TourListRow {
++ place_id: number;
++ name: string;
++ tour_type: string;
++ distance: number | null;
++ elevation_gain: number | null;
++ elevation_loss: number | null;
++ duration: number | null;
++ difficulty: string | null;
++ wanderer_ref: string | null;
++ match_confidence: number | null;
++ tour_group_id: number | null;
++ max_hiking_difficulty: number;
++ planned: number;
++ has_waypoints: number;
++}
++
++/** Every `tours` column, as the trip copy reads and re-inserts it. */
++export interface TourRow {
++ place_id: number;
++ tour_type: string;
++ distance: number | null;
++ elevation_gain: number | null;
++ elevation_loss: number | null;
++ duration: number | null;
++ difficulty: string | null;
++ wanderer_ref: string | null;
++ match_confidence: number | null;
++ tour_group_id: number | null;
++ created_at: string | null;
++ max_hiking_difficulty: number;
++}
++const _tourRowKeys: AssertRowKeys<TourRow, Tours> = true;
++
++/** What a create or a GPX import writes; the unset metadata columns stay NULL. */
++export interface TourInsert {
++ place_id: number;
++ tour_type: string;
++ distance: number | null;
++ elevation_gain: number | null;
++ elevation_loss: number | null;
++ duration: number | null;
++ match_confidence: number | null;
++ max_hiking_difficulty: number;
++}
++
++/** What a route edit replaces on an existing tour. */
++export type TourUpdate = Omit<TourInsert, 'place_id'>;
++
++interface ToursKyselyDB {
++ tours: TourRow;
++ places: { id: number; trip_id: number; name: string };
++ day_assignments: { id: number; day_id: number; place_id: number };
++ tour_waypoints: { id: number; place_id: number };
++}
++
++/**
++ * `tours` — the facet that makes a place a tour (#2586). Keyed on the owning
++ * place, so it carries no trip of its own: every trip-scoped statement here
++ * joins `places` for the predicate. Deleting the place cascades the row and
++ * its `tour_waypoints`.
++ *
++ * Kysely throughout: the list projection needs two correlated `EXISTS`
++ * subqueries, and the trip-scoped update and the day check join tables the
++ * entity has no relation path to.
++ */
++export class ToursRepository extends TrekRepository<Tours> {
++ private db() {
++ return this.kysely<ToursKyselyDB>();
++ }
++
++ /** The shared SELECT of {@link listForTrip} and {@link findInTrip}. */
++ private listQuery() {
++ return this.db()
++ .selectFrom('tours as t')
++ .innerJoin('places as p', 'p.id', 't.place_id')
++ .select((eb) => [
++ 'p.id as place_id',
++ 'p.name as name',
++ 't.tour_type as tour_type',
++ 't.distance as distance',
++ 't.elevation_gain as elevation_gain',
++ 't.elevation_loss as elevation_loss',
++ 't.duration as duration',
++ 't.difficulty as difficulty',
++ 't.wanderer_ref as wanderer_ref',
++ 't.match_confidence as match_confidence',
++ 't.tour_group_id as tour_group_id',
++ 't.max_hiking_difficulty as max_hiking_difficulty',
++ eb.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.place_id', '=', 'p.id')).as('planned'),
++ eb.exists(eb.selectFrom('tour_waypoints as tw').select('tw.id').whereRef('tw.place_id', '=', 'p.id')).as('has_waypoints'),
++ ]);
++ }
++
++ /**
++ * TO1 — `SELECT p.id AS place_id, p.name, t.*, EXISTS(day_assignments) AS
++ * planned, EXISTS(tour_waypoints) AS has_waypoints FROM tours t JOIN places
++ * p ON p.id = t.place_id WHERE p.trip_id = ? ORDER BY t.created_at DESC`,
++ * newest first. The place id breaks ties inside one CURRENT_TIMESTAMP second.
++ */
++ async listForTrip(trip_id: number): Promise<TourListRow[]> {
++ const rows = await this.listQuery()
++ .where('p.trip_id', '=', trip_id)
++ .orderBy('t.created_at', 'desc')
++ .orderBy('t.place_id', 'desc')
++ .execute();
++ return rows.map(toListRow);
++ }
++
++ /** TO2 — {@link listForTrip}'s projection for one place, `undefined` unless it is a tour of that trip. */
++ async findInTrip(trip_id: number, place_id: number): Promise<TourListRow | undefined> {
++ const row = await this.listQuery().where('p.trip_id', '=', trip_id).where('p.id', '=', place_id).executeTakeFirst();
++ return row ? toListRow(row) : undefined;
++ }
++
++ /** TO3 — `SELECT 1 FROM tours WHERE place_id = ?`: whether the place is a tour. */
++ async existsForPlace(place_id: number): Promise<boolean> {
++ const row = await this.db().selectFrom('tours').select('place_id').where('place_id', '=', place_id).executeTakeFirst();
++ return !!row;
++ }
++
++ /** TO4 — `SELECT place_id FROM tours WHERE place_id IN (...)`: which of these places are tours. */
++ async listTourPlaceIds(place_ids: number[]): Promise<number[]> {
++ if (place_ids.length === 0) return [];
++ const rows = await this.db().selectFrom('tours').select('place_id').where('place_id', 'in', place_ids).execute();
++ return rows.map((r) => r.place_id);
++ }
++
++ /**
++ * TO5 — `SELECT 1 FROM day_assignments da JOIN tours t ON t.place_id =
++ * da.place_id WHERE da.day_id = ? AND da.place_id = ? [AND da.id != ?]`.
++ *
++ * A tour fills its day, so one day holds it at most once. Create and move
++ * both ask this inside the transaction that writes the assignment; move
++ * passes the assignment being moved so it does not collide with itself.
++ * False for an ordinary place, which may sit on a day any number of times.
++ */
++ async isOnDay(day_id: number, place_id: number, except_assignment_id?: number): Promise<boolean> {
++ let query = this.db()
++ .selectFrom('day_assignments as da')
++ .innerJoin('tours as t', 't.place_id', 'da.place_id')
++ .select('da.id')
++ .where('da.day_id', '=', day_id)
++ .where('da.place_id', '=', place_id);
++ if (except_assignment_id !== undefined) query = query.where('da.id', '!=', except_assignment_id);
++ return !!(await query.executeTakeFirst());
++ }
++
++ /** TO6 — every `tours` row of a trip's places, for the trip copy to remap. */
++ async listRowsForTrip(trip_id: number): Promise<TourRow[]> {
++ return await this.db()
++ .selectFrom('tours as t')
++ .innerJoin('places as p', 'p.id', 't.place_id')
++ .selectAll('t')
++ .where('p.trip_id', '=', trip_id)
++ .orderBy('t.place_id', 'asc')
++ .execute();
++ }
++
++ /** TO7 — `INSERT INTO tours (place_id, tour_type, distance, ...) VALUES (...)`. */
++ async insertTour(input: TourInsert): Promise<void> {
++ await this.insert({
++ place: input.place_id,
++ tourTypeRef: input.tour_type,
++ distance: input.distance,
++ elevation_gain: input.elevation_gain,
++ elevation_loss: input.elevation_loss,
++ duration: input.duration,
++ match_confidence: input.match_confidence,
++ max_hiking_difficulty: input.max_hiking_difficulty,
++ });
++ }
++
++ /**
++ * TO8 — a copied tour keeps every column, `created_at` included, so the
++ * copy lists its tours in the source's order.
++ */
++ async insertCopy(place_id: number, row: Omit<TourRow, 'place_id'>): Promise<void> {
++ await this.db()
++ .insertInto('tours')
++ .values({ ...row, place_id })
++ .execute();
++ }
++
++ /**
++ * TO9 — `UPDATE tours SET tour_type = ?, distance = ?, ... WHERE place_id =
++ * ? AND place_id IN (SELECT id FROM places WHERE trip_id = ?)`. Returns
++ * whether a row of that trip was updated.
++ */
++ async updateInTrip(trip_id: number, place_id: number, input: TourUpdate): Promise<boolean> {
++ const result = await this.db()
++ .updateTable('tours')
++ .set({
++ tour_type: input.tour_type,
++ distance: input.distance,
++ elevation_gain: input.elevation_gain,
++ elevation_loss: input.elevation_loss,
++ duration: input.duration,
++ match_confidence: input.match_confidence,
++ max_hiking_difficulty: input.max_hiking_difficulty,
++ })
++ .where('place_id', '=', place_id)
++ .where('place_id', 'in', (eb) => eb.selectFrom('places').select('id').where('trip_id', '=', trip_id))
++ .executeTakeFirst();
++ return Number(result.numUpdatedRows ?? 0) > 0;
++ }
++}
++
++function toListRow<R extends Omit<TourListRow, 'planned' | 'has_waypoints'> & { planned: unknown; has_waypoints: unknown }>(r: R): TourListRow {
++ return { ...r, planned: Number(r.planned), has_waypoints: Number(r.has_waypoints) };
++}
diff --cc server/src/db/seeders/AddonSeeder.ts
index 000000000,cb7488365..5f35c0673
mode 000000,100644..100644
--- a/server/src/db/seeders/AddonSeeder.ts
+++ b/server/src/db/seeders/AddonSeeder.ts
@@@ -1,0 -1,163 +1,172 @@@
+ import type { EntityManager } from '@mikro-orm/core';
+ import { Seeder } from '@mikro-orm/seeder';
+
+ interface AddonRow {
+ id: string;
+ name: string;
+ description: string;
+ type: string;
+ icon: string;
+ enabled: 0 | 1;
+ sort_order: number;
+ }
+
+ const DEFAULT_ADDONS: AddonRow[] = [
+ {
+ id: 'packing',
+ name: 'Lists',
+ description: 'Packing lists and to-do tasks for your trips',
+ type: 'trip',
+ icon: 'ListChecks',
+ enabled: 1,
+ sort_order: 0,
+ },
+ {
+ id: 'budget',
+ name: 'Costs',
+ description: 'Track and split trip expenses',
+ type: 'trip',
+ icon: 'Wallet',
+ enabled: 1,
+ sort_order: 1,
+ },
+ {
+ id: 'documents',
+ name: 'Documents',
+ description: 'Store and manage travel documents',
+ type: 'trip',
+ icon: 'FileText',
+ enabled: 1,
+ sort_order: 2,
+ },
+ {
+ id: 'vacay',
+ name: 'Vacay',
+ description: 'Personal vacation day planner with calendar view',
+ type: 'global',
+ icon: 'CalendarDays',
+ enabled: 1,
+ sort_order: 10,
+ },
+ {
+ id: 'atlas',
+ name: 'Atlas',
+ description: 'World map of your visited countries with travel stats',
+ type: 'global',
+ icon: 'Globe',
+ enabled: 1,
+ sort_order: 11,
+ },
+ {
+ id: 'mcp',
+ name: 'MCP',
+ description: 'Model Context Protocol for AI assistant integration',
+ type: 'integration',
+ icon: 'Terminal',
+ enabled: 0,
+ sort_order: 12,
+ },
+ {
+ id: 'naver_list_import',
+ name: 'Naver List Import',
+ description: 'Import places from a shared Naver Maps list',
+ type: 'integration',
+ icon: 'Link2',
+ enabled: 1,
+ sort_order: 13,
+ },
+ {
+ id: 'collab',
+ name: 'Collab',
+ description: 'Notes, polls, and live chat for trip collaboration',
+ type: 'trip',
+ icon: 'Users',
+ enabled: 1,
+ sort_order: 6,
+ },
+ {
+ id: 'roadtrip',
+ name: 'Road trip',
+ description: 'Drives with stops along the route, driving times, and arrival times that update themselves',
+ type: 'trip',
+ icon: 'Route',
+ enabled: 0,
+ sort_order: 7,
+ },
++ {
++ id: 'tours',
++ name: 'Tours',
++ description: 'Hikes and other single-day tours that follow a route',
++ type: 'trip',
++ icon: 'Mountain',
++ enabled: 0,
++ sort_order: 8,
++ },
+ {
+ id: 'journey',
+ name: 'Journey',
+ description: 'Trip tracking & travel journal — check-ins, photos, daily stories',
+ type: 'global',
+ icon: 'Compass',
+ enabled: 0,
+ sort_order: 35,
+ },
+ {
+ id: 'airtrail',
+ name: 'AirTrail',
+ description: 'Sync flights from your AirTrail instance',
+ type: 'integration',
+ icon: 'Plane',
+ enabled: 0,
+ sort_order: 14,
+ },
+ {
+ id: 'dawarich',
+ name: 'Dawarich',
+ description:
+ 'Read visits and recorded routes from your Dawarich instance — suggested journal entries, places and countries you confirm yourself',
+ type: 'integration',
+ icon: 'Dawarich',
+ enabled: 0,
+ sort_order: 17,
+ },
+ {
+ id: 'llm_parsing',
+ name: 'AI Parsing',
+ description: 'LLM fallback for booking imports kitinerary cannot read',
+ type: 'integration',
+ icon: 'Sparkles',
+ enabled: 0,
+ sort_order: 15,
+ },
+ {
+ id: 'collections',
+ name: 'Collections',
+ description:
+ 'Personal place library — save places across trips into named lists, copy into any trip, share with others',
+ type: 'global',
+ icon: 'Bookmark',
+ enabled: 0,
+ sort_order: 16,
+ },
+ ];
+
+ /**
+ * Seeds the addon shelf.
+ *
+ * `INSERT OR IGNORE` per row, not a table-level emptiness check: an operator who
+ * has toggled an addon keeps their choice, and a release that adds a new addon
+ * still gets its tile on an existing install.
+ */
+ export class AddonSeeder extends Seeder {
+ async run(em: EntityManager): Promise<void> {
+ const connection = em.getConnection();
+ for (const addon of DEFAULT_ADDONS) {
+ await connection.execute(
+ 'INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ [addon.id, addon.name, addon.description, addon.type, addon.icon, addon.enabled, addon.sort_order],
+ );
+ }
+ console.log('Default addons seeded');
+ }
+ }
diff --cc server/src/nest/app.module.ts
index 50c7527e9,e026fde4f..f05cb2640
--- a/server/src/nest/app.module.ts
+++ b/server/src/nest/app.module.ts
@@@ -1,83 -1,89 +1,90 @@@
- import { Module } from '@nestjs/common';
- import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
- import { ZodValidationPipe } from './common/zod-validation.pipe';
+ import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../mcp/nest-mcp-policy';
+ import mikroOrmConfig from '../mikro-orm.config';
+ import { AppSettings } from '../db/entities/AppSettings.entity';
+ import { Users } from '../db/entities/Users.entity';
+ import { WebauthnCredentials } from '../db/entities/WebauthnCredentials.entity';
+ import { IdempotencyKeys } from '../db/entities/IdempotencyKeys.entity';
+ import { McpModule } from '../nest-mcp';
+ import { AccommodationsModule } from './accommodations/accommodations.module';
+ import { AddonsModule } from './addons/addons.module';
+ import { AdminModule } from './admin/admin.module';
+ import { AirportsModule } from './airports/airports.module';
import { AppConfigModule } from './app-config/app-config.module';
- import { DatabaseModule } from './database/database.module';
- import { RealtimeModule } from './realtime/realtime.module';
- import { HealthModule } from './health/health.module';
- import { PlatformModule } from './platform/platform.module';
- import { McpTransportModule } from './mcp-transport/mcp-transport.module';
+ import { AssignmentsModule } from './assignments/assignments.module';
+ import { AtlasModule } from './atlas/atlas.module';
+ import { AuditModule } from './audit/audit.module';
+ import { AuthModule } from './auth/auth.module';
import { GlobalAuthGuard } from './auth/global-auth.guard';
import { MfaPolicyGuard } from './auth/mfa-policy.guard';
+ import { SessionRenewalInterceptor } from './auth/session-renewal.interceptor';
+ import { BackupModule } from './backup/backup.module';
+ import { BookingImportModule } from './booking-import/booking-import.module';
+ import { BudgetModule } from './budget/budget.module';
+ import { CategoriesModule } from './categories/categories.module';
+ import { CollabModule } from './collab/collab.module';
+ import { CollectionsModule } from './collections/collections.module';
+ import { DemoModule } from './common/demo.module';
+ import { IdempotencyCleanupJob } from './common/idempotency-cleanup.job';
+ import { IdempotencyInterceptor } from './common/idempotency.interceptor';
import { ManagedGuard } from './common/managed.guard';
- import { WeatherModule } from './weather/weather.module';
- import { RoadtripModule } from './roadtrip/roadtrip.module';
- import { PublicApiModule } from './public-api/public-api.module';
- import { HelpModule } from './help/help.module';
- import { AirportsModule } from './airports/airports.module';
+ import { TrekExceptionFilter } from './common/trek-exception.filter';
+ import { ZodValidationPipe } from './common/zod-validation.pipe';
import { ConfigModule } from './config/config.module';
- import { SystemNoticesModule } from './system-notices/system-notices.module';
- import { ManagedExtModule } from './managed/managed-ext.module';
- import { MapsModule } from './maps/maps.module';
- import { GoogleQuotaModule } from './google-quota/google-quota.module';
- import { GeoModule } from './geo/geo.module';
- import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
- import { PlaceShadowModule } from './place-shadow/place-shadow.module';
- import { RouteUsageModule } from './route-usage/route-usage.module';
- import { CategoriesModule } from './categories/categories.module';
- import { TagsModule } from './tags/tags.module';
- import { NotificationsModule } from './notifications/notifications.module';
- import { AtlasModule } from './atlas/atlas.module';
- import { SchoolHolidaysModule } from './school-holidays/school-holidays.module';
- import { VacayModule } from './vacay/vacay.module';
- import { PackingModule } from './packing/packing.module';
- import { BudgetModule } from './budget/budget.module';
- import { ReservationsModule } from './reservations/reservations.module';
- import { DaysModule } from './days/days.module';
+ import { OrmModule } from './database/orm.module';
import { DayNotesModule } from './day-notes/day-notes.module';
- import { AccommodationsModule } from './accommodations/accommodations.module';
- import { AssignmentsModule } from './assignments/assignments.module';
- import { PlacesModule } from './places/places.module';
- import { ToursModule } from './tours/tours.module';
- import { TripsModule } from './trips/trips.module';
- import { TodoModule } from './todo/todo.module';
- import { CollabModule } from './collab/collab.module';
+ import { DaysModule } from './days/days.module';
+ import { DocSyncModule } from './doc-sync/doc-sync.module';
+ import { FeedsModule } from './feeds/feeds.module';
import { FilesModule } from './files/files.module';
- import { PhotosModule } from './photos/photos.module';
- import { MemoriesModule } from './memories/memories.module';
+ import { GeoModule } from './geo/geo.module';
+ import { GoogleQuotaModule } from './google-quota/google-quota.module';
+ import { HealthModule } from './health/health.module';
+ import { HelpModule } from './help/help.module';
import { AirtrailModule } from './integrations/airtrail.module';
import { DawarichModule } from './integrations/dawarich.module';
- import { DocSyncModule } from './doc-sync/doc-sync.module';
import { JourneyModule } from './journey/journey.module';
- import { CollectionsModule } from './collections/collections.module';
- import { ShareModule } from './share/share.module';
- import { TripInviteModule } from './trip-invite/trip-invite.module';
- import { TransitModule } from './transit/transit.module';
- import { FeedsModule } from './feeds/feeds.module';
- import { SettingsModule } from './settings/settings.module';
- import { StorageModule } from './storage/storage.module';
- import { BackupModule } from './backup/backup.module';
- import { BookingImportModule } from './booking-import/booking-import.module';
- import { ReservationImportModule } from './reservation-import/reservation-import.module';
- import { ReceiptScanModule } from './receipt-scan/receipt-scan.module';
import { LlmParseModule } from './llm-parse/llm-parse.module';
- import { AuthModule } from './auth/auth.module';
- import { OidcModule } from './oidc/oidc.module';
+ import { ManagedExtModule } from './managed/managed-ext.module';
+ import { MapsModule } from './maps/maps.module';
+ import { McpTransportModule } from './mcp-transport/mcp-transport.module';
+ import { MemoriesModule } from './memories/memories.module';
+ import { NotificationsModule } from './notifications/notifications.module';
import { OauthModule } from './oauth/oauth.module';
- import { AdminModule } from './admin/admin.module';
- import { AddonsModule } from './addons/addons.module';
- import { AuditModule } from './audit/audit.module';
+ import { OidcModule } from './oidc/oidc.module';
+ import { PackingModule } from './packing/packing.module';
import { PermissionsModule } from './permissions/permissions.module';
- import { PluginsModule } from './plugins/plugins.module';
- import { SchedulingModule } from './scheduling/scheduling.module';
- import { McpModule } from '../nest-mcp';
- import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../mcp/nest-mcp-policy';
- import { TrekExceptionFilter } from './common/trek-exception.filter';
+ import { PhotosModule } from './photos/photos.module';
+ import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
+ import { PlaceShadowModule } from './place-shadow/place-shadow.module';
+ import { PlacesModule } from './places/places.module';
+ import { PlatformModule } from './platform/platform.module';
import { SpaFallbackFilter } from './platform/spa-fallback.filter';
- import { IdempotencyInterceptor } from './common/idempotency.interceptor';
- import { SessionRenewalInterceptor } from './auth/session-renewal.interceptor';
- import { IdempotencyCleanupJob } from './common/idempotency-cleanup.job';
+ import { PluginsModule } from './plugins/plugins.module';
+ import { PublicApiModule } from './public-api/public-api.module';
import { RealtimeGatewayModule } from './realtime/realtime-gateway.module';
+ import { RealtimeModule } from './realtime/realtime.module';
+ import { ReceiptScanModule } from './receipt-scan/receipt-scan.module';
+ import { ReservationImportModule } from './reservation-import/reservation-import.module';
+ import { ReservationsModule } from './reservations/reservations.module';
+ import { RoadtripModule } from './roadtrip/roadtrip.module';
+ import { RouteUsageModule } from './route-usage/route-usage.module';
+ import { SchedulingModule } from './scheduling/scheduling.module';
+ import { SchoolHolidaysModule } from './school-holidays/school-holidays.module';
+ import { SettingsModule } from './settings/settings.module';
+ import { ShareModule } from './share/share.module';
+ import { StorageModule } from './storage/storage.module';
+ import { SystemNoticesModule } from './system-notices/system-notices.module';
+ import { TagsModule } from './tags/tags.module';
+ import { TodoModule } from './todo/todo.module';
++import { ToursModule } from './tours/tours.module';
+ import { TransitModule } from './transit/transit.module';
+ import { TripInviteModule } from './trip-invite/trip-invite.module';
+ import { TripsModule } from './trips/trips.module';
+ import { VacayModule } from './vacay/vacay.module';
+ import { WeatherModule } from './weather/weather.module';
+ import { MikroOrmModule } from '@mikro-orm/nestjs';
+ import { Module } from '@nestjs/common';
+ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
/**
* Root NestJS module for the incremental migration. Domain modules
@@@ -85,7 -91,94 +92,95 @@@
* migrated.
*/
@Module({
- imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, PublicApiModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, GoogleQuotaModule, PlaceEnrichmentModule, PlaceShadowModule, RouteUsageModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, SchoolHolidaysModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, RoadtripModule, ToursModule, TripsModule, CollabModule, FilesModule, DocSyncModule, PhotosModule, MemoriesModule, AirtrailModule, DawarichModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, ReceiptScanModule, LlmParseModule, ManagedExtModule],
+ imports: [
+ AppConfigModule,
+ DemoModule,
+ RealtimeModule,
+ RealtimeGatewayModule,
+ SchedulingModule,
+ McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }),
+ HealthModule,
+ PlatformModule,
+ McpTransportModule,
+ WeatherModule,
+ PublicApiModule,
+ HelpModule,
+ AirportsModule,
+ ConfigModule,
+ SystemNoticesModule,
+ GeoModule,
+ MapsModule,
+ GoogleQuotaModule,
+ PlaceEnrichmentModule,
+ PlaceShadowModule,
+ RouteUsageModule,
+ CategoriesModule,
+ TagsModule,
+ NotificationsModule,
+ AtlasModule,
+ VacayModule,
+ SchoolHolidaysModule,
+ PackingModule,
+ TodoModule,
+ BudgetModule,
+ ReservationsModule,
+ DaysModule,
+ DayNotesModule,
+ AccommodationsModule,
+ AssignmentsModule,
+ PlacesModule,
+ RoadtripModule,
++ ToursModule,
+ TripsModule,
+ CollabModule,
+ FilesModule,
+ DocSyncModule,
+ PhotosModule,
+ MemoriesModule,
+ AirtrailModule,
+ DawarichModule,
+ JourneyModule,
+ CollectionsModule,
+ ShareModule,
+ TripInviteModule,
+ TransitModule,
+ FeedsModule,
+ SettingsModule,
+ StorageModule,
+ BackupModule,
+ AuthModule,
+ OidcModule,
+ OauthModule,
+ AdminModule,
+ AddonsModule,
+ AuditModule,
+ PermissionsModule,
+ PluginsModule,
+ BookingImportModule,
+ ReservationImportModule,
+ ReceiptScanModule,
+ LlmParseModule,
+ ManagedExtModule,
+ // registerRequestContext off: bootstrap.ts mounts the per-request fork as a
+ // pathless middleware instead, because the module's own '{*all}' route
+ // turned a malformed %-escape into a 400 before any handler ran (UPLOADS-P16).
+ // Partial e2e harnesses keep the default; see tests/helpers/test-orm.ts.
+ MikroOrmModule.forRoot({ ...mikroOrmConfig, registerRequestContext: false }),
+ // `DatabaseModule` (the raw better-sqlite3 `db` Proxy + `DatabaseService`
+ // facade) is gone — Plan 4 Task 4 deleted it once every domain moved onto
+ // repositories/`UnitOfWork`. `OrmModule` is the module that survives.
+ OrmModule,
+ // MfaPolicyGuard (Plan 3b Task 1) is registered directly below as this
+ // module's own APP_GUARD, never per-controller — so it is the one place
+ // that needs `forFeature` for its three repositories; `Users` is not
+ // otherwise global (JwtAuthGuard and friends inject `EntityManager`
+ // instead precisely to avoid needing this everywhere — see their own
+ // docstrings). IdempotencyKeys: Plan 4 Task 1 — IdempotencyInterceptor/
+ // IdempotencyCleanupJob are ALSO registered directly here (common/ has
+ // no module of its own), so this is the one place their repository's
+ // `forFeature` needs to live too.
+ MikroOrmModule.forFeature([AppSettings, Users, WebauthnCredentials, IdempotencyKeys]),
+ ],
providers: [
// Default-deny: a route is authenticated unless it carries @Public() or
// @OptionalAuth(), or declares its own @UseGuards chain. Protection used to
diff --cc server/src/nest/assignments/assignments-domain.module.ts
index 377744971,265303050..1ebeb34f2
--- a/server/src/nest/assignments/assignments-domain.module.ts
+++ b/server/src/nest/assignments/assignments-domain.module.ts
@@@ -4,6 -5,13 +5,14 @@@ import { PermissionsModule } from '../p
import { QueryHelpersModule } from '../query-helpers/query-helpers.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { AssignmentsService } from './assignments.service';
+ import { DayAssignments } from '../../db/entities/DayAssignments.entity';
+ import { AssignmentParticipants } from '../../db/entities/AssignmentParticipants.entity';
+ import { Days } from '../../db/entities/Days.entity';
+ import { Places } from '../../db/entities/Places.entity';
+ import { TripMembers } from '../../db/entities/TripMembers.entity';
+ import { RoadtripVias } from '../../db/entities/RoadtripVias.entity';
+ import { Trips } from '../../db/entities/Trips.entity';
++import { Tours } from '../../db/entities/Tours.entity';
/**
* The assignments SERVICE, split from the controller/MCP/RPC surfaces (the
@@@ -12,10 -20,26 +21,27 @@@
* that stays off the DaysModule → PlacesModule → AssignmentsModule loop.
* That is what lets PlacesModule import this and places.mcp.ts inject the
* service, which retired assignments.bridge. Everything here is a leaf:
- * none of the four imports reaches the days or places domains.
+ * none of the four service imports reaches the days or places domains.
+ *
+ * `MikroOrmModule.forFeature([DayAssignments, AssignmentParticipants, Days,
+ * Places, TripMembers, RoadtripVias])` registers `DayAssignmentsRepository`/
+ * `AssignmentParticipantsRepository`/`DaysRepository`/`PlacesRepository`/
+ * `TripMembersRepository`/`RoadtripViasRepository` for `AssignmentsService`'s
+ * `@InjectRepository` constructor params (Plan 3c Task 3; `RoadtripVias`
+ * added by Plan 3d Task 1 for AS20–AS23) — the entity classes only, not the
+ * `DaysModule`/`PlacesModule`/`RoadtripModule` modules themselves, so the
+ * loop this module's docstring already avoids stays avoided (`DaysModule`'s
- * own precedent for pulling in `Trips` the same way).
++ * own precedent for pulling in `Trips` the same way). `Tours` backs the
++ * one-Tour-per-day check create and move share.
*/
@Module({
- imports: [PermissionsModule, QueryHelpersModule, JourneyDomainModule, RealtimeModule],
+ imports: [
+ PermissionsModule,
+ QueryHelpersModule,
+ JourneyDomainModule,
+ RealtimeModule,
- MikroOrmModule.forFeature([DayAssignments, AssignmentParticipants, Days, Places, TripMembers, RoadtripVias, Trips]),
++ MikroOrmModule.forFeature([DayAssignments, AssignmentParticipants, Days, Places, TripMembers, RoadtripVias, Trips, Tours]),
+ ],
providers: [AssignmentsService],
exports: [AssignmentsService],
})
diff --cc server/src/nest/assignments/assignments.service.ts
index e8fbb13d9,564fd1f18..048defbb1
--- a/server/src/nest/assignments/assignments.service.ts
+++ b/server/src/nest/assignments/assignments.service.ts
@@@ -1,13 -1,30 +1,32 @@@
-import { Injectable } from '@nestjs/common';
+import { ConflictException, Injectable } from '@nestjs/common';
+ import { InjectRepository } from '@mikro-orm/nestjs';
import { chronoOrder, type RoadtripVia, type TrekWsPayload, type TrekWsTripEventName } from '@trek/shared';
- import { isEmptyReanchoring, reanchorByStopOrder, type AnchoredVia } from '@trek/shared/roadtrip';
+ import { isEmptyReanchoring, reanchorByStopOrder } from '@trek/shared/roadtrip';
import { RealtimeService } from '../realtime/realtime.service';
- import { DatabaseService, type TripAccess } from '../database/database.service';
+ import type { TripAccess } from '../../db/repositories/Trips.repository';
import { PermissionsService } from '../permissions/permissions.service';
import { QueryHelpersService } from '../query-helpers/query-helpers.service';
import { formatAssignmentWithPlace } from '../common/rowShape';
- import type { AssignmentRow, DayAssignment, User, Participant } from '../../types';
+ import type { User } from '../../types';
import { JourneyDomainService } from '../journey/journey-domain.service';
+ import { UnitOfWork } from '../database/unit-of-work';
+ import { toRowId } from '../common/row-id';
+ import { DayAssignments } from '../../db/entities/DayAssignments.entity';
+ import type { DayAssignmentsRepository, DayStopRow } from '../../db/repositories/DayAssignments.repository';
+ import { AssignmentParticipants } from '../../db/entities/AssignmentParticipants.entity';
+ import type { AssignmentParticipantsRepository } from '../../db/repositories/AssignmentParticipants.repository';
+ import { Days } from '../../db/entities/Days.entity';
+ import type { DaysRepository } from '../../db/repositories/Days.repository';
+ import { Trips } from '../../db/entities/Trips.entity';
+ import type { TripsRepository } from '../../db/repositories/Trips.repository';
+ import { Places } from '../../db/entities/Places.entity';
+ import type { PlacesRepository } from '../../db/repositories/Places.repository';
+ import { TripMembers } from '../../db/entities/TripMembers.entity';
+ import type { TripMembersRepository } from '../../db/repositories/TripMembers.repository';
+ import { RoadtripVias } from '../../db/entities/RoadtripVias.entity';
+ import type { RoadtripViasRepository } from '../../db/repositories/RoadtripVias.repository';
++import { Tours } from '../../db/entities/Tours.entity';
++import type { ToursRepository } from '../../db/repositories/Tours.repository';
type Trip = TripAccess;
@@@ -64,13 -104,20 +106,21 @@@ export class AssignmentsService
private readonly realtime: RealtimeService,
private readonly queryHelpers: QueryHelpersService,
private readonly journey: JourneyDomainService,
+ private readonly uow: UnitOfWork,
+ @InjectRepository(DayAssignments) private readonly dayAssignmentsRepo: DayAssignmentsRepository,
+ @InjectRepository(AssignmentParticipants) private readonly assignmentParticipantsRepo: AssignmentParticipantsRepository,
+ @InjectRepository(Days) private readonly daysRepo: DaysRepository,
+ @InjectRepository(Places) private readonly placesRepo: PlacesRepository,
+ @InjectRepository(TripMembers) private readonly tripMembersRepo: TripMembersRepository,
+ @InjectRepository(RoadtripVias) private readonly roadtripViasRepo: RoadtripViasRepository,
++ @InjectRepository(Tours) private readonly toursRepo: ToursRepository,
) {}
- verifyTripAccess(tripId: string | number, userId: number) {
- return this.dbs.canAccessTrip(Number(tripId), userId);
+ async verifyTripAccess(tripId: string | number, userId: number) {
+ return await this.trips.findAccessible(Number(tripId), userId);
}
- canEdit(trip: Trip, user: User): boolean {
+ async canEdit(trip: Trip, user: User): Promise<boolean> {
return this.permissions.checkPermission('day_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id);
}
@@@ -174,19 -249,18 +252,19 @@@
* stop that reaches it without its booking id is one the day list cannot tell
* from a place the traveller added, so it draws the hotel a second time.
*/
- createAssignment(dayId: string | number, placeId: unknown, notes?: string | null, opts: { accommodationId?: number; orderIndex?: number } = {}) {
- const result = this.dbs.transaction(() => {
- const duplicateTourAssignment = this.dbs.get<{ id: number }>(
- `SELECT da.id FROM day_assignments da
- JOIN tours t ON t.place_id = da.place_id
- WHERE da.day_id = ? AND da.place_id = ?
- LIMIT 1`,
- dayId, placeId,
- );
- if (duplicateTourAssignment) throw new ConflictException('Tour is already assigned to this day');
-
- const maxOrder = this.dbs.get<{ max: number | null }>('SELECT MAX(order_index) as max FROM day_assignments WHERE day_id = ?', dayId)!;
- const end = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
+ async createAssignment(dayId: string | number, placeId: unknown, notes?: string | null, opts: { accommodationId?: number; orderIndex?: number } = {}) {
+ // Downstream of the caller's own dayExists/placeExists gate in the same
+ // request (every real call site), so the non-null assertion is
+ // dead-code-safe — the class docstring's affinity-seam note.
+ const dayIdNum = toRowId(dayId)!;
+ const placeIdNum = toRowId(placeId)!;
+
+ const insertedId = await this.uow.transactional(async () => {
++ await this.assertTourFreeOnDay(dayIdNum, placeIdNum);
+ // AS6 — the explicit null check (not `||`) is load-bearing: a stored 0
+ // order_index must survive, which `maxOrder || -1` would not.
+ const maxOrder = await this.dayAssignmentsRepo.maxOrderIndex(dayIdNum);
+ const end = (maxOrder !== null ? maxOrder : -1) + 1;
// Somewhere in the middle when the caller says so, which means everything from
// there on moves down. The end is still the default and still what every caller
// but one asks for.
@@@ -237,33 -331,38 +335,54 @@@
});
}
- getAssignmentForTrip(id: string | number, tripId: string | number) {
- return this.dbs.get<DayAssignment>(`
- SELECT da.* FROM day_assignments da
- JOIN days d ON da.day_id = d.id
- WHERE da.id = ? AND d.trip_id = ?
- `, id, tripId);
+ /**
+ * AS12 — `DayAssignmentsRepository.findInTrip`, `id` `toRowId`'d INSIDE
+ * this gate (Task 3 review H1 fix, absorbed in Task 4): every mutation
+ * behind this gate (`updateTime`, `setEndDay`, `updateNotes`,
+ * `setLegTransportMode`, `setIncomingLegTransportMode`, `setParticipants`,
+ * and `ItineraryRpc.unassign` via `moveAssignment`) converts `id` with its
+ * own `toRowId(id)!` — this must reject exactly what those reject, the
+ * same shape `assignmentExistsInDay` above uses for `deleteAssignment`.
+ * `tripId` keeps the legacy's own raw-bind scoping, unchanged.
+ */
+ async getAssignmentForTrip(id: string | number, tripId: string | number) {
+ const rowId = toRowId(id);
+ if (rowId === null) return undefined;
+ return await this.dayAssignmentsRepo.findInTrip(rowId, tripId);
}
- moveAssignment(id: string | number, newDayId: unknown, orderIndex: number | null | undefined) {
+ async moveAssignment(id: string | number, newDayId: unknown, orderIndex: number | null | undefined) {
+ const idNum = toRowId(id)!;
// The source day comes from the row, not the caller — callers can't lie
// about (or race on) where the assignment was.
- const oldDayId = this.dbs.transaction(() => {
- const row = this.dbs.get<{ day_id: number }>('SELECT day_id FROM day_assignments WHERE id = ?', id);
- this.dbs.run('UPDATE day_assignments SET day_id = ?, order_index = ? WHERE id = ?', newDayId, orderIndex ?? 0, id);
- return row?.day_id;
+ const oldDayId = await this.uow.transactional(async () => {
+ const dayId = await this.dayAssignmentsRepo.getDayId(idNum); // AS13
- await this.dayAssignmentsRepo.moveToDay(idNum, toRowId(newDayId)!, orderIndex ?? 0); // AS14
++ const targetDayId = toRowId(newDayId)!;
++ const placeId = await this.dayAssignmentsRepo.getPlaceId(idNum);
++ if (placeId !== undefined) await this.assertTourFreeOnDay(targetDayId, placeId, idNum);
++ await this.dayAssignmentsRepo.moveToDay(idNum, targetDayId, orderIndex ?? 0); // AS14
+ return dayId;
});
- const updated = this.getAssignmentWithPlace(Number(id));
+ const updated = await this.getAssignmentWithPlace(idNum);
return { assignment: updated, oldDayId };
}
- getParticipants(assignmentId: string | number) {
- return this.dbs.all(`
- SELECT ap.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
- FROM assignment_participants ap
- JOIN users u ON ap.user_id = u.id
- WHERE ap.assignment_id = ?
- `, assignmentId);
++ /**
++ * A Tour fills its day, so a day holds it at most once. Both ways a stop
++ * lands on a day (create and move) call this inside the transaction that
++ * writes it, so two concurrent requests cannot both pass the check. Move
++ * passes the assignment it moves so a reorder within the same day does
++ * not collide with itself. Ordinary places are never refused.
++ */
++ private async assertTourFreeOnDay(dayId: number, placeId: number, exceptAssignmentId?: number): Promise<void> {
++ if (await this.toursRepo.isOnDay(dayId, placeId, exceptAssignmentId)) {
++ throw new ConflictException('Tour is already assigned to this day');
++ }
++ }
++
+ /** AS15 — `AssignmentParticipantsRepository.listWithDisplayName`, the same AS2/AS31 statement. */
+ async getParticipants(assignmentId: string | number) {
+ return await this.assignmentParticipantsRepo.listWithDisplayName(toRowId(assignmentId)!);
}
/**
diff --cc server/src/nest/places/places.controller.ts
index 9bde9cc92,e5d55e4bc..cef0be793
--- a/server/src/nest/places/places.controller.ts
+++ b/server/src/nest/places/places.controller.ts
@@@ -313,22 -313,22 +313,22 @@@ export class PlacesController
@Body() body: PlaceBulkDeleteDto,
@Headers('x-socket-id') socketId?: string,
) {
- const trip = this.requireTrip(tripId, user);
- this.requireEdit(trip, user);
+ const trip = await this.requireTrip(tripId, user);
+ await this.requireEdit(trip, user);
const { ids } = body;
if (ids.length === 0) {
- return { deleted: [], count: 0 };
+ return { deleted: [], count: 0, tourPlaceIds: [] };
}
// Scope the ids to the trip before the hook: onPlaceDeleted keys on the
// place id alone, so an id from another trip would detach that trip's
// journey entries even though removeMany below refuses it. Still ahead of
// the DELETE — journey_entries.source_place_id is ON DELETE SET NULL, so
// afterwards there is nothing left to detach.
- const scoped = this.places.scopedIds(tripId, ids);
- for (const id of scoped) this.places.onDeleted(id);
+ const scoped = await this.places.scopedIds(tripId, ids);
+ for (const id of scoped) await this.places.onDeleted(id);
// Read the linked expenses before the delete — afterwards the link is gone (#1298).
- const expenseIds = this.places.linkedExpenseIds(tripId, scoped);
+ const expenseIds = await this.places.linkedExpenseIds(tripId, scoped);
- const { deleted, cancelled } = await this.places.removeMany(tripId, ids);
+ const { deleted, deletedTourPlaceIds = [], cancelled } = await this.places.removeMany(tripId, ids);
for (const id of deleted) {
this.places.broadcast(tripId, 'place:deleted', { placeId: id }, socketId);
}
@@@ -525,12 -525,12 +525,12 @@@
async remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
// Scope the id to the trip before the hook (see bulkDelete), then sync the
// journey ahead of the actual delete.
- if (!this.places.get(tripId, id)) {
+ if (!(await this.places.get(tripId, id))) {
throw new HttpException({ error: 'Place not found' }, 404);
}
- this.places.onDeleted(Number(id));
- const expenseIds = this.places.linkedExpenseIds(tripId, [id]);
+ await this.places.onDeleted(Number(id));
+ const expenseIds = await this.places.linkedExpenseIds(tripId, [id]);
- const { deleted, cancelled } = await this.places.remove(tripId, id);
+ const { deleted, deletedTourPlaceIds = [], cancelled } = await this.places.remove(tripId, id);
if (!deleted) {
throw new HttpException({ error: 'Place not found' }, 404);
}
diff --cc server/src/nest/places/places.service.ts
index 6038fb876,f0643dd91..a80b5b6aa
--- a/server/src/nest/places/places.service.ts
+++ b/server/src/nest/places/places.service.ts
@@@ -75,14 -93,6 +93,15 @@@ type Trip = TripAccess
type ImportedPlace = { id: number; route_geometry?: string | null; route_color?: string | null };
++/** One place parsed out of a GPX file, not yet persisted. */
+export interface PreparedGpxPlace {
+ name: string;
+ lat: number;
+ lng: number;
+ description: string | null;
+ routeGeometry?: string;
+}
+
/** Fields accepted when creating a place. */
export interface PlaceCreateInput {
name: string; description?: string; lat?: number; lng?: number; address?: string;
@@@ -517,45 -636,72 +645,78 @@@ export class PlacesService
}
}
- async remove(tripId: string, placeId: string): Promise<{ deleted: boolean; cancelled: CancelledStays }> {
+ async remove(tripId: string, placeId: string): Promise<{ deleted: boolean; deletedTourPlaceIds: number[]; cancelled: CancelledStays }> {
- const place = this.dbs.get<{ google_place_id: string | null; image_url: string | null }>(
- 'SELECT google_place_id, image_url FROM places WHERE id = ? AND trip_id = ?', placeId, tripId,
- );
const cancelled = noCancelledStays();
+ // `toRowId` first (Task 3 review H1, absorbed here): the write below
+ // (`deleteById`) must use the SAME id this gate's existence read used.
+ const id = toRowId(placeId);
- if (id === null) return { deleted: false, cancelled };
++ if (id === null) return { deleted: false, deletedTourPlaceIds: [], cancelled };
+ // Rule 21 (H1): the trip id gets the same `toRowId` treatment, parsed
+ // once here and reused for the gate AND every raw survivor below
+ // (`cancelStaysAt`'s PL16, the PL18 `budget_items` DELETE) —
+ // `Number(tripId)` used to disagree with those raw binds, so a hex trip
+ // id could pass this gate against a real trip's place while the raw
+ // deletes below matched nothing, leaving the place deleted but its
+ // linked expense and stay orphaned (H1, live: verified with a linked
+ // expense and a stay, both survived with `place_id: null`).
+ const tid = toRowId(tripId);
- if (tid === null) return { deleted: false, cancelled };
++ if (tid === null) return { deleted: false, deletedTourPlaceIds: [], cancelled };
+ // PL17 — the reclaim-candidate projection, read before the delete.
+ const place = await this.placesRepo.reclaimInputs(id, tid);
- if (!place) return { deleted: false, cancelled };
+ if (!place) return { deleted: false, deletedTourPlaceIds: [], cancelled };
+ let wasTour = false;
// The linked expense goes with the place, the same way a booking takes its
// expense with it (#1298). One transaction, so a place can never survive
// half-detached from its money.
- this.dbs.transaction(() => {
- wasTour = !!this.dbs.get('SELECT 1 FROM tours WHERE place_id = ?', placeId);
- this.cancelStaysAt(tripId, placeId, cancelled);
- this.dbs.run('DELETE FROM budget_items WHERE trip_id = ? AND place_id = ?', tripId, placeId);
- this.dbs.run('DELETE FROM places WHERE id = ?', placeId);
+ await this.uow.transactional(async () => {
++ // A Tour's facet row and waypoints go with the place (ON DELETE
++ // CASCADE); the caller still has to tell the client which ones did.
++ wasTour = await this.placesRepo.isTour(id);
+ await this.cancelStaysAt(tid, id, cancelled);
+ // PL18 — Plan 3e Task 2, converted: `BudgetItemsRepository.deleteForPlace`.
+ await this.budgetItemsRepo.deleteForPlace(tid, id);
+ // PL19 — `DELETE FROM places WHERE id = ?`.
+ await this.placesRepo.deleteById(id);
});
await reclaimPhotoCache(this.photoCache, place.google_place_id, place.image_url);
- await reclaimPlaceImage(this.storage, place.image_url);
- return { deleted: true, deletedTourPlaceIds: wasTour ? [Number(placeId)] : [], cancelled };
+ await this.reclaimPlaceImage(place.image_url);
- return { deleted: true, cancelled };
++ return { deleted: true, deletedTourPlaceIds: wasTour ? [id] : [], cancelled };
}
- async removeMany(tripId: string, ids: number[]): Promise<{ deleted: number[]; cancelled: CancelledStays }> {
+ async removeMany(tripId: string, ids: number[]): Promise<{ deleted: number[]; deletedTourPlaceIds: number[]; cancelled: CancelledStays }> {
const cancelled = noCancelledStays();
- if (ids.length === 0) return { deleted: [], cancelled };
+ if (ids.length === 0) return { deleted: [], deletedTourPlaceIds: [], cancelled };
- const selectStmt = this.dbs.prepare('SELECT google_place_id, image_url FROM places WHERE id = ? AND trip_id = ?');
- const selectTourStmt = this.dbs.prepare('SELECT 1 FROM tours WHERE place_id = ?');
- const deleteStmt = this.dbs.prepare('DELETE FROM places WHERE id = ?');
- const deleteExpenseStmt = this.dbs.prepare('DELETE FROM budget_items WHERE trip_id = ? AND place_id = ?');
+ // Rule 21 (H1): the trip id gets the same `toRowId` treatment as
+ // `remove()`'s, parsed once and reused for every id in the loop below.
+ // Task 9 fix wave (A-8): the claim this comment used to make — "the
+ // legacy raw bind produced the same shape, because the trip id didn't
+ // affinity-match any row" — was WRONG for `1.0`/`1 ` (and other
+ // SQLite-affinity-recognised spellings): the legacy statement DID match
+ // those against a real trip, deleting for real. `toRowId`'s narrower
+ // canonical-decimal check answers "nothing deleted" for those inputs
+ // too, which is the deliberate rule-15 narrowing (not parity) — and, as
+ // of this fix wave, moot in practice: `verifyTripAccess` already 404s
+ // any non-canonical trip id before `removeMany` is ever reached, so this
+ // `tid === null` branch only fires for a caller that skipped the gate.
+ const tid = toRowId(tripId);
- if (tid === null) return { deleted: [], cancelled };
++ if (tid === null) return { deleted: [], deletedTourPlaceIds: [], cancelled };
const deleted: number[] = [];
+ const deletedTourPlaceIds: number[] = [];
const reclaimable: { google_place_id: string | null; image_url: string | null }[] = [];
- this.dbs.transaction(() => {
+ await this.uow.transactional(async () => {
for (const id of ids) {
- const row = selectStmt.get(id, tripId) as { google_place_id: string | null; image_url: string | null } | undefined;
+ // PL20 — the reclaim-candidate projection, read before the delete
+ // (same statement as PL17). `id` is already a genuine `number`
+ // here (a body-validated array, not a route string) — no `toRowId`
+ // gate needed, the H1 class of bug is a route-string problem.
+ const row = await this.placesRepo.reclaimInputs(id, tid);
if (!row) continue;
- if (selectTourStmt.get(id)) deletedTourPlaceIds.push(id);
- this.cancelStaysAt(tripId, id, cancelled);
- deleteExpenseStmt.run(tripId, id);
- deleteStmt.run(id);
++ if (await this.placesRepo.isTour(id)) deletedTourPlaceIds.push(id);
+ await this.cancelStaysAt(tid, id, cancelled);
+ // PL22 — Plan 3e Task 2, converted: `BudgetItemsRepository.deleteForPlace`.
+ await this.budgetItemsRepo.deleteForPlace(tid, id);
+ // PL21 — `DELETE FROM places WHERE id = ?`.
+ await this.placesRepo.deleteById(id);
deleted.push(id);
reclaimable.push(row);
}
@@@ -563,9 -709,9 +724,9 @@@
// Reclaim after the transaction commits so isReferenced() sees the final place set.
for (const row of reclaimable) {
await reclaimPhotoCache(this.photoCache, row.google_place_id, row.image_url);
- await reclaimPlaceImage(this.storage, row.image_url);
+ await this.reclaimPlaceImage(row.image_url);
}
- return { deleted, cancelled };
+ return { deleted, deletedTourPlaceIds, cancelled };
}
/**
@@@ -769,17 -892,11 +907,22 @@@
day.points.push({ name: stop.name, lat: stop.lat, lng: stop.lng });
}
- const gpx = buildGpx({ tripTitle: trip.title, places, days: [...days.values()] }, opts);
- return gpx ? { gpx, filename: gpxFilename(trip.title) } : null;
+ const gpx = buildGpx({ tripTitle: title, places, days: [...days.values()] }, opts);
+ return gpx ? { gpx, filename: gpxFilename(title) } : null;
}
- private importGpxRows(tripId: string, fileBuffer: Buffer, opts: GpxImportOptions = {}): GpxImportResult | null {
+ private async importGpxRows(tripId: string, fileBuffer: Buffer, opts: GpxImportOptions = {}): Promise<GpxImportResult | null> {
+ const rows = this.prepareGpxRows(fileBuffer, opts);
+ if (!rows.length) return null;
- return this.dbs.transaction(() => this.persistGpxRows(tripId, rows));
++ return await this.uow.transactional(() => this.persistGpxRows(tripId, rows));
+ }
+
++ /**
++ * Parses a GPX file into the places an import would create, without writing
++ * anything. The Tours import reuses it to build its own selection before
++ * handing the rows to {@link importPreparedGpx}.
++ */
+ prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): PreparedGpxPlace[] {
const { importWaypoints = true, importRoutes = true, importTracks = true, defaultName } = opts;
const parsed = gpxParser.parse(fileBuffer.toString('utf-8'));
@@@ -848,35 -966,67 +991,82 @@@
}
}
- if (waypoints.length === 0) return null;
+ return waypoints;
+ }
+
- importPreparedGpx(tripId: string, rows: PreparedGpxPlace[]): GpxImportResult {
- if (!this.dbs.connection.inTransaction) throw new Error('Prepared GPX import requires an active transaction');
- const result = this.persistGpxRows(tripId, rows);
- const tracks = result.places.filter(place => place.route_geometry && !place.route_color);
- this.applyImportedTrackColors(this.dbs.connection, tripId, tracks);
- return result;
++ /**
++ * Persists rows from {@link prepareGpxRows} and colours their tracks, both in
++ * one transaction. Called from inside the Tours import's own transaction,
++ * where this becomes a savepoint, so the places and their tour facets
++ * commit or roll back together.
++ */
++ async importPreparedGpx(tripId: string, rows: PreparedGpxPlace[]): Promise<GpxImportResult> {
++ return await this.uow.transactional(async () => {
++ const result = await this.persistGpxRows(tripId, rows);
++ await this.colorizeImportedTracks(tripId, result);
++ return result;
++ });
+ }
- private persistGpxRows(tripId: string, waypoints: PreparedGpxPlace[]): GpxImportResult {
- const dedup = this.buildDedupSet(tripId);
- const insertStmt = this.dbs.prepare(`
- INSERT INTO places (trip_id, name, description, lat, lng, transport_mode, route_geometry)
- VALUES (?, ?, ?, ?, ?, 'walking', ?)
- `);
++ /** Inserts prepared GPX rows, skipping duplicates. The caller owns the transaction. */
++ private async persistGpxRows(tripId: string, waypoints: PreparedGpxPlace[]): Promise<GpxImportResult> {
+ // Rule 21 / M1 (Task 9 fix wave): non-null asserted, not `?? -1` — the
+ // controller's `requireTrip` (`verifyTripAccess`) already parsed and
+ // gated this SAME `tripId` with `toRowId` before `importGpx` was ever
+ // called, so a miss here can only mean a caller skipped the gate (see
+ // `create()`'s comment for the full ruling). `buildDedupSet` keeps the
+ // raw-bind seam (L6 ruling, PL24) — this does not touch it.
+ const tid = toRowId(tripId)!;
+ const dedup = await this.buildDedupSet(tripId);
const created: PlaceWithTags[] = [];
let skipped = 0;
+ // PL31/PL32 — one `insertPlace` call per waypoint. The legacy statement's
+ // narrower 7-column INSERT (trip_id, name, description, lat, lng,
+ // transport_mode='walking' literal, route_geometry) is reproduced as a
+ // typed `insertPlace` partial: the literal becomes a value, and every
+ // column the legacy INSERT omitted takes the same value the DB column
+ // default would have produced (`duration_minutes: 60`, everything else
+ // `null`) — parity by stored row, not by SQL text. Re-selected via
- // `findWithTagsAndRatings` INSIDE the same transaction the insert ran
- // in, so the read sees the still-uncommitted row.
- await this.uow.transactional(async () => {
- for (const wp of waypoints) {
- if (isPlaceDuplicate({ name: wp.name, lat: wp.lat, lng: wp.lng }, dedup)) {
- skipped++;
- continue;
- }
- const placeId = await this.placesRepo.insertPlace({
- trip_id: tid,
- name: wp.name,
- description: wp.description,
- lat: wp.lat,
- lng: wp.lng,
- address: null,
- category_id: null,
- price: null,
- currency: null,
- place_time: null,
- end_time: null,
- duration_minutes: 60,
- notes: null,
- image_url: null,
- google_place_id: null,
- google_ftid: null,
- osm_id: null,
- amap_poi_id: null,
- website: null,
- phone: null,
- transport_mode: 'walking',
- route_geometry: wp.routeGeometry || null,
- route_color: null,
- stop_type: null,
- fill_percent: null,
- email: null,
- opening_hours: null,
- });
- const place = (await this.placesRepo.findWithTagsAndRatings(placeId))!;
- created.push(place);
- trackInsertedInDedupSet({ name: wp.name, lat: wp.lat, lng: wp.lng }, dedup);
++ // `findWithTagsAndRatings` INSIDE the caller's transaction, so the read
++ // sees the still-uncommitted row.
+ for (const wp of waypoints) {
+ if (isPlaceDuplicate({ name: wp.name, lat: wp.lat, lng: wp.lng }, dedup)) {
+ skipped++;
+ continue;
}
- const result = insertStmt.run(tripId, wp.name, wp.description, wp.lat, wp.lng, wp.routeGeometry || null);
- const place = this.dbs.getPlaceWithTags(Number(result.lastInsertRowid))!;
- });
++ const placeId = await this.placesRepo.insertPlace({
++ trip_id: tid,
++ name: wp.name,
++ description: wp.description,
++ lat: wp.lat,
++ lng: wp.lng,
++ address: null,
++ category_id: null,
++ price: null,
++ currency: null,
++ place_time: null,
++ end_time: null,
++ duration_minutes: 60,
++ notes: null,
++ image_url: null,
++ google_place_id: null,
++ google_ftid: null,
++ osm_id: null,
++ amap_poi_id: null,
++ website: null,
++ phone: null,
++ transport_mode: 'walking',
++ route_geometry: wp.routeGeometry || null,
++ route_color: null,
++ stop_type: null,
++ fill_percent: null,
++ email: null,
++ opening_hours: null,
++ });
++ const place = (await this.placesRepo.findWithTagsAndRatings(placeId))!;
+ created.push(place);
+ trackInsertedInDedupSet({ name: wp.name, lat: wp.lat, lng: wp.lng }, dedup);
+ }
return { places: created, count: created.length, skipped };
}
diff --cc server/src/nest/tours/tours-import.controller.ts
index 000000000,000000000..6e9642c4b
new file mode 100644
--- /dev/null
+++ b/server/src/nest/tours/tours-import.controller.ts
@@@ -1,0 -1,0 +1,60 @@@
++import { Controller, Headers, HttpException, Param, Post, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
++import { FileInterceptor } from '@nestjs/platform-express';
++import { memoryStorage } from 'multer';
++import type { User } from '../../types';
++import { ADDON_IDS } from '../../addons';
++import { AddonsService } from '../addons/addons.service';
++import { CurrentUser } from '../auth/current-user.decorator';
++import { JwtAuthGuard } from '../auth/jwt-auth.guard';
++import { PlacesService } from '../places/places.service';
++import { ToursService } from './tours.service';
++
++const UPLOAD = { storage: memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } };
++
++/**
++ * POST /api/trips/:tripId/tours/import/gpx: the tours-mode GPX import.
++ *
++ * A controller of its own because it must not sit behind ToursController's
++ * AddonGuard and TripAccessGuard: a guard answers before multer has read the
++ * multipart body, and the client then sees ECONNRESET instead of the 404 or
++ * 403. The handler runs the same checks in the same order once the upload is
++ * drained, with the guards' own bodies: addon off 404, no trip access 404,
++ * no 'place_edit' 403. PlacesController.importGpx is the sibling.
++ */
++@Controller('api/trips/:tripId/tours')
++@UseGuards(JwtAuthGuard)
++export class ToursImportController {
++ constructor(
++ private readonly tours: ToursService,
++ private readonly places: PlacesService,
++ private readonly addons: AddonsService,
++ ) {}
++
++ @Post('import/gpx')
++ @UseInterceptors(FileInterceptor('file', UPLOAD))
++ async importGpx(
++ @CurrentUser() user: User,
++ @Param('tripId') tripId: string,
++ @UploadedFile() file: Express.Multer.File | undefined,
++ @Headers('x-socket-id') socketId?: string,
++ ) {
++ if (!(await this.addons.isAddonEnabled(ADDON_IDS.TOURS))) {
++ throw new HttpException({ error: 'Tours addon is not enabled' }, 404);
++ }
++ const trip = await this.places.verifyTripAccess(tripId, user.id);
++ if (!trip) {
++ throw new HttpException({ error: 'Trip not found' }, 404);
++ }
++ if (!(await this.places.canEdit(trip, user))) {
++ throw new HttpException({ error: 'No permission' }, 403);
++ }
++ if (!file) {
++ throw new HttpException({ error: 'No file uploaded' }, 400);
++ }
++ const result = await this.tours.importGpxAsTour(tripId, file.buffer, file.originalname, socketId);
++ if (!result) {
++ throw new HttpException({ error: 'No track or route found in GPX file' }, 400);
++ }
++ return result;
++ }
++}
diff --cc server/src/nest/tours/tours.controller.ts
index b2f8ac7aa,000000000..a72f06e52
mode 100644,000000..100644
--- a/server/src/nest/tours/tours.controller.ts
+++ b/server/src/nest/tours/tours.controller.ts
@@@ -1,76 -1,0 +1,53 @@@
- import {
- Body, Controller, Get, Headers, HttpException, Param, Post, Put, UploadedFile, UseGuards, UseInterceptors,
- } from '@nestjs/common';
- import { FileInterceptor } from '@nestjs/platform-express';
- import { memoryStorage } from 'multer';
++import { Body, Controller, Get, Headers, Param, Post, Put, UseGuards } from '@nestjs/common';
+import { ToursService } from './tours.service';
+import { JwtAuthGuard } from '../auth/jwt-auth.guard';
+import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
+import { AddonGuard } from '../addons/addon.guard';
+import { RequireAddon } from '../addons/require-addon.decorator';
+import { ADDON_IDS } from '../../addons';
+import { TourCreateDto } from './dto/tour-create.dto';
+
- const UPLOAD = { storage: memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } };
-
+/**
- * /api/trips/:tripId/tours: the Tours facet, read and tours-mode GPX import.
++ * /api/trips/:tripId/tours: the Tours facet, read and route edits.
+ * TripAccessGuard resolves
+ * :tripId (404 for no access); writes require 'place_edit'. Assignments stay
- * on the existing day_edit endpoints.
++ * on the existing day_edit endpoints. The multipart GPX import lives in
++ * ToursImportController, which checks the same rules in its handler.
+ */
+@Controller('api/trips/:tripId/tours')
+@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
+@RequireAddon(ADDON_IDS.TOURS, 'Tours')
+export class ToursController {
+ constructor(private readonly tours: ToursService) {}
+
+ @Get()
- list(@Param('tripId') tripId: string) {
- return { tours: this.tours.listTours(tripId) };
++ async list(@Param('tripId') tripId: string) {
++ return { tours: await this.tours.listTours(tripId) };
+ }
+
+ @Get(':placeId')
- detail(@Param('tripId') tripId: string, @Param('placeId') placeId: string) {
- return this.tours.getTour(tripId, placeId);
++ async detail(@Param('tripId') tripId: string, @Param('placeId') placeId: string) {
++ return await this.tours.getTour(tripId, placeId);
+ }
+
+ @RequirePermission('place_edit')
+ @Post()
- create(
++ async create(
+ @Param('tripId') tripId: string,
+ @Body() body: TourCreateDto,
+ @Headers('x-socket-id') socketId?: string,
+ ) {
- return this.tours.createTour(tripId, body, socketId);
++ return await this.tours.createTour(tripId, body, socketId);
+ }
+
+ @RequirePermission('place_edit')
+ @Put(':placeId')
- update(
++ async update(
+ @Param('tripId') tripId: string,
+ @Param('placeId') placeId: string,
+ @Body() body: TourCreateDto,
+ @Headers('x-socket-id') socketId?: string,
+ ) {
- return this.tours.updateTour(tripId, placeId, body, socketId);
- }
-
- @RequirePermission('place_edit')
- @Post('import/gpx')
- @UseInterceptors(FileInterceptor('file', UPLOAD))
- importGpx(
- @Param('tripId') tripId: string,
- @UploadedFile() file: Express.Multer.File | undefined,
- @Headers('x-socket-id') socketId?: string,
- ) {
- if (!file) {
- throw new HttpException({ error: 'No file uploaded' }, 400);
- }
- const result = this.tours.importGpxAsTour(tripId, file.buffer, file.originalname, socketId);
- if (!result) {
- throw new HttpException({ error: 'No track or route found in GPX file' }, 400);
- }
- return result;
++ return await this.tours.updateTour(tripId, placeId, body, socketId);
+ }
+}
diff --cc server/src/nest/tours/tours.module.ts
index c5067088f,000000000..16bf958c9
mode 100644,000000..100644
--- a/server/src/nest/tours/tours.module.ts
+++ b/server/src/nest/tours/tours.module.ts
@@@ -1,18 -1,0 +1,32 @@@
++import { MikroOrmModule } from '@mikro-orm/nestjs';
+import { Module } from '@nestjs/common';
++import { Places } from '../../db/entities/Places.entity';
++import { Tours } from '../../db/entities/Tours.entity';
++import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
+import { ToursController } from './tours.controller';
++import { ToursImportController } from './tours-import.controller';
+import { ToursService } from './tours.service';
+import { PlacesModule } from '../places/places.module';
+import { PermissionsModule } from '../permissions/permissions.module';
+import { AuthModule } from '../auth/auth.module';
+import { AddonsModule } from '../addons/addons.module';
+
+/**
+ * Tours domain: an isolated bounded context that imports PlacesModule to reuse
- * GPX preparation and persistence through PlacesService.
++ * GPX preparation and persistence through PlacesService. The tour SQL lives in
++ * the Tours and TourWaypoints repositories; the owning place's route columns go
++ * through PlacesRepository, registered here because forFeature only reaches
++ * this module's own providers.
+ */
+@Module({
- imports: [PlacesModule, PermissionsModule, AuthModule, AddonsModule],
- controllers: [ToursController],
++ imports: [
++ PlacesModule,
++ PermissionsModule,
++ AuthModule,
++ AddonsModule,
++ MikroOrmModule.forFeature([Tours, TourWaypoints, Places]),
++ ],
++ controllers: [ToursController, ToursImportController],
+ providers: [ToursService],
+})
+export class ToursModule {}
diff --cc server/src/nest/tours/tours.service.ts
index f2fa36c11,000000000..b064fd64d
mode 100644,000000..100644
--- a/server/src/nest/tours/tours.service.ts
+++ b/server/src/nest/tours/tours.service.ts
@@@ -1,280 -1,0 +1,249 @@@
++import { InjectRepository } from '@mikro-orm/nestjs';
+import { Injectable, Logger, NotFoundException } from '@nestjs/common';
+import type { TourCreateRequest, TourCreateResponse, TourDetailResponse, TourListItem, TourWaypoint } from '@trek/shared';
- import { DatabaseService } from '../database/database.service';
++import { Places } from '../../db/entities/Places.entity';
++import { Tours } from '../../db/entities/Tours.entity';
++import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
++import type { PlacesRepository } from '../../db/repositories/Places.repository';
++import type { TourListRow, ToursRepository, TourUpdate } from '../../db/repositories/Tours.repository';
++import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
++import { toRowId } from '../common/row-id';
++import { UnitOfWork } from '../database/unit-of-work';
+import { PlacesService } from '../places/places.service';
+import { computeTourMetrics, parseRouteGeometry, LOW_CONFIDENCE_THRESHOLD, type GeometryPoint } from './tours.helpers';
+
+export interface ImportGpxAsTourResult {
+ tours: TourListItem[];
+ caution: boolean;
+ skipped: number;
+}
+
- type TourJoinRow = {
- place_id: number; name: string; tour_type: string; distance: number | null;
- elevation_gain: number | null; elevation_loss: number | null; duration: number | null;
- difficulty: string | null; wanderer_ref: string | null; match_confidence: number | null;
- tour_group_id: number | null; max_hiking_difficulty: number | null; planned: number; has_waypoints: number;
- };
-
+/**
+ * Tours domain: the `tours` facet table (place_id PK/FK) carries tour-specific
+ * metadata while existing places and day assignments are reused.
+ * GPX parsing and persistence are reused through PlacesService.prepareGpxRows
+ * and importPreparedGpx. Places and facet rows are persisted in one transaction,
+ * with tour metrics derived from each place's route_geometry.
+ */
+@Injectable()
+export class ToursService {
+ private readonly logger = new Logger(ToursService.name);
+
+ constructor(
- private readonly dbs: DatabaseService,
++ private readonly uow: UnitOfWork,
+ private readonly places: PlacesService,
++ @InjectRepository(Tours) private readonly toursRepo: ToursRepository,
++ @InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,
++ @InjectRepository(Places) private readonly placesRepo: PlacesRepository,
+ ) {}
+
- private toItem(r: TourJoinRow): TourListItem {
++ private toItem(r: TourListRow): TourListItem {
+ return {
+ place_id: r.place_id,
+ name: r.name,
+ tour_type: r.tour_type as TourListItem['tour_type'],
+ distance: r.distance,
+ elevation_gain: r.elevation_gain,
+ elevation_loss: r.elevation_loss,
+ duration: r.duration,
+ difficulty: r.difficulty,
+ wanderer_ref: r.wanderer_ref,
+ match_confidence: r.match_confidence,
+ tour_group_id: r.tour_group_id,
+ max_hiking_difficulty: r.max_hiking_difficulty ?? 2,
+ planned: Boolean(r.planned),
+ caution: r.match_confidence !== null && r.match_confidence < LOW_CONFIDENCE_THRESHOLD,
+ has_waypoints: Boolean(r.has_waypoints),
+ };
+ }
+
++ /** The route a create or an update writes: metrics derived from the geometry, duration stored in minutes. */
++ private routeFields(input: TourCreateRequest): TourUpdate {
++ const metrics = computeTourMetrics(input.route_geometry as GeometryPoint[]);
++ return {
++ tour_type: input.tour_type,
++ distance: metrics.distanceKm,
++ elevation_gain: metrics.elevationGainM,
++ elevation_loss: metrics.elevationLossM,
++ duration: input.duration_seconds == null ? null : Math.round(input.duration_seconds / 60),
++ match_confidence: 1,
++ max_hiking_difficulty: input.max_hiking_difficulty,
++ };
++ }
++
+ /** All tours (the facet + owning place) for a trip, newest first. */
- listTours(tripId: string): TourListItem[] {
- const rows = this.dbs.all<TourJoinRow>(`
- SELECT p.id AS place_id, p.name, t.tour_type, t.distance, t.elevation_gain,
- t.elevation_loss, t.duration, t.difficulty, t.wanderer_ref, t.match_confidence,
- t.tour_group_id, t.max_hiking_difficulty,
- EXISTS(SELECT 1 FROM day_assignments da WHERE da.place_id = p.id) AS planned,
- EXISTS(SELECT 1 FROM tour_waypoints tw WHERE tw.place_id = p.id) AS has_waypoints
- FROM tours t
- JOIN places p ON p.id = t.place_id
- WHERE p.trip_id = ?
- ORDER BY t.created_at DESC
- `, tripId);
++ async listTours(tripId: string): Promise<TourListItem[]> {
++ const tid = toRowId(tripId);
++ if (tid === null) return [];
++ const rows = await this.toursRepo.listForTrip(tid);
+ return rows.map(r => this.toItem(r));
+ }
+
+ /** One saved tour plus the persisted routing controls needed by the editor. */
- getTour(tripId: string, placeId: string): TourDetailResponse {
- const row = this.dbs.get<TourJoinRow>(`
- SELECT p.id AS place_id, p.name, t.tour_type, t.distance, t.elevation_gain,
- t.elevation_loss, t.duration, t.difficulty, t.wanderer_ref, t.match_confidence,
- t.tour_group_id, t.max_hiking_difficulty,
- EXISTS(SELECT 1 FROM day_assignments da WHERE da.place_id = p.id) AS planned,
- EXISTS(SELECT 1 FROM tour_waypoints tw WHERE tw.place_id = p.id) AS has_waypoints
- FROM tours t
- JOIN places p ON p.id = t.place_id
- WHERE p.trip_id = ? AND p.id = ?
- `, tripId, placeId);
++ async getTour(tripId: string, placeId: string): Promise<TourDetailResponse> {
++ const tid = toRowId(tripId);
++ const pid = toRowId(placeId);
++ const row = tid !== null && pid !== null ? await this.toursRepo.findInTrip(tid, pid) : undefined;
+ if (!row) throw new NotFoundException('Tour not found');
+
- let waypoints = this.dbs.all<TourWaypoint>(`
- SELECT lat, lng, role, sequence
- FROM tour_waypoints
- WHERE place_id = ?
- ORDER BY sequence
- `, placeId);
++ let waypoints: TourWaypoint[] = await this.waypointsRepo.listForPlace(row.place_id);
+ // GPX tours created before tour_waypoints existed still belong in this
+ // all-tours rail. A read-only endpoint must not backfill the database, so
+ // expose their saved geometry endpoints as controls; the first edit/save
+ // replaces them with normal persisted tour_waypoints transactionally.
+ if (waypoints.length < 2) {
- const place = this.dbs.get<{ route_geometry: string | null }>(
- 'SELECT route_geometry FROM places WHERE id = ? AND trip_id = ?', placeId, tripId,
- );
++ const place = await this.placesRepo.findInTrip(row.place_id, tid!);
+ const geometry = parseRouteGeometry(place?.route_geometry);
+ if (geometry.length >= 2) {
+ const start = geometry[0];
+ const end = geometry[geometry.length - 1];
+ waypoints = [
+ { lat: start[0], lng: start[1], role: 'start', sequence: 0 },
+ { lat: end[0], lng: end[1], role: 'end', sequence: 1 },
+ ];
+ }
+ }
+
+ return { tour: this.toItem(row), waypoints };
+ }
+
+ /** Create the owning Place, Tours facet, and ordered control points as one write. */
- createTour(tripId: string, input: TourCreateRequest, socketId?: string): TourCreateResponse {
- const geometry = input.route_geometry as GeometryPoint[];
- const metrics = computeTourMetrics(geometry);
++ async createTour(tripId: string, input: TourCreateRequest, socketId?: string): Promise<TourCreateResponse> {
++ // The controller's TripAccessGuard already resolved this trip id.
++ const tid = toRowId(tripId)!;
+ const start = input.route_geometry[0];
- let placeId = 0;
-
- this.dbs.transaction(() => {
- const place = this.dbs.run(`
- INSERT INTO places (trip_id, name, lat, lng, transport_mode, route_geometry)
- VALUES (?, ?, ?, ?, 'walking', ?)
- `, tripId, input.name, start[0], start[1], JSON.stringify(input.route_geometry));
- placeId = Number(place.lastInsertRowid);
-
- this.dbs.run(`
- INSERT INTO tours (
- place_id, tour_type, distance, elevation_gain, elevation_loss, duration, match_confidence,
- max_hiking_difficulty
- ) VALUES (?, ?, ?, ?, ?, ?, 1, ?)
- `, placeId, input.tour_type, metrics.distanceKm, metrics.elevationGainM,
- metrics.elevationLossM, input.duration_seconds == null ? null : Math.round(input.duration_seconds / 60),
- input.max_hiking_difficulty);
-
- const insertWaypoint = this.dbs.prepare(`
- INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence)
- VALUES (?, ?, ?, ?, ?)
- `);
- for (const waypoint of input.waypoints) {
- insertWaypoint.run(placeId, waypoint.lat, waypoint.lng, waypoint.role, waypoint.sequence);
- }
++ const fields = this.routeFields(input);
++
++ const placeId = await this.uow.transactional(async () => {
++ const id = await this.placesRepo.insertTourPlace({
++ trip_id: tid, name: input.name, lat: start[0], lng: start[1], route_geometry: JSON.stringify(input.route_geometry),
++ });
++ await this.toursRepo.insertTour({ place_id: id, ...fields });
++ await this.waypointsRepo.insertForPlace(id, input.waypoints);
++ return id;
+ });
+
- const tour = this.listTours(tripId).find(item => item.place_id === placeId);
- const place = this.dbs.getPlaceWithTags(placeId);
- if (!tour || !place) throw new Error('Created tour could not be loaded');
- const waypoints = this.dbs.all<TourWaypoint>(`
- SELECT lat, lng, role, sequence
- FROM tour_waypoints
- WHERE place_id = ?
- ORDER BY sequence
- `, placeId);
++ const row = await this.toursRepo.findInTrip(tid, placeId);
++ const place = await this.placesRepo.findWithTagsAndRatings(placeId);
++ if (!row || !place) throw new Error('Created tour could not be loaded');
++ const waypoints = await this.waypointsRepo.listForPlace(placeId);
+
+ // Only announce after every row committed. The originating client reloads
+ // explicitly because socket-id exclusion intentionally suppresses its echo.
+ this.broadcastToursChanged(tripId, [placeId], socketId);
+ try {
+ this.places.broadcast(tripId, 'place:created', { place }, socketId);
+ } catch {
+ this.logger.warn(`Committed Tour ${placeId}: place notification failed`);
+ }
- return { tour, waypoints };
++ return { tour: this.toItem(row), waypoints };
+ }
+
+ /** Replace a saved tour's derived route and routing controls as one write. */
- updateTour(tripId: string, placeId: string, input: TourCreateRequest, socketId?: string): TourDetailResponse {
- // The trip predicate is the cross-trip boundary. Do this before any write so
- // an id from another accessible trip cannot be moved into the current one.
- this.getTour(tripId, placeId);
- const geometry = input.route_geometry as GeometryPoint[];
- const metrics = computeTourMetrics(geometry);
++ async updateTour(tripId: string, placeId: string, input: TourCreateRequest, socketId?: string): Promise<TourDetailResponse> {
++ const tid = toRowId(tripId);
++ const pid = toRowId(placeId);
++ if (tid === null || pid === null) throw new NotFoundException('Tour not found');
+ const start = input.route_geometry[0];
-
- this.dbs.transaction(() => {
- this.dbs.run(`
- UPDATE places
- SET name = ?, lat = ?, lng = ?, transport_mode = 'walking', route_geometry = ?
- WHERE id = ? AND trip_id = ?
- `, input.name, start[0], start[1], JSON.stringify(input.route_geometry), placeId, tripId);
- this.dbs.run(`
- UPDATE tours
- SET tour_type = ?, distance = ?, elevation_gain = ?, elevation_loss = ?,
- duration = ?, match_confidence = 1, max_hiking_difficulty = ?
- WHERE place_id = ?
- `, input.tour_type, metrics.distanceKm, metrics.elevationGainM, metrics.elevationLossM,
- input.duration_seconds == null ? null : Math.round(input.duration_seconds / 60), input.max_hiking_difficulty, placeId);
- this.dbs.run('DELETE FROM tour_waypoints WHERE place_id = ?', placeId);
-
- const insertWaypoint = this.dbs.prepare(`
- INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence)
- VALUES (?, ?, ?, ?, ?)
- `);
- for (const waypoint of input.waypoints) {
- insertWaypoint.run(placeId, waypoint.lat, waypoint.lng, waypoint.role, waypoint.sequence);
- }
++ const fields = this.routeFields(input);
++
++ await this.uow.transactional(async () => {
++ // The trip predicate is the cross-trip boundary. It runs inside the write
++ // so an id from another accessible trip cannot be moved into the current
++ // one, and a place deleted meanwhile answers 404 instead of failing a
++ // waypoint insert on its foreign key.
++ if (!(await this.toursRepo.findInTrip(tid, pid))) throw new NotFoundException('Tour not found');
++ const placeUpdated = await this.placesRepo.updateTourRoute(pid, tid, {
++ name: input.name, lat: start[0], lng: start[1], route_geometry: JSON.stringify(input.route_geometry),
++ });
++ if (!placeUpdated) throw new NotFoundException('Tour not found');
++ if (!(await this.toursRepo.updateInTrip(tid, pid, fields))) throw new NotFoundException('Tour not found');
++ await this.waypointsRepo.deleteForPlace(pid);
++ await this.waypointsRepo.insertForPlace(pid, input.waypoints);
+ });
+
- const result = this.getTour(tripId, placeId);
- const place = this.dbs.getPlaceWithTags(Number(placeId));
++ const result = await this.getTour(tripId, placeId);
++ const place = await this.placesRepo.findWithTagsAndRatings(pid);
+ if (!place) throw new Error('Updated tour could not be loaded');
- this.broadcastToursChanged(tripId, [Number(placeId)], socketId);
++ this.broadcastToursChanged(tripId, [pid], socketId);
+ try {
+ this.places.broadcast(tripId, 'place:updated', { place }, socketId);
+ } catch {
+ this.logger.warn(`Committed Tour ${placeId}: place notification failed`);
+ }
+ return result;
+ }
+
+ private broadcastToursChanged(tripId: string, placeIds: number[], socketId?: string): void {
+ try {
+ this.places.broadcast(tripId, 'tours:changed', { placeIds }, socketId);
+ } catch {
+ this.logger.warn(`Committed Tours change for trip ${tripId}: realtime invalidation failed`);
+ }
+ }
+
+ /**
- * The tours-mode GPX import prepares rows through PlacesService.prepareGpxRows
- * with waypoints excluded. PlacesService.importPreparedGpx persists the places
- * in the same transaction as their `tours` facet rows, whose metrics are
- * derived from route_geometry.
++ * The tours-mode GPX import prepares rows through PlacesService.prepareGpxRows
++ * with waypoints excluded. PlacesService.importPreparedGpx persists the places
++ * in the same transaction as their `tours` facet rows, whose metrics are
++ * derived from route_geometry.
+ *
- * Missing or implausible metrics do not block import:
++ * Missing or implausible metrics do not block import:
+ * a track without elevation still imports, just flagged with a low
+ * match_confidence so the client can surface a "with caution" toast.
+ */
- importGpxAsTour(tripId: string, fileBuffer: Buffer, defaultName?: string, socketId?: string): ImportGpxAsTourResult | null {
++ async importGpxAsTour(tripId: string, fileBuffer: Buffer, defaultName?: string, socketId?: string): Promise<ImportGpxAsTourResult | null> {
+ const rows = this.places.prepareGpxRows(fileBuffer, {
+ importWaypoints: false, importRoutes: true, importTracks: true, defaultName,
+ });
+ if (rows.length === 0) return null;
+
- const insertTour = this.dbs.prepare(`
- INSERT INTO tours (place_id, tour_type, distance, elevation_gain, elevation_loss, duration, match_confidence, max_hiking_difficulty)
- VALUES (?, 'hike', ?, ?, ?, NULL, ?, 2)
- `);
-
+ const tours: TourListItem[] = [];
- const result = this.dbs.transaction(() => {
- const result = this.places.importPreparedGpx(tripId, rows);
- for (const place of result.places) {
- const points = parseRouteGeometry(place.route_geometry);
- const metrics = computeTourMetrics(points);
++ const result = await this.uow.transactional(async () => {
++ // A nested transactional, so the places and their facets commit together.
++ const imported = await this.places.importPreparedGpx(tripId, rows);
++ for (const place of imported.places) {
++ const metrics = computeTourMetrics(parseRouteGeometry(place.route_geometry));
+ const matchConfidence = metrics.hasElevation ? 1 : 0.3;
- insertTour.run(place.id, metrics.distanceKm, metrics.elevationGainM, metrics.elevationLossM, matchConfidence);
++ await this.toursRepo.insertTour({
++ place_id: place.id,
++ tour_type: 'hike',
++ distance: metrics.distanceKm,
++ elevation_gain: metrics.elevationGainM,
++ elevation_loss: metrics.elevationLossM,
++ duration: null,
++ match_confidence: matchConfidence,
++ max_hiking_difficulty: 2,
++ });
+ tours.push(this.toItem({
+ place_id: place.id,
+ name: place.name,
+ tour_type: 'hike',
+ distance: metrics.distanceKm,
+ elevation_gain: metrics.elevationGainM,
+ elevation_loss: metrics.elevationLossM,
+ duration: null,
+ difficulty: null,
+ wanderer_ref: null,
+ match_confidence: matchConfidence,
+ tour_group_id: null,
+ max_hiking_difficulty: 2,
+ planned: 0,
+ has_waypoints: 0,
+ }));
+ }
- return result;
++ return imported;
+ });
+
+ if (result.places.length === 0) return { tours: [], caution: false, skipped: result.skipped };
+ this.broadcastToursChanged(tripId, result.places.map(place => place.id), socketId);
+ for (const place of result.places) {
+ try {
+ this.places.broadcast(tripId, 'place:created', { place }, socketId);
+ } catch {
+ this.logger.warn(`Committed GPX place ${place.id}: realtime notification failed`);
+ }
+ }
+ return { tours, caution: tours.some(t => t.caution), skipped: result.skipped };
+ }
+}
diff --cc server/src/nest/trips/trips.service.ts
index 43b680520,8207a0a5f..2e67d8dfc
--- a/server/src/nest/trips/trips.service.ts
+++ b/server/src/nest/trips/trips.service.ts
@@@ -1,6 -1,28 +1,31 @@@
import { Injectable } from '@nestjs/common';
import path from 'path';
- import { DatabaseService } from '../database/database.service';
+ import { EntityManager } from '@mikro-orm/core';
+ import { Trips } from '../../db/entities/Trips.entity';
+ import { Days } from '../../db/entities/Days.entity';
+ import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
+ import { Users } from '../../db/entities/Users.entity';
+ import { Places } from '../../db/entities/Places.entity';
+ import { DayAssignments } from '../../db/entities/DayAssignments.entity';
+ import { AssignmentParticipants } from '../../db/entities/AssignmentParticipants.entity';
+ import { Tags } from '../../db/entities/Tags.entity';
+ import { DayNotes } from '../../db/entities/DayNotes.entity';
+ import { RoadtripVias } from '../../db/entities/RoadtripVias.entity';
+ import { RoadtripDayTracks } from '../../db/entities/RoadtripDayTracks.entity';
+ import { RoadtripPreferences } from '../../db/entities/RoadtripPreferences.entity';
+ import { RoadtripDayBoundaries } from '../../db/entities/RoadtripDayBoundaries.entity';
+ import { DayAccommodations } from '../../db/entities/DayAccommodations.entity';
+ import { Reservations } from '../../db/entities/Reservations.entity';
+ import { BudgetItems } from '../../db/entities/BudgetItems.entity';
+ import { BudgetItemMembers } from '../../db/entities/BudgetItemMembers.entity';
+ import { BudgetItemPayers } from '../../db/entities/BudgetItemPayers.entity';
+ import { BudgetCategoryOrder } from '../../db/entities/BudgetCategoryOrder.entity';
+ import { PackingBags } from '../../db/entities/PackingBags.entity';
+ import { PackingItems } from '../../db/entities/PackingItems.entity';
+ import { TodoItems } from '../../db/entities/TodoItems.entity';
++import { Tours } from '../../db/entities/Tours.entity';
++import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
++import type { TourWaypointRow } from '../../db/repositories/TourWaypoints.repository';
import {
MAX_TRIP_DAYS,
planDayGrid,
@@@ -165,15 -221,117 +224,127 @@@ export class TripsService
return typeof preferred === 'string' && preferred.trim() ? preferred.trim() : 'EUR';
}
- canAccessTrip(tripId: string | number, userId: number) {
- return this.dbs.canAccessTrip(tripId, userId) as { user_id: number } | null | undefined;
+ // Plan 3g Task 4 (TP32/TP33) — `journey_entries`' trip-wide skeleton
+ // cleanup/detach, reached the same `this.em.getRepository(...)` way as
+ // `tripsRepo`/`daysRepo` above.
+ private get journeyEntriesRepo() {
+ return this.em.getRepository(JourneyEntries);
+ }
+
+ // Plan 3c Task 8 (`copy`'s own 6 owned tables): resolved the same way
+ // `tripsRepo`/`daysRepo` above are — `this.em.getRepository(...)`, not a
+ // new constructor parameter.
+ private get placesRepo() {
+ return this.em.getRepository(Places);
+ }
+
+ private get dayAssignmentsRepo() {
+ return this.em.getRepository(DayAssignments);
+ }
+
+ private get assignmentParticipantsRepo() {
+ return this.em.getRepository(AssignmentParticipants);
+ }
+
+ private get tagsRepo() {
+ return this.em.getRepository(Tags);
+ }
+
+ private get dayNotesRepo() {
+ return this.em.getRepository(DayNotes);
+ }
+
+ // Plan 3d Task 6 (`copy`'s 11 survivors — roadtrip vias/tracks/preferences/
+ // boundaries, day_accommodations, reservations): same `this.em
+ // .getRepository(...)` pattern as the Task 8 getters above, not a new
+ // constructor parameter.
+ private get roadtripViasRepo() {
+ return this.em.getRepository(RoadtripVias);
+ }
+
+ private get roadtripDayTracksRepo() {
+ return this.em.getRepository(RoadtripDayTracks);
+ }
+
+ private get roadtripPreferencesRepo() {
+ return this.em.getRepository(RoadtripPreferences);
+ }
+
+ private get roadtripDayBoundariesRepo() {
+ return this.em.getRepository(RoadtripDayBoundaries);
+ }
+
+ private get dayAccommodationsRepo() {
+ return this.em.getRepository(DayAccommodations);
+ }
+
+ // Plan 3d Task 7 whole-plan review (item 8/D4): TP58/TP59 (the
+ // reservations copy read/insert) moved onto `ReservationsRepository` —
+ // the table they read/write — out of `ReservationEndpointsRepository`,
+ // where they used to live only because Task 4 owned this file for the
+ // Task 6 tree window. Same `this.em.getRepository(...)` pattern as every
+ // other getter above.
+ private get reservationsRepo() {
+ return this.em.getRepository(Reservations);
+ }
+
+ // Plan 3e Task 2 (budget) — TP60-65/74-75 only (the budget-family rows of
+ // `copy`'s 14 survivors; TP66-69/packing and TP72-73/todo are Tasks 3/4's).
+ // Same `this.em.getRepository(...)` pattern as every getter above.
+ private get budgetItemsRepo() {
+ return this.em.getRepository(BudgetItems);
+ }
+
+ private get budgetItemMembersRepo() {
+ return this.em.getRepository(BudgetItemMembers);
+ }
+
+ private get budgetItemPayersRepo() {
+ return this.em.getRepository(BudgetItemPayers);
+ }
+
+ private get budgetCategoryOrderRepo() {
+ return this.em.getRepository(BudgetCategoryOrder);
+ }
+
+ // Plan 3e Task 3 (packing) — TP66-69 only (the packing-family rows of
+ // `copy`'s 14 survivors). Same `this.em.getRepository(...)` pattern as
+ // every getter above.
+ private get packingBagsRepo() {
+ return this.em.getRepository(PackingBags);
+ }
+
+ private get packingItemsRepo() {
+ return this.em.getRepository(PackingItems);
+ }
+
+ // Plan 3e Task 4 (todo) — TP72-73 only (the todo-family rows of `copy`'s
+ // 14 survivors). Same `this.em.getRepository(...)` pattern as every
+ // getter above.
+ private get todoItemsRepo() {
+ return this.em.getRepository(TodoItems);
}
- isOwner(tripId: string | number, userId: number): boolean {
- return this.dbs.isOwner(tripId, userId);
++ // Tours (#2586): a Tour's facet row and its route waypoints, copied with
++ // the place they hang off. Same `this.em.getRepository(...)` pattern.
++ private get toursRepo() {
++ return this.em.getRepository(Tours);
+ }
+
- can(action: string, role: string, ownerId: number | null, userId: number, isMember: boolean): boolean {
++ private get tourWaypointsRepo() {
++ return this.em.getRepository(TourWaypoints);
++ }
++
+ async canAccessTrip(tripId: string | number, userId: number) {
+ const access = await this.em.getRepository(Trips).findAccessible(tripId, userId);
+ return access as { user_id: number } | null | undefined;
+ }
+
+ async isOwner(tripId: string | number, userId: number): Promise<boolean> {
+ return await this.em.getRepository(Trips).isOwner(tripId, userId);
+ }
+
+ async can(action: string, role: string, ownerId: number | null, userId: number, isMember: boolean): Promise<boolean> {
return this.permissions.checkPermission(action, role, ownerId, userId, isMember);
}
@@@ -506,8 -649,8 +662,9 @@@
// ── Copy / duplicate ─────────────────────────────────────────────────────
/**
-- * Duplicates a trip (all days, places, assignments, accommodations, reservations,
-- * budget, packing bags/items, day notes) into a new trip owned by `newOwnerId`.
++ * Duplicates a trip (all days, places with their Tour facets and waypoints,
++ * assignments, accommodations, reservations, budget, packing bags/items, day
++ * notes) into a new trip owned by `newOwnerId`.
* Cross-links are remapped to the copied rows (reservation↔budget item,
* reservation↔accommodation) and split data travels with the copy
* (budget_item_members/payers incl. paid flags, assignment_participants).
@@@ -581,26 -721,22 +735,47 @@@
// the row rather than point it at the original, the way the assignment
// and accommodation loops below skip an id they cannot map.
const newPlaceId = placeMap.get(t.place_id);
- if (newDayId && newPlaceId) insertTrack.run(newDayId, newPlaceId, t.stray_km);
+ // `upsertTrack`'s ON CONFLICT branch never fires on this call path:
+ // `newDayId` is a day that was just inserted into the brand-new trip
+ // above, so no `roadtrip_day_tracks` row can already exist for it —
+ // a plain INSERT (the legacy statement) and this upsert produce the
+ // identical single row.
+ if (newDayId && newPlaceId) await this.roadtripDayTracksRepo.upsertTrack(newDayId, newPlaceId, t.stray_km); // TP45
}
- const oldTags = this.db.prepare(`
- SELECT pt.* FROM place_tags pt JOIN places p ON p.id = pt.place_id WHERE p.trip_id = ?
- `).all(sourceTripId) as any[];
- const insertTag = this.db.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)');
+ const oldTags = await this.tagsRepo.listPlaceTagsForTrip(sourceTripId); // TP46
for (const t of oldTags) {
const newPlaceId = placeMap.get(t.place_id);
- if (newPlaceId) insertTag.run(newPlaceId, t.tag_id);
+ if (newPlaceId) await this.tagsRepo.insertIgnore(newPlaceId, [t.tag_id]); // TP47
+ }
+
++ // A Tour is a place plus its `tours` facet and the waypoints its route was
++ // planned through. Without them the copy holds an ordinary place with a
++ // line on it: no longer listed as a Tour, and its route can't be edited
++ // because the points it was drawn from are gone. The facet row goes first,
++ // since the waypoints reference it.
++ const oldTours = await this.toursRepo.listRowsForTrip(Number(sourceTripId));
++ const copiedTours = new Set<number>();
++ for (const { place_id, ...tour } of oldTours) {
++ const newPlaceId = placeMap.get(place_id);
++ if (!newPlaceId) continue;
++ await this.toursRepo.insertCopy(newPlaceId, tour);
++ copiedTours.add(place_id);
+ }
+
- const oldAssignments = this.db.prepare(`
- SELECT da.* FROM day_assignments da JOIN days d ON d.id = da.day_id WHERE d.trip_id = ?
- `).all(sourceTripId) as any[];
- const assignmentMap = new Map<number, number | bigint>();
- const insertAssignment = this.db.prepare(`
- INSERT INTO day_assignments (day_id, place_id, order_index, notes, reservation_status, reservation_notes, reservation_datetime, assignment_time, assignment_end_time, end_day)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- `);
++ const waypointsByPlace = new Map<number, TourWaypointRow[]>();
++ for (const { place_id, ...waypoint } of await this.tourWaypointsRepo.listForTrip(Number(sourceTripId))) {
++ if (!copiedTours.has(place_id)) continue;
++ const list = waypointsByPlace.get(place_id) ?? [];
++ list.push(waypoint);
++ waypointsByPlace.set(place_id, list);
++ }
++ for (const [placeId, waypoints] of waypointsByPlace) {
++ await this.tourWaypointsRepo.insertForPlace(placeMap.get(placeId)!, waypoints);
++ }
++
+ const oldAssignments = await this.dayAssignmentsRepo.listAllForTrip(sourceTripId); // TP48
+ const assignmentMap = new Map<number, number>();
for (const a of oldAssignments) {
const newDayId = dayMap.get(a.day_id);
const newPlaceId = placeMap.get(a.place_id);
diff --cc server/tests/e2e/assignments.e2e.test.ts
index 902768d3c,4c9c3e905..8b1743055
--- a/server/tests/e2e/assignments.e2e.test.ts
+++ b/server/tests/e2e/assignments.e2e.test.ts
@@@ -150,47 -113,6 +113,47 @@@ describe('Assignments e2e (real auth gu
});
});
+ it('200 list projects Tour facets once per assignment and leaves other tracks ordinary', async () => {
+ const legacyGeometry = JSON.stringify([[48, 11, 600], [48.01, 11.02, 650]]);
+ const tourGeometry = JSON.stringify([[48.02, 11.03, 700], [48.03, 11.04, 750]]);
+ db.prepare('INSERT INTO places (id, trip_id, name, route_geometry) VALUES (3, 5, ?, ?), (4, 5, ?, ?)')
+ .run('Legacy track', legacyGeometry, 'Tour', tourGeometry);
- db.prepare('INSERT INTO tours (place_id) VALUES (4)').run();
++ db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (4, 'hike')").run();
+ const assignmentIds = [
+ seedAssignment(3, 2, 0),
+ seedAssignment(3, 3, 1),
+ seedAssignment(3, 4, 2),
+ seedAssignment(3, 4, 3),
+ ];
+
+ const res = await request(server).get('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1));
+
+ expect(res.status).toBe(200);
+ const assignments = res.body.assignments as Array<{
+ id: number;
+ place_id: number;
+ order_index: number;
+ tour_place_id: number | null;
+ tour_route_geometry: string | null;
+ }>;
+ expect(assignments).toHaveLength(4);
+ expect(assignments.map(a => a.id)).toEqual(assignmentIds);
+ expect(assignments.map(a => a.order_index)).toEqual([0, 1, 2, 3]);
+ expect(assignments[0]).toMatchObject({ place_id: 2, tour_place_id: null, tour_route_geometry: null });
+ expect(db.prepare('SELECT route_geometry FROM places WHERE id = 3').get()).toEqual({ route_geometry: legacyGeometry });
+ expect(db.prepare('SELECT place_id FROM tours WHERE place_id = 3').get()).toBeUndefined();
+ expect(db.prepare('SELECT place_id FROM tours WHERE place_id = 4').get()).toEqual({ place_id: 4 });
+ expect(assignments[1]).toMatchObject({ place_id: 3, tour_place_id: null, tour_route_geometry: null });
+ expect(assignments.slice(2).map(a => ({
+ place_id: a.place_id,
+ tour_place_id: a.tour_place_id,
+ tour_route_geometry: a.tour_route_geometry,
+ }))).toEqual([
+ { place_id: 4, tour_place_id: 4, tour_route_geometry: tourGeometry },
+ { place_id: 4, tour_place_id: 4, tour_route_geometry: tourGeometry },
+ ]);
+ });
+
it('201 create, 404 place', async () => {
reconcileTripSkeletons.mockClear();
const ok = await request(server).post('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1)).send({ place_id: 2 });
@@@ -204,38 -126,6 +167,38 @@@
expect(miss.body).toEqual({ error: 'Place not found' });
});
+ it('prevents duplicate Tour/day assignments through concurrent REST requests', async () => {
+ const tourPlaceId = 20;
+ db.prepare('INSERT INTO places (id, trip_id, name) VALUES (?, 5, ?)').run(tourPlaceId, 'Ridge walk');
- db.prepare('INSERT INTO tours (place_id) VALUES (?)').run(tourPlaceId);
++ db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')").run(tourPlaceId);
+ try {
+ const createTourAssignment = () => request(server)
+ .post('/api/trips/5/days/3/assignments')
+ .set('Cookie', sessionCookie(1))
+ .send({ place_id: tourPlaceId });
+ const results = await Promise.all([createTourAssignment(), createTourAssignment()]);
+
+ expect(results.map(result => result.status).sort()).toEqual([201, 409]);
+ expect(db.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = 3 AND place_id = ?').get(tourPlaceId)).toEqual({ n: 1 });
+
+ const otherDay = await request(server).post('/api/trips/5/days/4/assignments')
+ .set('Cookie', sessionCookie(1)).send({ place_id: tourPlaceId });
+ expect(otherDay.status).toBe(201);
+ expect(db.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE place_id = ?').get(tourPlaceId)).toEqual({ n: 2 });
+
+ const firstOrdinary = await request(server).post('/api/trips/5/days/3/assignments')
+ .set('Cookie', sessionCookie(1)).send({ place_id: 2 });
+ const secondOrdinary = await request(server).post('/api/trips/5/days/3/assignments')
+ .set('Cookie', sessionCookie(1)).send({ place_id: 2 });
+ expect(firstOrdinary.status).toBe(201);
+ expect(secondOrdinary.status).toBe(201);
+ } finally {
+ db.prepare('DELETE FROM day_assignments WHERE place_id = ?').run(tourPlaceId);
+ db.prepare('DELETE FROM tours WHERE place_id = ?').run(tourPlaceId);
+ db.prepare('DELETE FROM places WHERE id = ?').run(tourPlaceId);
+ }
+ });
+
it('200 delete assignment reconciles journey skeletons', async () => {
reconcileTripSkeletons.mockClear();
const id = seedAssignment();
@@@ -293,6 -183,6 +256,34 @@@
expect(reconcileTripSkeletons).toHaveBeenCalledWith(5, undefined);
});
++ it('409 moving a Tour onto a day that already holds it, the row stays put; a reorder within its day still works', async () => {
++ const tourPlaceId = 21;
++ db.prepare('INSERT INTO places (id, trip_id, name) VALUES (?, 5, ?)').run(tourPlaceId, 'Lake loop');
++ db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')").run(tourPlaceId);
++ try {
++ seedAssignment(4, tourPlaceId, 0);
++ const moving = seedAssignment(3, tourPlaceId, 0);
++ const conflict = await request(server)
++ .put(`/api/trips/5/assignments/${moving}/move`)
++ .set('Cookie', sessionCookie(1))
++ .send({ new_day_id: 4, order_index: 1 });
++ expect(conflict.status).toBe(409);
++ expect(conflict.body).toEqual({ error: 'Tour is already assigned to this day' });
++ expect(db.prepare('SELECT day_id, order_index FROM day_assignments WHERE id = ?').get(moving)).toEqual({ day_id: 3, order_index: 0 });
++
++ const reorder = await request(server)
++ .put(`/api/trips/5/assignments/${moving}/move`)
++ .set('Cookie', sessionCookie(1))
++ .send({ new_day_id: 3, order_index: 2 });
++ expect(reorder.status).toBe(200);
++ expect(reorder.body.assignment).toMatchObject({ id: moving, day_id: 3, order_index: 2, tour_place_id: tourPlaceId });
++ } finally {
++ db.prepare('DELETE FROM day_assignments WHERE place_id = ?').run(tourPlaceId);
++ db.prepare('DELETE FROM tours WHERE place_id = ?').run(tourPlaceId);
++ db.prepare('DELETE FROM places WHERE id = ?').run(tourPlaceId);
++ }
++ });
++
it('200 notes roundtrip: create with note, PUT edits it, GET list shows the new value (#2163)', async () => {
const create = await request(server).post('/api/trips/5/days/3/assignments').set('Cookie', sessionCookie(1))
.send({ place_id: 2, notes: 'Book the 10:00 timed entry' });
diff --cc server/tests/e2e/days.e2e.test.ts
index a2db899ca,b7e671ab3..61910558f
--- a/server/tests/e2e/days.e2e.test.ts
+++ b/server/tests/e2e/days.e2e.test.ts
@@@ -158,45 -97,6 +98,45 @@@ describe('Days + day-notes e2e (real au
expect(res.body.days[0]).toMatchObject({ id: 3, trip_id: 5, day_number: 1, assignments: [], notes_items: [] });
});
+ it('200 list projects Tour facets once per assignment and leaves other tracks ordinary', async () => {
+ const legacyGeometry = JSON.stringify([[48, 11, 600], [48.01, 11.02, 650]]);
+ const tourGeometry = JSON.stringify([[48.02, 11.03, 700], [48.03, 11.04, 750]]);
+ db.prepare('INSERT INTO places (id, trip_id, name, route_geometry) VALUES (2, 5, ?, ?), (3, 5, ?, ?), (4, 5, ?, ?)')
+ .run('Ordinary', null, 'Legacy track', legacyGeometry, 'Tour', tourGeometry);
- db.prepare('INSERT INTO tours (place_id) VALUES (4)').run();
++ db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (4, 'hike')").run();
+ const assignmentIds = [2, 3, 4, 4].map((placeId, orderIndex) => Number(
+ db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (3, ?, ?)')
+ .run(placeId, orderIndex).lastInsertRowid,
+ ));
+
+ const res = await request(server).get('/api/trips/5/days').set('Cookie', sessionCookie(1));
+
+ expect(res.status).toBe(200);
+ const assignments = res.body.days[0].assignments as Array<{
+ id: number;
+ order_index: number;
+ tour_place_id: number | null;
+ tour_route_geometry: string | null;
+ place: { id: number };
+ }>;
+ expect(assignments).toHaveLength(4);
+ expect(assignments.map(a => a.id)).toEqual(assignmentIds);
+ expect(assignments.map(a => a.order_index)).toEqual([0, 1, 2, 3]);
+ expect(assignments[0]).toMatchObject({ place: { id: 2 }, tour_place_id: null, tour_route_geometry: null });
+ expect(db.prepare('SELECT route_geometry FROM places WHERE id = 3').get()).toEqual({ route_geometry: legacyGeometry });
+ expect(db.prepare('SELECT place_id FROM tours WHERE place_id = 3').get()).toBeUndefined();
+ expect(db.prepare('SELECT place_id FROM tours WHERE place_id = 4').get()).toEqual({ place_id: 4 });
+ expect(assignments[1]).toMatchObject({ place: { id: 3 }, tour_place_id: null, tour_route_geometry: null });
+ expect(assignments.slice(2).map(a => ({
+ place_id: a.place.id,
+ tour_place_id: a.tour_place_id,
+ tour_route_geometry: a.tour_route_geometry,
+ }))).toEqual([
+ { place_id: 4, tour_place_id: 4, tour_route_geometry: tourGeometry },
+ { place_id: 4, tour_place_id: 4, tour_route_geometry: tourGeometry },
+ ]);
+ });
+
it('201 create day (real insert, auto day_number), 404 trip when not accessible', async () => {
const ok = await request(server).post('/api/trips/5/days').set('Cookie', sessionCookie(1)).send({ date: '2026-07-01' });
expect(ok.status).toBe(201);
diff --cc server/tests/e2e/places.e2e.test.ts
index 0e38c66af,2aa708ddb..24b4cb123
--- a/server/tests/e2e/places.e2e.test.ts
+++ b/server/tests/e2e/places.e2e.test.ts
@@@ -146,18 -116,6 +116,18 @@@ describe('Places e2e (real auth guard
expect(res.body.places[0]).toMatchObject({ id: 1, name: 'Spot', trip_id: 5, tags: [], ratings: [] });
});
+ it('marks Tour-backed Places without changing ordinary Place rows', async () => {
+ db.prepare("INSERT INTO places (id, trip_id, name) VALUES (1, 5, 'Plain'), (2, 5, 'Tour')").run();
- db.prepare('INSERT INTO tours (place_id) VALUES (2)').run();
++ db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (2, 'hike')").run();
+
+ const all = await request(server).get('/api/trips/5/places').set('Cookie', sessionCookie(1));
+ expect(all.status).toBe(200);
+ expect(all.body.places).toHaveLength(2);
+ const tourPlaceIdById = new Map(all.body.places.map((place: { id: number; tour_place_id: number | null }) => [place.id, place.tour_place_id]));
+ expect(tourPlaceIdById.get(1)).toBeNull();
+ expect(tourPlaceIdById.get(2)).toBe(2);
+ });
+
it('200 list scoped to the trip', async () => {
db.prepare("INSERT INTO places (trip_id, name) VALUES (5, 'Mine')").run();
db.prepare("INSERT INTO places (trip_id, name) VALUES (6, 'Theirs')").run();
@@@ -182,10 -140,11 +152,11 @@@
});
it('200 (not 201) bulk-delete, 400 on bad ids', async () => {
- db.prepare("INSERT INTO places (id, trip_id, name) VALUES (1, 5, 'A'), (2, 5, 'B'), (3, 6, 'Foreign')").run();
+ db.prepare("INSERT INTO places (id, trip_id, name) VALUES (1, 5, 'A'), (2, 5, 'B')").run();
+ db.prepare("INSERT INTO places (id, trip_id, name) VALUES (3, 6, 'Foreign')").run();
const ok = await request(server).post('/api/trips/5/places/bulk-delete').set('Cookie', sessionCookie(1)).send({ ids: [1, 2, 3] });
expect(ok.status).toBe(200);
- expect(ok.body).toEqual({ deleted: [1, 2], count: 2 });
+ expect(ok.body).toEqual({ deleted: [1, 2], count: 2, tourPlaceIds: [] });
// The foreign trip's place is untouched.
expect(db.prepare('SELECT id FROM places ORDER BY id').all()).toEqual([{ id: 3 }]);
@@@ -319,6 -279,6 +291,20 @@@
expect(foreign.body).toEqual({ error: 'Place not found' });
});
++ it('DELETE :id and bulk-delete report the Tour place ids they removed', async () => {
++ db.prepare("INSERT INTO places (id, trip_id, name) VALUES (20, 5, 'Tour A'), (21, 5, 'Tour B'), (22, 5, 'Plain')").run();
++ db.prepare("INSERT INTO tours (place_id, tour_type) VALUES (20, 'hike'), (21, 'hike')").run();
++
++ const single = await request(server).delete('/api/trips/5/places/20').set('Cookie', sessionCookie(1));
++ expect(single.status).toBe(200);
++ expect(single.body).toEqual({ success: true, tourPlaceIds: [20] });
++ expect(db.prepare('SELECT place_id FROM tours WHERE place_id = 20').get()).toBeUndefined();
++
++ const bulk = await request(server).post('/api/trips/5/places/bulk-delete').set('Cookie', sessionCookie(1)).send({ ids: [21, 22] });
++ expect(bulk.status).toBe(200);
++ expect(bulk.body).toEqual({ deleted: [21, 22], count: 2, tourPlaceIds: [21] });
++ });
++
it('DELETE :id takes the expense linked to the place with it (#1298)', async () => {
db.prepare("INSERT INTO places (id, trip_id, name) VALUES (12, 5, 'Louvre')").run();
db.prepare("INSERT INTO budget_items (id, trip_id, name, total_price, place_id) VALUES (44, 5, 'Tickets', 34, 12)").run();
diff --cc server/tests/e2e/tours.e2e.test.ts
index 000000000,000000000..d309edf41
new file mode 100644
--- /dev/null
+++ b/server/tests/e2e/tours.e2e.test.ts
@@@ -1,0 -1,0 +1,443 @@@
++/**
++ * Tours module e2e: every /api/trips/:tripId/tours endpoint through the real
++ * JwtAuthGuard, AddonGuard and TripAccessGuard against a real migrated and
++ * seeded temp SQLite db (createSnapshotTestDb()). ToursService, PlacesService,
++ * AssignmentsService and TripsService run their real SQL; only the permission
++ * check (a container spy), the journey hooks and the WebSocket broadcast are
++ * stubbed.
++ *
++ * Fixtures: user 1 owns trips 5 and 6, user 2 is a member of trip 5 whom the
++ * permission spy denies 'place_edit', user 3 has no access to either trip.
++ * AssignmentsModule and TripsModule are mounted next to ToursModule so the
++ * one-tour-per-day 409 on move and the trip copy run through their real routes.
++ */
++import { describe, it, expect, beforeAll, afterAll, beforeEach, vi, type MockInstance } from 'vitest';
++import request from 'supertest';
++import cookieParser from 'cookie-parser';
++import type { Server } from 'http';
++import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
++import { Test } from '@nestjs/testing';
++import { sessionCookie } from './harness';
++
++vi.mock('../../src/db/database', async () => {
++ const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
++ return buildDbMock(createSnapshotTestDb());
++});
++const { broadcast } = vi.hoisted(() => ({ broadcast: vi.fn() }));
++vi.mock('../../src/websocket', () => ({ broadcast }));
++vi.mock('../../src/nest/audit/audit-log.logger', () => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logDebug: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
++
++import { db } from '../../src/db/database';
++
++const { journeyHooks } = vi.hoisted(() => ({
++ journeyHooks: {
++ reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
++ onPlaceCreated: vi.fn().mockResolvedValue(undefined),
++ onPlaceUpdated: vi.fn().mockResolvedValue(undefined),
++ onPlaceDeleted: vi.fn().mockResolvedValue(undefined),
++ },
++}));
++import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
++import { PermissionsService } from '../../src/nest/permissions/permissions.service';
++import { BudgetService } from '../../src/nest/budget/budget.service';
++import { ToursModule } from '../../src/nest/tours/tours.module';
++import { AssignmentsModule } from '../../src/nest/assignments/assignments.module';
++import { TripsModule } from '../../src/nest/trips/trips.module';
++import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
++import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
++import { TestUnitOfWorkModule } from '../helpers/test-uow';
++import { createTestMikroOrmModule } from '../helpers/test-orm';
++
++let checkPermission: MockInstance;
++
++const OWNER = 1;
++const VIEWER = 2;
++const OUTSIDER = 3;
++
++const GEOMETRY = [[47, 11, 600], [47.01, 11.01, 700], [47.02, 11.02, 650]];
++const tourBody = (overrides: Record<string, unknown> = {}) => ({
++ name: 'Ridge walk',
++ route_geometry: GEOMETRY,
++ waypoints: [
++ { lat: 47, lng: 11, role: 'start', sequence: 0 },
++ { lat: 47.02, lng: 11.02, role: 'end', sequence: 1 },
++ ],
++ max_hiking_difficulty: 3,
++ duration_seconds: 3600,
++ ...overrides,
++});
++
++const TRACK_GPX = `<?xml version="1.0"?>
++<gpx version="1.1" creator="e2e"><trk><name>Alpine loop</name><trkseg>
++ <trkpt lat="49" lon="12"><ele>100</ele></trkpt>
++ <trkpt lat="49.01" lon="12.01"><ele>150</ele></trkpt>
++ <trkpt lat="49.02" lon="12.02"><ele>120</ele></trkpt>
++</trkseg></trk></gpx>`;
++const FLAT_GPX = `<?xml version="1.0"?>
++<gpx version="1.1" creator="e2e"><trk><name>Flat path</name><trkseg>
++ <trkpt lat="50" lon="13"/><trkpt lat="50.01" lon="13.01"/>
++</trkseg></trk></gpx>`;
++// Large enough that a guard rejecting before multer drained the body would
++// surface as a connection reset instead of a JSON response.
++const BIG_GPX = TRACK_GPX.replace('</gpx>', `<!-- ${'x'.repeat(512 * 1024)} --></gpx>`);
++
++describe('Tours e2e (real guards + temp SQLite)', () => {
++ let server: Server;
++ let app: Awaited<ReturnType<typeof build>>;
++
++ async function build() {
++ const moduleRef = await Test.createTestingModule({
++ imports: [
++ await TestUnitOfWorkModule.forRoot(db),
++ await createTestMikroOrmModule(db),
++ RealtimeModule,
++ ToursModule,
++ AssignmentsModule,
++ TripsModule,
++ ],
++ })
++ .overrideProvider(JourneyDomainService)
++ .useValue(journeyHooks)
++ .compile();
++ const nest = moduleRef.createNestApplication();
++ nest.use(cookieParser());
++ nest.useGlobalPipes(new ZodValidationPipe());
++ nest.useGlobalFilters(new TrekExceptionFilter());
++ await nest.init();
++ return nest;
++ }
++
++ const setAddon = (enabled: boolean) =>
++ db.prepare("UPDATE addons SET enabled = ? WHERE id = 'tours'").run(enabled ? 1 : 0);
++
++ const createViaApi = async (tripId = 5, body: Record<string, unknown> = tourBody()) => {
++ const res = await request(server).post(`/api/trips/${tripId}/tours`).set('Cookie', sessionCookie(OWNER)).send(body);
++ expect(res.status).toBe(201);
++ return res.body.tour.place_id as number;
++ };
++
++ const importGpx = (userId: number, xml: string | null, tripId = 5) => {
++ const req = request(server).post(`/api/trips/${tripId}/tours/import/gpx`).set('Cookie', sessionCookie(userId));
++ return xml === null ? req.field('note', 'none') : req.attach('file', Buffer.from(xml), { filename: 'track.gpx', contentType: 'application/gpx+xml' });
++ };
++
++ beforeAll(async () => {
++ db.prepare(`INSERT INTO users (id, username, email, password_hash, role, password_version) VALUES
++ (1, 'owner', '[email protected]', 'x', 'user', 0),
++ (2, 'viewer', '[email protected]', 'x', 'user', 0),
++ (3, 'outsider', '[email protected]', 'x', 'user', 0)`).run();
++ db.prepare("INSERT INTO trips (id, user_id, title) VALUES (5, 1, 'Alps'), (6, 1, 'Other')").run();
++ db.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (5, 2)').run();
++ db.prepare('INSERT INTO days (id, trip_id, day_number) VALUES (3, 5, 1), (4, 5, 2)').run();
++ app = await build();
++ checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
++ vi.spyOn(app.get(BudgetService), 'listBudgetItems').mockResolvedValue([]);
++ server = app.getHttpServer();
++ });
++
++ beforeEach(() => {
++ // The viewer is a trip member whose 'place_edit' is withheld; every other
++ // action and user passes, so the owner can create, move and copy.
++ checkPermission.mockImplementation((action: string, _role: string, _owner: number, userId: number) =>
++ !(action === 'place_edit' && userId === VIEWER));
++ setAddon(true);
++ broadcast.mockClear();
++ db.prepare('DELETE FROM day_assignments').run();
++ db.prepare('DELETE FROM places').run();
++ db.prepare('DELETE FROM trips WHERE id NOT IN (5, 6)').run();
++ });
++
++ afterAll(async () => {
++ await app.close();
++ });
++
++ describe('addon and access gates', () => {
++ it('401 without a cookie', async () => {
++ expect((await request(server).get('/api/trips/5/tours')).status).toBe(401);
++ });
++
++ it('404 on every route while the addon is disabled', async () => {
++ const placeId = await createViaApi();
++ setAddon(false);
++ const off = { error: 'Tours addon is not enabled' };
++ const cookie = sessionCookie(OWNER);
++ const responses = [
++ await request(server).get('/api/trips/5/tours').set('Cookie', cookie),
++ await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie),
++ await request(server).post('/api/trips/5/tours').set('Cookie', cookie).send(tourBody()),
++ await request(server).put(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie).send(tourBody({ name: 'Renamed' })),
++ await importGpx(OWNER, BIG_GPX),
++ ];
++ for (const res of responses) {
++ expect(res.status).toBe(404);
++ expect(res.body).toEqual(off);
++ }
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tours').get()).toEqual({ n: 1 });
++ expect(db.prepare('SELECT name FROM places WHERE id = ?').get(placeId)).toEqual({ name: 'Ridge walk' });
++ });
++
++ it('404 Trip not found for a user without access to the trip', async () => {
++ const placeId = await createViaApi();
++ const cookie = sessionCookie(OUTSIDER);
++ const responses = [
++ await request(server).get('/api/trips/5/tours').set('Cookie', cookie),
++ await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie),
++ await request(server).post('/api/trips/5/tours').set('Cookie', cookie).send(tourBody()),
++ await request(server).put(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie).send(tourBody()),
++ await importGpx(OUTSIDER, BIG_GPX),
++ await request(server).get('/api/trips/999/tours').set('Cookie', sessionCookie(OWNER)),
++ ];
++ for (const res of responses) {
++ expect(res.status).toBe(404);
++ expect(res.body).toEqual({ error: 'Trip not found' });
++ }
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tours').get()).toEqual({ n: 1 });
++ });
++
++ it('a member without place_edit can read but gets 403 on every write', async () => {
++ const placeId = await createViaApi();
++ const cookie = sessionCookie(VIEWER);
++
++ const list = await request(server).get('/api/trips/5/tours').set('Cookie', cookie);
++ expect(list.status).toBe(200);
++ expect(list.body.tours).toHaveLength(1);
++ expect((await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie)).status).toBe(200);
++
++ const writes = [
++ await request(server).post('/api/trips/5/tours').set('Cookie', cookie).send(tourBody()),
++ await request(server).put(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie).send(tourBody({ name: 'Hijacked' })),
++ await importGpx(VIEWER, BIG_GPX),
++ ];
++ for (const res of writes) {
++ expect(res.status).toBe(403);
++ expect(res.body).toEqual({ error: 'No permission' });
++ }
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tours').get()).toEqual({ n: 1 });
++ expect(db.prepare('SELECT name FROM places WHERE id = ?').get(placeId)).toEqual({ name: 'Ridge walk' });
++ });
++ });
++
++ describe('POST and GET', () => {
++ it('201 creates the place, the facet and its waypoints, then lists and reads them back', async () => {
++ const res = await request(server)
++ .post('/api/trips/5/tours')
++ .set('Cookie', sessionCookie(OWNER))
++ .set('X-Socket-Id', 'sock-1')
++ .send(tourBody());
++ expect(res.status).toBe(201);
++ const placeId = res.body.tour.place_id as number;
++ expect(res.body.tour).toMatchObject({
++ place_id: placeId, name: 'Ridge walk', tour_type: 'hike', duration: 60, match_confidence: 1,
++ max_hiking_difficulty: 3, planned: false, caution: false, has_waypoints: true,
++ });
++ expect(res.body.tour.distance).toBeGreaterThan(0);
++ expect(res.body.tour.elevation_gain).toBe(100);
++ expect(res.body.tour.elevation_loss).toBe(50);
++ expect(res.body.waypoints).toEqual(tourBody().waypoints);
++
++ expect(db.prepare('SELECT trip_id, lat, lng, transport_mode, route_geometry FROM places WHERE id = ?').get(placeId)).toEqual({
++ trip_id: 5, lat: 47, lng: 11, transport_mode: 'walking', route_geometry: JSON.stringify(GEOMETRY),
++ });
++ const events = broadcast.mock.calls.map(c => c[1]);
++ expect(events).toEqual(expect.arrayContaining(['tours:changed', 'place:created']));
++ expect(broadcast.mock.calls.every(c => c[3] === 'sock-1')).toBe(true);
++
++ const list = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(OWNER));
++ expect(list.status).toBe(200);
++ expect(list.body.tours).toEqual([res.body.tour]);
++
++ const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
++ expect(detail.status).toBe(200);
++ expect(detail.body).toEqual(res.body);
++ });
++
++ it('lists newest first and reports planned once a day holds the tour', async () => {
++ const first = await createViaApi(5, tourBody({ name: 'First' }));
++ const second = await createViaApi(5, tourBody({ name: 'Second' }));
++ db.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (3, ?, 0)').run(first);
++ const res = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(OWNER));
++ expect(res.body.tours.map((t: { place_id: number; planned: boolean }) => [t.place_id, t.planned])).toEqual([
++ [second, false],
++ [first, true],
++ ]);
++ });
++
++ it('400 for an invalid body, nothing written', async () => {
++ const cookie = sessionCookie(OWNER);
++ const badRole = await request(server).post('/api/trips/5/tours').set('Cookie', cookie).send(tourBody({
++ waypoints: [{ lat: 47, lng: 11, role: 'via', sequence: 0 }, { lat: 47.02, lng: 11.02, role: 'end', sequence: 1 }],
++ }));
++ expect(badRole.status).toBe(400);
++ const shortRoute = await request(server).post('/api/trips/5/tours').set('Cookie', cookie).send(tourBody({ route_geometry: [[47, 11, 600]] }));
++ expect(shortRoute.status).toBe(400);
++ const badDifficulty = await request(server).post('/api/trips/5/tours').set('Cookie', cookie).send(tourBody({ max_hiking_difficulty: 7 }));
++ expect(badDifficulty.status).toBe(400);
++ expect(db.prepare('SELECT COUNT(*) AS n FROM places').get()).toEqual({ n: 0 });
++ });
++
++ it('GET 404 for a tour of another trip, a plain place and a non-numeric id', async () => {
++ const foreign = await createViaApi(6);
++ const plain = Number(db.prepare("INSERT INTO places (trip_id, name) VALUES (5, 'Cafe')").run().lastInsertRowid);
++ for (const id of [foreign, plain, 'abc', 999999]) {
++ const res = await request(server).get(`/api/trips/5/tours/${id}`).set('Cookie', sessionCookie(OWNER));
++ expect(res.status).toBe(404);
++ expect(res.body).toEqual({ error: 'Tour not found' });
++ }
++ const list = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(OWNER));
++ expect(list.body.tours).toEqual([]);
++ });
++
++ it('GET falls back to the geometry endpoints for a tour without saved waypoints', async () => {
++ const res = await importGpx(OWNER, TRACK_GPX);
++ expect(res.status).toBe(201);
++ const placeId = res.body.tours[0].place_id as number;
++ const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
++ expect(detail.status).toBe(200);
++ expect(detail.body.tour).toMatchObject({ place_id: placeId, has_waypoints: false });
++ expect(detail.body.waypoints).toEqual([
++ { lat: 49, lng: 12, role: 'start', sequence: 0 },
++ { lat: 49.02, lng: 12.02, role: 'end', sequence: 1 },
++ ]);
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tour_waypoints WHERE place_id = ?').get(placeId)).toEqual({ n: 0 });
++ });
++ });
++
++ describe('PUT', () => {
++ it('200 replaces the route, metrics and waypoints', async () => {
++ const placeId = await createViaApi();
++ const geometry = [[46, 10, 1000], [46.01, 10.01, 1200], [46.02, 10.02, 1100]];
++ const waypoints = [
++ { lat: 46, lng: 10, role: 'start', sequence: 0 },
++ { lat: 46.01, lng: 10.01, role: 'via', sequence: 1 },
++ { lat: 46.02, lng: 10.02, role: 'end', sequence: 2 },
++ ];
++ const res = await request(server)
++ .put(`/api/trips/5/tours/${placeId}`)
++ .set('Cookie', sessionCookie(OWNER))
++ .send(tourBody({ name: 'Summit', route_geometry: geometry, waypoints, max_hiking_difficulty: 5, duration_seconds: null }));
++ expect(res.status).toBe(200);
++ expect(res.body.tour).toMatchObject({
++ place_id: placeId, name: 'Summit', elevation_gain: 200, elevation_loss: 100, duration: null, max_hiking_difficulty: 5,
++ });
++ expect(res.body.waypoints).toEqual(waypoints);
++ expect(db.prepare('SELECT name, lat, lng, route_geometry FROM places WHERE id = ?').get(placeId)).toEqual({
++ name: 'Summit', lat: 46, lng: 10, route_geometry: JSON.stringify(geometry),
++ });
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tour_waypoints WHERE place_id = ?').get(placeId)).toEqual({ n: 3 });
++ expect(broadcast.mock.calls.map(c => c[1])).toEqual(expect.arrayContaining(['tours:changed', 'place:updated']));
++ });
++
++ it('404 for a tour of another trip, a plain place and a non-numeric id, nothing changes', async () => {
++ const foreign = await createViaApi(6);
++ const plain = Number(db.prepare("INSERT INTO places (trip_id, name) VALUES (5, 'Cafe')").run().lastInsertRowid);
++ for (const id of [foreign, plain, 'abc']) {
++ const res = await request(server).put(`/api/trips/5/tours/${id}`).set('Cookie', sessionCookie(OWNER)).send(tourBody({ name: 'Moved' }));
++ expect(res.status).toBe(404);
++ expect(res.body).toEqual({ error: 'Tour not found' });
++ }
++ expect(db.prepare('SELECT trip_id, name FROM places WHERE id = ?').get(foreign)).toEqual({ trip_id: 6, name: 'Ridge walk' });
++ expect(db.prepare('SELECT name, route_geometry FROM places WHERE id = ?').get(plain)).toEqual({ name: 'Cafe', route_geometry: null });
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tours WHERE place_id = ?').get(plain)).toEqual({ n: 0 });
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tour_waypoints WHERE place_id = ?').get(foreign)).toEqual({ n: 2 });
++ });
++ });
++
++ describe('POST import/gpx', () => {
++ it('201 imports each track as a hike tour', async () => {
++ const res = await importGpx(OWNER, TRACK_GPX);
++ expect(res.status).toBe(201);
++ expect(res.body).toMatchObject({ caution: false, skipped: 0 });
++ expect(res.body.tours).toHaveLength(1);
++ const tour = res.body.tours[0];
++ expect(tour).toMatchObject({ name: 'Alpine loop', tour_type: 'hike', match_confidence: 1, max_hiking_difficulty: 2, has_waypoints: false });
++ expect(db.prepare('SELECT trip_id FROM places WHERE id = ?').get(tour.place_id)).toEqual({ trip_id: 5 });
++ expect(db.prepare('SELECT tour_type FROM tours WHERE place_id = ?').get(tour.place_id)).toEqual({ tour_type: 'hike' });
++ expect(broadcast.mock.calls.map(c => c[1])).toEqual(expect.arrayContaining(['tours:changed', 'place:created']));
++ });
++
++ it('flags a track without elevation with caution', async () => {
++ const res = await importGpx(OWNER, FLAT_GPX);
++ expect(res.status).toBe(201);
++ expect(res.body.caution).toBe(true);
++ expect(res.body.tours[0]).toMatchObject({ match_confidence: 0.3, caution: true });
++ });
++
++ it('a second import of the same track is skipped as a duplicate', async () => {
++ expect((await importGpx(OWNER, TRACK_GPX)).status).toBe(201);
++ const again = await importGpx(OWNER, TRACK_GPX);
++ expect(again.status).toBe(201);
++ expect(again.body).toEqual({ tours: [], caution: false, skipped: 1 });
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tours').get()).toEqual({ n: 1 });
++ });
++
++ it('400 without a file, and for a file with no track or route', async () => {
++ const missing = await importGpx(OWNER, null);
++ expect(missing.status).toBe(400);
++ expect(missing.body).toEqual({ error: 'No file uploaded' });
++ for (const xml of ['<not-gpx/>', '<gpx/>', '<gpx><wpt lat="1" lon="2"/></gpx>', 'plain text']) {
++ const res = await importGpx(OWNER, xml);
++ expect(res.status).toBe(400);
++ expect(res.body).toEqual({ error: 'No track or route found in GPX file' });
++ }
++ expect(db.prepare('SELECT COUNT(*) AS n FROM places').get()).toEqual({ n: 0 });
++ });
++ });
++
++ describe('other domains', () => {
++ it('409 moving a tour onto a day that already holds it, on create and on move', async () => {
++ const placeId = await createViaApi();
++ const cookie = sessionCookie(OWNER);
++ const onDay4 = await request(server).post('/api/trips/5/days/4/assignments').set('Cookie', cookie).send({ place_id: placeId });
++ expect(onDay4.status).toBe(201);
++ const onDay3 = await request(server).post('/api/trips/5/days/3/assignments').set('Cookie', cookie).send({ place_id: placeId });
++ expect(onDay3.status).toBe(201);
++
++ const twice = await request(server).post('/api/trips/5/days/4/assignments').set('Cookie', cookie).send({ place_id: placeId });
++ expect(twice.status).toBe(409);
++ expect(twice.body).toEqual({ error: 'Tour is already assigned to this day' });
++
++ const moving = onDay3.body.assignment.id as number;
++ const move = await request(server).put(`/api/trips/5/assignments/${moving}/move`).set('Cookie', cookie).send({ new_day_id: 4, order_index: 1 });
++ expect(move.status).toBe(409);
++ expect(move.body).toEqual({ error: 'Tour is already assigned to this day' });
++ expect(db.prepare('SELECT day_id FROM day_assignments WHERE id = ?').get(moving)).toEqual({ day_id: 3 });
++ expect(db.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE place_id = ?').get(placeId)).toEqual({ n: 2 });
++ });
++
++ it('copying the trip carries its tours and waypoints onto the new places', async () => {
++ const placeId = await createViaApi(5, tourBody({
++ waypoints: [
++ { lat: 47, lng: 11, role: 'start', sequence: 0 },
++ { lat: 47.01, lng: 11.01, role: 'via', sequence: 1 },
++ { lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
++ ],
++ }));
++ const res = await request(server).post('/api/trips/5/copy').set('Cookie', sessionCookie(OWNER)).send({ title: 'Alps again' });
++ expect(res.status).toBe(201);
++ const copyId = res.body.trip.id as number;
++
++ const list = await request(server).get(`/api/trips/${copyId}/tours`).set('Cookie', sessionCookie(OWNER));
++ expect(list.status).toBe(200);
++ expect(list.body.tours).toHaveLength(1);
++ const copied = list.body.tours[0];
++ expect(copied.place_id).not.toBe(placeId);
++ const source = (await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER))).body;
++ const { place_id: _sourceId, ...sourceRest } = source.tour;
++ const { place_id: _copyId, ...copyRest } = copied;
++ expect(copyRest).toEqual(sourceRest);
++
++ const detail = await request(server).get(`/api/trips/${copyId}/tours/${copied.place_id}`).set('Cookie', sessionCookie(OWNER));
++ expect(detail.body.waypoints).toEqual(source.waypoints);
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tour_waypoints WHERE place_id = ?').get(placeId)).toEqual({ n: 3 });
++ });
++
++ it('deleting the place removes its tour and waypoints and reports the tour id', async () => {
++ const placeId = await createViaApi();
++ const res = await request(server).delete(`/api/trips/5/places/${placeId}`).set('Cookie', sessionCookie(OWNER));
++ expect(res.status).toBe(200);
++ expect(res.body).toEqual({ success: true, tourPlaceIds: [placeId] });
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tours WHERE place_id = ?').get(placeId)).toEqual({ n: 0 });
++ expect(db.prepare('SELECT COUNT(*) AS n FROM tour_waypoints WHERE place_id = ?').get(placeId)).toEqual({ n: 0 });
++ });
++ });
++});
diff --cc server/tests/helpers/accommodations-service.ts
index 6864028a3,7d88a6c33..5c78967d2
--- a/server/tests/helpers/accommodations-service.ts
+++ b/server/tests/helpers/accommodations-service.ts
@@@ -6,7 -5,20 +5,21 @@@ import { JourneyDomainService } from '.
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { QueryHelpersService } from '../../src/nest/query-helpers/query-helpers.service';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
- import { TrekPhotosRepository } from '../../src/nest/photos/trek-photos.repository';
+ import { TrekPhotoRegistrationService } from '../../src/nest/photos/trek-photo-registration.service';
+ import { TrekPhotos } from '../../src/db/entities/TrekPhotos.entity';
+ import { TripPhotos } from '../../src/db/entities/TripPhotos.entity';
+ import {
+ createTestUnitOfWork, createTestAppSettingsRepo, createTestTagsRepo, createTestPlaceRatingsRepo,
+ createTestAssignmentParticipantsRepo, createTestDayAssignmentsRepo, createTestDaysRepo, createTestPlacesRepo,
+ createTestTripMembersRepo, createTestRoadtripViasRepo, createTestDayAccommodationsRepo, createTestReservationsRepo,
+ sharedTestOrm, createTestTripsRepo,
+ } from './test-uow';
+ import { createTestBudgetItemsRepo } from './files-repos';
+ import {
+ createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo,
+ createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo,
+ } from './journey-repos';
++import { createTestToursRepo } from './tours-repos';
/**
* AccommodationsService over a test connection.
@@@ -27,13 -45,41 +46,42 @@@ export async function makeAccommodation
* the same stop a night entered under Days does, and every suite that builds
* that service by hand needs one to hand it.
*/
- export function accommodationsOver(dbs: DatabaseService): AccommodationsService {
- const permissions = new PermissionsService(dbs);
+ export async function accommodationsOver(conn: Database): Promise<AccommodationsService> {
+ const permissions = new PermissionsService(await createTestAppSettingsRepo(conn), await createTestUnitOfWork(conn));
const realtime = new RealtimeService();
+ const t = await sharedTestOrm(conn);
const assignments = new AssignmentsService(
- dbs, permissions, realtime,
- new QueryHelpersService(dbs),
- new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs)),
+ await createTestTripsRepo(conn), permissions, realtime,
+ new QueryHelpersService(await createTestTagsRepo(conn), await createTestPlaceRatingsRepo(conn), await createTestAssignmentParticipantsRepo(conn)),
+ new JourneyDomainService(
+ realtime, new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), await createTestJourneyPhotosRepo(conn)), await createTestUnitOfWork(conn),
+ await createTestJourneysRepo(conn), await createTestJourneyContributorsRepo(conn),
+ await createTestJourneyTripsRepo(conn), await createTestJourneyEntriesRepo(conn), await createTestTripsRepo(conn),
+ // Plan 3g Task 2 constructor-ripple: JourneyPhotosRepository/JourneyEntryPhotosRepository/PlacesRepository.
+ await createTestJourneyPhotosRepo(conn), await createTestJourneyEntryPhotosRepo(conn), await createTestPlacesRepo(conn),
+ ),
+ await createTestUnitOfWork(conn),
+ await createTestDayAssignmentsRepo(conn),
+ await createTestAssignmentParticipantsRepo(conn),
+ await createTestDaysRepo(conn),
+ await createTestPlacesRepo(conn),
+ await createTestTripMembersRepo(conn),
+ await createTestRoadtripViasRepo(conn),
++ await createTestToursRepo(conn),
+ );
+ return new AccommodationsService(
+ permissions, realtime, assignments, await createTestUnitOfWork(conn),
+ // Plan 4 Task 2 — AccommodationsService's own canAccessTrip delegate is now
+ // TripsRepository.findAccessible. Plan 4 Task 3 — stampLodging's
+ // getPlaceWithTags is PlacesRepository.findWithTagsAndRatings directly
+ // (`placesRepo` below, already injected).
+ await createTestTripsRepo(conn),
+ await createTestDayAccommodationsRepo(conn),
+ await createTestDayAssignmentsRepo(conn),
+ await createTestPlacesRepo(conn),
+ await createTestDaysRepo(conn),
+ await createTestRoadtripViasRepo(conn),
+ await createTestReservationsRepo(conn),
+ await createTestBudgetItemsRepo(conn),
);
- return new AccommodationsService(dbs, permissions, realtime, assignments);
}
diff --cc server/tests/helpers/mcp-test-controllers.ts
index e5295f9b5,031ecffa0..8f822e9ea
--- a/server/tests/helpers/mcp-test-controllers.ts
+++ b/server/tests/helpers/mcp-test-controllers.ts
@@@ -120,7 -126,66 +126,67 @@@ import { AirtrailImportService } from '
import { ReservationImportMcp } from '../../src/nest/reservation-import/reservation-import.mcp';
import { HelpMcp } from '../../src/nest/help/help.mcp';
import { AddonsMcp } from '../../src/nest/addons/addons.mcp';
+ import {
+ createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo,
+ createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
+ createTestTripMembersRepo, createTestTripInviteTokensRepo, createTestPlaceRatingsRepo, createTestAssignmentParticipantsRepo,
+ createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo, createTestRoadtripViasRepo, createTestRoadtripDayTracksRepo,
+ createTestPlaceDetailsCacheRepo,
+ createTestRoadtripPreferencesRepo, createTestRoadtripDayBoundariesRepo,
+ createTestReservationsRepo,
+ createTestReservationEndpointsRepo,
+ createTestReservationTravelersRepo,
+ createTestReservationDayPositionsRepo,
+ createTestDayAccommodationsRepo,
+ createTestUsersRepo,
+ createTestCollectionsRepo, createTestCollectionMembersRepo, createTestCollectionLabelsRepo,
+ createTestCollectionPlacesRepo, createTestCollectionPlaceRatingsRepo,
+ sharedTestOrm,
+ } from './test-uow';
+ import { createTestOrm } from './test-orm';
+ import { createTestTripFilesRepo, createTestFileLinksRepo, createTestBudgetItemsRepo } from './files-repos';
+ import { budgetRepoArgs } from './budget-repos';
+ import { createTestShareTokensRepo, shareServiceRepoArgs, createTestPluginsRepo, createTestPluginUserErasureQueueRepo } from './share-repos';
+ import {
+ createTestCollabMessageReactionsRepo, createTestCollabNotesRepo, createTestCollabPollsRepo,
+ createTestCollabPollVotesRepo, createTestCollabLinksRepo, createTestCollabMessagesRepo,
+ } from './collab-repos';
+ import {
+ createTestPackingItemsRepo, createTestPackingItemContributorsRepo, createTestPackingBagsRepo,
+ createTestPackingCategoryAssigneesRepo, createTestPackingTemplatesRepo, createTestPackingTemplateCategoriesRepo,
+ createTestPackingTemplateItemsRepo,
+ } from './packing-repos';
+ import { createTestTodoItemsRepo, createTestTodoCategoryAssigneesRepo } from './todo-repos';
+ import {
+ createTestSchoolHolidayCountriesRepo, createTestSchoolHolidayRegionsRepo,
+ createTestSchoolHolidayPeriodsRepo, createTestVacayHolidayCalendarsRepo,
+ } from './school-holidays-repos';
+ import {
+ createTestVacayPlansRepo, createTestVacayPlanMembersRepo, createTestVacayYearsRepo, createTestVacayUserYearsRepo,
+ createTestVacayUserColorsRepo, createTestVacayEntriesRepo, createTestVacayCompanyHolidaysRepo,
+ createTestVacaySharesRepo, createTestVacayUserSettingsRepo,
+ } from './vacay-repos';
+ import {
+ createTestBucketListRepo, createTestHiddenCountriesRepo, createTestHiddenRegionsRepo,
+ createTestVisitedCountriesRepo, createTestVisitedRegionsRepo, createTestPlaceRegionsRepo,
+ } from './atlas-repos';
+ import {
+ createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo,
+ createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo,
+ } from './journey-repos';
+ import { createTestJourneyShareTokensRepo } from './journey-share-repos';
+ import { AppSettings } from '../../src/db/entities/AppSettings.entity';
+ import { AuditLog } from '../../src/db/entities/AuditLog.entity';
+ import { Users } from '../../src/db/entities/Users.entity';
+ import { Settings } from '../../src/db/entities/Settings.entity';
+ import { InviteTokens } from '../../src/db/entities/InviteTokens.entity';
+ import { McpTokens } from '../../src/db/entities/McpTokens.entity';
+ import { OauthTokens } from '../../src/db/entities/OauthTokens.entity';
+ import { WebauthnCredentials } from '../../src/db/entities/WebauthnCredentials.entity';
+ import { PasswordResetTokens } from '../../src/db/entities/PasswordResetTokens.entity';
import { noGoogleQuota } from './google-quota';
+ import { createTestPushSubscriptionsRepo } from './notifications-repos';
++import { createTestToursRepo } from './tours-repos';
/**
* Hand-wired counterpart of the boot-time discovery in McpRegistryService,
@@@ -169,12 -292,30 +293,31 @@@ export async function createMcpTestRegi
// dependency fails the build — pass them for real regardless of the gate.
// One instance, four consumers: AssignmentsMcp, ReservationsMcp, PlacesMcp and
// AccommodationsService, which writes the day stop a booked night implies.
- const assignmentsService = new AssignmentsService(dbService, permissionsService, realtimeService, queryHelpersService, journeyDomain);
- const accommodationsService = new AccommodationsService(dbService, permissionsService, realtimeService, assignmentsService);
+ const assignmentsService = new AssignmentsService(
+ await createTestTripsRepo(db), permissionsService, realtimeService, queryHelpersService, journeyDomain, await createTestUnitOfWork(db),
+ await createTestDayAssignmentsRepo(db),
+ await createTestAssignmentParticipantsRepo(db),
+ await createTestDaysRepo(db),
+ await createTestPlacesRepo(db),
+ await createTestTripMembersRepo(db),
+ await createTestRoadtripViasRepo(db),
++ await createTestToursRepo(db),
+ );
+ const accommodationsService = new AccommodationsService(
+ permissionsService, realtimeService, assignmentsService, await createTestUnitOfWork(db),
+ await createTestTripsRepo(db),
+ await createTestDayAccommodationsRepo(db),
+ await createTestDayAssignmentsRepo(db),
+ await createTestPlacesRepo(db),
+ await createTestDaysRepo(db),
+ await createTestRoadtripViasRepo(db),
+ await createTestReservationsRepo(db),
+ await createTestBudgetItemsRepo(db),
+ );
// Built after it: deleting a place cancels the nights booked at it through this one.
const placesService = new PlacesService(
- dbService, permissionsService, realtimeService, mapsService, queryHelpersService,
- new UnsplashService(dbService, new RuntimeEnvService(), generalStorage),
+ permissionsService, realtimeService, mapsService, queryHelpersService,
+ new UnsplashService(appSettings, usersRepo, new RuntimeEnvService(), generalStorage),
placePhotoCache,
journeyDomain,
generalStorage,
diff --cc server/tests/helpers/plugin-host.ts
index f4d3512ba,e3785b482..b3d4de955
--- a/server/tests/helpers/plugin-host.ts
+++ b/server/tests/helpers/plugin-host.ts
@@@ -70,10 -71,75 +71,76 @@@ import { EphemeralTokenService } from '
import { UserCleanupService } from '../../src/nest/auth/user-cleanup.service';
import { UnsplashService } from '../../src/nest/unsplash/unsplash.service';
import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-cache.service';
- import { TrekPhotosRepository } from '../../src/nest/photos/trek-photos.repository';
+ import { TrekPhotoRegistrationService } from '../../src/nest/photos/trek-photo-registration.service';
+ import { TrekPhotos } from '../../src/db/entities/TrekPhotos.entity';
+ import { TripPhotos } from '../../src/db/entities/TripPhotos.entity';
import { RuntimeEnvService } from '../../src/nest/app-config/runtime-env.service';
import { makeStorageFixture } from './storage-fixture';
+ import {
+ createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo, sharedTestOrm,
+ createTestCollectionsRepo, createTestCollectionMembersRepo, createTestCollectionLabelsRepo,
+ createTestCollectionPlacesRepo, createTestCollectionPlaceRatingsRepo,
+ createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
+ createTestTripMembersRepo, createTestPlaceRatingsRepo, createTestAssignmentParticipantsRepo,
+ createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo, createTestRoadtripViasRepo,
+ createTestPlaceDetailsCacheRepo,
+ createTestReservationsRepo,
+ createTestReservationEndpointsRepo,
+ createTestReservationTravelersRepo,
+ createTestReservationDayPositionsRepo,
+ createTestDayAccommodationsRepo,
+ createTestUsersRepo,
+ createTestRoadtripDayBoundariesRepo,
+ } from './test-uow';
+ import { AppSettings } from '../../src/db/entities/AppSettings.entity';
+ import { Addons } from '../../src/db/entities/Addons.entity';
+ import { AuditLog } from '../../src/db/entities/AuditLog.entity';
+ import { Users } from '../../src/db/entities/Users.entity';
+ import { Plugins } from '../../src/db/entities/Plugins.entity';
+ import { PluginErrorLog } from '../../src/db/entities/PluginErrorLog.entity';
+ import { PluginScheduledTasks } from '../../src/db/entities/PluginScheduledTasks.entity';
+ import { PluginUserErasureQueue } from '../../src/db/entities/PluginUserErasureQueue.entity';
+ import { PluginEgressHosts } from '../../src/db/entities/PluginEgressHosts.entity';
+ import { PluginSettingsFields } from '../../src/db/entities/PluginSettingsFields.entity';
+ import { PluginActions } from '../../src/db/entities/PluginActions.entity';
+ import { PluginUserConfig } from '../../src/db/entities/PluginUserConfig.entity';
+ import { PluginEntityMetadata } from '../../src/db/entities/PluginEntityMetadata.entity';
+ import { PluginOauthTokens } from '../../src/db/entities/PluginOauthTokens.entity';
+ import { PluginOauthState } from '../../src/db/entities/PluginOauthState.entity';
+ import { PluginMetaMigrations } from '../../src/db/entities/PluginMetaMigrations.entity';
+ import { PluginCapabilityAudit } from '../../src/db/entities/PluginCapabilityAudit.entity';
+ import { Settings } from '../../src/db/entities/Settings.entity';
+ import { NotificationChannelPreferences } from '../../src/db/entities/NotificationChannelPreferences.entity';
+ import { createTestTripFilesRepo, createTestFileLinksRepo, createTestBudgetItemsRepo } from './files-repos';
+ import { budgetRepoArgs } from './budget-repos';
+ import { createTestShareTokensRepo, createTestPluginsRepo, createTestPluginUserErasureQueueRepo } from './share-repos';
+ import {
+ createTestCollabMessageReactionsRepo, createTestCollabNotesRepo, createTestCollabPollsRepo,
+ createTestCollabPollVotesRepo, createTestCollabLinksRepo, createTestCollabMessagesRepo,
+ } from './collab-repos';
+ import {
+ createTestPackingItemsRepo, createTestPackingItemContributorsRepo, createTestPackingBagsRepo,
+ createTestPackingCategoryAssigneesRepo, createTestPackingTemplatesRepo, createTestPackingTemplateCategoriesRepo,
+ createTestPackingTemplateItemsRepo,
+ } from './packing-repos';
+ import { createTestTodoItemsRepo, createTestTodoCategoryAssigneesRepo } from './todo-repos';
+ import { createTestVacayHolidayCalendarsRepo, createTestSchoolHolidayRegionsRepo } from './school-holidays-repos';
+ import {
+ createTestVacayPlansRepo, createTestVacayPlanMembersRepo, createTestVacayYearsRepo, createTestVacayUserYearsRepo,
+ createTestVacayUserColorsRepo, createTestVacayEntriesRepo, createTestVacayCompanyHolidaysRepo,
+ createTestVacaySharesRepo, createTestVacayUserSettingsRepo,
+ } from './vacay-repos';
+ import {
+ createTestBucketListRepo, createTestHiddenCountriesRepo, createTestHiddenRegionsRepo,
+ createTestVisitedCountriesRepo, createTestVisitedRegionsRepo, createTestPlaceRegionsRepo,
+ } from './atlas-repos';
+ import {
+ createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo,
+ createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo,
+ } from './journey-repos';
+ import { createTestJourneyShareTokensRepo } from './journey-share-repos';
import { noGoogleQuota } from './google-quota';
++import { createTestToursRepo } from './tours-repos';
/**
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
@@@ -85,43 -151,165 +152,166 @@@
* domains, so what it builds is the same set of `@PluginController()` instances the
* container would discover, handed to the host factory as a registry.
*/
- export function createPluginRpcHostFactory(dbs: DatabaseService): PluginRpcHostFactory {
+ export async function createPluginRpcHostFactory(db: Database.Database): Promise<PluginRpcHostFactory> {
const generalStorage = makeStorageFixture('').storage;
- const permissions = new PermissionsService(dbs);
+ const appSettings = (await sharedTestOrm(db)).repo(AppSettings);
+ const usersRepo = (await sharedTestOrm(db)).repo(Users);
+ // Plan 3j Task 3 — `PluginRpcHostFactory`'s `audit` callback and `HostSurfaceRpc`'s
+ // `budgetFor` calls now take `PluginCapabilityAuditRepository`, not a raw connection.
+ const pluginAuditRepo = (await sharedTestOrm(db)).repo(PluginCapabilityAudit);
+ const permissions = new PermissionsService(await createTestAppSettingsRepo(db), await createTestUnitOfWork(db));
const exchangeRates = new ExchangeRatesService();
const realtime = new RealtimeService();
- const budget = new BudgetService(dbs, permissions, exchangeRates, realtime);
- const addons = new AddonsService(dbs);
- const queryHelpers = new QueryHelpersService(dbs);
- const todos = new TodoService(dbs, permissions, realtime);
- const packing = new PackingService(dbs, permissions, realtime, notificationsStub());
- const files = new FilesService(dbs, permissions, realtime, new EphemeralTokenService(), generalStorage);
- const collab = new CollabService(dbs, permissions, realtime, notificationsStub(), generalStorage, new RateLimitService());
- const vacay = new VacayService(dbs, realtime, notificationsStub());
- const days = new DaysService(dbs, permissions, realtime, queryHelpers);
- const photoCache = new PlacePhotoCacheService(dbs, makeStorageFixture('photos/google/').storage);
- const unsplash = new UnsplashService(dbs, new RuntimeEnvService(), generalStorage);
- const journey = new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs));
- const collections = new CollectionsService(dbs, permissions, realtime, notificationsStub(), generalStorage);
- const atlas = new AtlasService(dbs);
- const dayNotes = new DayNotesService(dbs, permissions, realtime);
- const assignments = new AssignmentsService(dbs, permissions, realtime, queryHelpers, journey);
- const membership = new TripMembershipService(dbs);
- const notifications = makeNotificationsService(dbs, realtime);
- const llmConfig = new LlmConfigResolver(new SettingsService(dbs), dbs, addons);
- const oauth = new PluginOAuthService(dbs);
- const accommodations = new AccommodationsService(dbs, permissions, realtime, assignments);
+ const budget = new BudgetService(permissions, exchangeRates, realtime, await createTestUnitOfWork(db), ...(await budgetRepoArgs(db)));
+ const addons = await createTestAddonsService(db);
+ const queryHelpers = new QueryHelpersService(await createTestTagsRepo(db), await createTestPlaceRatingsRepo(db), await createTestAssignmentParticipantsRepo(db));
+ const todos = new TodoService(permissions, realtime, await createTestUnitOfWork(db), await createTestTodoItemsRepo(db), await createTestTodoCategoryAssigneesRepo(db), await createTestTripsRepo(db), await createTestTripMembersRepo(db));
+ const packing = new PackingService(
+ permissions, realtime, notificationsStub(), await createTestUnitOfWork(db),
+ await createTestPackingItemsRepo(db), await createTestPackingItemContributorsRepo(db), await createTestPackingBagsRepo(db),
+ await createTestPackingCategoryAssigneesRepo(db), await createTestPackingTemplatesRepo(db), await createTestPackingTemplateCategoriesRepo(db),
+ await createTestPackingTemplateItemsRepo(db), await createTestTripsRepo(db), await createTestTripMembersRepo(db),
+ );
+ // Plan 3e Task 1 (files): FilesService now also takes uow + the repositories
+ // its R2 transactions and R12 cross-object trip-scoping guard need.
+ const files = new FilesService(
+ await createTestTripsRepo(db), permissions, realtime, new EphemeralTokenService(), generalStorage, (await sharedTestOrm(db)).em,
+ await createTestUnitOfWork(db),
+ await createTestTripFilesRepo(db),
+ await createTestFileLinksRepo(db),
+ await createTestReservationsRepo(db),
+ await createTestPlacesRepo(db),
+ await createTestDayAssignmentsRepo(db),
+ await createTestBudgetItemsRepo(db),
+ );
+ const collab = new CollabService(
+ permissions, realtime, notificationsStub(), generalStorage, new RateLimitService(), await createTestUnitOfWork(db),
+ await createTestCollabMessageReactionsRepo(db), await createTestCollabNotesRepo(db), await createTestCollabPollsRepo(db),
+ await createTestCollabPollVotesRepo(db), await createTestCollabLinksRepo(db), await createTestCollabMessagesRepo(db),
+ await createTestTripsRepo(db),
+ );
+ const vacay = new VacayService(
+ await createTestVacayPlansRepo(db), await createTestVacayPlanMembersRepo(db),
+ await createTestVacayYearsRepo(db), await createTestVacayUserYearsRepo(db),
+ await createTestVacayUserColorsRepo(db), await createTestVacayEntriesRepo(db),
+ await createTestVacayCompanyHolidaysRepo(db), await createTestVacayHolidayCalendarsRepo(db),
+ await createTestVacaySharesRepo(db), await createTestVacayUserSettingsRepo(db),
+ await createTestSchoolHolidayRegionsRepo(db),
+ realtime, notificationsStub(), await createTestUnitOfWork(db),
+ );
+ const days = new DaysService(
+ permissions,
+ realtime,
+ queryHelpers,
+ await createTestUnitOfWork(db),
+ await createTestDaysRepo(db),
+ await createTestDayAssignmentsRepo(db),
+ await createTestDayNotesRepo(db),
+ await createTestTripsRepo(db),
+ await createTestReservationsRepo(db),
+ await createTestReservationEndpointsRepo(db),
+ await createTestDayAccommodationsRepo(db),
+ await createTestRoadtripViasRepo(db),
+ await createTestRoadtripDayBoundariesRepo(db),
+ );
+ const photoCache = new PlacePhotoCacheService(makeStorageFixture('photos/google/').storage, await createTestGooglePlacePhotoMetaRepo(db), await createTestPlacesRepo(db), await createTestCollectionPlacesRepo(db));
+ const unsplash = new UnsplashService(appSettings, usersRepo, new RuntimeEnvService(), generalStorage);
+ const journey = new JourneyDomainService(
+ realtime, new TrekPhotoRegistrationService((await sharedTestOrm(db)).repo(TrekPhotos), (await sharedTestOrm(db)).repo(TripPhotos), await createTestJourneyPhotosRepo(db)), await createTestUnitOfWork(db),
+ // Plan 3g Task 1 — the constructor-ripple fix (R9): four journey-owned
+ // repositories + the already-shared `TripsRepository` (AP1/`getTitle`).
+ await createTestJourneysRepo(db), await createTestJourneyContributorsRepo(db),
+ await createTestJourneyTripsRepo(db), await createTestJourneyEntriesRepo(db),
+ await createTestTripsRepo(db),
+ // Plan 3g Task 2 — a genuine follow-up constructor-ripple (git status
+ // confirmed this file clean before editing, per the task brief's own
+ // allowance): `JourneyPhotosRepository`/`JourneyEntryPhotosRepository`
+ // (the photos surface, JG19/JG87-116) + `PlacesRepository` (JG44's
+ // `findRaw`, already imported above for `PlacePhotoCacheService`).
+ await createTestJourneyPhotosRepo(db), await createTestJourneyEntryPhotosRepo(db),
+ await createTestPlacesRepo(db),
+ );
+ const collections = new CollectionsService(
+ permissions, realtime, notificationsStub(), generalStorage, await createTestUnitOfWork(db),
+ // Plan 3h Task 1 — the constructor-ripple fix: collections part A's own
+ // repositories, first cut (`CollectionMembersRepository` extended by
+ // Task 2), plus the already-DONE `CategoriesRepository` (CL21 reuse).
+ await createTestCollectionsRepo(db), await createTestCollectionMembersRepo(db),
+ await createTestCollectionLabelsRepo(db), await createTestCategoriesRepo(db),
+ // Plan 3h Task 2 — part B's own repositories: `DatabaseService` dropped
+ // entirely (this service's last use of it), the trip/place/tag/user
+ // repositories AP1-AP6's `TripsRepository.findAccessible` calls and the
+ // cross-domain writes need, injected directly.
+ await createTestCollectionPlacesRepo(db), await createTestCollectionPlaceRatingsRepo(db),
+ await createTestTripsRepo(db), await createTestTripMembersRepo(db),
+ await createTestPlacesRepo(db), await createTestPlaceRatingsRepo(db),
+ await createTestTagsRepo(db), usersRepo,
+ );
+ const atlas = new AtlasService(
+ await createTestBucketListRepo(db), await createTestHiddenCountriesRepo(db),
+ await createTestHiddenRegionsRepo(db), await createTestVisitedCountriesRepo(db),
+ await createTestVisitedRegionsRepo(db), await createTestPlaceRegionsRepo(db),
+ await createTestTripsRepo(db), await createTestPlacesRepo(db),
+ await createTestReservationEndpointsRepo(db), await createTestUnitOfWork(db), (await sharedTestOrm(db)).orm,
+ );
+ const dayNotes = new DayNotesService(await createTestTripsRepo(db), permissions, realtime, await createTestDayNotesRepo(db), await createTestDaysRepo(db));
+ const assignments = new AssignmentsService(
+ await createTestTripsRepo(db), permissions, realtime, queryHelpers, journey, await createTestUnitOfWork(db),
+ await createTestDayAssignmentsRepo(db),
+ await createTestAssignmentParticipantsRepo(db),
+ await createTestDaysRepo(db),
+ await createTestPlacesRepo(db),
+ await createTestTripMembersRepo(db),
+ await createTestRoadtripViasRepo(db),
++ await createTestToursRepo(db),
+ );
+ const membership = new TripMembershipService(await createTestTripsRepo(db), await createTestTripMembersRepo(db));
+ const notifications = await makeNotificationsService(db, realtime);
+ // Plan 4 Task 1 constructor-ripple: LlmConfigResolver's addon-row read
+ // moved off DatabaseService onto AddonsRepository.
+ const llmConfig = new LlmConfigResolver(new SettingsService(await createTestUnitOfWork(db), appSettings, await createTestSettingsRepo(db)), (await sharedTestOrm(db)).repo(Addons), addons);
+ const pluginOrm = await sharedTestOrm(db);
+ const oauth = new PluginOAuthService(pluginOrm.repo(Plugins), pluginOrm.repo(PluginOauthTokens), pluginOrm.repo(PluginOauthState), pluginOrm.repo(PluginSettingsFields));
+ const accommodations = new AccommodationsService(
+ permissions, realtime, assignments, await createTestUnitOfWork(db),
+ await createTestTripsRepo(db),
+ await createTestDayAccommodationsRepo(db),
+ await createTestDayAssignmentsRepo(db),
+ await createTestPlacesRepo(db),
+ await createTestDaysRepo(db),
+ await createTestRoadtripViasRepo(db),
+ await createTestReservationsRepo(db),
+ await createTestBudgetItemsRepo(db),
+ );
// After it: deleting a place cancels the nights booked at it through this one.
- const places = new PlacesService(dbs, permissions, realtime, new MapsService(dbs, photoCache, noGoogleQuota), queryHelpers, unsplash, photoCache, journey, generalStorage, accommodations);
+ const places = new PlacesService(
+ permissions, realtime, new MapsService(photoCache, appSettings, usersRepo, await createTestPlaceDetailsCacheRepo(db), await createTestPlacesRepo(db), noGoogleQuota), queryHelpers, unsplash, photoCache, journey, generalStorage, accommodations, await createTestUnitOfWork(db),
+ await createTestPlacesRepo(db),
+ await createTestTagsRepo(db),
+ await createTestPlaceRatingsRepo(db),
+ await createTestTripMembersRepo(db),
+ await createTestDayAssignmentsRepo(db),
+ await createTestCategoriesRepo(db),
+ await createTestTripsRepo(db),
+ await createTestBudgetItemsRepo(db),
+ await createTestCollectionPlacesRepo(db),
+ );
// After accommodations: a hotel booking writes the stay's day stop through it.
- const reservations = new ReservationsService(dbs, permissions, budget, realtime, notificationsStub(), new ReservationsReadRepository(dbs), accommodations);
- const trips = new TripsService(dbs, reservations, days, permissions, budget, vacay, realtime, unsplash, generalStorage, new SettingsService(dbs));
- const members = new TripMembersService(dbs, budget, new UserCleanupService(dbs, budget), permissions, realtime, notificationsStub());
- const guards = new PluginGuards(dbs, permissions, addons);
+ const reservations = new ReservationsService(permissions, budget, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(db), await createTestReservationEndpointsRepo(db), await createTestReservationTravelersRepo(db)), accommodations, await createTestUnitOfWork(db), await createTestReservationsRepo(db), await createTestReservationEndpointsRepo(db), await createTestReservationTravelersRepo(db), await createTestReservationDayPositionsRepo(db), await createTestDayAccommodationsRepo(db), await createTestDaysRepo(db), await createTestPlacesRepo(db), await createTestDayAssignmentsRepo(db), await createTestTripMembersRepo(db), await createTestUsersRepo(db), await createTestTripsRepo(db), await createTestBudgetItemsRepo(db));
+ const trips = new TripsService(reservations, days, permissions, budget, vacay, realtime, unsplash, generalStorage, await createTestUnitOfWork(db), (await sharedTestOrm(db)).em, new SettingsService(await createTestUnitOfWork(db), appSettings, await createTestSettingsRepo(db)));
+ // Plan 4 Task 4: UserCleanupService's UC1 now goes through a directly-injected
+ // EntityManager (MaintenanceRepository.deletePluginUserData), not DatabaseService.
+ const members = new TripMembersService(budget, new UserCleanupService((await sharedTestOrm(db)).em, budget, await createTestUnitOfWork(db), usersRepo, await createTestTripMembersRepo(db), await createTestBudgetItemsRepo(db), await createTestJourneyShareTokensRepo(db), await createTestJourneysRepo(db), await createTestJourneyEntriesRepo(db), await createTestJourneyContributorsRepo(db), await createTestShareTokensRepo(db), await createTestPluginsRepo(db), await createTestPluginUserErasureQueueRepo(db)), permissions, realtime, notificationsStub(), await createTestUnitOfWork(db), await createTestTripsRepo(db), await createTestTripMembersRepo(db), usersRepo);
+ // Plan 3j Task 1 — PluginGuards' own role lookup (PG3/PG4) now goes
+ // through UsersRepository.getRole; `usersRepo` above is the same
+ // sharedTestOrm-backed repository every other service in this file uses.
+ // Plan 4 Task 2 — PluginGuards' own canAccessTrip delegate is now
+ // TripsRepository.findAccessible directly, in the same constructor slot.
+ const guards = new PluginGuards(await createTestTripsRepo(db), permissions, addons, usersRepo);
const registry = createTestPluginRegistry([
- new TagsRpc(new TagsService(dbs)),
- new CategoriesRpc(new CategoriesService(dbs)),
+ new TagsRpc(new TagsService(await createTestTagsRepo(db))),
+ new CategoriesRpc(new CategoriesService(await createTestCategoriesRepo(db))),
new WeatherRpc(new WeatherService()),
new ExchangeRatesRpc(exchangeRates),
new TodoRpc(todos, realtime, guards),
diff --cc server/tests/helpers/test-db.ts
index 99756524c,3ed5a99c0..2ddcc4221
--- a/server/tests/helpers/test-db.ts
+++ b/server/tests/helpers/test-db.ts
@@@ -21,109 -29,34 +29,37 @@@ import type { INestApplication } from '
import { AuthPublicController } from '../../src/nest/auth/auth-public.controller';
import type { RateLimitService } from '../../src/nest/common/rate-limit.service';
- // Tables to clear on reset, child-before-parent to be safe (FK checks are OFF during reset).
- // Keep in sync with schema.ts + migrations.ts. Intentionally excluded: categories, addons,
- // photo_providers, photo_provider_fields, schema_version (seed/config data, not user data).
- const RESET_TABLES = [
- 'school_holiday_periods',
- 'school_holiday_regions',
- 'school_holiday_countries',
- // Collab
- 'file_links',
- 'collab_message_reactions',
- 'collab_poll_votes',
- 'collab_messages',
- 'collab_polls',
- 'collab_notes',
- // Road trip (#1797). Both hang off days, so they go before it like the rest
- // of the day content; a new domain's tables belong here or its rows leak from
- // one case into the next.
- 'roadtrip_day_tracks',
- 'roadtrip_vias',
- 'roadtrip_day_boundaries',
- // Dawarich (#2279). The suggestions reference places and bucket_list, so they
- // are cleared before both; the connection row hangs off the user.
- 'dawarich_visit_suggestions',
- 'dawarich_connections',
- // Day content
- 'day_notes',
- 'todo_category_assignees',
- 'todo_items',
- 'assignment_participants',
- 'day_assignments',
- // Places
- 'place_regions',
- 'place_tags',
- 'places',
- // Packing
- 'packing_category_assignees',
- 'packing_bag_members',
- 'packing_bags',
- 'packing_template_items',
- 'packing_template_categories',
- 'packing_templates',
- 'packing_items',
- // Budget
- 'budget_item_members',
- 'budget_items',
- // Photos & files
- 'trip_photos',
- 'trip_album_links',
- 'trip_files',
- 'photos',
- // Reservations
- 'reservation_day_positions',
- 'reservations',
- // Accommodations & days
- 'day_accommodations',
- 'days',
- // Trip
- 'share_tokens',
- 'trip_invite_tokens',
- 'trip_members',
- 'trips',
- // Journey
- 'journey_books',
- 'journey_share_tokens',
- 'journey_photos',
- 'journey_entries',
- 'journey_contributors',
- 'journey_trips',
- 'journeys',
- // Vacay
- 'vacay_user_settings',
- 'vacay_shares',
- 'vacay_entries',
- 'vacay_company_holidays',
- 'vacay_holiday_calendars',
- 'vacay_plan_members',
- 'vacay_user_colors',
- 'vacay_user_years',
- 'vacay_years',
- 'vacay_plans',
- // Atlas
- 'visited_regions',
- 'visited_countries',
- 'bucket_list',
- // Notifications & audit
- 'push_subscriptions',
- 'notification_channel_preferences',
- 'notifications',
- 'audit_log',
- // System notices
- 'user_notice_dismissals',
- // User data
- 'settings',
- 'mcp_tokens',
- 'invite_tokens',
- 'tags',
- 'app_settings',
- 'webauthn_challenges',
- 'webauthn_credentials',
- 'users',
- ];
+ // createSnapshotTestDb / buildDbMock / CAN_ACCESS_TRIP_SQL live in db-mock.ts, a
+ // leaf module with no src/nest imports — see its header comment for why. This
+ // file imports AuthPublicController (for resetRateLimits below), so a vi.mock
+ // factory MUST import from db-mock.ts directly, never from here, or it
+ // re-enters src/db/database while its own mock for that module is still being
+ // built and captures the real one.
+ export { CAN_ACCESS_TRIP_SQL, buildDbMock } from './db-mock';
+
+ /**
+ * Tables `resetTestDb` must NOT clear: seed and config data every test assumes
+ * is present (categories, addons, the provider catalogues) plus the two
+ * migration bookkeeping tables. Everything else in the schema is user data and
+ * is derived from `sqlite_master` at reset time — see `resetTestDb`.
+ */
+ const KEEP_TABLES = new Set([
+ // Seeded reference data (`seedDefaults` below re-seeds the first three).
+ 'categories',
+ 'addons',
+ 'photo_providers',
+ 'photo_provider_fields',
+ 'document_providers',
+ 'document_provider_fields',
++ // Reference data the migration that creates it writes (`tours.tour_type`
++ // has an FK on it); nothing re-seeds it, so a reset must keep it.
++ 'tour_types',
+ // Migration bookkeeping: clearing these would make the next boot replay the
+ // whole history over a schema that already has it.
+ 'schema_version',
+ 'migrations',
+ 'mikro_orm_migrations',
+ ]);
const DEFAULT_CATEGORIES = [
{ name: 'Hotel', color: '#3b82f6', icon: '🏨' },
diff --cc server/tests/helpers/tours-repos.ts
index 000000000,000000000..e9ab4724a
new file mode 100644
--- /dev/null
+++ b/server/tests/helpers/tours-repos.ts
@@@ -1,0 -1,0 +1,38 @@@
++import type Database from 'better-sqlite3';
++import { sharedTestOrm } from './test-uow';
++import { Tours } from '../../src/db/entities/Tours.entity';
++import type { ToursRepository } from '../../src/db/repositories/Tours.repository';
++import { TourWaypoints } from '../../src/db/entities/TourWaypoints.entity';
++import type { TourWaypointsRepository } from '../../src/db/repositories/TourWaypoints.repository';
++
++/**
++ * Tours test-only repository factories, bound to a suite's own better-sqlite3
++ * handle through the same memoised `sharedTestOrm` `test-uow.ts` exports, so
++ * a repository built here and a `UnitOfWork` from `createTestUnitOfWork`
++ * resolve the same `EntityManager` (the `todo-repos.ts` precedent).
++ */
++export function createTestToursRepo(db: Database.Database): Promise<ToursRepository> {
++ return sharedTestOrm(db).then((t) => t.repo(Tours));
++}
++
++export function createTestTourWaypointsRepo(db: Database.Database): Promise<TourWaypointsRepository> {
++ return sharedTestOrm(db).then((t) => t.repo(TourWaypoints));
++}
++
++/** A `tours` row for an existing place, with the defaults a GPX import writes. */
++export function createTour(
++ db: Database.Database,
++ placeId: number,
++ overrides: Partial<{ distance: number | null; match_confidence: number | null; max_hiking_difficulty: number; created_at: string }> = {},
++): void {
++ db.prepare(
++ `INSERT INTO tours (place_id, tour_type, distance, match_confidence, max_hiking_difficulty, created_at)
++ VALUES (?, 'hike', ?, ?, ?, COALESCE(?, CURRENT_TIMESTAMP))`,
++ ).run(
++ placeId,
++ overrides.distance ?? null,
++ overrides.match_confidence ?? null,
++ overrides.max_hiking_difficulty ?? 2,
++ overrides.created_at ?? null,
++ );
++}
diff --cc server/tests/integration/journey-place-order.test.ts
index 000000000,ec1a8efbc..9ddbaeeb4
mode 000000,100644..100644
--- a/server/tests/integration/journey-place-order.test.ts
+++ b/server/tests/integration/journey-place-order.test.ts
@@@ -1,0 -1,135 +1,135 @@@
+ /**
+ * Regression for the Task 11 fix-round finding: PlacesService.onDeleted wraps
+ * a now-async JourneyDomainService.onPlaceDeleted call. The controller must
+ * await it before the place row (and its `journey_entries.source_place_id`
+ * FK, ON DELETE SET NULL) is actually deleted — otherwise the hook either
+ * never runs, or races the delete and finds nothing left to annotate.
+ *
+ * Wires PlacesController → PlacesService → JourneyDomainService for real (no
+ * journey mock), through the real buildApp() HTTP surface, and pins the
+ * end-to-end detach-then-annotate behaviour that path produces. It is NOT by
+ * itself a guard against a revert to fire-and-forget: the hook body today has
+ * no internal await, so it still runs to completion inside the same
+ * synchronous/microtask turn even if the controller stopped awaiting it, and
+ * this test would not notice. It becomes a true regression guard once the
+ * hook body awaits real async DB work of its own — see
+ * tests/unit/nest/places.controller.test.ts for the unit-level ordering test
+ * that stubs a macrotask hop and does catch a detached hook today.
+ */
+ import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
+ import request from 'supertest';
+ import type { Application } from 'express';
+ import type { INestApplication } from '@nestjs/common';
+
+ vi.mock('../../src/db/database', async () => {
+ const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
+ return buildDbMock(createSnapshotTestDb());
+ });
+ vi.mock('../../src/config', () => ({
+ JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
+ ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
+ updateJwtSecret: () => {},
+ SESSION_DURATION: '24h',
+ SESSION_DURATION_MS: 86400000,
+ SESSION_DURATION_SECONDS: 86400,
+ DEFAULT_LANGUAGE: 'en',
+ }));
+ vi.mock('../../src/websocket', () => ({
+ broadcast: vi.fn(),
+ broadcastToUser: vi.fn(),
+ getOnlineUserIds: vi.fn(() => []),
+ }));
+
+ import { db as testDb } from '../../src/db/database';
+ import { buildApp } from '../../src/bootstrap';
+ import { resetTestDb, resetRateLimits } from '../helpers/test-db';
+ import { createUser, createTrip, createPlace, createJourney, linkTripToJourney } from '../helpers/factories';
+ import { authCookie } from '../helpers/auth';
+ import { invalidatePermissionsCache } from '../../src/nest/permissions/permissions-cache';
+
+ let nestApp: INestApplication;
+ let app: Application;
+
+ beforeAll(async () => {
+ nestApp = await buildApp();
+ app = nestApp.getHttpAdapter().getInstance();
+ });
+ beforeEach(() => {
+ resetTestDb(testDb);
+ resetRateLimits(nestApp);
+ invalidatePermissionsCache();
+ // Enable the journey addon.
+ testDb.prepare(
+ "INSERT OR REPLACE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES ('journey', 'Journey', 'Travel journal', 'global', 'Compass', 1, 35)"
+ ).run();
+ });
+ afterAll(async () => {
+ await nestApp.close();
+ testDb.close();
+ });
+
+ describe('deleting a place detaches its journey entry ahead of the FK cascade', () => {
+ it('annotates a filled entry with the removal note instead of leaving it silently orphaned', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Café de Flore' });
+ const journey = createJourney(testDb, user.id);
+ linkTripToJourney(testDb, journey.id, trip.id);
+
+ // A filled entry (not a bare skeleton) sourced from this place, the way
+ // onPlaceDeleted documents: it survives the delete but gets detached and
+ // annotated, rather than deleted outright (that path is for content-less
+ // skeletons) or left dangling with a stale source_place_id.
+ const now = Date.now();
+ const entryId = testDb.prepare(`
+ INSERT INTO journey_entries (journey_id, source_trip_id, source_place_id, author_id, type, title, story, entry_date, visibility, sort_order, created_at, updated_at)
+ VALUES (?, ?, ?, ?, 'entry', ?, ?, '2026-01-15', 'private', 0, ?, ?)
+ `).run(journey.id, trip.id, place.id, user.id, 'A café', 'Lovely coffee.', now, now).lastInsertRowid;
+
+ const res = await request(app)
+ .delete(`/api/trips/${trip.id}/places/${place.id}`)
+ .set('Cookie', authCookie(user.id));
+ expect(res.status).toBe(200);
- expect(res.body).toEqual({ success: true });
++ expect(res.body).toEqual({ success: true, tourPlaceIds: [] });
+
+ // The place is gone.
+ expect(testDb.prepare('SELECT 1 FROM places WHERE id = ?').get(place.id)).toBeUndefined();
+
+ // The entry survives, detached and annotated — the FK's ON DELETE SET
+ // NULL alone would null source_place_id but would never touch story or
+ // type; only onPlaceDeleted having actually run produces the note.
+ const entry = testDb.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as {
+ source_place_id: number | null;
+ source_trip_id: number | null;
+ type: string;
+ story: string;
+ };
+ expect(entry.source_place_id).toBeNull();
+ expect(entry.source_trip_id).toBeNull();
+ expect(entry.type).toBe('entry');
+ expect(entry.story).toContain('the original trip place was removed from the trip plan');
+ });
+
+ it('deletes a content-less skeleton outright rather than leaving an orphaned row behind', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Musée Rodin' });
+ const journey = createJourney(testDb, user.id);
+ linkTripToJourney(testDb, journey.id, trip.id);
+
+ const now = Date.now();
+ const entryId = testDb.prepare(`
+ INSERT INTO journey_entries (journey_id, source_trip_id, source_place_id, author_id, type, title, entry_date, visibility, sort_order, created_at, updated_at)
+ VALUES (?, ?, ?, ?, 'skeleton', ?, '2026-01-16', 'private', 0, ?, ?)
+ `).run(journey.id, trip.id, place.id, user.id, place.name, now, now).lastInsertRowid;
+
+ const res = await request(app)
+ .delete(`/api/trips/${trip.id}/places/${place.id}`)
+ .set('Cookie', authCookie(user.id));
+ expect(res.status).toBe(200);
+
+ // onPlaceDeleted ran (and completed) as part of the request: the
+ // content-less skeleton is gone, not merely detached.
+ expect(testDb.prepare('SELECT 1 FROM journey_entries WHERE id = ?').get(entryId)).toBeUndefined();
+ });
+ });
diff --cc server/tests/unit/db/dialect/sql-functions.test.ts
index 000000000,2ca714059..66304d4ec
mode 000000,100644..100644
--- a/server/tests/unit/db/dialect/sql-functions.test.ts
+++ b/server/tests/unit/db/dialect/sql-functions.test.ts
@@@ -1,0 -1,1477 +1,1500 @@@
+ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
+ import { Platform } from '@mikro-orm/core';
+ import { expressionBuilder, type ExpressionBuilder } from 'kysely';
+ import { createSnapshotTestDb } from '../../../helpers/db-mock';
+ import { resetTestDb } from '../../../helpers/test-db';
+ import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
+ import { createUser } from '../../../helpers/factories';
+ import { Users } from '../../../../src/db/entities/Users.entity';
+ import {
+ absDifference,
+ caseWhenEquals,
++ caseWhenNotNull,
+ castInteger,
+ castIntegerKysely,
+ coalesce,
+ coalesceOverride,
+ coalesceOverrideWhileSame,
+ coalesceParam,
+ collateNoCase,
+ columnIncrementedBy,
+ columnRef,
+ concat,
+ concatKysely,
+ countAll,
+ countAllRef,
+ currentTimestamp,
+ currentTimestampKysely,
+ dateAdd,
+ dateOf,
+ dayDistance,
+ foundAgainState,
+ lower,
+ lowerParam,
+ lowerTrim,
+ lowerTrimParam,
+ maxOf,
+ minOf,
+ nowDateOffset,
+ nowMinusDays,
+ nowMinusHours,
+ nowPlusSeconds,
+ nowPlusSecondsKysely,
+ startsWithIsoDate,
+ startsWithIsoDateKysely,
+ substring,
+ substringKysely,
+ trim,
+ unixEpochToIsoKysely,
+ } from '../../../../src/db/dialect/sql-functions';
+ import { createJourney, createJourneyEntry } from '../../../helpers/factories';
+
+ /** The `users` columns the Kysely-expression tests below read/write, narrowed the same way every other Kysely-typed repository method in this program declares its own `TDB`. */
+ interface UsersKyselyDB {
+ users: {
+ id: number;
+ username: string;
+ display_name: string | null;
+ created_at: string | null;
+ };
+ }
+
+ const testDb = createSnapshotTestDb();
+ let t: TestOrm;
+
+ beforeAll(async () => { t = await createTestOrm(testDb); });
+ beforeEach(() => { resetTestDb(testDb); t.clear(); });
+ afterAll(async () => { await t.close(); testDb.close(); });
+
+ describe('sql-functions (sqlite)', () => {
+ it('SQLF-001: dateOf yields the calendar date of a stored timestamp', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare("UPDATE users SET created_at = '2026-09-21 13:05:09' WHERE id = ?").run(user.id);
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([dateOf(t.em.getPlatform(), 'u.created_at').as('d')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect(row).toEqual({ d: '2026-09-21' });
+ });
+
+ it('SQLF-002: dateAdd shifts by whole days', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare("UPDATE users SET created_at = '2026-09-21 13:05:09' WHERE id = ?").run(user.id);
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([dateAdd(t.em.getPlatform(), 'u.created_at', 10).as('d')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect(row).toEqual({ d: '2026-10-01' });
+ });
+
+ it('SQLF-003: currentTimestamp is the DB clock in the wire format', async () => {
+ createUser(testDb);
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([currentTimestamp(t.em.getPlatform()).as('now')])
+ .limit(1)
+ .execute('get', false);
+ expect(String((row as { now: string }).now)).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
+ });
+
+ it('SQLF-004: dateOf rejects anything that is not a plain column reference', () => {
+ expect(() => dateOf(t.em.getPlatform(), 'u.created_at); DROP TABLE users; --')).toThrow(/not a column reference/);
+ expect(() => dateOf(t.em.getPlatform(), 'u.created_at.extra')).toThrow(/not a column reference/);
+ expect(() => dateOf(t.em.getPlatform(), '')).toThrow(/not a column reference/);
+ });
+
+ it('SQLF-005: dateAdd rejects a non-integer day count', () => {
+ expect(() => dateAdd(t.em.getPlatform(), 'u.created_at', 1.5)).toThrow(/integer day count/);
+ expect(() => dateAdd(t.em.getPlatform(), 'u.created_at', Number.NaN)).toThrow(/integer day count/);
+ });
+
+ it('SQLF-006: dateAdd shifts backwards for a negative day count', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare("UPDATE users SET created_at = '2026-09-21 13:05:09' WHERE id = ?").run(user.id);
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([dateAdd(t.em.getPlatform(), 'u.created_at', -10).as('d')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect(row).toEqual({ d: '2026-09-11' });
+ });
+
+ it('SQLF-007: an unknown platform fails closed instead of guessing a spelling', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => dateOf(foreign, 'u.created_at')).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => dateAdd(foreign, 'u.created_at', 1)).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => currentTimestamp(foreign)).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => columnRef(foreign, 'u.max_uses')).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => columnIncrementedBy(foreign, 'u.used_count', 1)).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => lower(foreign, 'u.email')).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => lowerParam(foreign, 'x')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Plan 3b Task 1: UsersRepository's CI (case-insensitive) lookups
+ // (findByEmailCI, findIdByUsernameCI, ...) need `LOWER(col) = ?` as a
+ // `find`/`findOne` filter KEY, not just inside a QueryBuilder `.where()` —
+ // proving it works through `em.find`/`findOne` (the API the repository
+ // actually calls) rather than only through `createQueryBuilder`.
+ it('SQLF-012: lower is usable as a find() filter key, matching case-insensitively', async () => {
+ const { user } = createUser(testDb, { email: '[email protected]' });
+ const rows = await t.em.find(Users, { [lower(t.em.getPlatform(), 'email')]: '[email protected]' });
+ expect(rows.map((r) => r.id)).toEqual([user.id]);
+
+ // A differently-cased query value that still lowercases to the same
+ // string finds the same row; one that does not, finds nothing.
+ const none = await t.em.find(Users, { [lower(t.em.getPlatform(), 'email')]: '[email protected]' });
+ expect(none).toEqual([]);
+ });
+
+ it('SQLF-013: lower composes with other filter keys in one findOne call', async () => {
+ const { user } = createUser(testDb, { username: 'MixedCaseName' });
+ const row = await t.em.findOne(Users, {
+ [lower(t.em.getPlatform(), 'username')]: 'mixedcasename',
+ id: { $ne: -1 },
+ });
+ expect(row?.id).toBe(user.id);
+ });
+
+ // Plan 3b Task 0: InviteTokensRepository.incrementUsedCount needs a
+ // sibling-column comparison (`used_count < max_uses`) and a sibling-column
+ // increment (`used_count = used_count + 1`) inside a QueryBuilder filter —
+ // ESLint bans a repository from spelling `raw()` itself (src/db/repositories/**),
+ // so both go through these two dialect helpers instead.
+ it('SQLF-009: columnRef compares one column against another (not a bound value)', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET login_count = 5, password_version = 3 WHERE id = ?').run(user.id);
+ const below = await t.em.createQueryBuilder(Users, 'u')
+ .select('*')
+ .where({ id: user.id, password_version: { $lt: columnRef(t.em.getPlatform(), 'login_count') } })
+ .execute('get', false);
+ expect((below as { id: number } | undefined)?.id).toBe(user.id);
+
+ testDb.prepare('UPDATE users SET login_count = 1 WHERE id = ?').run(user.id);
+ const notBelow = await t.em.createQueryBuilder(Users, 'u')
+ .select('*')
+ .where({ id: user.id, password_version: { $lt: columnRef(t.em.getPlatform(), 'login_count') } })
+ .execute('get', false);
+ expect(notBelow).toBeUndefined();
+ });
+
+ it('SQLF-010: columnIncrementedBy writes <col> + n / <col> - n, never a bound-parameter add', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET login_count = 10 WHERE id = ?').run(user.id);
+ await t.em.createQueryBuilder(Users, 'u')
+ .update({ login_count: columnIncrementedBy(t.em.getPlatform(), 'login_count', 3) })
+ .where({ id: user.id })
+ .execute('run');
+ t.clear();
+ expect((testDb.prepare('SELECT login_count FROM users WHERE id = ?').get(user.id) as { login_count: number }).login_count).toBe(13);
+
+ await t.em.createQueryBuilder(Users, 'u')
+ .update({ login_count: columnIncrementedBy(t.em.getPlatform(), 'login_count', -5) })
+ .where({ id: user.id })
+ .execute('run');
+ t.clear();
+ expect((testDb.prepare('SELECT login_count FROM users WHERE id = ?').get(user.id) as { login_count: number }).login_count).toBe(8);
+ });
+
+ it('SQLF-011: columnIncrementedBy rejects a non-integer amount', () => {
+ expect(() => columnIncrementedBy(t.em.getPlatform(), 'u.login_count', 1.5)).toThrow(/integer amount/);
+ expect(() => columnIncrementedBy(t.em.getPlatform(), 'u.login_count', Number.NaN)).toThrow(/integer amount/);
+ });
+
+ // Plan 3b Task 0: OA8 (oauth_tokens' client-secret-rotation revoke) is the
+ // one call site in the whole codebase that spells "now" as `datetime('now')`
+ // instead of `CURRENT_TIMESTAMP` — same effective SQLite value, but D10
+ // wants exactly one dialect-function path. `currentTimestamp` already
+ // renders the literal `CURRENT_TIMESTAMP` fragment (SQLF-003 pins its wire
+ // format); this proves that fragment's stored text is byte-identical to
+ // what the legacy `datetime('now')` spelling produces, so OA8 (Task 4) can
+ // route through `currentTimestamp(platform)` with no behaviour change.
+ it("SQLF-008: currentTimestamp's CURRENT_TIMESTAMP spelling is byte-identical, in the same statement, to the legacy datetime('now') spelling", async () => {
+ // One atomic SELECT evaluates both expressions at the exact same instant —
+ // no timing window between two separate writes, so this is not a
+ // usually-true "close enough" comparison, it is a real strict equality.
+ const row = testDb.prepare("SELECT CURRENT_TIMESTAMP as a, datetime('now') as b").get() as { a: string; b: string };
+ expect(row.a).toBe(row.b);
+ expect(row.a).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
+
+ // And a real write through the repository-facing dialect helper, read
+ // back through the raw connection, stores that exact same shape — not
+ // just the fragment text in isolation.
+ const { user } = createUser(testDb);
+ await t.em.createQueryBuilder(Users, 'u')
+ .update({ created_at: currentTimestamp(t.em.getPlatform()) })
+ .where({ id: user.id })
+ .execute('run');
+ t.clear();
+ const stored = testDb.prepare('SELECT created_at FROM users WHERE id = ?').get(user.id) as { created_at: string };
+ expect(stored.created_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
+ });
+
+ // Program rule 18 / Plan 3b Task 7 review H1: SQLite's LOWER() is
+ // ASCII-only; JavaScript's toLowerCase() is full-Unicode. lowerParam()
+ // binds the RAW value so SQLite folds both sides of the comparison with
+ // the same engine, matching a legacy `LOWER(col) = LOWER(?)` statement.
+ it('SQLF-014: SQLite LOWER() is ASCII-only, unlike JS toLowerCase() — verified directly', () => {
+ const cases: Array<[string, string]> = [
+ ['JOSÉ@x.com', 'josÉ@x.com'],
+ ];
+ for (const [input, sqliteLowered] of cases) {
+ const row = testDb.prepare('SELECT LOWER(?) as l').get(input) as { l: string };
+ expect(row.l).toBe(sqliteLowered);
+ // Every non-ASCII case proves the two engines disagree.
+ if (input !== '[email protected]') {
+ expect(row.l).not.toBe(input.toLowerCase());
+ }
+ }
+ });
+
+ it('SQLF-015: lowerParam pairs with lower() to fold BOTH sides in SQLite, matching a non-ASCII stored spelling that toLowerCase() would miss', async () => {
+ const { user } = createUser(testDb, { email: 'JOSÉ@x.com' });
+ const platform = t.em.getPlatform();
+
+ // The exact stored spelling matches (SQLite's LOWER() is a no-op on both
+ // sides for this input, so this is really an equality check — the real
+ // proof is the next assertion).
+ const exact = await t.em.findOne(Users, { [lower(platform, 'email')]: lowerParam(platform, 'JOSÉ@x.com') });
+ expect(exact?.id).toBe(user.id);
+
+ // A JS-lowered value-side bind (the bug: mixing engines) must NOT match
+ // — this is the mutation-proof: reverting `lowerParam(platform, email)`
+ // to a plain `email.toLowerCase()` bind makes this assertion fail
+ // because SQLite's LOWER(column) still reads 'josÉ@x.com', which does
+ // not equal the JS-lowered bind 'josé@x.com'.
+ const jsLowered = await t.em.findOne(Users, { [lower(platform, 'email')]: 'josé@x.com' });
+ expect(jsLowered).toBeNull();
+
+ const none = await t.em.findOne(Users, { [lower(platform, 'email')]: lowerParam(platform, '[email protected]') });
+ expect(none).toBeNull();
+ });
+
+ // Plan 3c Task 0b (R6): no consumer yet — Tasks 1–8 wire these in as each
+ // converts the statement that needs them. Pinned here so a later task
+ // imports a tested helper instead of writing one inline.
+
+ it("SQLF-016: nowMinusDays renders datetime('now', '-N days'), matching a JS-computed date within a few seconds' tolerance", async () => {
+ const row = testDb.prepare(`SELECT ${nowMinusDays(t.em.getPlatform(), 5).sql} as d`).get() as { d: string };
+ const got = new Date(`${row.d.replace(' ', 'T')}Z`).getTime();
+ const expected = Date.now() - 5 * 24 * 60 * 60 * 1000;
+ expect(Math.abs(got - expected)).toBeLessThan(10_000);
+ });
+
+ it('SQLF-016b: nowMinusDays(0) is "now", not one day back', async () => {
+ const row = testDb.prepare(`SELECT ${nowMinusDays(t.em.getPlatform(), 0).sql} as d`).get() as { d: string };
+ const got = new Date(`${row.d.replace(' ', 'T')}Z`).getTime();
+ expect(Math.abs(got - Date.now())).toBeLessThan(10_000);
+ });
+
+ it('SQLF-017: nowMinusDays rejects a non-integer or negative day count', () => {
+ expect(() => nowMinusDays(t.em.getPlatform(), 1.5)).toThrow(/non-negative integer day count/);
+ expect(() => nowMinusDays(t.em.getPlatform(), -1)).toThrow(/non-negative integer day count/);
+ expect(() => nowMinusDays(t.em.getPlatform(), Number.NaN)).toThrow(/non-negative integer day count/);
+ });
+
+ it('SQLF-018: trim strips leading/trailing whitespace', async () => {
+ const { user } = createUser(testDb, { username: ' Padded Name ' });
+ const platform = t.em.getPlatform();
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([trim(platform, 'u.username').as('n')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect((row as { n: string }).n).toBe('Padded Name');
+ });
+
+ it('SQLF-019: coalesce(ref, fallbackRef) picks the first non-null column, else the second', async () => {
+ const { user: withName } = createUser(testDb, { username: 'has-display-name' });
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('Display Name', withName.id);
+ const { user: withoutName } = createUser(testDb, { username: 'no-display-name' });
+ const platform = t.em.getPlatform();
+
+ const a = await t.em.createQueryBuilder(Users, 'u')
+ .select([coalesce(platform, 'u.display_name', 'u.username').as('name')])
+ .where({ id: withName.id })
+ .execute('get', false);
+ expect((a as { name: string }).name).toBe('Display Name');
+
+ const b = await t.em.createQueryBuilder(Users, 'u')
+ .select([coalesce(platform, 'u.display_name', 'u.username').as('name')])
+ .where({ id: withoutName.id })
+ .execute('get', false);
+ expect((b as { name: string }).name).toBe('no-display-name');
+ });
+
+ it('SQLF-020: coalesceParam(ref, value) writes COALESCE(col, ?) with the fallback bound, not another column', async () => {
+ const { user } = createUser(testDb);
+ const platform = t.em.getPlatform();
+ await t.em.createQueryBuilder(Users, 'u')
+ .update({ display_name: coalesceParam(platform, 'display_name', 'Fallback Name') })
+ .where({ id: user.id })
+ .execute('run');
+ t.clear();
+ expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(user.id) as { display_name: string }).display_name).toBe('Fallback Name');
+
+ await t.em.createQueryBuilder(Users, 'u')
+ .update({ display_name: coalesceParam(platform, 'display_name', 'Never Used') })
+ .where({ id: user.id })
+ .execute('run');
+ t.clear();
+ expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(user.id) as { display_name: string }).display_name).toBe('Fallback Name');
+ });
+
+ // Plan 3h Task 5 (doc-sync, DS23/DS24) — `coalesceOverride`, the
+ // mirror-image value-side shape `COALESCE(?, col)`: the caller's NEW
+ // value wins unless it is null, unlike `coalesceParam`'s `COALESCE(col,
+ // ?)` above (existing column wins unless IT is null). Confirmed
+ // genuinely the opposite direction by a live round-trip, not assumed from
+ // the two functions' similar names.
+ it('SQLF-090: coalesceOverride(value, ref) writes COALESCE(?, col) — a non-null new value overwrites the existing column', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('Old Name', user.id);
+ const platform = t.em.getPlatform();
+ await t.em.createQueryBuilder(Users, 'u')
+ .update({ display_name: coalesceOverride(platform, 'New Name', 'display_name') })
+ .where({ id: user.id })
+ .execute('run');
+ t.clear();
+ expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(user.id) as { display_name: string }).display_name).toBe('New Name');
+ });
+
+ it('SQLF-091: coalesceOverride(null, ref) leaves the existing column untouched — a null new value never clobbers what is stored', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('Keep Me', user.id);
+ const platform = t.em.getPlatform();
+ await t.em.createQueryBuilder(Users, 'u')
+ .update({ display_name: coalesceOverride(platform, null, 'display_name') })
+ .where({ id: user.id })
+ .execute('run');
+ t.clear();
+ expect((testDb.prepare('SELECT display_name FROM users WHERE id = ?').get(user.id) as { display_name: string }).display_name).toBe('Keep Me');
+ });
+
+ it('SQLF-092: an unknown platform fails closed for coalesceOverride', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => coalesceOverride(foreign, 'x', 'u.a')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // `coalesceOverrideWhileSame` — IM4's `immich_allow_insecure_tls = CASE WHEN
+ // immich_url IS ? THEN COALESCE(?, immich_allow_insecure_tls) ELSE
+ // COALESCE(?, 0) END` (#2475), driven through the same `users` columns the
+ // repository writes, in ONE UPDATE that also overwrites the key column —
+ // proving the WHEN reads the stored URL, not the one being written.
+ describe('coalesceOverrideWhileSame (IM4 self-signed switch)', () => {
+ async function save(userId: number, url: string, value: number | null): Promise<{ immich_url: string; immich_allow_insecure_tls: number }> {
+ const platform = t.em.getPlatform();
+ await t.em.createQueryBuilder(Users, 'u')
+ .update({
+ immich_url: url,
+ immich_allow_insecure_tls: coalesceOverrideWhileSame(platform, value, 'immich_allow_insecure_tls', 'immich_url', url),
+ })
+ .where({ id: userId })
+ .execute('run');
+ t.clear();
+ return testDb.prepare('SELECT immich_url, immich_allow_insecure_tls FROM users WHERE id = ?').get(userId) as { immich_url: string; immich_allow_insecure_tls: number };
+ }
+
+ it('SQLF-093: a null value keeps the stored column while the key column still holds the value being written', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET immich_url = ?, immich_allow_insecure_tls = 1 WHERE id = ?').run('https://nas.local', user.id);
+ expect(await save(user.id, 'https://nas.local', null)).toEqual({ immich_url: 'https://nas.local', immich_allow_insecure_tls: 1 });
+ // Symmetric: a stored 0 is kept too, not merely "anything truthy survives".
+ testDb.prepare('UPDATE users SET immich_allow_insecure_tls = 0 WHERE id = ?').run(user.id);
+ expect(await save(user.id, 'https://nas.local', null)).toEqual({ immich_url: 'https://nas.local', immich_allow_insecure_tls: 0 });
+ });
+
+ it('SQLF-094: a non-null value overwrites the stored column in both directions, same key or not', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET immich_url = ?, immich_allow_insecure_tls = 1 WHERE id = ?').run('https://nas.local', user.id);
+ expect((await save(user.id, 'https://nas.local', 0)).immich_allow_insecure_tls).toBe(0);
+ expect((await save(user.id, 'https://nas.local', 1)).immich_allow_insecure_tls).toBe(1);
+ expect((await save(user.id, 'https://other.example.com', 1)).immich_allow_insecure_tls).toBe(1);
+ expect((await save(user.id, 'https://nas.local', 0)).immich_allow_insecure_tls).toBe(0);
+ });
+
+ it('SQLF-095: a null value falls back to 0, not to the stored column, once the key column changes — including from NULL (a first connection)', async () => {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET immich_url = ?, immich_allow_insecure_tls = 1 WHERE id = ?').run('https://nas.local', user.id);
+ expect(await save(user.id, 'https://photos.example.com', null)).toEqual({ immich_url: 'https://photos.example.com', immich_allow_insecure_tls: 0 });
+ // `IS` (not `=`) so a stored NULL url compares as "different", never as unknown.
+ testDb.prepare('UPDATE users SET immich_url = NULL, immich_allow_insecure_tls = 1 WHERE id = ?').run(user.id);
+ expect(await save(user.id, 'https://nas.local', null)).toEqual({ immich_url: 'https://nas.local', immich_allow_insecure_tls: 0 });
+ });
+
+ it('SQLF-096: matches the legacy CASE text row-for-row across every (stored url, new url, value) combination', async () => {
+ const { user } = createUser(testDb);
+ const legacy = testDb.prepare(
+ `UPDATE users SET immich_url = ?, immich_allow_insecure_tls = CASE WHEN immich_url IS ? THEN COALESCE(?, immich_allow_insecure_tls) ELSE COALESCE(?, 0) END WHERE id = ?`,
+ );
+ for (const storedUrl of [null, 'https://nas.local']) {
+ for (const storedFlag of [0, 1]) {
+ for (const newUrl of ['https://nas.local', 'https://photos.example.com']) {
+ for (const value of [null, 0, 1]) {
+ testDb.prepare('UPDATE users SET immich_url = ?, immich_allow_insecure_tls = ? WHERE id = ?').run(storedUrl, storedFlag, user.id);
+ legacy.run(newUrl, newUrl, value, value, user.id);
+ const expected = testDb.prepare('SELECT immich_url, immich_allow_insecure_tls FROM users WHERE id = ?').get(user.id);
+ testDb.prepare('UPDATE users SET immich_url = ?, immich_allow_insecure_tls = ? WHERE id = ?').run(storedUrl, storedFlag, user.id);
+ expect(await save(user.id, newUrl, value)).toEqual(expected);
+ }
+ }
+ }
+ }
+ });
+
+ it('SQLF-097: an unknown platform fails closed for coalesceOverrideWhileSame', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => coalesceOverrideWhileSame(foreign, null, 'u.a', 'u.b', 'x')).toThrow(/no implementation for platform FakePlatform/);
+ });
+ });
+
+ it('SQLF-021: absDifference is usable as a filter key, matching ABS(col - ?) <= tolerance', async () => {
+ const { user: near } = createUser(testDb);
+ testDb.prepare('UPDATE users SET login_count = 12 WHERE id = ?').run(near.id);
+ const { user: far } = createUser(testDb);
+ testDb.prepare('UPDATE users SET login_count = 100 WHERE id = ?').run(far.id);
+ const platform = t.em.getPlatform();
+
+ const rows = await t.em.find(Users, { [absDifference(platform, 'login_count', 10)]: { $lte: 5 } });
+ expect(rows.map((r) => r.id)).toEqual([near.id]);
+
+ const none = await t.em.find(Users, { [absDifference(platform, 'login_count', 10)]: { $lte: 0 } });
+ expect(none).toEqual([]);
+ });
+
+ it('SQLF-022: an unknown platform fails closed for every Plan 3c Task 0b helper', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => nowMinusDays(foreign, 1)).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => trim(foreign, 'u.name')).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => coalesce(foreign, 'u.a', 'u.b')).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => coalesceParam(foreign, 'u.a', 'x')).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => absDifference(foreign, 'u.lat', 1)).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Plan 3c Task 1 (§17a: COUNT(*)/MIN/MAX aggregates — `PlaceShadowPicksRepository
+ // .totals`/`countBySource`/`countByLiveRank`). ESLint bans `raw()` inside
+ // src/db/repositories/**, so these three aliased-aggregate helpers exist
+ // for repositories that need a COUNT/MIN/MAX in a SELECT projection.
+
+ it('SQLF-023: countAll/minOf/maxOf render one aliased aggregate row, matching a hand-written statement', async () => {
+ const { user: a } = createUser(testDb);
+ testDb.prepare("UPDATE users SET created_at = '2026-01-01 00:00:00' WHERE id = ?").run(a.id);
+ const { user: b } = createUser(testDb);
+ testDb.prepare("UPDATE users SET created_at = '2026-06-15 00:00:00' WHERE id = ?").run(b.id);
+ const platform = t.em.getPlatform();
+
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([countAll(platform, 'total'), minOf(platform, 'u.created_at', 'oldest'), maxOf(platform, 'u.created_at', 'newest')])
+ .where({ id: { $in: [a.id, b.id] } })
+ .execute('get', false);
+ expect(row).toEqual({ total: 2, oldest: '2026-01-01 00:00:00', newest: '2026-06-15 00:00:00' });
+
+ const expected = testDb
+ .prepare('SELECT COUNT(*) as total, MIN(created_at) as oldest, MAX(created_at) as newest FROM users WHERE id IN (?, ?)')
+ .get(a.id, b.id);
+ expect(row).toEqual(expected);
+ });
+
+ // No `.orderBy({ count: 'desc' })` here: MikroORM's QueryBuilder cannot
+ // order by an ad-hoc raw-fragment alias (verified directly — it throws
+ // "Trying to query by not existing property" at runtime, since `raw()`'s
+ // alias carries no literal type for `ExtractRawAliases` to register). The
+ // repository callers that need "ORDER BY <aliased count> DESC"
+ // (`PlaceShadowPicksRepository.countBySource`) order by the `COUNT(*)`
+ // EXPRESSION instead, via `countAllRef` below (SQLF-032) — NOT a JS
+ // `Array.prototype.sort` of the fetched rows: that would be stable and
+ // therefore leave ties in `GROUP BY`'s own (ascending-by-key) row order,
+ // which is not the same order SQLite's own, non-stable `ORDER BY count
+ // DESC` sorter produces on a tie (Task 1 fix review M1).
+ it('SQLF-024: countAll composes with GROUP BY, matching a hand-written GROUP BY statement', async () => {
+ createUser(testDb, { role: 'admin' });
+ createUser(testDb, { role: 'admin' });
+ createUser(testDb, { role: 'user' });
+ const platform = t.em.getPlatform();
+
+ const rows = await t.em.createQueryBuilder(Users, 'u')
+ .select(['u.role', countAll(platform, 'count')])
+ .groupBy('u.role')
+ .execute('all', false);
+
+ const expected = testDb.prepare('SELECT role, COUNT(*) as count FROM users GROUP BY role').all();
+ expect([...(rows as { role: string; count: number }[])].sort((a, b) => a.role.localeCompare(b.role)))
+ .toEqual([...(expected as { role: string; count: number }[])].sort((a, b) => a.role.localeCompare(b.role)));
+ });
+
+ it('SQLF-025: countAll/minOf/maxOf reject an alias that is not a plain identifier', () => {
+ const platform = t.em.getPlatform();
+ expect(() => countAll(platform, 'x; DROP TABLE users; --')).toThrow(/not an alias/);
+ expect(() => minOf(platform, 'u.created_at', '1bad')).toThrow(/not an alias/);
+ expect(() => maxOf(platform, 'u.created_at', '')).toThrow(/not an alias/);
+ });
+
+ it('SQLF-026: an unknown platform fails closed for countAll/minOf/maxOf', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => countAll(foreign, 'total')).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => minOf(foreign, 'u.created_at', 'oldest')).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => maxOf(foreign, 'u.created_at', 'newest')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Task 0b review M3 (blocks Task 4's PL26, places.service.ts:642
+ // `lower(trim(name))`): `lower()`/`trim()` cannot compose to build
+ // `LOWER(TRIM(name))` — `lowerTrim()` is the one fragment for that shape.
+ it('SQLF-027: lowerTrim renders LOWER(TRIM(<col>)) as one fragment, matching a hand-written statement', async () => {
+ const { user } = createUser(testDb, { username: ' Padded Name ' });
+ const platform = t.em.getPlatform();
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([lowerTrim(platform, 'u.username').as('n')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect((row as { n: string }).n).toBe('padded name');
+
+ const expected = testDb.prepare('SELECT LOWER(TRIM(username)) as n FROM users WHERE id = ?').get(user.id) as { n: string };
+ expect((row as { n: string }).n).toBe(expected.n);
+ });
+
+ it('SQLF-028: lowerTrim is usable as a find() filter key, and SQLite LOWER() stays ASCII-only through the TRIM', async () => {
+ const { user } = createUser(testDb, { username: ' JOSÉ ' });
+ const platform = t.em.getPlatform();
+ const rows = await t.em.find(Users, { [lowerTrim(platform, 'username')]: 'josé'.toLowerCase() });
+ // toLowerCase() is full-Unicode ('é' stays 'é'), but SQLite's LOWER() is
+ // ASCII-only and leaves 'É' untouched — so the JS-lowered bind does NOT
+ // match the SQL-lowered, SQL-trimmed column (program rule 18: mixing
+ // engines is the bug, not the fix).
+ expect(rows).toEqual([]);
+ const matching = await t.em.find(Users, { [lowerTrim(platform, 'username')]: 'josÉ' });
+ expect(matching.map((r) => r.id)).toEqual([user.id]);
+ });
+
+ it('SQLF-029: an unknown platform fails closed for lowerTrim', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => lowerTrim(foreign, 'u.name')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Plan 3c Task 6 — `TripMembersRepository.listWithUserAndInviter`'s `role`
+ // column (TM2): `CASE WHEN u.id = ? THEN 'owner' ELSE 'member' END`.
+ it("SQLF-030: caseWhenEquals renders CASE WHEN <col> = ? THEN ? ELSE ? END, matching a hand-written statement", async () => {
+ const { user: a } = createUser(testDb);
+ const { user: b } = createUser(testDb);
+ const platform = t.em.getPlatform();
+
+ const rows = await t.em.createQueryBuilder(Users, 'u')
+ .select(['u.id', caseWhenEquals(platform, 'u.id', a.id, 'owner', 'member').as('role')])
+ .where({ id: { $in: [a.id, b.id] } })
+ .orderBy({ id: 'asc' })
+ .execute('all', false);
+ expect(rows).toEqual([{ id: a.id, role: 'owner' }, { id: b.id, role: 'member' }]);
+
+ const expected = testDb
+ .prepare('SELECT id, CASE WHEN id = ? THEN ? ELSE ? END as role FROM users WHERE id IN (?, ?) ORDER BY id ASC')
+ .all(a.id, 'owner', 'member', a.id, b.id);
+ expect(rows).toEqual(expected);
+ });
+
+ it('SQLF-031: an unknown platform fails closed for caseWhenEquals', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => caseWhenEquals(foreign, 'u.id', 1, 'owner', 'member')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
++ // Tours (#2586): the assignment projection's `tour_route_geometry` column.
++ it('SQLF-098: caseWhenNotNull yields the THEN column only where the test column is not null', async () => {
++ const { user: a } = createUser(testDb);
++ const { user: b } = createUser(testDb);
++ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('Shown', a.id);
++ testDb.prepare('UPDATE users SET display_name = NULL WHERE id = ?').run(b.id);
++ const platform = t.em.getPlatform();
++
++ const rows = await t.em.createQueryBuilder(Users, 'u')
++ .select(['u.id', caseWhenNotNull(platform, 'u.display_name', 'u.username').as('picked')])
++ .where({ id: { $in: [a.id, b.id] } })
++ .orderBy({ id: 'asc' })
++ .execute('all', false);
++ expect(rows).toEqual([{ id: a.id, picked: a.username }, { id: b.id, picked: null }]);
++ });
++
++ it('SQLF-099: an unknown platform fails closed for caseWhenNotNull', () => {
++ class FakePlatform extends Platform {}
++ const foreign = new FakePlatform();
++ expect(() => caseWhenNotNull(foreign, 'u.a', 'u.b')).toThrow(/no implementation for platform FakePlatform/);
++ });
++
+ // Task 1 fix review M1 (`PlaceShadowPicksRepository.countBySource`, PS5):
+ // `countAll()`'s alias cannot be ordered by (`.orderBy({ count: 'desc' })`
+ // throws "not existing property" — verified in SQLF-024's comment above);
+ // `countAllRef` orders by the `COUNT(*)` EXPRESSION instead, which SQLite
+ // accepts. The full tie-order proof (against the legacy `ORDER BY count
+ // DESC` statement, on data with tied counts) lives in
+ // `PlaceShadowPicksRepository.countBySource`'s own test (PSPICKREPO-006b) —
+ // this pins the fragment's shape and composition with GROUP BY.
+ it('SQLF-032: countAllRef renders COUNT(*) as an ORDER BY expression, matching a hand-written GROUP BY … ORDER BY statement', async () => {
+ createUser(testDb, { role: 'admin' });
+ createUser(testDb, { role: 'admin' });
+ createUser(testDb, { role: 'user' });
+ const platform = t.em.getPlatform();
+
+ const rows = await t.em.createQueryBuilder(Users, 'u')
+ .select(['u.role', countAll(platform, 'count')])
+ .groupBy('u.role')
+ .orderBy({ [countAllRef(platform)]: 'desc' })
+ .execute('all', false);
+
+ const expected = testDb.prepare('SELECT role, COUNT(*) as count FROM users GROUP BY role ORDER BY COUNT(*) DESC').all();
+ expect(rows).toEqual(expected);
+ });
+
+ it('SQLF-033: an unknown platform fails closed for countAllRef', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => countAllRef(foreign)).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Plan 3d Task 0 (R6): no consumer yet — Tasks 2/4 wire these in as each
+ // converts RS11/RS20/RV2/DY23. Pinned here so a later task imports a
+ // tested helper instead of writing one inline.
+
+ it('SQLF-034: startsWithIsoDate matches a value that begins with YYYY-MM-DD, and only that shape (dates, non-dates, "2026-1-1", empty, NULL)', async () => {
+ const platform = t.em.getPlatform();
+ const cases: Array<[string | null, boolean]> = [
+ ['2026-09-21', true],
+ ['2026-09-21T13:05:09Z', true],
+ ['2026-09-21 13:05:09', true],
+ ['not-a-date', false],
+ ['2026-1-1', false], // not zero-padded — the legacy pattern is exactly 4-2-2 digit classes, not a wildcard shorthand
+ ['abcd-ef-gh', false], // Task 0 review L1 — the wider '????-??-??*' shorthand WOULD match this (a `?` matches any char); the digit-class pattern must not
+ ['yyyy-mm-dd', false], // Task 0 review L1 — same reason, letters where the pattern requires digits
+ ['', false],
+ [null, false],
+ ];
+ for (const [value, expected] of cases) {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run(value, user.id);
+
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([startsWithIsoDate(platform, 'u.display_name').as('matched')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect(Boolean((row as { matched: number | null }).matched)).toBe(expected);
+
+ const raw = testDb
+ .prepare(`SELECT (display_name GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*') as matched FROM users WHERE id = ?`)
+ .get(user.id) as { matched: number | null };
+ expect(Boolean(raw.matched)).toBe(expected);
+ }
+ });
+
+ it('SQLF-035: an unknown platform fails closed for startsWithIsoDate', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => startsWithIsoDate(foreign, 'u.reservation_time')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it('SQLF-036: substring(ref, start) — the two-arg form — reads from a 1-based position to the end, matching substr(col, N)', async () => {
+ const { user } = createUser(testDb, { username: 'iso-ts' });
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('2026-09-21T13:05:09Z', user.id);
+ const platform = t.em.getPlatform();
+
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([substring(platform, 'u.display_name', 12).as('n')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect((row as { n: string }).n).toBe('13:05:09Z');
+
+ const expected = testDb.prepare('SELECT substr(display_name, 12) as n FROM users WHERE id = ?').get(user.id) as { n: string };
+ expect((row as { n: string }).n).toBe(expected.n);
+ });
+
+ it('SQLF-037: substring(ref, start, length) — the three-arg form — matches substr(col, N, L)', async () => {
+ const { user } = createUser(testDb, { username: 'iso-ts-2' });
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('2026-09-21T13:05:09Z', user.id);
+ const platform = t.em.getPlatform();
+
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([substring(platform, 'u.display_name', 1, 10).as('n')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect((row as { n: string }).n).toBe('2026-09-21');
+
+ const expected = testDb.prepare('SELECT substr(display_name, 1, 10) as n FROM users WHERE id = ?').get(user.id) as { n: string };
+ expect((row as { n: string }).n).toBe(expected.n);
+ });
+
+ it('SQLF-038: substring rejects a non-positive start or a negative length', () => {
+ const platform = t.em.getPlatform();
+ expect(() => substring(platform, 'u.x', 0)).toThrow(/1-based integer start/);
+ expect(() => substring(platform, 'u.x', 1.5)).toThrow(/1-based integer start/);
+ expect(() => substring(platform, 'u.x', 1, -1)).toThrow(/non-negative integer length/);
+ expect(() => substring(platform, 'u.x', 1, 1.5)).toThrow(/non-negative integer length/);
+ });
+
+ it('SQLF-039: an unknown platform fails closed for substring', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => substring(foreign, 'u.x', 1)).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it('SQLF-040: concat renders <col> || <bound-literal> || <col>, matching the legacy d.date || \'T\' || a.check_in shape', async () => {
+ const { user } = createUser(testDb, { username: 'concat-me' });
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('13:05', user.id);
+ const platform = t.em.getPlatform();
+
+ const row = await t.em.createQueryBuilder(Users, 'u')
+ .select([concat(platform, { column: 'u.username' }, { value: 'T' }, { column: 'u.display_name' }).as('n')])
+ .where({ id: user.id })
+ .execute('get', false);
+ expect((row as { n: string }).n).toBe('concat-meT13:05');
+
+ const expected = testDb.prepare("SELECT username || ? || display_name as n FROM users WHERE id = ?").get('T', user.id) as { n: string };
+ expect((row as { n: string }).n).toBe(expected.n);
+ });
+
+ it('SQLF-041: concat rejects fewer than two parts', () => {
+ const platform = t.em.getPlatform();
+ expect(() => concat(platform, { column: 'u.a' })).toThrow(/at least two parts/);
+ expect(() => concat(platform)).toThrow(/at least two parts/);
+ });
+
+ it('SQLF-042: an unknown platform fails closed for concat', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => concat(foreign, { column: 'u.a' }, { value: 'x' })).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // §18.1: reservations.accommodation_id is TEXT holding integer ids with no
+ // FK; some rows read back as "14.0". castInteger exists so a comparison
+ // against a genuine INTEGER column matches both spellings the way the
+ // legacy CAST(... AS INTEGER) statement does.
+ it('SQLF-043: castInteger matches both "14" and "14.0" TEXT rows against a bound INTEGER value (the accommodation_id shape, §18.1)', async () => {
+ const platform = t.em.getPlatform();
+ const { user: exact } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('14', exact.id);
+ const { user: dotZero } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('14.0', dotZero.id);
+ const { user: other } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('15', other.id);
+
+ const rows = await t.em.createQueryBuilder(Users, 'u')
+ .select('u.id')
+ .where({ id: { $in: [exact.id, dotZero.id, other.id] }, [castInteger(platform, 'u.display_name')]: 14 })
+ .orderBy({ id: 'asc' })
+ .execute('all', false);
+ expect((rows as { id: number }[]).map((r) => r.id)).toEqual([exact.id, dotZero.id]);
+
+ const expected = testDb
+ .prepare('SELECT id FROM users WHERE id IN (?, ?, ?) AND CAST(display_name AS INTEGER) = ? ORDER BY id ASC')
+ .all(exact.id, dotZero.id, other.id, 14);
+ expect(rows).toEqual(expected);
+ });
+
+ it('SQLF-044: castInteger compares against another column via columnRef, matching CAST(col AS INTEGER) = other_col (the real RV2/RS20 shape)', async () => {
+ const platform = t.em.getPlatform();
+ const { user: exact } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run(String(exact.id), exact.id);
+ const { user: dotZero } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run(`${dotZero.id}.0`, dotZero.id);
+ const { user: mismatched } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run(String(exact.id), mismatched.id);
+
+ const rows = await t.em.createQueryBuilder(Users, 'u')
+ .select('u.id')
+ .where({ id: { $in: [exact.id, dotZero.id, mismatched.id] }, [castInteger(platform, 'u.display_name')]: columnRef(platform, 'u.id') })
+ .orderBy({ id: 'asc' })
+ .execute('all', false);
+ expect((rows as { id: number }[]).map((r) => r.id)).toEqual([exact.id, dotZero.id]);
+
+ const expected = testDb
+ .prepare('SELECT id FROM users WHERE id IN (?, ?, ?) AND CAST(display_name AS INTEGER) = id ORDER BY id ASC')
+ .all(exact.id, dotZero.id, mismatched.id);
+ expect(rows).toEqual(expected);
+ });
+
+ it('SQLF-045: an unknown platform fails closed for castInteger', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => castInteger(foreign, 'u.accommodation_id')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it('SQLF-046: dayDistance orders by nearest calendar date, matching ORDER BY ABS(JULIANDAY(col) - JULIANDAY(?)) ASC', async () => {
+ const platform = t.em.getPlatform();
+ const { user: a } = createUser(testDb);
+ testDb.prepare("UPDATE users SET created_at = '2026-01-01 00:00:00' WHERE id = ?").run(a.id);
+ const { user: b } = createUser(testDb);
+ testDb.prepare("UPDATE users SET created_at = '2026-06-15 00:00:00' WHERE id = ?").run(b.id);
+ const { user: c } = createUser(testDb);
+ testDb.prepare("UPDATE users SET created_at = '2026-06-20 00:00:00' WHERE id = ?").run(c.id);
+ const target = '2026-06-18';
+
+ const rows = await t.em.createQueryBuilder(Users, 'u')
+ .select('u.id')
+ .where({ id: { $in: [a.id, b.id, c.id] } })
+ .orderBy({ [dayDistance(platform, 'u.created_at', target)]: 'asc' })
+ .execute('all', false);
+ expect((rows as { id: number }[]).map((r) => r.id)).toEqual([c.id, b.id, a.id]);
+
+ const expected = testDb
+ .prepare('SELECT id FROM users WHERE id IN (?, ?, ?) ORDER BY ABS(JULIANDAY(created_at) - JULIANDAY(?)) ASC')
+ .all(a.id, b.id, c.id, target);
+ expect(rows).toEqual(expected);
+ });
+
+ it('SQLF-047: an unknown platform fails closed for dayDistance', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => dayDistance(foreign, 'u.date', '2026-01-01')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Plan 3d Task 0 review (H1/L1): the five helpers above return a MikroORM
+ // RawQueryFragment, which stringifies to a literal `?` token and throws at
+ // execution when handed into a Kysely statement — verified directly below
+ // (the whole reason these Kysely-native twins exist). Task 2 absorbed this
+ // finding; DY23 (`ReservationsRepository.restampLinkedReservation`) is the
+ // first consumer.
+
+ it('SQLF-048: a MikroORM RawQueryFragment cannot be coerced to a plain string outside the MikroORM QueryBuilder that produced it — the H1 finding, proven directly ([Symbol.toPrimitive]("string") returns an internal Symbol key the QueryBuilder recognises to re-substitute the real SQL text; nothing else, Kysely included, understands that key, which is why the Kysely-native twins below exist instead of reusing this fragment)', () => {
+ const platform = t.em.getPlatform();
+ const fragment = startsWithIsoDate(platform, 'username');
+ expect(typeof fragment[Symbol.toPrimitive]('string')).toBe('symbol');
+ expect(() => `${fragment}`).toThrow(TypeError);
+ });
+
+ it('SQLF-049: startsWithIsoDateKysely matches the same shapes as startsWithIsoDate (dates, non-dates, letters-in-place-of-digits, empty, NULL)', async () => {
+ const platform = t.em.getPlatform();
+ const cases: Array<[string | null, boolean]> = [
+ ['2026-09-21', true],
+ ['2026-09-21T13:05:09Z', true],
+ ['not-a-date', false],
+ ['2026-1-1', false],
+ ['abcd-ef-gh', false],
+ ['yyyy-mm-dd', false],
+ ['', false],
+ [null, false],
+ ];
+ for (const [value, expected] of cases) {
+ const { user } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run(value, user.id);
+
+ const row = await t.em.getKysely<UsersKyselyDB>()
+ .selectFrom('users')
+ .select((eb) => [startsWithIsoDateKysely(platform, eb, 'display_name').as('matched')])
+ .where('id', '=', user.id)
+ .executeTakeFirstOrThrow();
+ expect(Boolean(row.matched)).toBe(expected);
+
+ const raw = testDb
+ .prepare(`SELECT (display_name GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*') as matched FROM users WHERE id = ?`)
+ .get(user.id) as { matched: number | null };
+ expect(Boolean(raw.matched)).toBe(expected);
+ }
+ });
+
+ it('SQLF-050: an unknown platform fails closed for startsWithIsoDateKysely', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ const eb = expressionBuilder<UsersKyselyDB, 'users'>();
+ expect(() => startsWithIsoDateKysely(foreign, eb, 'username')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it('SQLF-051: substringKysely(ref, start) — the two-arg form — matches substr(col, N)', async () => {
+ const { user } = createUser(testDb, { username: 'kysely-iso-ts' });
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('2026-09-21T13:05:09Z', user.id);
+ const platform = t.em.getPlatform();
+
+ const row = await t.em.getKysely<UsersKyselyDB>()
+ .selectFrom('users')
+ .select((eb) => [substringKysely(platform, eb, 'display_name', 12).as('n')])
+ .where('id', '=', user.id)
+ .executeTakeFirstOrThrow();
+ expect(row.n).toBe('13:05:09Z');
+
+ const expected = testDb.prepare('SELECT substr(display_name, 12) as n FROM users WHERE id = ?').get(user.id) as { n: string };
+ expect(row.n).toBe(expected.n);
+ });
+
+ it('SQLF-052: substringKysely(ref, start, length) — the three-arg form — matches substr(col, N, L)', async () => {
+ const { user } = createUser(testDb, { username: 'kysely-iso-ts-2' });
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('2026-09-21T13:05:09Z', user.id);
+ const platform = t.em.getPlatform();
+
+ const row = await t.em.getKysely<UsersKyselyDB>()
+ .selectFrom('users')
+ .select((eb) => [substringKysely(platform, eb, 'display_name', 1, 10).as('n')])
+ .where('id', '=', user.id)
+ .executeTakeFirstOrThrow();
+ expect(row.n).toBe('2026-09-21');
+
+ const expected = testDb.prepare('SELECT substr(display_name, 1, 10) as n FROM users WHERE id = ?').get(user.id) as { n: string };
+ expect(row.n).toBe(expected.n);
+ });
+
+ it('SQLF-053: substringKysely rejects a non-positive start or a negative length', () => {
+ const platform = t.em.getPlatform();
+ const eb = expressionBuilder<UsersKyselyDB, 'users'>();
+ expect(() => substringKysely(platform, eb, 'username', 0)).toThrow(/1-based integer start/);
+ expect(() => substringKysely(platform, eb, 'username', 1.5)).toThrow(/1-based integer start/);
+ expect(() => substringKysely(platform, eb, 'username', 1, -1)).toThrow(/non-negative integer length/);
+ expect(() => substringKysely(platform, eb, 'username', 1, 1.5)).toThrow(/non-negative integer length/);
+ });
+
+ it('SQLF-054: concatKysely renders <col> || <bound-literal> || substringKysely(...), composing a nested Kysely expression (the shape concat() cannot do)', async () => {
+ const { user } = createUser(testDb, { username: 'concat-me' });
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('2026-09-21T13:05', user.id);
+ const platform = t.em.getPlatform();
+
+ const row = await t.em.getKysely<UsersKyselyDB>()
+ .selectFrom('users')
+ .select((eb) => [
+ concatKysely(platform, eb, { column: 'username' }, { value: '@' }, { expression: substringKysely(platform, eb, 'display_name', 12) }).as('n'),
+ ])
+ .where('id', '=', user.id)
+ .executeTakeFirstOrThrow();
+ expect(row.n).toBe('concat-me@13:05');
+
+ const expected = testDb
+ .prepare("SELECT username || ? || substr(display_name, 12) as n FROM users WHERE id = ?")
+ .get('@', user.id) as { n: string };
+ expect(row.n).toBe(expected.n);
+ });
+
+ it('SQLF-055: concatKysely rejects fewer than two parts', () => {
+ const platform = t.em.getPlatform();
+ const eb = expressionBuilder<UsersKyselyDB, 'users'>();
+ expect(() => concatKysely(platform, eb, { column: 'username' })).toThrow(/at least two parts/);
+ expect(() => concatKysely(platform, eb)).toThrow(/at least two parts/);
+ });
+
+ it('SQLF-056: an unknown platform fails closed for concatKysely and substringKysely', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ const eb = expressionBuilder<UsersKyselyDB, 'users'>();
+ expect(() => concatKysely(foreign, eb, { column: 'username' }, { value: 'x' })).toThrow(/no implementation for platform FakePlatform/);
+ expect(() => substringKysely(foreign, eb, 'username', 1)).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it('SQLF-057: castIntegerKysely matches both "14" and "14.0" TEXT rows against a bound INTEGER value (the accommodation_id shape, §18.1)', async () => {
+ const platform = t.em.getPlatform();
+ const { user: exact } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('14', exact.id);
+ const { user: dotZero } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('14.0', dotZero.id);
+ const { user: other } = createUser(testDb);
+ testDb.prepare('UPDATE users SET display_name = ? WHERE id = ?').run('15', other.id);
+
+ const rows = await t.em.getKysely<UsersKyselyDB>()
+ .selectFrom('users')
+ .select('id')
+ .where('id', 'in', [exact.id, dotZero.id, other.id])
+ .where((eb) => eb(castIntegerKysely(platform, eb, 'display_name'), '=', 14))
+ .orderBy('id', 'asc')
+ .execute();
+ expect(rows.map((r) => r.id)).toEqual([exact.id, dotZero.id]);
+
+ const expected = testDb
+ .prepare('SELECT id FROM users WHERE id IN (?, ?, ?) AND CAST(display_name AS INTEGER) = ? ORDER BY id ASC')
+ .all(exact.id, dotZero.id, other.id, 14);
+ expect(rows).toEqual(expected);
+ });
+
+ it('SQLF-058: an unknown platform fails closed for castIntegerKysely', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ const eb = expressionBuilder<UsersKyselyDB, 'users'>();
+ expect(() => castIntegerKysely(foreign, eb, 'display_name')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it('SQLF-059: DY23\'s exact shape compiles to the expected SQL text (compiled {sql, parameters} capture)', () => {
+ const platform = t.em.getPlatform();
+ const compiled = t.em.getKysely<UsersKyselyDB>()
+ .updateTable('users')
+ .set((eb) => ({
+ username: eb
+ .case()
+ .when('username', 'is', null)
+ .then(eb.val('2026-09-21'))
+ .else(concatKysely(platform, eb, { value: '2026-09-21' }, { expression: substringKysely(platform, eb, 'created_at', 11) }))
+ .end(),
+ }))
+ .where('id', '=', 1)
+ .compile();
+ expect(compiled.sql).toBe(
+ 'update "users" set "username" = case when "username" is null then ? else ? || substr("created_at", ?) end where "id" = ?',
+ );
+ expect(compiled.parameters).toEqual(['2026-09-21', '2026-09-21', 11, 1]);
+ });
+
+ // Plan 3f Task 0 (R9) — no consumer yet: Task 2 (collateNoCase), Task 4
+ // (nowMinusHours) and Task 1 (lowerTrimParam) wire these in as each
+ // converts the statement that needs them. Pinned here so each task imports
+ // a tested helper instead of writing one inline.
+
+ it('SQLF-060: collateNoCase renders <col> COLLATE NOCASE, and as a filter key selects the same rows as the legacy value-side spelling (name = ? COLLATE NOCASE)', async () => {
+ const { user: mixed } = createUser(testDb, { username: 'MixedCase' });
+ const { user: other } = createUser(testDb, { username: 'SomethingElse' });
+ const platform = t.em.getPlatform();
+
+ const typed = await t.em.find(Users, { [collateNoCase(platform, 'username')]: 'mixedcase' });
+ expect(typed.map((r) => r.id)).toEqual([mixed.id]);
+
+ const legacy = testDb
+ .prepare('SELECT id FROM users WHERE username = ? COLLATE NOCASE')
+ .all('mixedcase') as { id: number }[];
+ expect(typed.map((r) => r.id)).toEqual(legacy.map((r) => r.id));
+
+ const none = await t.em.find(Users, { [collateNoCase(platform, 'username')]: 'nobody-has-this-name' });
+ expect(none).toEqual([]);
+ expect(other.id).toBeDefined(); // seeded so the fixture has more than one row
+ });
+
+ it("SQLF-061: COLLATE NOCASE folds the same 26 ASCII letters LOWER() does, and does NOT diverge from LOWER() on SQLF-014's own non-ASCII fixtures — verified directly, not assumed", () => {
+ const cases: Array<[string, string]> = [
+ ['JOSÉ@x.com', 'josé@x.com'],
+ ];
+ for (const [upper, lower_] of cases) {
+ const collateMatch = testDb.prepare('SELECT (? = ? COLLATE NOCASE) as m').get(upper, lower_) as { m: number };
+ const lowerMatch = testDb.prepare('SELECT (LOWER(?) = LOWER(?)) as m').get(upper, lower_) as { m: number };
+ expect(collateMatch.m).toBe(lowerMatch.m);
+ }
+ // The ASCII case is the one pair both engines actually fold to equal;
+ // every non-ASCII pair above is left unfolded by BOTH engines (neither
+ // recognises the Unicode case mapping), which is exactly why they agree
+ // rather than diverge — this is genuinely the "no divergence found"
+ // branch R9 anticipates, not a skipped check.
+ const asciiCollate = testDb.prepare('SELECT (? = ? COLLATE NOCASE) as m').get('[email protected]', '[email protected]') as { m: number };
+ expect(asciiCollate.m).toBe(1);
+ const nonAsciiCollate = testDb.prepare('SELECT (? = ? COLLATE NOCASE) as m').get('JOSÉ@x.com', 'josé@x.com') as { m: number };
+ expect(nonAsciiCollate.m).toBe(0);
+ });
+
+ it('SQLF-062: an unknown platform fails closed for collateNoCase', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => collateNoCase(foreign, 'u.name')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it("SQLF-063: nowMinusHours renders datetime('now', '-N hours'), matching a JS-computed time within a few seconds' tolerance", async () => {
+ const row = testDb.prepare(`SELECT ${nowMinusHours(t.em.getPlatform(), 20).sql} as d`).get() as { d: string };
+ const got = new Date(`${row.d.replace(' ', 'T')}Z`).getTime();
+ const expected = Date.now() - 20 * 60 * 60 * 1000;
+ expect(Math.abs(got - expected)).toBeLessThan(10_000);
+ });
+
+ it('SQLF-063b: nowMinusHours(0) is "now", not one hour back', async () => {
+ const row = testDb.prepare(`SELECT ${nowMinusHours(t.em.getPlatform(), 0).sql} as d`).get() as { d: string };
+ const got = new Date(`${row.d.replace(' ', 'T')}Z`).getTime();
+ expect(Math.abs(got - Date.now())).toBeLessThan(10_000);
+ });
+
+ it('SQLF-064: nowMinusHours rejects a non-integer or negative hour count', () => {
+ expect(() => nowMinusHours(t.em.getPlatform(), 1.5)).toThrow(/non-negative integer hour count/);
+ expect(() => nowMinusHours(t.em.getPlatform(), -1)).toThrow(/non-negative integer hour count/);
+ expect(() => nowMinusHours(t.em.getPlatform(), Number.NaN)).toThrow(/non-negative integer hour count/);
+ });
+
+ it('SQLF-065: an unknown platform fails closed for nowMinusHours', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => nowMinusHours(foreign, 1)).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it('SQLF-066: lowerTrimParam pairs with lowerTrim to fold BOTH sides in SQLite (the AT31 dedup shape), and a JS-lowered+trimmed bind does NOT match — the mutation-proof for mixing engines', async () => {
+ const { user } = createUser(testDb, { username: ' JOSÉ ' });
+ const platform = t.em.getPlatform();
+
+ const exact = await t.em.findOne(Users, { [lowerTrim(platform, 'username')]: lowerTrimParam(platform, ' josÉ ') });
+ expect(exact?.id).toBe(user.id);
+
+ // A JS-lowered+trimmed value-side bind (mixing engines, program rule 18)
+ // must NOT match: SQLite's LOWER() leaves 'É' untouched, so the stored,
+ // SQL-folded spelling is 'josÉ', not the JS-folded 'josé'.
+ const jsLowered = await t.em.findOne(Users, { [lowerTrim(platform, 'username')]: ' josé '.trim().toLowerCase() });
+ expect(jsLowered).toBeNull();
+
+ const none = await t.em.findOne(Users, { [lowerTrim(platform, 'username')]: lowerTrimParam(platform, 'nobody') });
+ expect(none).toBeNull();
+ });
+
+ it('SQLF-067: an unknown platform fails closed for lowerTrimParam', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => lowerTrimParam(foreign, 'x')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Plan 3g Task 0 (R1) — unixEpochToIsoKysely, the third fallback tier of
+ // `GALLERY_CHRONOLOGICAL_ORDER` (journey-gallery-order.ts). No consumer
+ // yet: Task 1 (getJourneyFull) and Task 3 (getPublicJourney) each fold this
+ // into their own rebuild of the constant. The full composed ORDER BY proof
+ // (coalesce + nullif + correlated subquery + this helper, on a seeded
+ // gallery) is the describe block below this one.
+
+ it("SQLF-068: unixEpochToIsoKysely renders strftime('%Y-%m-%dT%H:%M:%SZ', <ref> / 1000, 'unixepoch'), matching a raw statement on the SAME fixed value, string-for-string", () => {
+ createUser(testDb); // one row so the anchor SELECT FROM users has something to select
+ const platform = t.em.getPlatform();
+ const createdAt = 1_700_000_000_000; // fixed epoch-millis value — the exact shape gp.created_at stores
+
+ const compiled = t.em.getKysely<UsersKyselyDB>()
+ .selectFrom('users')
+ .select((eb) => [unixEpochToIsoKysely(platform, eb, eb.val(createdAt)).as('iso')])
+ .compile();
+ expect(compiled.sql).toBe('select strftime(?, ? / ?, ?) as "iso" from "users"');
+ expect(compiled.parameters).toEqual(['%Y-%m-%dT%H:%M:%SZ', createdAt, 1000, 'unixepoch']);
+
+ const got = testDb.prepare(compiled.sql).get(...compiled.parameters) as { iso: string };
+ const expected = testDb
+ .prepare("SELECT strftime('%Y-%m-%dT%H:%M:%SZ', ? / 1000, 'unixepoch') as iso")
+ .get(createdAt) as { iso: string };
+ expect(got.iso).toBe(expected.iso);
+ expect(got.iso).toBe('2023-11-14T22:13:20Z'); // human-checkable: date -u -d @1700000000
+ });
+
+ it('SQLF-069: an unknown platform fails closed for unixEpochToIsoKysely', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ const eb = expressionBuilder<UsersKyselyDB, 'users'>();
+ expect(() => unixEpochToIsoKysely(foreign, eb, 'created_at')).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Plan 3h Task 0 — no consumer yet: Task 3 (DSY2), Task 4 (RU4), Task 5
+ // (DS23/DS26/recordLinkFailure) wire these in as each converts its own
+ // statement. Pinned here so each task imports a tested helper instead of
+ // writing one inline.
+
+ it("SQLF-071: nowDateOffset renders date('now', '-N days'), matching a JS-computed date within a few seconds' tolerance", async () => {
+ const row = testDb.prepare(`SELECT ${nowDateOffset(t.em.getPlatform(), -400).sql} as d`).get() as { d: string };
+ const got = new Date(`${row.d}T00:00:00Z`).getTime();
+ const expected = Date.now() - 400 * 24 * 60 * 60 * 1000;
+ // Compare calendar dates (UTC), not exact millis — date() truncates to a day.
+ expect(Math.abs(got - expected)).toBeLessThan(2 * 24 * 60 * 60 * 1000);
+ const expectedDate = new Date(expected).toISOString().slice(0, 10);
+ expect(row.d).toBe(expectedDate);
+ });
+
+ it("SQLF-072: nowDateOffset renders date('now', '+N days') for a positive count, matching DSY2's '+1 day' legacy text (singular) byte-for-byte, not just the helper's own plural spelling", async () => {
+ const helperRow = testDb.prepare(`SELECT ${nowDateOffset(t.em.getPlatform(), 1).sql} as d`).get() as { d: string };
+ const legacyRow = testDb.prepare(`SELECT date('now', '+1 day') as d`).get() as { d: string };
+ expect(helperRow.d).toBe(legacyRow.d);
+ const expectedDate = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
+ expect(helperRow.d).toBe(expectedDate);
+ });
+
+ it('SQLF-073: nowDateOffset(0) is today, not one day off in either direction', () => {
+ const row = testDb.prepare(`SELECT ${nowDateOffset(t.em.getPlatform(), 0).sql} as d`).get() as { d: string };
+ expect(row.d).toBe(new Date().toISOString().slice(0, 10));
+ });
+
+ it('SQLF-074: nowDateOffset rejects a non-integer day count', () => {
+ expect(() => nowDateOffset(t.em.getPlatform(), 1.5)).toThrow(/integer day count/);
+ expect(() => nowDateOffset(t.em.getPlatform(), Number.NaN)).toThrow(/integer day count/);
+ });
+
+ it('SQLF-075: an unknown platform fails closed for nowDateOffset', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => nowDateOffset(foreign, 1)).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it("SQLF-076: nowPlusSeconds renders datetime('now', '+N seconds'), matching a JS-computed time within a few seconds' tolerance", async () => {
+ const row = testDb.prepare(`SELECT ${nowPlusSeconds(t.em.getPlatform(), 30).sql} as d`).get() as { d: string };
+ const got = new Date(`${row.d.replace(' ', 'T')}Z`).getTime();
+ const expected = Date.now() + 30 * 1000;
+ expect(Math.abs(got - expected)).toBeLessThan(10_000);
+ });
+
+ it('SQLF-077: nowPlusSeconds(0) is "now", not thirty seconds off', () => {
+ const row = testDb.prepare(`SELECT ${nowPlusSeconds(t.em.getPlatform(), 0).sql} as d`).get() as { d: string };
+ const got = new Date(`${row.d.replace(' ', 'T')}Z`).getTime();
+ expect(Math.abs(got - Date.now())).toBeLessThan(10_000);
+ });
+
+ it('SQLF-078: nowPlusSeconds rejects a non-integer or negative second count', () => {
+ expect(() => nowPlusSeconds(t.em.getPlatform(), 1.5)).toThrow(/non-negative integer second count/);
+ expect(() => nowPlusSeconds(t.em.getPlatform(), -1)).toThrow(/non-negative integer second count/);
+ expect(() => nowPlusSeconds(t.em.getPlatform(), Number.NaN)).toThrow(/non-negative integer second count/);
+ });
+
+ it('SQLF-079: an unknown platform fails closed for nowPlusSeconds', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => nowPlusSeconds(foreign, 1)).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ it("SQLF-080: nowPlusSecondsKysely compiles to datetime(?, ?), matching nowPlusSeconds's own datetime('now', '+N seconds') text shape and runtime value (the DS23/DS26/recordLinkFailure shape, inside a Kysely ON CONFLICT DO UPDATE's CASE WHEN — R3)", async () => {
+ createUser(testDb); // one row so the anchor SELECT FROM users has something to select
+ const platform = t.em.getPlatform();
+
+ const compiled = t.em.getKysely<UsersKyselyDB>()
+ .selectFrom('users')
+ .select((eb) => [nowPlusSecondsKysely(platform, eb, 45).as('d')])
+ .compile();
+ expect(compiled.sql).toBe('select datetime(?, ?) as "d" from "users"');
+ expect(compiled.parameters).toEqual(['now', '+45 seconds']);
+
+ const got = testDb.prepare(compiled.sql).get(...compiled.parameters) as { d: string };
+ const raw = testDb.prepare(`SELECT ${nowPlusSeconds(platform, 45).sql} as d`).get() as { d: string };
+ // Both texts render the same shape; a wide tolerance sidesteps a same-second
+ // flake between the two separate statement executions (SQLF-016/063's own
+ // convention for every other 'now'-based helper in this file).
+ const gotMs = new Date(`${got.d.replace(' ', 'T')}Z`).getTime();
+ const rawMs = new Date(`${raw.d.replace(' ', 'T')}Z`).getTime();
+ expect(Math.abs(gotMs - rawMs)).toBeLessThan(10_000);
+ expect(Math.abs(gotMs - (Date.now() + 45 * 1000))).toBeLessThan(10_000);
+ });
+
+ it('SQLF-081: nowPlusSecondsKysely rejects a non-integer or negative second count', () => {
+ const eb = expressionBuilder<UsersKyselyDB, 'users'>();
+ const platform = t.em.getPlatform();
+ expect(() => nowPlusSecondsKysely(platform, eb, 1.5)).toThrow(/non-negative integer second count/);
+ expect(() => nowPlusSecondsKysely(platform, eb, -1)).toThrow(/non-negative integer second count/);
+ });
+
+ it('SQLF-082: an unknown platform fails closed for nowPlusSecondsKysely', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ const eb = expressionBuilder<UsersKyselyDB, 'users'>();
+ expect(() => nowPlusSecondsKysely(foreign, eb, 1)).toThrow(/no implementation for platform FakePlatform/);
+ });
+
+ // Plan 3h Task 5 (doc-sync) — `foundAgainState`, the typed rebuild of
+ // `doc-sync.service.ts`'s module-level `FOUND_AGAIN` SQL-text constant
+ // (DS2/DS3/DS5/DS12's shared SET clause). A scratch temp table stands in
+ // for `document_sync_items` here — the CASE only ever reads the two
+ // columns it names, so a two-column probe table exercises its logic
+ // exactly, without a trip/connection/link FK chain this file has no other
+ // reason to build.
+ describe('foundAgainState (doc-sync FOUND_AGAIN)', () => {
+ beforeEach(() => {
+ testDb.exec('DROP TABLE IF EXISTS found_again_probe');
+ testDb.exec('CREATE TEMP TABLE found_again_probe (id INTEGER PRIMARY KEY, state TEXT NOT NULL, file_id INTEGER)');
+ });
+
+ function apply(state: string, fileId: number | null): string {
+ const platform = t.em.getPlatform();
+ testDb.prepare('DELETE FROM found_again_probe WHERE id = 1').run();
+ testDb.prepare('INSERT INTO found_again_probe (id, state, file_id) VALUES (1, ?, ?)').run(state, fileId);
+ testDb.prepare(`UPDATE found_again_probe SET state = ${foundAgainState(platform, 'state', 'file_id').sql} WHERE id = 1`).run();
+ return (testDb.prepare('SELECT state FROM found_again_probe WHERE id = 1').get() as { state: string }).state;
+ }
+
+ it("SQLF-083: recovers a row on record as missing once its file is paired again, matching the legacy FOUND_AGAIN text (state='remote_missing' AND file_id IS NOT NULL -> 'synced')", () => {
+ expect(apply('remote_missing', 42)).toBe('synced');
+ });
+
+ it('SQLF-084: leaves a row on record as missing alone while it has no paired file (a rename/move under a path-as-id provider, not yet re-matched)', () => {
+ expect(apply('remote_missing', null)).toBe('remote_missing');
+ });
+
+ it('SQLF-085: leaves every other state untouched — error is never silently cleared by FOUND_AGAIN', () => {
+ for (const state of ['error', 'conflict', 'synced', 'pending', 'local_deleted']) {
+ expect(apply(state, 7)).toBe(state);
+ }
+ });
+
+ it('SQLF-086: an unknown platform fails closed for foundAgainState', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => foundAgainState(foreign, 'state', 'file_id')).toThrow(/no implementation for platform FakePlatform/);
+ });
+ });
+
+ // Plan 3h Task 5 (doc-sync, R3) — `currentTimestampKysely`, DS24's
+ // `last_seen_at = CURRENT_TIMESTAMP` inside the partial-index `ON
+ // CONFLICT ... DO UPDATE`.
+ describe('currentTimestampKysely', () => {
+ it('SQLF-087: compiles to the bare CURRENT_TIMESTAMP keyword with no parameters, matching currentTimestamp\'s own raw text and a real row\'s clock value', async () => {
+ const platform = t.em.getPlatform();
+ const compiled = t.em
+ .getKysely<UsersKyselyDB>()
+ .selectFrom('users')
+ .select(() => [currentTimestampKysely(platform).as('d')])
+ .compile();
+ expect(compiled.sql).toBe('select CURRENT_TIMESTAMP as "d" from "users"');
+ expect(compiled.parameters).toEqual([]);
+
+ createUser(testDb);
+ const got = testDb.prepare(compiled.sql).get(...compiled.parameters) as { d: string };
+ const raw = testDb.prepare(`SELECT ${currentTimestamp(platform).sql} as d`).get() as { d: string };
+ expect(Math.abs(new Date(`${got.d.replace(' ', 'T')}Z`).getTime() - new Date(`${raw.d.replace(' ', 'T')}Z`).getTime())).toBeLessThan(10_000);
+ });
+
+ it('SQLF-088: current_timestamp() called as a function is rejected by SQLite — proving the bare-keyword shape is load-bearing, not a style choice', () => {
+ expect(() => testDb.prepare('SELECT current_timestamp() as d').get()).toThrow(/syntax error/);
+ });
+
+ it('SQLF-089: an unknown platform fails closed for currentTimestampKysely', () => {
+ class FakePlatform extends Platform {}
+ const foreign = new FakePlatform();
+ expect(() => currentTimestampKysely(foreign)).toThrow(/no implementation for platform FakePlatform/);
+ });
+ });
+ });
+
+ /**
+ * Plan 3g Task 0 (R1) — the full Kysely rebuild of
+ * `journey-gallery-order.ts`'s `GALLERY_CHRONOLOGICAL_ORDER`, as a worked
+ * example: `COALESCE(NULLIF(tp.taken_at, ''), <correlated MIN+concat
+ * subquery over journey_entry_photos/journey_entries>, <unixEpochToIsoKysely
+ * of gp.created_at>) ASC, gp.sort_order ASC, gp.id ASC`. NOT exported from
+ * `sql-functions.ts` (only `unixEpochToIsoKysely`, this file's one named
+ * deliverable, lives there) — Task 1/Task 3 each own the actual repository
+ * method this becomes (`JourneyPhotosRepository`/callers, not yet built);
+ * this function is the verbatim builder chain Task 0's report hands them,
+ * proven row-order-identical to the legacy SQL text against a seeded
+ * gallery here so neither task re-derives it from scratch.
+ */
+ interface GalleryOrderTestDB {
+ journey_photos: {
+ id: number;
+ journey_id: number;
+ photo_id: number;
+ sort_order: number | null;
+ created_at: number;
+ };
+ trek_photos: {
+ id: number;
+ taken_at: string | null;
+ };
+ journey_entry_photos: {
+ entry_id: number;
+ journey_photo_id: number;
+ };
+ journey_entries: {
+ id: number;
+ entry_date: string;
+ entry_time: string | null;
+ };
+ }
+
+ function galleryChronologicalOrderExpr(
+ platform: Platform,
+ // Fixed to exactly the shape `.selectFrom('journey_photos as gp')
+ // .innerJoin('trek_photos as tp', ...)` itself produces against a
+ // `Kysely<GalleryOrderTestDB>` (`GalleryOrderTestDB` plus the derived
+ // `gp`/`tp` alias members, read off the SAME interface's own
+ // `journey_photos`/`trek_photos` entries) — the `publicStayExists`
+ // precedent (`_shared/reservation-visibility.ts`): a table's alias is a
+ // property of the QUERY, never of the `DB` interface itself, so a
+ // correlated-subquery helper with a fixed alias contract is typed this
+ // way rather than generic over an arbitrary caller `DB`/`TB`.
+ eb: ExpressionBuilder<GalleryOrderTestDB & { gp: GalleryOrderTestDB['journey_photos']; tp: GalleryOrderTestDB['trek_photos'] }, 'gp' | 'tp'>,
+ ) {
+ return eb.fn.coalesce(
+ eb.fn<string | null>('nullif', [eb.ref('tp.taken_at'), eb.val('')]),
+ eb
+ .selectFrom('journey_entry_photos as jep')
+ .innerJoin('journey_entries as je', 'je.id', 'jep.entry_id')
+ .select((eb2) =>
+ eb2.fn
+ .min<string | null>(
+ concatKysely(
+ platform,
+ eb2,
+ { column: 'je.entry_date' },
+ { value: 'T' },
+ { expression: eb2.fn.coalesce(eb2.fn<string | null>('nullif', [eb2.ref('je.entry_time'), eb2.val('')]), eb2.val('00:00')) },
+ ),
+ )
+ .as('min_dt'),
+ )
+ .whereRef('jep.journey_photo_id', '=', 'gp.id'),
+ unixEpochToIsoKysely(platform, eb, 'gp.created_at'),
+ );
+ }
+
+ describe('GALLERY_CHRONOLOGICAL_ORDER Kysely rebuild (Plan 3g Task 0, R1 worked example)', () => {
+ it('SQLF-070: row order matches the legacy GALLERY_CHRONOLOGICAL_ORDER text exactly on a seeded gallery covering all three fallback tiers, ties, NULL/empty taken_at, and entries with/without linked photos', async () => {
+ const platform = t.em.getPlatform();
+ const { user } = createUser(testDb, { username: 'gallery-owner' });
+ const journey = createJourney(testDb, user.id);
+ const entryEarly = createJourneyEntry(testDb, journey.id, user.id, { entry_date: '2026-01-05' });
+ testDb.prepare('UPDATE journey_entries SET entry_time = ? WHERE id = ?').run('14:30', entryEarly.id);
+ const entryNoTime = createJourneyEntry(testDb, journey.id, user.id, { entry_date: '2026-01-05' });
+ // entry_time left NULL — the entry-linked tier's own COALESCE(NULIF(entry_time,''),'00:00') fallback
+
+ const trekPhoto = (takenAt: string | null) => {
+ const r = testDb.prepare('INSERT INTO trek_photos (provider, asset_id, owner_id, taken_at) VALUES (?, ?, ?, ?)')
+ .run('immich', `asset-${Math.random()}`, user.id, takenAt);
+ return r.lastInsertRowid as number;
+ };
+ const galleryPhoto = (photoId: number, createdAt: number, sortOrder: number) => {
+ const r = testDb
+ .prepare('INSERT INTO journey_photos (journey_id, photo_id, sort_order, created_at) VALUES (?, ?, ?, ?)')
+ .run(journey.id, photoId, sortOrder, createdAt);
+ return r.lastInsertRowid as number;
+ };
+ const linkEntry = (entryId: number, journeyPhotoId: number) => {
+ testDb
+ .prepare('INSERT INTO journey_entry_photos (entry_id, journey_photo_id, created_at) VALUES (?, ?, ?)')
+ .run(entryId, journeyPhotoId, Date.now());
+ };
+
+ // Tier 1: has a capture time — wins outright regardless of everything else.
+ const pCapture = galleryPhoto(trekPhoto('2026-02-01T09:00:00Z'), 1_700_000_000_000, 0);
+ // Tier 1 skipped via empty-string NULLIF, not SQL NULL — proves both forms fall through.
+ const pEmptyTaken = galleryPhoto(trekPhoto(''), 1_600_000_000_000, 0);
+ linkEntry(entryEarly.id, pEmptyTaken); // tier 2: '2026-01-05T14:30'
+ // Tier 2 via SQL NULL taken_at, linked to the no-entry-time entry.
+ const pNullTaken = galleryPhoto(trekPhoto(null), 1_600_000_000_000, 0);
+ linkEntry(entryNoTime.id, pNullTaken); // tier 2: '2026-01-05T00:00'
+ // Tier 2, linked to TWO entries — proves the correlated subquery's MIN, not just any match.
+ const pMultiEntry = galleryPhoto(trekPhoto(null), 1_600_000_000_000, 0);
+ linkEntry(entryEarly.id, pMultiEntry); // '2026-01-05T14:30'
+ const entryLater = createJourneyEntry(testDb, journey.id, user.id, { entry_date: '2026-06-01' });
+ linkEntry(entryLater.id, pMultiEntry); // '2026-06-01T00:00' — MIN must still pick the earlier one
+ // Tier 3: no taken_at, no entry link at all — falls all the way to created_at.
+ const pFallbackA = galleryPhoto(trekPhoto(null), 1_650_000_000_000, 5);
+ // Tier 3 tie: identical created_at to pFallbackA, broken by sort_order (lower first).
+ const pFallbackTieLow = galleryPhoto(trekPhoto(null), 1_650_000_000_000, 1);
+ const pFallbackTieHigh = galleryPhoto(trekPhoto(null), 1_650_000_000_000, 1);
+ // (pFallbackTieLow/pFallbackTieHigh share BOTH created_at and sort_order —
+ // the final id ASC tiebreak must separate them, insertion order = id order.)
+
+ const rows = await t.em
+ .getKysely<GalleryOrderTestDB>()
+ .selectFrom('journey_photos as gp')
+ .innerJoin('trek_photos as tp', 'tp.id', 'gp.photo_id')
+ .select('gp.id')
+ .where('gp.journey_id', '=', journey.id)
+ .orderBy((eb) => galleryChronologicalOrderExpr(platform, eb), 'asc')
+ .orderBy('gp.sort_order', 'asc')
+ .orderBy('gp.id', 'asc')
+ .execute();
+
+ const legacy = testDb
+ .prepare(`
+ SELECT gp.id
+ FROM journey_photos gp JOIN trek_photos tp ON tp.id = gp.photo_id
+ WHERE gp.journey_id = ?
+ ORDER BY COALESCE(
+ NULLIF(tp.taken_at, ''),
+ (SELECT MIN(je.entry_date || 'T' || COALESCE(NULLIF(je.entry_time, ''), '00:00'))
+ FROM journey_entry_photos jep
+ JOIN journey_entries je ON je.id = jep.entry_id
+ WHERE jep.journey_photo_id = gp.id),
+ strftime('%Y-%m-%dT%H:%M:%SZ', gp.created_at / 1000, 'unixepoch')
+ ) ASC,
+ gp.sort_order ASC,
+ gp.id ASC
+ `)
+ .all(journey.id) as { id: number }[];
+
+ expect(rows.map((r) => r.id)).toEqual(legacy.map((r) => r.id));
+ // Pinned expected order, so a future change to the fixture that happens to
+ // keep both queries agreeing (but wrong) still gets caught:
+ expect(rows.map((r) => r.id)).toEqual([
+ pFallbackTieLow, // tier 3, strftime('2022-04-15T05:20:00Z'), sort_order=1, lower id first
+ pFallbackTieHigh, // tier 3, same created_at+sort_order, id tiebreak
+ pFallbackA, // tier 3, same created_at, sort_order=5 — sorts after the tier-3 pair above
+ pNullTaken, // tier 2, '2026-01-05T00:00' — earliest tier-2 text (entry_time NULL -> '00:00')
+ pEmptyTaken, // tier 2, '2026-01-05T14:30'
+ pMultiEntry, // tier 2, MIN of two links = '2026-01-05T14:30' (ties pEmptyTaken, id breaks it)
+ pCapture, // tier 1, '2026-02-01T09:00:00Z' — a real taken_at always wins tier 1
+ ]);
+ });
+ });
diff --cc server/tests/unit/db/entities-index.test.ts
index 000000000,770507485..d308ce388
mode 000000,100644..100644
--- a/server/tests/unit/db/entities-index.test.ts
+++ b/server/tests/unit/db/entities-index.test.ts
@@@ -1,0 -1,109 +1,110 @@@
+ import { EntitySchema, type EntityRepository } from '@mikro-orm/core';
+ import fs from 'node:fs';
+ import path from 'node:path';
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+ import { ALL_ENTITIES } from '../../../src/db/entities';
+ import { createSnapshotTestDb } from '../../helpers/db-mock';
+ import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
+ import { TrekRepository } from '../../../src/db/repositories/_shared/trek-repository';
+
+ const ENTITIES_DIR = path.join(__dirname, '../../../src/db/entities');
+ const REPOSITORIES_DIR = path.join(__dirname, '../../../src/db/repositories');
+
+ describe('ALL_ENTITIES', () => {
+ it('ENT-001: lists exactly one schema per *.entity.ts file', () => {
+ const files = fs.readdirSync(ENTITIES_DIR).filter((f) => f.endsWith('.entity.ts')).sort();
+ const names = ALL_ENTITIES.map((s) => s.name).sort();
+ const expected = files.map((f) => f.replace(/\.entity\.ts$/, '')).sort();
+ expect(names).toEqual(expected);
+ });
+
+ it('ENT-002: every entry is an EntitySchema with a class', () => {
+ for (const schema of ALL_ENTITIES) {
+ expect(schema).toBeInstanceOf(EntitySchema);
+ expect(typeof schema.meta.class).toBe('function');
+ }
+ });
+
+ /**
- * Plan 2 Task 3: every one of the 127 entities the migrated schema
++ * Plan 2 Task 3: every one of the 130 entities the migrated schema
+ * describes (120 rewritten + the 5 document-sync tables added this task,
- * + push_subscriptions and google_api_usage from legacy steps 245 and 254)
++ * + push_subscriptions and google_api_usage from legacy steps 245 and 254,
++ * + tour_types, tours and tour_waypoints from the Tours migration)
+ * is registered, and no two share a class name (a silent duplicate would
+ * shadow one of them in `orm.getMetadata()`, exactly the kind of drift
+ * `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
+ * which de-duplicates by class name).
+ */
- it('ENT-003: exactly 127 entities, every class name unique', () => {
- expect(ALL_ENTITIES.length).toBe(127);
++ it('ENT-003: exactly 130 entities, every class name unique', () => {
++ expect(ALL_ENTITIES.length).toBe(130);
+ const names = ALL_ENTITIES.map((s) => s.meta.className);
+ expect(new Set(names).size).toBe(names.length);
+ });
+
+ /**
+ * Task 1's review flagged this binding as otherwise unpinned: dropping an
+ * entity's `repository: () => XRepository` mutation stayed green in every
+ * gate up to here (task-1-review.md, minor 1). `em.getRepository(X)` must
+ * return an instance of the exact repository class
+ * `src/db/repositories/<Name>.repository.ts` exports, for every entity —
+ * the 120 the generator wrote a stub for this task plus the 5 pre-existing,
+ * hand-written ones (`Days`, `DayNotes`, `Trips`, `BudgetCategoryOrder`,
+ * `VacayUserSettings`) it left untouched.
+ */
+ describe('ENT-004: em.getRepository(X) is an instance of X.repository.ts', () => {
+ let t: TestOrm;
+ const testDb = createSnapshotTestDb();
+
+ beforeAll(async () => {
+ t = await createTestOrm(testDb);
+ });
+
+ afterAll(async () => {
+ await t.close();
+ testDb.close();
+ });
+
+ it('every entity resolves to its own repository class', async () => {
+ const failures: string[] = [];
+ for (const schema of ALL_ENTITIES) {
+ const className = schema.meta.className;
+ const repoFile = path.join(REPOSITORIES_DIR, `${className}.repository.ts`);
+ if (!fs.existsSync(repoFile)) {
+ failures.push(`${className}: no src/db/repositories/${className}.repository.ts file`);
+ continue;
+ }
+ const mod: Record<string, unknown> = await import(/* @vite-ignore */ `../../../src/db/repositories/${className}.repository`);
+ const RepoClass = mod[`${className}Repository`];
+ if (typeof RepoClass !== 'function') {
+ failures.push(`${className}: repository module has no exported ${className}Repository class`);
+ continue;
+ }
+ const repo: EntityRepository<object> = t.em.getRepository(schema.class as new () => object);
+ if (!(repo instanceof (RepoClass as abstract new (...args: never[]) => unknown))) {
+ failures.push(`${className}: em.getRepository() did not return a ${className}Repository instance`);
+ }
+ // Task 7 review, H2 carry-list item 1: the `extends EntityRepository`
+ // ratchet made self-enforcing — every bound repository must also be
+ // a TrekRepository (validateRequestContext + the disableIdentityMap
+ // read default), not just an instance of its own named class.
+ if (!(repo instanceof TrekRepository)) {
+ failures.push(`${className}: em.getRepository() did not return a TrekRepository instance`);
+ }
+ }
+ expect(failures).toEqual([]);
+ });
+
+ // Task 7 review, H2: a source-scan companion to the instanceof check
+ // above — belt and suspenders against a repository that extends
+ // TrekRepository indirectly (or not through this loop's import path).
+ it('SCAN-001: exactly one repository file extends EntityRepository directly — the base class itself', () => {
+ const files = fs.readdirSync(REPOSITORIES_DIR).filter((f) => f.endsWith('.repository.ts'));
+ const hits: string[] = [];
+ for (const file of files) {
+ const content = fs.readFileSync(path.join(REPOSITORIES_DIR, file), 'utf-8');
+ if (/\bextends\s+EntityRepository\b/.test(content)) hits.push(file);
+ }
+ expect(hits).toEqual([]); // the base class lives in _shared/, not matched by *.repository.ts
+ });
+ });
+ });
diff --cc server/tests/unit/db/entity-class-fields.test.ts
index 000000000,344e1fc5a..aec3173b4
mode 000000,100644..100644
--- a/server/tests/unit/db/entity-class-fields.test.ts
+++ b/server/tests/unit/db/entity-class-fields.test.ts
@@@ -1,0 -1,187 +1,188 @@@
+ import { EntityRepositoryType, ReferenceKind } from '@mikro-orm/core';
+ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
+ import { ALL_ENTITIES } from '../../../src/db/entities';
+ import { BudgetItems } from '../../../src/db/entities/BudgetItems.entity';
+ import { IdempotencyKeys } from '../../../src/db/entities/IdempotencyKeys.entity';
+ import { createUser, createTrip } from '../../helpers/factories';
+ import { createSnapshotTestDb } from '../../helpers/db-mock';
+ import { resetTestDb } from '../../helpers/test-db';
+ import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
+
+ /**
+ * Permanent guard for `task-4-review-shape.md` Important finding 1: a
+ * numeric class-field initialiser must never render `NaN` (see
+ * `scripts/generate-entities.ts`'s `RULE1d_fixNaNNumericDefaults` and
+ * `tests/unit/db/generate-entities.test.ts`'s `RULE1D-*` fixture tests for
+ * the mechanism). This file pins the OUTPUT of that rule against the real,
- * committed entities — every one of the 127, not a sample — and reproduces
++ * committed entities — every one of the 130, not a sample — and reproduces
+ * the reviewer's own insert probe so a future regenerate/hand-edit that
+ * reintroduces a `NaN` initialiser fails loudly here, not silently at a
+ * caller's first `em.create()`.
+ */
+ /** NOT NULL scalars with neither a column default nor a class-field initialiser (legitimate: the caller must supply them). */
+ // 424 + push_subscriptions (legacy step 245): id, user_id, endpoint, p256dh, auth, vapid_public_key.
-const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 430;
++// + Tours: tour_types label_key, icon, color; tours.tour_type; tour_waypoints id, place_id, lat, lng, role, sequence.
++const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 440;
+
+ describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
- it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 127 entities', () => {
++ it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 130 entities', () => {
+ const failures: string[] = [];
+ for (const schema of ALL_ENTITIES) {
+ const Ctor = schema.class as new () => Record<string, unknown>;
+ const instance = new Ctor();
+ for (const [key, value] of Object.entries(instance)) {
+ if (typeof value === 'number' && Number.isNaN(value)) {
+ failures.push(`${schema.meta.className}.${key}`);
+ }
+ }
+ }
+ expect(failures).toEqual([]);
+ });
+
+ /**
+ * Report-only (per the brief): a NOT NULL scalar property with no
+ * `default`/`defaultRaw` at all legitimately has no class-field
+ * initialiser — the caller is expected to supply it (`name!: string`, for
+ * example). That is normal and not a bug, so this never asserts the list
+ * is empty; it exists so a reviewer can see the shape at a glance and so a
+ * suspicious spike in the count (e.g. every numeric property in an entity
+ * suddenly losing its default) shows up in test output without failing
+ * the suite on a false positive.
+ */
+ it('CLASSFIELD-002: exactly the known NOT NULL, no-default scalar properties have no class-field initialiser', async () => {
+ const testDb = createSnapshotTestDb();
+ try {
+ const t = await createTestOrm(testDb);
+ try {
+ const report: string[] = [];
+ for (const schema of ALL_ENTITIES) {
+ const meta = t.orm.getMetadata().get(schema.class);
+ const Ctor = schema.class as new () => Record<string, unknown>;
+ const instance = new Ctor();
+ for (const prop of meta.props) {
+ if (prop.kind !== undefined && prop.kind !== ReferenceKind.SCALAR) continue;
+ if (prop.nullable) continue;
+ if (prop.default !== undefined || prop.defaultRaw !== undefined) continue;
+ if (!(prop.name in instance)) continue;
+ if (instance[prop.name] === undefined) {
+ report.push(`${meta.className}.${prop.name}`);
+ }
+ }
+ }
+ // Informational only — see the doc comment above. `console.info` (not
+ // a `console.log` vitest might buffer away) so it survives a run.
+ // A ratchet, not a census: the failure mode this file guards (a regeneration
+ // handing every numeric property a bogus default) makes this number DROP;
+ // a new NOT NULL column without a default bumps it by one — update the
+ // constant with the migration that adds the column.
+ expect(report.length, report.join(', ')).toBe(KNOWN_UNINITIALISED_NOT_NULL_SCALARS);
+ } finally {
+ await t.close();
+ }
+ } finally {
+ testDb.close();
+ }
+ });
+ });
+
+ /**
+ * Plan 3b pre-task (`scripts/generate-entities.ts`'s `RULE10_repositoryTypeMarker`
+ * / `injectRepositoryTypeMarker`): `[EntityRepositoryType]?: XRepository;` is
+ * a type-only class member, never routed through `meta.addProperty` — this
+ * pins that it stays that way, so CLASSFIELD-002's census above (and its
+ * pinned count, 423) can never silently start counting it.
+ */
+ describe('[EntityRepositoryType] marker is excluded from the class-field census (RULE10)', () => {
+ it('CLASSFIELD-003: every entity has an own [EntityRepositoryType] symbol property that is never a real metadata property and never leaks as a string key', async () => {
+ const testDb = createSnapshotTestDb();
+ try {
+ const t = await createTestOrm(testDb);
+ try {
+ const failures: string[] = [];
+ for (const schema of ALL_ENTITIES) {
+ const meta = t.orm.getMetadata().get(schema.class);
+ const Ctor = schema.class as new () => Record<string, unknown>;
+ const instance = new Ctor();
+ if (!Object.getOwnPropertySymbols(instance).includes(EntityRepositoryType)) {
+ failures.push(`${meta.className}: missing an own [EntityRepositoryType] symbol property`);
+ }
+ if (Object.keys(instance).includes('EntityRepositoryType')) {
+ failures.push(`${meta.className}: [EntityRepositoryType] leaked as a string-keyed own property`);
+ }
+ if (meta.props.some((prop) => prop.name === 'EntityRepositoryType')) {
+ failures.push(`${meta.className}: [EntityRepositoryType] was registered as a real metadata property`);
+ }
+ }
+ expect(failures).toEqual([]);
+ } finally {
+ await t.close();
+ }
+ } finally {
+ testDb.close();
+ }
+ });
+ });
+
+ /**
+ * The reviewer's exact repro (`task-4-review-shape.md`, Important finding
+ * 1): before the fix, `em.create(BudgetItems, …)` and
+ * `em.create(IdempotencyKeys, …)` both threw `SqliteError: no such column:
+ * NaN` at `flush()` — Kysely rendered the `NaN` class-field initialiser as a
+ * bare SQL identifier. Neither probe names the broken columns
+ * (`persons`/`days`/`place_id`/`reservation_id` on `BudgetItems`,
+ * `created_at` on `IdempotencyKeys`) — the whole point is that a caller
+ * should never have to.
+ */
+ describe('insert probes (task-4-review-shape.md, the reviewer\'s exact repro)', () => {
+ const testDb = createSnapshotTestDb();
+ let t: TestOrm;
+
+ beforeAll(async () => {
+ t = await createTestOrm(testDb);
+ });
+ beforeEach(() => {
+ resetTestDb(testDb);
+ t.clear();
+ });
+ afterAll(async () => {
+ await t.close();
+ testDb.close();
+ });
+
+ it('INSERT-PROBE-001: em.create(BudgetItems, { trip, name, total_price, exchange_rate }) + flush succeeds', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+
+ const created = t.em.create(BudgetItems, {
+ trip: trip.id,
+ name: 'Dinner',
+ total_price: 4200,
+ exchange_rate: 1,
+ });
+ await t.em.persist(created).flush();
+
+ const row = testDb.prepare('SELECT persons, days, place_id, reservation_id FROM budget_items WHERE id = ?').get(created.id);
+ expect(row).toEqual({ persons: null, days: null, place_id: null, reservation_id: null });
+ });
+
+ it('INSERT-PROBE-002: em.create(IdempotencyKeys, { key, user, method, path, status_code, response_body }) + flush succeeds', async () => {
+ const { user } = createUser(testDb);
+
+ const created = t.em.create(IdempotencyKeys, {
+ key: 'idem-key-probe-1',
+ user: user.id,
+ method: 'POST',
+ path: '/api/trips',
+ status_code: 201,
+ response_body: '{}',
+ });
+ await t.em.persist(created).flush();
+
+ const row = testDb
+ .prepare('SELECT created_at FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?')
+ .get('idem-key-probe-1', user.id, 'POST', '/api/trips') as { created_at: number };
+ // The DB's own defaultRaw (strftime('%s','now')) filled it in — never NaN, never null.
+ expect(row.created_at).toEqual(expect.any(Number));
+ expect(Number.isNaN(row.created_at)).toBe(false);
+ });
+ });
diff --cc server/tests/unit/db/legacy-baseline.test.ts
index 000000000,7f7295b47..d16c95ba0
mode 000000,100644..100644
--- a/server/tests/unit/db/legacy-baseline.test.ts
+++ b/server/tests/unit/db/legacy-baseline.test.ts
@@@ -1,0 -1,224 +1,228 @@@
+ /**
+ * The legacy step → migration map and the baseline that uses it
+ * (`src/db/legacy-baseline.ts`, Plan 4 final review B1).
+ *
+ * The map is derived from the migrations' own `Legacy migration step N`
+ * docstrings; LEGACYMAP-001/002 pin that derivation against the files on disk
+ * so a new migration that mis-numbers, duplicates or drops a step fails here
+ * rather than on somebody's upgrade. The rest pin the fail-closed paths.
+ * The end-to-end upgrade of real legacy databases is
+ * `tests/integration/legacy-upgrade-v*.test.ts`.
+ */
+ import { buildLegacyStepMap, migrateToHead, planLegacyBaseline } from '../../../src/db/legacy-baseline';
+ import {
+ createMigrationOrm,
+ migrateTo,
+ migratorOf,
+ pendingNames,
+ rawExec,
+ rawQuery,
+ } from '../../helpers/migration-step';
+ import type { MigrationInfo } from '@mikro-orm/core';
+ import type { MikroORM } from '@mikro-orm/sqlite';
+
+ import fs from 'node:fs';
+ import path from 'node:path';
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+ const MIGRATIONS = path.join(__dirname, '../../../src/db/migrations');
+ const BASELINE = 'Migration20200101000000_baseline_schema';
+ /** The migrations that carry no legacy step: the baseline, and the post-legacy ones every upgrade runs. */
-const UNNUMBERED = [BASELINE, 'Migration20200101040200_trek_photo_cache_meta_cache_key_not_null'];
++const UNNUMBERED = [
++ BASELINE,
++ 'Migration20200101040200_trek_photo_cache_meta_cache_key_not_null',
++ 'Migration20200101042000_tours',
++];
+ // The last step the positional runner ever had; planLegacyBaseline refuses a
+ // schema_version past it.
+ const LEGACY_FINAL_STEP = 258;
+
+ /** Synthetic migrations whose "source" is the text given, for the fail-closed cases. */
+ function fake(sources: Array<[string, string]>): { list: MigrationInfo[]; read: (p: string) => string } {
+ const byPath = new Map(sources.map(([name, text]) => [`/fake/${name}.ts`, text]));
+ return {
+ list: sources.map(([name]) => ({ name, path: `/fake/${name}.ts` })),
+ read: (p) => byPath.get(p) ?? '',
+ };
+ }
+
+ describe('the legacy step map', () => {
+ it('LEGACYMAP-001: every numbered migration maps to exactly one step, steps 1..258 are all present, in order, behind the baseline', async () => {
+ const orm = await createMigrationOrm();
+ try {
+ const all = await migratorOf(orm).getPending();
+ const map = buildLegacyStepMap(all);
+ expect(map.finalStep).toBe(LEGACY_FINAL_STEP);
+ expect([...map.steps.keys()]).toEqual(Array.from({ length: LEGACY_FINAL_STEP }, (_, i) => i + 1));
+ expect(new Set(map.steps.values()).size).toBe(LEGACY_FINAL_STEP);
+ expect(map.baseline).toEqual([BASELINE]);
+
+ // The unnumbered ones: the baseline, and the post-legacy migrations that
+ // must always run on an upgraded install.
+ const numbered = new Set(map.steps.values());
+ expect(all.map((m) => m.name).filter((name) => !numbered.has(name))).toEqual(UNNUMBERED);
+ expect(map.steps.get(242)).toBe('Migration20200101040300_a_booked_night_finally_took_the_seat_a_new');
+ expect(map.steps.get(243)).toBe('Migration20200101040400_immich_learns_the_switch_synology_airtrail_and');
+ expect(map.steps.get(258)).toBe('Migration20200101041900_a_journey_that_puts_an_entry_on');
+ expect(map.steps.get(26)).toBe('Migration20200101002600_day_assignments_add_assignment_time');
+ } finally {
+ await orm.close(true);
+ }
+ });
+
+ it('LEGACYMAP-002: the map agrees with an independent read of the files on disk', async () => {
+ const onDisk = new Map<string, number>();
+ for (const file of fs.readdirSync(MIGRATIONS).filter((f) => f.endsWith('.ts'))) {
+ const steps = [
+ ...fs.readFileSync(path.join(MIGRATIONS, file), 'utf8').matchAll(/Legacy migration step (\d+)\b/g),
+ ];
+ expect(steps.length, file).toBeLessThanOrEqual(1);
+ if (steps.length === 1) onDisk.set(file.replace(/\.ts$/, ''), Number(steps[0]![1]));
+ }
+ const orm = await createMigrationOrm();
+ try {
+ const map = buildLegacyStepMap(await migratorOf(orm).getPending());
+ expect(new Map([...map.steps].map(([step, name]) => [name, step]))).toEqual(onDisk);
+ } finally {
+ await orm.close(true);
+ }
+ });
+
+ it('LEGACYMAP-003: refuses a step claimed twice', () => {
+ const { list, read } = fake([
+ ['M0_base', ''],
+ ['M1', 'Legacy migration step 1'],
+ ['M2', 'Legacy migration step 1'],
+ ]);
+ expect(() => buildLegacyStepMap(list, read)).toThrow(/legacy step 1 is claimed by both M1 and M2/);
+ });
+
+ it('LEGACYMAP-004: refuses a gap in the steps', () => {
+ const { list, read } = fake([
+ ['M0_base', ''],
+ ['M1', 'Legacy migration step 1'],
+ ['M3', 'Legacy migration step 3'],
+ ]);
+ expect(() => buildLegacyStepMap(list, read)).toThrow(/no migration carries legacy step 2/);
+ });
+
+ it('LEGACYMAP-005: refuses a migration naming two steps, and steps applied out of order', () => {
+ const two = fake([
+ ['M0_base', ''],
+ ['M1', 'Legacy migration step 1, formerly Legacy migration step 2'],
+ ]);
+ expect(() => buildLegacyStepMap(two.list, two.read)).toThrow(/M1 names more than one legacy step \(1, 2\)/);
+
+ const swapped = fake([
+ ['M0_base', ''],
+ ['M1', 'Legacy migration step 2'],
+ ['M2', 'Legacy migration step 1'],
+ ]);
+ expect(() => buildLegacyStepMap(swapped.list, swapped.read)).toThrow(
+ /M2 \(legacy step 1\) sorts after legacy step 2/,
+ );
+ });
+
+ it('LEGACYMAP-006: refuses no baseline, no numbered step at all, and a migration without a source file', () => {
+ const noBase = fake([['M1', 'Legacy migration step 1']]);
+ expect(() => buildLegacyStepMap(noBase.list, noBase.read)).toThrow(
+ /no baseline migration sorts ahead of legacy step 1/,
+ );
+
+ const none = fake([['M0_base', '']]);
+ expect(() => buildLegacyStepMap(none.list, none.read)).toThrow(/no migration names a legacy step/);
+
+ expect(() => buildLegacyStepMap([{ name: 'M0_classOnly' }])).toThrow(/M0_classOnly has no source file/);
+ });
+ });
+
+ describe('planLegacyBaseline / migrateToHead', () => {
+ let orm: MikroORM;
+
+ beforeEach(async () => {
+ orm = await createMigrationOrm();
+ });
+
+ afterEach(async () => {
+ await orm.close(true);
+ });
+
+ const baseline = () => planLegacyBaseline(orm.em.getConnection(), migratorOf(orm));
+ const migrate = () => migrateToHead(orm.em.getConnection(), migratorOf(orm));
+ const recorded = async () =>
+ (await rawQuery<{ name: string }>(orm, 'SELECT name FROM mikro_orm_migrations ORDER BY id')).map((r) => r.name);
+
+ it('LEGACYBASE-001: a fresh database (no schema_version) is left alone', async () => {
+ await expect(baseline()).resolves.toEqual([]);
+ expect(await recorded()).toEqual([]);
+ });
+
+ it('LEGACYBASE-002: a database the migrator already knows is left alone, even though it carries schema_version', async () => {
+ await migrateTo(orm, 'Migration20200101020900_create_schema_version_new');
+ await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (241)');
+ const before = await recorded();
+ await expect(baseline()).resolves.toEqual([]);
+ expect(await recorded()).toEqual(before);
+ });
+
+ it('LEGACYBASE-003: a legacy database at step N plans steps 1..N in application order — never the baseline — and writes nothing', async () => {
+ const all = await pendingNames(orm);
+ await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
+ await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (10)');
+ // Review N1: the legacy runner ran createTables() before its steps on every
+ // boot, and ~30 tables exist only in the baseline, so it must run, not be marked.
+ await expect(baseline()).resolves.toEqual(all.slice(1, 11));
+ expect(all[0]).toBe(BASELINE);
+ expect(await recorded()).toEqual([]);
+ });
+
+ it('LEGACYBASE-004: refuses a schema_version newer than the last legacy step, and records nothing', async () => {
+ await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
+ await rawExec(orm, `INSERT INTO schema_version (version) VALUES (${LEGACY_FINAL_STEP + 1})`);
+ await expect(baseline()).rejects.toThrow(
+ `[DB] Refusing to boot: schema_version 259 is newer than the last legacy step this release knows (258)`,
+ );
+ expect(await recorded()).toEqual([]);
+ });
+
+ it.each([
+ ['0', '(0)', /schema_version 0 is not a legacy step/],
+ ['a text value', "('205')", /schema_version 205 is not a legacy step/],
+ ['a fraction', '(20.5)', /schema_version 20.5 is not a legacy step/],
+ ['two rows', '(205), (206)', /schema_version holds 2 rows/],
+ ['no row', null, /schema_version holds 0 rows/],
+ ])(
+ 'LEGACYBASE-005: refuses an unmappable schema_version (%s), and records nothing',
+ async (_label, values, error) => {
+ await rawExec(orm, 'CREATE TABLE schema_version (version)');
+ if (values) await rawExec(orm, `INSERT INTO schema_version (version) VALUES ${values}`);
+ await expect(baseline()).rejects.toThrow(error);
+ expect(await recorded()).toEqual([]);
+ },
+ );
+
+ it('LEGACYBASE-006: the baseline rows commit with the run — a failed first run leaves nothing recorded, so the next boot baselines again', async () => {
+ const all = await pendingNames(orm);
+ await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
+ await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (241)');
+ // An obstacle for Migration20200101040200's rebuild, which runs after the baseline.
+ await rawExec(orm, 'CREATE TABLE trek_photo_cache_meta_new (x INTEGER)');
+ await expect(migrate()).rejects.toThrow();
+ expect(await recorded()).toEqual([]);
+
+ // Nothing half-done: the next boot still sees a legacy install and plans the same steps.
+ await expect(baseline()).resolves.toEqual(all.filter((name) => name !== BASELINE).slice(0, 241));
+ expect(await recorded()).toEqual([]);
+ });
+
+ it('LEGACYBASE-007: an install the positional runner left past step 242 is baselined to its step, never refused or replayed', async () => {
+ const all = await pendingNames(orm);
+ const numbered = all.filter((name) => !UNNUMBERED.includes(name));
+ await rawExec(orm, 'CREATE TABLE schema_version (version INTEGER NOT NULL)');
+ await rawExec(orm, 'INSERT INTO schema_version (version) VALUES (250)');
+ const planned = await baseline();
+ expect(planned).toEqual(numbered.slice(0, 250));
+ expect(planned.at(-1)).toBe('Migration20200101041100_half_company_holidays_0_5_covers_the');
+ expect(await recorded()).toEqual([]);
+ });
+ });
diff --cc server/tests/unit/db/repositories/DayAssignments.repository.test.ts
index 000000000,e9bc66e84..120c089f7
mode 000000,100644..100644
--- a/server/tests/unit/db/repositories/DayAssignments.repository.test.ts
+++ b/server/tests/unit/db/repositories/DayAssignments.repository.test.ts
@@@ -1,0 -1,999 +1,1036 @@@
+ /**
+ * `DayAssignmentsRepository` (Plan 3c Task 2) — the DY1/DY3/AS1/AS3
+ * assignment-with-place projection contract (built here, Task 3 consumes it
+ * unchanged for AS1/AS3).
+ */
+ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+ import { createSnapshotTestDb } from '../../../helpers/db-mock';
+ import { resetTestDb } from '../../../helpers/test-db';
+ import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
+ import { createCategory, createDay, createDayAccommodation, createDayAssignment, createPlace, createTrip, createUser } from '../../../helpers/factories';
++import { createTour } from '../../../helpers/tours-repos';
+ import { DayAssignments } from '../../../../src/db/entities/DayAssignments.entity';
+ import type { DayAssignmentsRepository } from '../../../../src/db/repositories/DayAssignments.repository';
+ import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
+ import { withRequestContext } from '../../../../src/nest/database/request-context';
+
+ const testDb = createSnapshotTestDb();
+ let t: TestOrm;
+ let assignments: DayAssignmentsRepository;
+ let uow: UnitOfWork;
+
+ beforeAll(async () => {
+ t = await createTestOrm(testDb);
+ assignments = t.repo(DayAssignments);
+ uow = new UnitOfWork(t.em);
+ });
+ beforeEach(() => { resetTestDb(testDb); t.clear(); });
+ afterAll(async () => { await t.close(); testDb.close(); });
+
+ /** The DY1/DY3/AS1/AS3 statement, run raw — the parity oracle every assertion below is checked against. */
+ function legacyProjectionRow(id: number): unknown {
+ return testDb.prepare(`
+ SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
+ p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
+ COALESCE(da.assignment_time, p.place_time) as place_time,
+ COALESCE(da.assignment_end_time, p.end_time) as end_time,
+ p.duration_minutes, p.notes as place_notes,
+ p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.osm_id, p.amap_poi_id, p.website, p.phone, p.stop_type, p.fill_percent,
++ t.place_id AS tour_place_id, CASE WHEN t.place_id IS NOT NULL THEN p.route_geometry END AS tour_route_geometry,
+ c.name as category_name, c.color as category_color, c.icon as category_icon
+ FROM day_assignments da
+ JOIN places p ON da.place_id = p.id
++ LEFT JOIN tours t ON t.place_id = p.id
+ LEFT JOIN categories c ON p.category_id = c.id
+ WHERE da.id = ?
+ `).get(id);
+ }
+
+ async function withQueryCount<T>(fn: () => Promise<T>): Promise<{ value: T; queries: number }> {
+ const connection = t.orm.em.getConnection();
+ const spy = vi.spyOn(connection, 'execute');
+ try {
+ const value = await fn();
+ return { value, queries: spy.mock.calls.length };
+ } finally {
+ spy.mockRestore();
+ }
+ }
+
+ describe('DayAssignmentsRepository — the DY1/DY3/AS1/AS3 projection', () => {
+ it('ASSIGNPLACEREPO-001: listForDay returns [] for a day with no assignments', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ expect(await assignments.listForDay(day.id)).toEqual([]);
+ });
+
+ it('ASSIGNPLACEREPO-002: listForDay is byte-identical to the legacy statement, column for column', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const category = createCategory(testDb, { name: 'Museum', color: '#111111', icon: '🏛️' });
+ const place = createPlace(testDb, trip.id, { name: 'Louvre', category_id: category.id });
+ const assignment = createDayAssignment(testDb, day.id, place.id);
+
+ const rows = await assignments.listForDay(day.id);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toStrictEqual(legacyProjectionRow(assignment.id));
+ // Named spot-checks so a future field rename fails loudly here, not just via toStrictEqual.
+ expect(rows[0]).toMatchObject({
+ id: assignment.id, day_id: day.id, place_id: place.id,
+ place_name: 'Louvre', category_id: category.id,
+ category_name: 'Museum', category_color: '#111111', category_icon: '🏛️',
+ });
+ });
+
+ it('ASSIGNPLACEREPO-003: findWithPlaceAndCategory(id) is the same row, and null for a missing id', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
+ const assignment = createDayAssignment(testDb, day.id, place.id);
+
+ expect(await assignments.findWithPlaceAndCategory(assignment.id)).toStrictEqual(legacyProjectionRow(assignment.id));
+ expect(await assignments.findWithPlaceAndCategory(999999)).toBeNull();
+ });
+
++ it('ASSIGNPLACEREPO-009: the Tour facet columns are set for a Tour and null for a plain place, even one with a route', async () => {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id);
++ const day = createDay(testDb, trip.id);
++ const tourPlace = createPlace(testDb, trip.id, { name: 'Ridge walk' });
++ const trackPlace = createPlace(testDb, trip.id, { name: 'Imported track' });
++ testDb.prepare('UPDATE places SET route_geometry = ? WHERE id = ?').run('[[47,11],[47.1,11.1]]', tourPlace.id);
++ testDb.prepare('UPDATE places SET route_geometry = ? WHERE id = ?').run('[[1,2],[3,4]]', trackPlace.id);
++ createTour(testDb, tourPlace.id);
++ const tour = createDayAssignment(testDb, day.id, tourPlace.id, { order_index: 0 });
++ const track = createDayAssignment(testDb, day.id, trackPlace.id, { order_index: 1 });
++
++ const one = await assignments.findWithPlaceAndCategory(tour.id);
++ expect(one).toStrictEqual(legacyProjectionRow(tour.id));
++ expect(one).toMatchObject({ tour_place_id: tourPlace.id, tour_route_geometry: '[[47,11],[47.1,11.1]]' });
++ expect(await assignments.findWithPlaceAndCategory(track.id)).toMatchObject({ tour_place_id: null, tour_route_geometry: null });
++
++ const facets = (rows: { tour_place_id: number | null; tour_route_geometry: string | null }[]) =>
++ rows.map((r) => [r.tour_place_id, r.tour_route_geometry]);
++ const expected = [[tourPlace.id, '[[47,11],[47.1,11.1]]'], [null, null]];
++ expect(facets(await assignments.listForDay(day.id))).toEqual(expected);
++ expect(facets(await assignments.listWithPlaceAndCategory([day.id]))).toEqual(expected);
++ });
++
+ it('ASSIGNPLACEREPO-004: place_time/end_time COALESCE — the assignment\'s own time wins, the place\'s time is the fallback', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET place_time = ?, end_time = ? WHERE id = ?').run('09:00', '10:00', place.id);
+ const withOwnTime = createDayAssignment(testDb, day.id, place.id);
+ testDb.prepare('UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ? WHERE id = ?').run('14:00', '15:00', withOwnTime.id);
+ const withoutOwnTime = createDayAssignment(testDb, day.id, place.id);
+
+ const rows = await assignments.listForDay(day.id);
+ const own = rows.find((r) => r.id === withOwnTime.id)!;
+ const fallback = rows.find((r) => r.id === withoutOwnTime.id)!;
+ expect(own.place_time).toBe('14:00');
+ expect(own.end_time).toBe('15:00');
+ expect(fallback.place_time).toBe('09:00');
+ expect(fallback.end_time).toBe('10:00');
+ });
+
+ it('ASSIGNPLACEREPO-005: category is null for an uncategorised place (LEFT JOIN, not INNER)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET category_id = NULL WHERE id = ?').run(place.id);
+ const assignment = createDayAssignment(testDb, day.id, place.id);
+
+ const [row] = await assignments.listForDay(day.id);
+ expect(row.category_id).toBeNull();
+ expect(row.category_name).toBeNull();
+ expect(row.category_color).toBeNull();
+ expect(row.category_icon).toBeNull();
+ expect(row.id).toBe(assignment.id);
+ });
+
+ it('ASSIGNPLACEREPO-006: ORDER BY order_index ASC, created_at ASC', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const placeA = createPlace(testDb, trip.id, { name: 'Second' });
+ const placeB = createPlace(testDb, trip.id, { name: 'First' });
+ createDayAssignment(testDb, day.id, placeA.id, { order_index: 2 });
+ createDayAssignment(testDb, day.id, placeB.id, { order_index: 1 });
+
+ const rows = await assignments.listForDay(day.id);
+ expect(rows.map((r) => r.place_name)).toEqual(['First', 'Second']);
+ });
+
+ it('ASSIGNPLACEREPO-007: listWithPlaceAndCategory spans several days, in the same order; an empty array short-circuits with 0 queries', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const dayA = createDay(testDb, trip.id, { day_number: 1 });
+ const dayB = createDay(testDb, trip.id, { day_number: 2 });
+ const placeA = createPlace(testDb, trip.id, { name: 'A' });
+ const placeB = createPlace(testDb, trip.id, { name: 'B' });
+ const a = createDayAssignment(testDb, dayA.id, placeA.id);
+ const b = createDayAssignment(testDb, dayB.id, placeB.id);
+
+ const rows = await assignments.listWithPlaceAndCategory([dayA.id, dayB.id]);
+ expect(rows.map((r) => r.id).sort()).toEqual([a.id, b.id].sort());
+
+ const { value, queries } = await withQueryCount(() => assignments.listWithPlaceAndCategory([]));
+ expect(value).toEqual([]);
+ expect(queries).toBe(0);
+ });
+
+ // D-shape: every method here is a `qb().execute(..., false)` projection, which
+ // never hydrates an entity into the identity map by construction — proven
+ // anyway, the "not required, proven regardless" shape (AssignmentParticipants
+ // precedent).
+ //
+ // Task 2 review (task-2-review.md, L1): the setup read now passes `{
+ // disableIdentityMap: false }` so it genuinely caches a managed
+ // `DayAssignments` entity first (the base's own default previously made
+ // this a no-op read, same class of vacuousness as `DAYREPO-018`) — even
+ // so, `listForDay` is `qb().execute('all', false)`, never `find`/
+ // `findOne`, so it cannot return that cached entity regardless; this test
+ // proves the projection's OWN freshness, not the identity-map guard.
+ it('ASSIGNPLACEREPO-008 (fresh after a raw UPDATE, not D-shape): a place rename after an unrelated identity-map read is visible in the FIRST wider projection', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id, { name: 'Old Name' });
+ const assignment = createDayAssignment(testDb, day.id, place.id);
+ await t.repo(DayAssignments).find({}, { disableIdentityMap: false }); // populate the identity map with the managed assignment entity
+ testDb.prepare('UPDATE places SET name = ? WHERE id = ?').run('Renamed', place.id);
+
+ const [row] = await assignments.listForDay(day.id);
+ expect(row.place_name).toBe('Renamed');
+ expect(row.id).toBe(assignment.id);
+ });
+ });
+
+ describe('DayAssignmentsRepository — AC20/AC21 (the stop a booking owns, carried to another day by night-seat.ts\'s reseatOwnStopWith)', () => {
+ it('ASSIGNREPO-036 (AC20, maxOrderIndexExcluding): the highest order_index on the day without the excluded row — null for a day holding nothing else, a stored 0 not confused with "no rows"', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const fromDay = createDay(testDb, trip.id, { day_number: 1 });
+ const toDay = createDay(testDb, trip.id, { day_number: 2 });
+ const stopPlace = createPlace(testDb, trip.id, { name: 'Hotel stop' });
+ const otherPlace = createPlace(testDb, trip.id, { name: 'Existing stop' });
+ const stop = createDayAssignment(testDb, fromDay.id, stopPlace.id, { order_index: 0 });
+
+ expect(await assignments.maxOrderIndexExcluding(toDay.id, stop.id)).toBeNull();
+
+ const seated = createDayAssignment(testDb, toDay.id, otherPlace.id, { order_index: 0 });
+ expect(await assignments.maxOrderIndexExcluding(toDay.id, stop.id)).toBe(0);
+ // The excluded row is the only one on the day: nothing is left to measure against.
+ expect(await assignments.maxOrderIndexExcluding(toDay.id, seated.id)).toBeNull();
+
+ createDayAssignment(testDb, toDay.id, createPlace(testDb, trip.id).id, { order_index: 5 });
+ expect(await assignments.maxOrderIndexExcluding(toDay.id, stop.id)).toBe(5);
+ expect(await assignments.maxOrderIndexExcluding(fromDay.id, stop.id)).toBeNull();
+ });
+
+ it('ASSIGNREPO-037 (AC21, relocate): writes day_id, place_id and order_index onto exactly the given row, the other stops of both days untouched', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const fromDay = createDay(testDb, trip.id, { day_number: 1 });
+ const toDay = createDay(testDb, trip.id, { day_number: 2 });
+ const stopPlace = createPlace(testDb, trip.id, { name: 'Hotel stop' });
+ const otherPlace = createPlace(testDb, trip.id, { name: 'Existing stop' });
+ const stop = createDayAssignment(testDb, fromDay.id, stopPlace.id, { order_index: 0 });
+ const neighbour = createDayAssignment(testDb, fromDay.id, otherPlace.id, { order_index: 1 });
+ const existing = createDayAssignment(testDb, toDay.id, otherPlace.id, { order_index: 5 });
+
+ await assignments.relocate(stop.id, toDay.id, stopPlace.id, 6);
+
+ const read = testDb.prepare('SELECT day_id, place_id, order_index FROM day_assignments WHERE id = ?');
+ expect(read.get(stop.id)).toEqual({ day_id: toDay.id, place_id: stopPlace.id, order_index: 6 });
+ expect(read.get(neighbour.id)).toEqual({ day_id: fromDay.id, place_id: otherPlace.id, order_index: 1 });
+ expect(read.get(existing.id)).toEqual({ day_id: toDay.id, place_id: otherPlace.id, order_index: 5 });
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 3 (`AssignmentsService`) — appended after Task 2's own
+ // methods/tests above, per this task's file-ownership rule.
+ // ---------------------------------------------------------------------------
+
+ describe('DayAssignmentsRepository — AS4/AS9/AS12 existence + trip-scoped read', () => {
+ it('ASSIGNREPO-001 (AS9, existsInDay): true only for the matching assignment/day/trip triple', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const otherDay = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ expect(await assignments.existsInDay(a.id, day.id, trip.id)).toBe(true);
+ expect(await assignments.existsInDay(a.id, otherDay.id, trip.id)).toBe(false);
+ expect(await assignments.existsInDay(a.id, day.id, trip.id + 1)).toBe(false);
+ });
+
+ it('ASSIGNREPO-002 (AS9): raw-bind on day_id/trip_id — a string binds unconverted, same as a real number; `id` itself is `number`-only now (Task 3 review H1, absorbed in Task 4: the method\'s only caller `toRowId`s `id` before calling, so the type narrowed to match)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ expect(await assignments.existsInDay(a.id, String(day.id), String(trip.id))).toBe(true);
+ });
+
+ it('ASSIGNREPO-003 (AS12, findInTrip): the raw `da.*` row, scoped to the trip via a two-hop join; undefined cross-trip', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id, { order_index: 3 });
+ testDb.prepare('UPDATE day_assignments SET assignment_time = ?, notes = ? WHERE id = ?').run('09:00', 'a note', a.id);
+
+ const row = await assignments.findInTrip(a.id, trip.id);
+ const legacy = testDb.prepare(`SELECT da.* FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE da.id = ? AND d.trip_id = ?`).get(a.id, trip.id);
+ expect(row).toStrictEqual(legacy);
+ expect(row).toMatchObject({ id: a.id, day_id: day.id, order_index: 3, assignment_time: '09:00', notes: 'a note' });
+ expect(await assignments.findInTrip(a.id, trip.id + 1)).toBeUndefined();
+ });
+ });
+
+ describe('DayAssignmentsRepository — AS6/AS7/AS8 (createAssignment)', () => {
+ it('ASSIGNREPO-004 (AS6, maxOrderIndex): null for a day with no assignments, otherwise the highest order_index — a stored 0 is not confused with "no rows"', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ expect(await assignments.maxOrderIndex(day.id)).toBeNull();
+ createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
+ expect(await assignments.maxOrderIndex(day.id)).toBe(0);
+ createDayAssignment(testDb, day.id, place.id, { order_index: 5 });
+ expect(await assignments.maxOrderIndex(day.id)).toBe(5);
+ });
+
+ it('ASSIGNREPO-005 (AS7, shiftOrderFrom): shifts order_index for rows at/after the threshold, on that day only', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const otherDay = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const before = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
+ const at = createDayAssignment(testDb, day.id, place.id, { order_index: 1 });
+ const after = createDayAssignment(testDb, day.id, place.id, { order_index: 2 });
+ const foreign = createDayAssignment(testDb, otherDay.id, place.id, { order_index: 1 });
+
+ await withRequestContext(t.orm, async () => { await assignments.shiftOrderFrom(day.id, 1); });
+
+ const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
+ expect(order(before.id)).toBe(0);
+ expect(order(at.id)).toBe(2);
+ expect(order(after.id)).toBe(3);
+ expect(order(foreign.id)).toBe(1);
+ });
+
+ it('ASSIGNREPO-006 (AS8, insertAssignment): writes every column and returns the inserted id, notes/accommodation_id nullable', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+
+ const id = await withRequestContext(t.orm, () => assignments.insertAssignment({
+ day_id: day.id, place_id: place.id, order_index: 2, notes: null, accommodation_id: null,
+ }));
+ expect(typeof id).toBe('number');
+ const row = testDb.prepare('SELECT day_id, place_id, order_index, notes, accommodation_id FROM day_assignments WHERE id = ?').get(id);
+ expect(row).toEqual({ day_id: day.id, place_id: place.id, order_index: 2, notes: null, accommodation_id: null });
+
+ const id2 = await withRequestContext(t.orm, () => assignments.insertAssignment({
+ day_id: day.id, place_id: place.id, order_index: 0, notes: 'skip the line', accommodation_id: 42,
+ }));
+ const row2 = testDb.prepare('SELECT notes, accommodation_id FROM day_assignments WHERE id = ?').get(id2);
+ expect(row2).toEqual({ notes: 'skip the line', accommodation_id: 42 });
+ });
+ });
+
+ describe('DayAssignmentsRepository — AS10/AS11/AS13/AS14/AS19 (delete / order / move)', () => {
+ it('ASSIGNREPO-007 (AS10, deleteById): removes the row', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ await withRequestContext(t.orm, () => assignments.deleteById(a.id));
+ expect(testDb.prepare('SELECT id FROM day_assignments WHERE id = ?').get(a.id)).toBeUndefined();
+ });
+
+ it('ASSIGNREPO-008 (AS11, setOrderIndex day-scoped): writes only the row matching BOTH id and day_id', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const otherDay = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
+ const foreign = createDayAssignment(testDb, otherDay.id, place.id, { order_index: 0 });
+
+ await withRequestContext(t.orm, () => assignments.setOrderIndex(a.id, day.id, 7));
+ // A day_id mismatch (this id does not sit on otherDay) writes nothing.
+ await withRequestContext(t.orm, () => assignments.setOrderIndex(foreign.id, day.id, 9));
+
+ const order = (id: number) => (testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(id) as { order_index: number }).order_index;
+ expect(order(a.id)).toBe(7);
+ expect(order(foreign.id)).toBe(0);
+ });
+
+ it('ASSIGNREPO-009 (AS19, setOrderIndex unscoped): day_id undefined writes by id alone', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
+ await withRequestContext(t.orm, () => assignments.setOrderIndex(a.id, undefined, 3));
+ expect((testDb.prepare('SELECT order_index FROM day_assignments WHERE id = ?').get(a.id) as { order_index: number }).order_index).toBe(3);
+ });
+
+ it('ASSIGNREPO-010 (AS13, getDayId): the assignment\'s day_id, undefined for a missing id', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ expect(await assignments.getDayId(a.id)).toBe(day.id);
+ expect(await assignments.getDayId(999999)).toBeUndefined();
+ });
+
++ it('ASSIGNREPO-042 (getPlaceId): the place_id of the assignment, undefined for a missing id', async () => {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id);
++ const day = createDay(testDb, trip.id);
++ const place = createPlace(testDb, trip.id);
++ const a = createDayAssignment(testDb, day.id, place.id);
++ expect(await assignments.getPlaceId(a.id)).toBe(place.id);
++ expect(await assignments.getPlaceId(999999)).toBeUndefined();
++ });
++
+ it('ASSIGNREPO-011 (AS14, moveToDay): writes day_id and order_index together', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const target = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
+ await withRequestContext(t.orm, () => assignments.moveToDay(a.id, target.id, 4));
+ const row = testDb.prepare('SELECT day_id, order_index FROM day_assignments WHERE id = ?').get(a.id);
+ expect(row).toEqual({ day_id: target.id, order_index: 4 });
+ });
+
+ // Task 9 fix wave (B-M5, the OAUTHTOKREPO-012/REANCHORDAY-003 rollback
+ // shape): `moveToDay` writes inside a `uow.transactional` body that then
+ // throws — the write must roll back with it. MUTATION-PROVED (see the
+ // report): removing the `throw` makes the post-rollback assertion below
+ // fail (the row WOULD have moved).
+ it('ASSIGNREPO-031: inside a uow.transactional that then ROLLS BACK, moveToDay is left un-moved', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const target = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
+
+ let caught: unknown;
+ try {
+ await withRequestContext(t.orm, async () => {
+ await uow.transactional(async () => {
+ await assignments.moveToDay(a.id, target.id, 4);
+ throw new Error('force rollback');
+ });
+ });
+ } catch (e) { caught = e; }
+ expect((caught as Error).message).toBe('force rollback');
+
+ const row = testDb.prepare('SELECT day_id, order_index FROM day_assignments WHERE id = ?').get(a.id);
+ expect(row).toEqual({ day_id: day.id, order_index: 0 });
+ });
+ });
+
+ describe('DayAssignmentsRepository.effectiveStart (AS16, Kysely)', () => {
+ it('ASSIGNREPO-012: byte-identical to the legacy three-way COALESCE, own time wins over the place\'s', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET place_time = ? WHERE id = ?').run('08:00', place.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ testDb.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run('14:00', a.id);
+
+ const row = await withRequestContext(t.orm, () => assignments.effectiveStart(a.id));
+ const legacy = testDb.prepare(`
+ SELECT da.day_id, COALESCE(da.assignment_time, p.place_time, acc.check_in) AS start
+ FROM day_assignments da JOIN places p ON da.place_id = p.id
+ LEFT JOIN day_accommodations acc ON acc.id = da.accommodation_id
+ WHERE da.id = ?
+ `).get(a.id);
+ expect(row).toEqual(legacy);
+ expect(row).toEqual({ day_id: day.id, start: '14:00' });
+ });
+
+ it('ASSIGNREPO-013: falls back to the place\'s own time when the assignment has none', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET place_time = ? WHERE id = ?').run('08:00', place.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ expect(await withRequestContext(t.orm, () => assignments.effectiveStart(a.id))).toEqual({ day_id: day.id, start: '08:00' });
+ });
+
+ it('ASSIGNREPO-014: a booked night falls back further, to the accommodation\'s check_in (a LEFT JOIN through the plain accommodation_id column, no ORM relation)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const hotel = createPlace(testDb, trip.id);
+ const night = createDayAssignment(testDb, day.id, hotel.id);
+ const stay = testDb.prepare(
+ "INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in) VALUES (?, ?, ?, ?, '17:00')",
+ ).run(trip.id, hotel.id, day.id, day.id);
+ testDb.prepare('UPDATE day_assignments SET accommodation_id = ? WHERE id = ?').run(Number(stay.lastInsertRowid), night.id);
+
+ expect(await withRequestContext(t.orm, () => assignments.effectiveStart(night.id))).toEqual({ day_id: day.id, start: '17:00' });
+ });
+
+ it('ASSIGNREPO-015: null start when nothing sets a time anywhere in the chain', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ expect(await withRequestContext(t.orm, () => assignments.effectiveStart(a.id))).toEqual({ day_id: day.id, start: null });
+ });
+
+ it('ASSIGNREPO-016: undefined for a missing id', async () => {
+ expect(await withRequestContext(t.orm, () => assignments.effectiveStart(999999))).toBeUndefined();
+ });
+ });
+
+ describe('DayAssignmentsRepository.listForTimeSort (AS18, Kysely)', () => {
+ it('ASSIGNREPO-017: byte-identical to the legacy statement, including the computed `located` boolean (0/1) and the three-key ORDER BY', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const located = createPlace(testDb, trip.id, { name: 'Has coords' });
+ const unlocated = createPlace(testDb, trip.id, { name: 'No coords' });
+ testDb.prepare('UPDATE places SET lat = NULL, lng = NULL WHERE id = ?').run(unlocated.id);
+ const a1 = createDayAssignment(testDb, day.id, located.id, { order_index: 1 });
+ const a2 = createDayAssignment(testDb, day.id, unlocated.id, { order_index: 0 });
+ testDb.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run('09:00', a1.id);
+
+ const rows = await withRequestContext(t.orm, () => assignments.listForTimeSort(day.id));
+ const legacy = testDb.prepare(`
+ SELECT da.id, da.order_index, COALESCE(da.assignment_time, p.place_time, acc.check_in) as effective_time,
+ (p.lat IS NOT NULL AND p.lng IS NOT NULL) as located
+ FROM day_assignments da JOIN places p ON da.place_id = p.id
+ LEFT JOIN day_accommodations acc ON acc.id = da.accommodation_id
+ WHERE da.day_id = ?
+ ORDER BY da.order_index ASC, da.created_at ASC, da.id ASC
+ `).all(day.id);
+ expect(rows).toEqual(legacy);
+ expect(rows.map((r) => r.id)).toEqual([a2.id, a1.id]);
+ expect(rows.find((r) => r.id === a1.id)?.located).toBe(1);
+ expect(rows.find((r) => r.id === a2.id)?.located).toBe(0);
+ });
+
+ it('ASSIGNREPO-018: [] for a day with no assignments', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ expect(await withRequestContext(t.orm, () => assignments.listForTimeSort(day.id))).toEqual([]);
+ });
+ });
+
+ describe('DayAssignmentsRepository.listSeatRows (AC7, Kysely)', () => {
+ it('ASSIGNREPO-038: byte-identical to the legacy statement — a booked night at its check_in, a stop at its own time, a stop at its place\'s, `located` 0/1 and the three-key ORDER BY', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const hotel = createPlace(testDb, trip.id, { name: 'Hotel' });
+ const museum = createPlace(testDb, trip.id, { name: 'Museum' });
+ const cafe = createPlace(testDb, trip.id, { name: 'Cafe' });
+ const unlocated = createPlace(testDb, trip.id, { name: 'No coords' });
+ testDb.prepare('UPDATE places SET place_time = ? WHERE id = ?').run('08:00', hotel.id);
+ testDb.prepare('UPDATE places SET place_time = ? WHERE id = ?').run('11:00', cafe.id);
+ testDb.prepare('UPDATE places SET lat = NULL, lng = NULL WHERE id = ?').run(unlocated.id);
+ const night = createDayAssignment(testDb, day.id, hotel.id, { order_index: 3 });
+ const ownTime = createDayAssignment(testDb, day.id, museum.id, { order_index: 1 });
+ const placeTime = createDayAssignment(testDb, day.id, cafe.id, { order_index: 0 });
+ const noCoords = createDayAssignment(testDb, day.id, unlocated.id, { order_index: 2 });
+ const stay = createDayAccommodation(testDb, trip.id, hotel.id, day.id, day.id, { check_in: '17:00' });
+ testDb.prepare('UPDATE day_assignments SET accommodation_id = ? WHERE id = ?').run(stay.id, night.id);
+ testDb.prepare('UPDATE day_assignments SET assignment_time = ? WHERE id = ?').run('09:00', ownTime.id);
+
+ const rows = await withRequestContext(t.orm, () => assignments.listSeatRows(day.id));
+ const legacy = testDb.prepare(`
+ SELECT da.id, da.order_index,
+ CASE WHEN other.id IS NULL THEN COALESCE(da.assignment_time, p.place_time) ELSE other.check_in END AS at,
+ other.id AS night_id,
+ (p.lat IS NOT NULL AND p.lng IS NOT NULL) AS located
+ FROM day_assignments da JOIN places p ON p.id = da.place_id
+ LEFT JOIN day_accommodations other ON other.id = da.accommodation_id
+ WHERE da.day_id = ?
+ ORDER BY da.order_index ASC, da.created_at ASC, da.id ASC
+ `).all(day.id);
+ expect(rows).toEqual(legacy);
+ expect(rows.map((r) => r.id)).toEqual([placeTime.id, ownTime.id, noCoords.id, night.id]);
+ expect(rows.find((r) => r.id === night.id)).toMatchObject({ at: '17:00', night_id: stay.id, located: 1 });
+ expect(rows.find((r) => r.id === ownTime.id)).toMatchObject({ at: '09:00', night_id: null, located: 1 });
+ expect(rows.find((r) => r.id === placeTime.id)).toMatchObject({ at: '11:00', night_id: null });
+ expect(rows.find((r) => r.id === noCoords.id)?.located).toBe(0);
+ });
+ });
+
+ describe('DayAssignmentsRepository — AS17/AS24/AS25/AS26/AS27/AS32/AS33/AS34 (single-column writes)', () => {
+ it('ASSIGNREPO-019 (AS17, setTimes): writes both columns, null-clearable', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ await withRequestContext(t.orm, () => assignments.setTimes(a.id, '09:00', '10:30'));
+ expect(testDb.prepare('SELECT assignment_time, assignment_end_time FROM day_assignments WHERE id = ?').get(a.id))
+ .toEqual({ assignment_time: '09:00', assignment_end_time: '10:30' });
+ await withRequestContext(t.orm, () => assignments.setTimes(a.id, null, null));
+ expect(testDb.prepare('SELECT assignment_time, assignment_end_time FROM day_assignments WHERE id = ?').get(a.id))
+ .toEqual({ assignment_time: null, assignment_end_time: null });
+ });
+
+ // Task 9 fix wave (B-M5, the OAUTHTOKREPO-012/REANCHORDAY-003 rollback
+ // shape): `setTimes` writes inside a `uow.transactional` body that then
+ // throws — the write must roll back with it.
+ it('ASSIGNREPO-032: inside a uow.transactional that then ROLLS BACK, setTimes is left unwritten', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+
+ let caught: unknown;
+ try {
+ await withRequestContext(t.orm, async () => {
+ await uow.transactional(async () => {
+ await assignments.setTimes(a.id, '09:00', '10:30');
+ throw new Error('force rollback');
+ });
+ });
+ } catch (e) { caught = e; }
+ expect((caught as Error).message).toBe('force rollback');
+
+ expect(testDb.prepare('SELECT assignment_time, assignment_end_time FROM day_assignments WHERE id = ?').get(a.id))
+ .toEqual({ assignment_time: null, assignment_end_time: null });
+ });
+
+ it('ASSIGNREPO-020 (AS24, setEndDay): writes the 0/1 flag', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ await withRequestContext(t.orm, () => assignments.setEndDay(a.id, 1));
+ expect((testDb.prepare('SELECT end_day FROM day_assignments WHERE id = ?').get(a.id) as { end_day: number }).end_day).toBe(1);
+ });
+
+ it('ASSIGNREPO-021 (AS25, setNotes): null-clearable', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ await withRequestContext(t.orm, () => assignments.setNotes(a.id, 'a note'));
+ expect((testDb.prepare('SELECT notes FROM day_assignments WHERE id = ?').get(a.id) as { notes: string | null }).notes).toBe('a note');
+ await withRequestContext(t.orm, () => assignments.setNotes(a.id, null));
+ expect((testDb.prepare('SELECT notes FROM day_assignments WHERE id = ?').get(a.id) as { notes: string | null }).notes).toBeNull();
+ });
+
+ it('ASSIGNREPO-022 (AS26/AS27, setLegMode/setIncomingLegMode): each writes its own column', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ await withRequestContext(t.orm, () => assignments.setLegMode(a.id, 'cycling'));
+ await withRequestContext(t.orm, () => assignments.setIncomingLegMode(a.id, 'walking'));
+ expect(testDb.prepare('SELECT leg_transport_mode, incoming_leg_transport_mode FROM day_assignments WHERE id = ?').get(a.id))
+ .toEqual({ leg_transport_mode: 'cycling', incoming_leg_transport_mode: 'walking' });
+ await withRequestContext(t.orm, () => assignments.setLegMode(a.id, null));
+ expect((testDb.prepare('SELECT leg_transport_mode FROM day_assignments WHERE id = ?').get(a.id) as { leg_transport_mode: string | null }).leg_transport_mode).toBeNull();
+ });
+
+ it('ASSIGNREPO-039 (AS32, listIdsToClear): exactly the day\'s ids, [] for an empty day', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const otherDay = createDay(testDb, trip.id);
+ const emptyDay = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a1 = createDayAssignment(testDb, day.id, place.id);
+ const a2 = createDayAssignment(testDb, day.id, place.id);
+ createDayAssignment(testDb, otherDay.id, place.id);
+ expect((await withRequestContext(t.orm, () => assignments.listIdsToClear(day.id))).sort((x, y) => x - y)).toEqual([a1.id, a2.id]);
+ expect(await withRequestContext(t.orm, () => assignments.listIdsToClear(emptyDay.id))).toEqual([]);
+ });
+
+ it('ASSIGNREPO-040 (AS33, deleteForDay): removes only that day\'s rows', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const otherDay = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ createDayAssignment(testDb, day.id, place.id);
+ createDayAssignment(testDb, day.id, place.id);
+ const kept = createDayAssignment(testDb, otherDay.id, place.id);
+ await withRequestContext(t.orm, () => assignments.deleteForDay(day.id));
+ expect(testDb.prepare('SELECT id FROM day_assignments WHERE day_id = ?').all(day.id)).toEqual([]);
+ expect(testDb.prepare('SELECT id FROM day_assignments WHERE day_id = ?').all(otherDay.id)).toEqual([{ id: kept.id }]);
+ });
+
+ it('ASSIGNREPO-041 (AS34, setRouteExcluded): writes 1 and then 0 on exactly the given row', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ const other = createDayAssignment(testDb, day.id, place.id);
+ const routeExcluded = (id: number) => (testDb.prepare('SELECT route_excluded FROM day_assignments WHERE id = ?').get(id) as { route_excluded: number }).route_excluded;
+ await withRequestContext(t.orm, () => assignments.setRouteExcluded(a.id, 1));
+ expect(routeExcluded(a.id)).toBe(1);
+ expect(routeExcluded(other.id)).toBe(0);
+ await withRequestContext(t.orm, () => assignments.setRouteExcluded(a.id, 0));
+ expect(routeExcluded(a.id)).toBe(0);
+ expect(routeExcluded(other.id)).toBe(0);
+ });
+ });
+
+ // D-shape: a `qb().execute(..., false)` projection or a Kysely read, neither
+ // of which hydrates an entity into the identity map by construction (the
+ // ASSIGNPLACEREPO-008 precedent above) — proven anyway for the new reads.
+ // Task 2 review (task-2-review.md, L1, program note): the setup read passes
+ // `{ disableIdentityMap: false }` so it genuinely caches the managed
+ // assignment entity first (a bare `find({})` would be a no-op read under
+ // the base's own default, the same vacuousness `DAYREPO-018` had).
+ it('ASSIGNREPO-023 (fresh after a raw UPDATE, not D-shape): a notes write after an unrelated identity-map read is visible in findInTrip', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const a = createDayAssignment(testDb, day.id, place.id);
+ await t.repo(DayAssignments).find({}, { disableIdentityMap: false }); // populate the identity map with the managed assignment entity
+ await withRequestContext(t.orm, () => assignments.setNotes(a.id, 'fresh note'));
+ expect(await assignments.findInTrip(a.id, trip.id)).toMatchObject({ notes: 'fresh note' });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 4 (`PlacesService.exportGpx`) — the PL30 itinerary read.
+ // ---------------------------------------------------------------------------
+
+ describe('DayAssignmentsRepository.listItineraryForGpx (PL30)', () => {
+ it('ASSIGNREPO-024: joins day + place, only stops with coordinates, ordered by day_number then order_index', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day1 = createDay(testDb, trip.id, { day_number: 1, date: '2026-01-01', title: 'Day One' });
+ const day2 = createDay(testDb, trip.id, { day_number: 2, date: '2026-01-02' });
+ const geo = createPlace(testDb, trip.id, { name: 'Has Coords', lat: 1, lng: 2 });
+ const noGeo = testDb.prepare('INSERT INTO places (trip_id, name, lat, lng) VALUES (?, ?, NULL, NULL)').run(trip.id, 'No Coords').lastInsertRowid as number;
+ const secondStop = createPlace(testDb, trip.id, { name: 'Second Stop', lat: 3, lng: 4 });
+ // day2's stop first (order_index 0), day1's stop second — proves the
+ // ORDER BY is day_number then order_index, not insertion/id order.
+ createDayAssignment(testDb, day2.id, secondStop.id, { order_index: 0 });
+ createDayAssignment(testDb, day1.id, geo.id, { order_index: 0 });
+ createDayAssignment(testDb, day1.id, noGeo, { order_index: 1 });
+
+ const rows = await assignments.listItineraryForGpx(trip.id);
+ expect(rows).toEqual([
+ { day_number: 1, date: '2026-01-01', title: 'Day One', name: 'Has Coords', lat: 1, lng: 2 },
+ { day_number: 2, date: '2026-01-02', title: null, name: 'Second Stop', lat: 3, lng: 4 },
+ ]);
+ });
+
+ it('ASSIGNREPO-025: a trip with no coordinate-bearing stops returns []', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const noGeo = testDb.prepare('INSERT INTO places (trip_id, name, lat, lng) VALUES (?, ?, NULL, NULL)').run(trip.id, 'No Coords').lastInsertRowid as number;
+ createDayAssignment(testDb, day.id, noGeo);
+ expect(await assignments.listItineraryForGpx(trip.id)).toEqual([]);
+ });
+
+ it('ASSIGNREPO-026: another trip\'s stops never leak in', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ const day = createDay(testDb, other.id);
+ const place = createPlace(testDb, other.id, { lat: 5, lng: 6 });
+ createDayAssignment(testDb, day.id, place.id);
+ expect(await assignments.listItineraryForGpx(trip.id)).toEqual([]);
+ });
+ });
+
+ // ── Plan 3c Task 8 (`TripsService.copy`, TP48/TP49/TP57) — additive ─────────
+
+ describe('DayAssignmentsRepository.listAllForTrip (TP48)', () => {
+ // Task 9 fix wave (B-M4, rule 19): widened from an ids-only assertion to
+ // full-row parity on a fully seeded fixture — every nullable column
+ // non-null in one row, null in the other, plus a unicode string and a
+ // '007'-style digit string — `toEqual(<the legacy da.*-joined-through-d
+ // statement run raw>)`, so a renamed/dropped column or a changed row
+ // order would fail this, not just the id list.
+ it('ASSIGNREPO-027: every assignment of the trip, no ORDER BY guarantee, scoped by the day→trip join — toEqual(legacy) on a fully seeded fixture', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id, { name: 'Stop A' });
+ const bare = createPlace(testDb, trip.id, { name: 'Stop B' });
+ const accommodation = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id);
+
+ const insert = testDb.prepare(`
+ INSERT INTO day_assignments (
+ day_id, place_id, order_index, notes, reservation_status, reservation_notes,
+ reservation_datetime, created_at, assignment_time, assignment_end_time,
+ leg_transport_mode, incoming_leg_transport_mode, end_day, accommodation_id
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `);
+
+ // Row A: every nullable column non-null, a unicode string and a
+ // '007'-style digit string among the values.
+ const a1 = insert.run(
+ day.id, place.id, 5, 'Notes — 日本 ☕️ 007', 'confirmed', 'resv notes 007',
+ '2026-01-01T10:00:00Z', '2026-01-01 09:00:00', '10:00', '11:00',
+ 'walking', 'driving', 1, accommodation.id,
+ ).lastInsertRowid as number;
+
+ // Row B: every nullable column NULL (end_day is NOT NULL, given 0).
+ const a2 = insert.run(
+ day.id, bare.id, null, null, null, null,
+ null, null, null, null,
+ null, null, 0, null,
+ ).lastInsertRowid as number;
+
+ const otherDay = createDay(testDb, other.id);
+ const otherPlace = createPlace(testDb, other.id);
+ createDayAssignment(testDb, otherDay.id, otherPlace.id);
+
+ const rows = await assignments.listAllForTrip(trip.id);
+ const legacy = testDb.prepare('SELECT da.* FROM day_assignments da JOIN days d ON d.id = da.day_id WHERE d.trip_id = ?').all(trip.id);
+ expect(rows).toEqual(legacy);
+ expect(rows.map((r) => r.id)).toEqual([a1, a2]);
+ });
+
+ it('ASSIGNREPO-028: an empty trip returns []', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ expect(await assignments.listAllForTrip(trip.id)).toEqual([]);
+ });
+ });
+
+ describe('DayAssignmentsRepository.insertAssignmentCopy (TP49)', () => {
+ it('ASSIGNREPO-029: writes the 10-column copy set verbatim, no accommodation_id (stamped separately, TP57)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+
+ const newId = await assignments.insertAssignmentCopy({
+ day_id: day.id, place_id: place.id, order_index: 2, notes: 'n',
+ reservation_status: 'booked', reservation_notes: 'rn', reservation_datetime: '2026-01-01T10:00',
+ assignment_time: '10:00', assignment_end_time: '11:00', end_day: 0,
+ });
+
+ const row = testDb.prepare(`
+ SELECT day_id, place_id, order_index, notes, reservation_status, reservation_notes,
+ reservation_datetime, assignment_time, assignment_end_time, end_day, accommodation_id
+ FROM day_assignments WHERE id = ?
+ `).get(newId);
+ expect(row).toEqual({
+ day_id: day.id, place_id: place.id, order_index: 2, notes: 'n',
+ reservation_status: 'booked', reservation_notes: 'rn', reservation_datetime: '2026-01-01T10:00',
+ assignment_time: '10:00', assignment_end_time: '11:00', end_day: 0, accommodation_id: null,
+ });
+ });
+ });
+
+ describe('DayAssignmentsRepository.setAccommodation (TP57)', () => {
+ it('ASSIGNREPO-030: stamps accommodation_id onto exactly the given assignment', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id);
+ const assignment = createDayAssignment(testDb, day.id, place.id);
+ const other = createDayAssignment(testDb, day.id, place.id);
+ const accom = createDayAccommodation(testDb, trip.id, place.id, day.id, day.id);
+
+ await assignments.setAccommodation(assignment.id, accom.id);
+
+ expect((testDb.prepare('SELECT accommodation_id FROM day_assignments WHERE id = ?').get(assignment.id) as { accommodation_id: number }).accommodation_id).toBe(accom.id);
+ expect((testDb.prepare('SELECT accommodation_id FROM day_assignments WHERE id = ?').get(other.id) as { accommodation_id: number | null }).accommodation_id).toBeNull();
+ });
+ });
+
+ // ─────────────────────────────────────────────────────────────────────────────
+ // Plan 4 Task 8b-2, item 1 (3d Task 7 review's "DayAssignments.listRoadtripVisits"
+ // carry): RPL2 (`roadtrip-plan.service.ts::context`'s `visits` read) had no
+ // repository-level toEqual(<legacy raw>) test — a correlated scalar subquery
+ // inside a LEFT JOIN ON clause, exercised here with every nullable column
+ // both null (no stay, no leg transport, coalesce falls back to the place)
+ // and set (a matching stay + its checkout day, explicit assignment overrides).
+ // ─────────────────────────────────────────────────────────────────────────────
+
+ const LEGACY_LIST_ROADTRIP_VISITS = `
+ SELECT a.id, a.day_id, a.order_index, a.place_id, p.name, p.lat, p.lng,
+ COALESCE(a.assignment_time, p.place_time) AS time,
+ COALESCE(a.assignment_end_time, p.end_time) AS end_time,
+ p.duration_minutes, a.end_day,
+ a.leg_transport_mode, a.incoming_leg_transport_mode, p.stop_type, p.fill_percent,
+ a.accommodation_id, stay.id AS stay_id, stay.check_in, stay.check_out, checkout.day_number AS checkout_day
+ FROM day_assignments a
+ JOIN days d ON d.id = a.day_id
+ JOIN places p ON p.id = a.place_id
+ LEFT JOIN day_accommodations stay
+ ON stay.id = (SELECT id FROM day_accommodations WHERE place_id = p.id AND start_day_id = d.id ORDER BY id LIMIT 1)
+ LEFT JOIN days checkout ON checkout.id = stay.end_day_id
+ WHERE d.trip_id = ?
+ ORDER BY d.day_number, a.order_index, a.created_at
+ `;
+
+ describe('DayAssignmentsRepository.listRoadtripVisits (RPL2, roadtrip-plan.service.ts::context)', () => {
+ it('ASSIGNREPO-034: matches the legacy statement — no stay, coalesce falls back to the place, leg transport NULL', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const place = createPlace(testDb, trip.id, { name: 'Museum' });
+ testDb.prepare('UPDATE places SET place_time = ?, end_time = ?, duration_minutes = ?, stop_type = ?, fill_percent = ? WHERE id = ?')
+ .run('09:00', '11:00', 90, null, null, place.id);
+ createDayAssignment(testDb, day.id, place.id);
+
+ const legacy = testDb.prepare(LEGACY_LIST_ROADTRIP_VISITS).all(trip.id);
+ const typed = await assignments.listRoadtripVisits(trip.id);
+ expect(typed).toEqual(legacy);
+ expect(typed[0]).toMatchObject({ time: '09:00', end_time: '11:00', stay_id: null, check_in: null, check_out: null, checkout_day: null, leg_transport_mode: null });
+ });
+
+ it('ASSIGNREPO-035: matches the legacy statement — a matching stay populates stay/checkout columns, explicit overrides win over coalesce', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id, { day_number: 1 });
+ const checkoutDay = createDay(testDb, trip.id, { day_number: 2 });
+ const place = createPlace(testDb, trip.id, { name: 'Grand Hotel' });
+ testDb.prepare('UPDATE places SET place_time = ?, end_time = ?, duration_minutes = ?, stop_type = ?, fill_percent = ? WHERE id = ?')
+ .run('08:00', '10:00', 45, 'lodging', 80, place.id);
+ const stay = createDayAccommodation(testDb, trip.id, place.id, day.id, checkoutDay.id, { check_in: '15:00', check_out: '11:00' });
+ const assignment = createDayAssignment(testDb, day.id, place.id);
+ testDb.prepare('UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ?, leg_transport_mode = ?, incoming_leg_transport_mode = ?, end_day = ? WHERE id = ?')
+ .run('14:00', '14:30', 'driving', 'walking', 1, assignment.id);
+
+ const legacy = testDb.prepare(LEGACY_LIST_ROADTRIP_VISITS).all(trip.id);
+ const typed = await assignments.listRoadtripVisits(trip.id);
+ expect(typed).toEqual(legacy);
+ expect(typed[0]).toMatchObject({
+ time: '14:00', end_time: '14:30', stay_id: stay.id, check_in: '15:00', check_out: '11:00',
+ checkout_day: 2, leg_transport_mode: 'driving', incoming_leg_transport_mode: 'walking', end_day: 1,
+ stop_type: 'lodging', fill_percent: 80, duration_minutes: 45,
+ });
+ });
+
+ it('ASSIGNREPO-033: empty array for a trip with no assignments', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ expect(await assignments.listRoadtripVisits(trip.id)).toEqual([]);
+ });
+ });
+
+ /**
+ * Plan 4 Task 8b-4a (3h L4) — full-key `toEqual(<legacy raw>)` parity for
+ * `DayAssignmentsRepository.listPublicForShare` (SH9), flagged by the 3h
+ * ledger as having no repository-level parity test. Same WHERE/ORDER BY
+ * shape as {@link legacyProjectionRow}'s join above (`listForDay`'s single-
+ * id form widened to `day_id IN (...)`), but a narrower SELECT list: the
+ * six columns `SharePublicAssignmentRow` omits (`google_place_id`,
+ * `google_ftid`, `osm_id`, `amap_poi_id`, `stop_type`, `fill_percent`) must
+ * never appear on the row at all — a public share must not leak them.
+ */
+ function legacyPublicForShare(dayIds: number[]): unknown {
+ if (dayIds.length === 0) return [];
+ const placeholders = dayIds.map(() => '?').join(',');
+ return testDb.prepare(`
+ SELECT da.*, p.id as place_id, p.name as place_name, p.description as place_description,
+ p.lat, p.lng, p.address, p.category_id, p.price, p.currency as place_currency,
+ COALESCE(da.assignment_time, p.place_time) as place_time,
+ COALESCE(da.assignment_end_time, p.end_time) as end_time,
+ p.duration_minutes, p.notes as place_notes,
+ p.image_url, p.transport_mode, p.website, p.phone,
+ c.name as category_name, c.color as category_color, c.icon as category_icon
+ FROM day_assignments da
+ JOIN places p ON da.place_id = p.id
+ LEFT JOIN categories c ON p.category_id = c.id
+ WHERE da.day_id IN (${placeholders})
+ ORDER BY da.order_index ASC, da.created_at ASC
+ `).all(...dayIds);
+ }
+
+ describe('DayAssignmentsRepository.listPublicForShare (SH9, share.service.ts)', () => {
+ it('matches the legacy statement across multiple days, every nullable column both null and set, owner-only columns withheld', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day1 = createDay(testDb, trip.id, { day_number: 1 });
+ const day2 = createDay(testDb, trip.id, { day_number: 2 });
+ const excludedDay = createDay(testDb, trip.id, { day_number: 3 });
+ const category = createCategory(testDb, { name: 'Museum', color: '#111111', icon: '🏛️' });
+
+ const placeFull = createPlace(testDb, trip.id, { name: 'Louvre', lat: 48.86, lng: 2.34, category_id: category.id, description: 'Art museum' });
+ testDb.prepare(`
+ UPDATE places SET address = ?, price = ?, currency = ?, place_time = ?, end_time = ?,
+ duration_minutes = ?, notes = ?, image_url = ?, transport_mode = ?, website = ?, phone = ?,
+ google_place_id = 'ChIJ123', google_ftid = 'ftid1', osm_id = 'osm1', amap_poi_id = 'amap1',
+ stop_type = 'lodging', fill_percent = 80
+ WHERE id = ?`).run('Rue de Rivoli', 17.5, 'EUR', '09:00', '11:00', 120, 'bring ID', 'https://img/louvre.jpg', 'walking', 'https://louvre.fr', '+33140205050', placeFull.id);
+ const assignmentOnFullPlace = createDayAssignment(testDb, day1.id, placeFull.id, { order_index: 2 });
+ testDb.prepare(`
+ UPDATE day_assignments SET assignment_time = ?, assignment_end_time = ?, reservation_status = 'confirmed',
+ reservation_notes = 'window seat', reservation_datetime = '2026-09-01T09:00:00.000Z',
+ leg_transport_mode = 'driving', incoming_leg_transport_mode = 'walking', accommodation_id = NULL
+ WHERE id = ?`).run('14:00', '14:30', assignmentOnFullPlace.id);
+
+ const placeBare = createPlace(testDb, trip.id, { name: 'Unnamed spot' });
+ testDb.prepare(`
+ UPDATE places SET category_id = NULL, lat = NULL, lng = NULL, address = NULL, price = NULL,
+ currency = NULL, place_time = NULL, end_time = NULL, duration_minutes = NULL, notes = NULL,
+ image_url = NULL, transport_mode = NULL, website = NULL, phone = NULL, description = NULL
+ WHERE id = ?`).run(placeBare.id);
+ const assignmentOnBarePlace = createDayAssignment(testDb, day2.id, placeBare.id, { order_index: 1 });
+
+ // A second assignment on day1, ordered before both of the above by order_index.
+ const placeSecond = createPlace(testDb, trip.id, { name: 'Second stop' });
+ const earlierOrderAssignment = createDayAssignment(testDb, day1.id, placeSecond.id, { order_index: 0 });
+
+ // An assignment on a day NOT in the requested set — must never leak in.
+ const excludedPlace = createPlace(testDb, trip.id, { name: 'Excluded' });
+ createDayAssignment(testDb, excludedDay.id, excludedPlace.id);
+
+ const dayIds = [day1.id, day2.id];
+ const legacy = legacyPublicForShare(dayIds);
+ const typed = await assignments.listPublicForShare(dayIds);
+ expect(typed).toEqual(legacy);
+ expect(typed.map((r) => r.id)).toEqual([earlierOrderAssignment.id, assignmentOnBarePlace.id, assignmentOnFullPlace.id]);
+
+ const fullRow = typed.find((r) => r.id === assignmentOnFullPlace.id)!;
+ expect(fullRow).toMatchObject({ category_name: 'Museum', category_color: '#111111', category_icon: '🏛️', place_time: '14:00', end_time: '14:30' });
+ expect(fullRow).not.toHaveProperty('google_place_id');
+ expect(fullRow).not.toHaveProperty('google_ftid');
+ expect(fullRow).not.toHaveProperty('osm_id');
+ expect(fullRow).not.toHaveProperty('amap_poi_id');
+ expect(fullRow).not.toHaveProperty('stop_type');
+ expect(fullRow).not.toHaveProperty('fill_percent');
+
+ const bareRow = typed.find((r) => r.id === assignmentOnBarePlace.id)!;
+ expect(bareRow).toMatchObject({ category_id: null, category_name: null, category_color: null, category_icon: null, place_time: null, end_time: null });
+ });
+
+ it('[] for an empty day_ids array (no query issued)', async () => {
+ expect(await assignments.listPublicForShare([])).toEqual([]);
+ });
+ });
diff --cc server/tests/unit/db/repositories/Places.repository.test.ts
index 000000000,9aee409c3..893a97271
mode 000000,100644..100644
--- a/server/tests/unit/db/repositories/Places.repository.test.ts
+++ b/server/tests/unit/db/repositories/Places.repository.test.ts
@@@ -1,0 -1,1453 +1,1514 @@@
+ /**
+ * PlacesRepository.findWithTagsAndRatings (Plan 3c Task 0b): the legacy
+ * `getPlaceWithTags`'s three statements (place+category, tags, ratings),
+ * merged the same way. Real rows on the real test DB, including the
+ * non-empty tags/ratings shape neither `trip-access-primitives.test.ts`'s
+ * PRIM-GPWT-00x (empty tags/ratings only) nor any other suite exercises.
+ */
+ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
+ import { TRACK_COLORS } from '@trek/shared';
+ import { createSnapshotTestDb } from '../../../helpers/db-mock';
+ import { resetTestDb } from '../../../helpers/test-db';
+ import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
+ import { addTripMember, createCategory, createDay, createDayAssignment, createPlace, createTag, createTrip, createUser } from '../../../helpers/factories';
++import { createTour } from '../../../helpers/tours-repos';
+ import { Places } from '../../../../src/db/entities/Places.entity';
+ import type { PlacesRepository } from '../../../../src/db/repositories/Places.repository';
+
+ const testDb = createSnapshotTestDb();
+ let t: TestOrm;
+ let places: PlacesRepository;
+
+ beforeAll(async () => {
+ t = await createTestOrm(testDb);
+ places = t.repo(Places);
+ });
+ beforeEach(() => { resetTestDb(testDb); t.clear(); });
+ afterAll(async () => { await t.close(); testDb.close(); });
+
+ /**
+ * The legacy `getPlaceWithTags` (`db/database.ts:146-197` at base), run raw
+ * on the same rows — 0b security review F-B6: a `toMatchObject`/partial
+ * assertion cannot see a renamed key (B1's `u__id`) or a dropped one (B2's
+ * flat `category_name`/`category_color`/`category_icon`); this reproduces
+ * the legacy function's exact three-statement composition and the test below
+ * does a full `toEqual` against it, key for key.
+ */
+ function legacyGetPlaceWithTags(placeId: number): unknown {
+ const place = testDb
+ .prepare('SELECT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon FROM places p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?')
+ .get(placeId) as (Record<string, unknown> & { category_id: number | null; category_name: string | null; category_color: string | null; category_icon: string | null }) | undefined;
+ if (!place) return null;
+ const tags = testDb.prepare('SELECT t.* FROM tags t JOIN place_tags pt ON t.id = pt.tag_id WHERE pt.place_id = ?').all(placeId);
+ const ratings = testDb
+ .prepare('SELECT pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr JOIN users u ON pr.user_id = u.id WHERE pr.place_id = ? ORDER BY pr.created_at')
+ .all(placeId) as { user_id: number; username: string; avatar: string | null; rating: number }[];
+ return {
+ ...place,
+ category: place.category_id
+ ? { id: place.category_id, name: place.category_name, color: place.category_color, icon: place.category_icon }
+ : null,
+ tags,
+ ratings,
+ rating_avg: ratings.length > 0 ? ratings.reduce((s, r) => s + r.rating, 0) / ratings.length : null,
+ rating_count: ratings.length,
+ };
+ }
+
+ describe('PlacesRepository.findWithTagsAndRatings — parity with the legacy getPlaceWithTags', () => {
+ it('PLACEREPO-011 (0b security review F-B6): full key-for-key parity with the legacy statement, on a place with a category, two tags and two ratings', async () => {
+ const { user: owner } = createUser(testDb);
+ const { user: voterA } = createUser(testDb, { username: 'parity_voter_a' });
+ const { user: voterB } = createUser(testDb, { username: 'parity_voter_b' });
+ const trip = createTrip(testDb, owner.id);
+ const category = createCategory(testDb, { name: 'Parks', color: '#00aa00', icon: '🌳' });
+ const place = createPlace(testDb, trip.id, { category_id: category.id, name: 'Parity Park' });
+ const tagA = createTag(testDb, owner.id, { name: 'Green' });
+ const tagB = createTag(testDb, owner.id, { name: 'Quiet' });
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(place.id, tagA.id);
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(place.id, tagB.id);
+ testDb.prepare("INSERT INTO place_ratings (place_id, user_id, rating, created_at) VALUES (?, ?, ?, datetime('now', '-2 minutes'))").run(place.id, voterA.id, 5);
+ testDb.prepare("INSERT INTO place_ratings (place_id, user_id, rating, created_at) VALUES (?, ?, ?, datetime('now', '-1 minutes'))").run(place.id, voterB.id, 3);
+
+ const result = await places.findWithTagsAndRatings(place.id);
+ const legacy = legacyGetPlaceWithTags(place.id) as Record<string, unknown>;
+
+ // Sort both sides' tags/ratings arrays the same way before the full
+ // toEqual — the repository's join order and the legacy statement's join
+ // order are not contractually identical for the tags half (no ORDER BY
+ // in either), only the ratings half is `ORDER BY pr.created_at` on both.
+ const sortByField = <T extends Record<string, unknown>>(arr: T[], field: string): T[] =>
+ [...arr].sort((a, b) => String(a[field]).localeCompare(String(b[field])));
+ const normalize = (row: Record<string, unknown>): Record<string, unknown> => ({
+ ...row,
+ tags: sortByField(row.tags as Record<string, unknown>[], 'id'),
+ });
+
+ expect(normalize(result as unknown as Record<string, unknown>)).toEqual(normalize(legacy));
+ });
+ });
+
+ describe('PlacesRepository.findWithTagsAndRatings — parity with the legacy getPlaceWithTags (per-case)', () => {
+ it('PLACEREPO-001: no category, no tags, no ratings — null category, empty arrays, null average', async () => {
+ const { user: owner } = createUser(testDb);
+ const trip = createTrip(testDb, owner.id);
+ // category_id: null override defeats createPlace's default-first-category fallback.
+ testDb.prepare('DELETE FROM categories').run();
+ const place = createPlace(testDb, trip.id, { name: 'Uncategorized Spot' });
+
+ const result = await places.findWithTagsAndRatings(place.id);
+ expect(result).toMatchObject({
+ id: place.id,
+ name: 'Uncategorized Spot',
+ category: null,
+ tags: [],
+ ratings: [],
+ rating_avg: null,
+ rating_count: 0,
+ });
+ });
+
+ it('PLACEREPO-002: a category joins in by name/color/icon, not just its id', async () => {
+ const { user: owner } = createUser(testDb);
+ const trip = createTrip(testDb, owner.id);
+ const category = createCategory(testDb, { name: 'Museums', color: '#123456', icon: '🏛️' });
+ const place = createPlace(testDb, trip.id, { category_id: category.id });
+
+ const result = await places.findWithTagsAndRatings(place.id);
+ expect(result?.category).toEqual({ id: category.id, name: 'Museums', color: '#123456', icon: '🏛️' });
+ });
+
+ it('PLACEREPO-003: tags attach through place_tags, each one the full tags row', async () => {
+ const { user: owner } = createUser(testDb);
+ const trip = createTrip(testDb, owner.id);
+ const place = createPlace(testDb, trip.id);
+ const tagA = createTag(testDb, owner.id, { name: 'Must see' });
+ const tagB = createTag(testDb, owner.id, { name: 'Rainy day' });
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(place.id, tagA.id);
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(place.id, tagB.id);
+
+ const result = await places.findWithTagsAndRatings(place.id);
+ expect(result?.tags).toHaveLength(2);
+ expect(result?.tags.map((tg) => tg.name).sort()).toEqual(['Must see', 'Rainy day']);
+ });
+
+ it('PLACEREPO-004: ratings hydrate with the voter\'s username/avatar, in created_at order, and average correctly', async () => {
+ const { user: owner } = createUser(testDb);
+ const { user: voterA } = createUser(testDb, { username: 'voter_a' });
+ const { user: voterB } = createUser(testDb, { username: 'voter_b' });
+ const trip = createTrip(testDb, owner.id);
+ const place = createPlace(testDb, trip.id);
+ testDb
+ .prepare("INSERT INTO place_ratings (place_id, user_id, rating, created_at) VALUES (?, ?, ?, datetime('now', '-2 minutes'))")
+ .run(place.id, voterA.id, 4);
+ // Task 0b review M1: 4-and-2 averages to 3, which `Math.round(3)` also
+ // equals — the brief's own named mutation (wrapping the average in
+ // `Math.round(...)`) survived undetected. 4-and-3 averages to 3.5,
+ // which `Math.round` would corrupt to 3 or 4 — mutation-proved.
+ testDb
+ .prepare("INSERT INTO place_ratings (place_id, user_id, rating, created_at) VALUES (?, ?, ?, datetime('now', '-1 minutes'))")
+ .run(place.id, voterB.id, 3);
+
+ const result = await places.findWithTagsAndRatings(place.id);
+ expect(result?.ratings).toHaveLength(2);
+ expect(result?.ratings.map((r) => r.username)).toEqual(['voter_a', 'voter_b']);
+ expect(result?.rating_avg).toBe(3.5);
+ expect(result?.rating_count).toBe(2);
+ });
+
+ // Task 0b review B1 (HIGH, live regression): `ratings[].user_id` was
+ // emitted as `u__id` at runtime (a `join('pr.user','u')` + `.select(['pr.user',
+ // …])` interaction — TypeScript's declared `PlaceRatingRow.user_id` never
+ // existed on the actual row). The client's `StarRating.tsx` keys off
+ // `ratings.find(r => r.user_id === currentUserId)`, so this is the direct
+ // regression proof neither PLACEREPO-004 (keys off `username`) nor any
+ // other suite caught.
+ it('PLACEREPO-007 (0b review B1): a rating row carries a real user_id key, not u__id', async () => {
+ const { user: owner } = createUser(testDb);
+ const { user: voter } = createUser(testDb, { username: 'keyed_voter' });
+ const trip = createTrip(testDb, owner.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('INSERT INTO place_ratings (place_id, user_id, rating) VALUES (?, ?, ?)').run(place.id, voter.id, 5);
+
+ const result = await places.findWithTagsAndRatings(place.id);
+ expect(result?.ratings[0]).toEqual({ user_id: voter.id, username: 'keyed_voter', avatar: null, rating: 5 });
+ expect(result?.ratings[0]).not.toHaveProperty('u__id');
+ });
+
+ // Task 0b review B2 (HIGH, live regression): `category_name`/
+ // `category_color`/`category_icon` rode along on the legacy
+ // `getPlaceWithTags`'s runtime object (`{...place, category: ...}` over
+ // the raw `SELECT p.*, c.name as category_name, …` row) even though the
+ // declared `PlaceWithTags` interface never mentioned them — several live
+ // client call sites read them flat (map popups, dashboard, shared-trip
+ // page), so a repository that strips them via `const { category_name,
+ // ..., ...placeRest } = place` silently breaks those, even though every
+ // OTHER assertion in this file (which reads through `result?.category`)
+ // stays green.
+ it('PLACEREPO-008 (0b review B2): the flat category_name/category_color/category_icon columns ride along on the row, alongside the nested category object', async () => {
+ const { user: owner } = createUser(testDb);
+ const trip = createTrip(testDb, owner.id);
+ const category = createCategory(testDb, { name: 'Cafes', color: '#654321', icon: '☕' });
+ const place = createPlace(testDb, trip.id, { category_id: category.id });
+
+ const result = await places.findWithTagsAndRatings(place.id) as unknown as Record<string, unknown>;
+ expect(result.category_name).toBe('Cafes');
+ expect(result.category_color).toBe('#654321');
+ expect(result.category_icon).toBe('☕');
+ expect(result.category).toEqual({ id: category.id, name: 'Cafes', color: '#654321', icon: '☕' });
+ });
+
+ it('PLACEREPO-009: a missing place id resolves to null, not a throw', async () => {
+ expect(await places.findWithTagsAndRatings(999999)).toBeNull();
+ });
+
+ it('PLACEREPO-010: a non-numeric-looking id resolves to null, the same raw-bind seam TripsRepository documents', async () => {
+ expect(await places.findWithTagsAndRatings('abc')).toBeNull();
+ });
+ });
+
+ // Plan 3c Task 1, PP6 ruling (option 2): the `places`-owned half of
+ // `PlacePhotoCacheService.isReferenced`'s legacy `UNION ALL … LIMIT 1`.
+ describe('PlacesRepository.existsByGoogleIdOrImageUrl', () => {
+ it('EXISTSGOOGLEORIMAGE-001: true when a place carries the google_place_id', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET google_place_id = ? WHERE id = ?').run('ChIJ-gpid', place.id);
+ expect(await places.existsByGoogleIdOrImageUrl('ChIJ-gpid', '/api/maps/place-photo/ChIJ-gpid/bytes')).toBe(true);
+ });
+
+ it('EXISTSGOOGLEORIMAGE-002: true when a place carries the proxy image_url instead (coords: pseudo-ids never have a google_place_id)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ const proxyUrl = '/api/maps/place-photo/coords%3A1%3A2/bytes';
+ testDb.prepare('UPDATE places SET image_url = ? WHERE id = ?').run(proxyUrl, place.id);
+ expect(await places.existsByGoogleIdOrImageUrl('coords:1:2', proxyUrl)).toBe(true);
+ });
+
+ it('EXISTSGOOGLEORIMAGE-003: false when nothing references either value', async () => {
+ expect(await places.existsByGoogleIdOrImageUrl('never-seen', '/api/maps/place-photo/never-seen/bytes')).toBe(false);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 4 — the new PlacesRepository methods.
+ // ---------------------------------------------------------------------------
+
+ describe('PlacesRepository.existsInTrip / findInTrip / reclaimInputs / deleteById (PL0/PL7/PL9/PL17/PL19/PL48/PL49/AS5)', () => {
+ it('PLACEREPO-012: existsInTrip is true only for the matching id+trip pair', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const otherTrip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ expect(await places.existsInTrip(place.id, trip.id)).toBe(true);
+ expect(await places.existsInTrip(place.id, otherTrip.id)).toBe(false);
+ expect(await places.existsInTrip(999999, trip.id)).toBe(false);
+ });
+
+ // Task 9 fix wave (B-M3): relabelled. `findInTrip` is a
+ // `qb().execute('get', false)` projection, which never hydrates an entity
+ // into the identity map by construction, and the base default leaves the
+ // identity map disabled for every read anyway — there is no live
+ // identity-map entry here to bypass. This proves a DB round-trip, not an
+ // identity-map bypass.
+ it('PLACEREPO-013 (fresh after a raw UPDATE, not D-shape): a name write after an unrelated identity-map read is visible in findInTrip\'s FIRST wider read', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Before' });
+ // Populate the identity map with an unrelated, WIDER read first — `{ disableIdentityMap: false }`
+ // explicitly (program rule 20: the base default leaves the identity map empty, making this vacuous).
+ await t.repo(Places).find({ trip: trip.id }, { disableIdentityMap: false });
+ testDb.prepare('UPDATE places SET name = ? WHERE id = ?').run('After', place.id);
+ const row = await places.findInTrip(place.id, trip.id);
+ expect(row?.name).toBe('After');
+ });
+
+ // Task 9 fix wave (B-M4, rule 19): widened from `toMatchObject` on 3 keys
+ // (a title claiming "every scalar column" that only checked 3 of 28) to
+ // `toEqual(legacy SELECT p.* ... WHERE p.id = ? AND p.trip_id = ? run raw)`
+ // on the full key set, plus a fully NULL-nullable-column row, so a
+ // renamed or dropped column would fail this test.
+ it('PLACEREPO-014: findInTrip returns every scalar column (PL9/PL48\'s SELECT *), full toEqual(legacy) parity, undefined cross-trip', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const otherTrip = createTrip(testDb, user.id);
+ const category = createCategory(testDb);
+ const place = createPlace(testDb, trip.id, { name: 'Full Row' });
+ testDb.prepare(`
+ UPDATE places SET description = ?, lat = ?, lng = ?, address = ?, category_id = ?, price = ?, currency = ?,
+ reservation_status = ?, reservation_notes = ?, reservation_datetime = ?, place_time = ?, end_time = ?,
+ duration_minutes = ?, notes = ?, image_url = ?, google_place_id = ?, google_ftid = ?, website = ?, phone = ?,
+ transport_mode = ?, osm_id = ?, route_geometry = ?, route_color = ?, stop_type = ?, fill_percent = ?,
+ amap_poi_id = ?, source = ?
+ WHERE id = ?
+ `).run(
+ 'A description with 007-style digits', 48.1, 2.2, '007 Rue de Paris', category.id, 12.5, 'EUR',
+ 'confirmed', 'notes-a', '2026-01-01T10:00:00Z', '10:00', '11:00',
+ 45, 'place notes', '/img/a.png', 'gpid-007', 'gftid-a', 'https://a.example', '+33 1 23 45 67 89',
+ 'driving', 'osm-a', '{"type":"LineString"}', '#ff0000', 'hotel', 50,
+ 'amap-a', 'manual',
+ place.id,
+ );
+
+ const row = await places.findInTrip(place.id, trip.id);
+ const legacy = testDb.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(place.id, trip.id);
+ expect(row).toEqual(legacy);
+ expect(row).toMatchObject({ id: place.id, trip_id: trip.id, name: 'Full Row', google_place_id: 'gpid-007' });
+ expect(await places.findInTrip(place.id, otherTrip.id)).toBeUndefined();
+ });
+
+ it('PLACEREPO-052: findInTrip on a bare row — every nullable column comes back null (rule 16), matching legacy', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Bare Place' });
+ const row = await places.findInTrip(place.id, trip.id);
+ const legacy = testDb.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(place.id, trip.id);
+ expect(row).toEqual(legacy);
+ expect(row?.description).toBeNull();
+ expect(row?.google_ftid).toBeNull();
+ });
+
+ it('PLACEREPO-015: reclaimInputs projects only google_place_id/image_url', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET google_place_id = ?, image_url = ? WHERE id = ?').run('gpid-1', '/uploads/places/x.jpg', place.id);
+ expect(await places.reclaimInputs(place.id, trip.id)).toEqual({ google_place_id: 'gpid-1', image_url: '/uploads/places/x.jpg' });
+ expect(await places.reclaimInputs(999999, trip.id)).toBeUndefined();
+ });
+
+ it('PLACEREPO-016: deleteById removes exactly that row', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const keep = createPlace(testDb, trip.id, { name: 'Keep' });
+ const gone = createPlace(testDb, trip.id, { name: 'Gone' });
+ await places.deleteById(gone.id);
+ expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(gone.id)).toBeUndefined();
+ expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(keep.id)).toBeDefined();
+ });
+ });
+
+ describe('PlacesRepository.scopedIds (PL23) — input-order preservation', () => {
+ it('PLACEREPO-017: returns only the trip\'s own ids, in the CALLER\'s input order, not row/id order', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ const p1 = createPlace(testDb, trip.id);
+ const p2 = createPlace(testDb, trip.id);
+ const p3 = createPlace(testDb, trip.id);
+ const foreign = createPlace(testDb, other.id);
+ // Deliberately out of id order and interleaved with a foreign + missing id.
+ const result = await places.scopedIds(trip.id, [p3.id, 999999, p1.id, foreign.id, p2.id]);
+ expect(result).toEqual([p3.id, p1.id, p2.id]);
+ });
+
+ it('PLACEREPO-018: empty input short-circuits to []', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ expect(await places.scopedIds(trip.id, [])).toEqual([]);
+ });
+ });
+
+ describe('PlacesRepository.insertPlace (PL4) / updatePlace (PL11)', () => {
+ it('PLACEREPO-019: insertPlace writes every one of the 27 columns and returns the generated id', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const id = await places.insertPlace({
+ trip_id: trip.id, name: 'Full Insert', description: 'd', lat: 0, lng: 0, address: 'a',
+ category_id: null, price: 0, currency: 'USD', place_time: '09:00', end_time: '10:00',
+ duration_minutes: 60, notes: 'n', image_url: '/uploads/places/x.jpg', google_place_id: 'g',
+ google_ftid: 'f', osm_id: 'o', amap_poi_id: 'am', website: 'w', phone: 'p', email: '[email protected]', opening_hours: 'Mo-Fr 09:00-17:00',
+ transport_mode: 'walking', route_geometry: '[[1,2]]', route_color: '#fff', stop_type: 'fuel',
+ fill_percent: 50,
+ });
+ const row = await places.findInTrip(id, trip.id);
+ expect(row).toMatchObject({
+ trip_id: trip.id, name: 'Full Insert', description: 'd', lat: 0, lng: 0, address: 'a',
+ category_id: null, price: 0, currency: 'USD', place_time: '09:00', end_time: '10:00',
+ duration_minutes: 60, notes: 'n', image_url: '/uploads/places/x.jpg', google_place_id: 'g',
+ google_ftid: 'f', osm_id: 'o', amap_poi_id: 'am', website: 'w', phone: 'p', email: '[email protected]', opening_hours: 'Mo-Fr 09:00-17:00',
+ transport_mode: 'walking', route_geometry: '[[1,2]]', route_color: '#fff', stop_type: 'fuel',
+ fill_percent: 50,
+ });
+ });
+
+ it('PLACEREPO-020 (PL11 matrix): a written null vs a written value are byte-distinct on the same column', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Original' });
+ const base = {
+ name: 'Original', description: null, lat: null, lng: null, address: null, category_id: null,
+ price: null, currency: null, place_time: null, end_time: null, duration_minutes: null,
+ notes: null, image_url: null, google_place_id: null, google_ftid: null, osm_id: null,
+ amap_poi_id: null, website: null, phone: null, email: null, opening_hours: null, transport_mode: null, route_color: null,
+ stop_type: null, fill_percent: null,
+ };
+ // A non-COALESCE column (description) written explicitly null clears it.
+ await places.updatePlace(place.id, { ...base, description: 'first' });
+ expect((await places.findInTrip(place.id, trip.id))?.description).toBe('first');
+ await places.updatePlace(place.id, { ...base, description: null });
+ expect((await places.findInTrip(place.id, trip.id))?.description).toBeNull();
+ // duration_minutes: 0 is a real value, distinct from null (the service's
+ // `!== undefined` fallback — this repository test proves the write itself
+ // stores 0 and null distinctly, not that either collapses to the other).
+ await places.updatePlace(place.id, { ...base, duration_minutes: 0 });
+ expect((await places.findInTrip(place.id, trip.id))?.duration_minutes).toBe(0);
+ await places.updatePlace(place.id, { ...base, duration_minutes: null });
+ expect((await places.findInTrip(place.id, trip.id))?.duration_minutes).toBeNull();
+ });
+
+ it('PLACEREPO-021: updatePlace stamps updated_at with the current time', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Stampable' });
+ // Force a stale, second-resolution-distinguishable `updated_at` — this
+ // write and the assertion below both happen within the same real
+ // second, so comparing against `createPlace`'s own `CURRENT_TIMESTAMP`
+ // default would be flaky (Object.is on two identical second-granularity
+ // strings), not a proof of anything.
+ testDb.prepare("UPDATE places SET updated_at = datetime('now', '-1 hour') WHERE id = ?").run(place.id);
+ const before = (await places.findInTrip(place.id, trip.id))?.updated_at;
+ await places.updatePlace(place.id, {
+ name: 'Stamped', description: null, lat: null, lng: null, address: null, category_id: null,
+ price: null, currency: null, place_time: null, end_time: null, duration_minutes: null,
+ notes: null, image_url: null, google_place_id: null, google_ftid: null, osm_id: null,
+ amap_poi_id: null, website: null, phone: null, email: null, opening_hours: null, transport_mode: null, route_color: null,
+ stop_type: null, fill_percent: null,
+ });
+ const after = await places.findInTrip(place.id, trip.id);
+ expect(after?.name).toBe('Stamped');
+ expect(after?.updated_at).not.toBe(before);
+ });
+ });
+
+ describe('PlacesRepository.findDuplicateByExternalId / findDuplicateByName / findDuplicateByCoords (PL25/PL26/PL27)', () => {
+ it('PLACEREPO-022 (PL25): matches on any of the four provider-id columns, lowest id wins', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const first = createPlace(testDb, trip.id, { name: 'First' });
+ testDb.prepare('UPDATE places SET osm_id = ? WHERE id = ?').run('node:123', first.id);
+ const second = createPlace(testDb, trip.id, { name: 'Second' });
+ testDb.prepare('UPDATE places SET google_ftid = ? WHERE id = ?').run('node:123', second.id);
+ const hit = await places.findDuplicateByExternalId(String(trip.id), 'node:123');
+ expect(hit?.id).toBe(first.id);
+ });
+
+ // Task 4 review L2: only osm_id/google_ftid were exercised — a mutation
+ // dropping `amap_poi_id` from the `$or` survived every suite until this.
+ it('PLACEREPO-022b (PL25, L2): matches on amap_poi_id alone (no osm_id/google_ftid/google_place_id set)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Amap-only' });
+ testDb.prepare('UPDATE places SET amap_poi_id = ? WHERE id = ?').run('B0FFH00X01', place.id);
+ const hit = await places.findDuplicateByExternalId(String(trip.id), 'B0FFH00X01');
+ expect(hit?.id).toBe(place.id);
+ });
+
+ it('PLACEREPO-023 (PL26, rule 18 exception): lower(trim(name)) matches ASCII-folded names; a non-ASCII cased letter does NOT match — the documented legacy divergence, pinned not fixed', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: ' Café Central ' });
+ // The service's own JS-lowered+trimmed value, matching `normalizePlaceName`'s
+ // Unicode-aware fold — this side is honest, so it would match the row exactly.
+ const jsLowered = ' café central '.trim().toLowerCase();
+ // SQLite's lower()/trim() is ASCII-only: it lowercases "C" but never touches
+ // "É"/"é" — `Café Central` (stored) trims+lowers via SQL to `café central`.
+ const hit = await places.findDuplicateByName(String(trip.id), jsLowered);
+ expect(hit?.id).toBe(place.id);
+ // A row stored with an upper-case accented letter (`CAFÉ`) does NOT match a
+ // JS-lowered candidate (`café`) — SQLite's LOWER() never folds `É` to `é`,
+ // reproducing the documented disagreement (places.service.ts's own PL26 docstring).
+ const accented = createPlace(testDb, trip.id, { name: 'CAFÉ NORD' });
+ const jsLoweredAccented = 'café nord'.toLowerCase();
+ const miss = await places.findDuplicateByName(String(trip.id), jsLoweredAccented);
+ expect(miss?.id).not.toBe(accented.id);
+ });
+
+ it('PLACEREPO-024 (PL27): matches within the coordinate tolerance box, on both lat and lng', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { lat: 48.8566, lng: 2.3522 });
+ const hit = await places.findDuplicateByCoords(String(trip.id), 48.8566 + 0.00005, 2.3522 - 0.00005, 0.0001);
+ expect(hit?.id).toBe(place.id);
+ const miss = await places.findDuplicateByCoords(String(trip.id), 48.9, 2.5, 0.0001);
+ expect(miss).toBeUndefined();
+ });
+
+ // Task 4 review L2: PLACEREPO-024's miss case differed on both lat AND
+ // lng, so `lng` alone was never proven — a mutation widening the lng
+ // tolerance (or dropping the lng check entirely) survived every suite
+ // until this.
+ it('PLACEREPO-024b (PL27, L2): a candidate within lat tolerance but OUTSIDE lng tolerance is a miss', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ createPlace(testDb, trip.id, { lat: 48.8566, lng: 2.3522 });
+ // lat matches exactly; lng is 0.01 off — 100x the tolerance below.
+ const miss = await places.findDuplicateByCoords(String(trip.id), 48.8566, 2.3622, 0.0001);
+ expect(miss).toBeUndefined();
+ });
+ });
+
+ describe('PlacesRepository.listForGpx (PL29) and existsByImageUrl (PI1)', () => {
+ it('PLACEREPO-025: projects the waypoint columns plus the flat category name, ordered by id', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const category = createCategory(testDb, { name: 'Trails' });
+ const p1 = createPlace(testDb, trip.id, { name: 'A', category_id: category.id });
+ // `createPlace` always falls back to the first available category when
+ // no override is given (its own `?? defaultCat?.id ?? null` chain — an
+ // explicit `category_id: null` override is ALSO nullish, so it falls
+ // through the same way), and deleting the categories table would also
+ // break p1's own join. Insert place B directly instead, to genuinely
+ // pin `category_id = NULL` while `category` (p1's) still exists.
+ const p2Id = testDb.prepare('INSERT INTO places (trip_id, name, category_id) VALUES (?, ?, NULL)').run(trip.id, 'B').lastInsertRowid;
+ const p2 = { id: p2Id as number };
+ const rows = await places.listForGpx(String(trip.id));
+ expect(rows.map((r) => r.name)).toEqual(['A', 'B']);
+ expect(rows[0]).toMatchObject({ name: 'A', category: 'Trails' });
+ expect(rows[1]).toMatchObject({ name: 'B', category: null });
+ void p1; void p2;
+ });
+
+ it('PLACEREPO-026 (PI1): existsByImageUrl is trip-agnostic — true for any place carrying the url', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET image_url = ? WHERE id = ?').run('/uploads/places/shared.jpg', place.id);
+ expect(await places.existsByImageUrl('/uploads/places/shared.jpg')).toBe(true);
+ expect(await places.existsByImageUrl('/uploads/places/nope.jpg')).toBe(false);
+ });
+ });
+
+ /**
+ * PL24 (Task 5 review L6 ruling): `listDedupInputs` carries only the
+ * legacy projection — `PlacesService.buildDedupSet`'s JS folding (name
+ * lowercase+trim, coordinates only for unnamed rows, provider ids for every
+ * row) is untested here on purpose; it belongs to, and is already covered
+ * by, the service-level dedup tests.
+ */
+ describe('PlacesRepository.listDedupInputs (PL24)', () => {
+ it('PLACEREPO-048: projects exactly the seven dedup columns, scoped to the trip', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ testDb.prepare(
+ `INSERT INTO places (trip_id, name, lat, lng, google_place_id, google_ftid, osm_id, amap_poi_id)
+ VALUES (?, 'Louvre', 48.86, 2.34, 'gp1', 'ft1', 'osm1', 'amap1')`,
+ ).run(trip.id);
+ testDb.prepare(
+ `INSERT INTO places (trip_id, name, lat, lng) VALUES (?, '', 1.1, 2.2)`,
+ ).run(trip.id);
+ createPlace(testDb, other.id, { name: 'Not this trip' });
+
+ const rows = await places.listDedupInputs(String(trip.id));
+ expect(rows).toEqual([
+ { name: 'Louvre', lat: 48.86, lng: 2.34, google_place_id: 'gp1', google_ftid: 'ft1', osm_id: 'osm1', amap_poi_id: 'amap1' },
+ { name: '', lat: 1.1, lng: 2.2, google_place_id: null, google_ftid: null, osm_id: null, amap_poi_id: null },
+ ]);
+ });
+
+ it('PLACEREPO-049: an empty trip returns an empty array', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ expect(await places.listDedupInputs(String(trip.id))).toEqual([]);
+ });
+ });
+
+ describe('PlacesRepository.listForTrip (PL3) — filter fragments', () => {
+ it('PLACEREPO-027: no filters — every trip place, DISTINCT, newest first', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const older = createPlace(testDb, trip.id, { name: 'Older' });
+ testDb.prepare("UPDATE places SET created_at = datetime('now', '-1 hour') WHERE id = ?").run(older.id);
+ const newer = createPlace(testDb, trip.id, { name: 'Newer' });
+ const rows = await places.listForTrip(String(trip.id), {});
+ expect(rows.map((r) => r.id)).toEqual([newer.id, older.id]);
+ });
+
+ it('PLACEREPO-028: searchPattern matches name/address/description (already-escaped, wrapped by the caller — NOT a test of the ESCAPE clause itself: `%Eiffel%` has no literal `%`/`_` to escape. `ESCAPE \'\\\'` is proven by `PLACE-SVC-068`/PLACEREPO-028b below, which do carry a literal wildcard character)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const hit = createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
+ const miss = createPlace(testDb, trip.id, { name: 'Louvre' });
+ const rows = await places.listForTrip(String(trip.id), { searchPattern: '%Eiffel%' });
+ expect(rows.map((r) => r.id)).toEqual([hit.id]);
+ void miss;
+ });
+
+ it('PLACEREPO-028b (M2 — the ESCAPE clause this repository method actually relies on): a literal `%` in the already-escaped pattern matches literally, not as a wildcard', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ // escapeLikePattern (the service) would have produced this pattern for a
+ // literal search term "50%": the `%` the user typed is backslash-escaped,
+ // and the wrapping `%…%` are the real wildcards this method adds.
+ const hit = createPlace(testDb, trip.id, { name: '50% off tour' });
+ const miss = createPlace(testDb, trip.id, { name: '50X off tour' });
+ const rows = await places.listForTrip(String(trip.id), { searchPattern: '%50\\%%' });
+ expect(rows.map((r) => r.id)).toEqual([hit.id]);
+ void miss;
+ });
+
+ it('PLACEREPO-029: category filters to that category_id only', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const cat = createCategory(testDb, { name: 'Museums' });
+ const inCat = createPlace(testDb, trip.id, { category_id: cat.id });
+ const outCat = createPlace(testDb, trip.id);
+ testDb.prepare('DELETE FROM categories WHERE id != ?').run(cat.id);
+ const rows = await places.listForTrip(String(trip.id), { category: String(cat.id) });
+ expect(rows.map((r) => r.id)).toEqual([inCat.id]);
+ void outCat;
+ });
+
+ it('PLACEREPO-030: tag filters via the place_tags subquery', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const tag = createTag(testDb, user.id, { name: 'Must see' });
+ const tagged = createPlace(testDb, trip.id, { name: 'Tagged' });
+ const untagged = createPlace(testDb, trip.id, { name: 'Untagged' });
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(tagged.id, tag.id);
+ const rows = await places.listForTrip(String(trip.id), { tag: String(tag.id) });
+ expect(rows.map((r) => r.id)).toEqual([tagged.id]);
+ void untagged;
+ });
+
+ it('PLACEREPO-031: assignment=unassigned / assigned split the trip\'s places by day_assignments membership', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const assigned = createPlace(testDb, trip.id, { name: 'On a day' });
+ const unassigned = createPlace(testDb, trip.id, { name: 'In the pool' });
+ createDayAssignment(testDb, day.id, assigned.id);
+ const assignedRows = await places.listForTrip(String(trip.id), { assignment: 'assigned' });
+ expect(assignedRows.map((r) => r.id)).toEqual([assigned.id]);
+ const unassignedRows = await places.listForTrip(String(trip.id), { assignment: 'unassigned' });
+ expect(unassignedRows.map((r) => r.id)).toEqual([unassigned.id]);
+ });
+
+ it('PLACEREPO-032: search + category + tag + assignment combine with AND, all four fragments at once', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const cat = createCategory(testDb, { name: 'Parks' });
+ const tag = createTag(testDb, user.id, { name: 'Green' });
+ const day = createDay(testDb, trip.id);
+ const winner = createPlace(testDb, trip.id, { name: 'Central Park', category_id: cat.id });
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(winner.id, tag.id);
+ createDayAssignment(testDb, day.id, winner.id);
+ // A near-miss on every axis, to prove the AND actually excludes it.
+ const other = createPlace(testDb, trip.id, { name: 'Central Park Annex', category_id: cat.id });
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(other.id, tag.id);
+ // `other` is left unassigned, so `assignment: 'assigned'` alone should exclude it.
+ const rows = await places.listForTrip(String(trip.id), {
+ searchPattern: '%Central Park%', category: String(cat.id), tag: String(tag.id), assignment: 'assigned',
+ });
+ expect(rows.map((r) => r.id)).toEqual([winner.id]);
+ });
+ });
+
+ /**
+ * PL3 parity (Task 4 review M2/rule 19): the base `94c6efbbc` raw statement
+ * (`places.service.ts:180-217` at that commit — reproduced verbatim below,
+ * the same `let query += …` composition, the same param order), run over
+ * every `search × category × tag × assignment` combination
+ * (2 × 2 × 2 × 4 = 32, undefined/present for the first three, {undefined,
+ * 'all', 'assigned', 'unassigned'} for the fourth). Each cell asserts
+ * `toEqual` on the FULL row set from both statements, not just the id list —
+ * a dropped/renamed column would pass an id-only comparison silently.
+ */
+ describe('PlacesRepository.listForTrip (PL3) — toEqual(legacy) over all 32 filter combinations', () => {
+ function legacyListForTrip(
+ tripId: string,
+ filters: { searchPattern?: string; category?: string; tag?: string; assignment?: 'all' | 'unassigned' | 'assigned' },
+ ): unknown[] {
+ let query = `
- SELECT DISTINCT p.*, c.name as category_name, c.color as category_color, c.icon as category_icon,
++ SELECT DISTINCT p.*, t.place_id AS tour_place_id, c.name as category_name, c.color as category_color, c.icon as category_icon,
+ pr.country_code as country_code, pr.region_name as region_name
+ FROM places p
++ LEFT JOIN tours t ON t.place_id = p.id
+ LEFT JOIN categories c ON p.category_id = c.id
+ LEFT JOIN place_regions pr ON pr.place_id = p.id
+ WHERE p.trip_id = ?
+ `;
+ const params: (string | number)[] = [tripId];
+
+ if (filters.searchPattern) {
+ query += " AND (p.name LIKE ? ESCAPE '\\' OR p.address LIKE ? ESCAPE '\\' OR p.description LIKE ? ESCAPE '\\')";
+ params.push(filters.searchPattern, filters.searchPattern, filters.searchPattern);
+ }
+ if (filters.category) {
+ query += ' AND p.category_id = ?';
+ params.push(filters.category);
+ }
+ if (filters.tag) {
+ query += ' AND p.id IN (SELECT place_id FROM place_tags WHERE tag_id = ?)';
+ params.push(filters.tag);
+ }
+ if (filters.assignment === 'unassigned') {
+ query += ' AND p.id NOT IN (SELECT da.place_id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE d.trip_id = ?)';
+ params.push(tripId);
+ } else if (filters.assignment === 'assigned') {
+ query += ' AND p.id IN (SELECT da.place_id FROM day_assignments da JOIN days d ON da.day_id = d.id WHERE d.trip_id = ?)';
+ params.push(tripId);
+ }
+ query += ' ORDER BY p.created_at DESC';
+ return testDb.prepare(query).all(...params);
+ }
+
+ it('PLACEREPO-032b (PL3, M2): every row, every column, on all 32 combinations, byte-identical to the legacy raw statement', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const otherTrip = createTrip(testDb, user.id);
+ const cat = createCategory(testDb, { name: 'Museums' });
+ const tag = createTag(testDb, user.id, { name: 'Must see' });
+ const day = createDay(testDb, trip.id);
+
+ // p1: category + tag + assigned + matches the search term.
+ const p1 = createPlace(testDb, trip.id, { name: 'Central Park', category_id: cat.id });
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(p1.id, tag.id);
+ createDayAssignment(testDb, day.id, p1.id);
+ // p2: category, no tag, unassigned, matches the search term (a near-miss on 3 of 4 axes).
+ createPlace(testDb, trip.id, { name: 'Central Station', category_id: cat.id });
+ // p3: no category, tag + assigned, does NOT match the search term.
+ const p3 = createPlace(testDb, trip.id, { name: 'Louvre' });
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(p3.id, tag.id);
+ createDayAssignment(testDb, day.id, p3.id);
- // p4: no category, no tag, unassigned, does NOT match the search term.
- createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
++ // p4: no category, no tag, unassigned, does NOT match the search term,
++ // and a Tour, so tour_place_id is non-null on exactly one row.
++ const p4 = createPlace(testDb, trip.id, { name: 'Eiffel Tower' });
++ createTour(testDb, p4.id);
+ // Another trip's place, named to collide with the search term — must
+ // never appear in either statement's output (both scope by trip_id).
+ createPlace(testDb, otherTrip.id, { name: 'Central Perk' });
+
+ const searchOptions: (string | undefined)[] = [undefined, '%Central%'];
+ const categoryOptions: (string | undefined)[] = [undefined, String(cat.id)];
+ const tagOptions: (string | undefined)[] = [undefined, String(tag.id)];
+ const assignmentOptions: (('all' | 'unassigned' | 'assigned') | undefined)[] = [undefined, 'all', 'assigned', 'unassigned'];
+
+ let combinations = 0;
+ for (const searchPattern of searchOptions) {
+ for (const category of categoryOptions) {
+ for (const tag_ of tagOptions) {
+ for (const assignment of assignmentOptions) {
+ combinations++;
+ const filters = { searchPattern, category, tag: tag_, assignment };
+ const actual = await places.listForTrip(String(trip.id), filters);
+ const legacy = legacyListForTrip(String(trip.id), filters);
+ expect(actual).toEqual(legacy);
+ }
+ }
+ }
+ }
+ expect(combinations).toBe(32);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Plan 3c Task 5 — the four importers' `insertPlace` column sets, the
+ // colorize read+write transaction, the ftid backfill, and the
+ // enrichment/backfill `fillIfEmpty` matrix.
+ // ---------------------------------------------------------------------------
+
+ describe('PlacesRepository.insertPlace — the four importers\' narrower column sets (PL31/34/38/41), read back inside the same transaction (PL32/35/40/42)', () => {
+ const base = {
+ address: null, category_id: null, price: null, currency: null,
+ place_time: null, end_time: null, duration_minutes: 60, notes: null, image_url: null,
+ google_place_id: null, google_ftid: null, osm_id: null, amap_poi_id: null, website: null,
+ phone: null, email: null, opening_hours: null, transport_mode: 'walking', route_geometry: null, route_color: null,
+ stop_type: null, fill_percent: null,
+ };
+
+ it('PLACEREPO-033 (PL31/PL32, GPX): the 7-column GPX shape is stored, and the read inside the same transaction sees the uncommitted row', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+
+ const row = await t.em.transactional(async () => {
+ const id = await places.insertPlace({
+ ...base,
+ trip_id: trip.id, name: 'GPX Waypoint', description: 'from a gpx file',
+ lat: 48.85, lng: 2.35, route_geometry: '[[48.85,2.35],[48.86,2.36]]',
+ });
+ // Same transaction, no commit yet — this read must still see it.
+ return places.findWithTagsAndRatings(id);
+ });
+
+ expect(row).toMatchObject({
+ trip_id: trip.id, name: 'GPX Waypoint', description: 'from a gpx file',
+ lat: 48.85, lng: 2.35, address: null, category_id: null, notes: null,
+ transport_mode: 'walking', route_geometry: '[[48.85,2.35],[48.86,2.36]]',
+ duration_minutes: 60, category: null, tags: [], ratings: [],
+ });
+ // Committed for real, not just visible mid-transaction.
+ expect(testDb.prepare('SELECT name FROM places WHERE trip_id = ?').get(trip.id)).toMatchObject({ name: 'GPX Waypoint' });
+ });
+
+ it('PLACEREPO-033b: a transaction that throws after the insert leaves no row behind — the insert really was uncommitted, not autocommitted ahead of the wrapper', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+
+ await expect(t.em.transactional(async () => {
+ const id = await places.insertPlace({ ...base, trip_id: trip.id, name: 'Rolled back', description: null, lat: 1, lng: 1 });
+ // The uncommitted row is visible to a read inside the same transaction...
+ const seen = await places.findWithTagsAndRatings(id);
+ expect(seen?.name).toBe('Rolled back');
+ throw new Error('force rollback');
+ })).rejects.toThrow('force rollback');
+
+ // ...but never lands once the wrapping transaction rolls back.
+ expect(testDb.prepare('SELECT COUNT(*) as c FROM places WHERE trip_id = ?').get(trip.id)).toMatchObject({ c: 0 });
+ });
+
+ it('PLACEREPO-034 (PL34/PL35, KML): the 8-column KML shape (adds category_id) is stored, read back in the same transaction', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const cat = createCategory(testDb, { name: 'Hiking' });
+
+ const row = await t.em.transactional(async () => {
+ const id = await places.insertPlace({
+ ...base,
+ trip_id: trip.id, name: 'Placemark 1', description: 'a kml placemark',
+ lat: 35.0, lng: 139.0, category_id: cat.id, route_geometry: null,
+ });
+ return places.findWithTagsAndRatings(id);
+ });
+
+ expect(row).toMatchObject({
+ trip_id: trip.id, name: 'Placemark 1', description: 'a kml placemark',
+ lat: 35.0, lng: 139.0, category_id: cat.id, duration_minutes: 60,
+ transport_mode: 'walking', address: null, notes: null,
+ category: { id: cat.id, name: 'Hiking' },
+ });
+ });
+
+ it('PLACEREPO-035 (PL38/PL40, Google list): the 7-column Google shape (notes + google_ftid) is stored, read back in the same transaction', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+
+ const row = await t.em.transactional(async () => {
+ const id = await places.insertPlace({
+ ...base,
+ trip_id: trip.id, name: 'Google Place', description: null,
+ lat: 40.7, lng: -74.0, notes: 'a note', google_ftid: '0x1:0x2',
+ });
+ return places.findWithTagsAndRatings(id);
+ });
+
+ expect(row).toMatchObject({
+ trip_id: trip.id, name: 'Google Place', notes: 'a note', google_ftid: '0x1:0x2',
+ lat: 40.7, lng: -74.0, address: null, category_id: null, duration_minutes: 60,
+ transport_mode: 'walking',
+ });
+ });
+
+ it('PLACEREPO-036 (PL41/PL42, Naver list): the 7-column Naver shape (address + notes) is stored, read back in the same transaction', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+
+ const row = await t.em.transactional(async () => {
+ const id = await places.insertPlace({
+ ...base,
+ trip_id: trip.id, name: 'Naver Spot', description: null,
+ lat: 37.5, lng: 127.0, address: '123 Some Street', notes: 'a naver note',
+ });
+ return places.findWithTagsAndRatings(id);
+ });
+
+ expect(row).toMatchObject({
+ trip_id: trip.id, name: 'Naver Spot', address: '123 Some Street', notes: 'a naver note',
+ lat: 37.5, lng: 127.0, category_id: null, duration_minutes: 60, transport_mode: 'walking',
+ });
+ });
+ });
+
+ describe('PlacesRepository.distinctRouteColors / setRouteColor (PL36/PL37)', () => {
+ it('PLACEREPO-037: distinctRouteColors returns only this trip\'s non-null colours, scoped by trip_id', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ testDb.prepare("INSERT INTO places (trip_id, name, lat, lng, route_geometry, route_color) VALUES (?, 'A', 1, 1, '[[1,1]]', ?)").run(trip.id, TRACK_COLORS[0]);
+ testDb.prepare("INSERT INTO places (trip_id, name, lat, lng, route_geometry, route_color) VALUES (?, 'B', 1, 1, '[[1,1]]', ?)").run(trip.id, TRACK_COLORS[1]);
+ testDb.prepare("INSERT INTO places (trip_id, name, lat, lng, route_geometry) VALUES (?, 'C', 1, 1, '[[1,1]]')").run(trip.id);
+ testDb.prepare("INSERT INTO places (trip_id, name, lat, lng, route_geometry, route_color) VALUES (?, 'D', 1, 1, '[[1,1]]', ?)").run(other.id, TRACK_COLORS[2]);
+
+ const colors = await places.distinctRouteColors(trip.id);
+ expect(new Set(colors)).toEqual(new Set([TRACK_COLORS[0], TRACK_COLORS[1]]));
+ });
+
+ it('PLACEREPO-038: setRouteColor writes the column without stamping updated_at', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET updated_at = ? WHERE id = ?').run('2020-01-01 00:00:00', place.id);
+
+ await places.setRouteColor(place.id, TRACK_COLORS[3]);
+
+ const row = testDb.prepare('SELECT route_color, updated_at FROM places WHERE id = ?').get(place.id) as { route_color: string; updated_at: string };
+ expect(row.route_color).toBe(TRACK_COLORS[3]);
+ expect(row.updated_at).toBe('2020-01-01 00:00:00');
+ });
+
+ it('PLACEREPO-039 (D6 single-connection race safety): two concurrent colour claims for the same trip never pick the same free colour', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const placeA = createPlace(testDb, trip.id, { name: 'Track A' });
+ const placeB = createPlace(testDb, trip.id, { name: 'Track B' });
+ testDb.prepare("UPDATE places SET route_geometry = '[[1,1]]' WHERE id IN (?, ?)").run(placeA.id, placeB.id);
+
+ // Mirrors PlacesService.colorizeImportedTracks's own PL36+PL37 pairing
+ // EXACTLY: the read AND the write for one claim share ONE transaction —
+ // splitting them (read in one transaction, write in a second, separate
+ // one) is precisely the bug this pairing exists to prevent, and doing
+ // that here would make the test pass for the wrong reason.
+ const claimAndWrite = (placeId: number) => t.em.transactional(async () => {
+ const taken = new Set(await places.distinctRouteColors(trip.id));
+ const free = TRACK_COLORS.find((c) => !taken.has(c));
+ if (!free) throw new Error('palette exhausted');
+ await places.setRouteColor(placeId, free);
+ return free;
+ });
+
+ const [colorA, colorB] = await Promise.all([
+ claimAndWrite(placeA.id),
+ claimAndWrite(placeB.id),
+ ]);
+
+ expect(colorA).not.toBe(colorB);
+ const rows = testDb.prepare('SELECT route_color FROM places WHERE id IN (?, ?)').all(placeA.id, placeB.id) as { route_color: string }[];
+ expect(new Set(rows.map((r) => r.route_color)).size).toBe(2);
+ });
+ });
+
+ describe('PlacesRepository.backfillFtid (PL39)', () => {
+ it('PLACEREPO-040: stamps google_ftid and updated_at, unscoped by trip (the candidate was already resolved against the trip by findDuplicatePlace)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET updated_at = ? WHERE id = ?').run('2020-01-01 00:00:00', place.id);
+
+ await places.backfillFtid(place.id, '0x9:0x9');
+
+ const row = testDb.prepare('SELECT google_ftid, updated_at FROM places WHERE id = ?').get(place.id) as { google_ftid: string; updated_at: string };
+ expect(row.google_ftid).toBe('0x9:0x9');
+ expect(row.updated_at).not.toBe('2020-01-01 00:00:00');
+ });
+ });
+
+ describe('PlacesRepository.fillIfEmpty (PL43/PL44/PL46) — three call shapes over one COALESCE-per-column method', () => {
+ it('PLACEREPO-041 (PL43 shape): fills every empty column named in fields, stamps updated_at, and leaves an omitted column untouched', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET phone = ?, updated_at = ? WHERE id = ?').run('+1 555', '2020-01-01 00:00:00', place.id);
+
+ await places.fillIfEmpty(place.id, trip.id, {
+ google_place_id: 'gp1', google_ftid: 'gf1', address: 'addr1', website: 'https://x', phone: 'ignored',
+ });
+
+ const row = testDb.prepare('SELECT google_place_id, google_ftid, address, website, phone, updated_at FROM places WHERE id = ?').get(place.id) as Record<string, string>;
+ expect(row.google_place_id).toBe('gp1');
+ expect(row.google_ftid).toBe('gf1');
+ expect(row.address).toBe('addr1');
+ expect(row.website).toBe('https://x');
+ // Already set — COALESCE keeps the existing value, not the caller's.
+ expect(row.phone).toBe('+1 555');
+ expect(row.updated_at).not.toBe('2020-01-01 00:00:00');
+ });
+
+ it('PLACEREPO-042: a column already set is NOT overwritten; an empty one is filled', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET address = ? WHERE id = ?').run('Existing address', place.id);
+
+ await places.fillIfEmpty(place.id, trip.id, { address: 'New address' });
+
+ expect((testDb.prepare('SELECT address FROM places WHERE id = ?').get(place.id) as { address: string }).address).toBe('Existing address');
+
+ const empty = createPlace(testDb, trip.id, { name: 'No address yet' });
+ await places.fillIfEmpty(empty.id, trip.id, { address: 'First address' });
+ expect((testDb.prepare('SELECT address FROM places WHERE id = ?').get(empty.id) as { address: string }).address).toBe('First address');
+ });
+
+ it('PLACEREPO-043 (PL44 shape): image_url-only', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+
+ await places.fillIfEmpty(place.id, trip.id, { image_url: '/api/maps/place-photo/x/bytes' });
+
+ const row = testDb.prepare('SELECT image_url, google_place_id FROM places WHERE id = ?').get(place.id) as { image_url: string; google_place_id: string | null };
+ expect(row.image_url).toBe('/api/maps/place-photo/x/bytes');
+ // Not touched — the key was never in `fields`, not even COALESCE'd against itself.
+ expect(row.google_place_id).toBeNull();
+ });
+
+ it('PLACEREPO-044 (PL46 shape): address-only', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+
+ await places.fillIfEmpty(place.id, trip.id, { address: '1 Rue de Rivoli' });
+
+ expect((testDb.prepare('SELECT address FROM places WHERE id = ?').get(place.id) as { address: string }).address).toBe('1 Rue de Rivoli');
+ });
+
+ it('PLACEREPO-045: WHERE id = ? AND trip_id = ? scoping — a mismatched trip_id writes nothing', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const otherTrip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+
+ await places.fillIfEmpty(place.id, otherTrip.id, { address: 'Should not land' });
+
+ expect((testDb.prepare('SELECT address FROM places WHERE id = ?').get(place.id) as { address: string | null }).address).toBeNull();
+ });
+ });
+
+ // ── Plan 3c Task 7 (trips.rpc.ts::getPlaces, RP2) — additive ────────────────
+
+ describe('PlacesRepository.listForTripOrdered (RP2)', () => {
+ it('PLACEREPO-046: every place of the trip, ORDER BY created_at DESC, scoped to the trip', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const otherTrip = createTrip(testDb, user.id);
+ const p1 = createPlace(testDb, trip.id, { name: 'First' });
+ testDb.prepare('UPDATE places SET created_at = ? WHERE id = ?').run('2026-01-01 00:00:00', p1.id);
+ const p2 = createPlace(testDb, trip.id, { name: 'Second' });
+ testDb.prepare('UPDATE places SET created_at = ? WHERE id = ?').run('2026-02-01 00:00:00', p2.id);
+ createPlace(testDb, otherTrip.id, { name: 'Elsewhere' });
+
+ const legacy = testDb.prepare('SELECT * FROM places WHERE trip_id = ? ORDER BY created_at DESC').all(trip.id);
+ const rows = await places.listForTripOrdered(trip.id);
+ expect(rows).toEqual(legacy);
+ expect(rows.map((r) => r.id)).toEqual([p2.id, p1.id]);
+ });
+
+ it('PLACEREPO-047: an empty trip returns an empty array, not a throw', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ expect(await places.listForTripOrdered(trip.id)).toEqual([]);
+ });
+ });
+
+ // Task 9 fix wave (B-M4, rule 19): `listAllForTrip` (TP40, `TripsService.copy`'s
+ // places read) had no repository test at all. Full-row parity on a fully
+ // seeded fixture — every nullable column non-null in one row, null in the
+ // other, plus a unicode string and a '007'-style digit string — so a
+ // renamed/dropped column or a changed row order would fail this, not a
+ // `toMatchObject` on a few keys.
+ describe('PlacesRepository.listAllForTrip (TP40)', () => {
+ it('PLACEREPO-050: every column, rowid scan order (no ORDER BY) — toEqual(legacy SELECT * run raw) on a fully seeded fixture', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const otherTrip = createTrip(testDb, user.id);
+ const category = createCategory(testDb);
+
+ const insert = testDb.prepare(`
+ INSERT INTO places (
+ trip_id, name, description, lat, lng, address, category_id, price, currency,
+ reservation_status, reservation_notes, reservation_datetime, place_time, end_time,
+ duration_minutes, notes, image_url, google_place_id, google_ftid, website, phone,
+ transport_mode, created_at, updated_at, osm_id, route_geometry, route_color, stop_type,
+ fill_percent, amap_poi_id, source
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `);
+
+ // Row A: every nullable column non-null — a unicode string and a
+ // '007'-style digit string among the values (rule 19's fixture bar).
+ const rowA = insert.run(
+ trip.id, 'Café — 日本 ☕️', 'A description with 007-style digits', 48.1, 2.2, '007 Rue de Paris', category.id, 12.5, 'EUR',
+ 'confirmed', 'notes-a', '2026-01-01T10:00:00Z', '10:00', '11:00',
+ 45, 'place notes', '/img/a.png', 'gpid-007', 'gftid-a', 'https://a.example', '+33 1 23 45 67 89',
+ 'driving', '2026-01-01 09:00:00', '2026-01-01 09:30:00', 'osm-a', '{"type":"LineString"}', '#ff0000', 'hotel',
+ 50, 'amap-a', 'manual',
+ ).lastInsertRowid as number;
+
+ // Row B: every nullable column NULL.
+ const rowB = insert.run(
+ trip.id, 'Bare Place', null, null, null, null, null, null, null,
+ null, null, null, null, null,
+ null, null, null, null, null, null, null,
+ null, null, null, null, null, null, null,
+ null, null, null,
+ ).lastInsertRowid as number;
+
+ // A place on another trip — must not leak into this trip's listAllForTrip.
+ createPlace(testDb, otherTrip.id, { name: 'Elsewhere' });
+
+ const rows = await places.listAllForTrip(trip.id);
+ const legacy = testDb.prepare('SELECT * FROM places WHERE trip_id = ?').all(trip.id);
+ expect(rows).toEqual(legacy);
+ // rowid-ascending scan order (no ORDER BY), not insertion-reversed or re-sorted.
+ expect(rows.map((r) => r.id)).toEqual([rowA, rowB]);
+ });
+
+ it('PLACEREPO-051: an empty trip returns an empty array, not a throw', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ expect(await places.listAllForTrip(trip.id)).toEqual([]);
+ });
+ });
+
+ // ─────────────────────────────────────────────────────────────────────────────
+ // L3 (Plan 3d Task 7 whole-plan review): CH1 (`findChargingProbe`,
+ // `ChargingService.read`'s trip-scoped gate) had zero coverage of the REAL
+ // repository call anywhere in the suite — every existing `charging.test.ts`/
+ // `roadtrip.e2e.test.ts` case mocks `findChargingProbe` or `ChargingService
+ // .read` itself. Pinned here at the repository level (parity with the legacy
+ // `SELECT name, lat, lng, stop_type FROM places WHERE id = ? AND trip_id =
+ // ?`), and separately at the route level for the foreign-place 404
+ // (`tests/e2e/roadtrip.e2e.test.ts`).
+ // ─────────────────────────────────────────────────────────────────────────────
+
+ describe('PlacesRepository.findChargingProbe (CH1)', () => {
+ it('CH1-001: an own-trip place resolves name/lat/lng/stop_type, matching the legacy statement', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Ladepark Nord', lat: 48.137, lng: 11.575 });
+ testDb.prepare("UPDATE places SET stop_type = 'charging' WHERE id = ?").run(place.id);
+
+ const typed = await places.findChargingProbe(place.id, trip.id);
+ const legacy = testDb
+ .prepare('SELECT name, lat, lng, stop_type FROM places WHERE id = ? AND trip_id = ?')
+ .get(place.id, trip.id);
+
+ expect(typed).toEqual(legacy);
+ expect(typed).toEqual({ name: 'Ladepark Nord', lat: 48.137, lng: 11.575, stop_type: 'charging' });
+ });
+
+ it('CH1-002: a place belonging to a DIFFERENT trip resolves to undefined, matching the legacy miss', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const otherTrip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, otherTrip.id, { name: 'Theirs' });
+
+ const typed = await places.findChargingProbe(place.id, trip.id);
+ const legacy = testDb
+ .prepare('SELECT name, lat, lng, stop_type FROM places WHERE id = ? AND trip_id = ?')
+ .get(place.id, trip.id);
+
+ expect(typed).toBeUndefined();
+ expect(legacy).toBeUndefined();
+ });
+
+ it('CH1-003: a non-charging place still resolves (the caller, not this query, decides what to do with stop_type)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Just a stop' });
+
+ const typed = await places.findChargingProbe(place.id, trip.id);
+ expect(typed).toEqual({ name: 'Just a stop', lat: 48.8566, lng: 2.3522, stop_type: null });
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Plan 3h Task 3 (`DawarichSuggestionsService::acceptAsPlace`) — additive.
+ // ---------------------------------------------------------------------------
+
+ describe('PlacesRepository.setSource (DWS7)', () => {
+ it('DWS7-001: stamps source without touching updated_at, matching the legacy statement\'s own column list', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Imported stay' });
+ const before = testDb.prepare('SELECT updated_at FROM places WHERE id = ?').get(place.id) as { updated_at: string | null };
+
+ await places.setSource(place.id, 'dawarich');
+
+ const row = testDb.prepare('SELECT source, updated_at FROM places WHERE id = ?').get(place.id) as { source: string | null; updated_at: string | null };
+ expect(row.source).toBe('dawarich');
+ expect(row.updated_at).toBe(before.updated_at);
+ });
+ });
+
+ // ---------------------------------------------------------------------------
+ // Plan 3h Task 7 review, M1 coverage — Plan 3h Task 4's `maps.service.ts`
+ // photo-fetch (MAP9), untested at the repository level (the service test
+ // stubs this method).
+ // ---------------------------------------------------------------------------
+
+ describe('PlacesRepository.setImageUrlIfUnset (MAP9)', () => {
+ it('MAP9-001: fills a NULL image_url, matching the legacy $or guard', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'No photo yet' });
+ testDb.prepare("UPDATE places SET google_place_id = 'ChIJ_shared' WHERE id = ?").run(place.id);
+
+ const n = await places.setImageUrlIfUnset('ChIJ_shared', '/uploads/photo-cache/new.jpg');
+
+ expect(n).toBe(1);
+ const row = testDb.prepare('SELECT image_url FROM places WHERE id = ?').get(place.id) as { image_url: string | null };
+ expect(row.image_url).toBe('/uploads/photo-cache/new.jpg');
+ });
+
+ it('MAP9-002: fills an EMPTY-STRING image_url too (the second half of the $or)', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Blank photo' });
+ testDb.prepare("UPDATE places SET google_place_id = 'ChIJ_blank', image_url = '' WHERE id = ?").run(place.id);
+
+ const n = await places.setImageUrlIfUnset('ChIJ_blank', '/uploads/photo-cache/filled.jpg');
+
+ expect(n).toBe(1);
+ const row = testDb.prepare('SELECT image_url FROM places WHERE id = ?').get(place.id) as { image_url: string | null };
+ expect(row.image_url).toBe('/uploads/photo-cache/filled.jpg');
+ });
+
+ it('MAP9-003: an already-set image_url is left untouched — never clobbers a custom image', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id, { name: 'Custom photo' });
+ testDb.prepare("UPDATE places SET google_place_id = 'ChIJ_custom', image_url = '/uploads/custom.jpg' WHERE id = ?").run(place.id);
+
+ const n = await places.setImageUrlIfUnset('ChIJ_custom', '/uploads/photo-cache/should-not-land.jpg');
+
+ expect(n).toBe(0);
+ const row = testDb.prepare('SELECT image_url FROM places WHERE id = ?').get(place.id) as { image_url: string | null };
+ expect(row.image_url).toBe('/uploads/custom.jpg');
+ });
+
+ it('MAP9-004: unscoped by trip — every empty-image row sharing the google_place_id across trips is filled in one statement', async () => {
+ const { user } = createUser(testDb);
+ const tripA = createTrip(testDb, user.id);
+ const tripB = createTrip(testDb, user.id);
+ const placeA = createPlace(testDb, tripA.id, { name: 'A' });
+ const placeB = createPlace(testDb, tripB.id, { name: 'B' });
+ testDb.prepare("UPDATE places SET google_place_id = 'ChIJ_shared2' WHERE id IN (?, ?)").run(placeA.id, placeB.id);
+
+ const n = await places.setImageUrlIfUnset('ChIJ_shared2', '/uploads/photo-cache/both.jpg');
+
+ expect(n).toBe(2);
+ expect((testDb.prepare('SELECT image_url FROM places WHERE id = ?').get(placeA.id) as { image_url: string }).image_url).toBe('/uploads/photo-cache/both.jpg');
+ expect((testDb.prepare('SELECT image_url FROM places WHERE id = ?').get(placeB.id) as { image_url: string }).image_url).toBe('/uploads/photo-cache/both.jpg');
+ });
+ });
+
+ describe('PlacesRepository.listAssignedForPublicApi (Plan 4 Task 1, public-api.service.ts::placesByDay)', () => {
+ it('PLACEREPO-053: day_id + place fields + category name, scoped to the trip, ordered by day then order_index — a booked-night stop is excluded', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ const category = createCategory(testDb, { name: 'Museum' });
+ const dayA = createDay(testDb, trip.id);
+ const dayB = createDay(testDb, trip.id);
+ const placeA1 = createPlace(testDb, trip.id, { name: 'A-first', category_id: category.id });
+ const placeA2 = createPlace(testDb, trip.id, { name: 'A-second' });
+ testDb.prepare('UPDATE places SET category_id = NULL WHERE id = ?').run(placeA2.id); // no category, not the factory's default
+ const placeB1 = createPlace(testDb, trip.id, { name: 'B-first' });
+ const hotelPlace = createPlace(testDb, trip.id, { name: 'Hotel' });
+ createDayAssignment(testDb, dayA.id, placeA2.id, { order_index: 5 });
+ createDayAssignment(testDb, dayA.id, placeA1.id, { order_index: 1 });
+ createDayAssignment(testDb, dayB.id, placeB1.id, { order_index: 0 });
+ // A booked-night stop: da.accommodation_id IS NOT NULL, must be excluded.
+ testDb.prepare('INSERT INTO day_assignments (day_id, place_id, order_index, accommodation_id) VALUES (?, ?, 0, 999)').run(dayA.id, hotelPlace.id);
+ // Unassigned place in the same trip — never a candidate at all.
+ createPlace(testDb, trip.id, { name: 'Unassigned' });
+ // A place assigned on a DIFFERENT trip — must not leak in.
+ const otherDay = createDay(testDb, other.id);
+ createDayAssignment(testDb, otherDay.id, createPlace(testDb, other.id, { name: 'Elsewhere' }).id);
+
+ const rows = await places.listAssignedForPublicApi(trip.id);
+
+ expect(rows.map((r) => r.name)).toEqual(['A-first', 'A-second', 'B-first']);
+ expect(rows[0]).toMatchObject({ day_id: dayA.id, name: 'A-first', category: 'Museum' });
+ expect(rows[1]).toMatchObject({ day_id: dayA.id, name: 'A-second', category: null });
+ expect(rows[2]).toMatchObject({ day_id: dayB.id, name: 'B-first' });
+ });
+
+ it('PLACEREPO-054: empty array when nothing is assigned', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ expect(await places.listAssignedForPublicApi(trip.id)).toEqual([]);
+ });
+ });
+
+ // ─────────────────────────────────────────────────────────────────────────────
+ // Plan 4 Task 8b-2, item 1 (3d Task 7 review's "Places.findTrackInTrip" carry,
+ // the actual method is `isTrackInTrip`): RT13 (`RoadtripService.trackExists`)
+ // had no repository-level parity test. `SELECT id FROM places WHERE id = ?
+ // AND trip_id = ? AND route_geometry IS NOT NULL AND route_geometry != ''`,
+ // both nullable/empty-string edges pinned against the legacy predicate.
+ // ─────────────────────────────────────────────────────────────────────────────
+
+ describe('PlacesRepository.isTrackInTrip (RT13, RoadtripService.trackExists)', () => {
+ const legacyIsTrackInTrip = (id: number, tripId: number): boolean =>
+ !!testDb.prepare(
+ "SELECT id FROM places WHERE id = ? AND trip_id = ? AND route_geometry IS NOT NULL AND route_geometry != ''",
+ ).get(id, tripId);
+
+ it('PLACEREPO-055: a place with route_geometry set matches the legacy predicate — true', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET route_geometry = ? WHERE id = ?').run('{"type":"LineString"}', place.id);
+
+ expect(await places.isTrackInTrip(place.id, trip.id)).toBe(legacyIsTrackInTrip(place.id, trip.id));
+ expect(await places.isTrackInTrip(place.id, trip.id)).toBe(true);
+ });
+
+ it('PLACEREPO-056: route_geometry NULL matches the legacy predicate — false', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare('UPDATE places SET route_geometry = NULL WHERE id = ?').run(place.id);
+
+ expect(await places.isTrackInTrip(place.id, trip.id)).toBe(legacyIsTrackInTrip(place.id, trip.id));
+ expect(await places.isTrackInTrip(place.id, trip.id)).toBe(false);
+ });
+
+ it('PLACEREPO-057: route_geometry \'\' (empty string) matches the legacy predicate — false', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const place = createPlace(testDb, trip.id);
+ testDb.prepare("UPDATE places SET route_geometry = '' WHERE id = ?").run(place.id);
+
+ expect(await places.isTrackInTrip(place.id, trip.id)).toBe(legacyIsTrackInTrip(place.id, trip.id));
+ expect(await places.isTrackInTrip(place.id, trip.id)).toBe(false);
+ });
+
+ it('PLACEREPO-058: a track on a DIFFERENT trip is not found — false', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ const place = createPlace(testDb, other.id);
+ testDb.prepare('UPDATE places SET route_geometry = ? WHERE id = ?').run('{"type":"LineString"}', place.id);
+
+ expect(await places.isTrackInTrip(place.id, trip.id)).toBe(legacyIsTrackInTrip(place.id, trip.id));
+ expect(await places.isTrackInTrip(place.id, trip.id)).toBe(false);
+ });
+ });
+
+ // ─────────────────────────────────────────────────────────────────────────────
+ // Plan 4 Task 8b-2, item 3 (3f L6 carry): AtlasService's own reads on
+ // PlacesRepository — AT2 (listForTripIds) and AT41 (listAddressesForUser) —
+ // had no repository-level toEqual(<legacy raw>) parity test.
+ // ─────────────────────────────────────────────────────────────────────────────
+
+ describe('PlacesRepository.listForTripIds (AT2, AtlasService#getPlacesForTrips)', () => {
+ it('PLACEREPO-059: matches SELECT * FROM places WHERE trip_id IN (...) run raw', async () => {
+ const { user } = createUser(testDb);
+ const tripA = createTrip(testDb, user.id);
+ const tripB = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ const pa = createPlace(testDb, tripA.id, { name: 'A' });
+ const pb = createPlace(testDb, tripB.id, { name: 'B' });
+ createPlace(testDb, other.id, { name: 'Not in the batch' });
+
+ const legacy = testDb.prepare(`SELECT * FROM places WHERE trip_id IN (${[tripA.id, tripB.id].join(',')})`).all();
+ const typed = await places.listForTripIds([tripA.id, tripB.id]);
+ expect(typed).toEqual(legacy);
+ expect(typed.map((p) => p.id).sort((a, b) => a - b)).toEqual([pa.id, pb.id].sort((a, b) => a - b));
+ });
+
+ it('PLACEREPO-060: an empty trip-id array short-circuits to [] without a query', async () => {
+ expect(await places.listForTripIds([])).toEqual([]);
+ });
+ });
+
+ describe('PlacesRepository.listAddressesForUser (AT41, AtlasService#getTravelStats)', () => {
+ it('PLACEREPO-061: matches the legacy DISTINCT statement, owner and member trips, region_name joined from place_regions', async () => {
+ const { user: owner } = createUser(testDb);
+ const { user: member } = createUser(testDb);
+ const { user: stranger } = createUser(testDb);
+ const trip = createTrip(testDb, owner.id);
+ addTripMember(testDb, trip.id, member.id);
+ const place = createPlace(testDb, trip.id, { name: 'Tower', lat: 48.85, lng: 2.35 });
+ testDb.prepare('UPDATE places SET address = ? WHERE id = ?').run('5 Avenue Anatole France', place.id);
+ testDb.prepare('INSERT INTO place_regions (place_id, country_code, region_code, region_name) VALUES (?, ?, ?, ?)')
+ .run(place.id, 'FR', 'FR-IDF', 'Île-de-France');
+ const noAddress = createPlace(testDb, trip.id, { name: 'No address' });
+ testDb.prepare('UPDATE places SET address = NULL, lat = NULL, lng = NULL WHERE id = ?').run(noAddress.id);
+
+ const legacy = testDb.prepare(`
+ SELECT DISTINCT p.address, p.lat, p.lng, pr.region_name
+ FROM places p JOIN trips t ON p.trip_id = t.id
+ LEFT JOIN trip_members tm ON t.id = tm.trip_id
+ LEFT JOIN place_regions pr ON pr.place_id = p.id
+ WHERE t.user_id = ? OR tm.user_id = ?`).all(owner.id, owner.id);
+
+ const typedOwner = await places.listAddressesForUser(owner.id);
+ expect(typedOwner).toEqual(legacy);
+ expect(typedOwner).toEqual([
+ { address: '5 Avenue Anatole France', lat: 48.85, lng: 2.35, region_name: 'Île-de-France' },
+ { address: null, lat: null, lng: null, region_name: null },
+ ]);
+
+ const typedMember = await places.listAddressesForUser(member.id);
+ expect(typedMember).toEqual(typedOwner);
+
+ expect(await places.listAddressesForUser(stranger.id)).toEqual([]);
+ });
+ });
+
+ /**
+ * Plan 4 Task 8b-4a (3h L4) — full-key `toEqual(<legacy raw>)` parity for
+ * `PlacesRepository.listPublicForShare` (`share.service.ts:340` SH12),
+ * flagged by the 3h ledger as having no repository-level parity test. The
+ * legacy statement (the method's own docstring) is a named 20-column
+ * allow-list (never `p.*`) LEFT JOINed to `categories`, scoped by trip only
+ * — a public share sees every place in the pool regardless of any
+ * assignment/booking status, but never the owner-only columns
+ * (`reservation_status`, `google_place_id`, `osm_id`, `route_geometry`,
+ * `source`, …) this SELECT list withholds by omission.
+ */
+ describe('PlacesRepository — share.service.ts SH12 read', () => {
+ function legacyPublicForShare(tripId: number): unknown {
+ return testDb.prepare(`
+ SELECT p.id, p.trip_id, p.name, p.description, p.lat, p.lng, p.address, p.category_id,
+ p.price, p.currency, p.place_time, p.end_time, p.duration_minutes, p.notes,
+ p.image_url, p.website, p.phone, p.transport_mode, p.created_at, p.updated_at,
+ c.name as category_name, c.color as category_color, c.icon as category_icon
+ FROM places p
+ LEFT JOIN categories c ON c.id = p.category_id
+ WHERE p.trip_id = ?
+ ORDER BY p.created_at DESC`).all(tripId);
+ }
+
+ it('listPublicForShare — matches the legacy statement, categorised and uncategorised, every nullable column both null and set', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const other = createTrip(testDb, user.id);
+ const category = createCategory(testDb, { name: 'Museum', color: '#111111', icon: '🏛️' });
+
+ const withCategory = createPlace(testDb, trip.id, { name: 'Louvre', lat: 48.86, lng: 2.34, category_id: category.id, description: 'Art museum' });
+ testDb.prepare(`
+ UPDATE places SET address = ?, price = ?, currency = ?, place_time = ?, end_time = ?,
+ duration_minutes = ?, notes = ?, image_url = ?, website = ?, phone = ?, transport_mode = ?,
+ updated_at = ?, created_at = ?, reservation_status = 'confirmed', google_place_id = 'ChIJ123'
+ WHERE id = ?`).run(
+ 'Rue de Rivoli', 17.5, 'EUR', '10:00', '12:00', 120, 'bring ID', 'https://img/louvre.jpg',
+ 'https://louvre.fr', '+33140205050', 'walking', '2026-09-01T09:00:00.000Z', '2026-09-01T08:00:00.000Z',
+ withCategory.id,
+ );
+
+ const bare = createPlace(testDb, trip.id, { name: 'Unnamed spot' });
+ testDb.prepare(`
+ UPDATE places SET category_id = NULL, lat = NULL, lng = NULL, address = NULL, price = NULL,
+ currency = NULL, place_time = NULL, end_time = NULL, duration_minutes = NULL, notes = NULL,
+ image_url = NULL, website = NULL, phone = NULL, transport_mode = NULL, updated_at = NULL,
+ created_at = '2026-09-02T08:00:00.000Z', description = NULL
+ WHERE id = ?`).run(bare.id);
+
+ // A place on a different trip must never leak in.
+ createPlace(testDb, other.id, { name: 'Foreign place' });
+
+ const legacy = legacyPublicForShare(trip.id);
+ const typed = await places.listPublicForShare(trip.id);
+ expect(typed).toEqual(legacy);
+ // ORDER BY p.created_at DESC: bare (2026-09-02) before withCategory (2026-09-01).
+ expect(typed.map((r) => r.id)).toEqual([bare.id, withCategory.id]);
+ expect(typed.find((r) => r.id === withCategory.id)).toMatchObject({
+ category_name: 'Museum', category_color: '#111111', category_icon: '🏛️',
+ });
+ expect(typed.find((r) => r.id === bare.id)).toMatchObject({
+ category_id: null, category_name: null, category_color: null, category_icon: null,
+ });
+ // Owner-only columns are withheld by omission — never present on the row at all.
+ expect(typed[1]).not.toHaveProperty('reservation_status');
+ expect(typed[1]).not.toHaveProperty('google_place_id');
+ });
+
+ it('listPublicForShare — [] for a trip with no places', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ expect(await places.listPublicForShare(trip.id)).toEqual([]);
+ });
+ });
++
++describe('PlacesRepository.insertTourPlace (TO10) / updateTourRoute (TO11)', () => {
++ it('PLACEREPO-TOUR-001: insertTourPlace writes the route place as a walking place and leaves the rest at its defaults', async () => {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id);
++ const id = await places.insertTourPlace({ trip_id: trip.id, name: 'Ridge walk', lat: 47, lng: 11, route_geometry: '[[47,11],[47.1,11.1]]' });
++
++ expect(await places.findInTrip(id, trip.id)).toMatchObject({
++ trip_id: trip.id, name: 'Ridge walk', lat: 47, lng: 11, transport_mode: 'walking',
++ route_geometry: '[[47,11],[47.1,11.1]]', duration_minutes: 60, reservation_status: 'none', category_id: null,
++ });
++ });
++
++ it('PLACEREPO-TOUR-002: updateTourRoute rewrites the route of a place of that trip, stamps updated_at, and refuses another trip', async () => {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id);
++ const other = createTrip(testDb, user.id);
++ const place = createPlace(testDb, trip.id, { name: 'Old', lat: 1, lng: 1 });
++ testDb.prepare("UPDATE places SET transport_mode = 'driving', updated_at = NULL WHERE id = ?").run(place.id);
++ const route = { name: 'New', lat: 47, lng: 11, route_geometry: '[[47,11],[47.2,11.2]]' };
++
++ expect(await places.updateTourRoute(place.id, other.id, route)).toBe(false);
++ expect(await places.findInTrip(place.id, trip.id)).toMatchObject({ name: 'Old', transport_mode: 'driving', updated_at: null });
++
++ expect(await places.updateTourRoute(place.id, trip.id, route)).toBe(true);
++ const row = await places.findInTrip(place.id, trip.id);
++ expect(row).toMatchObject({ ...route, transport_mode: 'walking' });
++ expect(row?.updated_at).not.toBeNull();
++ });
++});
++
++describe('PlacesRepository.isTour / listForTrip tour_place_id', () => {
++ it('PLACEREPO-TOUR-003: isTour is true only for a place with a tours row', async () => {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id);
++ const tour = createPlace(testDb, trip.id, { name: 'Ridge walk' });
++ const plain = createPlace(testDb, trip.id, { name: 'Cafe' });
++ createTour(testDb, tour.id);
++
++ expect(await places.isTour(tour.id)).toBe(true);
++ expect(await places.isTour(plain.id)).toBe(false);
++ expect(await places.isTour(999_999)).toBe(false);
++ });
++
++ it('PLACEREPO-TOUR-004: listForTrip carries the place id as tour_place_id for Tours and null otherwise', async () => {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id);
++ const tour = createPlace(testDb, trip.id, { name: 'Ridge walk' });
++ const plain = createPlace(testDb, trip.id, { name: 'Cafe' });
++ createTour(testDb, tour.id);
++
++ const rows = await places.listForTrip(String(trip.id), {});
++ const byId = new Map(rows.map((r) => [r.id, r.tour_place_id]));
++ expect(byId.get(tour.id)).toBe(tour.id);
++ expect(byId.get(plain.id)).toBeNull();
++ });
++});
diff --cc server/tests/unit/db/repositories/TourWaypoints.repository.test.ts
index 000000000,000000000..e4a90bc64
new file mode 100644
--- /dev/null
+++ b/server/tests/unit/db/repositories/TourWaypoints.repository.test.ts
@@@ -1,0 -1,0 +1,78 @@@
++/**
++ * `TourWaypointsRepository`: TW1 (`listForPlace`), TW2 (`listForTrip`), TW3
++ * (`insertForPlace`) and TW4 (`deleteForPlace`).
++ */
++import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
++import { createSnapshotTestDb } from '../../../helpers/db-mock';
++import { resetTestDb } from '../../../helpers/test-db';
++import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
++import { createPlace, createTrip, createUser } from '../../../helpers/factories';
++import { createTour } from '../../../helpers/tours-repos';
++import { TourWaypoints } from '../../../../src/db/entities/TourWaypoints.entity';
++import type { TourWaypointRow, TourWaypointsRepository } from '../../../../src/db/repositories/TourWaypoints.repository';
++
++const testDb = createSnapshotTestDb();
++let t: TestOrm;
++let repo: TourWaypointsRepository;
++
++beforeAll(async () => {
++ t = await createTestOrm(testDb);
++ repo = t.repo(TourWaypoints);
++});
++beforeEach(() => { resetTestDb(testDb); t.clear(); });
++afterAll(async () => { await t.close(); testDb.close(); });
++
++const ROUTE: TourWaypointRow[] = [
++ { lat: 47.1, lng: 11.1, role: 'end', sequence: 2 },
++ { lat: 47, lng: 11, role: 'start', sequence: 0 },
++ { lat: 47.05, lng: 11.05, role: 'via', sequence: 1 },
++];
++
++function tourInTrip() {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id);
++ const place = createPlace(testDb, trip.id);
++ createTour(testDb, place.id);
++ return { trip, place };
++}
++
++describe('TourWaypointsRepository', () => {
++ it('TWREPO-001: insertForPlace writes every point and listForPlace reads them back in route order', async () => {
++ const { place } = tourInTrip();
++ await repo.insertForPlace(place.id, ROUTE);
++ expect(await repo.listForPlace(place.id)).toEqual([...ROUTE].sort((a, b) => a.sequence - b.sequence));
++ });
++
++ it('TWREPO-002: insertForPlace with no points writes nothing', async () => {
++ const { place } = tourInTrip();
++ await repo.insertForPlace(place.id, []);
++ expect(await repo.listForPlace(place.id)).toEqual([]);
++ });
++
++ it('TWREPO-003: deleteForPlace clears one tour and leaves another alone', async () => {
++ const first = tourInTrip();
++ const second = tourInTrip();
++ await repo.insertForPlace(first.place.id, ROUTE);
++ await repo.insertForPlace(second.place.id, ROUTE);
++
++ await repo.deleteForPlace(first.place.id);
++ expect(await repo.listForPlace(first.place.id)).toEqual([]);
++ expect(await repo.listForPlace(second.place.id)).toHaveLength(3);
++ });
++
++ it('TWREPO-004: listForTrip returns every waypoint of the trip with its place, ordered by place and sequence', async () => {
++ const { trip, place } = tourInTrip();
++ const other = tourInTrip();
++ const second = createPlace(testDb, trip.id);
++ createTour(testDb, second.id);
++ await repo.insertForPlace(second.id, ROUTE.slice(0, 2));
++ await repo.insertForPlace(place.id, ROUTE);
++ await repo.insertForPlace(other.place.id, ROUTE);
++
++ const rows = await repo.listForTrip(trip.id);
++ expect(rows.map((r) => [r.place_id, r.sequence])).toEqual([
++ [place.id, 0], [place.id, 1], [place.id, 2], [second.id, 0], [second.id, 2],
++ ]);
++ expect(rows[0]).toEqual({ place_id: place.id, lat: 47, lng: 11, role: 'start', sequence: 0 });
++ });
++});
diff --cc server/tests/unit/db/repositories/Tours.repository.test.ts
index 000000000,000000000..724134645
new file mode 100644
--- /dev/null
+++ b/server/tests/unit/db/repositories/Tours.repository.test.ts
@@@ -1,0 -1,0 +1,167 @@@
++/**
++ * `ToursRepository`: the list/detail projection (TO1/TO2), the facet probes
++ * places and assignments ask (TO3/TO4/TO5), the trip copy read and write
++ * (TO6/TO8), and the create/edit writes (TO7/TO9).
++ */
++import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
++import { createSnapshotTestDb } from '../../../helpers/db-mock';
++import { resetTestDb } from '../../../helpers/test-db';
++import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
++import { createDay, createDayAssignment, createPlace, createTrip, createUser } from '../../../helpers/factories';
++import { createTour } from '../../../helpers/tours-repos';
++import { Tours } from '../../../../src/db/entities/Tours.entity';
++import type { ToursRepository } from '../../../../src/db/repositories/Tours.repository';
++
++const testDb = createSnapshotTestDb();
++let t: TestOrm;
++let repo: ToursRepository;
++
++beforeAll(async () => {
++ t = await createTestOrm(testDb);
++ repo = t.repo(Tours);
++});
++beforeEach(() => { resetTestDb(testDb); t.clear(); });
++afterAll(async () => { await t.close(); testDb.close(); });
++
++function fixture() {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id);
++ const other = createTrip(testDb, user.id);
++ return { trip, other };
++}
++
++function addWaypoint(placeId: number, sequence: number): void {
++ testDb.prepare("INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (?, 47, 11, 'via', ?)").run(placeId, sequence);
++}
++
++const METRICS = {
++ tour_type: 'hike',
++ distance: 8.25,
++ elevation_gain: 420,
++ elevation_loss: 380,
++ duration: 150,
++ match_confidence: 1,
++ max_hiking_difficulty: 3,
++};
++
++describe('ToursRepository reads', () => {
++ it('TOURREPO-001: listForTrip projects the facet with its place name and both flags, newest first, never another trip', async () => {
++ const { trip, other } = fixture();
++ const older = createPlace(testDb, trip.id, { name: 'Older' });
++ const newer = createPlace(testDb, trip.id, { name: 'Newer' });
++ const plain = createPlace(testDb, trip.id, { name: 'Not a tour' });
++ const foreign = createPlace(testDb, other.id, { name: 'Foreign' });
++ createTour(testDb, older.id, { created_at: '2026-01-01 10:00:00', distance: 5, match_confidence: 0.3 });
++ createTour(testDb, newer.id, { created_at: '2026-01-02 10:00:00', max_hiking_difficulty: 5 });
++ createTour(testDb, foreign.id);
++ createDayAssignment(testDb, createDay(testDb, trip.id).id, older.id);
++ addWaypoint(newer.id, 0);
++
++ expect(await repo.listForTrip(trip.id)).toEqual([
++ {
++ place_id: newer.id, name: 'Newer', tour_type: 'hike', distance: null, elevation_gain: null, elevation_loss: null,
++ duration: null, difficulty: null, wanderer_ref: null, match_confidence: null, tour_group_id: null,
++ max_hiking_difficulty: 5, planned: 0, has_waypoints: 1,
++ },
++ {
++ place_id: older.id, name: 'Older', tour_type: 'hike', distance: 5, elevation_gain: null, elevation_loss: null,
++ duration: null, difficulty: null, wanderer_ref: null, match_confidence: 0.3, tour_group_id: null,
++ max_hiking_difficulty: 2, planned: 1, has_waypoints: 0,
++ },
++ ]);
++ expect((await repo.listForTrip(trip.id)).map((r) => r.place_id)).not.toContain(plain.id);
++ });
++
++ it('TOURREPO-002: listForTrip breaks a created_at tie by the newer place', async () => {
++ const { trip } = fixture();
++ const a = createPlace(testDb, trip.id);
++ const b = createPlace(testDb, trip.id);
++ createTour(testDb, a.id, { created_at: '2026-01-01 10:00:00' });
++ createTour(testDb, b.id, { created_at: '2026-01-01 10:00:00' });
++ expect((await repo.listForTrip(trip.id)).map((r) => r.place_id)).toEqual([b.id, a.id]);
++ });
++
++ it('TOURREPO-003: findInTrip returns the row for its own trip and undefined across trips or for a plain place', async () => {
++ const { trip, other } = fixture();
++ const tour = createPlace(testDb, trip.id, { name: 'Ridge' });
++ const plain = createPlace(testDb, trip.id);
++ createTour(testDb, tour.id);
++
++ expect(await repo.findInTrip(trip.id, tour.id)).toMatchObject({ place_id: tour.id, name: 'Ridge', planned: 0, has_waypoints: 0 });
++ expect(await repo.findInTrip(other.id, tour.id)).toBeUndefined();
++ expect(await repo.findInTrip(trip.id, plain.id)).toBeUndefined();
++ });
++
++ it('TOURREPO-004: existsForPlace and listTourPlaceIds tell tours from plain places', async () => {
++ const { trip } = fixture();
++ const tour = createPlace(testDb, trip.id);
++ const plain = createPlace(testDb, trip.id);
++ createTour(testDb, tour.id);
++
++ expect(await repo.existsForPlace(tour.id)).toBe(true);
++ expect(await repo.existsForPlace(plain.id)).toBe(false);
++ expect(await repo.listTourPlaceIds([plain.id, tour.id])).toEqual([tour.id]);
++ expect(await repo.listTourPlaceIds([])).toEqual([]);
++ });
++
++ it('TOURREPO-005: isOnDay is true only for a tour already on that day, and ignores the assignment being moved', async () => {
++ const { trip } = fixture();
++ const day1 = createDay(testDb, trip.id);
++ const day2 = createDay(testDb, trip.id);
++ const tour = createPlace(testDb, trip.id);
++ const plain = createPlace(testDb, trip.id);
++ createTour(testDb, tour.id);
++ const onDay1 = createDayAssignment(testDb, day1.id, tour.id);
++ createDayAssignment(testDb, day1.id, plain.id);
++
++ expect(await repo.isOnDay(day1.id, tour.id)).toBe(true);
++ expect(await repo.isOnDay(day2.id, tour.id)).toBe(false);
++ expect(await repo.isOnDay(day1.id, plain.id)).toBe(false);
++ expect(await repo.isOnDay(day1.id, tour.id, onDay1.id)).toBe(false);
++ });
++});
++
++describe('ToursRepository writes', () => {
++ it('TOURREPO-006: insertTour writes the metrics and leaves the unset metadata NULL', async () => {
++ const { trip } = fixture();
++ const place = createPlace(testDb, trip.id, { name: 'Drawn' });
++ await repo.insertTour({ place_id: place.id, ...METRICS });
++
++ expect(await repo.findInTrip(trip.id, place.id)).toEqual({
++ place_id: place.id, name: 'Drawn', ...METRICS, difficulty: null, wanderer_ref: null, tour_group_id: null,
++ planned: 0, has_waypoints: 0,
++ });
++ });
++
++ it('TOURREPO-007: updateInTrip replaces the metrics of a tour of that trip and refuses one of another trip', async () => {
++ const { trip, other } = fixture();
++ const place = createPlace(testDb, trip.id);
++ createTour(testDb, place.id);
++
++ expect(await repo.updateInTrip(other.id, place.id, METRICS)).toBe(false);
++ expect(await repo.findInTrip(trip.id, place.id)).toMatchObject({ distance: null, max_hiking_difficulty: 2 });
++
++ expect(await repo.updateInTrip(trip.id, place.id, METRICS)).toBe(true);
++ expect(await repo.findInTrip(trip.id, place.id)).toMatchObject(METRICS);
++ });
++
++ it('TOURREPO-008: listRowsForTrip and insertCopy carry every column, created_at included, onto the copied place', async () => {
++ const { trip, other } = fixture();
++ const source = createPlace(testDb, trip.id);
++ createTour(testDb, source.id, { created_at: '2026-03-04 05:06:07', distance: 3.5, max_hiking_difficulty: 4 });
++ testDb.prepare("UPDATE tours SET difficulty = 'T3', wanderer_ref = 'w-1', tour_group_id = 9 WHERE place_id = ?").run(source.id);
++
++ const rows = await repo.listRowsForTrip(trip.id);
++ expect(rows).toEqual([{
++ place_id: source.id, tour_type: 'hike', distance: 3.5, elevation_gain: null, elevation_loss: null, duration: null,
++ difficulty: 'T3', wanderer_ref: 'w-1', match_confidence: null, tour_group_id: 9, created_at: '2026-03-04 05:06:07',
++ max_hiking_difficulty: 4,
++ }]);
++ expect(await repo.listRowsForTrip(other.id)).toEqual([]);
++
++ const copy = createPlace(testDb, other.id);
++ const { place_id: _sourceId, ...columns } = rows[0];
++ await repo.insertCopy(copy.id, columns);
++ expect(await repo.listRowsForTrip(other.id)).toEqual([{ ...rows[0], place_id: copy.id }]);
++ });
++});
diff --cc server/tests/unit/db/tours-migration.test.ts
index 000000000,000000000..f3bbc31a8
new file mode 100644
--- /dev/null
+++ b/server/tests/unit/db/tours-migration.test.ts
@@@ -1,0 -1,0 +1,139 @@@
++/**
++ * `Migration20200101042000_tours`: the Tours tables on a fresh install, and on
++ * a test instance that already carries them from the pre-ORM Tours branch.
++ *
++ * Migrate to the step immediately before it, optionally lay down the
++ * branch's own tables with rows in them, apply just this migration, assert.
++ */
++import { describe, expect, it } from 'vitest';
++import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
++import type { MikroORM } from '@mikro-orm/sqlite';
++
++const TARGET = 'Migration20200101042000_tours';
++
++async function ormBeforeTarget(): Promise<MikroORM> {
++ const orm = await createMigrationOrm();
++ const names = await pendingNames(orm);
++ const idx = names.indexOf(TARGET);
++ expect(idx).toBeGreaterThan(0);
++ await migrateTo(orm, names[idx - 1]);
++ return orm;
++}
++
++async function indexNames(orm: MikroORM, table: string): Promise<string[]> {
++ const rows = await rawQuery<{ name: string }>(orm, `SELECT name FROM pragma_index_list('${table}') ORDER BY name`);
++ return rows.map((r) => r.name);
++}
++
++async function seedTripWithPlace(orm: MikroORM): Promise<void> {
++ await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')");
++ await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Alps')");
++ await rawExec(orm, "INSERT INTO places (id, trip_id, name) VALUES (100, 10, 'Ridge walk')");
++}
++
++describe('Tours migration', () => {
++ it('TOURMIG-001: a fresh install gets the three tables, the hike type and no redundant waypoint index', async () => {
++ const orm = await ormBeforeTarget();
++ try {
++ await migrateTo(orm, TARGET);
++
++ expect(await rawQuery(orm, 'SELECT key, label_key, icon, color, routing_profile, is_sport, enabled, sort_order FROM tour_types')).toEqual([
++ { key: 'hike', label_key: 'tourTypes.hike', icon: 'Mountain', color: '#16a34a', routing_profile: 'pedestrian', is_sport: 1, enabled: 1, sort_order: 0 },
++ ]);
++
++ const tourColumns = await rawQuery<{ name: string; notnull: number; dflt_value: string | null; pk: number }>(
++ orm,
++ "SELECT name, \"notnull\", dflt_value, pk FROM pragma_table_info('tours') ORDER BY cid",
++ );
++ expect(tourColumns.map((c) => c.name)).toEqual([
++ 'place_id', 'tour_type', 'distance', 'elevation_gain', 'elevation_loss', 'duration', 'difficulty',
++ 'wanderer_ref', 'match_confidence', 'tour_group_id', 'created_at', 'max_hiking_difficulty',
++ ]);
++ expect(tourColumns.find((c) => c.name === 'max_hiking_difficulty')).toMatchObject({ notnull: 1, dflt_value: '2' });
++ expect(tourColumns.find((c) => c.name === 'place_id')).toMatchObject({ pk: 1 });
++
++ expect(await indexNames(orm, 'tours')).toContain('idx_tours_tour_type');
++ expect(await indexNames(orm, 'tour_waypoints')).not.toContain('idx_tour_waypoints_place');
++
++ const fks = await rawQuery<{ table: string; from: string; to: string; on_delete: string }>(
++ orm,
++ "SELECT \"table\", \"from\", \"to\", on_delete FROM pragma_foreign_key_list('tours') UNION ALL SELECT \"table\", \"from\", \"to\", on_delete FROM pragma_foreign_key_list('tour_waypoints') ORDER BY 1, 2",
++ );
++ expect(fks).toEqual([
++ { table: 'places', from: 'place_id', to: 'id', on_delete: 'CASCADE' },
++ { table: 'tour_types', from: 'tour_type', to: 'key', on_delete: 'NO ACTION' },
++ { table: 'tours', from: 'place_id', to: 'place_id', on_delete: 'CASCADE' },
++ ]);
++ } finally {
++ await orm.close(true);
++ }
++ }, 30000);
++
++ it('TOURMIG-002: the CHECKs refuse out-of-range values and a place delete cascades through tours to its waypoints', async () => {
++ const orm = await ormBeforeTarget();
++ try {
++ await migrateTo(orm, TARGET);
++ await rawExec(orm, 'PRAGMA foreign_keys = ON');
++ await seedTripWithPlace(orm);
++
++ await expect(rawExec(orm, "INSERT INTO tours (place_id, tour_type, max_hiking_difficulty) VALUES (100, 'hike', 7)")).rejects.toThrow(/CHECK/);
++ await expect(rawExec(orm, "INSERT INTO tours (place_id, tour_type) VALUES (100, 'kayak')")).rejects.toThrow(/FOREIGN KEY/);
++ await rawExec(orm, "INSERT INTO tours (place_id, tour_type) VALUES (100, 'hike')");
++ expect(await rawQuery(orm, 'SELECT max_hiking_difficulty FROM tours')).toEqual([{ max_hiking_difficulty: 2 }]);
++
++ await expect(rawExec(orm, "INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (100, 91, 0, 'start', 0)")).rejects.toThrow(/CHECK/);
++ await expect(rawExec(orm, "INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (100, 0, 0, 'detour', 0)")).rejects.toThrow(/CHECK/);
++ await rawExec(orm, "INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (100, 47, 11, 'start', 0), (100, 47.1, 11.1, 'end', 1)");
++ await expect(rawExec(orm, "INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (100, 47, 11, 'via', 1)")).rejects.toThrow(/UNIQUE/);
++
++ await rawExec(orm, 'DELETE FROM places WHERE id = 100');
++ expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM tours')).toEqual([{ n: 0 }]);
++ expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM tour_waypoints')).toEqual([{ n: 0 }]);
++ } finally {
++ await orm.close(true);
++ }
++ }, 30000);
++
++ it('TOURMIG-003: on an instance that already has the pre-ORM Tours tables it keeps every row and drops only the redundant index', async () => {
++ const orm = await ormBeforeTarget();
++ try {
++ // The pre-ORM branch's final shape, rows and all, with its custom hike row.
++ await rawExec(orm, `CREATE TABLE tour_types (
++ key TEXT PRIMARY KEY, label_key TEXT NOT NULL, icon TEXT NOT NULL, color TEXT NOT NULL, routing_profile TEXT,
++ is_sport INTEGER NOT NULL DEFAULT 1, enabled INTEGER NOT NULL DEFAULT 1, sort_order INTEGER NOT NULL DEFAULT 0)`);
++ await rawExec(orm, "INSERT INTO tour_types (key, label_key, icon, color, routing_profile) VALUES ('hike', 'tourTypes.hike', 'Mountain', '#000000', 'pedestrian')");
++ await rawExec(orm, `CREATE TABLE tours (
++ place_id INTEGER PRIMARY KEY REFERENCES places(id) ON DELETE CASCADE,
++ tour_type TEXT NOT NULL REFERENCES tour_types(key), distance REAL, elevation_gain REAL, elevation_loss REAL,
++ duration REAL, difficulty TEXT, wanderer_ref TEXT, match_confidence REAL, tour_group_id INTEGER,
++ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
++ max_hiking_difficulty INTEGER NOT NULL DEFAULT 2 CHECK(max_hiking_difficulty BETWEEN 1 AND 6))`);
++ await rawExec(orm, 'CREATE INDEX idx_tours_tour_type ON tours(tour_type)');
++ await rawExec(orm, `CREATE TABLE tour_waypoints (
++ id INTEGER PRIMARY KEY AUTOINCREMENT,
++ place_id INTEGER NOT NULL REFERENCES tours(place_id) ON DELETE CASCADE,
++ lat REAL NOT NULL CHECK(lat >= -90 AND lat <= 90), lng REAL NOT NULL CHECK(lng >= -180 AND lng <= 180),
++ role TEXT NOT NULL CHECK(role IN ('start', 'via', 'end')), sequence INTEGER NOT NULL CHECK(sequence >= 0),
++ UNIQUE(place_id, sequence))`);
++ await rawExec(orm, 'CREATE INDEX idx_tour_waypoints_place ON tour_waypoints(place_id, sequence)');
++ await seedTripWithPlace(orm);
++ await rawExec(orm, "INSERT INTO tours (place_id, tour_type, distance, max_hiking_difficulty) VALUES (100, 'hike', 12.5, 4)");
++ await rawExec(orm, "INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (100, 47, 11, 'start', 0), (100, 47.1, 11.1, 'end', 1)");
++
++ await migrateTo(orm, TARGET);
++
++ expect(await rawQuery(orm, 'SELECT key, color FROM tour_types')).toEqual([{ key: 'hike', color: '#000000' }]);
++ expect(await rawQuery(orm, 'SELECT place_id, tour_type, distance, max_hiking_difficulty FROM tours')).toEqual([
++ { place_id: 100, tour_type: 'hike', distance: 12.5, max_hiking_difficulty: 4 },
++ ]);
++ expect(await rawQuery(orm, 'SELECT role, sequence FROM tour_waypoints ORDER BY sequence')).toEqual([
++ { role: 'start', sequence: 0 },
++ { role: 'end', sequence: 1 },
++ ]);
++ expect(await indexNames(orm, 'tours')).toContain('idx_tours_tour_type');
++ expect(await indexNames(orm, 'tour_waypoints')).not.toContain('idx_tour_waypoints_place');
++ } finally {
++ await orm.close(true);
++ }
++ }, 30000);
++});
diff --cc server/tests/unit/nest/assignments.controller.test.ts
index fd88a2f54,7f5a70704..db87ceb27
--- a/server/tests/unit/nest/assignments.controller.test.ts
+++ b/server/tests/unit/nest/assignments.controller.test.ts
@@@ -47,24 -47,12 +47,24 @@@ describe('DayAssignmentsController (par
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:created', { assignment: { id: 9 } }, 'sock');
expect(reconcile).toHaveBeenCalledWith('5', 'sock');
});
+
- it('409 duplicate Tour assignment propagates without announcing a new assignment', () => {
++ it('409 duplicate Tour assignment propagates without announcing a new assignment', async () => {
+ const broadcast = vi.fn();
+ const reconcile = vi.fn();
- const createAssignment = vi.fn(() => { throw new ConflictException('Tour is already assigned to this day') });
++ const createAssignment = vi.fn().mockRejectedValue(new ConflictException('Tour is already assigned to this day'));
+ const controller = new DayAssignmentsController(svc({ createAssignment, broadcast, reconcile } as Partial<AssignmentsService>));
+
- expect(thrown(() => controller.create(user, '5', '3', { place_id: 42 }))).toMatchObject({ status: 409 });
++ expect(await thrownAsync(() => controller.create(user, '5', '3', { place_id: 42 }))).toMatchObject({ status: 409 });
+ expect(createAssignment).toHaveBeenCalledWith('3', 42, undefined);
+ expect(broadcast).not.toHaveBeenCalled();
+ expect(reconcile).not.toHaveBeenCalled();
+ });
});
- it('PUT /reorder 404 day, else reorders + broadcasts', () => {
- expect(thrown(() => new DayAssignmentsController(svc({ dayExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>)).reorder(user, '5', '3', { orderedIds: [1, 2] }))).toEqual({ status: 404, body: { error: 'Day not found' } });
+ it('PUT /reorder 404 day, else reorders + broadcasts', async () => {
+ expect(await thrownAsync(() => new DayAssignmentsController(svc({ dayExists: vi.fn().mockReturnValue(false) } as Partial<AssignmentsService>)).reorder(user, '5', '3', { orderedIds: [1, 2] }))).toEqual({ status: 404, body: { error: 'Day not found' } });
const reorderAssignments = vi.fn(); const broadcast = vi.fn();
- expect(new DayAssignmentsController(svc({ reorderAssignments, broadcast } as Partial<AssignmentsService>)).reorder(user, '5', '3', { orderedIds: [2, 1] }, 'sock')).toEqual({ success: true });
+ expect(await new DayAssignmentsController(svc({ reorderAssignments, broadcast } as Partial<AssignmentsService>)).reorder(user, '5', '3', { orderedIds: [2, 1] }, 'sock')).toEqual({ success: true });
expect(reorderAssignments).toHaveBeenCalledWith('3', [2, 1]);
expect(broadcast).toHaveBeenCalledWith('5', 'assignment:reordered', { dayId: 3, orderedIds: [2, 1] }, 'sock');
});
diff --cc server/tests/unit/nest/assignments.service.test.ts
index f25f9b28a,2a5bf1ca8..0adc0ad28
--- a/server/tests/unit/nest/assignments.service.test.ts
+++ b/server/tests/unit/nest/assignments.service.test.ts
@@@ -55,19 -51,47 +52,49 @@@ import { AssignmentsService } from '../
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
- import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
-
- const dbs = new DatabaseService(testDb);
- const realtime = new RealtimeService();
- const svc = new AssignmentsService(
- dbs,
- new PermissionsService(dbs),
- realtime,
- new QueryHelpersService(dbs),
- // Real collaborator rather than a stub: reconcile() runs after every mutation
- // and needs the same connection to see the rows these cases write.
- new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs)),
- );
+ import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photo-registration.service';
+ import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
+ import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity';
+ import {
+ createTestUnitOfWork, createTestAppSettingsRepo, createTestTagsRepo, createTestPlaceRatingsRepo,
+ createTestAssignmentParticipantsRepo, createTestDayAssignmentsRepo, createTestDaysRepo, createTestPlacesRepo,
+ createTestTripMembersRepo, createTestRoadtripViasRepo, sharedTestOrm, createTestTripsRepo,
+ } from '../../helpers/test-uow';
+ import {
+ createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo,
+ createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo,
+ } from '../../helpers/journey-repos';
++import { createTestToursRepo, createTour } from '../../helpers/tours-repos';
+
+ let svc: AssignmentsService;
+ beforeAll(async () => {
+ const realtime = new RealtimeService();
+ svc = new AssignmentsService(
+ // Plan 4 Task 2 — AssignmentsService's own canAccessTrip delegate is now
+ // TripsRepository.findAccessible, in the same constructor slot.
+ await createTestTripsRepo(testDb),
+ new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
+ realtime,
+ new QueryHelpersService(await createTestTagsRepo(testDb), await createTestPlaceRatingsRepo(testDb), await createTestAssignmentParticipantsRepo(testDb)),
+ // Real collaborator rather than a stub: reconcile() runs after every mutation
+ // and needs the same connection to see the rows these cases write.
+ new JourneyDomainService(
+ realtime, new TrekPhotoRegistrationService((await sharedTestOrm(testDb)).repo(TrekPhotos), (await sharedTestOrm(testDb)).repo(TripPhotos), await createTestJourneyPhotosRepo(testDb)), await createTestUnitOfWork(testDb),
+ await createTestJourneysRepo(testDb), await createTestJourneyContributorsRepo(testDb),
+ await createTestJourneyTripsRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestTripsRepo(testDb),
+ // Plan 3g Task 2 constructor-ripple: JourneyPhotosRepository/JourneyEntryPhotosRepository/PlacesRepository.
+ await createTestJourneyPhotosRepo(testDb), await createTestJourneyEntryPhotosRepo(testDb), await createTestPlacesRepo(testDb),
+ ),
+ await createTestUnitOfWork(testDb),
+ await createTestDayAssignmentsRepo(testDb),
+ await createTestAssignmentParticipantsRepo(testDb),
+ await createTestDaysRepo(testDb),
+ await createTestPlacesRepo(testDb),
+ await createTestTripMembersRepo(testDb),
+ await createTestRoadtripViasRepo(testDb),
++ await createTestToursRepo(testDb),
+ );
+ });
/**
* canEdit only reads trip.user_id, so the case below hands it just that field.
@@@ -100,11 -119,6 +122,12 @@@ function fixture()
return { user, trip, day, place };
}
- function addTourFacet(placeId: number) {
- testDb.prepare("INSERT OR IGNORE INTO tour_types (key, label_key, icon, color) VALUES ('hike', 'hike', 'Mountain', '#000000')").run();
- testDb.prepare("INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')").run(placeId);
++/** Makes `placeId` a Tour: a `tours` facet row plus the route it was planned along. */
++function addTourFacet(placeId: number, routeGeometry = '[[48.1,11.5],[48.2,11.6]]') {
++ testDb.prepare('UPDATE places SET route_geometry = ? WHERE id = ?').run(routeGeometry, placeId);
++ createTour(testDb, placeId);
+}
+
// ── verifyTripAccess / canEdit ────────────────────────────────────────────────
describe('verifyTripAccess', () => {
@@@ -196,43 -264,9 +273,63 @@@ describe('createAssignment', () =>
});
// The same compact tag projection as listDayAssignments — id/name/color/
// created_at only, no user_id — so both read paths share one wire shape.
- expect(a!.place.tags).toEqual([{ id: tag.id, name: 'museum', color: '#10b981', created_at: (tag as { created_at?: string }).created_at }]);
+ expect((await a!).place.tags).toEqual([{ id: tag.id, name: 'museum', color: '#10b981', created_at: (tag as { created_at?: string }).created_at }]);
void trip;
});
+
- it('ASG-SVC-031: rejects a duplicate Tour assignment on the same day but allows another day and ordinary Place duplicates', () => {
++ it('ASG-SVC-031: rejects a duplicate Tour assignment on the same day but allows another day and ordinary Place duplicates', async () => {
+ const { trip, day, place: tourPlace } = fixture();
+ const secondDay = createDay(testDb, trip.id);
+ const ordinaryPlace = createPlace(testDb, trip.id, { name: 'Ordinary place' });
+ addTourFacet(tourPlace.id);
+
- const firstTourAssignment = svc.createAssignment(day.id, tourPlace.id);
- expect(() => svc.createAssignment(day.id, tourPlace.id)).toThrow(ConflictException);
- const otherDayTourAssignment = svc.createAssignment(secondDay.id, tourPlace.id);
++ const firstTourAssignment = await svc.createAssignment(day.id, tourPlace.id);
++ await expect(svc.createAssignment(day.id, tourPlace.id)).rejects.toThrow(ConflictException);
++ await expect(svc.createAssignment(day.id, tourPlace.id)).rejects.toThrow('Tour is already assigned to this day');
++ const otherDayTourAssignment = await svc.createAssignment(secondDay.id, tourPlace.id);
+ expect(firstTourAssignment?.day_id).toBe(day.id);
+ expect(otherDayTourAssignment?.day_id).toBe(secondDay.id);
+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE place_id = ?').get(tourPlace.id)).toEqual({ n: 2 });
+
- svc.createAssignment(day.id, ordinaryPlace.id);
- svc.createAssignment(day.id, ordinaryPlace.id);
++ await svc.createAssignment(day.id, ordinaryPlace.id);
++ await svc.createAssignment(day.id, ordinaryPlace.id);
+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE place_id = ?').get(ordinaryPlace.id)).toEqual({ n: 2 });
+ });
+
+ it('ASG-SVC-032: near-concurrent Tour assignments serialize to one row and one conflict', async () => {
+ const { day, place } = fixture();
+ addTourFacet(place.id);
+
+ const results = await Promise.allSettled([
- Promise.resolve().then(() => svc.createAssignment(day.id, place.id)),
- Promise.resolve().then(() => svc.createAssignment(day.id, place.id)),
++ svc.createAssignment(day.id, place.id),
++ svc.createAssignment(day.id, place.id),
+ ]);
+
+ expect(results.filter(result => result.status === 'fulfilled')).toHaveLength(1);
+ const rejected = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
+ expect(rejected).toHaveLength(1);
+ expect(rejected[0].reason).toBeInstanceOf(ConflictException);
+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM day_assignments WHERE day_id = ? AND place_id = ?').get(day.id, place.id)).toEqual({ n: 1 });
+ });
++
++ it('ASG-SVC-048: a Tour stop carries its facet id and route geometry, an ordinary stop nulls both', async () => {
++ const { trip, day, place: tourPlace } = fixture();
++ const ordinaryPlace = createPlace(testDb, trip.id, { name: 'Ordinary place' });
++ // Geometry on a plain place (an imported track) must not leak into the Tour fields.
++ testDb.prepare('UPDATE places SET route_geometry = ? WHERE id = ?').run('[[1,2],[3,4]]', ordinaryPlace.id);
++ addTourFacet(tourPlace.id, '[[47,11],[47.5,11.5]]');
++
++ const tour = await svc.createAssignment(day.id, tourPlace.id);
++ const ordinary = await svc.createAssignment(day.id, ordinaryPlace.id);
++ expect(tour).toMatchObject({ tour_place_id: tourPlace.id, tour_route_geometry: '[[47,11],[47.5,11.5]]' });
++ expect(ordinary).toMatchObject({ tour_place_id: null, tour_route_geometry: null });
++
++ const list = await svc.listDayAssignments(day.id);
++ expect(list.map(a => [a.tour_place_id, a.tour_route_geometry])).toEqual([
++ [tourPlace.id, '[[47,11],[47.5,11.5]]'],
++ [null, null],
++ ]);
++ });
});
// ── listDayAssignments ────────────────────────────────────────────────────────
@@@ -334,10 -368,10 +431,34 @@@ describe('moveAssignment', () =>
const { trip, day, place } = fixture();
const target = createDay(testDb, trip.id);
const a = createDayAssignment(testDb, day.id, place.id, { order_index: 7 });
- expect(svc.moveAssignment(a.id, target.id, undefined).assignment!.order_index).toBe(0);
- expect(svc.moveAssignment(a.id, day.id, null).assignment!.order_index).toBe(0);
- expect(svc.moveAssignment(a.id, target.id, 0).assignment!.order_index).toBe(0);
+ expect((await svc.moveAssignment(a.id, target.id, undefined)).assignment!.order_index).toBe(0);
+ expect((await svc.moveAssignment(a.id, day.id, null)).assignment!.order_index).toBe(0);
+ expect((await svc.moveAssignment(a.id, target.id, 0)).assignment!.order_index).toBe(0);
+ });
++
++ it('ASG-SVC-049: refuses to move a Tour onto a day that already holds it, and leaves the row where it was', async () => {
++ const { trip, day, place } = fixture();
++ const target = createDay(testDb, trip.id);
++ addTourFacet(place.id);
++ createDayAssignment(testDb, target.id, place.id);
++ const a = createDayAssignment(testDb, day.id, place.id, { order_index: 3 });
++
++ await expect(svc.moveAssignment(a.id, target.id, 0)).rejects.toThrow(ConflictException);
++ expect(testDb.prepare('SELECT day_id, order_index FROM day_assignments WHERE id = ?').get(a.id)).toEqual({ day_id: day.id, order_index: 3 });
++ });
++
++ it('ASG-SVC-050: a Tour may be reordered within its own day, and an ordinary place may join a day that already holds it', async () => {
++ const { trip, day, place } = fixture();
++ const target = createDay(testDb, trip.id);
++ addTourFacet(place.id);
++ const tour = createDayAssignment(testDb, day.id, place.id, { order_index: 0 });
++ expect((await svc.moveAssignment(tour.id, day.id, 2)).assignment).toMatchObject({ day_id: day.id, order_index: 2 });
++
++ const ordinary = createPlace(testDb, trip.id, { name: 'Ordinary place' });
++ createDayAssignment(testDb, target.id, ordinary.id);
++ const second = createDayAssignment(testDb, day.id, ordinary.id);
++ expect((await svc.moveAssignment(second.id, target.id, 1)).assignment).toMatchObject({ day_id: target.id });
+ });
});
// ── participants ──────────────────────────────────────────────────────────────
diff --cc server/tests/unit/nest/common/rowShape.test.ts
index a8ac363f3,1c3ed1a17..8d22870d8
--- a/server/tests/unit/nest/common/rowShape.test.ts
+++ b/server/tests/unit/nest/common/rowShape.test.ts
@@@ -30,10 -48,14 +48,16 @@@ function makeRow(overrides: Partial<Ass
transport_mode: 'walk',
google_place_id: 'ChIJLU7jZClu5kcR4PcOOO6p3I0',
google_ftid: '0x47e66e2c94e34e2d:0x8ddca9ee380ef7e0',
+ osm_id: null,
+ amap_poi_id: null,
website: 'https://eiffel-tower.com',
phone: '+33 1 2345 6789',
+ stop_type: null,
+ fill_percent: null,
++ tour_place_id: null,
++ tour_route_geometry: null,
...overrides,
- } as AssignmentRow;
+ };
}
const sampleTags: Partial<Tag>[] = [
@@@ -88,6 -110,6 +112,13 @@@ describe('formatAssignmentWithPlace', (
expect(result.place.category).toBeNull();
});
++ it('keeps the Tour facet fields at the assignment level, null for an ordinary place', () => {
++ expect(formatAssignmentWithPlace(makeRow(), [], [])).toMatchObject({ tour_place_id: null, tour_route_geometry: null });
++ const geometry = '[[48.1,11.5],[48.2,11.6]]';
++ const tour = formatAssignmentWithPlace(makeRow({ tour_place_id: 100, tour_route_geometry: geometry }), [], []);
++ expect(tour).toMatchObject({ tour_place_id: 100, tour_route_geometry: geometry });
++ });
++
it('passes tags and participants through untouched', () => {
const result = formatAssignmentWithPlace(makeRow(), sampleTags, sampleParticipants);
expect(result.place.tags).toEqual(sampleTags);
diff --cc server/tests/unit/nest/day-removal.service.test.ts
index e59621d59,e13c9e687..7748b3d2e
--- a/server/tests/unit/nest/day-removal.service.test.ts
+++ b/server/tests/unit/nest/day-removal.service.test.ts
@@@ -45,23 -38,78 +38,80 @@@ import { QueryHelpersService } from '..
import { DaysService } from '../../../src/nest/days/days.service';
import { DayRemovalService, DayDeleteError, LAST_DAY_MESSAGE, type DayRemoval } from '../../../src/nest/days/day-removal.service';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
- import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
+ import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photo-registration.service';
import { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
import { AccommodationsService, type MirrorSender } from '../../../src/nest/accommodations/accommodations.service';
+ import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
+ import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity';
+ import {
+ createTestUnitOfWork, createTestAppSettingsRepo, createTestTagsRepo, createTestPlaceRatingsRepo,
+ createTestAssignmentParticipantsRepo, createTestDayAssignmentsRepo, createTestDaysRepo, createTestPlacesRepo,
+ createTestTripMembersRepo, createTestRoadtripViasRepo, createTestDayAccommodationsRepo, createTestReservationsRepo,
+ createTestReservationEndpointsRepo, createTestDayNotesRepo, createTestRoadtripDayBoundariesRepo,
+ sharedTestOrm, createTestTripsRepo,
+ } from '../../helpers/test-uow';
+ import { createTestBudgetItemsRepo } from '../../helpers/files-repos';
+ import {
+ createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo,
+ createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo,
+ } from '../../helpers/journey-repos';
++import { createTestToursRepo } from '../../helpers/tours-repos';
+
+ let days: DaysService;
+ let journey: JourneyDomainService;
+ let assignments: AssignmentsService;
+ let accommodations: AccommodationsService;
+ let removal: DayRemovalService;
+
+ /** A DayRemovalService over the test connection, with the accommodations service given. */
+ async function removalWith(acc: AccommodationsService): Promise<DayRemovalService> {
+ return new DayRemovalService(
+ days, acc, assignments, await createTestUnitOfWork(testDb),
+ await createTestDaysRepo(testDb), await createTestDayAccommodationsRepo(testDb),
+ await createTestRoadtripDayBoundariesRepo(testDb), await createTestTripsRepo(testDb),
+ );
+ }
- const dbs = new DatabaseService(testDb);
- const permissions = new PermissionsService(dbs);
- const realtime = new RealtimeService();
- const queryHelpers = new QueryHelpersService(dbs);
- const days = new DaysService(dbs, permissions, realtime, queryHelpers);
- const journey = new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs));
- const assignments = new AssignmentsService(dbs, permissions, realtime, queryHelpers, journey);
- const accommodations = new AccommodationsService(dbs, permissions, realtime, assignments);
- const removal = new DayRemovalService(dbs, days, accommodations, assignments);
-
- beforeAll(() => {
- createTables(testDb);
- runMigrations(testDb);
+ beforeAll(async () => {
+ const permissions = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
+ const realtime = new RealtimeService();
+ const queryHelpers = new QueryHelpersService(await createTestTagsRepo(testDb), await createTestPlaceRatingsRepo(testDb), await createTestAssignmentParticipantsRepo(testDb));
+ const t = await sharedTestOrm(testDb);
+ days = new DaysService(
+ permissions, realtime, queryHelpers, await createTestUnitOfWork(testDb),
+ await createTestDaysRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestDayNotesRepo(testDb),
+ await createTestTripsRepo(testDb), await createTestReservationsRepo(testDb), await createTestReservationEndpointsRepo(testDb),
+ await createTestDayAccommodationsRepo(testDb), await createTestRoadtripViasRepo(testDb), await createTestRoadtripDayBoundariesRepo(testDb),
+ );
+ journey = new JourneyDomainService(
+ realtime, new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), await createTestJourneyPhotosRepo(testDb)), await createTestUnitOfWork(testDb),
+ await createTestJourneysRepo(testDb), await createTestJourneyContributorsRepo(testDb),
+ await createTestJourneyTripsRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestTripsRepo(testDb),
+ await createTestJourneyPhotosRepo(testDb), await createTestJourneyEntryPhotosRepo(testDb), await createTestPlacesRepo(testDb),
+ );
+ assignments = new AssignmentsService(
+ await createTestTripsRepo(testDb), permissions, realtime, queryHelpers, journey,
+ await createTestUnitOfWork(testDb),
+ await createTestDayAssignmentsRepo(testDb),
+ await createTestAssignmentParticipantsRepo(testDb),
+ await createTestDaysRepo(testDb),
+ await createTestPlacesRepo(testDb),
+ await createTestTripMembersRepo(testDb),
+ await createTestRoadtripViasRepo(testDb),
++ await createTestToursRepo(testDb),
+ );
+ accommodations = new AccommodationsService(
+ permissions, realtime, assignments, await createTestUnitOfWork(testDb),
+ await createTestTripsRepo(testDb),
+ await createTestDayAccommodationsRepo(testDb),
+ await createTestDayAssignmentsRepo(testDb),
+ await createTestPlacesRepo(testDb),
+ await createTestDaysRepo(testDb),
+ await createTestRoadtripViasRepo(testDb),
+ await createTestReservationsRepo(testDb),
+ await createTestBudgetItemsRepo(testDb),
+ );
+ removal = await removalWith(accommodations);
});
beforeEach(() => {
diff --cc server/tests/unit/nest/days.service.test.ts
index f8e5785bc,a1907b4b5..d0dc4933a
--- a/server/tests/unit/nest/days.service.test.ts
+++ b/server/tests/unit/nest/days.service.test.ts
@@@ -50,11 -48,9 +48,10 @@@ vi.mock('../../../src/config', () => (
}));
vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
- import { createTables } from '../../../src/db/schema';
- import { runMigrations } from '../../../src/db/migrations';
+ import { db as testDb } from '../../../src/db/database';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, createDayAssignment, createDayAccommodation, createDayNote, createTag, createReservation } from '../../helpers/factories';
- import { DatabaseService } from '../../../src/nest/database/database.service';
++import { createTour } from '../../helpers/tours-repos';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { DaysService, DayReorderError, DayAppendError, NO_DATES_MESSAGE, addDays } from '../../../src/nest/days/days.service';
// Was days.bridge, deleted with the other three that had no consumer outside the
@@@ -104,26 -125,7 +126,25 @@@ describe('verifyTripAccess', () =>
// ── getAssignmentsForDay ──────────────────────────────────────────────────────
describe('getAssignmentsForDay', () => {
- it('projects only facet-backed Tour geometry in both day read paths', () => {
++ it('DAY-SVC-TOUR-001: projects only facet-backed Tour geometry in both day read paths', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const tour = createPlace(testDb, trip.id, { name: 'Hike', lat: 48.1, lng: 11.1 });
+ const track = createPlace(testDb, trip.id, { name: 'Legacy track', lat: 48.2, lng: 11.2 });
+ const geometry = JSON.stringify([[48.1, 11.1], [48.3, 11.3]]);
+ testDb.prepare('UPDATE places SET route_geometry = ? WHERE id IN (?, ?)').run(geometry, tour.id, track.id);
- testDb.prepare("INSERT INTO tour_types (key, label_key, icon, color) VALUES ('hike', 'hike', 'hike', '#000000')").run();
- testDb.prepare("INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')").run(tour.id);
++ createTour(testDb, tour.id);
+ createDayAssignment(testDb, day.id, tour.id, { order_index: 0 });
+ createDayAssignment(testDb, day.id, track.id, { order_index: 1 });
+
- for (const assignments of [svc.getAssignmentsForDay(day.id), svc.list(trip.id).days[0].assignments]) {
++ for (const assignments of [await svc.getAssignmentsForDay(day.id), (await svc.list(trip.id)).days[0].assignments]) {
+ expect(assignments?.[0]).toMatchObject({ tour_place_id: tour.id, tour_route_geometry: geometry });
+ expect(assignments?.[1]).toMatchObject({ tour_place_id: null, tour_route_geometry: null });
+ }
+ });
+
- it('DAY-SVC-003 — returns empty array when day has no assignments', () => {
+ it('DAY-SVC-003 — returns empty array when day has no assignments', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const day = createDay(testDb, trip.id) as any;
diff --cc server/tests/unit/nest/places.controller.test.ts
index 316570a6f,90b580663..dac2cea9e
--- a/server/tests/unit/nest/places.controller.test.ts
+++ b/server/tests/unit/nest/places.controller.test.ts
@@@ -312,6 -274,26 +304,26 @@@ describe('PlacesController (parity wit
expect(onDeleted.mock.invocationCallOrder[0]).toBeLessThan(removeMany.mock.invocationCallOrder[0]);
});
+ // invocationCallOrder above only proves the hook was CALLED first — a mock
+ // that resolves synchronously can't tell an awaited hook from a detached
+ // (fire-and-forget) one, since both invoke onDeleted() before removeMany() is
+ // invoked either way. A hook stubbed with a real macrotask hop, and a delete
+ // that records when it actually RUNS, catches a regression to detached.
+ it('the journey hook actually finishes before the delete runs, not just gets called first', async () => {
+ const order: string[] = [];
+ const onDeleted = vi.fn(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ order.push('hook');
+ });
+ const removeMany = vi.fn(async () => {
+ order.push('delete');
- return { deleted: [1], cancelled: { reservationIds: [], budgetItemIds: [] } };
++ return { deleted: [1], deletedTourPlaceIds: [], cancelled: { reservationIds: [], budgetItemIds: [] } };
+ });
+ const s = svc({ removeMany, onDeleted, scopedIds: vi.fn().mockReturnValue([1]), broadcast: vi.fn() } as Partial<PlacesService>);
+ await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1] });
+ expect(order).toEqual(['hook', 'delete']);
+ });
+
// #1298: the link is gone once the place is, so the ids have to be read first.
it('announces the expenses the deleted places took with them', async () => {
const removeMany = vi.fn().mockReturnValue({ deleted: [1, 2], cancelled: { reservationIds: [], budgetItemIds: [] } });
@@@ -507,14 -489,30 +519,34 @@@
expect(await thrownAsync(() => new PlacesController(svc({ remove, onDeleted } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).remove(user, '5', '9'))).toEqual({ status: 404, body: { error: 'Place not found' } });
expect(onDeleted).toHaveBeenCalledWith(9);
expect(onDeleted.mock.invocationCallOrder[0]).toBeLessThan(remove.mock.invocationCallOrder[0]);
- const s = svc({ remove: vi.fn().mockReturnValue({ deleted: true, cancelled: { reservationIds: [], budgetItemIds: [] } }), broadcast: vi.fn() } as Partial<PlacesService>);
- expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9')).toEqual({ success: true });
+ const s = svc({ remove: vi.fn().mockReturnValue({ deleted: true, deletedTourPlaceIds: [9], cancelled: { reservationIds: [], budgetItemIds: [] } }), broadcast: vi.fn() } as Partial<PlacesService>);
+ expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9')).toEqual({ success: true, tourPlaceIds: [9] });
+ });
+
+ it('requires place_edit for single Place/Tour deletion', () => {
+ expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, PlacesController.prototype.remove)).toBe('place_edit');
});
+ // invocationCallOrder in the case above only proves the hook was CALLED
+ // first — a synchronously-resolving mock can't tell an awaited hook from a
+ // detached (fire-and-forget) one. A hook stubbed with a real macrotask hop,
+ // and a delete that records when it actually RUNS, catches a regression to
+ // detached (the trap this pins: onDeleted must finish before the DELETE).
+ it('DELETE /:id — the journey hook actually finishes before the delete runs, not just gets called first', async () => {
+ const order: string[] = [];
+ const onDeleted = vi.fn(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ order.push('hook');
+ });
+ const remove = vi.fn(async () => {
+ order.push('delete');
- return { deleted: true, cancelled: { reservationIds: [], budgetItemIds: [] } };
++ return { deleted: true, deletedTourPlaceIds: [], cancelled: { reservationIds: [], budgetItemIds: [] } };
+ });
+ const s = svc({ remove, onDeleted, broadcast: vi.fn() } as Partial<PlacesService>);
+ await new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9');
+ expect(order).toEqual(['hook', 'delete']);
+ });
+
it('DELETE /:id announces the booking and the expense a cancelled night took down', async () => {
// place:deleted says nothing about either, and an expense linked by
// reservation_id is not one linkedExpenseIds finds.
diff --cc server/tests/unit/nest/places.service.test.ts
index 72a813f24,25838c8f0..530469f93
--- a/server/tests/unit/nest/places.service.test.ts
+++ b/server/tests/unit/nest/places.service.test.ts
@@@ -145,21 -187,7 +187,20 @@@ describe('list', () =>
expect(places).toHaveLength(2);
});
- it('PLACE-SVC-TOURS-002 — identifies Tours by their facet in the ordinary Place read model', () => {
++ it('PLACE-SVC-TOURS-002 — identifies Tours by their facet in the ordinary Place read model', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const tour = createPlace(testDb, trip.id, { name: 'Facet-backed tour' }) as any;
+ const place = createPlace(testDb, trip.id, { name: 'Ordinary place' }) as any;
- testDb.prepare(`INSERT OR IGNORE INTO tour_types (key, label_key, icon, color) VALUES ('hike', 'test', 'Mountain', '#000000')`).run();
+ testDb.prepare(`INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')`).run(tour.id);
+
- const byId = new Map((svc.list(String(trip.id), {}) as any[]).map(item => [item.id, item]));
++ const byId = new Map(((await svc.list(String(trip.id), {})) as any[]).map(item => [item.id, item]));
+
+ expect(byId.get(tour.id)).toMatchObject({ tour_place_id: tour.id });
+ expect(byId.get(place.id)).toMatchObject({ tour_place_id: null });
+ });
+
- it('PLACE-SVC-003 — does not return places from other trips', () => {
+ it('PLACE-SVC-003 — does not return places from other trips', async () => {
const { user } = createUser(testDb);
const t1 = createTrip(testDb, user.id);
const t2 = createTrip(testDb, user.id);
@@@ -494,43 -647,6 +660,42 @@@ describe('remove', () =>
expect(testDb.prepare('SELECT id FROM day_assignments WHERE day_id = ?').all(day.id)).toEqual([]);
});
+ it('PLACE-SVC-TOURS-001 — reports Tour deletion and cascades only its facet, waypoints, assignments, and links', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const day = createDay(testDb, trip.id);
+ const tour = createPlace(testDb, trip.id, { name: 'Tour to delete' }) as any;
+ const keptTour = createPlace(testDb, trip.id, { name: 'Tour to keep' }) as any;
+ const keptPlace = createPlace(testDb, trip.id, { name: 'Ordinary place' }) as any;
- testDb.prepare(`INSERT OR IGNORE INTO tour_types (key, label_key, icon, color) VALUES ('hike', 'test', 'Mountain', '#000000')`).run();
+ for (const place of [tour, keptTour]) {
+ testDb.prepare(`INSERT INTO tours (place_id, tour_type, max_hiking_difficulty) VALUES (?, 'hike', 4)`).run(place.id);
+ testDb.prepare(`INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (?, 48, 11, 'start', 0)`).run(place.id);
+ testDb.prepare('INSERT INTO day_assignments (day_id, place_id, order_index) VALUES (?, ?, 0)').run(day.id, place.id);
+ }
+ const tourFileId = Number(testDb.prepare(`
+ INSERT INTO trip_files (trip_id, place_id, filename, original_name) VALUES (?, ?, 'tour.gpx', 'tour.gpx')
+ `).run(trip.id, tour.id).lastInsertRowid);
+ const keptFileId = Number(testDb.prepare(`
+ INSERT INTO trip_files (trip_id, place_id, filename, original_name) VALUES (?, ?, 'kept.gpx', 'kept.gpx')
+ `).run(trip.id, keptTour.id).lastInsertRowid);
+ testDb.prepare('INSERT INTO file_links (file_id, place_id) VALUES (?, ?)').run(tourFileId, tour.id);
+
+ const result = await svc.remove(String(trip.id), String(tour.id));
+
+ expect(result).toMatchObject({ deleted: true, deletedTourPlaceIds: [tour.id] });
+ expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(tour.id)).toBeUndefined();
+ expect(testDb.prepare('SELECT place_id FROM tours WHERE place_id = ?').get(tour.id)).toBeUndefined();
+ expect(testDb.prepare('SELECT id FROM tour_waypoints WHERE place_id = ?').all(tour.id)).toEqual([]);
+ expect(testDb.prepare('SELECT id FROM day_assignments WHERE place_id = ?').all(tour.id)).toEqual([]);
+ expect(testDb.prepare('SELECT id, place_id FROM trip_files WHERE id = ?').get(tourFileId)).toMatchObject({ id: tourFileId, place_id: null });
+ expect(testDb.prepare('SELECT id FROM file_links WHERE file_id = ?').all(tourFileId)).toEqual([]);
+ expect(testDb.prepare('SELECT place_id FROM tours WHERE place_id = ?').get(keptTour.id)).toBeTruthy();
+ expect(testDb.prepare('SELECT id FROM tour_waypoints WHERE place_id = ?').all(keptTour.id)).toHaveLength(1);
+ expect(testDb.prepare('SELECT id FROM day_assignments WHERE place_id = ?').all(keptTour.id)).toHaveLength(1);
+ expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(keptPlace.id)).toBeTruthy();
+ expect(testDb.prepare('SELECT id, place_id FROM trip_files WHERE id = ?').get(keptFileId)).toMatchObject({ id: keptFileId, place_id: keptTour.id });
+ });
+
it('PLACE-SVC-019e — a place with no booking is untouched by that', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
@@@ -607,25 -752,6 +801,24 @@@
// ── removeMany ────────────────────────────────────────────────────────────────
describe('removeMany', () => {
+ it('PLACE-SVC-TOURS-003 — mixed bulk deletion reports only the deleted Tour facets', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id);
+ const tour = createPlace(testDb, trip.id, { name: 'Tour to delete' }) as any;
+ const ordinary = createPlace(testDb, trip.id, { name: 'Ordinary place' }) as any;
+ const keptTour = createPlace(testDb, trip.id, { name: 'Tour to keep' }) as any;
- testDb.prepare(`INSERT OR IGNORE INTO tour_types (key, label_key, icon, color) VALUES ('hike', 'test', 'Mountain', '#000000')`).run();
+ for (const place of [tour, keptTour]) {
+ testDb.prepare(`INSERT INTO tours (place_id, tour_type) VALUES (?, 'hike')`).run(place.id);
+ }
+
+ const result = await svc.removeMany(String(trip.id), [ordinary.id, tour.id]);
+
+ expect(result.deleted).toEqual([ordinary.id, tour.id]);
+ expect(result.deletedTourPlaceIds).toEqual([tour.id]);
+ expect(testDb.prepare('SELECT place_id FROM tours WHERE place_id = ?').get(keptTour.id)).toBeTruthy();
+ expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(keptTour.id)).toBeTruthy();
+ });
+
it('PLACE-SVC-056 — deletes the trip-scoped ids in one transaction and reports them', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
diff --cc server/tests/unit/nest/tours.controller.test.ts
index 6730c0f57,000000000..d550232f5
mode 100644,000000..100644
--- a/server/tests/unit/nest/tours.controller.test.ts
+++ b/server/tests/unit/nest/tours.controller.test.ts
@@@ -1,68 -1,0 +1,228 @@@
- import { describe, expect, it, vi } from 'vitest';
++/**
++ * ToursController and ToursImportController: route metadata, delegation to
++ * ToursService, and the GPX import's handler-level checks. The import is not
++ * guarded (a guard answers before multer drains the body and the client sees
++ * ECONNRESET), so its handler has to reproduce the guards' answers itself, in
++ * the same order and with the same bodies (parity with AddonGuard and
++ * TripAccessGuard).
++ */
+import 'reflect-metadata';
++import { describe, expect, it, vi } from 'vitest';
++import { HttpException, RequestMethod } from '@nestjs/common';
++import { GUARDS_METADATA, HTTP_CODE_METADATA, INTERCEPTORS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
+
- vi.mock('../../../src/config', () => { throw new Error('Config initialization is forbidden in mock-only tests'); });
- vi.mock('../../../src/db/database', () => { throw new Error('Legacy database imports are forbidden in mock-only tests'); });
- vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in mock-only tests'); });
- vi.mock('../../../src/nest/database/database.service', () => ({
- DatabaseService: vi.fn(() => { throw new Error('Database construction is forbidden in mock-only tests'); }),
++const { legacyDatabaseAccess } = vi.hoisted(() => ({
++ legacyDatabaseAccess: vi.fn((property: string | symbol): never => {
++ throw new Error(`Unexpected legacy database access: ${String(property)}`);
++ }),
++}));
++
++vi.mock('../../../src/config', () => ({
++ ENCRYPTION_KEY: 'test-only-inert-key',
++ JWT_SECRET: 'test-only-inert-secret',
++ updateJwtSecret: vi.fn(),
++}));
++vi.mock('../../../src/db/database', () => ({
++ db: new Proxy({}, {
++ get: (_target, property: string | symbol) => legacyDatabaseAccess(property),
++ }),
+}));
+vi.mock('../../../src/nest/permissions/permissions.service', () => ({ PermissionsService: class {} }));
+vi.mock('../../../src/nest/addons/addons.service', () => ({ AddonsService: class {} }));
++vi.mock('../../../src/nest/places/places.service', () => ({ PlacesService: class {} }));
+vi.mock('../../../src/nest/tours/tours.service', () => ({ ToursService: class {} }));
+vi.mock('../../../src/nest/auth/jwt-verify', () => ({ extractToken: vi.fn(), verifyJwtAndLoadUser: vi.fn() }));
- import { GUARDS_METADATA } from '@nestjs/common/constants';
++
+import type { TourCreateRequest } from '@trek/shared';
+import { ToursController } from '../../../src/nest/tours/tours.controller';
++import { ToursImportController } from '../../../src/nest/tours/tours-import.controller';
+import type { ToursService } from '../../../src/nest/tours/tours.service';
++import type { PlacesService } from '../../../src/nest/places/places.service';
++import type { AddonsService } from '../../../src/nest/addons/addons.service';
+import { AddonGuard } from '../../../src/nest/addons/addon.guard';
+import { JwtAuthGuard } from '../../../src/nest/auth/jwt-auth.guard';
- import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
++import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
+import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
++import type { User } from '../../../src/types';
+
+const request: TourCreateRequest = {
+ name: 'Ridge walk',
+ tour_type: 'hike' as const,
+ route_geometry: [[48, 11, 600], [48.02, 11.04, 630]] as [number, number, number][],
+ waypoints: [
+ { lat: 48, lng: 11, role: 'start' as const, sequence: 0 },
+ { lat: 48.02, lng: 11.04, role: 'end' as const, sequence: 1 },
+ ],
+ max_hiking_difficulty: 2,
+ duration_seconds: 3600,
+};
+
++const user = { id: 2, role: 'user', email: '[email protected]' } as User;
++const trip = { id: 7, user_id: 1 };
++const file = { buffer: Buffer.from('<gpx/>'), originalname: 'ridge.gpx' } as Express.Multer.File;
++
++async function thrownAsync(fn: () => Promise<unknown>): Promise<{ status: number; body: unknown }> {
++ try { await fn(); } catch (err) {
++ expect(err).toBeInstanceOf(HttpException);
++ const e = err as HttpException;
++ return { status: e.getStatus(), body: e.getResponse() };
++ }
++ throw new Error('expected throw');
++}
++
++function importFixture(o: { addon?: boolean; trip?: typeof trip | undefined; canEdit?: boolean; result?: unknown } = {}) {
++ const addons = { isAddonEnabled: vi.fn(async () => o.addon ?? true) };
++ const places = {
++ verifyTripAccess: vi.fn(async () => ('trip' in o ? o.trip : trip)),
++ canEdit: vi.fn(async () => o.canEdit ?? true),
++ };
++ const result = 'result' in o ? o.result : { tours: [{ place_id: 42 }], caution: false, skipped: 0 };
++ const tours = { importGpxAsTour: vi.fn(async () => result) };
++ const controller = new ToursImportController(
++ tours as unknown as ToursService,
++ places as unknown as PlacesService,
++ addons as unknown as AddonsService,
++ );
++ return { addons, places, tours, controller, result };
++}
++
+describe('ToursController planner routes', () => {
++ it('does not access the legacy global database initializer', () => {
++ expect(legacyDatabaseAccess).not.toHaveBeenCalled();
++ });
++
+ it('TOURS-CTL-001: hides every Tours route behind the addon guard before auth', () => {
- const guards = Reflect.getMetadata(GUARDS_METADATA, ToursController) as unknown[];
- expect(guards).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);
++ expect(Reflect.getMetadata(PATH_METADATA, ToursController)).toBe('api/trips/:tripId/tours');
++ expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);
+ expect(Reflect.getMetadata(REQUIRE_ADDON, ToursController)).toEqual({ addonId: 'tours', label: 'Tours' });
+ });
+
- it('TOURS-CTL-002: POST /tours delegates the validated payload and socket id', () => {
++ it('TOURS-CTL-001b: routes, methods and write permissions', () => {
++ const routes = [
++ ['list', RequestMethod.GET, '/', undefined],
++ ['detail', RequestMethod.GET, ':placeId', undefined],
++ ['create', RequestMethod.POST, '/', 'place_edit'],
++ ['update', RequestMethod.PUT, ':placeId', 'place_edit'],
++ ] as const;
++ for (const [handler, method, path, permission] of routes) {
++ const fn = ToursController.prototype[handler];
++ expect(Reflect.getMetadata(METHOD_METADATA, fn)).toBe(method);
++ expect(Reflect.getMetadata(PATH_METADATA, fn)).toBe(path);
++ expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, fn)).toBe(permission);
++ }
++ // POST keeps Nest's default 201, as the PR's route answered.
++ expect(Reflect.getMetadata(HTTP_CODE_METADATA, ToursController.prototype.create)).toBeUndefined();
++ });
++
++ it('TOURS-CTL-002: POST /tours delegates the validated payload and socket id', async () => {
+ const result = { tour: { place_id: 1 }, waypoints: request.waypoints };
- const service = { createTour: vi.fn().mockReturnValue(result) } as unknown as ToursService;
++ const service = { createTour: vi.fn().mockResolvedValue(result) } as unknown as ToursService;
+ const controller = new ToursController(service);
+
- expect(controller.create('7', request, 'socket-1')).toBe(result);
++ expect(await controller.create('7', request, 'socket-1')).toBe(result);
+ expect(service.createTour).toHaveBeenCalledWith('7', request, 'socket-1');
+ });
+
- it('TOURS-CTL-003: GET /tours/:placeId delegates within the guarded trip', () => {
++ it('TOURS-CTL-003: GET /tours/:placeId delegates within the guarded trip', async () => {
+ const result = { tour: { place_id: 1 }, waypoints: request.waypoints };
- const service = { getTour: vi.fn().mockReturnValue(result) } as unknown as ToursService;
++ const service = { getTour: vi.fn().mockResolvedValue(result) } as unknown as ToursService;
+ const controller = new ToursController(service);
+
- expect(controller.detail('7', '1')).toBe(result);
++ expect(await controller.detail('7', '1')).toBe(result);
+ expect(service.getTour).toHaveBeenCalledWith('7', '1');
+ });
+
- it('TOURS-CTL-004: PUT /tours/:placeId delegates the validated payload and socket id', () => {
++ it('TOURS-CTL-004: PUT /tours/:placeId delegates the validated payload and socket id', async () => {
+ const result = { tour: { place_id: 1 }, waypoints: request.waypoints };
- const service = { updateTour: vi.fn().mockReturnValue(result) } as unknown as ToursService;
++ const service = { updateTour: vi.fn().mockResolvedValue(result) } as unknown as ToursService;
+ const controller = new ToursController(service);
+
- expect(controller.update('7', '1', request, 'socket-2')).toBe(result);
++ expect(await controller.update('7', '1', request, 'socket-2')).toBe(result);
+ expect(service.updateTour).toHaveBeenCalledWith('7', '1', request, 'socket-2');
+ });
++
++ it('TOURS-CTL-005: GET /tours wraps the list in { tours }', async () => {
++ const tours = [{ place_id: 1 }];
++ const service = { listTours: vi.fn().mockResolvedValue(tours) } as unknown as ToursService;
++
++ expect(await new ToursController(service).list('7')).toEqual({ tours });
++ expect(service.listTours).toHaveBeenCalledWith('7');
++ });
++});
++
++describe('ToursImportController (POST /api/trips/:tripId/tours/import/gpx)', () => {
++ it('TOURS-IMP-001: the multipart route carries only the JWT guard and checks the rest in the handler', () => {
++ expect(Reflect.getMetadata(PATH_METADATA, ToursImportController)).toBe('api/trips/:tripId/tours');
++ expect(Reflect.getMetadata(GUARDS_METADATA, ToursImportController)).toEqual([JwtAuthGuard]);
++ expect(Reflect.getMetadata(REQUIRE_ADDON, ToursImportController)).toBeUndefined();
++ const handler = ToursImportController.prototype.importGpx;
++ expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.POST);
++ expect(Reflect.getMetadata(PATH_METADATA, handler)).toBe('import/gpx');
++ expect(Reflect.getMetadata(GUARDS_METADATA, handler)).toBeUndefined();
++ expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handler)).toBeUndefined();
++ expect(Reflect.getMetadata(INTERCEPTORS_METADATA, handler)).toHaveLength(1);
++ });
++
++ it('TOURS-IMP-002: delegates the route trip, file and socket id and returns the service result', async () => {
++ const { controller, tours, places, result } = importFixture();
++
++ expect(await controller.importGpx(user, '7', file, 'socket')).toBe(result);
++ expect(places.verifyTripAccess).toHaveBeenCalledWith('7', user.id);
++ expect(places.canEdit).toHaveBeenCalledWith(trip, user);
++ expect(tours.importGpxAsTour).toHaveBeenCalledWith('7', file.buffer, 'ridge.gpx', 'socket');
++ });
++
++ it('TOURS-IMP-003: a duplicate-only import is a successful skipped result', async () => {
++ const allSkipped = { tours: [], caution: false, skipped: 2 };
++ const { controller } = importFixture({ result: allSkipped });
++ expect(await controller.importGpx(user, '7', file)).toBe(allSkipped);
++ });
++
++ it('TOURS-IMP-004: addon off is the AddonGuard 404 before any trip lookup', async () => {
++ const { controller, places, tours, addons } = importFixture({ addon: false });
++
++ expect(await thrownAsync(() => controller.importGpx(user, '7', file))).toEqual({
++ status: 404, body: { error: 'Tours addon is not enabled' },
++ });
++ expect(addons.isAddonEnabled).toHaveBeenCalledWith('tours');
++ expect(places.verifyTripAccess).not.toHaveBeenCalled();
++ expect(tours.importGpxAsTour).not.toHaveBeenCalled();
++ });
++
++ it('TOURS-IMP-005: an inaccessible trip is the TripAccessGuard 404 before any permission check', async () => {
++ const { controller, places, tours } = importFixture({ trip: undefined });
++
++ expect(await thrownAsync(() => controller.importGpx(user, '8', file))).toEqual({
++ status: 404, body: { error: 'Trip not found' },
++ });
++ expect(places.verifyTripAccess).toHaveBeenCalledWith('8', user.id);
++ expect(places.canEdit).not.toHaveBeenCalled();
++ expect(tours.importGpxAsTour).not.toHaveBeenCalled();
++ });
++
++ it('TOURS-IMP-006: without place_edit it is the TripAccessGuard 403, checked before the file', async () => {
++ const { controller, tours } = importFixture({ canEdit: false });
++
++ expect(await thrownAsync(() => controller.importGpx(user, '7', undefined))).toEqual({
++ status: 403, body: { error: 'No permission' },
++ });
++ expect(tours.importGpxAsTour).not.toHaveBeenCalled();
++ });
++
++ it('TOURS-IMP-007: 400 without a file', async () => {
++ const { controller, tours } = importFixture();
++
++ expect(await thrownAsync(() => controller.importGpx(user, '7', undefined))).toEqual({
++ status: 400, body: { error: 'No file uploaded' },
++ });
++ expect(tours.importGpxAsTour).not.toHaveBeenCalled();
++ });
++
++ it('TOURS-IMP-008: 400 when the GPX has no track or route', async () => {
++ const { controller } = importFixture({ result: null });
++
++ expect(await thrownAsync(() => controller.importGpx(user, '7', file))).toEqual({
++ status: 400, body: { error: 'No track or route found in GPX file' },
++ });
++ });
+});
diff --cc server/tests/unit/nest/tours.gpx.atomic.test.ts
index ad586a271,000000000..2a19b6dab
mode 100644,000000..100644
--- a/server/tests/unit/nest/tours.gpx.atomic.test.ts
+++ b/server/tests/unit/nest/tours.gpx.atomic.test.ts
@@@ -1,208 -1,0 +1,297 @@@
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
- import Database from 'better-sqlite3';
++/**
++ * The tours-mode GPX import end to end through the real PlacesService and
++ * ToursService over the migrated per-worker DB: the places, their track
++ * colours and their tours facets commit in one transaction (PlacesService's
++ * importPreparedGpx nests in ToursService's as a savepoint), any failure on
++ * the way rolls all of it back, and the realtime events go out only after the
++ * commit. Failures are injected with SQLite triggers on the real tables.
++ */
++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
+import { Logger } from '@nestjs/common';
+
++vi.mock('../../../src/db/database', async () => {
++ const { createSnapshotTestDb, buildDbMock } = await import('../../helpers/db-mock');
++ return buildDbMock(createSnapshotTestDb());
++});
+vi.mock('../../../src/config', () => ({
+ JWT_SECRET: 'test-secret',
+ ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
- updateJwtSecret: vi.fn(),
++ updateJwtSecret: () => {},
+}));
- vi.mock('../../../src/db/database', () => ({
- db: {
- prepare: () => { throw new Error('Legacy database access forbidden'); },
- exec: () => { throw new Error('Legacy database access forbidden'); },
- },
- }));
- vi.mock('../../../src/nest/database/database.service', () => ({ DatabaseService: class {} }));
- vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
+
++import { db as testDb } from '../../../src/db/database';
++import type { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service';
++import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
++import type { UsersRepository } from '../../../src/db/repositories/Users.repository';
++import type { UnitOfWork } from '../../../src/nest/database/unit-of-work';
++import { UnsplashService } from '../../../src/nest/unsplash/unsplash.service';
++import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
++import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
++import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
+import { PlacesService } from '../../../src/nest/places/places.service';
++import { MapsService } from '../../../src/nest/maps/maps.service';
++import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
++import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
++import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photo-registration.service';
+import { ToursService } from '../../../src/nest/tours/tours.service';
+import { gpxParser } from '../../../src/nest/places/places.helpers';
++import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
++import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity';
++import { resetTestDb } from '../../helpers/test-db';
++import { createTrip, createUser } from '../../helpers/factories';
++import { accommodationsOver } from '../../helpers/accommodations-service';
++import { makeStorageFixture } from '../../helpers/storage-fixture';
++import { noGoogleQuota } from '../../helpers/google-quota';
++import {
++ createTestUnitOfWork, createTestAppSettingsRepo, createTestUsersRepo, createTestTagsRepo, createTestPlaceRatingsRepo,
++ createTestAssignmentParticipantsRepo, createTestPlacesRepo, createTestTripMembersRepo, createTestDayAssignmentsRepo,
++ createTestCategoriesRepo, createTestTripsRepo, createTestCollectionPlacesRepo, sharedTestOrm,
++} from '../../helpers/test-uow';
++import { createTestBudgetItemsRepo } from '../../helpers/files-repos';
++import {
++ createTestJourneysRepo, createTestJourneyContributorsRepo, createTestJourneyTripsRepo, createTestJourneyEntriesRepo,
++ createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo,
++} from '../../helpers/journey-repos';
++import { createTestToursRepo, createTestTourWaypointsRepo } from '../../helpers/tours-repos';
+
+const mixedGpx = Buffer.from(`<gpx>
+ <wpt lat="1" lon="2"><name>Ignored POI</name></wpt>
+ <rte><desc>Route description</desc><rtept lat="48" lon="11"/><rtept lat="48.01" lon="11.01"/></rte>
+ <trk><name>Ridge</name><desc>Track description</desc><trkseg>
+ <trkpt lat="49" lon="12"><ele>100</ele></trkpt>
+ <trkpt lat="49.01" lon="12.01"><ele>150</ele></trkpt>
+ </trkseg><trkseg><trkpt lat="49.02" lon="12.02"><ele>120</ele></trkpt></trkseg></trk>
+</gpx>`);
+
- function makeHarness() {
- const raw = new Database(':memory:');
- raw.pragma('foreign_keys = ON');
- raw.exec(`
- CREATE TABLE places (id INTEGER PRIMARY KEY, trip_id TEXT, name TEXT, description TEXT,
- lat REAL, lng REAL, transport_mode TEXT, route_geometry TEXT, route_color TEXT,
- google_place_id TEXT, google_ftid TEXT, osm_id TEXT, amap_poi_id TEXT);
- CREATE TABLE tours (place_id INTEGER PRIMARY KEY REFERENCES places(id), tour_type TEXT,
- distance REAL, elevation_gain REAL, elevation_loss REAL, duration REAL,
- match_confidence REAL, max_hiking_difficulty INTEGER);
- CREATE TABLE tour_waypoints (id INTEGER PRIMARY KEY, tour_place_id INTEGER REFERENCES tours(place_id));
- `);
- const db = {
- connection: raw,
- prepare: (sql: string) => raw.prepare(sql),
- all: (sql: string, ...params: unknown[]) => raw.prepare(sql).all(...params),
- getPlaceWithTags: (id: number) => ({ ...raw.prepare('SELECT * FROM places WHERE id = ?').get(id) as object, tags: [] }),
- transaction: vi.fn(<Result>(write: (conn: Database.Database) => Result): Result => {
- expect(raw.inTransaction).toBe(false);
- return raw.transaction(() => write(raw))();
- }),
- };
- const broadcast = vi.fn();
- const places = new PlacesService(db as never, {} as never, { broadcast } as never,
- {} as never, {} as never, {} as never, {} as never, {} as never, {} as never, {} as never);
- return { raw, db, places, broadcast, tours: new ToursService(db as never, places) };
++const TRIGGERS = ['fail_facet', 'fail_place', 'fail_color'];
++
++/** The collaborator set the container hands PlacesService (the places.service.test.ts builder). */
++async function makePlacesService(): Promise<PlacesService> {
++ const photoCacheStub = { removeIfUnreferenced: vi.fn() } as unknown as PlacePhotoCacheService;
++ const noAppSettings = { getValue: async () => null } as unknown as AppSettingsRepository;
++ const noUsers = { getApiKeyColumn: async () => null } as unknown as UsersRepository;
++ const storage = makeStorageFixture('').storage;
++ const orm = await sharedTestOrm(testDb);
++ return new PlacesService(
++ new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
++ new RealtimeService(),
++ new MapsService(photoCacheStub, noAppSettings, noUsers, {} as never, {} as never, noGoogleQuota),
++ new QueryHelpersService(await createTestTagsRepo(testDb), await createTestPlaceRatingsRepo(testDb), await createTestAssignmentParticipantsRepo(testDb)),
++ new UnsplashService(await createTestAppSettingsRepo(testDb), await createTestUsersRepo(testDb), new RuntimeEnvService(), storage),
++ photoCacheStub,
++ new JourneyDomainService(
++ new RealtimeService(), new TrekPhotoRegistrationService(orm.repo(TrekPhotos), orm.repo(TripPhotos), await createTestJourneyPhotosRepo(testDb)), await createTestUnitOfWork(testDb),
++ await createTestJourneysRepo(testDb), await createTestJourneyContributorsRepo(testDb),
++ await createTestJourneyTripsRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestTripsRepo(testDb),
++ await createTestJourneyPhotosRepo(testDb), await createTestJourneyEntryPhotosRepo(testDb), await createTestPlacesRepo(testDb),
++ ),
++ storage,
++ await accommodationsOver(testDb), await createTestUnitOfWork(testDb),
++ await createTestPlacesRepo(testDb),
++ await createTestTagsRepo(testDb),
++ await createTestPlaceRatingsRepo(testDb),
++ await createTestTripMembersRepo(testDb),
++ await createTestDayAssignmentsRepo(testDb),
++ await createTestCategoriesRepo(testDb),
++ await createTestTripsRepo(testDb),
++ await createTestBudgetItemsRepo(testDb),
++ await createTestCollectionPlacesRepo(testDb),
++ );
+}
+
- describe('Tours GPX atomic persistence and postcommit publication', () => {
- let setup: ReturnType<typeof makeHarness>;
- beforeEach(() => { setup = makeHarness(); });
- afterEach(() => { setup.raw.close(); vi.restoreAllMocks(); });
++let uow: UnitOfWork;
++let places: PlacesService;
++let tours: ToursService;
++let tripId: string;
++let broadcast: MockInstance<PlacesService['broadcast']>;
++
++const count = (table: string) => (testDb.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n;
++
++beforeAll(async () => {
++ uow = await createTestUnitOfWork(testDb);
++ places = await makePlacesService();
++ tours = new ToursService(
++ uow, places, await createTestToursRepo(testDb), await createTestTourWaypointsRepo(testDb), await createTestPlacesRepo(testDb),
++ );
++});
++
++beforeEach(async () => {
++ resetTestDb(testDb);
++ (await sharedTestOrm(testDb)).clear();
++ const { user } = createUser(testDb);
++ tripId = String(createTrip(testDb, user.id).id);
++ broadcast = vi.spyOn(places, 'broadcast').mockImplementation(() => {});
++});
++
++afterEach(() => {
++ for (const name of TRIGGERS) testDb.exec(`DROP TRIGGER IF EXISTS ${name}`);
++ vi.restoreAllMocks();
++});
++
++afterAll(() => { testDb.close(); });
+
++describe('Tours GPX atomic persistence and postcommit publication', () => {
+ function expectEmpty() {
- for (const table of ['places', 'tours', 'tour_waypoints']) {
- expect(setup.raw.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get()).toEqual({ count: 0 });
- }
- expect(setup.broadcast).not.toHaveBeenCalled();
++ for (const table of ['places', 'tours', 'tour_waypoints']) expect(count(table)).toBe(0);
++ expect(broadcast).not.toHaveBeenCalled();
+ }
+
- it('commits routes, tracks, colors and facets once before publishing, without Planner waypoints', () => {
- setup.broadcast.mockImplementation((tripId, event, payload, socketId) => {
- expect(setup.raw.inTransaction).toBe(false);
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM tours').get()).toEqual({ count: 2 });
- expect(tripId).toBe('7');
- if (event === 'tours:changed') {
- expect(payload).toEqual({ placeIds: [1, 2] });
- expect(socketId).toBe('socket');
- } else {
- expect(event).toBe('place:created');
- expect(socketId).toBe('socket');
- expect(payload.place.route_color).toBeTruthy();
- }
- });
- const result = setup.tours.importGpxAsTour('7', mixedGpx, 'walk.gpx', 'socket')!;
- expect(setup.db.transaction).toHaveBeenCalledOnce();
++ it('commits routes, tracks, colors and facets once before publishing, without Planner waypoints', async () => {
++ const transactional = vi.spyOn(uow, 'transactional');
++ const seen: { inTransaction: boolean; tours: number }[] = [];
++ broadcast.mockImplementation(() => { seen.push({ inTransaction: testDb.inTransaction, tours: count('tours') }); });
++
++ const result = (await tours.importGpxAsTour(tripId, mixedGpx, 'walk.gpx', 'socket'))!;
++
++ // The tours transaction, with importPreparedGpx and its colouring nested inside as savepoints.
++ expect(transactional.mock.calls.length).toBeGreaterThanOrEqual(2);
+ expect(result.tours).toHaveLength(2);
+ expect(result.skipped).toBe(0);
+ expect(result.caution).toBe(true);
- expect(result.tours[0]).toMatchObject({ name: 'walk', tour_type: 'hike', max_hiking_difficulty: 2, planned: false, has_waypoints: false, caution: true });
- expect(result.tours[1]).toMatchObject({ name: 'Ridge', elevation_gain: 50, elevation_loss: 30, caution: false });
- const rows = setup.raw.prepare('SELECT * FROM places ORDER BY id').all() as { trip_id: string; description: string; route_geometry: string; route_color: string }[];
- expect(rows.map(row => row.trip_id)).toEqual(['7', '7']);
++ expect(result.tours[0]).toMatchObject({ name: 'walk', tour_type: 'hike', max_hiking_difficulty: 2, planned: false, has_waypoints: false, caution: true, match_confidence: 0.3 });
++ expect(result.tours[1]).toMatchObject({ name: 'Ridge', elevation_gain: 50, elevation_loss: 30, caution: false, match_confidence: 1 });
++
++ const rows = testDb.prepare('SELECT * FROM places ORDER BY id').all() as { id: number; trip_id: number; description: string; route_geometry: string; route_color: string }[];
++ expect(rows.map(row => row.trip_id)).toEqual([Number(tripId), Number(tripId)]);
+ expect(rows.map(row => row.description)).toEqual(['Route description', 'Track description']);
+ expect(JSON.parse(rows[0].route_geometry)).toEqual([[48, 11], [48.01, 11.01]]);
+ expect(JSON.parse(rows[1].route_geometry)).toEqual([[49, 12, 100], [49.01, 12.01, 150], [49.02, 12.02, 120]]);
+ expect(new Set(rows.map(row => row.route_color)).size).toBe(2);
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM tour_waypoints').get()).toEqual({ count: 0 });
- expect(setup.broadcast.mock.calls.map(call => call[1])).toEqual(['tours:changed', 'place:created', 'place:created']);
- expect(setup.broadcast.mock.calls.slice(1).map(call => call[2].place.id)).toEqual(result.tours.map(tour => tour.place_id));
++ expect(testDb.prepare('SELECT place_id, tour_type FROM tours ORDER BY place_id').all())
++ .toEqual(rows.map(row => ({ place_id: row.id, tour_type: 'hike' })));
++ expect(count('tour_waypoints')).toBe(0);
++
++ expect(seen).toEqual([
++ { inTransaction: false, tours: 2 }, { inTransaction: false, tours: 2 }, { inTransaction: false, tours: 2 },
++ ]);
++ expect(broadcast.mock.calls.map(call => call[1])).toEqual(['tours:changed', 'place:created', 'place:created']);
++ expect(broadcast.mock.calls[0]).toEqual([tripId, 'tours:changed', { placeIds: rows.map(row => row.id) }, 'socket']);
++ for (const call of broadcast.mock.calls.slice(1)) {
++ expect(call[3]).toBe('socket');
++ expect((call[2] as { place: { route_color: string } }).place.route_color).toBeTruthy();
++ }
++ expect(broadcast.mock.calls.slice(1).map(call => (call[2] as { place: { id: number } }).place.id))
++ .toEqual(result.tours.map(tour => tour.place_id));
+ });
+
- it.each([1, 2])('rolls back every carrier and facet when facet %i fails', (ordinal) => {
- setup.raw.exec(`CREATE TRIGGER fail_facet BEFORE INSERT ON tours
++ it.each([1, 2])('rolls back every carrier and facet when facet %i fails', async (ordinal) => {
++ testDb.exec(`CREATE TRIGGER fail_facet BEFORE INSERT ON tours
+ WHEN (SELECT COUNT(*) FROM tours) = ${ordinal - 1}
+ BEGIN SELECT RAISE(ABORT, 'facet failure'); END;`);
- expect(() => setup.tours.importGpxAsTour('7', mixedGpx)).toThrow('facet failure');
++ await expect(tours.importGpxAsTour(tripId, mixedGpx)).rejects.toThrow('facet failure');
+ expectEmpty();
+ });
+
- it('rolls back earlier carriers when the later Place insert fails', () => {
- setup.raw.exec(`CREATE TRIGGER fail_place BEFORE INSERT ON places WHEN NEW.name = 'Ridge'
++ it('rolls back earlier carriers when the later Place insert fails', async () => {
++ testDb.exec(`CREATE TRIGGER fail_place BEFORE INSERT ON places WHEN NEW.name = 'Ridge'
+ BEGIN SELECT RAISE(ABORT, 'place failure'); END;`);
- expect(() => setup.tours.importGpxAsTour('7', mixedGpx)).toThrow('place failure');
++ await expect(tours.importGpxAsTour(tripId, mixedGpx)).rejects.toThrow('place failure');
+ expectEmpty();
+ });
+
- it('rolls back carriers and earlier colors when later coloring fails', () => {
- setup.raw.exec(`CREATE TRIGGER fail_color BEFORE UPDATE OF route_color ON places WHEN NEW.name = 'Ridge'
++ it('rolls back carriers and earlier colors when later coloring fails', async () => {
++ testDb.exec(`CREATE TRIGGER fail_color BEFORE UPDATE OF route_color ON places WHEN NEW.name = 'Ridge'
+ BEGIN SELECT RAISE(ABORT, 'color failure'); END;`);
- expect(() => setup.tours.importGpxAsTour('7', mixedGpx)).toThrow('color failure');
++ await expect(tours.importGpxAsTour(tripId, mixedGpx)).rejects.toThrow('color failure');
+ expectEmpty();
+ });
+
- it.each(['<not-gpx/>', '<gpx/>', '<gpx><wpt lat="1" lon="2"/></gpx>', '<gpx><trk><trkseg><trkpt/></trkseg></trk></gpx>'])('does not write or publish unusable input %s', (xml) => {
- expect(setup.tours.importGpxAsTour('7', Buffer.from(xml))).toBeNull();
- expect(setup.db.transaction).not.toHaveBeenCalled();
++ it.each(['<not-gpx/>', '<gpx/>', '<gpx><wpt lat="1" lon="2"/></gpx>', '<gpx><trk><trkseg><trkpt/></trkseg></trk></gpx>'])('does not write or publish unusable input %s', async (xml) => {
++ const transactional = vi.spyOn(uow, 'transactional');
++ expect(await tours.importGpxAsTour(tripId, Buffer.from(xml))).toBeNull();
++ expect(transactional).not.toHaveBeenCalled();
+ expectEmpty();
+ });
+
- it('propagates parser failures before entering the transaction', () => {
++ it('propagates parser failures before entering the transaction', async () => {
++ const transactional = vi.spyOn(uow, 'transactional');
+ vi.spyOn(gpxParser, 'parse').mockImplementationOnce(() => { throw new Error('parser failure'); });
- expect(() => setup.tours.importGpxAsTour('7', mixedGpx)).toThrow('parser failure');
- expect(setup.db.transaction).not.toHaveBeenCalled();
++ await expect(tours.importGpxAsTour(tripId, mixedGpx)).rejects.toThrow('parser failure');
++ expect(transactional).not.toHaveBeenCalled();
+ expectEmpty();
+ });
+
- it('keeps a committed response and attempts remaining events if publication throws', () => {
++ it('keeps a committed response and attempts remaining events if publication throws', async () => {
+ const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {});
- setup.broadcast.mockImplementationOnce(() => { throw new Error('transport unavailable'); });
- expect(setup.tours.importGpxAsTour('7', mixedGpx)?.tours).toHaveLength(2);
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM tours').get()).toEqual({ count: 2 });
- expect(setup.broadcast).toHaveBeenCalledTimes(3);
++ broadcast.mockImplementationOnce(() => { throw new Error('transport unavailable'); });
++ expect((await tours.importGpxAsTour(tripId, mixedGpx))?.tours).toHaveLength(2);
++ expect(count('tours')).toBe(2);
++ expect(broadcast).toHaveBeenCalledTimes(3);
+ expect(warn).toHaveBeenCalledOnce();
+ });
+
- it('keeps committed rows and success response if the Tours invalidation event fails', () => {
++ it('keeps committed rows and success response if a place event fails', async () => {
++ const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {});
++ broadcast.mockImplementation((_tripId, event) => {
++ if (event === 'place:created') throw new Error('transport unavailable');
++ });
++
++ expect((await tours.importGpxAsTour(tripId, mixedGpx))?.tours).toHaveLength(2);
++ expect(count('places')).toBe(2);
++ expect(warn).toHaveBeenCalledTimes(2);
++ });
++
++ it('keeps committed rows and success response if the Tours invalidation event fails', async () => {
+ const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {});
- setup.broadcast.mockImplementation((_tripId, event) => {
++ broadcast.mockImplementation((_tripId, event) => {
+ if (event === 'tours:changed') throw new Error('invalidation unavailable');
+ });
+
- const result = setup.tours.importGpxAsTour('7', mixedGpx);
++ const result = await tours.importGpxAsTour(tripId, mixedGpx);
+
+ expect(result?.tours).toHaveLength(2);
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM places').get()).toEqual({ count: 2 });
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM tours').get()).toEqual({ count: 2 });
- expect(setup.broadcast.mock.calls.map(call => call[1])).toEqual(['tours:changed', 'place:created', 'place:created']);
++ expect(count('places')).toBe(2);
++ expect(count('tours')).toBe(2);
++ expect(broadcast.mock.calls.map(call => call[1])).toEqual(['tours:changed', 'place:created', 'place:created']);
+ expect(warn).toHaveBeenCalledOnce();
+ });
+
- it('returns a successful skipped result for duplicate-only imports without publishing events', () => {
- expect(setup.tours.importGpxAsTour('7', mixedGpx)?.tours).toHaveLength(2);
- const rowsBefore = setup.raw.prepare('SELECT id, trip_id, name FROM places ORDER BY id').all();
- const facetsBefore = setup.raw.prepare('SELECT place_id FROM tours ORDER BY place_id').all();
- setup.broadcast.mockClear();
++ it('returns a successful skipped result for duplicate-only imports without publishing events', async () => {
++ expect((await tours.importGpxAsTour(tripId, mixedGpx))?.tours).toHaveLength(2);
++ const rowsBefore = testDb.prepare('SELECT id, trip_id, name FROM places ORDER BY id').all();
++ const facetsBefore = testDb.prepare('SELECT place_id FROM tours ORDER BY place_id').all();
++ broadcast.mockClear();
+
- expect(setup.tours.importGpxAsTour('7', mixedGpx)).toEqual({ tours: [], caution: false, skipped: 2 });
- expect(setup.raw.prepare('SELECT id, trip_id, name FROM places ORDER BY id').all()).toEqual(rowsBefore);
- expect(setup.raw.prepare('SELECT place_id FROM tours ORDER BY place_id').all()).toEqual(facetsBefore);
- expect(setup.broadcast).not.toHaveBeenCalled();
- })
++ expect(await tours.importGpxAsTour(tripId, mixedGpx)).toEqual({ tours: [], caution: false, skipped: 2 });
++ expect(testDb.prepare('SELECT id, trip_id, name FROM places ORDER BY id').all()).toEqual(rowsBefore);
++ expect(testDb.prepare('SELECT place_id FROM tours ORDER BY place_id').all()).toEqual(facetsBefore);
++ expect(broadcast).not.toHaveBeenCalled();
++ });
+
- it('imports only the new tracks and publishes only committed rows in a mixed result', () => {
++ it('imports only the new tracks and publishes only committed rows in a mixed result', async () => {
+ const existing = Buffer.from(`<gpx><trk><name>Ridge</name><trkseg>
+ <trkpt lat="49" lon="12"><ele>100</ele></trkpt><trkpt lat="49.01" lon="12.01"><ele>150</ele></trkpt>
- </trkseg></trk></gpx>`)
- expect(setup.tours.importGpxAsTour('7', existing)?.tours).toHaveLength(1);
- setup.broadcast.mockClear();
++ </trkseg></trk></gpx>`);
++ expect((await tours.importGpxAsTour(tripId, existing))?.tours).toHaveLength(1);
++ broadcast.mockClear();
+
- const result = setup.tours.importGpxAsTour('7', mixedGpx, 'walk.gpx', 'socket');
++ const result = await tours.importGpxAsTour(tripId, mixedGpx, 'walk.gpx', 'socket');
+
+ expect(result?.tours).toHaveLength(1);
+ expect(result?.tours[0].name).toBe('walk');
+ expect(result?.skipped).toBe(1);
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM places').get()).toEqual({ count: 2 });
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM tours').get()).toEqual({ count: 2 });
- expect(setup.broadcast.mock.calls.map(call => [call[1], call[2]])).toEqual([
- ['tours:changed', { placeIds: [2] }],
- ['place:created', expect.objectContaining({ place: expect.objectContaining({ id: 2, name: 'walk' }) })],
++ expect(count('places')).toBe(2);
++ expect(count('tours')).toBe(2);
++ const walkId = result!.tours[0].place_id;
++ expect(broadcast.mock.calls.map(call => [call[1], call[2]])).toEqual([
++ ['tours:changed', { placeIds: [walkId] }],
++ ['place:created', expect.objectContaining({ place: expect.objectContaining({ id: walkId, name: 'walk' }) })],
+ ]);
- })
++ });
+
- it('preserves single-track response and trip scoping', () => {
++ it('preserves single-track response and trip scoping', async () => {
++ const { user } = createUser(testDb);
++ const otherTripId = String(createTrip(testDb, user.id).id);
+ const single = Buffer.from('<gpx><trk><trkseg><trkpt lat="48" lon="11"/><trkpt lat="48.01" lon="11.01"/></trkseg></trk></gpx>');
- const result = setup.tours.importGpxAsTour('8', single, 'single.gpx')!;
++
++ const result = (await tours.importGpxAsTour(otherTripId, single, 'single.gpx'))!;
++
+ expect(result.tours).toHaveLength(1);
+ expect(result.tours[0].name).toBe('single');
+ expect(result.caution).toBe(true);
- expect(setup.broadcast.mock.calls.map(call => call[1])).toEqual(['tours:changed', 'place:created']);
- });
-
- it('rejects caller-owned persistence outside a transaction before writing', () => {
- expect(() => setup.places.importPreparedGpx('7', setup.places.prepareGpxRows(mixedGpx))).toThrow('active transaction');
- expectEmpty();
++ expect(testDb.prepare('SELECT trip_id FROM places').all()).toEqual([{ trip_id: Number(otherTripId) }]);
++ expect((await tours.listTours(otherTripId)).map(t => t.place_id)).toEqual([result.tours[0].place_id]);
++ expect(await tours.listTours(tripId)).toEqual([]);
++ expect(broadcast.mock.calls.map(call => call[1])).toEqual(['tours:changed', 'place:created']);
+ });
- });
++});
diff --cc server/tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts
index e11a566dd,000000000..b515e4ed8
mode 100644,000000..100644
--- a/server/tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts
+++ b/server/tests/unit/nest/tours.permissions.boundaries.mock-only.test.ts
@@@ -1,238 -1,0 +1,273 @@@
++/**
++ * Tours reuse the ordinary place and day-assignment endpoints for deletion and
++ * planning, so their permissions are those endpoints' permissions: deleting a
++ * tour needs 'place_edit' only, assigning or unassigning one needs 'day_edit'
++ * only. Run through the real TripAccessGuard with mocked collaborators (no DB).
++ * The last block pins ToursService's trip boundary on update against stubbed
++ * repositories.
++ */
+import 'reflect-metadata';
- import { afterAll, describe, expect, it, vi } from 'vitest';
- import { HttpException, type ExecutionContext } from '@nestjs/common';
++import { describe, expect, it, vi } from 'vitest';
++import { HttpException, NotFoundException, RequestMethod, type ExecutionContext } from '@nestjs/common';
+import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
- import { RequestMethod } from '@nestjs/common';
+import { Reflector } from '@nestjs/core';
++import type { EntityManager } from '@mikro-orm/core';
+import type { TourCreateRequest } from '@trek/shared';
+
- vi.mock('../../../src/config', () => { throw new Error('Config initialization is forbidden in mock-only tests'); });
- vi.mock('../../../src/nest/database/database.service', () => ({
- DatabaseService: vi.fn(() => { throw new Error('Database construction is forbidden in this suite'); }),
++const { legacyDatabaseAccess } = vi.hoisted(() => ({
++ legacyDatabaseAccess: vi.fn((property: string | symbol): never => {
++ throw new Error(`Unexpected legacy database access: ${String(property)}`);
++ }),
+}));
- vi.mock('../../../src/db/database', () => ({
- db: { prepare: vi.fn(() => { throw new Error('Legacy database access is forbidden in this suite'); }) },
++
++vi.mock('../../../src/config', () => ({
++ ENCRYPTION_KEY: 'test-only-inert-key',
++ JWT_SECRET: 'test-only-inert-secret',
++ updateJwtSecret: vi.fn(),
+}));
- vi.mock('better-sqlite3', () => ({
- default: vi.fn(() => { throw new Error('SQLite construction is forbidden in this suite'); }),
++vi.mock('../../../src/db/database', () => ({
++ db: new Proxy({}, {
++ get: (_target, property: string | symbol) => legacyDatabaseAccess(property),
++ }),
+}));
+vi.mock('../../../src/nest/permissions/permissions.service', () => ({ PermissionsService: class {} }));
+vi.mock('../../../src/nest/places/places.service', () => ({ PlacesService: class {} }));
+vi.mock('../../../src/nest/assignments/assignments.service', () => ({ AssignmentsService: class {} }));
+vi.mock('../../../src/nest/app-config/runtime-env.service', () => ({ RuntimeEnvService: class {} }));
+vi.mock('../../../src/nest/storage/storage.service', () => ({ StorageService: class {} }));
+vi.mock('../../../src/nest/auth/jwt-verify', () => ({ extractToken: vi.fn(), verifyJwtAndLoadUser: vi.fn() }));
+
- import { DatabaseService } from '../../../src/nest/database/database.service';
- import { db as legacyDatabase } from '../../../src/db/database';
- import SqliteDatabase from 'better-sqlite3';
+import { PlacesController } from '../../../src/nest/places/places.controller';
+import { DayAssignmentsController } from '../../../src/nest/assignments/assignments.controller';
+import { ToursService } from '../../../src/nest/tours/tours.service';
+import { JwtAuthGuard } from '../../../src/nest/auth/jwt-auth.guard';
+import { TripAccessGuard, TRIP_PERMISSION_KEY } from '../../../src/nest/permissions/trip-access.guard';
++import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
++import type { PlacesService } from '../../../src/nest/places/places.service';
++import type { AssignmentsService } from '../../../src/nest/assignments/assignments.service';
++import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
++import type { StorageService } from '../../../src/nest/storage/storage.service';
++import type { UnitOfWork } from '../../../src/nest/database/unit-of-work';
++import type { PlacesRepository } from '../../../src/db/repositories/Places.repository';
++import type { ToursRepository } from '../../../src/db/repositories/Tours.repository';
++import type { TourWaypointsRepository } from '../../../src/db/repositories/TourWaypoints.repository';
++import type { User } from '../../../src/types';
+
+const matrix = [[false, false], [true, false], [false, true], [true, true]] as const;
+
- afterAll(() => {
- expect(DatabaseService).not.toHaveBeenCalled();
- expect(legacyDatabase.prepare).not.toHaveBeenCalled();
- expect(SqliteDatabase).not.toHaveBeenCalled();
- });
-
+function authorization(controller: typeof PlacesController | typeof DayAssignmentsController, handler: 'create' | 'remove', canEdit: boolean, canAssign: boolean, tripId = '7') {
- const request = { params: { tripId }, user: { id: 2, role: 'user' } };
++ const request = { params: { tripId }, user: { id: 2, role: 'user' } as User };
+ const trip = { id: 7, user_id: 1 };
- const access = vi.fn((id: number, userId: number) => id === 7 && userId === 2 ? trip : undefined);
- const permission = vi.fn((action: string) => action === 'place_edit' ? canEdit : action === 'day_edit' && canAssign);
++ const access = vi.fn(async (id: number, userId: number) => id === 7 && userId === 2 ? trip : undefined);
++ const permission = vi.fn(async (action: string) => action === 'place_edit' ? canEdit : action === 'day_edit' && canAssign);
+ const context = {
+ switchToHttp: () => ({ getRequest: () => request }),
+ getHandler: () => controller.prototype[handler],
+ getClass: () => controller,
+ } as unknown as ExecutionContext;
- const guard = new TripAccessGuard({ canAccessTrip: access } as never, { checkPermission: permission } as never, new Reflector());
++ const em = { getRepository: vi.fn(() => ({ findAccessible: access })) } as unknown as EntityManager;
++ const guard = new TripAccessGuard(em, { checkPermission: permission } as unknown as PermissionsService, new Reflector());
+ return { request, access, permission, context, guard };
+}
+
- async function rejected(action: () => unknown, status: number) {
- await expect(Promise.resolve().then(action)).rejects.toMatchObject({ status });
++async function rejected(action: () => Promise<unknown>, status: number) {
++ await expect(action()).rejects.toMatchObject({ status });
+}
+
+function placesFixture() {
+ const places = {
- get: vi.fn(() => ({ id: 42, trip_id: 7 })),
- onDeleted: vi.fn(),
- linkedExpenseIds: vi.fn(() => []),
- remove: vi.fn(async () => ({ deleted: true, deletedTourPlaceIds: [], cancelled: { reservationIds: [], budgetItemIds: [] } })),
++ get: vi.fn(async () => ({ id: 42, trip_id: 7 })),
++ onDeleted: vi.fn(async () => {}),
++ linkedExpenseIds: vi.fn(async () => []),
++ remove: vi.fn(async () => ({ deleted: true, deletedTourPlaceIds: [42], cancelled: { reservationIds: [], budgetItemIds: [] } })),
+ broadcast: vi.fn(),
+ };
- return { places, controller: new PlacesController(places as never, {} as never, {} as never) };
++ const controller = new PlacesController(
++ places as unknown as PlacesService, {} as RuntimeEnvService, {} as StorageService,
++ );
++ return { places, controller };
+}
+
+function assignmentsFixture() {
+ const assignment = { id: 51, place_id: 42, day_id: 11 };
+ const assignments = {
- dayExists: vi.fn(() => true),
- placeExists: vi.fn(() => true),
- assignmentExistsInDay: vi.fn(() => true),
- createAssignment: vi.fn(() => assignment),
- deleteAssignment: vi.fn(),
++ dayExists: vi.fn(async () => true),
++ placeExists: vi.fn(async () => true),
++ assignmentExistsInDay: vi.fn(async () => true),
++ createAssignment: vi.fn(async () => assignment),
++ deleteAssignment: vi.fn(async () => {}),
+ broadcast: vi.fn(),
- reconcile: vi.fn(),
++ reconcile: vi.fn(async () => {}),
+ };
- return { assignment, assignments, controller: new DayAssignmentsController(assignments as never) };
++ return { assignment, assignments, controller: new DayAssignmentsController(assignments as unknown as AssignmentsService) };
+}
+
+describe('Tours deletion and assignment authorization (mock-only)', () => {
++ it('does not access the legacy global database initializer', () => {
++ expect(legacyDatabaseAccess).not.toHaveBeenCalled();
++ });
++
+ it('keeps existing Places deletion and day assignment endpoints wired to their exact permissions', () => {
+ expect(Reflect.getMetadata(PATH_METADATA, PlacesController)).toBe('api/trips/:tripId/places');
+ expect(Reflect.getMetadata(GUARDS_METADATA, PlacesController)).toEqual([JwtAuthGuard]);
+ expect(Reflect.getMetadata(GUARDS_METADATA, PlacesController.prototype.remove)).toEqual([TripAccessGuard]);
+ expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, PlacesController.prototype.remove)).toBe('place_edit');
+ expect(Reflect.getMetadata(METHOD_METADATA, PlacesController.prototype.remove)).toBe(RequestMethod.DELETE);
+ expect(Reflect.getMetadata(PATH_METADATA, PlacesController.prototype.remove)).toBe(':id');
+ expect(Reflect.getMetadata(PATH_METADATA, DayAssignmentsController)).toBe('api/trips/:tripId/days/:dayId/assignments');
+ expect(Reflect.getMetadata(GUARDS_METADATA, DayAssignmentsController)).toEqual([JwtAuthGuard, TripAccessGuard]);
+ for (const handler of ['create', 'remove'] as const) {
+ expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, DayAssignmentsController.prototype[handler])).toBe('day_edit');
+ }
+ expect(Reflect.getMetadata(METHOD_METADATA, DayAssignmentsController.prototype.create)).toBe(RequestMethod.POST);
+ expect(Reflect.getMetadata(METHOD_METADATA, DayAssignmentsController.prototype.remove)).toBe(RequestMethod.DELETE);
+ expect(Reflect.getMetadata(PATH_METADATA, DayAssignmentsController.prototype.remove)).toBe(':id');
+ });
+
+ it.each(matrix)('edit=%s assign=%s: tour deletion requires only place_edit', async (canEdit, canAssign) => {
+ const auth = authorization(PlacesController, 'remove', canEdit, canAssign);
+ const { places, controller } = placesFixture();
- const invoke = () => {
- auth.guard.canActivate(auth.context);
- return controller.remove(auth.request.user as never, '7', '42', 'socket');
++ const invoke = async () => {
++ await auth.guard.canActivate(auth.context);
++ return await controller.remove(auth.request.user, '7', '42', 'socket');
+ };
+ if (canEdit) {
- await expect(invoke()).resolves.toEqual({ success: true, tourPlaceIds: [] });
++ await expect(invoke()).resolves.toEqual({ success: true, tourPlaceIds: [42] });
+ expect(places.get).toHaveBeenCalledWith('7', '42');
+ expect(places.onDeleted).toHaveBeenCalledWith(42);
+ expect(places.remove).toHaveBeenCalledWith('7', '42');
+ expect(places.broadcast).toHaveBeenCalledWith('7', 'place:deleted', { placeId: 42 }, 'socket');
+ } else {
+ await rejected(invoke, 403);
+ for (const method of Object.values(places)) expect(method).not.toHaveBeenCalled();
+ }
+ expect(auth.permission).toHaveBeenCalledExactlyOnceWith('place_edit', 'user', 1, 2, true);
+ });
+
+ describe.each(['create', 'remove'] as const)('assignment %s', handler => {
+ it.each(matrix)('edit=%s assign=%s: requires only day_edit', async (canEdit, canAssign) => {
+ const auth = authorization(DayAssignmentsController, handler, canEdit, canAssign);
+ const { assignment, assignments, controller } = assignmentsFixture();
- const invoke = () => {
- auth.guard.canActivate(auth.context);
++ const invoke = async () => {
++ await auth.guard.canActivate(auth.context);
+ return handler === 'create'
- ? controller.create(auth.request.user as never, '7', '11', { place_id: 42, notes: 'Tour' }, 'socket')
- : controller.remove(auth.request.user as never, '7', '11', '51', 'socket');
++ ? await controller.create(auth.request.user, '7', '11', { place_id: 42, notes: 'Tour' }, 'socket')
++ : await controller.remove(auth.request.user, '7', '11', '51', 'socket');
+ };
+ if (canAssign) {
- expect(invoke()).toEqual(handler === 'create' ? { assignment } : { success: true });
++ expect(await invoke()).toEqual(handler === 'create' ? { assignment } : { success: true });
+ if (handler === 'create') {
+ expect(assignments.dayExists).toHaveBeenCalledWith('11', '7');
+ expect(assignments.placeExists).toHaveBeenCalledWith(42, '7');
+ expect(assignments.createAssignment).toHaveBeenCalledWith('11', 42, 'Tour');
+ expect(assignments.deleteAssignment).not.toHaveBeenCalled();
+ expect(assignments.broadcast).toHaveBeenCalledWith('7', 'assignment:created', { assignment }, 'socket');
+ } else {
+ expect(assignments.assignmentExistsInDay).toHaveBeenCalledWith('51', '11', '7');
+ expect(assignments.deleteAssignment).toHaveBeenCalledWith('51');
+ expect(assignments.createAssignment).not.toHaveBeenCalled();
+ expect(assignments.broadcast).toHaveBeenCalledWith('7', 'assignment:deleted', { assignmentId: 51, dayId: 11 }, 'socket');
+ }
+ expect(assignments.reconcile).toHaveBeenCalledWith('7', 'socket');
+ } else {
+ await rejected(invoke, 403);
+ for (const method of Object.values(assignments)) expect(method).not.toHaveBeenCalled();
+ }
+ expect(auth.permission).toHaveBeenCalledExactlyOnceWith('day_edit', 'user', 1, 2, true);
+ });
+ });
+
+ it.each([
+ [PlacesController, 'remove'],
+ [DayAssignmentsController, 'create'],
+ [DayAssignmentsController, 'remove'],
+ ] as const)('%s.%s rejects an inaccessible route trip before checking permissions', async (owner, handler) => {
+ const auth = authorization(owner, handler, true, true, '8');
+ await rejected(() => auth.guard.canActivate(auth.context), 404);
+ expect(auth.access).toHaveBeenCalledExactlyOnceWith(8, 2);
+ expect(auth.permission).not.toHaveBeenCalled();
+ });
+});
+
+const input: TourCreateRequest = {
+ name: 'Ridge walk', tour_type: 'hike', max_hiking_difficulty: 2,
+ route_geometry: [[48, 11, 600], [48.02, 11.04, 630]],
+ waypoints: [
+ { lat: 48, lng: 11, role: 'start', sequence: 0 },
+ { lat: 48.02, lng: 11.04, role: 'end', sequence: 1 },
+ ],
+};
+
- function tourDatabaseFixture(ownerTripId: string) {
++/** Tour 42 belongs to `ownerTripId`; findInTrip answers only for that trip. */
++function tourRepositoryFixture(ownerTripId: number) {
+ const row = {
+ place_id: 42, name: 'Ridge walk', tour_type: 'hike', distance: 3,
+ elevation_gain: 30, elevation_loss: 0, duration: null, difficulty: null,
+ wanderer_ref: null, match_confidence: 1, tour_group_id: null,
+ max_hiking_difficulty: 2, planned: 0, has_waypoints: 1,
+ };
- const waypointRun = vi.fn();
- const db = {
- get: vi.fn((sql: string, tripId: string, placeId: string) => {
- expect(sql.replace(/\s+/g, ' ')).toContain('WHERE p.trip_id = ? AND p.id = ?');
- return tripId === ownerTripId && placeId === '42' ? row : undefined;
- }),
- all: vi.fn(() => input.waypoints),
- run: vi.fn(),
- prepare: vi.fn(() => ({ run: waypointRun })),
- transaction: vi.fn((write: () => void) => write()),
- getPlaceWithTags: vi.fn(() => ({ id: 42, trip_id: Number(ownerTripId) })),
++ const uow = { transactional: vi.fn(async <T>(fn: () => Promise<T>): Promise<T> => await fn()) };
++ const toursRepo = {
++ findInTrip: vi.fn(async (tripId: number, placeId: number) => tripId === ownerTripId && placeId === 42 ? row : undefined),
++ updateInTrip: vi.fn(async () => true),
++ };
++ const waypointsRepo = {
++ listForPlace: vi.fn(async () => input.waypoints),
++ deleteForPlace: vi.fn(async () => {}),
++ insertForPlace: vi.fn(async () => {}),
++ };
++ const placesRepo = {
++ updateTourRoute: vi.fn(async () => true),
++ findInTrip: vi.fn(async () => undefined),
++ findWithTagsAndRatings: vi.fn(async () => ({ id: 42, trip_id: ownerTripId })),
+ };
+ const places = { broadcast: vi.fn() };
- return { db, waypointRun, places, service: new ToursService(db as never, places as never) };
++ const service = new ToursService(
++ uow as unknown as UnitOfWork,
++ places as unknown as PlacesService,
++ toursRepo as unknown as ToursRepository,
++ waypointsRepo as unknown as TourWaypointsRepository,
++ placesRepo as unknown as PlacesRepository,
++ );
++ return { uow, toursRepo, waypointsRepo, placesRepo, places, service };
+}
+
- describe('Real ToursService update trip boundary (mock database module)', () => {
- it('rejects a placeId belonging to another trip before any transaction or write', () => {
- const { db, waypointRun, places, service } = tourDatabaseFixture('8');
- expect(service.getTour('8', '42').tour.place_id).toBe(42);
- db.get.mockClear();
- db.all.mockClear();
- try {
- service.updateTour('7', '42', input, 'socket');
- expect.fail('Expected cross-trip rejection');
- } catch (error) {
- expect(error).toBeInstanceOf(HttpException);
- expect((error as HttpException).getStatus()).toBe(404);
- expect((error as Error).message).toBe('Tour not found');
- }
- expect(db.get).toHaveBeenCalledExactlyOnceWith(expect.any(String), '7', '42');
- for (const method of [db.all, db.transaction, db.run, db.prepare, waypointRun, db.getPlaceWithTags, places.broadcast]) {
++describe('Real ToursService update trip boundary (stubbed repositories)', () => {
++ it('rejects a placeId belonging to another trip before any write', async () => {
++ const f = tourRepositoryFixture(8);
++ expect((await f.service.getTour('8', '42')).tour.place_id).toBe(42);
++ f.toursRepo.findInTrip.mockClear();
++ f.waypointsRepo.listForPlace.mockClear();
++
++ const error: unknown = await f.service.updateTour('7', '42', input, 'socket').catch((e: unknown) => e);
++
++ expect(error).toBeInstanceOf(NotFoundException);
++ expect((error as HttpException).getStatus()).toBe(404);
++ expect((error as Error).message).toBe('Tour not found');
++ expect(f.toursRepo.findInTrip).toHaveBeenCalledExactlyOnceWith(7, 42);
++ for (const method of [
++ f.placesRepo.updateTourRoute, f.toursRepo.updateInTrip, f.waypointsRepo.deleteForPlace,
++ f.waypointsRepo.insertForPlace, f.waypointsRepo.listForPlace, f.placesRepo.findWithTagsAndRatings, f.places.broadcast,
++ ]) {
+ expect(method).not.toHaveBeenCalled();
+ }
- expect(DatabaseService).not.toHaveBeenCalled();
+ });
+
- it('allows a same-trip update through the fake transaction and prepare interface', () => {
- const { db, waypointRun, places, service } = tourDatabaseFixture('7');
- expect(service.updateTour('7', '42', input, 'socket').tour.place_id).toBe(42);
- expect(db.get).toHaveBeenCalledTimes(2);
- expect(db.transaction).toHaveBeenCalledOnce();
- expect(db.run).toHaveBeenCalledTimes(3);
- expect(db.run).toHaveBeenNthCalledWith(1, expect.stringMatching(/WHERE id = \? AND trip_id = \?/), input.name, 48, 11, JSON.stringify(input.route_geometry), '42', '7');
- expect(db.prepare).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('INSERT INTO tour_waypoints'));
- expect(waypointRun).toHaveBeenCalledTimes(2);
- for (const waypoint of input.waypoints) {
- expect(waypointRun).toHaveBeenCalledWith('42', waypoint.lat, waypoint.lng, waypoint.role, waypoint.sequence);
- }
- expect(db.getPlaceWithTags).toHaveBeenCalledWith(42);
- expect(places.broadcast).toHaveBeenCalledWith('7', 'place:updated', { place: { id: 42, trip_id: 7 } }, 'socket');
- expect(DatabaseService).not.toHaveBeenCalled();
++ it('allows a same-trip update through the transaction with trip-scoped writes', async () => {
++ const f = tourRepositoryFixture(7);
++
++ expect((await f.service.updateTour('7', '42', input, 'socket')).tour.place_id).toBe(42);
++
++ expect(f.uow.transactional).toHaveBeenCalledOnce();
++ // Once inside the write, once for the response.
++ expect(f.toursRepo.findInTrip).toHaveBeenCalledTimes(2);
++ expect(f.placesRepo.updateTourRoute).toHaveBeenCalledExactlyOnceWith(42, 7, {
++ name: input.name, lat: 48, lng: 11, route_geometry: JSON.stringify(input.route_geometry),
++ });
++ expect(f.toursRepo.updateInTrip).toHaveBeenCalledExactlyOnceWith(7, 42, expect.objectContaining({ tour_type: 'hike', duration: null }));
++ expect(f.waypointsRepo.deleteForPlace).toHaveBeenCalledExactlyOnceWith(42);
++ expect(f.waypointsRepo.insertForPlace).toHaveBeenCalledExactlyOnceWith(42, input.waypoints);
++ expect(f.placesRepo.findWithTagsAndRatings).toHaveBeenCalledWith(42);
++ expect(f.places.broadcast).toHaveBeenCalledWith('7', 'place:updated', { place: { id: 42, trip_id: 7 } }, 'socket');
+ });
- });
++});
diff --cc server/tests/unit/nest/tours.permissions.test.ts
index 1f0aa51b6,000000000..5f616d53b
mode 100644,000000..100644
--- a/server/tests/unit/nest/tours.permissions.test.ts
+++ b/server/tests/unit/nest/tours.permissions.test.ts
@@@ -1,108 -1,0 +1,167 @@@
++/**
++ * The Tours permission contract, run through the real guards with mocked
++ * collaborators (no DB): reads need trip access only, writes need
++ * 'place_edit' and never 'day_edit', an inaccessible trip is a 404 before any
++ * permission check, and the addon and JWT refusals stop a request before the
++ * trip is resolved. The GPX import answers the same matrix from its handler.
++ */
+import 'reflect-metadata';
+import { describe, expect, it, vi } from 'vitest';
+import { HttpException, type ExecutionContext } from '@nestjs/common';
+import { GUARDS_METADATA } from '@nestjs/common/constants';
+import { Reflector } from '@nestjs/core';
++import type { EntityManager } from '@mikro-orm/core';
+
- vi.mock('../../../src/config', () => { throw new Error('Config initialization is forbidden in mock-only tests'); });
- vi.mock('../../../src/db/database', () => { throw new Error('Legacy database imports are forbidden in mock-only tests'); });
- vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in mock-only tests'); });
- vi.mock('../../../src/nest/database/database.service', () => ({
- DatabaseService: vi.fn(() => { throw new Error('Database construction is forbidden in mock-only tests'); }),
++const { legacyDatabaseAccess } = vi.hoisted(() => ({
++ legacyDatabaseAccess: vi.fn((property: string | symbol): never => {
++ throw new Error(`Unexpected legacy database access: ${String(property)}`);
++ }),
++}));
++
++vi.mock('../../../src/config', () => ({
++ ENCRYPTION_KEY: 'test-only-inert-key',
++ JWT_SECRET: 'test-only-inert-secret',
++ updateJwtSecret: vi.fn(),
++}));
++vi.mock('../../../src/db/database', () => ({
++ db: new Proxy({}, {
++ get: (_target, property: string | symbol) => legacyDatabaseAccess(property),
++ }),
+}));
+vi.mock('../../../src/nest/permissions/permissions.service', () => ({ PermissionsService: class {} }));
+vi.mock('../../../src/nest/addons/addons.service', () => ({ AddonsService: class {} }));
++vi.mock('../../../src/nest/places/places.service', () => ({ PlacesService: class {} }));
+vi.mock('../../../src/nest/tours/tours.service', () => ({ ToursService: class {} }));
+vi.mock('../../../src/nest/auth/jwt-verify', () => ({ extractToken: vi.fn(), verifyJwtAndLoadUser: vi.fn() }));
+
+import { ToursController } from '../../../src/nest/tours/tours.controller';
++import { ToursImportController } from '../../../src/nest/tours/tours-import.controller';
+import { TripAccessGuard, TRIP_PERMISSION_KEY, TRIP_REQUEST_KEY } from '../../../src/nest/permissions/trip-access.guard';
++import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
++import type { PlacesService } from '../../../src/nest/places/places.service';
++import type { AddonsService } from '../../../src/nest/addons/addons.service';
++import type { ToursService } from '../../../src/nest/tours/tours.service';
+import { AddonGuard } from '../../../src/nest/addons/addon.guard';
+import { JwtAuthGuard } from '../../../src/nest/auth/jwt-auth.guard';
+import { extractToken, verifyJwtAndLoadUser } from '../../../src/nest/auth/jwt-verify';
++import type { User } from '../../../src/types';
+
++const matrix = [[false, false], [true, false], [false, true], [true, true]] as const;
++const user = { id: 2, role: 'user' } as User;
++const trip = { id: 7, user_id: 1 };
++
++/** Trip 7 is reachable for user 2; it belongs to user 1, so every check is a shared-trip check. */
+function fixture(handler: keyof ToursController, canEdit = false, canAssign = false, tripId = '7') {
- const request = { params: { tripId }, user: { id: 2, role: 'user' } };
- const trip = { id: 7, user_id: 1 };
- const access = vi.fn((id: number, userId: number) => id === 7 && userId === 2 ? trip : undefined);
- const permission = vi.fn((action: string) => action === 'place_edit' ? canEdit : action === 'day_edit' && canAssign);
++ const request = { params: { tripId }, user };
++ const access = vi.fn(async (id: number, userId: number) => id === 7 && userId === 2 ? trip : undefined);
++ const permission = vi.fn(async (action: string) => action === 'place_edit' ? canEdit : action === 'day_edit' && canAssign);
+ const context = {
+ switchToHttp: () => ({ getRequest: () => request }),
+ getHandler: () => ToursController.prototype[handler],
+ getClass: () => ToursController,
+ } as unknown as ExecutionContext;
- const guard = new TripAccessGuard({ canAccessTrip: access } as never, { checkPermission: permission } as never, new Reflector());
- return { request, trip, access, permission, context, guard };
++ const em = { getRepository: vi.fn(() => ({ findAccessible: access })) } as unknown as EntityManager;
++ const guard = new TripAccessGuard(em, { checkPermission: permission } as unknown as PermissionsService, new Reflector());
++ return { request, access, permission, context, guard };
+}
+
- function expectStatus(action: () => unknown, status: number) {
++/** The import handler's own checks, with the same access and permission doubles. */
++function importFixture(canEdit: boolean, canAssign: boolean) {
++ const permission = vi.fn(async (action: string, ..._context: unknown[]) => action === 'place_edit' ? canEdit : action === 'day_edit' && canAssign);
++ const access = vi.fn(async (id: string, userId: number) => id === '7' && userId === 2 ? trip : undefined);
++ const places = {
++ verifyTripAccess: access,
++ canEdit: vi.fn(async (t: typeof trip, u: User) => permission('place_edit', u.role, t.user_id, u.id, t.user_id !== u.id)),
++ };
++ const importGpxAsTour = vi.fn(async () => ({ tours: [{ place_id: 42 }], caution: false, skipped: 0 }));
++ const controller = new ToursImportController(
++ { importGpxAsTour } as unknown as ToursService,
++ places as unknown as PlacesService,
++ { isAddonEnabled: vi.fn(async () => true) } as unknown as AddonsService,
++ );
++ return { controller, access, permission, importGpxAsTour };
++}
++
++async function expectStatus(action: () => Promise<unknown>, status: number) {
+ try {
- action();
- expect.fail('Expected guard rejection');
++ await action();
++ expect.fail('Expected rejection');
+ } catch (error) {
+ expect(error).toBeInstanceOf(HttpException);
+ expect((error as HttpException).getStatus()).toBe(status);
+ }
+}
+
++const file = { buffer: Buffer.from('gpx'), originalname: 'ridge.gpx' } as Express.Multer.File;
++
+describe('Tours permission contract (mock-only, no DB)', () => {
++ it('does not access the legacy global database initializer', () => {
++ expect(legacyDatabaseAccess).not.toHaveBeenCalled();
++ });
++
+ it('retains addon/JWT/trip guard order and exact write metadata', () => {
+ expect(Reflect.getMetadata(GUARDS_METADATA, ToursController)).toEqual([AddonGuard, JwtAuthGuard, TripAccessGuard]);
- for (const handler of ['create', 'update', 'importGpx'] as const) {
++ expect(Reflect.getMetadata(GUARDS_METADATA, ToursImportController)).toEqual([JwtAuthGuard]);
++ for (const handler of ['create', 'update'] as const) {
+ expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, ToursController.prototype[handler])).toBe('place_edit');
+ }
+ for (const handler of ['list', 'detail'] as const) {
+ expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, ToursController.prototype[handler])).toBeUndefined();
+ }
+ });
+
- it.each([[false, false], [true, false], [false, true], [true, true]])('edit=%s assign=%s permits reads and only place-edit writes', (canEdit, canAssign) => {
++ it.each(matrix)('edit=%s assign=%s permits reads and only place-edit writes', async (canEdit, canAssign) => {
+ for (const handler of ['list', 'detail'] as const) {
+ const test = fixture(handler, canEdit, canAssign);
- expect(test.guard.canActivate(test.context)).toBe(true);
++ expect(await test.guard.canActivate(test.context)).toBe(true);
+ expect(test.permission).not.toHaveBeenCalled();
- expect(test.request[TRIP_REQUEST_KEY as keyof typeof test.request]).toEqual(test.trip);
++ expect(test.request[TRIP_REQUEST_KEY as keyof typeof test.request]).toEqual(trip);
+ }
- for (const handler of ['create', 'update', 'importGpx'] as const) {
++ for (const handler of ['create', 'update'] as const) {
+ const test = fixture(handler, canEdit, canAssign);
- if (canEdit) expect(test.guard.canActivate(test.context)).toBe(true);
- else expectStatus(() => test.guard.canActivate(test.context), 403);
- expect(test.permission).toHaveBeenCalledWith('place_edit', 'user', 1, 2, true);
++ if (canEdit) expect(await test.guard.canActivate(test.context)).toBe(true);
++ else await expectStatus(() => test.guard.canActivate(test.context), 403);
++ expect(test.permission).toHaveBeenCalledExactlyOnceWith('place_edit', 'user', 1, 2, true);
+ }
+ });
+
- it.each(['list', 'detail', 'create', 'update', 'importGpx'] as const)('%s rejects inaccessible route trips before any write permission check', handler => {
++ it.each(matrix)('edit=%s assign=%s: the GPX import handler requires only place_edit', async (canEdit, canAssign) => {
++ const test = importFixture(canEdit, canAssign);
++ if (canEdit) {
++ expect(await test.controller.importGpx(user, '7', file, 'socket')).toMatchObject({ tours: [{ place_id: 42 }] });
++ expect(test.importGpxAsTour).toHaveBeenCalledWith('7', file.buffer, 'ridge.gpx', 'socket');
++ } else {
++ await expectStatus(() => test.controller.importGpx(user, '7', file), 403);
++ expect(test.importGpxAsTour).not.toHaveBeenCalled();
++ }
++ expect(test.permission).toHaveBeenCalledExactlyOnceWith('place_edit', 'user', 1, 2, true);
++ });
++
++ it.each(['list', 'detail', 'create', 'update'] as const)('%s rejects inaccessible route trips before any write permission check', async handler => {
+ const test = fixture(handler, true, true, '8');
- expectStatus(() => test.guard.canActivate(test.context), 404);
++ await expectStatus(() => test.guard.canActivate(test.context), 404);
+ expect(test.access).toHaveBeenCalledWith(8, 2);
+ expect(test.permission).not.toHaveBeenCalled();
+ });
+
- it('preserves addon and JWT refusal without reaching trip resolution', () => {
++ it('importGpx rejects an inaccessible route trip before any permission check', async () => {
++ const test = importFixture(true, true);
++ await expectStatus(() => test.controller.importGpx(user, '8', file), 404);
++ expect(test.access).toHaveBeenCalledWith('8', 2);
++ expect(test.permission).not.toHaveBeenCalled();
++ expect(test.importGpxAsTour).not.toHaveBeenCalled();
++ });
++
++ it('preserves addon and JWT refusal without reaching trip resolution', async () => {
+ const test = fixture('create', true, true);
- const addon = new AddonGuard({ isAddonEnabled: vi.fn(() => false) } as never, new Reflector());
- expectStatus(() => addon.canActivate(test.context), 404);
++ const addon = new AddonGuard({ isAddonEnabled: vi.fn(async () => false) } as unknown as AddonsService, new Reflector());
++ await expectStatus(() => addon.canActivate(test.context), 404);
++ const jwt = new JwtAuthGuard({ getRepository: vi.fn() } as unknown as EntityManager);
+ vi.mocked(extractToken).mockReturnValue(null);
- const jwt = new JwtAuthGuard();
- expectStatus(() => jwt.canActivate(test.context), 401);
++ await expectStatus(() => jwt.canActivate(test.context), 401);
+ vi.mocked(extractToken).mockReturnValue('token');
- vi.mocked(verifyJwtAndLoadUser).mockReturnValue(null);
- expectStatus(() => jwt.canActivate(test.context), 401);
++ vi.mocked(verifyJwtAndLoadUser).mockResolvedValue(null);
++ await expectStatus(() => jwt.canActivate(test.context), 401);
+ expect(test.access).not.toHaveBeenCalled();
+ });
-
- it('delegates import with the route trip and preserves missing/empty-file prechecks', () => {
- const imported = { tours: [{ place_id: 42 }] };
- const importGpxAsTour = vi.fn(() => imported);
- const controller = new ToursController({ importGpxAsTour } as never);
- const buffer = Buffer.from('gpx');
- expect(controller.importGpx('7', { buffer, originalname: 'ridge.gpx' } as Express.Multer.File, 'socket')).toBe(imported);
- expect(importGpxAsTour).toHaveBeenCalledWith('7', buffer, 'ridge.gpx', 'socket');
- const allSkipped = { tours: [], caution: false, skipped: 2 };
- importGpxAsTour.mockReturnValueOnce(allSkipped as never);
- expect(controller.importGpx('7', { buffer, originalname: 'duplicates.gpx' } as Express.Multer.File)).toBe(allSkipped);
- expectStatus(() => controller.importGpx('7', undefined), 400);
- importGpxAsTour.mockReturnValueOnce(null as never);
- expectStatus(() => controller.importGpx('7', { buffer, originalname: 'empty.gpx' } as Express.Multer.File), 400);
- });
- });
++});
diff --cc server/tests/unit/nest/tours.service.permissions.test.ts
index 2ea2b682c,000000000..9da8adeeb
mode 100644,000000..100644
--- a/server/tests/unit/nest/tours.service.permissions.test.ts
+++ b/server/tests/unit/nest/tours.service.permissions.test.ts
@@@ -1,153 -1,0 +1,230 @@@
++/**
++ * ToursService write contracts against stubbed repositories and a stub
++ * UnitOfWork (the budget.service.test.ts pattern): which repository call runs
++ * with which arguments, and that every write runs inside the transaction while
++ * the read-back and the broadcasts run after it. Rollback against a real
++ * SQLite database is covered by tours.service.test.ts.
++ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
++import { NotFoundException } from '@nestjs/common';
+
- vi.mock('../../../src/config', () => { throw new Error('Config initialization is forbidden in mock-only tests'); });
- vi.mock('../../../src/db/database', () => { throw new Error('Legacy database imports are forbidden in mock-only tests'); });
- vi.mock('../../../src/nest/database/database.service', () => ({
- DatabaseService: vi.fn(() => { throw new Error('Database construction is forbidden in mock-only tests'); }),
++const { legacyDatabaseAccess } = vi.hoisted(() => ({
++ legacyDatabaseAccess: vi.fn((property: string | symbol): never => {
++ throw new Error(`Unexpected legacy database access: ${String(property)}`);
++ }),
++}));
++
++vi.mock('../../../src/config', () => ({
++ ENCRYPTION_KEY: 'test-only-inert-key',
++ JWT_SECRET: 'test-only-inert-secret',
++ updateJwtSecret: vi.fn(),
++}));
++vi.mock('../../../src/db/database', () => ({
++ db: new Proxy({}, {
++ get: (_target, property: string | symbol) => legacyDatabaseAccess(property),
++ }),
+}));
- vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in mock-only tests'); });
+vi.mock('../../../src/nest/places/places.service', () => ({ PlacesService: class {} }));
+
+import { ToursService } from '../../../src/nest/tours/tours.service';
+import { tourCreateRequestSchema, type TourCreateRequest } from '@trek/shared';
++import type { UnitOfWork } from '../../../src/nest/database/unit-of-work';
++import type { PlacesService } from '../../../src/nest/places/places.service';
++import type { PlacesRepository } from '../../../src/db/repositories/Places.repository';
++import type { ToursRepository } from '../../../src/db/repositories/Tours.repository';
++import type { TourWaypointsRepository } from '../../../src/db/repositories/TourWaypoints.repository';
++
++const request: TourCreateRequest = {
++ name: 'Ridge walk',
++ tour_type: 'hike',
++ route_geometry: [[48, 11, 600], [48.01, 11.02, 650], [48.02, 11.04, 630]],
++ waypoints: [
++ { lat: 48, lng: 11, role: 'start', sequence: 0 },
++ { lat: 48.02, lng: 11.04, role: 'end', sequence: 1 },
++ ],
++ max_hiking_difficulty: 2,
++ duration_seconds: 3600,
++};
+
+function makeService() {
+ const row = {
+ place_id: 42, name: request.name, tour_type: 'hike', distance: 3,
+ elevation_gain: 50, elevation_loss: 20, duration: 60, difficulty: null,
+ wanderer_ref: null, match_confidence: 1, tour_group_id: null,
+ max_hiking_difficulty: 2, planned: 0, has_waypoints: 1,
+ };
++ const place = { id: 42, trip_id: 7 };
+ let inTransaction = false;
- const waypointRun = vi.fn(() => { expect(inTransaction).toBe(true); });
- const db = {
- get: vi.fn((): unknown => row),
- all: vi.fn((sql: string): unknown[] => sql.includes('JOIN places') ? [row] : request.waypoints),
- run: vi.fn<(sql: string, ...params: unknown[]) => { lastInsertRowid: number }>(() => {
- expect(inTransaction).toBe(true);
- return { lastInsertRowid: 42 };
- }),
- prepare: vi.fn(() => {
- expect(inTransaction).toBe(true);
- return { run: waypointRun };
- }),
- transaction: vi.fn((write: () => void) => {
++ /** Records whether each write ran inside the transaction. */
++ const inTx = <T>(value: T) => vi.fn(async (..._args: unknown[]) => { expect(inTransaction).toBe(true); return value; });
++
++ const uow = {
++ transactional: vi.fn(async <T>(fn: () => Promise<T>): Promise<T> => {
+ inTransaction = true;
- try { write(); } finally { inTransaction = false; }
++ try { return await fn(); } finally { inTransaction = false; }
+ }),
- getPlaceWithTags: vi.fn(() => ({ id: 42, trip_id: 7 })),
+ };
- const places = { broadcast: vi.fn() };
- return { db, waypointRun, places, service: new ToursService(db as never, places as never) };
++ const toursRepo = {
++ findInTrip: vi.fn(async (): Promise<typeof row | undefined> => row),
++ insertTour: inTx(undefined),
++ updateInTrip: inTx(true),
++ };
++ const waypointsRepo = {
++ listForPlace: vi.fn(async () => request.waypoints),
++ insertForPlace: inTx(undefined),
++ deleteForPlace: inTx(undefined),
++ };
++ const placesRepo = {
++ insertTourPlace: inTx(42),
++ updateTourRoute: inTx(true),
++ findInTrip: vi.fn(async (): Promise<{ route_geometry: string | null } | undefined> => undefined),
++ findWithTagsAndRatings: vi.fn(async () => {
++ expect(inTransaction).toBe(false);
++ return place;
++ }),
++ };
++ const places = { broadcast: vi.fn(() => { expect(inTransaction).toBe(false); }) };
++ const service = new ToursService(
++ uow as unknown as UnitOfWork,
++ places as unknown as PlacesService,
++ toursRepo as unknown as ToursRepository,
++ waypointsRepo as unknown as TourWaypointsRepository,
++ placesRepo as unknown as PlacesRepository,
++ );
++ return { uow, toursRepo, waypointsRepo, placesRepo, places, place, service };
+}
+
- const request: TourCreateRequest = {
- name: 'Ridge walk',
- tour_type: 'hike',
- route_geometry: [[48, 11, 600], [48.01, 11.02, 650], [48.02, 11.04, 630]],
- waypoints: [
- { lat: 48, lng: 11, role: 'start', sequence: 0 },
- { lat: 48.02, lng: 11.04, role: 'end', sequence: 1 },
- ],
- max_hiking_difficulty: 2,
- duration_seconds: 3600,
- };
-
- describe('ToursService planner contracts (mock-only; SQLite rollback semantics require separate integration coverage)', () => {
++describe('ToursService planner contracts (mock-only; SQLite rollback semantics are covered in tours.service.test.ts)', () => {
+ let setup: ReturnType<typeof makeService>;
+ beforeEach(() => { setup = makeService(); });
+
- it('TOURS-SVC-001: sends geometry, metrics, and ordered controls through one injected transaction', () => {
- const result = setup.service.createTour('7', request, 'socket-1');
-
- expect(setup.db.transaction).toHaveBeenCalledOnce();
- expect(setup.db.run).toHaveBeenCalledTimes(2);
- expect(setup.db.run).toHaveBeenNthCalledWith(1, expect.stringContaining('INSERT INTO places'), '7', request.name, 48, 11, JSON.stringify(request.route_geometry));
- expect(setup.db.run).toHaveBeenNthCalledWith(2, expect.stringContaining('INSERT INTO tours'), 42, 'hike', expect.any(Number), 50, 20, 60, 2);
- expect(setup.db.run.mock.calls[1][3]).toBeGreaterThan(0);
- expect(setup.waypointRun).toHaveBeenCalledTimes(2);
- for (const waypoint of request.waypoints) {
- expect(setup.waypointRun).toHaveBeenCalledWith(42, waypoint.lat, waypoint.lng, waypoint.role, waypoint.sequence);
- }
++ it('does not access the legacy global database initializer', () => {
++ expect(legacyDatabaseAccess).not.toHaveBeenCalled();
++ });
++
++ it('TOURS-SVC-001: sends geometry, metrics, and ordered controls through one transaction', async () => {
++ const result = await setup.service.createTour('7', request, 'socket-1');
++
++ expect(setup.uow.transactional).toHaveBeenCalledOnce();
++ expect(setup.placesRepo.insertTourPlace).toHaveBeenCalledExactlyOnceWith({
++ trip_id: 7, name: request.name, lat: 48, lng: 11, route_geometry: JSON.stringify(request.route_geometry),
++ });
++ expect(setup.toursRepo.insertTour).toHaveBeenCalledExactlyOnceWith({
++ place_id: 42, tour_type: 'hike', distance: expect.any(Number), elevation_gain: 50, elevation_loss: 20,
++ duration: 60, match_confidence: 1, max_hiking_difficulty: 2,
++ });
++ expect((setup.toursRepo.insertTour.mock.calls[0][0] as { distance: number }).distance).toBeGreaterThan(0);
++ expect(setup.waypointsRepo.insertForPlace).toHaveBeenCalledExactlyOnceWith(42, request.waypoints);
++ expect(setup.toursRepo.findInTrip).toHaveBeenCalledWith(7, 42);
+ expect(result.tour).toMatchObject({ name: 'Ridge walk', planned: false, has_waypoints: true });
+ expect(result.waypoints).toEqual(request.waypoints);
+ expect(setup.places.broadcast).toHaveBeenNthCalledWith(1, '7', 'tours:changed', { placeIds: [42] }, 'socket-1');
- expect(setup.places.broadcast).toHaveBeenNthCalledWith(2, '7', 'place:created', { place: { id: 42, trip_id: 7 } }, 'socket-1');
++ expect(setup.places.broadcast).toHaveBeenNthCalledWith(2, '7', 'place:created', { place: setup.place }, 'socket-1');
+ });
+
- it('TOURS-SVC-002: propagates injected waypoint failure without publishing or reading an uncommitted create', () => {
++ it('TOURS-SVC-002: propagates a waypoint failure without publishing or reading an uncommitted create', async () => {
+ const failure = new Error('Injected waypoint failure');
- setup.waypointRun.mockImplementationOnce(() => { throw failure; });
- expect(() => setup.service.createTour('7', request)).toThrow(failure);
- expect(setup.db.transaction).toHaveBeenCalledOnce();
- expect(setup.db.all).not.toHaveBeenCalled();
- expect(setup.db.getPlaceWithTags).not.toHaveBeenCalled();
++ setup.waypointsRepo.insertForPlace.mockRejectedValueOnce(failure);
++
++ await expect(setup.service.createTour('7', request)).rejects.toBe(failure);
++
++ expect(setup.uow.transactional).toHaveBeenCalledOnce();
++ expect(setup.toursRepo.findInTrip).not.toHaveBeenCalled();
++ expect(setup.placesRepo.findWithTagsAndRatings).not.toHaveBeenCalled();
+ expect(setup.places.broadcast).not.toHaveBeenCalled();
+ });
+
- it('TOURS-SVC-003: validates and rounds fractional routed duration before the create write', () => {
++ it('TOURS-SVC-003: validates and rounds a fractional routed duration before the create write', async () => {
+ const validated = tourCreateRequestSchema.parse({ ...request, duration_seconds: 3599.5 });
- const result = setup.service.createTour('7', validated);
- expect(setup.db.run).toHaveBeenNthCalledWith(2, expect.stringContaining('INSERT INTO tours'), 42, 'hike', expect.any(Number), 50, 20, 60, 2);
++ const result = await setup.service.createTour('7', validated);
++ expect(setup.toursRepo.insertTour).toHaveBeenCalledWith(expect.objectContaining({ place_id: 42, duration: 60 }));
+ expect(result.tour).toMatchObject({ name: 'Ridge walk', planned: false });
+ });
+
- it('TOURS-SVC-004: scopes detail reads to the trip and derives legacy GPX controls without writes', () => {
- expect(setup.service.getTour('7', '42').waypoints).toEqual(request.waypoints);
- expect(setup.db.get).toHaveBeenCalledWith(expect.stringMatching(/WHERE p.trip_id = \? AND p.id = \?/), '7', '42');
- expect(setup.db.all).toHaveBeenCalledWith(expect.stringContaining('ORDER BY sequence'), '42');
- setup.db.get.mockReturnValueOnce(undefined);
- setup.db.all.mockClear();
- expect(() => setup.service.getTour('8', '42')).toThrow('Tour not found');
- expect(setup.db.all).not.toHaveBeenCalled();
- setup.db.get.mockReturnValueOnce({ place_id: 42, has_waypoints: 0 }).mockReturnValueOnce({ route_geometry: JSON.stringify(request.route_geometry) });
- setup.db.all.mockReturnValueOnce([]);
- const legacyGpx = setup.service.getTour('7', '42');
- expect(legacyGpx.tour.has_waypoints).toBe(false);
++ it('TOURS-SVC-004: scopes detail reads to the trip and derives legacy GPX controls without writes', async () => {
++ expect((await setup.service.getTour('7', '42')).waypoints).toEqual(request.waypoints);
++ expect(setup.toursRepo.findInTrip).toHaveBeenCalledWith(7, 42);
++ expect(setup.waypointsRepo.listForPlace).toHaveBeenCalledWith(42);
++
++ setup.toursRepo.findInTrip.mockResolvedValueOnce(undefined);
++ setup.waypointsRepo.listForPlace.mockClear();
++ await expect(setup.service.getTour('8', '42')).rejects.toThrow('Tour not found');
++ expect(setup.waypointsRepo.listForPlace).not.toHaveBeenCalled();
++
++ setup.waypointsRepo.listForPlace.mockResolvedValueOnce([]);
++ setup.placesRepo.findInTrip.mockResolvedValueOnce({ route_geometry: JSON.stringify(request.route_geometry) });
++ const legacyGpx = await setup.service.getTour('7', '42');
++ expect(setup.placesRepo.findInTrip).toHaveBeenCalledWith(42, 7);
+ expect(legacyGpx.waypoints).toEqual([
+ { lat: 48, lng: 11, role: 'start', sequence: 0 },
+ { lat: 48.02, lng: 11.04, role: 'end', sequence: 1 },
+ ]);
- for (const method of [setup.db.transaction, setup.db.run, setup.db.prepare, setup.waypointRun, setup.places.broadcast]) {
++ for (const method of [
++ setup.uow.transactional, setup.placesRepo.insertTourPlace, setup.placesRepo.updateTourRoute,
++ setup.toursRepo.insertTour, setup.toursRepo.updateInTrip,
++ setup.waypointsRepo.insertForPlace, setup.waypointsRepo.deleteForPlace, setup.places.broadcast,
++ ]) {
+ expect(method).not.toHaveBeenCalled();
+ }
+ });
+
- it('TOURS-SVC-005: updates route data and replaces controls through the injected transaction', () => {
++ it('TOURS-SVC-005: updates route data and replaces controls through one transaction', async () => {
+ const update: TourCreateRequest = {
+ ...request,
+ name: 'Updated ridge walk',
+ route_geometry: [[49, 12, 700], [49.02, 12.04, 760]],
+ waypoints: [
+ { lat: 49, lng: 12, role: 'start', sequence: 0 },
+ { lat: 49.01, lng: 12.02, role: 'via', sequence: 1 },
+ { lat: 49.02, lng: 12.04, role: 'end', sequence: 2 },
+ ],
+ duration_seconds: 2700.5,
+ };
+
- setup.service.updateTour('7', '42', update, 'socket-2');
- expect(setup.db.transaction).toHaveBeenCalledOnce();
- expect(setup.db.run).toHaveBeenCalledTimes(3);
- expect(setup.db.run).toHaveBeenNthCalledWith(1, expect.stringMatching(/WHERE id = \? AND trip_id = \?/), update.name, 49, 12, JSON.stringify(update.route_geometry), '42', '7');
- expect(setup.db.run).toHaveBeenNthCalledWith(2, expect.stringContaining('UPDATE tours'), 'hike', expect.any(Number), 60, 0, 45, 2, '42');
- expect(setup.db.run).toHaveBeenNthCalledWith(3, 'DELETE FROM tour_waypoints WHERE place_id = ?', '42');
- expect(setup.waypointRun).toHaveBeenCalledTimes(3);
- for (const waypoint of update.waypoints) {
- expect(setup.waypointRun).toHaveBeenCalledWith('42', waypoint.lat, waypoint.lng, waypoint.role, waypoint.sequence);
- }
- expect(setup.places.broadcast).toHaveBeenCalledWith(
- '7', 'place:updated', expect.objectContaining({ place: expect.anything() }), 'socket-2',
- );
++ await setup.service.updateTour('7', '42', update, 'socket-2');
++
++ expect(setup.uow.transactional).toHaveBeenCalledOnce();
++ expect(setup.placesRepo.updateTourRoute).toHaveBeenCalledExactlyOnceWith(42, 7, {
++ name: update.name, lat: 49, lng: 12, route_geometry: JSON.stringify(update.route_geometry),
++ });
++ expect(setup.toursRepo.updateInTrip).toHaveBeenCalledExactlyOnceWith(7, 42, {
++ tour_type: 'hike', distance: expect.any(Number), elevation_gain: 60, elevation_loss: 0,
++ duration: 45, match_confidence: 1, max_hiking_difficulty: 2,
++ });
++ expect(setup.waypointsRepo.deleteForPlace).toHaveBeenCalledExactlyOnceWith(42);
++ expect(setup.waypointsRepo.insertForPlace).toHaveBeenCalledExactlyOnceWith(42, update.waypoints);
++ expect(setup.waypointsRepo.deleteForPlace.mock.invocationCallOrder[0])
++ .toBeLessThan(setup.waypointsRepo.insertForPlace.mock.invocationCallOrder[0]);
++ expect(setup.places.broadcast).toHaveBeenCalledWith('7', 'place:updated', { place: setup.place }, 'socket-2');
+ });
+
- it('TOURS-SVC-006: propagates injected replacement failure without publishing or reloading', () => {
++ it('TOURS-SVC-006: propagates a replacement failure without publishing or reloading', async () => {
+ const failure = new Error('Injected replacement failure');
- setup.waypointRun.mockImplementationOnce(() => { throw failure; });
- expect(() => setup.service.updateTour('7', '42', request)).toThrow(failure);
- expect(setup.db.transaction).toHaveBeenCalledOnce();
- expect(setup.db.get).toHaveBeenCalledTimes(1);
- expect(setup.db.getPlaceWithTags).not.toHaveBeenCalled();
++ setup.waypointsRepo.insertForPlace.mockRejectedValueOnce(failure);
++
++ await expect(setup.service.updateTour('7', '42', request)).rejects.toBe(failure);
++
++ expect(setup.uow.transactional).toHaveBeenCalledOnce();
++ expect(setup.toursRepo.findInTrip).toHaveBeenCalledTimes(1);
++ expect(setup.placesRepo.findWithTagsAndRatings).not.toHaveBeenCalled();
++ expect(setup.places.broadcast).not.toHaveBeenCalled();
++ });
++
++ it.each([
++ ['the tour lookup', 'findInTrip'],
++ ['the trip-scoped place update', 'updateTourRoute'],
++ ['the trip-scoped tour update', 'updateInTrip'],
++ ] as const)('TOURS-SVC-010: a miss in %s is a 404 that stops the write', async (_label, step) => {
++ if (step === 'findInTrip') setup.toursRepo.findInTrip.mockResolvedValueOnce(undefined);
++ if (step === 'updateTourRoute') setup.placesRepo.updateTourRoute.mockResolvedValueOnce(false);
++ if (step === 'updateInTrip') setup.toursRepo.updateInTrip.mockResolvedValueOnce(false);
++
++ await expect(setup.service.updateTour('7', '42', request)).rejects.toBeInstanceOf(NotFoundException);
++
++ // The existence check runs inside the write's own transaction (F44).
++ expect(setup.uow.transactional).toHaveBeenCalledOnce();
++ expect(setup.waypointsRepo.deleteForPlace).not.toHaveBeenCalled();
++ expect(setup.waypointsRepo.insertForPlace).not.toHaveBeenCalled();
+ expect(setup.places.broadcast).not.toHaveBeenCalled();
+ });
- });
++});
diff --cc server/tests/unit/nest/tours.service.test.ts
index 662d95dfd,000000000..f250a6407
mode 100644,000000..100644
--- a/server/tests/unit/nest/tours.service.test.ts
+++ b/server/tests/unit/nest/tours.service.test.ts
@@@ -1,210 -1,0 +1,282 @@@
- import { beforeEach, describe, expect, it, vi } from 'vitest';
- import Database from 'better-sqlite3';
- import { Logger } from '@nestjs/common';
-
- const { legacyDatabaseAccess } = vi.hoisted(() => ({
- legacyDatabaseAccess: vi.fn((property: string | symbol): never => {
- throw new Error(`Unexpected legacy database access: ${String(property)}`);
- }),
- }));
++/**
++ * ToursService over the real migrated per-worker DB: the tours facet, its
++ * ordered control points and the owning place are written through the Tours,
++ * TourWaypoints and Places repositories inside one UnitOfWork transaction, and
++ * realtime events go out only after that transaction committed.
++ *
++ * PlacesService is a broadcast stub here; the GPX import path, which needs the
++ * real PlacesService, is covered by tours.gpx.atomic.test.ts.
++ */
++import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
++import { Logger, NotFoundException } from '@nestjs/common';
+
++vi.mock('../../../src/db/database', async () => {
++ const { createSnapshotTestDb, buildDbMock } = await import('../../helpers/db-mock');
++ return buildDbMock(createSnapshotTestDb());
++});
+vi.mock('../../../src/config', () => ({
- ENCRYPTION_KEY: 'test-only-inert-key',
- JWT_SECRET: 'test-only-inert-secret',
- updateJwtSecret: vi.fn(),
- }));
- vi.mock('../../../src/db/database', () => ({
- db: new Proxy({}, {
- get: (_target, property: string | symbol) => legacyDatabaseAccess(property),
- }),
++ JWT_SECRET: 'test-secret',
++ ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
++ updateJwtSecret: () => {},
+}));
+
- import { ToursService } from '../../../src/nest/tours/tours.service';
++import { db as testDb } from '../../../src/db/database';
+import { tourCreateRequestSchema, type TourCreateRequest } from '@trek/shared';
-
- function makeService() {
- const raw = new Database(':memory:');
- raw.pragma('foreign_keys = ON');
- raw.exec(`
- CREATE TABLE places (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- trip_id INTEGER NOT NULL,
- name TEXT NOT NULL,
- lat REAL,
- lng REAL,
- transport_mode TEXT,
- route_geometry TEXT
- );
- CREATE TABLE day_assignments (place_id INTEGER);
- CREATE TABLE tour_types (key TEXT PRIMARY KEY);
- INSERT INTO tour_types (key) VALUES ('hike');
- CREATE TABLE tours (
- place_id INTEGER PRIMARY KEY REFERENCES places(id) ON DELETE CASCADE,
- tour_type TEXT NOT NULL REFERENCES tour_types(key),
- distance REAL, elevation_gain REAL, elevation_loss REAL, duration REAL,
- difficulty TEXT, wanderer_ref TEXT, match_confidence REAL,
- tour_group_id INTEGER, max_hiking_difficulty INTEGER NOT NULL DEFAULT 2,
- created_at TEXT DEFAULT CURRENT_TIMESTAMP
- );
- CREATE TABLE tour_waypoints (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- place_id INTEGER NOT NULL REFERENCES tours(place_id) ON DELETE CASCADE,
- lat REAL NOT NULL, lng REAL NOT NULL,
- role TEXT NOT NULL CHECK(role IN ('start', 'via', 'end')),
- sequence INTEGER NOT NULL,
- UNIQUE(place_id, sequence)
- );
- `);
- const db = {
- get: <T>(sql: string, ...params: unknown[]) => raw.prepare(sql).get(...params as never[]) as T | undefined,
- all: <T>(sql: string, ...params: unknown[]) => raw.prepare(sql).all(...params as never[]) as T[],
- run: (sql: string, ...params: unknown[]) => raw.prepare(sql).run(...params as never[]),
- prepare: (sql: string) => raw.prepare(sql),
- transaction: <T>(fn: () => T) => raw.transaction(fn)(),
- getPlaceWithTags: (id: number) => raw.prepare('SELECT * FROM places WHERE id = ?').get(id),
- };
- const places = { broadcast: vi.fn() };
- return { raw, places, service: new ToursService(db as never, places as never) };
- }
++import { ToursService } from '../../../src/nest/tours/tours.service';
++import type { PlacesService } from '../../../src/nest/places/places.service';
++import { resetTestDb } from '../../helpers/test-db';
++import { createPlace, createTrip, createUser } from '../../helpers/factories';
++import { createTestPlacesRepo, createTestUnitOfWork, sharedTestOrm } from '../../helpers/test-uow';
++import { createTestToursRepo, createTestTourWaypointsRepo, createTour } from '../../helpers/tours-repos';
+
+const request: TourCreateRequest = {
+ name: 'Ridge walk',
+ tour_type: 'hike',
+ route_geometry: [[48, 11, 600], [48.01, 11.02, 650], [48.02, 11.04, 630]],
+ waypoints: [
+ { lat: 48, lng: 11, role: 'start', sequence: 0 },
+ { lat: 48.02, lng: 11.04, role: 'end', sequence: 1 },
+ ],
+ max_hiking_difficulty: 2,
+ duration_seconds: 3600,
+};
+
- describe('ToursService planner creation', () => {
- let setup: ReturnType<typeof makeService>;
- beforeEach(() => { setup = makeService(); });
++/** Two waypoints on the same sequence: the UNIQUE(place_id, sequence) index rejects the second one. */
++const duplicateSequence = {
++ ...request,
++ waypoints: [request.waypoints[0], { ...request.waypoints[1], sequence: 0 }],
++} as TourCreateRequest;
+
- it('does not access the legacy global database initializer', () => {
- expect(legacyDatabaseAccess).not.toHaveBeenCalled();
- });
++const broadcast = vi.fn();
++let service: ToursService;
++let tripId: string;
++let otherTripId: string;
+
- it('TOURS-SVC-001: atomically stores full geometry, derived metrics, and ordered control points', () => {
++const count = (table: string) => (testDb.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n;
++
++beforeAll(async () => {
++ service = new ToursService(
++ await createTestUnitOfWork(testDb),
++ { broadcast } as unknown as PlacesService,
++ await createTestToursRepo(testDb),
++ await createTestTourWaypointsRepo(testDb),
++ await createTestPlacesRepo(testDb),
++ );
++});
++
++beforeEach(async () => {
++ resetTestDb(testDb);
++ (await sharedTestOrm(testDb)).clear();
++ broadcast.mockReset();
++ const { user } = createUser(testDb);
++ tripId = String(createTrip(testDb, user.id).id);
++ otherTripId = String(createTrip(testDb, user.id).id);
++});
++
++afterEach(() => { vi.restoreAllMocks(); });
++
++afterAll(() => { testDb.close(); });
++
++describe('ToursService planner creation', () => {
++ it('TOURS-SVC-001: atomically stores full geometry, derived metrics, and ordered control points', async () => {
+ const writeStates: boolean[] = [];
- setup.places.broadcast.mockImplementation(() => { writeStates.push(setup.raw.inTransaction); });
- const result = setup.service.createTour('7', request, 'socket-1');
++ broadcast.mockImplementation(() => { writeStates.push(testDb.inTransaction); });
+
- const place = setup.raw.prepare('SELECT * FROM places').get() as Record<string, unknown>;
- const tour = setup.raw.prepare('SELECT * FROM tours').get() as Record<string, unknown>;
- const points = setup.raw.prepare('SELECT role, sequence FROM tour_waypoints ORDER BY sequence').all();
++ const result = await service.createTour(tripId, request, 'socket-1');
+
++ const placeId = result.tour.place_id;
++ const place = testDb.prepare('SELECT * FROM places WHERE id = ?').get(placeId) as Record<string, unknown>;
++ const tour = testDb.prepare('SELECT * FROM tours WHERE place_id = ?').get(placeId) as Record<string, unknown>;
++ const points = testDb.prepare('SELECT role, sequence FROM tour_waypoints WHERE place_id = ? ORDER BY sequence').all(placeId);
++
++ expect(place).toMatchObject({ trip_id: Number(tripId), name: 'Ridge walk', lat: 48, lng: 11, transport_mode: 'walking' });
+ expect(JSON.parse(String(place.route_geometry))).toEqual(request.route_geometry);
++ expect(tour).toMatchObject({ tour_type: 'hike', match_confidence: 1, max_hiking_difficulty: 2 });
+ expect(tour.distance).toBeGreaterThan(0);
+ expect(tour.elevation_gain).toBe(50);
+ expect(tour.elevation_loss).toBe(20);
+ expect(tour.duration).toBe(60);
+ expect(points).toEqual([{ role: 'start', sequence: 0 }, { role: 'end', sequence: 1 }]);
- expect(result.tour).toMatchObject({ name: 'Ridge walk', planned: false, has_waypoints: true });
- expect(setup.places.broadcast).toHaveBeenNthCalledWith(1, '7', 'tours:changed', { placeIds: [1] }, 'socket-1');
- expect(setup.places.broadcast).toHaveBeenNthCalledWith(2, '7', 'place:created', { place: expect.anything() }, 'socket-1');
- expect(setup.places.broadcast).toHaveBeenCalledTimes(2);
++ expect(result.tour).toMatchObject({ name: 'Ridge walk', planned: false, has_waypoints: true, caution: false });
++ expect(result.waypoints).toEqual(request.waypoints);
++ expect(broadcast).toHaveBeenNthCalledWith(1, tripId, 'tours:changed', { placeIds: [placeId] }, 'socket-1');
++ expect(broadcast).toHaveBeenNthCalledWith(2, tripId, 'place:created', { place: expect.objectContaining({ id: placeId }) }, 'socket-1');
++ expect(broadcast).toHaveBeenCalledTimes(2);
++ // Both events go out after the commit, never from inside the write.
+ expect(writeStates).toEqual([false, false]);
+ });
+
- it('TOURS-SVC-002: rolls the owning place and facet back when a waypoint insert fails', () => {
- const invalid = {
- ...request,
- waypoints: [request.waypoints[0], { ...request.waypoints[1], sequence: 0 }],
- } as TourCreateRequest;
++ it('TOURS-SVC-002: rolls the owning place and facet back when a waypoint insert fails', async () => {
++ await expect(service.createTour(tripId, duplicateSequence)).rejects.toThrow();
+
- expect(() => setup.service.createTour('7', invalid)).toThrow();
- expect(setup.raw.prepare('SELECT count(*) AS n FROM places').get()).toEqual({ n: 0 });
- expect(setup.raw.prepare('SELECT count(*) AS n FROM tours').get()).toEqual({ n: 0 });
- expect(setup.places.broadcast).not.toHaveBeenCalled();
++ expect(count('places')).toBe(0);
++ expect(count('tours')).toBe(0);
++ expect(count('tour_waypoints')).toBe(0);
++ expect(broadcast).not.toHaveBeenCalled();
+ });
+
- it('TOURS-SVC-003: validates a fractional routed duration before the atomic create', () => {
++ it('TOURS-SVC-003: validates a fractional routed duration before the atomic create', async () => {
+ const validated = tourCreateRequestSchema.parse({ ...request, duration_seconds: 3599.5 });
+
- const result = setup.service.createTour('7', validated);
++ const result = await service.createTour(tripId, validated);
+
- expect(setup.raw.prepare('SELECT count(*) AS n FROM places').get()).toEqual({ n: 1 });
- expect(setup.raw.prepare('SELECT count(*) AS n FROM tours').get()).toEqual({ n: 1 });
- expect(setup.raw.prepare('SELECT count(*) AS n FROM tour_waypoints').get()).toEqual({ n: 2 });
- expect(setup.raw.prepare('SELECT duration FROM tours').get()).toEqual({ duration: 60 });
++ expect(count('places')).toBe(1);
++ expect(count('tours')).toBe(1);
++ expect(count('tour_waypoints')).toBe(2);
++ expect(testDb.prepare('SELECT duration FROM tours').get()).toEqual({ duration: 60 });
+ expect(result.tour).toMatchObject({ name: 'Ridge walk', planned: false });
+ });
+
- it('TOURS-SVC-004: loads only a trip-owned tour with its ordered control points', () => {
- const created = setup.service.createTour('7', request);
++ it('TOURS-SVC-003b: stores no duration when the client sends none', async () => {
++ const { duration_seconds: _omitted, ...withoutDuration } = request;
++ const result = await service.createTour(tripId, withoutDuration);
++ expect(result.tour.duration).toBeNull();
++ });
++
++ it('keeps a committed create successful when Tours invalidation publication fails', async () => {
++ const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {});
++ broadcast.mockImplementation((_tripId: string, event: string) => {
++ if (event === 'tours:changed') throw new Error('transport unavailable');
++ });
++
++ const result = await service.createTour(tripId, request);
++
++ expect(result.tour.name).toBe('Ridge walk');
++ expect(count('places')).toBe(1);
++ expect(count('tours')).toBe(1);
++ expect(broadcast).toHaveBeenCalledTimes(2);
++ expect(warn).toHaveBeenCalledOnce();
++ });
++
++ it('keeps a committed create successful when the place notification fails', async () => {
++ const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {});
++ broadcast.mockImplementation((_tripId: string, event: string) => {
++ if (event === 'place:created') throw new Error('transport unavailable');
++ });
++
++ await expect(service.createTour(tripId, request)).resolves.toMatchObject({ tour: { name: 'Ridge walk' } });
++ expect(warn).toHaveBeenCalledOnce();
++ });
++});
++
++describe('ToursService reads', () => {
++ it('TOURS-SVC-004: loads only a trip-owned tour with its ordered control points', async () => {
++ const created = await service.createTour(tripId, request);
++ const placeId = String(created.tour.place_id);
+
- expect(setup.service.getTour('7', String(created.tour.place_id))).toEqual(created);
- expect(() => setup.service.getTour('8', String(created.tour.place_id))).toThrow('Tour not found');
++ expect(await service.getTour(tripId, placeId)).toEqual(created);
++ await expect(service.getTour(otherTripId, placeId)).rejects.toThrow('Tour not found');
+
- setup.raw.prepare('DELETE FROM tour_waypoints WHERE place_id = ?').run(created.tour.place_id);
- const legacyGpx = setup.service.getTour('7', String(created.tour.place_id));
++ testDb.prepare('DELETE FROM tour_waypoints WHERE place_id = ?').run(created.tour.place_id);
++ const legacyGpx = await service.getTour(tripId, placeId);
+ expect(legacyGpx.tour.has_waypoints).toBe(false);
+ expect(legacyGpx.waypoints).toEqual([
+ { lat: 48, lng: 11, role: 'start', sequence: 0 },
+ { lat: 48.02, lng: 11.04, role: 'end', sequence: 1 },
+ ]);
++ // The fallback is read-only: nothing was backfilled.
++ expect(count('tour_waypoints')).toBe(0);
+ });
+
- it('TOURS-SVC-005: atomically updates route data and replaces persisted control points', () => {
- const created = setup.service.createTour('7', request);
- setup.places.broadcast.mockClear();
++ it('TOURS-SVC-004b: a plain place, a malformed id and a geometry-less tour', async () => {
++ const plain = createPlace(testDb, Number(tripId), { name: 'Not a tour' });
++ await expect(service.getTour(tripId, String(plain.id))).rejects.toBeInstanceOf(NotFoundException);
++ await expect(service.getTour(tripId, 'abc')).rejects.toThrow('Tour not found');
++ await expect(service.getTour('abc', String(plain.id))).rejects.toThrow('Tour not found');
++
++ const bare = createPlace(testDb, Number(tripId), { name: 'Bare import' });
++ createTour(testDb, bare.id);
++ const detail = await service.getTour(tripId, String(bare.id));
++ expect(detail.tour).toMatchObject({ place_id: bare.id, has_waypoints: false });
++ expect(detail.waypoints).toEqual([]);
++ });
++
++ it('TOURS-SVC-007: lists only this trip\'s tours, newest first, with the caution flag', async () => {
++ const older = createPlace(testDb, Number(tripId), { name: 'Older' });
++ const newer = createPlace(testDb, Number(tripId), { name: 'Newer' });
++ const foreign = createPlace(testDb, Number(otherTripId), { name: 'Foreign' });
++ createPlace(testDb, Number(tripId), { name: 'Plain place' });
++ createTour(testDb, older.id, { created_at: '2026-01-01 10:00:00', match_confidence: 0.3 });
++ createTour(testDb, newer.id, { created_at: '2026-02-01 10:00:00', match_confidence: 1 });
++ createTour(testDb, foreign.id);
++
++ const list = await service.listTours(tripId);
++
++ expect(list.map(t => t.name)).toEqual(['Newer', 'Older']);
++ expect(list[0]).toMatchObject({ caution: false, planned: false, has_waypoints: false, tour_type: 'hike' });
++ expect(list[1]).toMatchObject({ caution: true, match_confidence: 0.3 });
++ expect(await service.listTours('not-a-number')).toEqual([]);
++ });
++});
++
++describe('ToursService updates', () => {
++ const update: TourCreateRequest = {
++ ...request,
++ name: 'Updated ridge walk',
++ route_geometry: [[49, 12, 700], [49.02, 12.04, 760]],
++ waypoints: [
++ { lat: 49, lng: 12, role: 'start', sequence: 0 },
++ { lat: 49.01, lng: 12.02, role: 'via', sequence: 1 },
++ { lat: 49.02, lng: 12.04, role: 'end', sequence: 2 },
++ ],
++ duration_seconds: 2700.5,
++ };
++
++ it('TOURS-SVC-005: atomically updates route data and replaces persisted control points', async () => {
++ const created = await service.createTour(tripId, request);
++ broadcast.mockReset();
+ const writeStates: boolean[] = [];
- setup.places.broadcast.mockImplementation(() => { writeStates.push(setup.raw.inTransaction); });
- const update: TourCreateRequest = {
- ...request,
- name: 'Updated ridge walk',
- route_geometry: [[49, 12, 700], [49.02, 12.04, 760]],
- waypoints: [
- { lat: 49, lng: 12, role: 'start', sequence: 0 },
- { lat: 49.01, lng: 12.02, role: 'via', sequence: 1 },
- { lat: 49.02, lng: 12.04, role: 'end', sequence: 2 },
- ],
- duration_seconds: 2700.5,
- };
-
- const result = setup.service.updateTour('7', String(created.tour.place_id), update, 'socket-2');
++ broadcast.mockImplementation(() => { writeStates.push(testDb.inTransaction); });
++
++ const result = await service.updateTour(tripId, String(created.tour.place_id), update, 'socket-2');
+
+ expect(result.tour).toMatchObject({ place_id: created.tour.place_id, name: 'Updated ridge walk' });
+ expect(result.waypoints).toEqual(update.waypoints);
- expect(setup.raw.prepare('SELECT name, lat, lng FROM places').get()).toEqual({
- name: 'Updated ridge walk', lat: 49, lng: 12,
++ expect(testDb.prepare('SELECT name, lat, lng, transport_mode FROM places').get()).toEqual({
++ name: 'Updated ridge walk', lat: 49, lng: 12, transport_mode: 'walking',
++ });
++ expect(testDb.prepare('SELECT duration, elevation_gain, elevation_loss FROM tours').get()).toEqual({
++ duration: 45, elevation_gain: 60, elevation_loss: 0,
+ });
- expect(setup.raw.prepare('SELECT duration FROM tours').get()).toEqual({ duration: 45 });
- expect(setup.places.broadcast).toHaveBeenNthCalledWith(1, '7', 'tours:changed', { placeIds: [created.tour.place_id] }, 'socket-2');
- expect(setup.places.broadcast).toHaveBeenNthCalledWith(2,
- '7', 'place:updated', expect.objectContaining({ place: expect.anything() }), 'socket-2',
++ expect(broadcast).toHaveBeenNthCalledWith(1, tripId, 'tours:changed', { placeIds: [created.tour.place_id] }, 'socket-2');
++ expect(broadcast).toHaveBeenNthCalledWith(2,
++ tripId, 'place:updated', expect.objectContaining({ place: expect.objectContaining({ id: created.tour.place_id }) }), 'socket-2',
+ );
+ expect(writeStates).toEqual([false, false]);
+ });
+
- it('TOURS-SVC-006: rolls an invalid waypoint replacement back to the previous saved tour', () => {
- const created = setup.service.createTour('7', request);
- const invalid = {
- ...request,
- name: 'Must roll back',
- waypoints: [request.waypoints[0], { ...request.waypoints[1], sequence: 0 }],
- } as TourCreateRequest;
-
- expect(() => setup.service.updateTour('7', String(created.tour.place_id), invalid)).toThrow();
- expect(setup.raw.prepare('SELECT name FROM places').get()).toEqual({ name: 'Ridge walk' });
- expect(setup.service.getTour('7', String(created.tour.place_id)).waypoints).toEqual(request.waypoints);
++ it('TOURS-SVC-006: rolls an invalid waypoint replacement back to the previous saved tour', async () => {
++ const created = await service.createTour(tripId, request);
++ broadcast.mockReset();
++
++ await expect(service.updateTour(tripId, String(created.tour.place_id), { ...duplicateSequence, name: 'Must roll back' })).rejects.toThrow();
++
++ expect(testDb.prepare('SELECT name FROM places').get()).toEqual({ name: 'Ridge walk' });
++ expect((await service.getTour(tripId, String(created.tour.place_id))).waypoints).toEqual(request.waypoints);
++ expect(broadcast).not.toHaveBeenCalled();
+ });
+
- it('keeps a committed create successful when Tours invalidation publication fails', () => {
- const warn = vi.spyOn(Logger.prototype, 'warn').mockImplementation(() => {});
- setup.places.broadcast.mockImplementation((_tripId, event) => {
- if (event === 'tours:changed') throw new Error('transport unavailable');
- });
++ it('TOURS-SVC-008: a tour of another trip is a 404 and stays untouched', async () => {
++ const created = await service.createTour(otherTripId, request);
++ broadcast.mockReset();
+
- const result = setup.service.createTour('7', request);
++ await expect(service.updateTour(tripId, String(created.tour.place_id), update, 'socket')).rejects.toThrow('Tour not found');
+
- expect(result.tour.name).toBe('Ridge walk');
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM places').get()).toEqual({ count: 1 });
- expect(setup.raw.prepare('SELECT COUNT(*) AS count FROM tours').get()).toEqual({ count: 1 });
- expect(setup.places.broadcast).toHaveBeenCalledTimes(2);
- expect(warn).toHaveBeenCalledOnce();
++ expect(testDb.prepare('SELECT trip_id, name FROM places WHERE id = ?').get(created.tour.place_id))
++ .toEqual({ trip_id: Number(otherTripId), name: 'Ridge walk' });
++ expect((await service.getTour(otherTripId, String(created.tour.place_id))).waypoints).toEqual(request.waypoints);
++ expect(broadcast).not.toHaveBeenCalled();
++ });
++
++ it('TOURS-SVC-009: a plain place or a malformed id is a 404 without a write', async () => {
++ const plain = createPlace(testDb, Number(tripId), { name: 'Plain' });
++
++ await expect(service.updateTour(tripId, String(plain.id), update)).rejects.toBeInstanceOf(NotFoundException);
++ await expect(service.updateTour(tripId, 'abc', update)).rejects.toThrow('Tour not found');
++ await expect(service.updateTour('abc', String(plain.id), update)).rejects.toThrow('Tour not found');
++
++ expect(testDb.prepare('SELECT name FROM places WHERE id = ?').get(plain.id)).toEqual({ name: 'Plain' });
++ expect(count('tours')).toBe(0);
++ expect(broadcast).not.toHaveBeenCalled();
+ });
+});
diff --cc server/tests/unit/nest/trips.service.test.ts
index f7bef785c,0c826fdf8..496c85a42
--- a/server/tests/unit/nest/trips.service.test.ts
+++ b/server/tests/unit/nest/trips.service.test.ts
@@@ -50,12 -48,10 +48,11 @@@ const { broadcast } = vi.hoisted(() =>
vi.mock('../../../src/websocket', () => ({ broadcast }));
// notifyInvite fires a notification via a dynamic import — keep it out of unit scope
- import { createTables } from '../../../src/db/schema';
- import { runMigrations } from '../../../src/db/migrations';
+ import { db as testDb } from '../../../src/db/database';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createReservation, createPlace, createDay, createDayAssignment, createDayNote, addTripMember } from '../../helpers/factories';
++import { createTestTourWaypointsRepo, createTour } from '../../helpers/tours-repos';
import { MAX_TRIP_DAYS, resolveDayGridRange, tripSpanDays } from '@trek/shared';
- import { DatabaseService } from '../../../src/nest/database/database.service';
import { DaysService } from '../../../src/nest/days/days.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
@@@ -1426,52 -1627,268 +1628,329 @@@ describe('folded quirk branches', () =
});
});
- // ── Post-fold quirk fixes (transactions, owner display name) ─────────────────
+ // ── Plan 3c Task 8 deliverable: whole-copy parity + rollback ─────────────────
- describe('quirk fixes', () => {
- /** A TripsService whose connection throws when preparing SQL matching `match`. */
- function failingConnection(match: string) {
- const conn = new Proxy(testDb, {
- get(target, prop) {
- if (prop === 'prepare') {
- return (sql: string) => {
- if (sql.includes(match)) throw new Error('boom');
- return target.prepare(sql);
- };
- }
- const v = (target as any)[prop];
- return typeof v === 'function' ? v.bind(target) : v;
- },
+ describe('copy — whole-trip parity (Task 8)', () => {
+ it('TRIP-SVC-069: every table copy touches is byte-identical to the source modulo ids/timestamps, with ids consistently remapped', async () => {
+ const { user: owner } = createUser(testDb);
+ const { user: member } = createUser(testDb);
+ const trip = createTrip(testDb, owner.id, {
+ title: 'Full Fixture', start_date: '2025-09-01', end_date: '2025-09-03',
});
- return { connection: conn, canAccessTrip: dbMock.canAccessTrip, isOwner: dbMock.isOwner } as unknown as import('../../../src/nest/database/database.service').DatabaseService;
- }
+ testDb.prepare("UPDATE trips SET description = 'A full trip', currency = 'EUR', cover_image = 'cover.png', reminder_days = 5 WHERE id = ?").run(trip.id);
+ addTripMember(testDb, trip.id, member.id);
+ const days = getDays(trip.id);
+ testDb.prepare("UPDATE days SET notes = 'Pack light', title = 'Arrival' WHERE id = ?").run(days[0].id);
+ testDb.prepare("UPDATE days SET notes = 'Checkout' WHERE id = ?").run(days[1].id);
- function failingTrips(match: string) {
- const fdbs = failingConnection(match);
- return new TripsService(
- fdbs,
- new ReservationsService(dbs(), new PermissionsService(dbs()), budgetSvc, new RealtimeService(), notificationsStub(), new ReservationsReadRepository(dbs()), accommodationsSvc),
- daysSvc,
- new PermissionsService(dbs()),
- budgetSvc,
- new VacayService(dbs(), new RealtimeService(), notificationsStub()),
- new RealtimeService(),
- undefined as never,
- coversFx.storage,
- new SettingsService(dbs()),
- );
- }
+ const stop = createPlace(testDb, trip.id, { name: 'Hotel Full', description: 'Nice place' });
+ const track = createPlace(testDb, trip.id, { name: 'Scenic road' });
+ testDb.prepare("UPDATE places SET reservation_status = 'booked', reservation_notes = 'rn', reservation_datetime = '2025-09-01T14:00', route_color = '#ff0000', stop_type = 'hotel', fill_percent = 80 WHERE id = ?").run(stop.id);
+
+ const tag = Number(testDb.prepare("INSERT INTO tags (name, user_id) VALUES ('beach', ?)").run(owner.id).lastInsertRowid);
+ testDb.prepare('INSERT INTO place_tags (place_id, tag_id) VALUES (?, ?)').run(stop.id, tag);
+
+ const assignment = createDayAssignment(testDb, days[0].id, stop.id);
+ testDb.prepare(`UPDATE day_assignments SET reservation_status = 'booked', reservation_notes = 'arn', reservation_datetime = '2025-09-01T15:00',
+ assignment_time = '15:00', assignment_end_time = '16:00', end_day = 1 WHERE id = ?`).run(assignment.id);
+ testDb.prepare('INSERT INTO assignment_participants (assignment_id, user_id) VALUES (?, ?), (?, ?)').run(assignment.id, owner.id, assignment.id, member.id);
+
+ testDb.prepare('INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (?, 0, 0, 48.1, 2.1)').run(days[0].id);
+ testDb.prepare('INSERT INTO roadtrip_day_tracks (day_id, place_id, stray_km) VALUES (?, ?, 2.5)').run(days[0].id, track.id);
+ testDb.prepare("INSERT INTO roadtrip_preferences (trip_id, key, value) VALUES (?, 'avoid_tolls', 'true')").run(trip.id);
+ testDb.prepare('INSERT INTO roadtrip_day_boundaries (trip_id, day_number, from_assignment_id, to_assignment_id, fraction) VALUES (?, 1, ?, NULL, 0.5)').run(trip.id, assignment.id);
- /** Same frozen connection, for the guest deletion that now lives on the roster. */
- function failingMembers(match: string) {
- return new TripMembersService(
- failingConnection(match), budgetSvc, new UserCleanupService(dbs(), budgetSvc),
- new PermissionsService(dbs()), new RealtimeService(),
- notificationsStub(),
+ const accomId = Number(testDb.prepare(
+ "INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes) VALUES (?, ?, ?, ?, '15:00', '15:30', '11:00', 'CONF-1', 'Late checkout ok')",
+ ).run(trip.id, stop.id, days[0].id, days[1].id).lastInsertRowid);
+ testDb.prepare('UPDATE day_assignments SET accommodation_id = ? WHERE id = ?').run(accomId, assignment.id);
+
+ const resId = Number(testDb.prepare(`
+ INSERT INTO reservations (trip_id, day_id, end_day_id, place_id, assignment_id, accommodation_id, title, reservation_time, reservation_end_time,
+ location, confirmation_number, notes, url, status, type, metadata, day_plan_position, needs_review, ingest_state,
+ external_source, external_id, sync_enabled)
+ VALUES (?, ?, ?, ?, ?, ?, 'Stay', '15:00', '11:00', 'Front desk', 'CONF-99', 'Bring ID', 'https://example.com/booking',
+ 'confirmed', 'hotel', '{"note":"seed"}', 1.5, 1, 'live', 'airtrail', 'ext-123', 0)
+ `).run(trip.id, days[0].id, days[1].id, stop.id, assignment.id, accomId).lastInsertRowid);
+ // Confirms the seed itself reproduces the legacy "14.0" TEXT shape
+ // (this is the SOURCE row's own accommodation_id, written the same way
+ // the pre-migration `copy` bound it — a plain number through
+ // better-sqlite3 into the TEXT column).
+ expect((testDb.prepare('SELECT accommodation_id FROM reservations WHERE id = ?').get(resId) as { accommodation_id: string }).accommodation_id).toBe(`${accomId}.0`);
+
+ const itemId = Number(testDb.prepare(
+ "INSERT INTO budget_items (trip_id, category, name, total_price, reservation_id, currency) VALUES (?, 'Accommodation', 'Hotel', 300, ?, 'EUR')",
+ ).run(trip.id, resId).lastInsertRowid);
+ testDb.prepare('INSERT INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 1, 150), (?, ?, 0, 150)')
+ .run(itemId, owner.id, itemId, member.id);
+ testDb.prepare('INSERT INTO budget_item_payers (budget_item_id, user_id, amount) VALUES (?, ?, 300)').run(itemId, owner.id);
+ testDb.prepare("INSERT INTO budget_category_order (trip_id, category, sort_order) VALUES (?, 'Accommodation', 1)").run(trip.id);
+
+ const bagId = Number(testDb.prepare("INSERT INTO packing_bags (trip_id, name) VALUES (?, 'Carry-on')").run(trip.id).lastInsertRowid);
+ testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, bag_id) VALUES (?, ?, 1, ?)').run(trip.id, 'Shared tent', bagId);
+ testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, is_private, owner_id) VALUES (?, ?, 1, 1, ?)').run(trip.id, "Owner's diary", owner.id);
+ testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, is_private, owner_id) VALUES (?, ?, 1, 1, ?)').run(trip.id, "Member's meds", member.id);
+
+ createDayNote(testDb, days[0].id, trip.id, { text: 'Remember passport', time: '08:00', icon: '🛂', sort_order: 1 });
+ testDb.prepare("INSERT INTO todo_items (trip_id, name, checked, category, sort_order) VALUES (?, 'Book taxi', 1, 'travel', 1)").run(trip.id);
+
+ // ── copy, run by the OWNER (so their own private item copies, member's does not) ──
+ const newTripId = await svc.copy(trip.id, owner.id, 'Full Copy');
+
+ // trips
+ const newTrip = testDb.prepare('SELECT * FROM trips WHERE id = ?').get(newTripId) as Record<string, unknown>;
+ expect(newTrip).toMatchObject({
+ user_id: owner.id, title: 'Full Copy', description: 'A full trip',
+ start_date: '2025-09-01', end_date: '2025-09-03', currency: 'EUR',
+ cover_image: 'cover.png', is_archived: 0, reminder_days: 5,
+ });
+
+ // days
+ const newDays = getDays(newTripId);
+ expect(newDays).toHaveLength(3);
+ expect(newDays.map(d => ({ day_number: d.day_number, date: d.date }))).toEqual(
+ days.map(d => ({ day_number: d.day_number, date: d.date })),
);
+ expect((testDb.prepare('SELECT notes, title FROM days WHERE id = ?').get(newDays[0].id) as { notes: string | null; title: string | null })).toEqual({ notes: 'Pack light', title: 'Arrival' });
+ expect((testDb.prepare('SELECT notes FROM days WHERE id = ?').get(newDays[1].id) as { notes: string | null }).notes).toBe('Checkout');
+
+ // places
+ const newStop = testDb.prepare('SELECT * FROM places WHERE trip_id = ? AND name = ?').get(newTripId, 'Hotel Full') as {
+ id: number; description: string | null; reservation_status: string | null; reservation_notes: string | null;
+ reservation_datetime: string | null; route_color: string | null; stop_type: string | null; fill_percent: number | null;
+ };
+ const newTrack = testDb.prepare('SELECT * FROM places WHERE trip_id = ? AND name = ?').get(newTripId, 'Scenic road') as { id: number };
+ expect(newStop).toMatchObject({
+ description: 'Nice place', reservation_status: 'booked', reservation_notes: 'rn',
+ reservation_datetime: '2025-09-01T14:00', route_color: '#ff0000', stop_type: 'hotel', fill_percent: 80,
+ });
+
+ // place_tags
+ expect((testDb.prepare('SELECT tag_id FROM place_tags WHERE place_id = ?').get(newStop.id) as { tag_id: number }).tag_id).toBe(tag);
+
+ // day_assignments (+ the TP57 accommodation stamp)
+ const newAssignment = getAssignments(newDays[0].id)[0];
+ const newAssignmentFull = testDb.prepare('SELECT * FROM day_assignments WHERE id = ?').get(newAssignment.id) as {
+ place_id: number; reservation_status: string | null; reservation_notes: string | null; reservation_datetime: string | null;
+ assignment_time: string | null; assignment_end_time: string | null; end_day: number; accommodation_id: number | null;
+ };
+ expect(newAssignmentFull).toMatchObject({
+ place_id: newStop.id, reservation_status: 'booked', reservation_notes: 'arn',
+ reservation_datetime: '2025-09-01T15:00', assignment_time: '15:00', assignment_end_time: '16:00', end_day: 1,
+ });
+
+ // assignment_participants
+ const newParticipants = testDb.prepare('SELECT user_id FROM assignment_participants WHERE assignment_id = ?').all(newAssignment.id) as { user_id: number }[];
+ expect(newParticipants.map(p => p.user_id).sort((a, b) => a - b)).toEqual([owner.id, member.id].sort((a, b) => a - b));
+
+ // roadtrip_vias / roadtrip_day_tracks
+ const newVia = testDb.prepare('SELECT after_order_index, sequence, lat, lng FROM roadtrip_vias WHERE day_id = ?').get(newDays[0].id) as {
+ after_order_index: number; sequence: number; lat: number; lng: number;
+ };
+ expect(newVia).toEqual({ after_order_index: 0, sequence: 0, lat: 48.1, lng: 2.1 });
+ const newTrackRow = testDb.prepare('SELECT place_id, stray_km FROM roadtrip_day_tracks WHERE day_id = ?').get(newDays[0].id) as { place_id: number; stray_km: number | null };
+ expect(newTrackRow).toEqual({ place_id: newTrack.id, stray_km: 2.5 });
+
+ // roadtrip_preferences / roadtrip_day_boundaries
+ expect((testDb.prepare("SELECT value FROM roadtrip_preferences WHERE trip_id = ? AND key = 'avoid_tolls'").get(newTripId) as { value: string }).value).toBe('true');
+ const newBoundary = testDb.prepare('SELECT day_number, from_assignment_id, to_assignment_id, fraction FROM roadtrip_day_boundaries WHERE trip_id = ?').get(newTripId) as {
+ day_number: number; from_assignment_id: number; to_assignment_id: number | null; fraction: number;
+ };
+ expect(newBoundary).toEqual({ day_number: 1, from_assignment_id: newAssignment.id, to_assignment_id: null, fraction: 0.5 });
+
+ // day_accommodations (TP55/TP56, byte-diffed against the source — full
+ // key set modulo id/trip_id/place_id/start_day_id/end_day_id/created_at,
+ // every one of which is either a remapped FK or excluded on principle),
+ // and the assignment's accommodation_id stamped at the NEW accommodation
+ const newAccom = testDb.prepare('SELECT * FROM day_accommodations WHERE trip_id = ?').get(newTripId) as {
+ id: number; place_id: number | null; start_day_id: number; end_day_id: number;
+ check_in: string | null; check_in_end: string | null; check_out: string | null; confirmation: string | null; notes: string | null;
+ };
+ const sourceAccom = testDb.prepare('SELECT check_in, check_in_end, check_out, confirmation, notes FROM day_accommodations WHERE id = ?').get(accomId) as {
+ check_in: string | null; check_in_end: string | null; check_out: string | null; confirmation: string | null; notes: string | null;
+ };
+ expect({ check_in: newAccom.check_in, check_in_end: newAccom.check_in_end, check_out: newAccom.check_out, confirmation: newAccom.confirmation, notes: newAccom.notes }).toEqual(sourceAccom);
+ expect({ place_id: newAccom.place_id, start_day_id: newAccom.start_day_id, end_day_id: newAccom.end_day_id }).toEqual({ place_id: newStop.id, start_day_id: newDays[0].id, end_day_id: newDays[1].id });
+ expect(newAssignmentFull.accommodation_id).toBe(newAccom.id);
+
+ // reservations (TP58/TP59), byte-diffed against the source — full key
+ // set modulo id/trip_id/day_id/end_day_id/place_id/assignment_id/
+ // created_at (remapped FKs) and the external_*/sync_enabled columns
+ // (deliberately NOT copied, asserted below).
+ const newRes = testDb.prepare('SELECT * FROM reservations WHERE trip_id = ?').get(newTripId) as {
+ id: number; day_id: number | null; end_day_id: number | null; place_id: number | null; assignment_id: number | null;
+ title: string; reservation_time: string | null; reservation_end_time: string | null; location: string | null;
+ confirmation_number: string | null; notes: string | null; url: string | null; status: string | null; type: string | null;
+ metadata: string | null; day_plan_position: number | null; needs_review: number; ingest_state: string; accommodation_id: string | null;
+ external_source: string | null; external_id: string | null; sync_enabled: number | null;
+ };
+ expect({
+ title: newRes.title, reservation_time: newRes.reservation_time, reservation_end_time: newRes.reservation_end_time,
+ location: newRes.location, confirmation_number: newRes.confirmation_number, notes: newRes.notes, url: newRes.url,
+ status: newRes.status, type: newRes.type, metadata: newRes.metadata, day_plan_position: newRes.day_plan_position,
+ needs_review: newRes.needs_review, ingest_state: newRes.ingest_state,
+ }).toEqual({
+ title: 'Stay', reservation_time: '15:00', reservation_end_time: '11:00', location: 'Front desk',
+ confirmation_number: 'CONF-99', notes: 'Bring ID', url: 'https://example.com/booking', status: 'confirmed',
+ type: 'hotel', metadata: '{"note":"seed"}', day_plan_position: 1.5, needs_review: 1, ingest_state: 'live',
+ });
+ expect({ day_id: newRes.day_id, end_day_id: newRes.end_day_id, place_id: newRes.place_id, assignment_id: newRes.assignment_id }).toEqual({
+ day_id: newDays[0].id, end_day_id: newDays[1].id, place_id: newStop.id, assignment_id: newAssignment.id,
+ });
+ // The TRAP proof: the copy's accommodation_id is the LEGACY raw-bound
+ // TEXT shape (`'<id>.0'`), not the `em.insert()`-inlined `'<id>'` shape
+ // rule 22 would otherwise produce.
+ expect(newRes.accommodation_id).toBe(`${newAccom.id}.0`);
+ // external_* / sync_enabled are deliberately NOT copied — the duplicate
+ // must not inherit the source's external sync identity (the source has
+ // both set, above).
+ expect(newRes.external_source).toBeNull();
+ expect(newRes.external_id).toBeNull();
+ expect(newRes.sync_enabled).toBe(1); // the column's own DB DEFAULT, never the source's `0`
+
+ // budget_items / members / payers / category order
+ const newItem = testDb.prepare('SELECT * FROM budget_items WHERE trip_id = ?').get(newTripId) as {
+ id: number; category: string; name: string; total_price: number; reservation_id: number | null; currency: string | null;
+ };
+ expect(newItem).toMatchObject({ category: 'Accommodation', name: 'Hotel', total_price: 300, reservation_id: newRes.id, currency: 'EUR' });
+ const newMembers = testDb.prepare('SELECT user_id, paid, amount FROM budget_item_members WHERE budget_item_id = ? ORDER BY user_id').all(newItem.id) as { user_id: number; paid: number; amount: number | null }[];
+ expect(newMembers).toEqual([owner.id, member.id].sort((a, b) => a - b).map((uid) =>
+ uid === owner.id ? { user_id: owner.id, paid: 1, amount: 150 } : { user_id: member.id, paid: 0, amount: 150 },
+ ));
+ const newPayers = testDb.prepare('SELECT user_id, amount FROM budget_item_payers WHERE budget_item_id = ?').all(newItem.id) as { user_id: number; amount: number }[];
+ expect(newPayers).toEqual([{ user_id: owner.id, amount: 300 }]);
+ expect((testDb.prepare("SELECT sort_order FROM budget_category_order WHERE trip_id = ? AND category = 'Accommodation'").get(newTripId) as { sort_order: number }).sort_order).toBe(1);
+
+ // packing_bags / packing_items (incl. the TP68 privacy filter — the copIER is the owner)
+ const newBag = testDb.prepare("SELECT id FROM packing_bags WHERE trip_id = ? AND name = 'Carry-on'").get(newTripId) as { id: number };
+ const newPacking = testDb.prepare('SELECT name, checked, is_private, owner_id, bag_id FROM packing_items WHERE trip_id = ? ORDER BY name').all(newTripId) as {
+ name: string; checked: number | null; is_private: number; owner_id: number | null; bag_id: number | null;
+ }[];
+ expect(newPacking.map(p => p.name)).toEqual(['Owner\'s diary', 'Shared tent']); // member's private item is NOT copied
+ expect(newPacking.find(p => p.name === 'Shared tent')).toMatchObject({ checked: 0, is_private: 0, owner_id: null, bag_id: newBag.id });
+ expect(newPacking.find(p => p.name === "Owner's diary")).toMatchObject({ checked: 0, is_private: 1, owner_id: owner.id });
+
+ // day_notes
+ const newNote = testDb.prepare('SELECT day_id, text, time, icon, sort_order FROM day_notes WHERE trip_id = ?').get(newTripId) as {
+ day_id: number; text: string; time: string | null; icon: string | null; sort_order: number | null;
+ };
+ expect(newNote).toEqual({ day_id: newDays[0].id, text: 'Remember passport', time: '08:00', icon: '🛂', sort_order: 1 });
+
+ // todo_items — reset to unchecked, no assignee
+ const newTodo = testDb.prepare('SELECT name, checked, category, sort_order, assigned_user_id FROM todo_items WHERE trip_id = ?').get(newTripId) as {
+ name: string; checked: number | null; category: string | null; sort_order: number | null; assigned_user_id: number | null;
+ };
+ expect(newTodo).toEqual({ name: 'Book taxi', checked: 0, category: 'travel', sort_order: 1, assigned_user_id: null });
+
+ // The source trip is untouched.
+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM days WHERE trip_id = ?').get(trip.id)).toEqual({ n: 3 });
+ expect(testDb.prepare('SELECT COUNT(*) AS n FROM packing_items WHERE trip_id = ?').get(trip.id)).toEqual({ n: 3 });
+ });
+
+ it('TRIP-SVC-070 (mutation-proved): copy is atomic — a failing late insert leaves no new trip and no partial rows', async () => {
+ const { user } = createUser(testDb);
+ const trip = createTrip(testDb, user.id, { title: 'Rollback source', start_date: '2025-10-01', end_date: '2025-10-02' });
+ const days = getDays(trip.id);
+ const place = createPlace(testDb, trip.id, { name: 'Doomed place' });
+ createDayAssignment(testDb, days[0].id, place.id);
+ const tripsBefore = (testDb.prepare('SELECT COUNT(*) AS n FROM trips').get() as { n: number }).n;
+ const daysBefore = (testDb.prepare('SELECT COUNT(*) AS n FROM days').get() as { n: number }).n;
+
+ const dayNotesRepo = await createTestDayNotesRepo(testDb);
+ const spy = vi.spyOn(dayNotesRepo, 'insertNoteCopy').mockRejectedValueOnce(new Error('boom'));
+ createDayNote(testDb, days[0].id, trip.id, { text: 'Triggers the late failure' });
+ try {
+ await expect(svc.copy(trip.id, user.id, 'Never lands')).rejects.toThrow('boom');
+ } finally {
+ spy.mockRestore();
+ }
+
+ // No new trip, and every earlier insert in the same transaction (trips/days/
+ // places/assignments/…) rolled back with it — nothing partially lands.
+ expect((testDb.prepare('SELECT COUNT(*) AS n FROM trips').get() as { n: number }).n).toBe(tripsBefore);
+ expect((testDb.prepare('SELECT COUNT(*) AS n FROM days').get() as { n: number }).n).toBe(daysBefore);
+ expect(testDb.prepare("SELECT id FROM trips WHERE title = 'Never lands'").get()).toBeUndefined();
+ // The source trip itself is untouched.
+ expect(testDb.prepare('SELECT id FROM trips WHERE id = ?').get(trip.id)).toBeDefined();
+ });
+ });
+
++describe('copy: Tours (#2586)', () => {
++ /** A Tour on `tripId`: the place, its `tours` facet and three route waypoints. */
++ function seedTour(tripId: number, name: string) {
++ const place = createPlace(testDb, tripId, { name });
++ testDb.prepare("UPDATE places SET transport_mode = 'walking', route_geometry = '[[47,11],[47.2,11.2]]' WHERE id = ?").run(place.id);
++ createTour(testDb, place.id, { distance: 12.5, match_confidence: 0.9, max_hiking_difficulty: 4, created_at: '2025-01-02 03:04:05' });
++ testDb.prepare("UPDATE tours SET elevation_gain = 800, elevation_loss = 790, duration = 5.5, difficulty = 'T3', wanderer_ref = 'w-1', tour_group_id = 7 WHERE place_id = ?").run(place.id);
++ const insert = testDb.prepare('INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (?, ?, ?, ?, ?)');
++ insert.run(place.id, 47, 11, 'start', 0);
++ insert.run(place.id, 47.1, 11.1, 'via', 1);
++ insert.run(place.id, 47.2, 11.2, 'end', 2);
++ return place;
+ }
+
- it('TRIP-SVC-051: remove is atomic — a failed trip DELETE keeps the journey entries intact', () => {
++ const tourColumns = (placeId: number) => {
++ const { place_id: _placeId, ...rest } = testDb.prepare('SELECT * FROM tours WHERE place_id = ?').get(placeId) as Record<string, unknown>;
++ return rest;
++ };
++ const waypoints = (placeId: number) =>
++ testDb.prepare('SELECT lat, lng, role, sequence FROM tour_waypoints WHERE place_id = ? ORDER BY sequence').all(placeId);
++
++ it('TRIP-SVC-081: a copied Tour keeps its facet row and waypoints, remapped onto the copied place', async () => {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id, { title: 'Alps' });
++ const tour = seedTour(trip.id, 'Ridge walk');
++ createPlace(testDb, trip.id, { name: 'Plain stop' });
++
++ const newTripId = await svc.copy(trip.id, user.id, 'Alps again');
++
++ const newTour = testDb.prepare("SELECT id FROM places WHERE trip_id = ? AND name = 'Ridge walk'").get(newTripId) as { id: number };
++ const newPlain = testDb.prepare("SELECT id FROM places WHERE trip_id = ? AND name = 'Plain stop'").get(newTripId) as { id: number };
++ expect(newTour.id).not.toBe(tour.id);
++ expect(tourColumns(newTour.id)).toEqual(tourColumns(tour.id));
++ expect(tourColumns(newTour.id)).toMatchObject({ tour_type: 'hike', created_at: '2025-01-02 03:04:05', max_hiking_difficulty: 4, tour_group_id: 7 });
++ expect(waypoints(newTour.id)).toEqual(waypoints(tour.id));
++ expect(waypoints(newTour.id)).toHaveLength(3);
++ // The plain place stays plain, and the source keeps its own rows.
++ expect(testDb.prepare('SELECT 1 FROM tours WHERE place_id = ?').get(newPlain.id)).toBeUndefined();
++ expect(testDb.prepare('SELECT COUNT(*) AS n FROM tours t JOIN places p ON p.id = t.place_id WHERE p.trip_id = ?').get(trip.id)).toEqual({ n: 1 });
++ expect(waypoints(tour.id)).toHaveLength(3);
++ });
++
++ it('TRIP-SVC-082: a failing waypoint insert rolls the copied Tour back with the rest of the copy', async () => {
++ const { user } = createUser(testDb);
++ const trip = createTrip(testDb, user.id, { title: 'Doomed alps' });
++ seedTour(trip.id, 'Doomed ridge');
++ const toursBefore = (testDb.prepare('SELECT COUNT(*) AS n FROM tours').get() as { n: number }).n;
++
++ const waypointsRepo = await createTestTourWaypointsRepo(testDb);
++ const spy = vi.spyOn(waypointsRepo, 'insertForPlace').mockRejectedValueOnce(new Error('boom'));
++ try {
++ await expect(svc.copy(trip.id, user.id, 'Never lands')).rejects.toThrow('boom');
++ } finally {
++ spy.mockRestore();
++ }
++
++ expect((testDb.prepare('SELECT COUNT(*) AS n FROM tours').get() as { n: number }).n).toBe(toursBefore);
++ expect(testDb.prepare("SELECT id FROM trips WHERE title = 'Never lands'").get()).toBeUndefined();
++ });
++});
++
+ // ── Post-fold quirk fixes (transactions, owner display name) ─────────────────
+
+ describe('quirk fixes', () => {
+ // Plan 3c Task 7 (R8): the SQL-text-keyed `failingConnection`/`failingTrips`
+ // Proxy this test used to build a one-off TripsService around is rewritten
+ // as a repository-level fault, the same shape TRIP-SVC-052 below already
+ // uses for `deleteGuest` — `remove`'s TP32-TP34 (journey_entries stay raw;
+ // `deleteById` is TP34, `TripsRepository`'s) are the statements this test
+ // pins, and TP34 is now a repository method to `vi.spyOn`, not SQL text to
+ // pattern-match. The Proxy could never trigger any more: no statement text
+ // matching `'DELETE FROM trips WHERE id = ?'` runs through `this.db`
+ // inside `remove`'s transaction any more (TP32/TP33 are the only survivors
+ // there, and their own text is untouched).
+
+ it('TRIP-SVC-051 (mutation-proved): remove is atomic — a failed trip DELETE keeps the journey entries intact', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const journeyId = Number(testDb.prepare(
diff --cc server/tests/unit/nest/wiring.test.ts
index 75e974820,3e3dd0a61..816ed6b0a
--- a/server/tests/unit/nest/wiring.test.ts
+++ b/server/tests/unit/nest/wiring.test.ts
@@@ -1,51 -1,19 +1,51 @@@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import { HttpException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
- import { db } from '../../../src/db/database';
import { AppModule } from '../../../src/nest/app.module';
import { FeaturesController } from '../../../src/nest/health/features.controller';
- import { DatabaseService } from '../../../src/nest/database/database.service';
import { AdminGuard } from '../../../src/nest/auth/admin.guard';
+vi.mock('../../../src/config', async () => {
+ const { readEnv } = await import('../../../src/app-config');
+ const env = readEnv();
+ return {
+ ENCRYPTION_KEY: 'wiring-test-inert-encryption-key',
+ JWT_SECRET: 'wiring-test-inert-jwt-secret',
+ updateJwtSecret: vi.fn(),
+ DEFAULT_LANGUAGE: env.app.defaultLanguage,
+ SESSION_DURATION: env.session.duration,
+ SESSION_DURATION_MS: env.session.durationMs,
+ SESSION_DURATION_SECONDS: env.session.durationSeconds,
+ SESSION_DURATION_REMEMBER: env.session.durationRemember,
+ SESSION_DURATION_REMEMBER_MS: env.session.durationRememberMs,
+ SESSION_DURATION_REMEMBER_SECONDS: env.session.durationRememberSeconds,
+ };
+});
+
function ctx(user: unknown) {
return { switchToHttp: () => ({ getRequest: () => ({ user }) }) } as never;
}
describe('AppModule wiring', () => {
- it('registers the pinned upstream module union and Tours exactly once', () => {
- const imports = Reflect.getMetadata('imports', AppModule) as Array<Function | { module: Function }>;
- const names = imports.map(entry => (typeof entry === 'function' ? entry : entry.module).name);
- expect(names).toHaveLength(68);
++ it('registers the upstream feature modules and Tours exactly once', () => {
++ // Only plain class imports: forRoot()/forFeature() entries are dynamic
++ // (MikroOrmModule legitimately appears twice) and some resolve async.
++ const imports = Reflect.getMetadata('imports', AppModule) as unknown[];
++ const names = imports
++ .filter((entry): entry is { name: string } => typeof entry === 'function')
++ .map(entry => entry.name);
+ expect(new Set(names).size).toBe(names.length);
+ expect(names).toEqual(expect.arrayContaining([
+ 'GoogleQuotaModule', 'ReceiptScanModule', 'SchoolHolidaysModule', 'DocSyncModule',
+ 'DawarichModule', 'NotificationsModule', 'ToursModule',
+ ]));
+ expect(names.filter(name => name === 'ToursModule')).toHaveLength(1);
+ });
+
it('compiles with the global filter + DB provider and resolves the controller', async () => {
- const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
- .overrideProvider(DatabaseService)
- .useValue({ get: () => ({ n: 0 }) })
- .compile();
+ // Plan 4 Task 4: `DatabaseService` is gone — nothing left in the graph
+ // needs overriding for this to compile.
+ const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
// The one test that builds the whole AppModule: resolving a controller out of
// it proves every module in the graph compiled, not just this one.
expect(moduleRef.get(FeaturesController)).toBeInstanceOf(FeaturesController);