Compare commits

...

6 Commits

Author SHA1 Message Date
Maurice a2cf911ce1 fix(dashboard): respect pointer type when focusing trip titles
Mark the title through the existing dialog focus mechanism so a
mouse can type right away and touch keeps focus on the dialog.
Cover creating and editing a trip in the dashboard tests.
2026-12-02 14:49:52 +01:00
Luffy 7a66a54e66 fix(dashboard): focus the title in desktop trip forms 2026-12-02 14:46:23 +01:00
Maurice 748434fc47 style(server): satisfy accommodation confirmation lint
Keep ordered writes for one linked booking in a single method. Check
that each test fixture exists before using the reservation.
2026-12-02 11:55:45 +01:00
Maurice 618f070675 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
2026-12-02 11:49:33 +01:00
Maurice dacf19b4d5 style(server): format the assistant proposal guard
The Server lint formatting check rejected the assistant agent and its regression test. Apply the repository Prettier configuration to those two files.
2026-12-02 10:23:11 +01:00
Maurice 103631d5fc Hold identical assistant changes only once per step 2026-12-02 10:23:11 +01:00
19 changed files with 421 additions and 119 deletions
@@ -521,6 +521,7 @@ export default function TripFormModal({
{t('dashboard.tripTitle')} <span className="text-danger">*</span> {t('dashboard.tripTitle')} <span className="text-danger">*</span>
</label> </label>
<input <input
data-initial-focus={(!embedded && canEditTrip) || undefined}
type="text" type="text"
value={formData.title} value={formData.title}
onChange={(e) => canEditTrip && update('title', e.target.value)} onChange={(e) => canEditTrip && update('title', e.target.value)}
+17 -7
View File
@@ -42,8 +42,17 @@ beforeEach(() => {
afterEach(() => { afterEach(() => {
vi.useRealTimers(); vi.useRealTimers();
vi.unstubAllGlobals();
}); });
function mockFinePointer() {
const matchMedia = window.matchMedia.bind(window);
vi.stubGlobal('matchMedia', (query: string) => {
const result = matchMedia(query);
return query === '(pointer: fine)' ? { ...result, matches: true } : result;
});
}
describe('DashboardPage', () => { describe('DashboardPage', () => {
describe('FE-PAGE-DASH-001: Unauthenticated user is redirected', () => { describe('FE-PAGE-DASH-001: Unauthenticated user is redirected', () => {
it('does not render dashboard content when not authenticated', () => { it('does not render dashboard content when not authenticated', () => {
@@ -100,7 +109,8 @@ describe('DashboardPage', () => {
}); });
describe('FE-PAGE-DASH-005: Create Trip button opens TripFormModal', () => { describe('FE-PAGE-DASH-005: Create Trip button opens TripFormModal', () => {
it('clicking New Trip button opens the trip form modal', async () => { it.each(['mouse', 'touch'])('PR-3305: opening the trip form sets the right focus for %s', async (pointer) => {
if (pointer === 'mouse') mockFinePointer();
const user = userEvent.setup(); const user = userEvent.setup();
render(<DashboardPage />); render(<DashboardPage />);
@@ -110,10 +120,9 @@ describe('DashboardPage', () => {
await user.click(screen.getAllByRole('button', { name: /new trip/i })[0]); await user.click(screen.getAllByRole('button', { name: /new trip/i })[0]);
// TripFormModal opens — "Create New Trip" appears in heading and submit button const dialog = await screen.findByRole('dialog', { name: 'Create New Trip' });
await waitFor(() => { const target = pointer === 'mouse' ? within(dialog).getByPlaceholderText(/summer in japan/i) : dialog;
expect(screen.getAllByText(/create new trip/i).length).toBeGreaterThan(0); expect(target).toHaveFocus();
});
}); });
}); });
@@ -253,7 +262,8 @@ describe('DashboardPage', () => {
}); });
describe('FE-PAGE-DASH-012: Edit trip opens form with pre-filled data', () => { describe('FE-PAGE-DASH-012: Edit trip opens form with pre-filled data', () => {
it('clicking edit on a trip card opens TripFormModal with trip title pre-filled', async () => { it('PR-3305: focuses the prefilled title when editing a trip', async () => {
mockFinePointer();
const user = userEvent.setup(); const user = userEvent.setup();
render(<DashboardPage />); render(<DashboardPage />);
@@ -266,7 +276,7 @@ describe('DashboardPage', () => {
await waitFor(() => { await waitFor(() => {
const titleInput = screen.getByDisplayValue('Paris Adventure'); const titleInput = screen.getByDisplayValue('Paris Adventure');
expect(titleInput).toBeInTheDocument(); expect(titleInput).toHaveFocus();
}); });
}); });
}); });
+2 -2
View File
@@ -9,7 +9,7 @@
"src/db/repositories/CollabPollVotes.repository.ts": 1, "src/db/repositories/CollabPollVotes.repository.ts": 1,
"src/db/repositories/DawarichConnections.repository.ts": 4, "src/db/repositories/DawarichConnections.repository.ts": 4,
"src/db/repositories/DawarichVisitSuggestions.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/DayAssignments.repository.ts": 20,
"src/db/repositories/DayNotes.repository.ts": 6, "src/db/repositories/DayNotes.repository.ts": 6,
"src/db/repositories/Days.repository.ts": 7, "src/db/repositories/Days.repository.ts": 7,
@@ -28,7 +28,7 @@
"src/db/repositories/PushSubscriptions.repository.ts": 1, "src/db/repositories/PushSubscriptions.repository.ts": 1,
"src/db/repositories/ReservationDayPositions.repository.ts": 1, "src/db/repositories/ReservationDayPositions.repository.ts": 1,
"src/db/repositories/ReservationEndpoints.repository.ts": 5, "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/ReservationTravelers.repository.ts": 2,
"src/db/repositories/RoadtripDayBoundaries.repository.ts": 3, "src/db/repositories/RoadtripDayBoundaries.repository.ts": 3,
"src/db/repositories/RoadtripDayTracks.repository.ts": 1, "src/db/repositories/RoadtripDayTracks.repository.ts": 1,
+2 -2
View File
@@ -2,7 +2,7 @@
"scripts/db-call-graph.mjs": 1036, "scripts/db-call-graph.mjs": 1036,
"scripts/generate-entities.ts": 2259, "scripts/generate-entities.ts": 2259,
"src/db/repositories/Places.repository.ts": 1432, "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/Trips.repository.ts": 1120,
"src/db/repositories/Users.repository.ts": 1403, "src/db/repositories/Users.repository.ts": 1403,
"src/nest/atlas/atlas.service.ts": 1166, "src/nest/atlas/atlas.service.ts": 1166,
@@ -15,6 +15,6 @@
"src/nest/places/places.service.ts": 1517, "src/nest/places/places.service.ts": 1517,
"src/nest/plugins/plugin-runtime.service.ts": 1458, "src/nest/plugins/plugin-runtime.service.ts": 1458,
"src/nest/plugins/runtime/plugin-sdk.ts": 1093, "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 "src/nest/vacay/vacay.service.ts": 1393
} }
@@ -121,13 +121,8 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
.execute('run'); .execute('run');
} }
/** RS30/RS43 — `UPDATE day_accommodations SET confirmation = COALESCE(?, confirmation) WHERE id = ?`. */
async patchConfirmation(id: number, confirmation: string | null): Promise<void> { async patchConfirmation(id: number, confirmation: string | null): Promise<void> {
const platform = this.getEntityManager().getPlatform(); await this.nativeUpdate({ id }, { confirmation });
await this.qb()
.update({ confirmation: coalesceOverride(platform, confirmation, 'confirmation') })
.where({ id })
.execute('run');
} }
/** /**
@@ -159,14 +154,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
return row?.check_in; return row?.check_in;
} }
/** /** An omitted confirmation leaves the stay's existing reference in place. */
* 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).
*/
async updateFromBooking( async updateFromBooking(
id: number, id: number,
write: { write: {
@@ -175,7 +163,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
end_day_id: number; end_day_id: number;
check_in: string | null; check_in: string | null;
check_out: string | null; check_out: string | null;
confirmation: string | null; confirmation?: string | null;
}, },
): Promise<void> { ): Promise<void> {
await this.nativeUpdate( await this.nativeUpdate(
@@ -186,7 +174,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
endDay: write.end_day_id, endDay: write.end_day_id,
check_in: write.check_in, check_in: write.check_in,
check_out: write.check_out, 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: string | null;
check_in_end: string | null; check_in_end: string | null;
check_out: string | null; check_out: string | null;
confirmation: string | null; confirmation?: string | null;
notes: string | null; notes: string | null;
}, },
): Promise<void> { ): Promise<void> {
@@ -356,7 +344,7 @@ export class DayAccommodationsRepository extends TrekRepository<DayAccommodation
check_in: write.check_in, check_in: write.check_in,
check_in_end: write.check_in_end, check_in_end: write.check_in_end,
check_out: write.check_out, check_out: write.check_out,
confirmation: write.confirmation, ...(write.confirmation !== undefined ? { confirmation: write.confirmation } : {}),
notes: write.notes, notes: write.notes,
}, },
); );
@@ -1,7 +1,7 @@
import type { Reservations } from '../entities/Reservations.entity'; import type { Reservations } from '../entities/Reservations.entity';
import { DayAssignments } from '../entities/DayAssignments.entity'; import { DayAssignments } from '../entities/DayAssignments.entity';
import { Days } from '../entities/Days.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 { concatKysely, startsWithIsoDateKysely, substringKysely } from '../dialect/kysely-functions';
import { accommodationIdMatches, reservationStayIs } from './_shared/reservation-accommodation'; import { accommodationIdMatches, reservationStayIs } from './_shared/reservation-accommodation';
import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility'; 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"). // Reservations repositories where a read belongs there").
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/** /** The partner hotel booking created with a stay. The caller decides its initial status. */
* 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.
*/
async insertHotelPartner(input: { async insertHotelPartner(input: {
trip_id: number | string; trip_id: number | string;
day_id: number; day_id: number;
title: string; title: string;
reservation_time: string | null; reservation_time: string | null;
confirmation_number: string | null; confirmation_number: string | null;
status: 'pending' | 'confirmed';
notes: string | null; notes: string | null;
accommodation_id: string; accommodation_id: string;
metadata: string | null; metadata: string | null;
@@ -693,8 +683,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
location: null, location: null,
confirmation_number: input.confirmation_number, confirmation_number: input.confirmation_number,
notes: input.notes, notes: input.notes,
// A stay without a confirmation number is not a confirmed booking yet. status: input.status,
status: input.confirmation_number ? 'confirmed' : 'pending',
type: 'hotel', type: 'hotel',
accommodation_id: input.accommodation_id, accommodation_id: input.accommodation_id,
metadata: input.metadata, metadata: input.metadata,
@@ -719,24 +708,23 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
return rows as { id: number; metadata: string | null }[]; return rows as { id: number; metadata: string | null }[];
} }
/** /** Clearing a reference reopens a confirmed booking that actually held a reference. */
* AC38 (`AccommodationsService.updateAccommodation`) — `UPDATE async setMetadataAndConfirmation(id: number, metadata: string, confirmation?: string | null): Promise<void> {
* reservations SET metadata = ?, confirmation_number = COALESCE(?, await this.kysely<Pick<DB, 'reservations'>>()
* confirmation_number) WHERE id = ?`. Runs AFTER `updateAccommodation`'s .updateTable('reservations')
* own transaction commits (§18.6 — R5 class, flagged not fixed). .set((eb) => ({
* `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({
metadata, metadata,
confirmation_number: coalesceOverride(platform, confirmation, 'confirmation_number'), confirmation_number: confirmation,
}) status: confirmation === null
.where({ id }) ? eb.case()
.execute('run'); .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. */ /** 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: z.string().max(10).optional(),
check_in_end: z.string().max(10).optional().describe('Check-in window end time e.g. "20:00"'), 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(), 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(), notes: z.string().max(1000).optional(),
}, },
annotations: TOOL_ANNOTATIONS_WRITE, annotations: TOOL_ANNOTATIONS_WRITE,
@@ -285,7 +285,7 @@ export class AccommodationsMcp {
check_in?: string; check_in?: string;
check_in_end?: string; check_in_end?: string;
check_out?: string; check_out?: string;
confirmation?: string; confirmation?: string | null;
notes?: string; notes?: string;
}, },
ctx: McpContext, ctx: McpContext,
@@ -89,7 +89,7 @@ export class AccommodationsRpc {
check_in?: string; check_in?: string;
check_in_end?: string; check_in_end?: string;
check_out?: string; check_out?: string;
confirmation?: string; confirmation?: string | null;
notes?: string; 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. // 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; 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 * 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 * 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?: string;
check_in_end?: string; check_in_end?: string;
check_out?: string; check_out?: string;
confirmation?: string; confirmation?: string | null;
notes?: string; notes?: string;
} }
@@ -778,6 +785,7 @@ export class AccommodationsService {
async createAccommodation(tripId: string | number, data: CreateAccommodationData) { 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 { 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 // 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. // 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: check_in || null,
check_in_end: check_in_end || null, check_in_end: check_in_end || null,
check_out: check_out || null, check_out: check_out || null,
confirmation: confirmation || null, confirmation: reference,
notes: notes || null, notes: notes || null,
}); });
@@ -810,7 +818,8 @@ export class AccommodationsService {
day_id: start_day_id, day_id: start_day_id,
title: placeName, title: placeName,
reservation_time: startDayDate || null, reservation_time: startDayDate || null,
confirmation_number: confirmation || null, confirmation_number: reference,
status: looksLikeBookingReference(reference) ? 'confirmed' : 'pending',
notes: notes || null, notes: notes || null,
accommodation_id: legacyBoundIntegerText(newId), accommodation_id: legacyBoundIntegerText(newId),
metadata: Object.keys(meta).length > 0 ? encodeJson(RESERVATION_METADATA, meta) : null, metadata: Object.keys(meta).length > 0 ? encodeJson(RESERVATION_METADATA, meta) : null,
@@ -832,14 +841,14 @@ export class AccommodationsService {
return await this.dayAccommodationsRepo.findInTrip(idNum, tripIdNum); return await this.dayAccommodationsRepo.findInTrip(idNum, tripIdNum);
} }
/** private async syncLinkedReservation(
* Writes a stay's times and confirmation number onto one linked booking. A number id: number,
* also confirms the booking when it was still pending, and that has to come after metadata: string,
* the write, so both steps stay together here for each booking. confirmation: string | null | undefined,
*/ shouldConfirm: boolean,
private async syncLinkedReservation(id: number, metadata: string, confirmation: string | null): Promise<void> { ): Promise<void> {
await this.reservationsRepo.setMetadataAndConfirmation(id, metadata, confirmation); await this.reservationsRepo.setMetadataAndConfirmation(id, metadata, confirmation);
if (confirmation) await this.reservationsRepo.confirmIfPending(id); if (shouldConfirm) await this.reservationsRepo.confirmIfPending(id);
} }
async updateAccommodation( async updateAccommodation(
@@ -852,7 +861,7 @@ export class AccommodationsService {
check_in?: string; check_in?: string;
check_in_end?: string; check_in_end?: string;
check_out?: string; check_out?: string;
confirmation?: string; confirmation?: string | null;
notes?: string; notes?: string;
}, },
) { ) {
@@ -862,7 +871,9 @@ export class AccommodationsService {
const newCheckIn = fields.check_in !== undefined ? fields.check_in : existing.check_in; 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 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 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; const newNotes = fields.notes !== undefined ? fields.notes : existing.notes;
// The stay row, the day stop that mirrors it and the linked bookings' times all // The stay row, the day stop that mirrors it and the linked bookings' times all
@@ -879,7 +890,7 @@ export class AccommodationsService {
check_in: newCheckIn, check_in: newCheckIn,
check_in_end: newCheckInEnd, check_in_end: newCheckInEnd,
check_out: newCheckOut, check_out: newCheckOut,
confirmation: newConfirmation, confirmation,
notes: newNotes, notes: newNotes,
}); });
const moved = await this.remirrorStay(existing.id, newPlaceId, newStartDayId, newCheckIn, { const moved = await this.remirrorStay(existing.id, newPlaceId, newStartDayId, newCheckIn, {
@@ -896,7 +907,7 @@ export class AccommodationsService {
if (newCheckIn) meta.check_in_time = newCheckIn; if (newCheckIn) meta.check_in_time = newCheckIn;
if (newCheckInEnd) meta.check_in_end_time = newCheckInEnd; if (newCheckInEnd) meta.check_in_end_time = newCheckInEnd;
if (newCheckOut) meta.check_out_time = newCheckOut; if (newCheckOut) meta.check_out_time = newCheckOut;
await this.syncLinkedReservation(res.id, encodeJson(RESERVATION_METADATA, meta), newConfirmation || null); await this.syncLinkedReservation(res.id, encodeJson(RESERVATION_METADATA, meta), confirmation, shouldConfirm);
} }
return moved; return moved;
}); });
+6 -1
View File
@@ -35,6 +35,8 @@ import {
type TrekCard, type TrekCard,
} from '@trek/shared'; } from '@trek/shared';
import { isDeepStrictEqual } from 'node:util';
type ToolArgs = Record<string, unknown>; type ToolArgs = Record<string, unknown>;
/** /**
@@ -139,6 +141,7 @@ interface AgentOutcome {
} }
const TOO_MANY_CHANGES = `Too many changes in one step: propose at most ${MAX_WRITES_PER_STEP} at once.`; const TOO_MANY_CHANGES = `Too many changes in one step: propose at most ${MAX_WRITES_PER_STEP} at once.`;
const CHANGE_ALREADY_PROPOSED = 'This exact change is already waiting for approval.';
const TOO_MANY_LOOKUPS = `Too many lookups in one step: make at most ${MAX_READS_PER_STEP} at once.`; const TOO_MANY_LOOKUPS = `Too many lookups in one step: make at most ${MAX_READS_PER_STEP} at once.`;
/** What a step collects while its calls run: its parts, and the weather its lookups found. */ /** What a step collects while its calls run: its parts, and the weather its lookups found. */
@@ -495,7 +498,9 @@ async function runCalls(turn: Turn, calls: AiToolCall[], collected: StepParts):
const unknownPlace = 'error' in prepared ? null : placeIdRefusal(call.name, prepared.args, turn.knownPlaceIds); const unknownPlace = 'error' in prepared ? null : placeIdRefusal(call.name, prepared.args, turn.knownPlaceIds);
if (unknownPlace) prepared = { error: unknownPlace }; if (unknownPlace) prepared = { error: unknownPlace };
if (kind === 'write' && !('error' in prepared)) { if (kind === 'write' && !('error' in prepared)) {
const refused = await deps.refusalOf?.(call.name, prepared.args); const { args } = prepared;
const duplicate = held.some((change) => change.toolName === call.name && isDeepStrictEqual(change.args, args));
const refused = duplicate ? CHANGE_ALREADY_PROPOSED : await deps.refusalOf?.(call.name, args);
if (refused) prepared = { error: refused }; if (refused) prepared = { error: refused };
} }
if (kind === 'read' && !('error' in prepared)) reads += 1; if (kind === 'read' && !('error' in prepared)) reads += 1;
@@ -29,7 +29,7 @@ export interface CreateAccommodation {
end_day_id?: number; end_day_id?: number;
check_in?: string; check_in?: string;
check_out?: string; check_out?: string;
confirmation?: string; confirmation?: string | null;
} }
export interface CreateReservationData extends ReservationOrigin { export interface CreateReservationData extends ReservationOrigin {
@@ -58,7 +58,7 @@ export interface UpdateReservationData {
reservation_time?: string; reservation_time?: string;
reservation_end_time?: string; reservation_end_time?: string;
location?: string; location?: string;
confirmation_number?: string; confirmation_number?: string | null;
notes?: string; notes?: string;
url?: string; url?: string;
day_id?: number | null; 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.'), reservation_end_time: z.string().optional().describe('When it ends. Ignored for hotels, whose span is the check-in/check-out days.'),
url: urlField, url: urlField,
location: z.string().max(500).optional(), 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(), notes: z.string().max(1000).optional(),
status: z.enum(RESERVATION_STATUSES).optional().describe('Reservation status: "pending", "confirmed", or "cancelled"'), 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'), 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, reservationId, title, type, reservation_time, reservation_end_time, url, location, confirmation_number, notes, status, place_id, assignment_id }: {
tripId: number; reservationId: number; title?: string; tripId: number; reservationId: number; title?: string;
type?: BookingType; 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; status?: ReservationStatus; place_id?: number | null; assignment_id?: number | null;
}, },
ctx: McpContext, ctx: McpContext,
@@ -824,10 +824,14 @@ export class ReservationsService {
if (!accExists) resolvedAccId = null; if (!accExists) resolvedAccId = null;
} }
const hadStay = Boolean(resolvedAccId); 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) { if (type === 'hotel' && create_accommodation) {
const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = 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) { if (start_day_id && end_day_id) {
await this.requireResolvableStay(create_accommodation); await this.requireResolvableStay(create_accommodation);
const stayConfirmation = bookingConfirmation === undefined ? referenceOrNull(accConf) : bookingConfirmation;
if (resolvedAccId) { if (resolvedAccId) {
const resolvedAccIdNum = accIdForRead(resolvedAccId)!; const resolvedAccIdNum = accIdForRead(resolvedAccId)!;
const priorCheckIn = await this.dayAccommodationsRepo.getCheckIn(resolvedAccIdNum); const priorCheckIn = await this.dayAccommodationsRepo.getCheckIn(resolvedAccIdNum);
@@ -837,11 +841,9 @@ export class ReservationsService {
end_day_id, end_day_id,
check_in: check_in || null, check_in: check_in || null,
check_out: check_out || 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 // Carry the booking's day stop to the stay's new dates and place.
// 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.
stayMirror = await this.accommodations.moveStayStop(resolvedAccIdNum, accPlaceId || null, start_day_id, check_in, { stayMirror = await this.accommodations.moveStayStop(resolvedAccIdNum, accPlaceId || null, start_day_id, check_in, {
checkInChanged: (check_in || null) !== (priorCheckIn ?? null), checkInChanged: (check_in || null) !== (priorCheckIn ?? null),
}); });
@@ -853,10 +855,11 @@ export class ReservationsService {
end_day_id, end_day_id,
check_in: check_in || null, check_in: check_in || null,
check_out: check_out || 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); stayMirror = await this.accommodations.attachStayStop(resolvedAccId, accPlaceId, start_day_id, check_in);
} }
if (resolvedAccId) bookingConfirmation = stayConfirmation;
accommodationChanged = true; 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 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)); 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 // Resolve the update against the current row before writing.
// 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.
const idNum = this.rowIdNum(id); const idNum = this.rowIdNum(id);
await this.reservationsRepo.updateReservation(idNum, { await this.reservationsRepo.updateReservation(idNum, {
title: title || current.title, title: title || current.title,
reservation_time: nextReservationTime, reservation_time: nextReservationTime,
reservation_end_time: nextReservationEndTime, reservation_end_time: nextReservationEndTime,
location: location !== undefined ? (location || null) : (current.location ?? null), 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), notes: notes !== undefined ? (notes || null) : (current.notes ?? null),
url: url !== undefined ? (url || null) : ((current as Reservation & { url?: string | null }).url ?? null), url: url !== undefined ? (url || null) : ((current as Reservation & { url?: string | null }).url ?? null),
day_id: nextDayId, day_id: nextDayId,
@@ -932,19 +928,19 @@ export class ReservationsService {
await this.saveEndpoints(idNum, endpoints); 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); const resolvedMeta = nextMetadata !== undefined ? nextMetadata : (current.metadata ? decodeJson(RESERVATION_METADATA, current.metadata, `reservation ${idNum}`) : null);
if (resolvedAccId && resolvedMeta) { if (resolvedAccId) {
const meta = decodeJson(RESERVATION_METADATA, resolvedMeta) as AccommodationTimesMeta; const meta = resolvedMeta ? decodeJson(RESERVATION_METADATA, resolvedMeta) as AccommodationTimesMeta : null;
const resolvedAccIdNum = accIdForRead(resolvedAccId)!; 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( await this.dayAccommodationsRepo.patchTimes(
resolvedAccIdNum, meta.check_in_time || null, meta.check_in_end_time || null, meta.check_out_time || null, 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 (!accommodationChanged && bookingConfirmation !== undefined) {
if (resolvedConf) { await this.dayAccommodationsRepo.patchConfirmation(resolvedAccIdNum, bookingConfirmation);
await this.dayAccommodationsRepo.patchConfirmation(resolvedAccIdNum, resolvedConf); 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', tool: 'update_accommodation',
needs: ['stay'], 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: { rest: {
method: 'put', method: 'put',
path: (s) => `/api/trips/${s.trip.id}/accommodations/${s.stay.id}`, path: (s) => `/api/trips/${s.trip.id}/accommodations/${s.stay.id}`,
body: () => ({ notes: 'Late arrival' }), body: () => ({ confirmation: null }),
}, },
expect: ['accommodation:updated'], expect: ['accommodation:updated'],
}, },
@@ -352,14 +352,19 @@ export const bookings: CaseGroup = {
{ {
tool: 'update_reservation', tool: 'update_reservation',
needs: ['stay', 'member'], 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: { rest: {
method: 'put', method: 'put',
path: (s) => `/api/trips/${s.trip.id}/reservations/${s.stay.reservationId}`, path: (s) => `/api/trips/${s.trip.id}/reservations/${s.stay.reservationId}`,
body: () => ({ status: 'confirmed' }), body: () => ({ status: 'confirmed', confirmation_number: null }),
}, },
settle: true, 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. // A hotel booking takes its stay (and the stay's stop) and its linked cost along.
@@ -65,6 +65,7 @@ const KINDS: Record<string, AssistantToolKind> = {
get_weather: 'read', get_weather: 'read',
get_place_details: 'read', get_place_details: 'read',
create_place: 'write', create_place: 'write',
create_packing_item: 'write',
open_trip_chat: 'read', open_trip_chat: 'read',
}; };
@@ -284,6 +285,40 @@ describe('runAgentLoop', () => {
expect(t.chunks.at(-1)).toEqual({ type: 'finish', finishReason: 'tool-calls' }); expect(t.chunks.at(-1)).toEqual({ type: 'finish', finishReason: 'tool-calls' });
}); });
it('holds one proposal when the model repeats the same packing item change in a step', async () => {
const t = setup([
[
{
type: 'tool-call',
call: { id: 'first', name: 'create_packing_item', args: { name: 'Adapter', quantity: 2 } },
},
{
type: 'tool-call',
call: { id: 'repeat', name: 'create_packing_item', args: { quantity: 2, name: 'Adapter' } },
},
{
type: 'tool-call',
call: { id: 'other', name: 'create_packing_item', args: { name: 'Adapter', quantity: 3 } },
},
],
]);
const outcome = await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
expect(outcome.end).toBe('awaiting');
expect(t.memory.held[0].held.map((call) => call.providerCallId)).toEqual(['first', 'other']);
expect(t.chunks.filter((chunk) => chunk.type === 'tool-approval-request')).toHaveLength(2);
expect(t.memory.held[0].step.parts).toContainEqual({
type: 'tool-call',
toolCallId: 'repeat',
toolName: 'create_packing_item',
args: { quantity: 2, name: 'Adapter' },
result: 'This exact change is already waiting for approval.',
isError: true,
});
expect(t.tools.call).not.toHaveBeenCalled();
});
it('ASTAGT-004: more changes than a step may hold go back to the model as an error', async () => { it('ASTAGT-004: more changes than a step may hold go back to the model as an error', async () => {
const calls = Array.from({ length: MAX_WRITES_PER_STEP + 1 }, (_, i): AiChatEvent => ({ const calls = Array.from({ length: MAX_WRITES_PER_STEP + 1 }, (_, i): AiChatEvent => ({
type: 'tool-call', type: 'tool-call',
@@ -1174,6 +1174,7 @@ describe('ReservationsService — legacy branch parity (coverage of the folded c
const place = createPlace(testDb, trip.id); const place = createPlace(testDb, trip.id);
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[]; 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' }); 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 current = (await svc.getReservation(String(res.id), String(trip.id)))!;
const { reservation, accommodationChanged } = await svc.update(String(res.id), String(trip.id), { const { reservation, accommodationChanged } = await svc.update(String(res.id), String(trip.id), {
type: 'hotel', type: 'hotel',
@@ -1181,7 +1182,7 @@ describe('ReservationsService — legacy branch parity (coverage of the folded c
}, current); }, current);
expect(accommodationChanged).toBe(true); expect(accommodationChanged).toBe(true);
expect(reservation.accommodation_id).not.toBeNull(); 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 () => { 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); 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 { trip } = ownerTrip({ start_date: '2030-05-01', end_date: '2030-05-02' });
const place = createPlace(testDb, trip.id); const place = createPlace(testDb, trip.id);
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[]; 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' }); 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' }); 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)))!; 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), { notes: 'touch' }, current);
const row = await findRow(orm, DayAccommodations, { id: acc.id }); 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 () => { 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' }); 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 { trip } = ownerTrip({ start_date: '2030-05-01', end_date: '2030-05-02' });
const place = createPlace(testDb, trip.id); const place = createPlace(testDb, trip.id);
const days = await findRows(orm, Days, { trip: trip.id }, { day_number: 'asc' }) as { id: number }[]; 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 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' }); 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' }); 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)))!; 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 }); const row = await findRow(orm, DayAccommodations, { id: acc.id });
expect(row).toMatchObject({ confirmation: 'RES-NEW' }); 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));
if (!current) throw new Error('Booking was not found');
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));
if (!current) throw new Error('Booking was not found');
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 () => { 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 { 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 }[]; 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 () => { it('BOOK-RPC-015d deleting a block without a partner cascades only its own event', async () => {
const f = build(); const f = build();
await f.host().dispatch(req('accommodations.delete', { tripId: 1, accommodationId: 11 }), 42); await f.host().dispatch(req('accommodations.delete', { tripId: 1, accommodationId: 11 }), 42);
+1 -1
View File
@@ -315,7 +315,7 @@ export const accommodationCreateBodySchema = accommodationCreateRequestSchema.pa
}); });
export type AccommodationCreateBody = z.infer<typeof accommodationCreateBodySchema>; 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>; export type AccommodationUpdateRequest = z.infer<typeof accommodationUpdateRequestSchema>;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------