fix(accommodations): keep booking confirmations in sync

Distinguish omitted references from explicit clears on stays and their
linked bookings. Reserve automatic confirmation for a new reference
with a booking code format. Announce linked changes after booking edits.

Closes #3301
This commit is contained in:
Maurice
2026-12-02 11:49:33 +01:00
parent dacf19b4d5
commit 618f070675
15 changed files with 360 additions and 114 deletions
@@ -121,13 +121,8 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
.execute('run');
}
/** RS30/RS43 — `UPDATE day_accommodations SET confirmation = COALESCE(?, confirmation) WHERE id = ?`. */
async patchConfirmation(id: number, confirmation: string | null): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.qb()
.update({ confirmation: coalesceOverride(platform, confirmation, 'confirmation') })
.where({ id })
.execute('run');
await this.nativeUpdate({ id }, { confirmation });
}
/**
@@ -159,14 +154,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
return row?.check_in;
}
/**
* RS39 — `UPDATE day_accommodations SET place_id = ?, start_day_id = ?,
* end_day_id = ?, check_in = ?, check_out = ?, confirmation = ? WHERE id =
* ?`. Six columns (no `check_in_end`/`notes`, unlike `AccommodationsService
* .moveStay`'s own write) — the caller's already-decided values, written
* verbatim (the `PlacesRepository.updatePlace`/PL11 precedent: no SQL-side
* COALESCE here, the legacy statement itself has none for these columns).
*/
/** An omitted confirmation leaves the stay's existing reference in place. */
async updateFromBooking(
id: number,
write: {
@@ -175,7 +163,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
end_day_id: number;
check_in: string | null;
check_out: string | null;
confirmation: string | null;
confirmation?: string | null;
},
): Promise<void> {
await this.nativeUpdate(
@@ -186,7 +174,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
endDay: write.end_day_id,
check_in: write.check_in,
check_out: write.check_out,
confirmation: write.confirmation,
...(write.confirmation !== undefined ? { confirmation: write.confirmation } : {}),
},
);
}
@@ -343,7 +331,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
check_in: string | null;
check_in_end: string | null;
check_out: string | null;
confirmation: string | null;
confirmation?: string | null;
notes: string | null;
},
): Promise<void> {
@@ -356,7 +344,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
check_in: write.check_in,
check_in_end: write.check_in_end,
check_out: write.check_out,
confirmation: write.confirmation,
...(write.confirmation !== undefined ? { confirmation: write.confirmation } : {}),
notes: write.notes,
},
);
@@ -1,7 +1,7 @@
import type { Reservations } from '../entities/Reservations.entity';
import { DayAssignments } from '../entities/DayAssignments.entity';
import { Days } from '../entities/Days.entity';
import { coalesceOverride, columnRef, dayDistance, isCalendarDate } from '../dialect/sql-functions';
import { columnRef, dayDistance, isCalendarDate } from '../dialect/sql-functions';
import { concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions';
import { accommodationIdMatches, reservationStayIs } from './_shared/reservation-accommodation';
import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility';
@@ -663,24 +663,14 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
// Reservations repositories where a read belongs there").
// ---------------------------------------------------------------------------
/**
* AC33 (`AccommodationsService.createAccommodation`) — `INSERT INTO
* reservations (trip_id, day_id, title, reservation_time, location,
* confirmation_number, notes, status, type, accommodation_id, metadata)
* VALUES (?, ?, ?, ?, ?, ?, ?, 'confirmed', 'hotel', ?, ?)` — the
* auto-created partner hotel booking. `status`/`type` literals, `location`
* always `null` (matching the legacy statement exactly — it never binds a
* value there). `accommodation_id: string` — R2: the caller stringifies
* the new stay's numeric id (`String(newId)`) the same way `insertReservation`'s
* own `accommodation_id` caller already does, so SQLite's TEXT-affinity
* storage is identical to the legacy raw bind of the bare number.
*/
/** The partner hotel booking created with a stay. The caller decides its initial status. */
async insertHotelPartner(input: {
trip_id: number | string;
day_id: number;
title: string;
reservation_time: string | null;
confirmation_number: string | null;
status: 'pending' | 'confirmed';
notes: string | null;
accommodation_id: string;
metadata: string | null;
@@ -693,8 +683,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
location: null,
confirmation_number: input.confirmation_number,
notes: input.notes,
// A stay without a confirmation number is not a confirmed booking yet.
status: input.confirmation_number ? 'confirmed' : 'pending',
status: input.status,
type: 'hotel',
accommodation_id: input.accommodation_id,
metadata: input.metadata,
@@ -719,24 +708,23 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
return rows as { id: number; metadata: string | null }[];
}
/**
* AC38 (`AccommodationsService.updateAccommodation`) — `UPDATE
* reservations SET metadata = ?, confirmation_number = COALESCE(?,
* confirmation_number) WHERE id = ?`. Runs AFTER `updateAccommodation`'s
* own transaction commits (§18.6 — R5 class, flagged not fixed).
* `coalesceOverride` for the value-side COALESCE — the bound `?` FIRST,
* the column the fallback, so the new value wins
* (`DayAccommodationsRepository.patchConfirmation`'s precedent).
*/
async setMetadataAndConfirmation(id: number, metadata: string, confirmation: string | null): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.qb()
.update({
/** Clearing a reference reopens a confirmed booking that actually held a reference. */
async setMetadataAndConfirmation(id: number, metadata: string, confirmation?: string | null): Promise<void> {
await this.kysely<Pick<DB, 'reservations'>>()
.updateTable('reservations')
.set((eb) => ({
metadata,
confirmation_number: coalesceOverride(platform, confirmation, 'confirmation_number'),
})
.where({ id })
.execute('run');
confirmation_number: confirmation,
status: confirmation === null
? eb.case()
.when(eb.and([eb('status', '=', 'confirmed'), eb('confirmation_number', '!=', '')]))
.then('pending')
.else(eb.ref('status'))
.end()
: undefined,
}))
.where('id', '=', id)
.execute();
}
/** A pending hotel booking turns confirmed once its stay gets a confirmation number; other statuses stay. */
@@ -258,7 +258,7 @@ export class AccommodationsMcp {
check_in: z.string().max(10).optional(),
check_in_end: z.string().max(10).optional().describe('Check-in window end time e.g. "20:00"'),
check_out: z.string().max(10).optional(),
confirmation: z.string().max(100).optional(),
confirmation: z.string().max(100).nullable().optional().describe('Booking reference, or null to clear it'),
notes: z.string().max(1000).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
@@ -285,7 +285,7 @@ export class AccommodationsMcp {
check_in?: string;
check_in_end?: string;
check_out?: string;
confirmation?: string;
confirmation?: string | null;
notes?: string;
},
ctx: McpContext,
@@ -89,7 +89,7 @@ export class AccommodationsRpc {
check_in?: string;
check_in_end?: string;
check_out?: string;
confirmation?: string;
confirmation?: string | null;
notes?: string;
};
// The input is open: a ref is read like a plugin RPC id, so '0x1' or 1.5 is BAD_PARAMS, not bound.
@@ -112,6 +112,13 @@ const stayNotFound = () => new DomainError(404, 'Accommodation not found', { mcp
const STAY_REFS = ['place_id', 'start_day_id', 'end_day_id'] as const;
function looksLikeBookingReference(confirmation: string | null | undefined): boolean {
if (!confirmation) return false;
const compact = confirmation.toLowerCase().replace(/[./_ -]/g, '');
if (compact === 'tbd' || compact === 'na' || compact === 'notbookedyet') return false;
return /^[\p{L}\p{N}]+(?:[./_-][\p{L}\p{N}]+)*$/u.test(confirmation) || /^\p{N}+(?: +\p{N}+)+$/u.test(confirmation);
}
/**
* The place and day refs of a stay write, each read with toRowId; an absent one
* stays absent. A value it refuses ('0x1', '1e0', 1.5) is a 400 in the words the
@@ -137,7 +144,7 @@ export interface CreateAccommodationData {
check_in?: string;
check_in_end?: string;
check_out?: string;
confirmation?: string;
confirmation?: string | null;
notes?: string;
}
@@ -778,6 +785,7 @@ export class AccommodationsService {
async createAccommodation(tripId: string | number, data: CreateAccommodationData) {
const { place_id, start_day_id, end_day_id, check_in, check_in_end, check_out, confirmation, notes } = data;
const reference = confirmation?.trim() || null;
// The stay, its partner hotel reservation and the day stop it implies are one
// logical write, and an atomic one, so a failed insert halfway can't leave an orphan.
@@ -791,7 +799,7 @@ export class AccommodationsService {
check_in: check_in || null,
check_in_end: check_in_end || null,
check_out: check_out || null,
confirmation: confirmation || null,
confirmation: reference,
notes: notes || null,
});
@@ -810,7 +818,8 @@ export class AccommodationsService {
day_id: start_day_id,
title: placeName,
reservation_time: startDayDate || null,
confirmation_number: confirmation || null,
confirmation_number: reference,
status: looksLikeBookingReference(reference) ? 'confirmed' : 'pending',
notes: notes || null,
accommodation_id: legacyBoundIntegerText(newId),
metadata: Object.keys(meta).length > 0 ? encodeJson(RESERVATION_METADATA, meta) : null,
@@ -832,16 +841,6 @@ export class AccommodationsService {
return await this.dayAccommodationsRepo.findInTrip(idNum, tripIdNum);
}
/**
* Writes a stay's times and confirmation number onto one linked booking. A number
* also confirms the booking when it was still pending, and that has to come after
* the write, so both steps stay together here for each booking.
*/
private async syncLinkedReservation(id: number, metadata: string, confirmation: string | null): Promise<void> {
await this.reservationsRepo.setMetadataAndConfirmation(id, metadata, confirmation);
if (confirmation) await this.reservationsRepo.confirmIfPending(id);
}
async updateAccommodation(
id: string | number,
existing: DayAccommodation,
@@ -852,7 +851,7 @@ export class AccommodationsService {
check_in?: string;
check_in_end?: string;
check_out?: string;
confirmation?: string;
confirmation?: string | null;
notes?: string;
},
) {
@@ -862,7 +861,9 @@ export class AccommodationsService {
const newCheckIn = fields.check_in !== undefined ? fields.check_in : existing.check_in;
const newCheckInEnd = fields.check_in_end !== undefined ? fields.check_in_end : existing.check_in_end;
const newCheckOut = fields.check_out !== undefined ? fields.check_out : existing.check_out;
const newConfirmation = fields.confirmation !== undefined ? fields.confirmation : existing.confirmation;
const confirmation = fields.confirmation === undefined ? undefined : fields.confirmation?.trim() || null;
// Saving a stay form can resend its current reference. Mirror it without overriding the chosen status.
const shouldConfirm = looksLikeBookingReference(confirmation) && confirmation !== existing.confirmation?.trim();
const newNotes = fields.notes !== undefined ? fields.notes : existing.notes;
// The stay row, the day stop that mirrors it and the linked bookings' times all
@@ -879,7 +880,7 @@ export class AccommodationsService {
check_in: newCheckIn,
check_in_end: newCheckInEnd,
check_out: newCheckOut,
confirmation: newConfirmation,
confirmation,
notes: newNotes,
});
const moved = await this.remirrorStay(existing.id, newPlaceId, newStartDayId, newCheckIn, {
@@ -896,7 +897,12 @@ export class AccommodationsService {
if (newCheckIn) meta.check_in_time = newCheckIn;
if (newCheckInEnd) meta.check_in_end_time = newCheckInEnd;
if (newCheckOut) meta.check_out_time = newCheckOut;
await this.syncLinkedReservation(res.id, encodeJson(RESERVATION_METADATA, meta), newConfirmation || null);
await this.reservationsRepo.setMetadataAndConfirmation(
res.id,
encodeJson(RESERVATION_METADATA, meta),
confirmation,
);
if (shouldConfirm) await this.reservationsRepo.confirmIfPending(res.id);
}
return moved;
});
@@ -29,7 +29,7 @@ export interface CreateAccommodation {
end_day_id?: number;
check_in?: string;
check_out?: string;
confirmation?: string;
confirmation?: string | null;
}
export interface CreateReservationData extends ReservationOrigin {
@@ -58,7 +58,7 @@ export interface UpdateReservationData {
reservation_time?: string;
reservation_end_time?: string;
location?: string;
confirmation_number?: string;
confirmation_number?: string | null;
notes?: string;
url?: string;
day_id?: number | null;
@@ -438,7 +438,7 @@ export class ReservationsMcp {
reservation_end_time: z.string().optional().describe('When it ends. Ignored for hotels, whose span is the check-in/check-out days.'),
url: urlField,
location: z.string().max(500).optional(),
confirmation_number: z.string().max(100).optional(),
confirmation_number: z.string().max(100).nullable().optional().describe('Booking reference, or null to clear it'),
notes: z.string().max(1000).optional(),
status: z.enum(RESERVATION_STATUSES).optional().describe('Reservation status: "pending", "confirmed", or "cancelled"'),
place_id: idSchema.nullable().optional().describe('Link to a place (use for hotel type), or null to unlink'),
@@ -451,7 +451,7 @@ export class ReservationsMcp {
{ tripId, reservationId, title, type, reservation_time, reservation_end_time, url, location, confirmation_number, notes, status, place_id, assignment_id }: {
tripId: number; reservationId: number; title?: string;
type?: BookingType;
reservation_time?: string; reservation_end_time?: string; url?: string; location?: string; confirmation_number?: string; notes?: string;
reservation_time?: string; reservation_end_time?: string; url?: string; location?: string; confirmation_number?: string | null; notes?: string;
status?: ReservationStatus; place_id?: number | null; assignment_id?: number | null;
},
ctx: McpContext,
@@ -824,10 +824,14 @@ export class ReservationsService {
if (!accExists) resolvedAccId = null;
}
const hadStay = Boolean(resolvedAccId);
const referenceOrNull = (value: string | null | undefined) =>
typeof value === 'string' && !value.trim() ? null : value;
let bookingConfirmation = referenceOrNull(confirmation_number);
if (type === 'hotel' && create_accommodation) {
const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = create_accommodation;
if (start_day_id && end_day_id) {
await this.requireResolvableStay(create_accommodation);
const stayConfirmation = bookingConfirmation === undefined ? referenceOrNull(accConf) : bookingConfirmation;
if (resolvedAccId) {
const resolvedAccIdNum = accIdForRead(resolvedAccId)!;
const priorCheckIn = await this.dayAccommodationsRepo.getCheckIn(resolvedAccIdNum);
@@ -837,11 +841,9 @@ export class ReservationsService {
end_day_id,
check_in: check_in || null,
check_out: check_out || null,
confirmation: accConf || confirmation_number || null,
confirmation: stayConfirmation,
});
// The stay just moved. Its stop moves with it, or it is left sitting on a
// day nobody sleeps there any more, hidden from the day list because it
// still carries this booking's id and stranded in the middle of the drive.
// Carry the booking's day stop to the stay's new dates and place.
stayMirror = await this.accommodations.moveStayStop(resolvedAccIdNum, accPlaceId || null, start_day_id, check_in, {
checkInChanged: (check_in || null) !== (priorCheckIn ?? null),
});
@@ -853,10 +855,11 @@ export class ReservationsService {
end_day_id,
check_in: check_in || null,
check_out: check_out || null,
confirmation: accConf || confirmation_number || null,
confirmation: stayConfirmation === undefined ? current.confirmation_number ?? null : stayConfirmation,
});
stayMirror = await this.accommodations.attachStayStop(resolvedAccId, accPlaceId, start_day_id, check_in);
}
if (resolvedAccId) bookingConfirmation = stayConfirmation;
accommodationChanged = true;
}
}
@@ -900,21 +903,14 @@ export class ReservationsService {
const nextPlaceId = await this.resolvedOrNull('places', place_id !== undefined ? (place_id || null) : (current.place_id ?? null));
const nextAssignmentId = await this.resolvedOrNull('day_assignments', assignment_id !== undefined ? (assignment_id || null) : (current.assignment_id ?? null));
// RS41. The `PlacesRepository.updatePlace`/PL11 precedent: the four
// legacy `COALESCE(?, col)` keep-if-null columns (`title`/`status`/
// `type`/`needs_review`) are resolved to their FINAL value here, in JS,
// against the `current` pre-image this method already holds — nothing
// else in this same transaction touches those four columns between the
// read and this write, so `current`'s snapshot is exactly what the
// legacy statement's own SQL-side `COALESCE` against the live row would
// have read.
// Resolve the update against the current row before writing.
const idNum = this.rowIdNum(id);
await this.reservationsRepo.updateReservation(idNum, {
title: title || current.title,
reservation_time: nextReservationTime,
reservation_end_time: nextReservationEndTime,
location: location !== undefined ? (location || null) : (current.location ?? null),
confirmation_number: confirmation_number !== undefined ? (confirmation_number || null) : (current.confirmation_number ?? null),
confirmation_number: bookingConfirmation !== undefined ? (bookingConfirmation || null) : (current.confirmation_number ?? null),
notes: notes !== undefined ? (notes || null) : (current.notes ?? null),
url: url !== undefined ? (url || null) : ((current as Reservation & { url?: string | null }).url ?? null),
day_id: nextDayId,
@@ -932,19 +928,19 @@ export class ReservationsService {
await this.saveEndpoints(idNum, endpoints);
}
// Sync check-in/out to accommodation if linked
// Sync times and explicit confirmation edits to the linked stay.
const resolvedMeta = nextMetadata !== undefined ? nextMetadata : (current.metadata ? decodeJson(RESERVATION_METADATA, current.metadata, `reservation ${idNum}`) : null);
if (resolvedAccId && resolvedMeta) {
const meta = decodeJson(RESERVATION_METADATA, resolvedMeta) as AccommodationTimesMeta;
if (resolvedAccId) {
const meta = resolvedMeta ? decodeJson(RESERVATION_METADATA, resolvedMeta) as AccommodationTimesMeta : null;
const resolvedAccIdNum = accIdForRead(resolvedAccId)!;
if (meta.check_in_time || meta.check_in_end_time || meta.check_out_time) {
if (meta?.check_in_time || meta?.check_in_end_time || meta?.check_out_time) {
await this.dayAccommodationsRepo.patchTimes(
resolvedAccIdNum, meta.check_in_time || null, meta.check_in_end_time || null, meta.check_out_time || null,
);
}
const resolvedConf = confirmation_number !== undefined ? confirmation_number : current.confirmation_number;
if (resolvedConf) {
await this.dayAccommodationsRepo.patchConfirmation(resolvedAccIdNum, resolvedConf);
if (!accommodationChanged && bookingConfirmation !== undefined) {
await this.dayAccommodationsRepo.patchConfirmation(resolvedAccIdNum, bookingConfirmation);
accommodationChanged = true;
}
}