mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
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:
@@ -9,7 +9,7 @@
|
||||
"src/db/repositories/CollabPollVotes.repository.ts": 1,
|
||||
"src/db/repositories/DawarichConnections.repository.ts": 4,
|
||||
"src/db/repositories/DawarichVisitSuggestions.repository.ts": 4,
|
||||
"src/db/repositories/DayAccommodations.repository.ts": 12,
|
||||
"src/db/repositories/DayAccommodations.repository.ts": 11,
|
||||
"src/db/repositories/DayAssignments.repository.ts": 20,
|
||||
"src/db/repositories/DayNotes.repository.ts": 6,
|
||||
"src/db/repositories/Days.repository.ts": 7,
|
||||
@@ -28,7 +28,7 @@
|
||||
"src/db/repositories/PushSubscriptions.repository.ts": 1,
|
||||
"src/db/repositories/ReservationDayPositions.repository.ts": 1,
|
||||
"src/db/repositories/ReservationEndpoints.repository.ts": 5,
|
||||
"src/db/repositories/Reservations.repository.ts": 14,
|
||||
"src/db/repositories/Reservations.repository.ts": 13,
|
||||
"src/db/repositories/ReservationTravelers.repository.ts": 2,
|
||||
"src/db/repositories/RoadtripDayBoundaries.repository.ts": 3,
|
||||
"src/db/repositories/RoadtripDayTracks.repository.ts": 1,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"scripts/db-call-graph.mjs": 1036,
|
||||
"scripts/generate-entities.ts": 2259,
|
||||
"src/db/repositories/Places.repository.ts": 1432,
|
||||
"src/db/repositories/Reservations.repository.ts": 1550,
|
||||
"src/db/repositories/Reservations.repository.ts": 1538,
|
||||
"src/db/repositories/Trips.repository.ts": 1120,
|
||||
"src/db/repositories/Users.repository.ts": 1403,
|
||||
"src/nest/atlas/atlas.service.ts": 1166,
|
||||
@@ -15,6 +15,6 @@
|
||||
"src/nest/places/places.service.ts": 1517,
|
||||
"src/nest/plugins/plugin-runtime.service.ts": 1458,
|
||||
"src/nest/plugins/runtime/plugin-sdk.ts": 1093,
|
||||
"src/nest/reservations/reservations.service.ts": 1163,
|
||||
"src/nest/reservations/reservations.service.ts": 1159,
|
||||
"src/nest/vacay/vacay.service.ts": 1393
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { Reservations } from '../../src/db/entities/Reservations.entity';
|
||||
import { AccommodationsService } from '../../src/nest/accommodations/accommodations.service';
|
||||
import { legacyBoundIntegerText } from '../../src/nest/common/row-id';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { ReservationsService } from '../../src/nest/reservations/reservations.service';
|
||||
import { makePlace } from '../helpers/factories/places';
|
||||
import { makeReservation } from '../helpers/factories/reservations';
|
||||
import { findRow, findRows, updateRows } from '../helpers/factories/rows';
|
||||
import { makeDay, makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
let app: INestApplication;
|
||||
let orm: MikroORM;
|
||||
let svc: AccommodationsService;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
orm = app.get(MikroORM);
|
||||
svc = app.get(AccommodationsService);
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
});
|
||||
|
||||
function linkedReservation(accommodationId: number) {
|
||||
return findRow(orm, Reservations, { accommodation_id: legacyBoundIntegerText(accommodationId) });
|
||||
}
|
||||
|
||||
function editStay(id: number, tripId: number, fields: Parameters<AccommodationsService['updateAccommodation']>[2]) {
|
||||
return withRequestContext(orm, async () => {
|
||||
const existing = await svc.getAccommodation(id, tripId);
|
||||
if (!existing) throw new Error('Stay was not found');
|
||||
return svc.updateAccommodation(id, existing, fields);
|
||||
});
|
||||
}
|
||||
|
||||
describe('Accommodation confirmation references', () => {
|
||||
async function stayForConfirmation(confirmation?: string) {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
const day = await makeDay(orm, trip.id);
|
||||
const place = await makePlace(orm, trip.id);
|
||||
const { accommodation } = await withRequestContext(orm, () =>
|
||||
svc.createAccommodation(trip.id, {
|
||||
place_id: place.id,
|
||||
start_day_id: day.id,
|
||||
end_day_id: day.id,
|
||||
confirmation,
|
||||
}),
|
||||
);
|
||||
if (!accommodation) throw new Error('Stay was not created');
|
||||
return { accommodation, trip, day, place };
|
||||
}
|
||||
|
||||
it.each(['Waiting for the hotel', 'tBd', 'N/a', 'NOT-BOOKED-YET'])(
|
||||
'ACC-3301: creates a pending booking with placeholder %s',
|
||||
async (confirmation) => {
|
||||
const { accommodation } = await stayForConfirmation(confirmation);
|
||||
|
||||
expect(accommodation.confirmation).toBe(confirmation);
|
||||
expect(await linkedReservation(accommodation.id)).toMatchObject({
|
||||
confirmation_number: confirmation,
|
||||
status: 'pending',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['NOT BOOKED YET: pick a hotel', 'ABC-12345'],
|
||||
['not_booked_yet', '1234 567 890'],
|
||||
['T.B.D', 'XYZ'],
|
||||
])('ACC-3301: confirms a booking after placeholder %s is replaced with %s', async (confirmation, reference) => {
|
||||
const { accommodation, trip } = await stayForConfirmation();
|
||||
const { accommodation: updated } = await editStay(accommodation.id, trip.id, { confirmation });
|
||||
|
||||
expect(updated?.confirmation).toBe(confirmation);
|
||||
expect(await linkedReservation(accommodation.id)).toMatchObject({
|
||||
confirmation_number: confirmation,
|
||||
status: 'pending',
|
||||
});
|
||||
await editStay(accommodation.id, trip.id, { confirmation: ` ${reference} ` });
|
||||
expect(await linkedReservation(accommodation.id)).toMatchObject({
|
||||
confirmation_number: reference,
|
||||
status: 'confirmed',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([null, '', ' \t '])(
|
||||
'ACC-3301: clearing with %j clears each booking reference and reopens its confirmation',
|
||||
async (confirmation) => {
|
||||
const { accommodation, trip } = await stayForConfirmation('ABC123');
|
||||
const accommodation_id = legacyBoundIntegerText(accommodation.id);
|
||||
await makeReservation(orm, trip.id, {
|
||||
accommodation_id,
|
||||
type: 'hotel',
|
||||
status: 'cancelled',
|
||||
confirmation_number: 'ABC123',
|
||||
});
|
||||
await makeReservation(orm, trip.id, { accommodation_id, type: 'hotel', status: 'confirmed' });
|
||||
const { accommodation: updated } = await editStay(accommodation.id, trip.id, { confirmation });
|
||||
|
||||
expect(updated?.confirmation).toBeNull();
|
||||
expect(await findRows(orm, Reservations, { accommodation_id }, { id: 'asc' })).toMatchObject([
|
||||
{ confirmation_number: null, status: 'pending' },
|
||||
{ confirmation_number: null, status: 'cancelled' },
|
||||
{ confirmation_number: null, status: 'confirmed' },
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it('ACC-3301: omitting the code preserves the linked booking reference and its chosen status', async () => {
|
||||
const { accommodation, trip } = await stayForConfirmation('STAY-1');
|
||||
await updateRows(
|
||||
orm,
|
||||
Reservations,
|
||||
{ accommodation_id: legacyBoundIntegerText(accommodation.id) },
|
||||
{
|
||||
confirmation_number: 'BOOKING-1',
|
||||
status: 'pending',
|
||||
},
|
||||
);
|
||||
const { accommodation: updated } = await editStay(accommodation.id, trip.id, {
|
||||
notes: 'Late arrival',
|
||||
});
|
||||
|
||||
expect(updated?.confirmation).toBe('STAY-1');
|
||||
expect(await linkedReservation(accommodation.id)).toMatchObject({
|
||||
confirmation_number: 'BOOKING-1',
|
||||
status: 'pending',
|
||||
});
|
||||
});
|
||||
|
||||
it('ACC-3301: resubmitting the same stay reference reconciles the booking while preserving its pending status', async () => {
|
||||
const { accommodation, trip } = await stayForConfirmation('STAY-1');
|
||||
await updateRows(
|
||||
orm,
|
||||
Reservations,
|
||||
{ accommodation_id: legacyBoundIntegerText(accommodation.id) },
|
||||
{
|
||||
confirmation_number: 'BOOKING-1',
|
||||
status: 'pending',
|
||||
},
|
||||
);
|
||||
await editStay(accommodation.id, trip.id, { confirmation: 'STAY-1', notes: 'Late arrival' });
|
||||
|
||||
expect(await linkedReservation(accommodation.id)).toMatchObject({
|
||||
confirmation_number: 'STAY-1',
|
||||
status: 'pending',
|
||||
});
|
||||
});
|
||||
|
||||
it('ACC-3301: explicitly clearing an empty stay clears a stale booking reference', async () => {
|
||||
const { accommodation, trip } = await stayForConfirmation();
|
||||
await updateRows(
|
||||
orm,
|
||||
Reservations,
|
||||
{ accommodation_id: legacyBoundIntegerText(accommodation.id) },
|
||||
{
|
||||
confirmation_number: 'STALE',
|
||||
status: 'confirmed',
|
||||
},
|
||||
);
|
||||
await editStay(accommodation.id, trip.id, { confirmation: null });
|
||||
|
||||
expect(await linkedReservation(accommodation.id)).toMatchObject({ confirmation_number: null, status: 'pending' });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ nested: null, expected: null },
|
||||
{ nested: ' \t ', expected: null },
|
||||
{ nested: 'NEW-REF', expected: 'NEW-REF' },
|
||||
{ top: null, nested: 'OLD-REF', expected: null },
|
||||
{ top: 'TOP-REF', nested: null, expected: 'TOP-REF' },
|
||||
])(
|
||||
'ACC-3301: syncs the selected reference across a complete booking update (%j)',
|
||||
async ({ top, nested, expected }) => {
|
||||
const { accommodation, trip, day, place } = await stayForConfirmation('OLD-REF');
|
||||
const booking = await linkedReservation(accommodation.id);
|
||||
if (!booking) throw new Error('Booking was not found');
|
||||
const bookings = app.get(ReservationsService);
|
||||
|
||||
await withRequestContext(orm, async () => {
|
||||
const current = await bookings.getReservation(booking.id, trip.id);
|
||||
if (!current) throw new Error('Booking was not found');
|
||||
const { reservation, accommodationChanged } = await bookings.update(
|
||||
booking.id,
|
||||
trip.id,
|
||||
{
|
||||
type: 'hotel',
|
||||
status: 'confirmed',
|
||||
confirmation_number: top,
|
||||
create_accommodation: {
|
||||
place_id: place.id,
|
||||
start_day_id: day.id,
|
||||
end_day_id: day.id,
|
||||
confirmation: nested,
|
||||
},
|
||||
},
|
||||
current,
|
||||
);
|
||||
expect(accommodationChanged).toBe(true);
|
||||
expect(reservation).toMatchObject({ confirmation_number: expected, status: 'confirmed' });
|
||||
expect(await svc.getAccommodation(accommodation.id, trip.id)).toMatchObject({ confirmation: expected });
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -294,11 +294,11 @@ export const bookings: CaseGroup = {
|
||||
{
|
||||
tool: 'update_accommodation',
|
||||
needs: ['stay'],
|
||||
args: (s) => ({ tripId: s.trip.id, accommodationId: s.stay.id, notes: 'Late arrival' }),
|
||||
args: (s) => ({ tripId: s.trip.id, accommodationId: s.stay.id, confirmation: null }),
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => `/api/trips/${s.trip.id}/accommodations/${s.stay.id}`,
|
||||
body: () => ({ notes: 'Late arrival' }),
|
||||
body: () => ({ confirmation: null }),
|
||||
},
|
||||
expect: ['accommodation:updated'],
|
||||
},
|
||||
@@ -352,14 +352,19 @@ export const bookings: CaseGroup = {
|
||||
{
|
||||
tool: 'update_reservation',
|
||||
needs: ['stay', 'member'],
|
||||
args: (s) => ({ tripId: s.trip.id, reservationId: s.stay.reservationId, status: 'confirmed' }),
|
||||
args: (s) => ({
|
||||
tripId: s.trip.id,
|
||||
reservationId: s.stay.reservationId,
|
||||
status: 'confirmed',
|
||||
confirmation_number: null,
|
||||
}),
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => `/api/trips/${s.trip.id}/reservations/${s.stay.reservationId}`,
|
||||
body: () => ({ status: 'confirmed' }),
|
||||
body: () => ({ status: 'confirmed', confirmation_number: null }),
|
||||
},
|
||||
settle: true,
|
||||
expect: ['reservation:updated', BOOKING_NOTICE],
|
||||
expect: ['accommodation:updated', 'reservation:updated', BOOKING_NOTICE],
|
||||
},
|
||||
{
|
||||
// A hotel booking takes its stay (and the stay's stop) and its linked cost along.
|
||||
|
||||
@@ -1174,6 +1174,7 @@ describe('ReservationsService — legacy branch parity (coverage of the folded c
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[];
|
||||
const res = createReservation(testDb, trip.id, { title: 'Hotel', type: 'hotel' });
|
||||
await updateRows(orm, Reservations, { id: res.id }, { confirmation_number: 'BOOKING-1' });
|
||||
const current = (await svc.getReservation(String(res.id), String(trip.id)))!;
|
||||
const { reservation, accommodationChanged } = await svc.update(String(res.id), String(trip.id), {
|
||||
type: 'hotel',
|
||||
@@ -1181,7 +1182,7 @@ describe('ReservationsService — legacy branch parity (coverage of the folded c
|
||||
}, current);
|
||||
expect(accommodationChanged).toBe(true);
|
||||
expect(reservation.accommodation_id).not.toBeNull();
|
||||
expect(({ c: await countRows(orm, DayAccommodations, { trip: trip.id }) })).toEqual({ c: 1 });
|
||||
expect(await findRows(orm, DayAccommodations, { trip: trip.id })).toMatchObject([{ confirmation: 'BOOKING-1' }]);
|
||||
});
|
||||
|
||||
it('RESV-SVC-023: explicit update fields bind their values; empty strings null; absent fields keep current', async () => {
|
||||
@@ -1220,17 +1221,17 @@ describe('ReservationsService — legacy branch parity (coverage of the folded c
|
||||
expect(reservation.end_day_id).toBe(days[1].id);
|
||||
});
|
||||
|
||||
it('RESV-SVC-025: with metadata absent, the stored metadata JSON drives the accommodation sync (confirmation falls back to current)', async () => {
|
||||
it('RESV-SVC-025: stored metadata drives the accommodation time sync while ACC-3301 preserves an omitted reference', async () => {
|
||||
const { trip } = ownerTrip({ start_date: '2030-05-01', end_date: '2030-05-02' });
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[];
|
||||
const acc = createDayAccommodation(testDb, trip.id, place.id, days[0].id, days[1].id);
|
||||
const acc = createDayAccommodation(testDb, trip.id, place.id, days[0].id, days[1].id, { confirmation: 'STAY-REF' });
|
||||
const res = createReservation(testDb, trip.id, { title: 'Hotel', type: 'hotel' });
|
||||
await updateRows(orm, Reservations, { id: res.id }, { accommodation_id: String(acc.id), metadata: JSON.stringify({ check_in_time: '16:00' }), confirmation_number: 'KEEP' });
|
||||
const current = (await svc.getReservation(String(res.id), String(trip.id)))!;
|
||||
await svc.update(String(res.id), String(trip.id), { notes: 'touch' }, current);
|
||||
const row = await findRow(orm, DayAccommodations, { id: acc.id });
|
||||
expect(row).toMatchObject({ check_in: '16:00', confirmation: 'KEEP' });
|
||||
expect(row).toMatchObject({ check_in: '16:00', confirmation: 'STAY-REF' });
|
||||
});
|
||||
|
||||
it('H1 (Plan 3h Task 7 review) — patchTimes: updating a linked reservation OVERRIDES the stay\'s existing non-null check-in/end/out — the new value wins, matching legacy COALESCE(?, col)', async () => {
|
||||
@@ -1254,22 +1255,56 @@ describe('ReservationsService — legacy branch parity (coverage of the folded c
|
||||
expect(row).toMatchObject({ check_in: '16:30', check_in_end: '11:15', check_out: '09:00' });
|
||||
});
|
||||
|
||||
it('H1 (Plan 3h Task 7 review) — patchConfirmation: updating a linked reservation OVERRIDES the stay\'s existing non-null confirmation — the new value wins, matching legacy COALESCE(?, confirmation)', async () => {
|
||||
it('H1: explicitly updating a booking reference replaces the stay reference', async () => {
|
||||
const { trip } = ownerTrip({ start_date: '2030-05-01', end_date: '2030-05-02' });
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[];
|
||||
// The stay already holds a DIFFERENT, non-null confirmation — if
|
||||
// `coalesceParam`'s (existing-wins) direction were used instead of
|
||||
// `coalesceOverride`'s (new-wins), the stay would keep it.
|
||||
const acc = createDayAccommodation(testDb, trip.id, place.id, days[0].id, days[1].id, { confirmation: 'ACC-OLD' });
|
||||
const res = createReservation(testDb, trip.id, { title: 'Hotel', type: 'hotel' });
|
||||
await updateRows(orm, Reservations, { id: res.id }, { accommodation_id: String(acc.id), metadata: JSON.stringify({}), confirmation_number: 'RES-NEW' });
|
||||
const current = (await svc.getReservation(String(res.id), String(trip.id)))!;
|
||||
await svc.update(String(res.id), String(trip.id), { notes: 'touch' }, current);
|
||||
await svc.update(String(res.id), String(trip.id), { confirmation_number: 'RES-NEW' }, current);
|
||||
const row = await findRow(orm, DayAccommodations, { id: acc.id });
|
||||
expect(row).toMatchObject({ confirmation: 'RES-NEW' });
|
||||
});
|
||||
|
||||
it('ACC-3301: clearing the booking reference clears the stay without overriding the chosen status', async () => {
|
||||
const { trip } = ownerTrip({ start_date: '2030-05-01', end_date: '2030-05-02' });
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[];
|
||||
const acc = createDayAccommodation(testDb, trip.id, place.id, days[0].id, days[1].id, { confirmation: 'ABC123' });
|
||||
const res = createReservation(testDb, trip.id, { title: 'Hotel', type: 'hotel' });
|
||||
await updateRows(orm, Reservations, { id: res.id }, { accommodation_id: String(acc.id), confirmation_number: 'ABC123' });
|
||||
const current = (await svc.getReservation(String(res.id), String(trip.id)))!;
|
||||
|
||||
const { reservation, accommodationChanged } = await svc.update(String(res.id), String(trip.id), {
|
||||
confirmation_number: null, status: 'confirmed',
|
||||
}, current);
|
||||
|
||||
expect(reservation).toMatchObject({ confirmation_number: null, status: 'confirmed' });
|
||||
expect(accommodationChanged).toBe(true);
|
||||
expect(await findRow(orm, DayAccommodations, { id: acc.id })).toMatchObject({ confirmation: null });
|
||||
});
|
||||
|
||||
it('ACC-3301: a booking edit with stay details and no reference preserves the existing stay reference', async () => {
|
||||
const { trip } = ownerTrip({ start_date: '2030-05-01', end_date: '2030-05-02' });
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[];
|
||||
const acc = createDayAccommodation(testDb, trip.id, place.id, days[0].id, days[1].id, { confirmation: 'ABC123' });
|
||||
const res = createReservation(testDb, trip.id, { title: 'Hotel', type: 'hotel' });
|
||||
await updateRows(orm, Reservations, { id: res.id }, { accommodation_id: String(acc.id) });
|
||||
const current = (await svc.getReservation(String(res.id), String(trip.id)))!;
|
||||
|
||||
await svc.update(String(res.id), String(trip.id), {
|
||||
type: 'hotel',
|
||||
create_accommodation: { place_id: place.id, start_day_id: days[0].id, end_day_id: days[1].id, check_in: '14:00' },
|
||||
}, current);
|
||||
|
||||
expect(await findRow(orm, DayAccommodations, { id: acc.id })).toMatchObject({
|
||||
confirmation: 'ABC123', check_in: '14:00',
|
||||
});
|
||||
});
|
||||
|
||||
it('RESV-SVC-026: resync derives the end day too, keeping the stored one when the end time is out of range', async () => {
|
||||
const { trip } = ownerTrip({ start_date: '2030-05-01', end_date: '2030-05-03' });
|
||||
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[];
|
||||
|
||||
@@ -551,6 +551,21 @@ describe('AccommodationsRpc', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('ACC-3301: a plugin can explicitly clear the stay reference with null', async () => {
|
||||
const f = build();
|
||||
const res = await f
|
||||
.host()
|
||||
.dispatch(req('accommodations.update', { tripId: 1, accommodationId: 11, input: { confirmation: null } }), 42);
|
||||
|
||||
expect(res).toMatchObject({ k: 'res', result: { id: 11 } });
|
||||
expect(f.days.updateAccommodation).toHaveBeenCalledWith(
|
||||
11,
|
||||
{ id: 11 },
|
||||
expect.objectContaining({ confirmation: null }),
|
||||
);
|
||||
expect(events(f.realtime)).toEqual(['accommodation:updated']);
|
||||
});
|
||||
|
||||
it('BOOK-RPC-015d deleting a block without a partner cascades only its own event', async () => {
|
||||
const f = build();
|
||||
await f.host().dispatch(req('accommodations.delete', { tripId: 1, accommodationId: 11 }), 42);
|
||||
|
||||
@@ -315,7 +315,7 @@ export const accommodationCreateBodySchema = accommodationCreateRequestSchema.pa
|
||||
});
|
||||
export type AccommodationCreateBody = z.infer<typeof accommodationCreateBodySchema>;
|
||||
|
||||
export const accommodationUpdateRequestSchema = open;
|
||||
export const accommodationUpdateRequestSchema = open.and(accommodationCreateRequestSchema.pick({ confirmation: true }));
|
||||
export type AccommodationUpdateRequest = z.infer<typeof accommodationUpdateRequestSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user