mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 08:53:13 +00:00
fix(server): plan 3d close-out — legacy text shape for stored accommodation ids restores the date-change restamp; reservation ids parsed once at the gate; parity tests for the reservation repositories
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import type { ReservationEndpoints } from '../entities/ReservationEndpoints.entity';
|
||||
import { Reservations } from '../entities/Reservations.entity';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
@@ -21,51 +20,6 @@ export interface ReservationEndpointRow {
|
||||
|
||||
const _reservationEndpointRowKeys: AssertRowKeys<ReservationEndpointRow, ReservationEndpoints> = true;
|
||||
|
||||
/**
|
||||
* TP58's `SELECT *` shape — every scalar column of `Reservations`. Declared
|
||||
* here, not on `Reservations.repository.ts` (which has its own, differently
|
||||
* named row type for the same shape, RS35's `ReservationAllColumnsRow`):
|
||||
* Task 4 owns that file for Plan 3d Task 6's tree window, so the
|
||||
* reservations-copy read/write (TP58/TP59) live on this repository instead
|
||||
* — see {@link ReservationEndpointsRepository.listAllForTrip}.
|
||||
*/
|
||||
export interface ReservationCopySourceRow {
|
||||
id: number;
|
||||
trip_id: number;
|
||||
day_id: number | null;
|
||||
end_day_id: number | null;
|
||||
place_id: number | null;
|
||||
assignment_id: number | null;
|
||||
title: string;
|
||||
accommodation_id: string | null;
|
||||
reservation_time: string | null;
|
||||
reservation_end_time: string | null;
|
||||
location: string | null;
|
||||
confirmation_number: string | null;
|
||||
notes: string | null;
|
||||
status: string | null;
|
||||
type: string | null;
|
||||
created_at: string | null;
|
||||
metadata: string | null;
|
||||
day_plan_position: number | null;
|
||||
needs_review: number;
|
||||
external_source: string | null;
|
||||
external_id: string | null;
|
||||
external_owner_user_id: number | null;
|
||||
external_synced_at: string | null;
|
||||
sync_enabled: number | null;
|
||||
external_hash: string | null;
|
||||
url: string | null;
|
||||
ingest_state: string;
|
||||
}
|
||||
|
||||
const _reservationCopySourceRowKeys: AssertRowKeys<ReservationCopySourceRow, Reservations> = true;
|
||||
|
||||
/** Kysely typing for TP58 — this repository is templated on `ReservationEndpoints`, which has no relation to walk to `reservations`' own scalar columns, so the read goes through Kysely directly (program rule 23). */
|
||||
interface ReservationsCopyKyselyDB {
|
||||
reservations: ReservationCopySourceRow;
|
||||
}
|
||||
|
||||
export class ReservationEndpointsRepository extends TrekRepository<ReservationEndpoints> {
|
||||
/**
|
||||
* RS3 (`ReservationsService.loadEndpointsByTrip`) — `SELECT e.* FROM
|
||||
@@ -144,93 +98,4 @@ export class ReservationEndpointsRepository extends TrekRepository<ReservationEn
|
||||
async setLocalDate(id: number, local_date: string): Promise<void> {
|
||||
await this.nativeUpdate({ id }, { local_date });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3d Task 6 (`trips.service.ts::copy`) — additive. Endpoints/travelers/
|
||||
// day-positions are never copied with a reservation (R7, `copy` never
|
||||
// copied them — kept); these two methods reach the PARENT `reservations`
|
||||
// table only, for TP58/TP59, because Task 4 owns `Reservations
|
||||
// .repository.ts` for this same tree window ("a needed method in the
|
||||
// other's repository is requested via the report, not written").
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* TP58 (`trips.service.ts::copy`'s reservations read) — `SELECT * FROM
|
||||
* reservations WHERE trip_id = ?`, no `ORDER BY` (matching the legacy
|
||||
* statement; the copy loop's own id-remap doesn't depend on read order).
|
||||
*/
|
||||
async listAllForTrip(trip_id: number): Promise<ReservationCopySourceRow[]> {
|
||||
return await this.kysely<ReservationsCopyKyselyDB>()
|
||||
.selectFrom('reservations')
|
||||
.selectAll()
|
||||
.where('trip_id', '=', trip_id)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* TP59 (`trips.service.ts::copy`'s reservation INSERT) — `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) VALUES (?×19)`. The
|
||||
* `external_*`/`sync_enabled`/`created_at` columns are deliberately
|
||||
* omitted (the legacy statement's own column list never named them — a
|
||||
* copy must not inherit the source's external sync identity).
|
||||
*
|
||||
* `this.getEntityManager().insert(Reservations, …)`, not `this.insert()`:
|
||||
* this repository is templated on `ReservationEndpoints`, so `this.insert`
|
||||
* would write THAT table. `getEntityManager()` is `TrekRepository`'s own
|
||||
* validated override (its class docstring), so this still fails closed
|
||||
* outside a request context/open transaction exactly like every other
|
||||
* write in this file — the escape hatch is safe, not a bypass.
|
||||
*
|
||||
* `accommodation_id` arrives ALREADY formatted as the legacy `'<id>.0'`
|
||||
* TEXT shape (`trips.service.ts`'s own `legacyAccommodationIdText`, the
|
||||
* program's Plan 3d Task 3 `"14.0"` finding): a plain JS number written
|
||||
* here would be inlined as a SQL literal (rule 22) and stored as `'14'`,
|
||||
* not the shape the legacy raw-bound statement produced.
|
||||
*/
|
||||
async insertReservationCopy(input: {
|
||||
trip_id: number;
|
||||
day_id: number | null;
|
||||
end_day_id: number | null;
|
||||
place_id: number | null;
|
||||
assignment_id: number | null;
|
||||
accommodation_id: string | 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;
|
||||
}): Promise<number> {
|
||||
return await this.getEntityManager().insert(Reservations, {
|
||||
trip: input.trip_id,
|
||||
day: input.day_id,
|
||||
endDay: input.end_day_id,
|
||||
place: input.place_id,
|
||||
assignment: input.assignment_id,
|
||||
accommodation_id: input.accommodation_id,
|
||||
title: input.title,
|
||||
reservation_time: input.reservation_time,
|
||||
reservation_end_time: input.reservation_end_time,
|
||||
location: input.location,
|
||||
confirmation_number: input.confirmation_number,
|
||||
notes: input.notes,
|
||||
url: input.url,
|
||||
status: input.status,
|
||||
type: input.type,
|
||||
metadata: input.metadata,
|
||||
day_plan_position: input.day_plan_position,
|
||||
needs_review: input.needs_review,
|
||||
ingest_state: input.ingest_state,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,35 +124,42 @@ interface ReservationRestampKyselyDB {
|
||||
/**
|
||||
* Kysely typing for AC37/AC40 (`listIdMetadataByStay`/`listIdsByStay`).
|
||||
*
|
||||
* A bound-parameter `WHERE accommodation_id = ?` on this TEXT column is NOT
|
||||
* the same comparison the legacy statement's own `Number(id)` bind produced
|
||||
* (Task 3 finding, verified empirically against the live driver, not
|
||||
* assumed from the inventory's §18.1 wording): `better-sqlite3` binds every
|
||||
* plain JS number as SQLite REAL, integer-valued or not (`typeof(?)` on a
|
||||
* bound `14` reads back `'real'`) — including through MikroORM's Kysely
|
||||
* dialect — and SQLite's TEXT-affinity conversion of a REAL for a
|
||||
* comparison renders its decimal form (`14` → `'14.0'`), not the plain
|
||||
* integer text `'14'`. A row this repository itself writes through
|
||||
* `em.insert()`/`nativeUpdate()` stores the OTHER shape (`'14'`, no `.0` —
|
||||
* MikroORM inlines the value as a literal in the generated SQL, rule 22,
|
||||
* which SQLite's parser treats as a genuine INTEGER token, not a
|
||||
* REAL-bound parameter) — so a plain `WHERE accommodation_id = ?` bound
|
||||
* with a number would consistently MISS every row this cluster's own
|
||||
* `em.insert()` calls write, not just the documented `"14.0"` edge case.
|
||||
* {@link castIntegerKysely} (SQLF-057, `sql-functions.test.ts`) sidesteps
|
||||
* the whole shape question: `CAST(accommodation_id AS INTEGER) = ?` matches
|
||||
* `'14'` AND `'14.0'` alike (SQLite compares the CAST result against the
|
||||
* bound REAL/INTEGER numerically, not as text), which is what "every
|
||||
* linked booking" (AC37/AC40's own contract — more than one reservation,
|
||||
* written by different call sites with different shapes, can point at one
|
||||
* stay) actually needs, and is R2's own "tested with both `'14'` and
|
||||
* `'14.0'` rows" requirement satisfied structurally rather than by picking
|
||||
* a side.
|
||||
* **Revert to the REAL-bound compare (Plan 3d Task 7 whole-plan review, M3;
|
||||
* corrects this docstring's earlier claim).** A bound-parameter `WHERE
|
||||
* accommodation_id = ?` with a plain JS `number` is EXACTLY the comparison
|
||||
* the legacy statement's own `Number(id)` bind produced: `better-sqlite3`
|
||||
* binds every plain JS number as SQLite REAL, integer-valued or not
|
||||
* (`typeof(?)` on a bound `14` reads back `'real'`) — including through
|
||||
* MikroORM's Kysely dialect — and SQLite's TEXT-affinity conversion of a
|
||||
* REAL for a comparison renders its decimal form (`14` → `'14.0'`), so a
|
||||
* bound `WHERE accommodation_id = ?` matches `'14.0'` ONLY, same as the
|
||||
* legacy statement — never `'14'`. The earlier version of this docstring
|
||||
* claimed the opposite (that `em.insert()`/`nativeUpdate()` calls in this
|
||||
* cluster store the bare `'14'` shape and a REAL-bound compare would
|
||||
* therefore miss them): that was true only because RS28/RS41
|
||||
* (`reservations.service.ts`, outside this repository) used to write
|
||||
* `String(n)` instead of the legacy's REAL-bound shape (H1, the same
|
||||
* review). H1 fixes every write in this cluster to store `'<id>.0'`
|
||||
* (`legacyBoundIntegerText`), so the widening below has no remaining
|
||||
* reason to exist, and parity is law once it doesn't: `CAST(accommodation_id
|
||||
* AS INTEGER) = ?` (via {@link castIntegerKysely}) matches `'14'`, `'14.0'`,
|
||||
* `'14 '` and `'14abc'` alike — a WIDER row set than the legacy's own
|
||||
* `'14.0'`-only compare (measured, task-7-review.md M3) — which is an
|
||||
* unpinned parity break, not a fix, on a read the legacy also bound
|
||||
* `Number(id)` for. `castIntegerKysely` stays in use elsewhere in this file
|
||||
* (RS20/RV2's correlated subqueries) where the legacy statement's OWN
|
||||
* comparison used a `CAST`, not a bound number — this interface's two
|
||||
* consumers are not that case.
|
||||
*/
|
||||
interface ReservationsByAccommodationKyselyDB {
|
||||
reservations: {
|
||||
id: number;
|
||||
accommodation_id: string | null;
|
||||
// `string | number | null`, not just `string` (R2's ruling, the same
|
||||
// widening {@link ReservationRestampKyselyDB} documents for DY23): the
|
||||
// column is TEXT, but the bind below is a plain `number`, matching the
|
||||
// legacy's own `Number(id)` bind — the interface only needs to
|
||||
// type-check that bind, not describe the column's storage type.
|
||||
accommodation_id: string | number | null;
|
||||
metadata: string | null;
|
||||
};
|
||||
}
|
||||
@@ -924,16 +931,16 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
|
||||
* AC37 (`AccommodationsService.updateAccommodation`) — `SELECT id,
|
||||
* metadata FROM reservations WHERE accommodation_id = ?`, every linked
|
||||
* booking (no unique constraint on the column — more than one booking can
|
||||
* point at the same stay, and different write paths can leave it in
|
||||
* either TEXT shape). `castIntegerKysely` (see
|
||||
* {@link ReservationsByAccommodationKyselyDB}'s docstring for why).
|
||||
* point at the same stay). Bound as a plain `number`, matching the
|
||||
* legacy's own `Number(id)` bind byte-for-byte — see
|
||||
* {@link ReservationsByAccommodationKyselyDB}'s docstring (M3, reverted
|
||||
* from the `castIntegerKysely` widening).
|
||||
*/
|
||||
async listIdMetadataByStay(accommodation_id: number): Promise<{ id: number; metadata: string | null }[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.kysely<ReservationsByAccommodationKyselyDB>()
|
||||
.selectFrom('reservations')
|
||||
.select(['id', 'metadata'])
|
||||
.where((eb) => eb(castIntegerKysely(platform, eb, 'accommodation_id'), '=', accommodation_id))
|
||||
.where('accommodation_id', '=', accommodation_id)
|
||||
.execute();
|
||||
return rows as { id: number; metadata: string | null }[];
|
||||
}
|
||||
@@ -960,18 +967,110 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
|
||||
/**
|
||||
* AC40 (`AccommodationsService.deleteAccommodation`) — `SELECT id FROM
|
||||
* reservations WHERE accommodation_id = ?`, ALL linked bookings. Same
|
||||
* `castIntegerKysely` reasoning as {@link listIdMetadataByStay}.
|
||||
* REAL-bound compare as {@link listIdMetadataByStay} (M3).
|
||||
*/
|
||||
async listIdsByStay(accommodation_id: number): Promise<{ id: number }[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.kysely<ReservationsByAccommodationKyselyDB>()
|
||||
.selectFrom('reservations')
|
||||
.select(['id'])
|
||||
.where((eb) => eb(castIntegerKysely(platform, eb, 'accommodation_id'), '=', accommodation_id))
|
||||
.where('accommodation_id', '=', accommodation_id)
|
||||
.execute();
|
||||
return rows as { id: number }[];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3d Task 6 (`trips.service.ts::copy`) — moved here from
|
||||
// `ReservationEndpoints.repository.ts` in the Task 7 whole-plan review's
|
||||
// fix wave (item 8/D4, "one repository per table"): Task 4 owned this file
|
||||
// for the Task 6 tree window, so TP58/TP59 (the reservations copy
|
||||
// read/write) landed on `ReservationEndpointsRepository` instead at the
|
||||
// time — a pure move now that the window is closed, same statements,
|
||||
// same parity proof (`Reservations.repository.test.ts`). Endpoints/
|
||||
// travelers/day-positions are never copied with a reservation (R7,
|
||||
// `copy` never copied them — kept as-is on their own repositories).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* TP58 (`trips.service.ts::copy`'s reservations read) — `SELECT * FROM
|
||||
* reservations WHERE trip_id = ?`, no `ORDER BY` (matching the legacy
|
||||
* statement; the copy loop's own id-remap doesn't depend on read order).
|
||||
* `ReservationAllColumnsRow` (RS35's own `SELECT *` shape) rather than a
|
||||
* second, differently-named copy of the same fields.
|
||||
*/
|
||||
async listAllForTrip(trip_id: number): Promise<ReservationAllColumnsRow[]> {
|
||||
return await this.kysely<{ reservations: ReservationAllColumnsRow }>()
|
||||
.selectFrom('reservations')
|
||||
.selectAll()
|
||||
.where('trip_id', '=', trip_id)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* TP59 (`trips.service.ts::copy`'s reservation INSERT) — `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) VALUES (?×19)`. The
|
||||
* `external_*`/`sync_enabled`/`created_at` columns are deliberately
|
||||
* omitted (the legacy statement's own column list never named them — a
|
||||
* copy must not inherit the source's external sync identity).
|
||||
*
|
||||
* `this.insert(...)`, not `this.getEntityManager().insert(Reservations,
|
||||
* …)`: this repository IS templated on `Reservations` (unlike
|
||||
* `ReservationEndpointsRepository`, where this method used to live and
|
||||
* needed the escape hatch to reach a table it wasn't templated on) — the
|
||||
* ordinary `TrekRepository.insert` is the right call here.
|
||||
*
|
||||
* `accommodation_id` arrives ALREADY formatted as the legacy `'<id>.0'`
|
||||
* TEXT shape (`row-id.ts`'s `legacyBoundIntegerText`, the program's
|
||||
* Plan 3d Task 3 `"14.0"` finding): a plain JS number written here would
|
||||
* be inlined as a SQL literal (rule 22) and stored as `'14'`, not the
|
||||
* shape the legacy raw-bound statement produced.
|
||||
*/
|
||||
async insertReservationCopy(input: {
|
||||
trip_id: number;
|
||||
day_id: number | null;
|
||||
end_day_id: number | null;
|
||||
place_id: number | null;
|
||||
assignment_id: number | null;
|
||||
accommodation_id: string | 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;
|
||||
}): Promise<number> {
|
||||
return await this.insert({
|
||||
trip: input.trip_id,
|
||||
day: input.day_id,
|
||||
endDay: input.end_day_id,
|
||||
place: input.place_id,
|
||||
assignment: input.assignment_id,
|
||||
accommodation_id: input.accommodation_id,
|
||||
title: input.title,
|
||||
reservation_time: input.reservation_time,
|
||||
reservation_end_time: input.reservation_end_time,
|
||||
location: input.location,
|
||||
confirmation_number: input.confirmation_number,
|
||||
notes: input.notes,
|
||||
url: input.url,
|
||||
status: input.status,
|
||||
type: input.type,
|
||||
metadata: input.metadata,
|
||||
day_plan_position: input.day_plan_position,
|
||||
needs_review: input.needs_review,
|
||||
ingest_state: input.ingest_state,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3d Task 4 — additive (see the file-level comment above the interfaces
|
||||
// this section's methods return).
|
||||
|
||||
@@ -6,7 +6,7 @@ import { DatabaseService, type PlaceWithTags, type TripAccess } from '../databas
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { AssignmentsService } from '../assignments/assignments.service';
|
||||
import { toRowId } from '../common/row-id';
|
||||
import { toRowId, legacyBoundIntegerText } from '../common/row-id';
|
||||
import { DayAccommodations } from '../../db/entities/DayAccommodations.entity';
|
||||
import type { DayAccommodationsRepository, DayAccommodationRow } from '../../db/repositories/DayAccommodations.repository';
|
||||
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
|
||||
@@ -55,31 +55,6 @@ export interface AccommodationMirror {
|
||||
* stay row themselves and have to answer with a mirror either way. */
|
||||
export const noStayMirror = (): AccommodationMirror => ({ created: null, moved: null, updated: [], removed: [], stamped: null });
|
||||
|
||||
/**
|
||||
* AC33's `accommodation_id` value, in the exact TEXT shape the TRUE legacy
|
||||
* (pre-ORM) statement stored (Task 3 finding, verified empirically against
|
||||
* the live `better-sqlite3` driver, not assumed): the legacy `INSERT INTO
|
||||
* reservations (…, accommodation_id, …) VALUES (…, ?, …)` bound the new
|
||||
* stay's id — a plain JS `number` from `result.lastInsertRowid` — as a
|
||||
* `?` parameter, and `better-sqlite3` binds every plain JS number as SQLite
|
||||
* REAL regardless of integer-ness (confirmed via `typeof(?)`); SQLite's own
|
||||
* "numeric data inserted into a TEXT column is converted to text first"
|
||||
* rule then renders a REAL's decimal form, `14` → `'14.0'`, not the plain
|
||||
* integer text `'14'`. `accommodations.service.test.ts`'s DAY-SVC-020/023/
|
||||
* 025 etc. read this column back with their OWN plain-number-bound raw SQL
|
||||
* (`testDb.prepare('… WHERE accommodation_id = ?').get(accom.id)`, matching
|
||||
* the same REAL-binding path), so this write must reproduce that exact
|
||||
* shape for those UNCHANGED "proof" tests to keep passing — `String(id)`
|
||||
* (`'14'`, what `MikroORM.em.insert()` would store for either a number or a
|
||||
* string, since it inlines the value as a SQL-text literal, rule 22, a
|
||||
* DIFFERENT shape) does not. `ReservationsRepository`'s own reads of this
|
||||
* column (`listIdMetadataByStay`/`listIdsByStay`) go through
|
||||
* `castIntegerKysely` instead, which matches this shape AND `'14'` alike —
|
||||
* see that file's docstring.
|
||||
*/
|
||||
function legacyBoundIntegerText(id: number): string {
|
||||
return `${id}.0`;
|
||||
}
|
||||
const noMirror = noStayMirror;
|
||||
|
||||
export interface DayAccommodation {
|
||||
|
||||
@@ -92,3 +92,29 @@ export function toRowId(value: unknown): number | null {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The TEXT shape the legacy raw-SQL layer actually stored for an
|
||||
* `accommodation_id` value bound as a plain JS number (Plan 3d Task 3/7
|
||||
* finding, verified empirically against the live `better-sqlite3` driver,
|
||||
* not assumed): `better-sqlite3` binds every plain JS `number` as SQLite
|
||||
* REAL regardless of integer-ness (confirmed via `typeof(?)`), and SQLite's
|
||||
* own "numeric value inserted into a TEXT column becomes text" rule then
|
||||
* renders a REAL's decimal form — `14` → `'14.0'`, never the plain integer
|
||||
* text `'14'`. `String(id)` (what a SQL-literal-inlined `em.insert()`,
|
||||
* rule 22, would produce for a bound `number`) renders `'14'` instead — a
|
||||
* DIFFERENT stored shape from the legacy's — and a reader that still
|
||||
* compares against the REAL-bound form (`restampLinkedReservation`/DY23
|
||||
* binds the id as a number through Kysely, which is REAL again) silently
|
||||
* misses every row written that way.
|
||||
*
|
||||
* Use this wherever a `number` id is written into the `accommodation_id`
|
||||
* TEXT column so the stored bytes match what the legacy statement would
|
||||
* have stored for the same input — never `String(id)` for that column.
|
||||
* `ReservationsRepository`'s reads of this column that must match BOTH the
|
||||
* legacy shape and a `String(id)` shape go through `castIntegerKysely`
|
||||
* instead (see that file's docstring); this helper is for WRITES only.
|
||||
*/
|
||||
export function legacyBoundIntegerText(id: number): string {
|
||||
return `${id}.0`;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { BudgetService } from '../budget/budget.service';
|
||||
import { typeToCostCategory } from '@trek/shared';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { AccommodationsService, noStayMirror, type AccommodationMirror } from '../accommodations/accommodations.service';
|
||||
import { toRowId } from '../common/row-id';
|
||||
import { toRowId, legacyBoundIntegerText } from '../common/row-id';
|
||||
import { Reservations } from '../../db/entities/Reservations.entity';
|
||||
import type { ReservationsRepository } from '../../db/repositories/Reservations.repository';
|
||||
import { ReservationEndpoints as ReservationEndpointsEntity } from '../../db/entities/ReservationEndpoints.entity';
|
||||
@@ -733,10 +733,13 @@ export class ReservationsService {
|
||||
const resolvedAssignmentId = await this.resolvedOrNull('day_assignments', assignment_id || null);
|
||||
|
||||
// RS28. `accommodation_id` bound as the TEXT column's string form (R2 —
|
||||
// the legacy statement bound a plain JS number and let better-sqlite3's
|
||||
// driver / SQLite's own TEXT-affinity conversion at write time store it
|
||||
// as text; `String(n)` on a normal integer id renders the identical
|
||||
// bytes, so this is byte-parity, not a behaviour change).
|
||||
// the legacy statement bound a plain JS number, which better-sqlite3
|
||||
// binds as SQLite REAL, so the TEXT column stores the `'<id>.0'` shape,
|
||||
// not the plain integer text `String(n)` renders — H1, Plan 3d Task 7
|
||||
// review: this used to be `String(n)`, which stored a DIFFERENT shape
|
||||
// than the legacy and silently broke `restampLinkedReservation`/DY23's
|
||||
// REAL-bound compare. `legacyBoundIntegerText` reproduces the legacy
|
||||
// bytes exactly.
|
||||
const insertedId = await this.reservationsRepo.insertReservation({
|
||||
trip_id: this.rowIdNum(tripId),
|
||||
day_id: resolvedDayId,
|
||||
@@ -752,7 +755,7 @@ export class ReservationsService {
|
||||
url: url || null,
|
||||
status: status || 'pending',
|
||||
type: resolvedType,
|
||||
accommodation_id: resolvedAccommodationId == null ? null : String(resolvedAccommodationId),
|
||||
accommodation_id: resolvedAccommodationId == null ? null : legacyBoundIntegerText(resolvedAccommodationId),
|
||||
metadata: metadata ? JSON.stringify(metadata) : null,
|
||||
needs_review: needs_review ? 1 : 0,
|
||||
});
|
||||
@@ -793,8 +796,16 @@ export class ReservationsService {
|
||||
// agree on it. Doing that in the statement rather than as a pre-check also
|
||||
// makes a stale id a quiet no-op instead of a foreign-key error surfacing
|
||||
// as a 500.
|
||||
const dayIdNum = this.rowIdNum(dayId);
|
||||
//
|
||||
// M4, Plan 3d Task 7 review: `dayId` parsed with `toRowId` (rule 21),
|
||||
// not `rowIdNum` — `rowIdNum`'s `Number(...)` fallback let a
|
||||
// hex/exponent `dayId` (`0x1`, `1e1`) coerce to a real day and reach
|
||||
// the join, where the legacy raw-bind statement's affinity never
|
||||
// converts a hex string and so matched no row. A miss here is the same
|
||||
// quiet no-op the join already gives a stale id — no write happens.
|
||||
const dayIdNum = toRowId(dayId);
|
||||
const tripIdNum = this.rowIdNum(tripId);
|
||||
if (dayIdNum === null) return;
|
||||
await this.uow.transactional(async () => {
|
||||
for (const item of positions) {
|
||||
// RS31/RS32. position is NOT NULL while the wire contract leaves the value optional.
|
||||
@@ -858,16 +869,32 @@ export class ReservationsService {
|
||||
// `resolvedAccId` deliberately keeps BOTH shapes alive, exactly as the
|
||||
// legacy code's own type lie did at runtime (`Reservation
|
||||
// .accommodation_id` claimed `number` while the raw row underneath was
|
||||
// always the TEXT column's string): when the payload names
|
||||
// `accommodation_id` it is a genuine `number` (`UpdateReservationData`'s
|
||||
// declared type); when it falls back to `current.accommodation_id` it is
|
||||
// the UNCONVERTED string this reservation already stored (R2 — a
|
||||
// always the TEXT column's string; `UpdateReservationData.accommodation_id`
|
||||
// carries the same lie for the INCOMING payload — the wire schema is
|
||||
// `z.union([z.number(), z.string()])`, so a string reaches here despite
|
||||
// the declared `number` type): when the payload names `accommodation_id`
|
||||
// it is USER INPUT and goes through `toRowId` (L2, Plan 3d Task 7
|
||||
// review — `Number('0x1')` used to coerce a hex-spelled link and pass
|
||||
// the existence check below where the legacy raw-bind statement's own
|
||||
// affinity never would; `toRowId` returns `null` for any non-canonical
|
||||
// shape, including a `'1.0'`/`' 1'` string — an ACCEPTED rule-15
|
||||
// narrowing here, since a payload value is untrusted input, unlike the
|
||||
// fallback below); when it falls back to `current.accommodation_id` it
|
||||
// is the UNCONVERTED string this reservation already stored (R2 — a
|
||||
// `"14.0"`-shaped value must round-trip byte-identical through a no-op
|
||||
// update, which a `Number()`/`String()` round-trip would truncate to
|
||||
// `"14"`). `accIdForRead(...)` below is the READ-only numeric form every
|
||||
// repository call needs; the final write still binds `resolvedAccId`
|
||||
// itself (via `String(...)`, a no-op on an already-string value).
|
||||
let resolvedAccId: number | string | null = accommodation_id !== undefined ? (accommodation_id || null) : (current.accommodation_id ?? null);
|
||||
// update, which running it through `toRowId` — or a `Number()`/
|
||||
// `String()` round-trip — would break: `toRowId('14.0')` is `null`,
|
||||
// which would silently drop the link on every edit that doesn't touch
|
||||
// `accommodation_id`; OUR OWN previously-written data is not the input
|
||||
// L2 is about). `accIdForRead(...)` below is the READ-only numeric form
|
||||
// every repository call needs; the final write formats a genuine
|
||||
// `number` through `legacyBoundIntegerText` (H1, Plan 3d Task 7 review —
|
||||
// a bare `String(...)` stored `'<id>'`, not the legacy's REAL-bound
|
||||
// `'<id>.0'`) and passes an already-string value through unchanged, a
|
||||
// no-op.
|
||||
let resolvedAccId: number | string | null = accommodation_id !== undefined
|
||||
? (accommodation_id == null ? null : toRowId(accommodation_id))
|
||||
: (current.accommodation_id ?? null);
|
||||
const accIdForRead = (v: number | string | null): number | null => (v == null ? null : Number(v));
|
||||
if (resolvedAccId) {
|
||||
// Scoped to the trip on purpose: an id belonging to someone else's trip
|
||||
@@ -987,7 +1014,7 @@ export class ReservationsService {
|
||||
assignment_id: nextAssignmentId,
|
||||
status: status || current.status,
|
||||
type: type || current.type,
|
||||
accommodation_id: resolvedAccId == null ? null : String(resolvedAccId),
|
||||
accommodation_id: resolvedAccId == null ? null : (typeof resolvedAccId === 'number' ? legacyBoundIntegerText(resolvedAccId) : resolvedAccId),
|
||||
metadata: nextMetadata !== undefined ? (nextMetadata ? JSON.stringify(nextMetadata) : null) : (current.metadata ?? null),
|
||||
needs_review: needs_review === undefined ? (current.needs_review ?? 0) : (needs_review ? 1 : 0),
|
||||
});
|
||||
@@ -1023,8 +1050,16 @@ export class ReservationsService {
|
||||
/** The accommodation + budget-item + reservation deletes are one logical
|
||||
* cascade — all-or-nothing. */
|
||||
async remove(id: string | number, tripId: string | number): Promise<{ deleted: { id: number; title: string; type: string | null; accommodation_id: string | null } | undefined; accommodationDeleted: boolean; deletedBudgetItemId: number | null }> {
|
||||
const idNum = this.rowIdNum(id);
|
||||
const tripIdNum = this.rowIdNum(tripId);
|
||||
// M4, Plan 3d Task 7 review: parsed ONCE here with `toRowId` (rule 21),
|
||||
// not `rowIdNum` — `rowIdNum`'s `Number(...)` fallback let a hex/exponent
|
||||
// id (`0x1`, `1e1`) reach `findHeaderInTrip` and delete a real row where
|
||||
// the legacy raw-bind statement 404'd. A miss here answers exactly the
|
||||
// `findHeaderInTrip`-miss shape below, without touching the DB.
|
||||
const idNum = toRowId(id);
|
||||
const tripIdNum = toRowId(tripId);
|
||||
if (idNum === null || tripIdNum === null) {
|
||||
return { deleted: undefined, accommodationDeleted: false, deletedBudgetItemId: null };
|
||||
}
|
||||
const removed = await this.uow.transactional(async () => {
|
||||
// RS45
|
||||
const reservation = await this.reservationsRepo.findHeaderInTrip(idNum, tripIdNum);
|
||||
|
||||
@@ -84,13 +84,24 @@ export class RoadtripService {
|
||||
return await this.daysRepo.existsInTrip(dayId, tripId);
|
||||
}
|
||||
|
||||
// L1 (Plan 3d Task 7 whole-plan review): `toRowId`, not `Number()` — a
|
||||
// hex/exponent-spelled id used to coerce to a real row and return its
|
||||
// vias/tracks, where the legacy raw-bind statement's affinity never
|
||||
// converts a hex string and so matched nothing. `TripAccessGuard` already
|
||||
// authorised the SAME hex-spelled id through its own `Number()` (not a
|
||||
// leak, rule-21 seam widening) — a miss here answers the legacy empty
|
||||
// shape, matching every other read path in this class.
|
||||
async listForDay(dayId: string | number): Promise<RoadtripVia[]> {
|
||||
return await this.viasRepo.listForDay(Number(dayId));
|
||||
const dayIdNum = toRowId(dayId);
|
||||
if (dayIdNum === null) return [];
|
||||
return await this.viasRepo.listForDay(dayIdNum);
|
||||
}
|
||||
|
||||
/** Every via of a trip, so the client can route all days without one request per day. */
|
||||
async listForTrip(tripId: string | number): Promise<RoadtripVia[]> {
|
||||
return await this.viasRepo.listForTrip(Number(tripId));
|
||||
const tripIdNum = toRowId(tripId);
|
||||
if (tripIdNum === null) return [];
|
||||
return await this.viasRepo.listForTrip(tripIdNum);
|
||||
}
|
||||
|
||||
async create(dayId: string | number, input: { after_order_index: number; lat: number; lng: number; sequence?: number }): Promise<RoadtripVia> {
|
||||
@@ -162,12 +173,16 @@ export class RoadtripService {
|
||||
* second route for a handful of rows would be a second round trip for nothing.
|
||||
*/
|
||||
async tracksForTrip(tripId: string | number): Promise<RoadtripDayTrack[]> {
|
||||
return await this.tracksRepo.listForTrip(Number(tripId));
|
||||
const tripIdNum = toRowId(tripId);
|
||||
if (tripIdNum === null) return [];
|
||||
return await this.tracksRepo.listForTrip(tripIdNum);
|
||||
}
|
||||
|
||||
/** Whether a place is on this trip, and is a track rather than an ordinary place. RT13 → `PlacesRepository.isTrackInTrip`. */
|
||||
async trackExists(placeId: number, tripId: string | number): Promise<boolean> {
|
||||
return await this.placesRepo.isTrackInTrip(placeId, Number(tripId));
|
||||
const tripIdNum = toRowId(tripId);
|
||||
if (tripIdNum === null) return false;
|
||||
return await this.placesRepo.isTrackInTrip(placeId, tripIdNum);
|
||||
}
|
||||
|
||||
/** Moving a via is the whole edit; where it sits in the chain does not change. */
|
||||
|
||||
@@ -15,7 +15,7 @@ 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 { ReservationEndpoints } from '../../db/entities/ReservationEndpoints.entity';
|
||||
import { Reservations } from '../../db/entities/Reservations.entity';
|
||||
import { MAX_TRIP_DAYS, tripSpanDays, type ActiveTrip, type TrekWsPayload, type TrekWsTripEventName } from '@trek/shared';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
@@ -28,6 +28,7 @@ import { UnsplashService } from '../unsplash/unsplash.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { NotFoundError, ValidationError } from '../common/domain-errors';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { legacyBoundIntegerText } from '../common/row-id';
|
||||
|
||||
export const MS_PER_DAY = 86400000;
|
||||
|
||||
@@ -58,26 +59,6 @@ export function withoutFeedToken<T>(row: T): T {
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* `copy`'s (TP59) `reservations.accommodation_id` write. Mirrors
|
||||
* `AccommodationsService`'s own `legacyBoundIntegerText` (Plan 3d Task 3,
|
||||
* `accommodations.service.ts` — unexported there, so not importable across
|
||||
* this task's file-ownership boundary; reproduced here instead, same
|
||||
* one-line shape): a plain JS number bound as a `?` parameter through
|
||||
* better-sqlite3 is stored as SQLite REAL regardless of integer-ness, and
|
||||
* SQLite's "numeric value inserted into a TEXT column becomes text" rule
|
||||
* then renders `14` as `'14.0'`, not the plain integer text `'14'` a
|
||||
* SQL-literal-inlined `em.insert()` (rule 22) would produce. The legacy raw
|
||||
* `copy` statement bound the new stay's id (a plain number from `accomMap`)
|
||||
* the same way — reproduced explicitly here since the write now goes
|
||||
* through a typed insert (`ReservationEndpointsRepository
|
||||
* .insertReservationCopy`) instead of a raw bound parameter; passing an
|
||||
* already-formatted STRING sidesteps the shape question entirely (SQLite
|
||||
* applies no numeric conversion to a value that already has TEXT affinity).
|
||||
*/
|
||||
function legacyAccommodationIdText(id: number): string {
|
||||
return `${id}.0`;
|
||||
}
|
||||
|
||||
interface CreateTripData {
|
||||
title: string;
|
||||
@@ -257,13 +238,14 @@ export class TripsService {
|
||||
return this.em.getRepository(DayAccommodations);
|
||||
}
|
||||
|
||||
// `ReservationEndpointsRepository`, not `ReservationsRepository`: Task 4
|
||||
// owns `Reservations.repository.ts` for this tree window, so TP58/TP59
|
||||
// (the reservations read/insert) live on a repository this task owns
|
||||
// instead — see `ReservationEndpoints.repository.ts`'s own docstring on
|
||||
// `listAllForTrip`/`insertReservationCopy`.
|
||||
private get reservationEndpointsRepo() {
|
||||
return this.em.getRepository(ReservationEndpoints);
|
||||
// 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);
|
||||
}
|
||||
|
||||
async canAccessTrip(tripId: string | number, userId: number) {
|
||||
@@ -814,7 +796,7 @@ export class TripsService {
|
||||
if (newAssignmentId && newAccomId) await this.dayAssignmentsRepo.setAccommodation(newAssignmentId, newAccomId); // TP57
|
||||
}
|
||||
|
||||
const oldReservations = await this.reservationEndpointsRepo.listAllForTrip(Number(sourceTripId)); // TP58
|
||||
const oldReservations = await this.reservationsRepo.listAllForTrip(Number(sourceTripId)); // TP58
|
||||
// The external_* / sync_enabled columns are deliberately not copied: the
|
||||
// duplicate must not inherit the source's external sync identity.
|
||||
const reservationMap = new Map<number, number>();
|
||||
@@ -823,7 +805,7 @@ export class TripsService {
|
||||
// as a string — coerce before the number-keyed map lookup or the
|
||||
// link silently nulls.
|
||||
const newAccomId = r.accommodation_id != null ? (accomMap.get(Number(r.accommodation_id)) ?? null) : null;
|
||||
const newReservationId = await this.reservationEndpointsRepo.insertReservationCopy({
|
||||
const newReservationId = await this.reservationsRepo.insertReservationCopy({
|
||||
trip_id: newTripId,
|
||||
day_id: r.day_id ? (dayMap.get(r.day_id) ?? null) : null,
|
||||
// end_day_id is a day reference too (multi-day transport) — remap it like
|
||||
@@ -832,8 +814,8 @@ export class TripsService {
|
||||
place_id: r.place_id ? (placeMap.get(r.place_id) ?? null) : null,
|
||||
assignment_id: r.assignment_id ? (assignmentMap.get(r.assignment_id) ?? null) : null,
|
||||
// the NEW value is re-formatted to the legacy raw-bound `'<id>.0'`
|
||||
// TEXT shape on the way back out — see `legacyAccommodationIdText`.
|
||||
accommodation_id: newAccomId != null ? legacyAccommodationIdText(newAccomId) : null,
|
||||
// TEXT shape on the way back out — see `legacyBoundIntegerText`.
|
||||
accommodation_id: newAccomId != null ? legacyBoundIntegerText(newAccomId) : null,
|
||||
title: r.title, reservation_time: r.reservation_time, reservation_end_time: r.reservation_end_time,
|
||||
location: r.location, confirmation_number: r.confirmation_number, notes: r.notes, url: r.url, status: r.status, type: r.type,
|
||||
// ingest_state travels with the copy: a staged booking must not turn
|
||||
|
||||
Reference in New Issue
Block a user