feat(server): plan 3d groundwork — dialect helpers, visibility predicate, feed and cron context ratchets

This commit is contained in:
jubnl
2026-09-23 13:52:38 +02:00
parent 4ceb94613f
commit 93324e71c4
24 changed files with 1473 additions and 30 deletions
+181 -1
View File
@@ -212,8 +212,19 @@ export function coalesce(platform: Platform, ref: string, fallbackRef: string):
* `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 {
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);
}
@@ -320,3 +331,172 @@ export function countAllRef(platform: Platform): RawQueryFragment & symbol {
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);
}
@@ -23,7 +23,7 @@ export const RoadtripDayBoundariesSchema = defineEntity({
checks: [
{
name: 'roadtrip_day_boundaries_fraction_check',
expression: 'fraction BETWEEN 0 AND 1), PRIMARY KEY (trip_id, day_number',
expression: 'fraction BETWEEN 0 AND 1',
},
{
name: 'roadtrip_day_boundaries_day_number_check',
@@ -0,0 +1,136 @@
import type { Platform } from '@mikro-orm/core';
import type { ExpressionBuilder } from 'kysely';
import { coalesceParam } from '../../dialect/sql-functions';
/**
* The visibility predicate an anonymous viewer's reads are filtered
* through — ONE source, typed, for `reservations`/`day_accommodations`
* (Plan 3d Task 0, R3).
*
* Derived from the two legacy SQL-fragment builders this file supersedes
* (`src/nest/reservations/reservation-visibility.ts`'s `publicReservationSql`
* and `publicStaySql`, kept in place — string form — until Tasks 2/4/5
* convert their own consumers and `share`'s owner is decided, §14.6):
*
* - **RV1** `publicReservationSql(alias)` — `` COALESCE(${alias}.ingest_state,
* 'live') <> 'staged' ``. A reservation is public unless an automated
* ingest staged it for review.
* - **RV2** `publicStaySql(alias)` — a stay is public when nothing points at
* it (added by hand), or when a LIVE booking does:
* `(NOT EXISTS (…) OR EXISTS (… AND <RV1>))`, correlated on
* `CAST(vr.accommodation_id AS INTEGER) = ${alias}.id` (`accommodation_id`
* is TEXT with no FK, §18.1 — some rows read back as `"14.0"`).
*
* Two shapes are exported because the two predicates need different query
* APIs: RV1 has no correlated subquery, so it renders as a typed MikroORM
* QueryBuilder filter OBJECT (`publicReservationCondition`) — spreadable
* into any `.where({...})` call at any table alias, exactly like the
* legacy fragment builder's own runtime-alias shape, no compile-time table
* binding needed (rule 23: a typed condition, not a string). RV2's
* NOT EXISTS/EXISTS pair has no MikroORM QueryBuilder expression (no
* relation exists from `day_accommodations` to `reservations` via
* `accommodation_id` — R10 keeps it that way; QB's `$exists` operator
* checks embeddable/JSON path existence, not a correlated SQL subquery),
* so it is built with Kysely's own typed `ExpressionBuilder`
* (`publicStayExists`) — `eb.exists`/`eb.not` (Kysely's `unary('exists'|
* 'not', …)` shortcuts), `eb.cast`, `eb.fn.coalesce`, all fully typed,
* never a `raw()` call or a `sql` tagged template (both banned under
* `src/db/repositories/**` by ESLint's `no-restricted-syntax`, checked
* directly against `server/eslint.config.mjs`).
*
* **`publicStayExists` is deliberately narrow, not maximally generic** —
* `ReservationVisibilityKyselyDB` fixes the two aliases every known
* caller already uses (`a` for the outer stay row, `vr` for the
* correlated reservations lookup — "Alias interpolation is a
* caller-supplied constant ('r', 'vr', 'a'); never user input", inventory
* §2d). `Trips.repository.ts`'s `tripSelectQuery` docstring records why a
* shared Kysely helper across differently-joined outer queries doesn't
* compose well ("a shared private helper can't be typed across these four
* callbacks either… `leftJoin`'s alias widens each callback's own
* `ExpressionBuilder` table-set in a way a separate generic method
* signature can't match structurally") — the same limitation would bite a
* predicate meant to serve arbitrarily-different outer queries. This
* function instead requires exactly one contract: the caller's outer query
* is built with `.selectFrom('day_accommodations as a')` (or any
* `.selectFrom`/`.leftJoin` chain that puts an `a` alias with an `id`
* column into scope) and a `reservations` table exists in the same `DB`
* interface. A consumer whose own local Kysely `DB` interface satisfies
* `ReservationVisibilityKyselyDB` structurally can pass its `eb` straight
* through, extending its interface with `& ReservationVisibilityKyselyDB`
* if needed (the same additive-intersection shape
* `DayAssignmentsKyselyDB`/`AssignmentTimeSortKyselyDB` already use for
* their own narrow, per-query interfaces) — proven end-to-end (not just
* typechecked) by this file's own test and by the string-vs-predicate
* parity harness (`tests/unit/db/repositories/_shared/reservation-visibility.test.ts`),
* which Tasks 2/4/5 reuse rather than re-derive.
*
* `ingest_state` visibility is deliberately NOT filtered for authenticated
* reads (`reservation-visibility.ts`'s own docstring: "the staging inbox
* has to see its own rows, or nobody can confirm them") — these two
* exports exist ONLY for the two anonymous surfaces (the ICS feeds,
* `share`) that need it; nothing in this file changes an authenticated
* list.
*/
/**
* RV1 as a typed QB filter-object condition:
* `COALESCE(<alias>.ingest_state, 'live') <> 'staged'`. Spread into a
* `.where({...})` call — `{ ...publicReservationCondition(platform, 'r'),
* trip_id: tripId }` — at any table alias the caller's own query already
* established; this needs no compile-time table binding, the same way
* `coalesceParam` itself needs none (its `ref` argument is validated only
* by `column()`'s identifier-shape regex, not against a live entity's
* declared columns).
*/
export function publicReservationCondition(platform: Platform, alias: string) {
return { [coalesceParam(platform, `${alias}.ingest_state`, 'live')]: { $ne: 'staged' } };
}
/**
* `reservations`/`day_accommodations`'s REAL table names, the shape
* `publicStayExists` needs. A consumer's own local Kysely `DB` interface
* (the `DayAssignmentsKyselyDB`/`AssignmentTimeSortKyselyDB`/
* `TripSelectKyselyDB` per-query-interface precedent) satisfies this by
* structural extension — declaring `day_accommodations`/`reservations`
* with at least these columns is enough; `Kysely<DB>` typed against it and
* queried via `.selectFrom('day_accommodations as a')` (the fixed alias
* every known legacy caller uses — see this file's module docstring) is
* what actually produces the aliased `a` member `publicStayExists`
* requires; Kysely computes that from THIS interface's `day_accommodations`
* entry, not from a hand-declared `a` key (a table's alias is a property of
* the QUERY, never of the `DB` interface itself).
*/
export interface ReservationVisibilityKyselyDB {
day_accommodations: { id: number };
reservations: { id: number; accommodation_id: number | string | null; ingest_state: string | null };
}
/**
* RV2 as a Kysely predicate: `(NOT EXISTS (…) OR EXISTS (… AND <RV1>))`,
* correlated on `CAST(vr.accommodation_id AS INTEGER) = a.id`. Call inside
* a `.where((eb) => publicStayExists(eb))` on a query already
* `.selectFrom('day_accommodations as a')` against a `Kysely<DB>` whose
* `DB` satisfies `ReservationVisibilityKyselyDB`. The parameter type is
* fixed to exactly the shape `.selectFrom('day_accommodations as a')`
* itself produces (`ReservationVisibilityKyselyDB` plus the derived `a`
* alias member) rather than generic over an arbitrary caller `DB`/`TB` —
* `Trips.repository.ts`'s `tripSelectQuery` docstring records why a shared
* Kysely helper generic across differently-shaped outer queries doesn't
* compose ("a shared private helper can't be typed across these four
* callbacks either… a separate generic method signature can't match
* structurally"); this function accepts exactly one contract instead,
* proven end-to-end by this file's own parity-harness test.
*/
export function publicStayExists(eb: ExpressionBuilder<ReservationVisibilityKyselyDB & { a: { id: number } }, 'a'>) {
const linkedTo = eb
.selectFrom('reservations as vr')
.select('vr.id')
.where((eb2) => eb2(eb2.cast(eb2.ref('vr.accommodation_id'), 'integer'), '=', eb2.ref('a.id')));
return eb.or([
eb.not(eb.exists(linkedTo)),
eb.exists(
linkedTo.where((eb2) => eb2(eb2.fn.coalesce(eb2.ref('vr.ingest_state'), eb2.val('live')), '<>', eb2.val('staged'))),
),
]);
}
+1 -1
View File
@@ -302,7 +302,7 @@ finer-grained module instead:
- `reservations.controller.ts` → `airtrail.bridge`: the pull genuinely needs
ReservationsService, so `AirtrailModule` keeps it — but the write-back push
only needs the hydrated reservation READ. That read became
`ReservationsReadRepository` (leaf, the trek_photos pattern), the link
`ReservationsReadService` (leaf, the trek_photos pattern), the link
lifecycle + push became `AirtrailLinkService` in `AirtrailCoreModule`, and
the controller injects it. `airtrail.bridge` is deleted, and
`notifications.instance.ts` — whose last consumer it was — died with it.
@@ -3,7 +3,7 @@ import { ADDON_IDS } from '../../addons';
import { DatabaseService } from '../database/database.service';
import { RealtimeService } from '../realtime/realtime.service';
import { AddonsService } from '../addons/addons.service';
import { ReservationsReadRepository } from '../reservations/reservations-read.repository';
import { ReservationsReadService } from '../reservations/reservations-read.service';
import { logError } from '../audit/audit-log.logger';
import { AirtrailAuthError, type AirtrailCreds, type AirtrailFlightRaw } from './airtrail.client';
import { AirtrailClient } from './airtrail.client';
@@ -15,7 +15,7 @@ import { buildSavePayload } from './airtrail-sync.helpers';
* The AirTrail link lifecycle — the enablement gate, the detach policy, the
* multi-leg guard (#1535) and the TREK → AirTrail write-back (#1240) — split
* out of AirtrailSyncService so ReservationsModule can inject it: it reads
* reservations through the leaf ReservationsReadRepository, never through
* reservations through the leaf ReservationsReadService, never through
* ReservationsService, so AirtrailCoreModule stays off the
* ReservationsModule → AirtrailModule → ReservationsModule loop that used to
* force airtrail.bridge. The pull half stays in AirtrailSyncService, which
@@ -28,7 +28,7 @@ export class AirtrailLinkService {
private readonly db: DatabaseService,
private readonly realtime: RealtimeService,
private readonly addons: AddonsService,
private readonly reads: ReservationsReadRepository,
private readonly reads: ReservationsReadService,
private readonly client: AirtrailClient,
private readonly airtrail: AirtrailService,
) {}
@@ -1,5 +1,5 @@
import { Module } from '@nestjs/common';
import { ReservationsReadRepository } from './reservations-read.repository';
import { ReservationsReadService } from './reservations-read.service';
/**
* A leaf on purpose (the trip-membership precedent): AirtrailCoreModule needs
@@ -7,7 +7,7 @@ import { ReservationsReadRepository } from './reservations-read.repository';
* in — which would re-close the cycle that airtrail.bridge used to dodge.
*/
@Module({
providers: [ReservationsReadRepository],
exports: [ReservationsReadRepository],
providers: [ReservationsReadService],
exports: [ReservationsReadService],
})
export class ReservationsReadModule {}
@@ -17,9 +17,21 @@ export function toTraveler(r: { user_id: number; username: string; avatar: strin
* ReservationsModule → AirtrailCoreModule → ReservationsModule — the cycle
* that used to force airtrail.bridge. ReservationsService injects this and
* delegates, so there is exactly one copy of each query.
*
* Renamed from `ReservationsReadRepository` (Plan 3d Task 0, R11 — inventory
* §18.3): this is a plain Nest `@Injectable` over `DatabaseService.prepare`,
* not a MikroORM repository extending `TrekRepository`, so it must not carry
* the `Repository` suffix — that name is reserved for the ORM layer's "one
* repository per entity" convention (D4). Its three statements (RR1-RR3)
* still convert to `ReservationsRepository`/`ReservationEndpointsRepository`/
* `ReservationTravelersRepository` methods in a later Plan 3d task (per §18.3
* option (a), which then deletes this class and turns
* `ReservationsReadModule` into a plain `MikroOrmModule.forFeature([...])`
* leaf, the `TripMembershipModule` precedent) — Task 0 converts no SQL site,
* so only the rename happens here, with zero behaviour change.
*/
@Injectable()
export class ReservationsReadRepository {
export class ReservationsReadService {
constructor(private readonly db: DatabaseService) {}
async getReservationWithJoins(id: string | number): Promise<ReservationRow | undefined> {
@@ -4,7 +4,7 @@ import { UnitOfWork } from '../database/unit-of-work';
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
import { PermissionsService } from '../permissions/permissions.service';
import { ReservationsReadRepository, toTraveler } from './reservations-read.repository';
import { ReservationsReadService, toTraveler } from './reservations-read.service';
import { keepMirroredPrice } from './reservation-metadata';
import type { Reservation, User } from '../../types';
import { BudgetService } from '../budget/budget.service';
@@ -150,7 +150,7 @@ export class ReservationsService {
private readonly budget: BudgetService,
private readonly realtime: RealtimeService,
private readonly notifications: NotificationsService,
private readonly reads: ReservationsReadRepository,
private readonly reads: ReservationsReadService,
private readonly accommodations: AccommodationsService,
private readonly uow: UnitOfWork,
) {}