mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 23:27:31 +00:00
fix(booking-import): import a booking the document calls confirmed as confirmed
The mail import already wrote a booking as confirmed when its metadata held reservationStatus, but nothing ever filled that field: the KItinerary mapper dropped schema.org's reservationStatus, the AI reading was neither asked for it nor given it in its response schema (a schema-bound provider fills declared properties only), and the review form, the file import confirm path and the assistant's import card all started every booking as pending. The mapper now reads reservationStatus from every node, schema.org URL, bare ReservationConfirmed or a plain word alike, and keeps it in the item's metadata as TREK's word. The AI prompt and response schema ask for it. One shared helper turns it into the status a booking is saved with: confirmed when the document said so, pending otherwise, so a cancellation or an unknown value still lands as pending. The review form prefill, the mail import, the confirm path and the assistant card all use it. Closes #3238
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import type { BookingImportPreviewItem } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { parsedItemToDraft } from './parsedItemToDraft';
|
||||
|
||||
const item = (metadata?: Record<string, unknown>): BookingImportPreviewItem => ({
|
||||
type: 'flight',
|
||||
title: 'Kuala Lumpur to Bangkok',
|
||||
metadata,
|
||||
source: { fileName: 'airasia.eml', index: 0 },
|
||||
});
|
||||
|
||||
describe('parsedItemToDraft', () => {
|
||||
// #3238: the review form opens with the status the document states.
|
||||
it('FE-PARSED-DRAFT-001: a booking the document calls confirmed opens confirmed, anything else pending', () => {
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'confirmed' })).status).toBe('confirmed');
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'cancelled' })).status).toBe('pending');
|
||||
expect(parsedItemToDraft(item({ reservationStatus: 'pending' })).status).toBe('pending');
|
||||
expect(parsedItemToDraft(item()).status).toBe('pending');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BookingImportPreviewItem, Reservation, ReservationEndpoint } from '@trek/shared'
|
||||
import { importedReservationStatus, type BookingImportPreviewItem, type Reservation, type ReservationEndpoint } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* A pre-fill draft for the reservation/transport edit modals built from a parsed
|
||||
@@ -29,7 +29,8 @@ export function parsedItemToDraft(item: BookingImportPreviewItem): BookingReview
|
||||
return {
|
||||
type: item.type,
|
||||
title: item.title,
|
||||
status: 'pending',
|
||||
// Confirmed when the document said so, pending otherwise (#3238).
|
||||
status: importedReservationStatus(item.metadata),
|
||||
reservation_time: item.reservation_time ?? null,
|
||||
reservation_end_time: item.reservation_end_time ?? null,
|
||||
location: item.location ?? item._venue?.address ?? item._venue?.name ?? null,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { rowsOf } from '../undo-snapshot';
|
||||
import { bookingCard, bookingItemOf, changedBetween } from './booking-item';
|
||||
import { idOf, rowOfReservation, rowOfStay, scopeOfCard, type BookingRow, type StaySource } from './booking-row';
|
||||
import { bookingRowOf, dateOf, stayRowOf } from './booking-trip';
|
||||
import type { BookingCard, CardMoney, TrekCard } from '@trek/shared';
|
||||
import { importedReservationStatus, type BookingCard, type CardMoney, type TrekCard } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The cards of held booking writes: what will be saved, drawn from the
|
||||
@@ -261,16 +261,19 @@ export function importedBookingCard(ctx: PreviewContext, args: ToolArgs): TrekCa
|
||||
const stay = recordOf(args._accommodation);
|
||||
const venue = recordOf(args._venue);
|
||||
const isStay = args.type === 'hotel' || args._accommodation !== undefined;
|
||||
const meta = recordOf(args.metadata);
|
||||
const row: BookingRow = {
|
||||
...blankRow(ctx.card.tripId),
|
||||
type: isStay ? 'hotel' : args.type,
|
||||
title: args.title,
|
||||
// Saved confirmed when the file said so (#3238); a booking it says nothing about shows no status.
|
||||
status: importedReservationStatus(meta) === 'confirmed' ? 'confirmed' : null,
|
||||
needsReview: args.needs_review === true,
|
||||
confirmation: args.confirmation_number,
|
||||
reservationTime: args.reservation_time,
|
||||
reservationEndTime: args.reservation_end_time,
|
||||
location: args.location ?? venue.name,
|
||||
meta: recordOf(args.metadata),
|
||||
meta,
|
||||
endpoints: rowsOf(args.endpoints),
|
||||
point: { lat: venue.lat, lng: venue.lng },
|
||||
stay: isStay
|
||||
|
||||
@@ -24,7 +24,7 @@ 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';
|
||||
import { importedReservationStatus, normalizePlaceWebsite, typeToCostCategory } from '@trek/shared';
|
||||
import type {
|
||||
BookingImportPreviewItem,
|
||||
BookingImportPreviewResponse,
|
||||
@@ -520,6 +520,8 @@ export class BookingImportService {
|
||||
tripId,
|
||||
{
|
||||
...reservationData,
|
||||
// Confirmed when the document said so (#3238), like the mail import and the review form.
|
||||
status: importedReservationStatus(item.metadata),
|
||||
...origin,
|
||||
place_id: placeId,
|
||||
create_accommodation: createAccommodation && { ...createAccommodation, place_id: placeId },
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
haversineMetres,
|
||||
LEG_RESERVATION_TYPES,
|
||||
normalizeLocalDateTime,
|
||||
readReservationStatus,
|
||||
splitLocalDateTime,
|
||||
sumMinor,
|
||||
toMinor,
|
||||
@@ -730,9 +731,14 @@ function segmentDetail(r: KiReservation): {
|
||||
};
|
||||
}
|
||||
|
||||
/** Merge a node's seat/class/platform/price into its item's metadata. The item's own metadata wins. */
|
||||
/**
|
||||
* Merge a node's seat/class/platform/price and the status the document states
|
||||
* into its item's metadata. The item's own metadata wins. The status is the one
|
||||
* the mail import and the review form read (#3238), written as TREK's word.
|
||||
*/
|
||||
function applyCommonMeta(item: ParsedBookingItem, r: KiReservation): ParsedBookingItem {
|
||||
const detail = segmentDetail(r);
|
||||
const status = readReservationStatus(r.reservationStatus);
|
||||
const detail = { ...segmentDetail(r), ...(status ? { reservationStatus: status } : {}) };
|
||||
if (Object.keys(detail).length) item.metadata = { ...detail, ...(item.metadata ?? {}) };
|
||||
return item;
|
||||
}
|
||||
|
||||
@@ -147,6 +147,8 @@ export interface KiReservation {
|
||||
platform?: string;
|
||||
price?: number | string;
|
||||
priceCurrency?: string;
|
||||
/** schema.org's ReservationConfirmed, ReservationCancelled and the like, bare or as a URL. */
|
||||
reservationStatus?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ export function reservationShapeRules(): string[] {
|
||||
'Each reservation is a schema.org JSON-LD object whose "@type" is one of:',
|
||||
KI_RESERVATION_TYPES.map((t) => ` - ${t}`).join('\n'),
|
||||
'Put the booking/confirmation code in "reservationNumber" on each reservation.',
|
||||
'When the document states the booking status, put it in "reservationStatus" on each reservation: "ReservationConfirmed", "ReservationPending" or "ReservationCancelled". Leave it out when the document does not say.',
|
||||
'All dates/times are plain ISO 8601 local strings, e.g. "2026-06-11T10:00:00" (no timezone wrapper objects).',
|
||||
'IMPORTANT: nest the type-specific fields INSIDE a "reservationFor" object — do NOT place them at the top level of the reservation.',
|
||||
'Populate "reservationFor" with the type-specific fields:',
|
||||
|
||||
@@ -20,6 +20,7 @@ import { parsePriceMinor } from './mail-money';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
importedReservationStatus,
|
||||
normalizePlaceWebsite,
|
||||
typeToCostCategory,
|
||||
type BookingImportPreviewItem,
|
||||
@@ -285,7 +286,7 @@ export class MailIngestApplyService {
|
||||
return {
|
||||
title: fields.title,
|
||||
type: fields.type,
|
||||
status: statusOf(item),
|
||||
status: importedReservationStatus(item.metadata),
|
||||
reservation_time: fields.reservation_time ?? undefined,
|
||||
reservation_end_time: fields.reservation_end_time ?? undefined,
|
||||
location: fields.location ?? undefined,
|
||||
@@ -356,12 +357,6 @@ interface RemovedBooking {
|
||||
placeIds: number[];
|
||||
}
|
||||
|
||||
/** The status a booking is written with: confirmed when the mail said so, pending otherwise. */
|
||||
function statusOf(item: BookingImportPreviewItem): string {
|
||||
const status = item.metadata?.reservationStatus;
|
||||
return typeof status === 'string' && /confirm/i.test(status) ? 'confirmed' : 'pending';
|
||||
}
|
||||
|
||||
/** A hotel's stay: its days by check-in and check-out date, its times of day alone. */
|
||||
function stayOf(
|
||||
stay: NonNullable<BookingImportPreviewItem['_accommodation']>,
|
||||
|
||||
@@ -588,6 +588,20 @@ describe('booking change cards', () => {
|
||||
expect(appliedCardOf('import_booking', { args: {}, result: 'Not added.', preview })).toBeNull();
|
||||
});
|
||||
|
||||
// #3238: a booking the file calls confirmed is saved confirmed, and the card says so.
|
||||
it('ASTBOOK-016s: a booking the file calls confirmed is drawn confirmed, one it says nothing about without a status', () => {
|
||||
const flight = {
|
||||
type: 'flight',
|
||||
title: 'Kuala Lumpur to Bangkok',
|
||||
reservation_time: '2026-06-03T08:15',
|
||||
source: { fileName: 'airasia.eml', index: 0 },
|
||||
};
|
||||
const confirmed = changeCard('import_booking', { ...flight, metadata: { reservationStatus: 'confirmed' } });
|
||||
expect(first(parsed(confirmed.card))).toMatchObject({ status: 'confirmed' });
|
||||
const silent = changeCard('import_booking', flight);
|
||||
expect(first(parsed(silent.card))).toMatchObject({ status: null });
|
||||
});
|
||||
|
||||
it('ASTBOOK-018: an applied flight from a file keeps its route, times and price, and can show it on the map', () => {
|
||||
const args = {
|
||||
type: 'flight',
|
||||
|
||||
@@ -450,6 +450,28 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
|
||||
source: { fileName: 'ticket.pdf', index: 0 },
|
||||
};
|
||||
|
||||
// #3238: the status the document states goes on the booking; a booking it says nothing about stays pending.
|
||||
it('BOOKING-IMPORT-TX-STATUS: writes a confirmed booking as confirmed and anything else as pending', async () => {
|
||||
const { svc, reservations } = makeConfirm();
|
||||
|
||||
await svc.confirm(
|
||||
'5',
|
||||
1,
|
||||
[{ ...priced, metadata: { ...priced.metadata, reservationStatus: 'confirmed' } } as never],
|
||||
'sock',
|
||||
);
|
||||
await svc.confirm(
|
||||
'5',
|
||||
1,
|
||||
[{ ...priced, metadata: { ...priced.metadata, reservationStatus: 'cancelled' } } as never],
|
||||
'sock',
|
||||
);
|
||||
await svc.confirm('5', 1, [priced as never], 'sock');
|
||||
|
||||
const statuses = reservations.createWithCostInTx.mock.calls.map((call) => (call as unknown[])[1]);
|
||||
expect(statuses.map((data) => (data as { status?: string }).status)).toEqual(['confirmed', 'pending', 'pending']);
|
||||
});
|
||||
|
||||
it('BOOKING-IMPORT-TX-001: freezes the rate first, writes booking and cost in one call, announces the cost after the booking', async () => {
|
||||
const { svc, reservations, order, costEvents } = makeConfirm();
|
||||
|
||||
|
||||
@@ -680,3 +680,53 @@ describe('kitinerary mapper: the seat on each leg of a connecting flight', () =>
|
||||
expect(legsMeta[1]).toMatchObject({ seat: '40A' });
|
||||
});
|
||||
});
|
||||
|
||||
// #3238: a booking the document calls confirmed is imported as confirmed.
|
||||
describe('kitinerary mapper: the reservation status the document states', () => {
|
||||
it('carries a confirmed status, however schema.org spells it, on a flight, a connecting flight and a train', () => {
|
||||
const one = { ...flight('CE9P8V', SFO, JFK, '2026-06-11T10:00:00', '2026-06-11T18:30:00', '450') };
|
||||
const spelled = [
|
||||
'http://schema.org/ReservationConfirmed',
|
||||
'https://schema.org/ReservationConfirmed',
|
||||
'ReservationConfirmed',
|
||||
'confirmed',
|
||||
];
|
||||
for (const reservationStatus of spelled) {
|
||||
const { items } = mapReservations(legs({ ...one, reservationStatus } as never), 'test.json');
|
||||
expect(items[0].metadata).toMatchObject({ reservationStatus: 'confirmed' });
|
||||
}
|
||||
const first = {
|
||||
...flight('ABC123', FRA, BER, '2026-06-11T10:00:00', '2026-06-11T12:00:00', 'LH 100'),
|
||||
reservationStatus: 'ReservationConfirmed',
|
||||
};
|
||||
const second = {
|
||||
...flight('ABC123', BER, HND, '2026-06-11T14:30:00', '2026-06-11T23:30:00', 'LH 200'),
|
||||
reservationStatus: 'ReservationConfirmed',
|
||||
};
|
||||
const { items: grouped } = mapReservations(legs(first as never, second as never), 'test.json');
|
||||
expect(grouped).toHaveLength(1);
|
||||
expect(grouped[0].metadata).toMatchObject({ reservationStatus: 'confirmed' });
|
||||
const rail = train('BAOLAU1', KLU, VIL, '2026-07-04T06:12:00', '2026-07-04T06:30:00', 'SE1', {
|
||||
reservationStatus: 'http://schema.org/ReservationConfirmed',
|
||||
});
|
||||
const { items: trains } = mapReservations([rail] as unknown as KiReservation[], 'baolau.pdf');
|
||||
expect(trains[0].metadata).toMatchObject({ reservationStatus: 'confirmed' });
|
||||
});
|
||||
|
||||
it('reads a cancellation and a pending booking, and leaves an unknown or missing status out', () => {
|
||||
const base = flight('CE9P8V', SFO, JFK, '2026-06-11T10:00:00', '2026-06-11T18:30:00', '450');
|
||||
const statusOf = (reservationStatus?: unknown) =>
|
||||
mapReservations(
|
||||
legs({ ...base, ...(reservationStatus === undefined ? {} : { reservationStatus }) } as never),
|
||||
'test.json',
|
||||
).items[0].metadata?.reservationStatus;
|
||||
expect(statusOf('http://schema.org/ReservationCancelled')).toBe('cancelled');
|
||||
expect(statusOf('canceled')).toBe('cancelled');
|
||||
expect(statusOf('ReservationPending')).toBe('pending');
|
||||
expect(statusOf('ReservationHold')).toBe('pending');
|
||||
expect(statusOf('unconfirmed')).toBeUndefined();
|
||||
expect(statusOf('Gibberish')).toBeUndefined();
|
||||
expect(statusOf(42)).toBeUndefined();
|
||||
expect(statusOf()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,17 @@ describe('llm-prompt', () => {
|
||||
expect(prompt).toContain('never repeat it on each leg');
|
||||
});
|
||||
|
||||
// #3238: a schema-constrained provider fills declared properties only, so the status is declared too.
|
||||
it('asks for the booking status the document states and declares it', () => {
|
||||
const prompt = buildSystemPrompt();
|
||||
expect(prompt).toContain('"reservationStatus"');
|
||||
expect(item.properties.reservationStatus).toEqual({
|
||||
type: 'string',
|
||||
enum: ['ReservationConfirmed', 'ReservationPending', 'ReservationCancelled'],
|
||||
});
|
||||
expect(item.required).not.toContain('reservationStatus');
|
||||
});
|
||||
|
||||
it('instructs JSON-only output wrapped in reservations', () => {
|
||||
const prompt = buildSystemPrompt();
|
||||
expect(prompt).toMatch(/"reservations"/);
|
||||
|
||||
@@ -143,6 +143,11 @@ export const KI_RESERVATION_JSON_SCHEMA = {
|
||||
properties: {
|
||||
'@type': { type: 'string', enum: [...KI_RESERVATION_TYPES] },
|
||||
reservationNumber: { type: 'string' },
|
||||
// What the document says about the booking (#3238); left out when it says nothing.
|
||||
reservationStatus: {
|
||||
type: 'string',
|
||||
enum: ['ReservationConfirmed', 'ReservationPending', 'ReservationCancelled'],
|
||||
},
|
||||
// Hotel check-in/out, car pickup/dropoff, event/restaurant start/end —
|
||||
// plain ISO 8601 strings (no KDE QDateTime wrapper).
|
||||
checkinTime: { type: 'string' },
|
||||
|
||||
@@ -10,7 +10,9 @@ import {
|
||||
ROADTRIP_RESERVATION_TYPES,
|
||||
TRANSPORT_RESERVATION_TYPES,
|
||||
TRAVEL_RESERVATION_TYPES,
|
||||
importedReservationStatus,
|
||||
isTransportReservationType,
|
||||
readReservationStatus,
|
||||
reservationTypeInfo,
|
||||
} from './reservation-types';
|
||||
import { reservationSchema, reservationStatusSchema, reservationTypeSchema } from './reservation.schema';
|
||||
@@ -108,3 +110,30 @@ describe('reservation response type and status', () => {
|
||||
expect(reservationSchema.parse(row)).toMatchObject({ type: 'balloon' });
|
||||
});
|
||||
});
|
||||
|
||||
// #3238: the status a booking document states, and the one an import saves.
|
||||
describe('readReservationStatus / importedReservationStatus', () => {
|
||||
it('reads schema.org and plain spellings, and nothing else', () => {
|
||||
expect(readReservationStatus('http://schema.org/ReservationConfirmed')).toBe('confirmed');
|
||||
expect(readReservationStatus('https://schema.org/ReservationConfirmed')).toBe('confirmed');
|
||||
expect(readReservationStatus(' ReservationConfirmed ')).toBe('confirmed');
|
||||
expect(readReservationStatus('Confirmed')).toBe('confirmed');
|
||||
expect(readReservationStatus('http://schema.org/ReservationCancelled')).toBe('cancelled');
|
||||
expect(readReservationStatus('canceled')).toBe('cancelled');
|
||||
expect(readReservationStatus('ReservationHold')).toBe('pending');
|
||||
expect(readReservationStatus('ReservationPending')).toBe('pending');
|
||||
expect(readReservationStatus('unconfirmed')).toBeUndefined();
|
||||
expect(readReservationStatus('')).toBeUndefined();
|
||||
expect(readReservationStatus(null)).toBeUndefined();
|
||||
expect(readReservationStatus(1)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('saves an import confirmed only when the document said so', () => {
|
||||
expect(importedReservationStatus({ reservationStatus: 'confirmed' })).toBe('confirmed');
|
||||
expect(importedReservationStatus({ reservationStatus: 'ReservationConfirmed' })).toBe('confirmed');
|
||||
expect(importedReservationStatus({ reservationStatus: 'cancelled' })).toBe('pending');
|
||||
expect(importedReservationStatus({})).toBe('pending');
|
||||
expect(importedReservationStatus(null)).toBe('pending');
|
||||
expect(importedReservationStatus(undefined)).toBe('pending');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -135,3 +135,31 @@ export function isTransportReservationType(type: string | null | undefined): boo
|
||||
/** The statuses a reservation can be in. A row without one reads as `pending`. */
|
||||
export const RESERVATION_STATUSES = ['pending', 'confirmed', 'cancelled'] as const;
|
||||
export type ReservationStatus = (typeof RESERVATION_STATUSES)[number];
|
||||
|
||||
/**
|
||||
* The status a booking document states, as TREK writes it: schema.org's
|
||||
* `ReservationConfirmed` (bare or as a schema.org URL) or a plain `confirmed`
|
||||
* is confirmed, a cancellation is cancelled, a booking held or pending is
|
||||
* pending. Anything else says nothing, so the caller keeps its own default.
|
||||
*/
|
||||
export function readReservationStatus(value: unknown): ReservationStatus | undefined {
|
||||
if (typeof value !== 'string') return undefined;
|
||||
const word = value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^https?:\/\/schema\.org\//, '')
|
||||
.replace(/^reservation/, '');
|
||||
if (word === 'confirmed') return 'confirmed';
|
||||
if (word === 'cancelled' || word === 'canceled') return 'cancelled';
|
||||
if (word === 'pending' || word === 'hold') return 'pending';
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The status an imported booking is saved with (#3238): confirmed when the
|
||||
* document said so, pending otherwise. A cancellation is no status to add a
|
||||
* booking with, so it stays pending here; the mail import refuses it before.
|
||||
*/
|
||||
export function importedReservationStatus(metadata: Record<string, unknown> | null | undefined): ReservationStatus {
|
||||
return readReservationStatus(metadata?.reservationStatus) === 'confirmed' ? 'confirmed' : 'pending';
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user