feat(reservations): record an import's origin and scope the joined read to its trip

CreateReservationData and insertReservation take an optional external_source,
external_id and sync_enabled, so an importer can record where a booking came from;
without them every write keeps the column defaults. Client bodies on REST and the
plugin RPC have the origin stripped, so no caller can pose as an import or a link.
getReservationWithJoins now takes the trip and reads nothing outside it.
This commit is contained in:
Maurice
2026-11-13 14:52:59 +01:00
parent 64418489e2
commit d2b12cd3dd
11 changed files with 187 additions and 38 deletions
@@ -398,10 +398,15 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
/**
* RR1 (`ReservationsReadService.getReservationWithJoins`) — the SAME
* projection for one reservation, no `ORDER BY` (a single row).
* projection for one reservation, no `ORDER BY` (a single row), and only
* when it belongs to `trip_id`: every caller holds the trip it checked, so a
* booking id from another trip reads as missing rather than leaking its row.
*/
async findWithJoins(id: number | string): Promise<ReservationJoinRow | undefined> {
const row = await this.joinedQuery().where('r.id', '=', id as number).executeTakeFirst();
async findWithJoins(id: number | string, trip_id: number | string): Promise<ReservationJoinRow | undefined> {
const row = await this.joinedQuery()
.where('r.id', '=', id as number)
.where('r.trip_id', '=', trip_id as number)
.executeTakeFirst();
return row as ReservationJoinRow | undefined;
}
@@ -459,12 +464,16 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* (trip_id, day_id, end_day_id, place_id, assignment_id, title,
* reservation_time, reservation_end_time, location, confirmation_number,
* notes, url, status, type, accommodation_id, metadata, needs_review)
* VALUES (?×17)`. `sync_enabled`/`ingest_state`/`day_plan_position`
* deliberately NOT named, so the column's own DB-level `DEFAULT` applies
* (`sync_enabled INTEGER DEFAULT 1`, `Migration20200101021800_…`;
* `ingest_state` `.default('live')`) — the caller has already resolved
* every value (the `|| null` coercions, `resolvedOrNull`, the numeric
* `accommodation_id` stringified for the TEXT column, R2).
* VALUES (?×17)`. `ingest_state`/`day_plan_position` deliberately NOT
* named, so the column's own DB-level `DEFAULT` applies (`ingest_state`
* `.default('live')`) — the caller has already resolved every value (the
* `|| null` coercions, `resolvedOrNull`, the numeric `accommodation_id`
* stringified for the TEXT column, R2).
*
* `external_source`/`external_id`/`sync_enabled` are named only when the
* caller passes them: an imported booking records where it came from, every
* other write leaves them to the column defaults as before (`sync_enabled
* INTEGER DEFAULT 1`, `Migration20200101021800_…`).
*/
async insertReservation(input: {
trip_id: number;
@@ -484,6 +493,9 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
accommodation_id: string | null;
metadata: string | null;
needs_review: number;
external_source?: string;
external_id?: string;
sync_enabled?: number;
}): Promise<number> {
return await this.insert({
trip: input.trip_id,
@@ -503,9 +515,26 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
accommodation_id: input.accommodation_id,
metadata: input.metadata,
needs_review: input.needs_review,
...(input.external_source !== undefined && { external_source: input.external_source }),
...(input.external_id !== undefined && { external_id: input.external_id }),
...(input.sync_enabled !== undefined && { sync_enabled: input.sync_enabled }),
});
}
/**
* The booking an import already wrote into this trip under the same origin,
* or undefined: what `idx_reservations_external (external_source,
* external_id, trip_id)` would refuse, read before the write so a repeat
* import is reported instead of failing on the unique index.
*/
async findIdByExternal(trip_id: number, external_source: string, external_id: string): Promise<number | undefined> {
const row = await this.qb('r')
.select(['r.id'])
.where({ trip: trip_id, external_source, external_id })
.execute<{ id: number } | undefined>('get', false);
return row?.id;
}
/**
* RS41 (`ReservationsService.updateInTx`) — the 16-column `UPDATE
* reservations SET … WHERE id = ?`. The `PlacesRepository.updatePlace`/PL11
@@ -53,7 +53,7 @@ export class AirtrailLinkService {
async broadcastUpdated(tripId: number, reservationId: number): Promise<void> {
try {
const reservation = await this.reads.getReservationWithJoins(reservationId);
const reservation = await this.reads.getReservationWithJoins(reservationId, tripId);
if (reservation)
this.realtime.broadcast(String(tripId), 'reservation:updated', { reservation } as never, undefined);
} catch {
@@ -97,7 +97,7 @@ export class AirtrailLinkService {
// 1:1 mapping to the AirTrail flight: pushing would rewrite that flight to the
// full span, and the next pull would flatten the layover again. Detach — the
// merge is a deliberate local restructuring, like a joined import (#1535).
const reservation = await this.reads.getReservationWithJoins(row.id);
const reservation = await this.reads.getReservationWithJoins(row.id, row.trip_id);
if (!reservation) return;
if (await this.hasLocalMultiLegShape(row.id, (reservation as { metadata?: string | null }).metadata)) {
await this.detach(tripId, row.id);
@@ -59,9 +59,10 @@ export class ReservationsReadService {
@InjectRepository(ReservationDayPositions) private readonly dayPositionsRepo: ReservationDayPositionsRepository,
) {}
async getReservationWithJoins(id: string | number): Promise<ReservationRow | undefined> {
/** The booking with its endpoints, travellers and day slots, or undefined when it is not one of this trip's. */
async getReservationWithJoins(id: string | number, tripId: string | number): Promise<ReservationRow | undefined> {
// RR1
const row = await this.reservationsRepo.findWithJoins(id);
const row = await this.reservationsRepo.findWithJoins(id, tripId);
if (!row) return undefined;
const result: ReservationRow = { ...row };
result.endpoints = await this.loadEndpoints(row.id);
@@ -9,7 +9,7 @@ import {
ReservationPositionsDto,
ReservationTravelersDto,
} from './reservations.dto';
import { ReservationsService } from './reservations.service';
import { ReservationsService, withoutOrigin } from './reservations.service';
import { Body, Controller, Delete, Get, Headers, HttpException, Param, Post, Put, UseGuards } from '@nestjs/common';
type ReservationBody = Record<string, unknown> & {
@@ -63,7 +63,7 @@ export class ReservationsController {
// The booking and its linked cost are one write.
return this.writes.createBooking(
tripId,
body as never,
withoutOrigin(body) as never,
budgetEntry,
this.writes.restWriter(tripId, user, socketId),
);
@@ -824,7 +824,7 @@ export class ReservationsMcp {
type: resolvedType,
// Endpoints the caller did not replace stay the geometry the legs run
// over, so read them back (the row carries them) instead of guessing.
endpoints: resolvedEndpoints ?? ((await this.reservations.getReservationWithJoins(reservationId))?.endpoints ?? []).map(e => ({
endpoints: resolvedEndpoints ?? ((await this.reservations.getReservationWithJoins(reservationId, tripId))?.endpoints ?? []).map(e => ({
role: e.role, sequence: e.sequence, name: e.name, code: e.code,
lat: e.lat, lng: e.lng, timezone: e.timezone,
local_time: e.local_time, local_date: e.local_date,
@@ -4,7 +4,7 @@ import { PluginController, PluginMethod } from '../../nest-rpc/rpc-kit/decorator
import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types';
import { num, schemaMessage } from '../../nest-rpc/rpc-params';
import { RealtimeService } from '../realtime/realtime.service';
import { ReservationsService } from './reservations.service';
import { ReservationsService, withoutOrigin } from './reservations.service';
import {
reservationCreateRequestSchema,
reservationEndpointsInputSchema,
@@ -44,7 +44,7 @@ export class ReservationsRpc {
const budgetEntry = await this.reservations.withFrozenRate(tripId, i.create_budget_entry as never);
const { reservation, accommodationCreated, costEvents } = await this.reservations.createWithCost(
String(tripId),
input as never,
withoutOrigin(input) as never,
budgetEntry,
);
if (accommodationCreated) this.realtime.broadcast(tripId, 'accommodation:created', {}, undefined);
@@ -122,6 +122,38 @@ export interface CreateReservationData {
create_accommodation?: CreateAccommodation;
endpoints?: EndpointInput[];
needs_review?: boolean;
/**
* Where an imported booking came from (`import`, `mail`) and its key there,
* unique per trip. Both or neither; without them the row is a hand-made
* booking, as every write was before imports recorded their origin.
*/
external_source?: string;
external_id?: string;
/** False keeps an imported booking out of any sync back to its source; the column defaults to on. */
sync_enabled?: boolean;
}
/** The origin fields of {@link CreateReservationData}, which only a server-side import may set. */
type ReservationOrigin = Pick<CreateReservationData, 'external_source' | 'external_id' | 'sync_enabled'>;
/**
* A create body from a client without the origin fields. The REST and plugin
* bodies are open objects, and an origin a caller could name would let it pose
* as an AirTrail link or an import, so only the importers set one.
*/
export function withoutOrigin(body: Record<string, unknown>): Record<string, unknown> {
const { external_source: _source, external_id: _id, sync_enabled: _sync, ...rest } = body;
return rest;
}
/** The origin columns an insert names, none for a booking without an origin. */
function originColumns(data: ReservationOrigin): { external_source?: string; external_id?: string; sync_enabled?: number } {
if (!data.external_source || !data.external_id) return {};
return {
external_source: data.external_source,
external_id: data.external_id,
...(data.sync_enabled !== undefined && { sync_enabled: data.sync_enabled ? 1 : 0 }),
};
}
export interface UpdateReservationData {
@@ -305,7 +337,7 @@ export class ReservationsService {
async setTravelers(id: string, tripId: string, userIds: number[]) {
if (!(await this.getReservation(id, tripId))) return null;
await this.setReservationTravelers(id, tripId, userIds);
return { travelers: await this.loadTravelers(id), reservation: await this.getReservationWithJoins(Number(id)) };
return { travelers: await this.loadTravelers(id), reservation: await this.getReservationWithJoins(Number(id), tripId) };
}
// Resolve the day row whose date matches the date portion of an ISO-ish
@@ -437,8 +469,8 @@ export class ReservationsService {
return await this.reservationsRepo.listUpcomingForUser(userId, date, time, limit);
}
async getReservationWithJoins(id: string | number) {
return this.reads.getReservationWithJoins(id);
async getReservationWithJoins(id: string | number, tripId: string | number) {
return this.reads.getReservationWithJoins(id, tripId);
}
/**
@@ -749,6 +781,7 @@ export class ReservationsService {
accommodation_id: resolvedAccommodationId == null ? null : legacyBoundIntegerText(resolvedAccommodationId),
metadata: metadata ? JSON.stringify(metadata) : null,
needs_review: needs_review ? 1 : 0,
...originColumns(data),
});
if (endpoints && endpoints.length > 0) {
@@ -772,7 +805,7 @@ export class ReservationsService {
}
// The row was just inserted, so the re-select can't miss (legacy typed this any).
const reservation = (await this.getReservationWithJoins(insertedId))!;
const reservation = (await this.getReservationWithJoins(insertedId, tripId))!;
return { reservation, accommodationCreated, stayMirror };
}
@@ -1018,7 +1051,7 @@ export class ReservationsService {
// The caller passed the pre-checked `current` row, so the re-select can't
// miss (legacy typed this any).
const reservation = (await this.getReservationWithJoins(id))!;
const reservation = (await this.getReservationWithJoins(id, tripId))!;
return { reservation, accommodationChanged, accommodationCreated: !hadStay && Boolean(resolvedAccId), stayMirror };
}
@@ -117,9 +117,9 @@ export class WalletPassService {
);
if (!allowed) throw new DomainError(429, 'Too many Wallet passes, try again in a minute');
const row = await this.reservations.getReservationWithJoins(reservationId);
// The trip guard checked the trip; the booking must belong to it as well.
if (!row || Number(row.trip_id) !== tripId) throw new DomainError(404, 'Reservation not found');
// The trip guard checked the trip; the read is scoped to it, so a booking of another trip is not found.
const row = await this.reservations.getReservationWithJoins(reservationId, tripId);
if (!row) throw new DomainError(404, 'Reservation not found');
// The trip's title and where the booking is, read by the reservations domain itself.
const context = await this.reservations.passContext(reservationId, tripId);
@@ -563,10 +563,10 @@ describe('ReservationsRepository — Task 2 reads (listForTrip / findWithJoins /
});
it('RR1 findWithJoins — matches the legacy joined statement for one row, place/accommodation columns populated', async () => {
const { hotel, stay, hotelPlace } = await seed();
const { trip, hotel, stay, hotelPlace } = await seed();
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare(`${legacyJoinedSql} WHERE r.id = ?`).get(hotel.id);
const typed = await reservationsRepo.findWithJoins(hotel.id);
const typed = await reservationsRepo.findWithJoins(hotel.id, trip.id);
expect(typed).toEqual(legacy);
expect(typed).toMatchObject({
accommodation_place_id: hotelPlace.id,
@@ -575,6 +575,14 @@ describe('ReservationsRepository — Task 2 reads (listForTrip / findWithJoins /
});
});
it('RR1 findWithJoins — a booking of another trip reads as missing', async () => {
const { trip, hotel } = await seed();
const { user } = createUser(testDb);
const other = createTrip(testDb, user.id);
expect(await reservationsRepo.findWithJoins(hotel.id, other.id)).toBeUndefined();
expect(await reservationsRepo.findWithJoins(hotel.id, String(trip.id))).toMatchObject({ id: hotel.id });
});
it('RS35 findInTrip — matches the legacy statement, scoped by trip', async () => {
const { trip, dinner } = await seed();
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
@@ -1070,3 +1078,53 @@ describe('ReservationsRepository — findPassContext', () => {
expect(await reservationsRepo.findPassContext(dinner.id, other.id)).toBeUndefined();
});
});
describe('ReservationsRepository — the origin of an imported booking', () => {
const baseRow = (tripId: number) => ({
trip_id: tripId,
day_id: null,
end_day_id: null,
place_id: null,
assignment_id: null,
title: 'LH 716',
reservation_time: null,
reservation_end_time: null,
location: null,
confirmation_number: 'ABC123',
notes: null,
url: null,
status: 'pending',
type: 'flight',
accommodation_id: null,
metadata: null,
needs_review: 0,
});
it('RES-ORIGIN-001: a hand-made booking keeps the column defaults, no origin and sync on', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const id = await reservationsRepo.insertReservation(baseRow(trip.id));
// test-sql-allow: reads back the raw columns the insert left to their defaults.
const row = testDb.prepare('SELECT external_source, external_id, sync_enabled FROM reservations WHERE id = ?').get(id);
expect(row).toEqual({ external_source: null, external_id: null, sync_enabled: 1 });
});
it('RES-ORIGIN-002: an imported booking records its origin and is found by it in its own trip only', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const id = await reservationsRepo.insertReservation({
...baseRow(trip.id),
external_source: 'import',
external_id: 'ABC123|flight|2026-09-01|FRA-NRT',
sync_enabled: 0,
});
// test-sql-allow: reads back the raw origin columns the insert named.
const row = testDb.prepare('SELECT external_source, external_id, sync_enabled FROM reservations WHERE id = ?').get(id);
expect(row).toEqual({ external_source: 'import', external_id: 'ABC123|flight|2026-09-01|FRA-NRT', sync_enabled: 0 });
expect(await reservationsRepo.findIdByExternal(trip.id, 'import', 'ABC123|flight|2026-09-01|FRA-NRT')).toBe(id);
expect(await reservationsRepo.findIdByExternal(other.id, 'import', 'ABC123|flight|2026-09-01|FRA-NRT')).toBeUndefined();
expect(await reservationsRepo.findIdByExternal(trip.id, 'mail', 'ABC123|flight|2026-09-01|FRA-NRT')).toBeUndefined();
});
});
@@ -33,7 +33,7 @@ import { HttpException } from '@nestjs/common';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createReservation, createBudgetItem, createPlace, createDay, createDayAccommodation, createDayAssignment, addTripMember } from '../../helpers/factories';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { ReservationsService, type UpdateReservationData } from '../../../src/nest/reservations/reservations.service';
import { ReservationsService, withoutOrigin, type UpdateReservationData } from '../../../src/nest/reservations/reservations.service';
import { ReservationsReadService } from '../../../src/nest/reservations/reservations-read.service';
import type { BudgetService } from '../../../src/nest/budget/budget.service';
// Was reservations.bridge, deleted along with the other three that had no
@@ -46,7 +46,7 @@ const bridge = {
resyncReservationDays: (tripId: string | number) => svc.resyncReservationDays(tripId),
createReservation: (tripId: string | number, data: Parameters<ReservationsService['create']>[1]) => svc.create(tripId, data),
getReservation: (id: string | number, tripId: string | number) => svc.getReservation(id, tripId),
getReservationWithJoins: (id: string | number) => svc.getReservationWithJoins(id),
getReservationWithJoins: (id: string | number, tripId: string | number) => svc.getReservationWithJoins(id, tripId),
updateReservation: (
id: string | number,
tripId: string | number,
@@ -123,6 +123,28 @@ describe('ReservationsService (DI-native, real SQL)', () => {
});
});
it('RESV-SVC-002b: an import records its origin with sync off; a booking without one keeps the defaults', async () => {
const { trip } = ownerTrip();
const { reservation: imported } = await svc.create(String(trip.id), {
title: 'LH 716',
type: 'flight',
external_source: 'import',
external_id: 'ABC123|flight|2030-05-01|FRA-NRT',
sync_enabled: false,
});
expect(imported).toMatchObject({ external_source: 'import', external_id: 'ABC123|flight|2030-05-01|FRA-NRT', sync_enabled: 0 });
// A source without a key is no origin: the row stays a hand-made booking.
const { reservation: plain } = await svc.create(String(trip.id), { title: 'Dinner', external_source: 'import' });
expect(plain).toMatchObject({ external_source: null, external_id: null, sync_enabled: 1 });
});
it('RESV-SVC-002c: withoutOrigin drops the origin a client body names and keeps everything else', () => {
expect(
withoutOrigin({ title: 'Dinner', external_source: 'airtrail', external_id: '7', sync_enabled: true, notes: 'x' }),
).toEqual({ title: 'Dinner', notes: 'x' });
});
it('RESV-SVC-003: derives day_id from reservation_time for non-hotel bookings', async () => {
const { trip } = ownerTrip({ start_date: '2030-05-01', end_date: '2030-05-03' });
const day2 = await findRow(orm, Days, { trip: trip.id, date: '2030-05-02' }) as { id: number };
@@ -387,7 +409,7 @@ describe('ReservationsService (DI-native, real SQL)', () => {
expect(row.day_positions).toEqual({ [days[0].id]: 2 });
expect(row.travelers).toHaveLength(1);
const single = (await svc.getReservationWithJoins(res.id))!;
const single = (await svc.getReservationWithJoins(res.id, trip.id))!;
expect(single.accommodation_id).toBe(acc.id);
expect(single.travelers).toHaveLength(1);
expect(single.day_positions).toEqual({ [days[0].id]: 2 });
@@ -406,11 +428,14 @@ describe('ReservationsService (DI-native, real SQL)', () => {
const current = await svc.getReservation(String(moved.id), String(trip.id));
const { reservation } = await svc.update(String(moved.id), String(trip.id), { notes: 'window seat' }, current as Parameters<ReservationsService['update']>[3]);
expect(reservation.day_positions).toEqual({ [days[1].id]: 3.5 });
expect((await svc.getReservationWithJoins(untouched.id))?.day_positions).toBeNull();
expect((await svc.getReservationWithJoins(untouched.id, trip.id))?.day_positions).toBeNull();
});
it('RESV-SVC-016: getReservationWithJoins returns undefined for a missing id', async () => {
expect(await svc.getReservationWithJoins(999)).toBeUndefined();
it('RESV-SVC-016: getReservationWithJoins returns undefined for a missing id or another trip', async () => {
const { trip } = ownerTrip();
const res = createReservation(testDb, trip.id);
expect(await svc.getReservationWithJoins(999, trip.id)).toBeUndefined();
expect(await svc.getReservationWithJoins(res.id, trip.id + 1)).toBeUndefined();
});
});
@@ -1048,7 +1073,7 @@ describe('ReservationsService — the surface the deleted bridge exposed', () =>
it('RESV-BRIDGE-006: getReservationWithJoins attaches endpoints + travelers', async () => {
const { trip } = ownerTrip();
const res = createReservation(testDb, trip.id);
expect(await bridge.getReservationWithJoins(res.id)).toMatchObject({ id: res.id, endpoints: [], travelers: [] });
expect(await bridge.getReservationWithJoins(res.id, trip.id)).toMatchObject({ id: res.id, endpoints: [], travelers: [] });
});
it('RESV-BRIDGE-007: updateReservation updates through the bridge', async () => {
@@ -74,7 +74,10 @@ afterAll(async () => {
/** The service from the module, with its collaborators set to a hotel booking that may have a pass. */
function make(mode: 'auto' | 'off' = 'auto') {
config.mode = mode;
reservations.getReservationWithJoins.mockReset().mockImplementation(async () => ({ ...ROW }));
// The read is trip-scoped: a booking asked for under another trip is not found.
reservations.getReservationWithJoins
.mockReset()
.mockImplementation(async (_id: number, tripId: number) => (tripId === ROW.trip_id ? { ...ROW } : undefined));
reservations.passContext.mockReset().mockImplementation(async () => ({
trip_title: 'Japan 2027',
place_lat: 34.985,
@@ -221,8 +224,8 @@ describe('WalletPassService', () => {
expect(await refusal(service.googleSaveUrlFor(1, 42, 7, 'en'))).toBe(502);
safeFetchAdminConfigured.mockRejectedValueOnce(new Error('ECONNREFUSED'));
expect(await refusal(service.googleSaveUrlFor(1, 42, 7, 'en'))).toBe(502);
reservations.getReservationWithJoins.mockResolvedValueOnce({ ...ROW, trip_id: 99 });
expect(await refusal(service.googleSaveUrlFor(1, 42, 7, 'en'))).toBe(404);
expect(await refusal(service.googleSaveUrlFor(1, 99, 7, 'en'))).toBe(404);
expect(reservations.getReservationWithJoins).toHaveBeenLastCalledWith(7, 99);
});
it('WALLET-S-010: the Google route sits beside /pass, query kept; any other signer URL has none', async () => {