feat(booking-import): report each unconfirmed item and check the right in confirm()

confirm() now answers { created, failed: [{ index, reason }] } instead of logging
and dropping the items it could not write, and checks the trip and reservation_edit
itself so the import route and the assistant get one answer. An item with a booking
reference records it as its origin (sync off) and a repeat import is a duplicate.
This commit is contained in:
Maurice
2026-11-13 14:57:17 +01:00
parent d2b12cd3dd
commit 5dc1de0e5b
12 changed files with 507 additions and 142 deletions
@@ -20,6 +20,7 @@ const PHOTO_EXTENSIONS: ReadonlySet<string> = new Set(LLM_PHOTO_EXTENSIONS);
const NOT_ALLOWED = 'You are not allowed to add bookings to this trip.';
const NOT_ADDED = 'The booking could not be added.';
const ALREADY_THERE = 'This booking is already in the trip.';
const BROKEN = 'This booking can no longer be read.';
/**
@@ -129,9 +130,9 @@ export class AssistantBookingImportService implements AttachedFileReader {
}
// No socket to spare from the echo: the user's own planner learns of the
// booking like every other member's.
const { created } = await this.bookingImport.confirm(String(tripId), [parsed.data], undefined);
const { created, failed } = await this.bookingImport.confirm(String(tripId), userId, [parsed.data], undefined);
const reservation = created[0];
if (!reservation) return { ok: false, value: NOT_ADDED };
if (!reservation) return { ok: false, value: failed[0]?.reason === 'duplicate' ? ALREADY_THERE : NOT_ADDED };
return {
ok: true,
value: {
@@ -1,5 +1,6 @@
import { Days } from '../../db/entities/Days.entity';
import { Reservations } from '../../db/entities/Reservations.entity';
import { Users } from '../../db/entities/Users.entity';
import { AddonsModule } from '../addons/addons.module';
import { BudgetModule } from '../budget/budget.module';
import { LlmParseModule } from '../llm-parse/llm-parse.module';
@@ -14,9 +15,11 @@ import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
/**
* `MikroOrmModule.forFeature([Days, Reservations])` (Plan 3h Task 4, BI1/BI2):
* `MikroOrmModule.forFeature([Days, Reservations, Users])` (Plan 3h Task 4, BI1/BI2):
* `BookingImportService.resolveDayId` reaches `DaysRepository.findByTripAndDate`
* and `ReservationsRepository.findNearestDayId`.
* and `ReservationsRepository.findNearestDayId`; confirm() reads the duplicate
* key through `ReservationsRepository` and the importing person's role through
* `UsersRepository` for its own permission check.
*/
@Module({
imports: [
@@ -28,7 +31,7 @@ import { Module } from '@nestjs/common';
AddonsModule,
MapsModule,
PlacesModule,
MikroOrmModule.forFeature([Days, Reservations]),
MikroOrmModule.forFeature([Days, Reservations, Users]),
],
providers: [BookingImportService, ImportJobsService],
// The HTTP surface lives in reservation-import/, which shares the prefix with
@@ -1,9 +1,10 @@
import { ADDON_IDS } from '../../addons';
import { Days } from '../../db/entities/Days.entity';
import { Reservations } from '../../db/entities/Reservations.entity';
import { Users } from '../../db/entities/Users.entity';
import { DaysRepository } from '../../db/repositories/Days.repository';
import { ReservationsRepository } from '../../db/repositories/Reservations.repository';
import type { User } from '../../types';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { AddonsService } from '../addons/addons.service';
import { BudgetService } from '../budget/budget.service';
import { DomainError } from '../common/domain-error';
@@ -15,10 +16,12 @@ import { PermissionsService } from '../permissions/permissions.service';
import { PlaceOriginsService } from '../places/place-origins.service';
import { PlacesService } from '../places/places.service';
import { RealtimeService } from '../realtime/realtime.service';
import { ReservationsService } from '../reservations/reservations.service';
import { ReservationsService, withoutOrigin, type CreateAccommodation } from '../reservations/reservations.service';
import { IMPORT_SOURCE, importExternalId } from './booking-origin';
import { KitineraryExtractorService } from './kitinerary-extractor.service';
import { mapReservations } from './kitinerary-mapper';
import type { ParsedBookingItem, KiReservation } from './kitinerary.types';
import { UniqueConstraintViolationException } from '@mikro-orm/core';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import { normalizePlaceWebsite, typeToCostCategory } from '@trek/shared';
@@ -26,6 +29,7 @@ import type {
BookingImportPreviewItem,
BookingImportPreviewResponse,
BookingImportConfirmResponse,
BookingImportFailureReason,
BookingImportMode,
BookingImportFileReport,
Reservation,
@@ -47,6 +51,7 @@ export class BookingImportService {
private readonly places: PlacesService,
private readonly uow: UnitOfWork,
private readonly origins: PlaceOriginsService,
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
) {}
/**
@@ -298,148 +303,203 @@ export class BookingImportService {
}
/**
* Persist a confirmed list of parsed items.
* Persist a confirmed list of parsed items for a person who may edit the
* trip's bookings; the check is made here, so every caller (the import route,
* the assistant) gets the same answer.
*
* Per item, the network work runs first (venue and endpoint geocoding, the cost's
* frozen rate). Then the venue's place row, the booking and its linked cost are one
* transaction, so a booking that fails leaves no stray place behind. place:created,
* reservation:created, accommodation:created and the cost go out after the commit.
*
* An item with a booking reference records it as its origin, and one the trip
* already holds under the same key is reported as a duplicate instead of
* being written twice. Every item that is not created is named in `failed`
* by its position, so the caller can say which one and why.
*
* @txIndependent one transaction per imported item: each booking lands whole with its
* venue and cost, and one that fails is skipped without undoing the ones before it.
*/
async confirm(
tripId: string,
userId: number,
items: BookingImportPreviewItem[],
socketId: string | undefined,
): Promise<BookingImportConfirmResponse> {
await this.requireBookingEdit(tripId, userId);
const created: Reservation[] = [];
const confirmGeoCache = new Map<string, { lat: number; lng: number } | null>();
const failed: { index: number; reason: BookingImportFailureReason }[] = [];
const geoCache = new Map<string, { lat: number; lng: number } | null>();
const venues: number[] = [];
for (const item of items) {
for (const [index, item] of items.entries()) {
const externalId = importExternalId(item);
if (externalId && (await this.alreadyImported(tripId, externalId))) {
failed.push({ index, reason: 'duplicate' });
continue;
}
try {
const { _venue, _accommodation, source: _src, ...reservationData } = item;
// A place row for venue-based reservations, written with the booking below.
let venue: Parameters<PlacesService['create']>[1] | undefined;
if (_venue?.name) {
// Geocode before creating so the broadcast carries the coordinates
let lat = _venue.lat;
let lng = _venue.lng;
if (lat == null && (_venue.address || _venue.name)) {
try {
const queries = [
_venue.address ? `${_venue.name} ${_venue.address}` : null,
_venue.address ?? null,
_venue.name,
].filter((q): q is string => !!q);
for (const q of queries) {
const hit = await this.maps.geocodeQuery(q);
if (hit) {
lat = hit.lat;
lng = hit.lng;
break;
}
}
} catch {
// geocoding failure is non-fatal
}
}
venue = {
name: _venue.name,
lat,
lng,
address: _venue.address,
// A booking mail gives the venue's site however its sender wrote it;
// it lands as https or not at all (#2483).
website: normalizePlaceWebsite(_venue.website) ?? undefined,
phone: _venue.phone,
};
}
// The same lookup preview() runs, through the same helper. On anything
// that came from a preview this is a no-op, since the endpoints already
// carry coordinates; it stays because this route can also be called
// with items that never went through one.
if (Array.isArray(reservationData.endpoints)) {
await this.geocodeEndpoints(
reservationData.endpoints,
{ location: (reservationData as { location?: string | null }).location, address: _venue?.address },
confirmGeoCache,
);
// Persist only coord'd endpoints (reservation_endpoints needs lat/lng);
// ungeocodable ones still appeared in the preview's From→To.
reservationData.endpoints = reservationData.endpoints.filter((ep) => ep.lat != null && ep.lng != null);
}
// Build create_accommodation for hotel reservations.
// start_day_id / end_day_id are resolved from check-in/out ISO dates so
// the accommodation row is actually inserted (createReservation gates on them).
let createAccommodation:
| {
place_id?: number;
start_day_id?: number;
end_day_id?: number;
check_in?: string;
check_out?: string;
confirmation?: string;
}
| undefined;
if (item.type === 'hotel' && _accommodation) {
const startDayId = await this.resolveDayId(tripId, _accommodation.check_in);
const endDayId = await this.resolveDayId(tripId, _accommodation.check_out);
createAccommodation = {
start_day_id: startDayId ?? undefined,
end_day_id: endDayId ?? undefined,
check_in: _accommodation.check_in,
check_out: _accommodation.check_out,
confirmation: _accommodation.confirmation,
};
}
// The venue, the booking and its linked cost are one write; the booking goes
// through the same service core REST, MCP and the plugin RPC take. The cost's
// rate is frozen first, outside that write, since it can fetch rates over the network.
const cost = await this.linkedCost(tripId, item);
const { place, reservation, accommodationCreated, costEvents, stayMirror } = await this.uow.transactional(
async () => {
const placeRow = venue ? await this.places.create(tripId, venue) : null;
const placeId = placeRow?.id;
const written = await this.reservations.createWithCostInTx(
tripId,
{
...reservationData,
place_id: placeId,
create_accommodation: createAccommodation && { ...createAccommodation, place_id: placeId },
} as never,
cost,
);
return { place: placeRow, ...written };
},
);
if (place) venues.push(place.id);
if (place) this.realtime.broadcast(tripId, 'place:created', { place }, socketId);
this.realtime.broadcast(tripId, 'reservation:created', { reservation }, socketId);
if (accommodationCreated) {
this.realtime.broadcast(tripId, 'accommodation:created', {}, socketId);
}
await this.reservations.announceStayMirror(tripId, stayMirror);
this.reservations.announceCost(tripId, costEvents, socketId);
const { reservation, placeId } = await this.createItem(tripId, item, externalId, socketId, geoCache);
if (placeId !== null) venues.push(placeId);
created.push(reservation);
} catch (err) {
console.error(
`[booking-import] Failed to create reservation "${item.title}":`,
err instanceof Error ? err.message : err,
);
failed.push({ index, reason: failureReason(err, item) });
}
}
// The venues' websites and phones come from the bookings, not from a person: an import, never shared.
if (venues.length > 0) await this.origins.recordImported(venues);
return { created };
return { created, failed };
}
/** 404 when the person cannot reach the trip, 403 when they may not edit its bookings. */
private async requireBookingEdit(tripId: string, userId: number): Promise<void> {
const trip = await this.reservations.verifyTripAccess(tripId, userId);
if (!trip) throw new DomainError(404, 'Trip not found');
const role = (await this.usersRepo.getRole(userId)) ?? 'user';
const isMember = trip.user_id !== userId;
if (!(await this.permissions.checkPermission('reservation_edit', role, trip.user_id, userId, isMember))) {
throw new DomainError(403, 'No permission');
}
}
/** Whether an earlier import already wrote the booking this key names into the trip. */
private async alreadyImported(tripId: string, externalId: string): Promise<boolean> {
const id = await this.reservationsRepo.findIdByExternal(this.rowIdNum(tripId), IMPORT_SOURCE, externalId);
return id !== undefined;
}
/** The place row a venue booking brings, geocoded first so the broadcast carries coordinates. */
private async venuePlace(
venue: BookingImportPreviewItem['_venue'],
): Promise<Parameters<PlacesService['create']>[1] | undefined> {
if (!venue?.name) return undefined;
let lat = venue.lat;
let lng = venue.lng;
if (lat == null) {
const queries = [venue.address ? `${venue.name} ${venue.address}` : null, venue.address ?? null, venue.name];
try {
for (const q of queries) {
if (!q) continue;
const hit = await this.maps.geocodeQuery(q);
if (hit) {
lat = hit.lat;
lng = hit.lng;
break;
}
}
} catch {
// geocoding failure is non-fatal
}
}
return {
name: venue.name,
lat,
lng,
address: venue.address,
// A booking mail gives the venue's site however its sender wrote it;
// it lands as https or not at all (#2483).
website: normalizePlaceWebsite(venue.website) ?? undefined,
phone: venue.phone,
};
}
/**
* The stay a hotel booking brings. start_day_id / end_day_id are resolved from
* the check-in/out dates so the accommodation row is actually inserted
* (createReservation gates on them).
*/
private async accommodationFor(
tripId: string,
item: BookingImportPreviewItem,
): Promise<CreateAccommodation | undefined> {
const stay = item._accommodation;
if (item.type !== 'hotel' || !stay) return undefined;
const startDayId = await this.resolveDayId(tripId, stay.check_in);
const endDayId = await this.resolveDayId(tripId, stay.check_out);
return {
start_day_id: startDayId ?? undefined,
end_day_id: endDayId ?? undefined,
check_in: stay.check_in,
check_out: stay.check_out,
confirmation: stay.confirmation,
};
}
/** One confirmed item written with its venue and cost, and announced once that committed. */
private async createItem(
tripId: string,
item: BookingImportPreviewItem,
externalId: string | null,
socketId: string | undefined,
geoCache: Map<string, { lat: number; lng: number } | null>,
): Promise<{ reservation: Reservation; placeId: number | null }> {
// The origin is the import's to set, never the item's: the confirm body comes from the client.
const { _venue, _accommodation, source: _src, ...fields } = item;
const reservationData = withoutOrigin(fields) as typeof fields;
const venue = await this.venuePlace(_venue);
// The same lookup preview() runs, through the same helper. On anything
// that came from a preview this is a no-op, since the endpoints already
// carry coordinates; it stays because this route can also be called
// with items that never went through one.
if (Array.isArray(reservationData.endpoints)) {
await this.geocodeEndpoints(
reservationData.endpoints,
{ location: reservationData.location, address: _venue?.address },
geoCache,
);
// Persist only coord'd endpoints (reservation_endpoints needs lat/lng);
// ungeocodable ones still appeared in the preview's From→To.
reservationData.endpoints = reservationData.endpoints.filter((ep) => ep.lat != null && ep.lng != null);
}
const createAccommodation = await this.accommodationFor(tripId, item);
const origin = externalId ? { external_source: IMPORT_SOURCE, external_id: externalId, sync_enabled: false } : {};
// The venue, the booking and its linked cost are one write; the booking goes
// through the same service core REST, MCP and the plugin RPC take. The cost's
// rate is frozen first, outside that write, since it can fetch rates over the network.
const cost = await this.linkedCost(tripId, item);
const { place, reservation, accommodationCreated, costEvents, stayMirror } = await this.uow.transactional(
async () => {
const placeRow = venue ? await this.places.create(tripId, venue) : null;
const placeId = placeRow?.id;
const written = await this.reservations.createWithCostInTx(
tripId,
{
...reservationData,
...origin,
place_id: placeId,
create_accommodation: createAccommodation && { ...createAccommodation, place_id: placeId },
} as never,
cost,
);
return { place: placeRow, ...written };
},
);
if (place) this.realtime.broadcast(tripId, 'place:created', { place }, socketId);
this.realtime.broadcast(tripId, 'reservation:created', { reservation }, socketId);
if (accommodationCreated) {
this.realtime.broadcast(tripId, 'accommodation:created', {}, socketId);
}
await this.reservations.announceStayMirror(tripId, stayMirror);
this.reservations.announceCost(tripId, costEvents, socketId);
return { reservation, placeId: place ? place.id : null };
}
}
/**
* Why an item's write failed. Two imports of one booking at once both pass the
* duplicate read, and the unique index refuses the second: that is a
* duplicate too, not a failure worth a log line.
*/
function failureReason(err: unknown, item: BookingImportPreviewItem): BookingImportFailureReason {
if (err instanceof UniqueConstraintViolationException) return 'duplicate';
console.error(
`[booking-import] Failed to create reservation "${item.title}":`,
err instanceof Error ? err.message : err,
);
return 'write_failed';
}
@@ -0,0 +1,35 @@
import type { BookingImportPreviewItem } from '@trek/shared';
/** The `external_source` of a booking written by the file import. */
export const IMPORT_SOURCE = 'import';
/** `external_id` is free text, but a key past this length is a document that is not a booking reference. */
const MAX_EXTERNAL_ID = 200;
/** A booking reference as an operator prints it, without the spacing and case a mail adds. */
function normalizeReference(value: string | null | undefined): string {
return (value ?? '').replace(/\s+/g, '').toUpperCase();
}
/** An endpoint as the key names it: its code where it has one, else its name. */
function endpointKey(endpoint: { code?: string | null; name?: string | null } | undefined): string {
if (!endpoint) return '';
return (endpoint.code || endpoint.name || '').trim().toLowerCase();
}
/**
* The key one booking of a reference is stored under, or null without a
* reference. One reference covers several bookings (an outbound and a return
* flight, two hotels of one trip), so the key adds what tells them apart: the
* type, the day it starts (the check-in for a stay) and, for a transport, where
* it runs from and to. The same booking imported twice gives the same key, and
* `idx_reservations_external` holds one booking per key and trip.
*/
export function importExternalId(item: BookingImportPreviewItem): string | null {
const reference = normalizeReference(item.confirmation_number);
if (!reference) return null;
const start = (item.reservation_time ?? item._accommodation?.check_in ?? '').slice(0, 10);
const endpoints = item.endpoints ?? [];
const route = endpoints.length > 0 ? `${endpointKey(endpoints[0])}-${endpointKey(endpoints.at(-1))}` : '';
return [reference, item.type, start, route].join('|').slice(0, MAX_EXTERNAL_ID);
}
@@ -224,6 +224,6 @@ export class ReservationImportController {
// The DTO asserts an array of objects and stops there, so the per-item shape
// is still the service's to interpret — as it was before the contract landed.
return this.bookingImport.confirm(tripId, items as BookingImportPreviewItem[], socketId);
return this.bookingImport.confirm(tripId, user.id, items as BookingImportPreviewItem[], socketId);
}
}
@@ -94,7 +94,7 @@ export type ReservationRow = Record<string, unknown> & {
travelers?: ReservationTraveler[];
};
interface CreateAccommodation {
export interface CreateAccommodation {
place_id?: number;
start_day_id?: number;
end_day_id?: number;