|
|
|
@@ -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';
|
|
|
|
|
}
|
|
|
|
|