fix(booking-import): stop writing an unreadable type down as a hotel (#2076)

When neither the keyword table nor the model produced a type, the router wrote
"hotel" and cast whatever string it got to FlatType without checking it. A hotel
is a booking type, so a ferry voucher imported from the Transport tab opened the
booking form, which offers six chips and not one transport among them, and
"other" was the only honest pick left. An unrecognised string got through the
cast too and then vanished silently in nuExtractToKiReservations.

The type is validated against FLAT_TYPES now. When it cannot be read the item is
still extracted with the lodging shape so it survives mapping, but it says so,
and the tie-breaker #2080 added finally has something to fire on: isUnplaceableItem
only ever matched a type outside both form's vocabularies, and the server can
only emit its own eight, so on a real document it never matched at all.

The tab travels with the job instead of sitting in component state. The parse
deliberately outlives navigation and reload and the review is triggered by the
global widget on any page, so by the time it ran the state had remounted back to
its default and the context was gone.
This commit is contained in:
Maurice
2026-08-28 13:23:23 +02:00
committed by Maurice
parent 016fdeec64
commit 130272cfb0
12 changed files with 175 additions and 28 deletions
@@ -127,6 +127,11 @@ export interface KiEvent {
/** A single output node from kitinerary-extractor's JSON array */
export interface KiReservation {
'@type': string;
/**
* TREK's own marker, not schema.org: the extractor could not read a type and
* fell back to the lodging shape so the item would survive mapping (#2076).
*/
trekTypeGuessed?: boolean;
reservationNumber?: string;
checkinTime?: KiDateTimeish;
checkoutTime?: KiDateTimeish;
@@ -182,6 +187,8 @@ export interface ParsedAccommodation {
*/
export interface ParsedBookingItem {
type: string;
/** The type was filled in, not read from the document (#2076). */
type_guessed?: boolean;
title: string;
reservation_time?: string | null;
reservation_end_time?: string | null;
@@ -170,6 +170,9 @@ function buildNode(x: Record<string, unknown>): Record<string, unknown> | undefi
const node: Record<string, unknown> = {
'@type': atType,
// Not a schema.org field: it says the router had to guess the type, so the
// importer can offer the form the user was importing into (#2076).
...(x.type_guessed === true ? { trekTypeGuessed: true } : {}),
reservationNumber: x.booking_reference,
seat: x.seat,
class: x.travel_class,
@@ -18,9 +18,10 @@
* existing `nuExtractToKiReservations` mapper, so nothing downstream changes.
*/
import { normalizeLocalDateTime } from '@trek/shared';
import type { KiReservation } from '../../booking-import/kitinerary.types';
import { nuExtractToKiReservations } from '../clients/nuextract';
import { FLAT_SCHEMA_BY_TYPE, FLIGHTS_ARRAY_SCHEMA, UNION_SINGLE_SCHEMA, type FlatType, type FlatLike } from './flat-schemas';
import { FLAT_SCHEMA_BY_TYPE, FLAT_TYPES, FLIGHTS_ARRAY_SCHEMA, UNION_SINGLE_SCHEMA, type FlatType, type FlatLike } from './flat-schemas';
import { extractEnforced } from './ollama-format.client';
export interface RouterContext {
@@ -38,9 +39,9 @@ const TYPE_HINT: Record<FlatType, string> = {
train: 'train. from_name/to_name = stations, vehicle_number = train number, times = full ISO, price/currency = total fare.',
bus: 'bus. from_name/to_name = stops, times = full ISO, price/currency = total fare.',
ferry: 'ferry/cruise. from_name/to_name = terminals/ports, times = full ISO, price/currency = total fare.',
car: 'rental car. operator = the rental company, from_name = pick-up location, to_name = return location (may differ), departure_time = pick-up, arrival_time = return, price/currency = total rental cost.',
car: 'rental car. operator = the rental company, from_name = pick-up location, to_name = return location (may differ), departure_time = pick-up, arrival_time = return, times = full ISO (24-hour), price/currency = total rental cost.',
hotel: 'hotel stay. name = hotel name, address = the hotel street address, checkin_time/checkout_time = full ISO date-time, price/currency = total paid.',
restaurant: 'restaurant booking. name = the restaurant, address = its street address, start_time = the reservation date-time, price/currency = total if shown.',
restaurant: 'restaurant booking. name = the restaurant, address = its street address, start_time = the reservation date-time as full ISO (24-hour), price/currency = total if shown.',
event: 'event/attraction. name = the event/ticket, address = the venue, start_time/end_time = full ISO, price/currency = ticket price.',
};
@@ -150,8 +151,14 @@ export function extractTotalPrice(text: string): { price: string; currency?: str
*/
export function fixArrivalDate(flat: FlatLike): FlatLike {
if (!TRANSPORT_TYPES.includes(flat.type)) return flat;
const dep = /(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(String(flat.departure_time ?? ''));
const arr = /(\d{2}:\d{2})/.exec(String(flat.arrival_time ?? ''));
// Both sides go through the 12-hour normalizer first. Reading the arrival
// with a bare /(\d{2}:\d{2})/ used to throw a trailing "PM" away, and the
// comparison below is lexicographic: "04:00" < "12:40" rolled a 13:11
// arrival onto the next day and turned a short hop into an overnight (#2094).
const depSource = normalizeLocalDateTime(String(flat.departure_time ?? ''));
const arrSource = normalizeLocalDateTime(String(flat.arrival_time ?? ''));
const dep = /(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(depSource);
const arr = /(\d{2}:\d{2})/.exec(arrSource.slice(10));
if (!dep || !arr) return flat;
const [, depDate, depTime] = dep;
const arrTime = arr[1];
@@ -167,16 +174,25 @@ const DATE_FIELDS = ['departure_time', 'arrival_time', 'checkin_time', 'checkout
* Coerce a date value to ISO 8601. Models occasionally ignore the format instruction and
* emit a natural-language date ("Aug 23 2025 13:30"), which the downstream `splitIso` then
* slices into garbage ("Aug 23 202"). Keep already-ISO values untouched; otherwise parse and
* reformat. (The server runs in UTC, so the components line up.)
* reformat.
*
* These fields are naive local wall-clock strings everywhere else in TREK, so the components
* are read back locally. Reading with Date.parse and printing with getUTC* used to shift every
* such value by the container's UTC offset, which docker-compose sets from TZ and documents
* with Europe/Berlin. That is why a rental car came back off by the offset rather than by
* twelve hours: only `car` and `restaurant` lack the full-ISO instruction in TYPE_HINT, so
* only they reach this parse at all (#2094).
*/
function toIso(value: unknown): unknown {
if (typeof value !== 'string' || !value.trim()) return value;
if (/^\d{4}-\d{2}-\d{2}/.test(value)) return value;
// An ISO date with a printed meridiem behind it ("2026-06-11T02:30 PM") is not
// already ISO, it only looks like it. Resolve the clock, keep everything else.
if (/^\d{4}-\d{2}-\d{2}/.test(value)) return normalizeLocalDateTime(value);
const t = Date.parse(value);
if (Number.isNaN(t)) return value;
const d = new Date(t);
const p = (n: number) => String(n).padStart(2, '0');
return `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}T${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:00`;
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}:00`;
}
/** Normalize every date-ish field on a flat reservation to ISO before mapping. */
@@ -213,8 +229,21 @@ async function extractSingle(text: string, ctx: RouterContext): Promise<FlatLike
return fixArrivalDate(normalizeDates({ ...out, type: known }));
}
const out = (await call(UNION_SINGLE_SCHEMA, 'Pick the correct "type".')) ?? {};
const type = (typeof out.type === 'string' ? out.type : 'hotel') as FlatType;
return fixArrivalDate(normalizeDates({ ...out, type }));
// "I could not tell" used to be written down as "hotel", and a hotel is a
// booking, so a ferry voucher imported from the Transport tab opened the
// booking form with no transport type to pick and stayed 'other' (#2076).
// An unvalidated cast also let any string through, and the item then vanished
// silently in nuExtractToKiReservations, which drops an unmapped type.
const raw = typeof out.type === 'string' ? out.type.toLowerCase().trim() : '';
const picked = (FLAT_TYPES as string[]).includes(raw) ? (raw as FlatType) : null;
// Still extract with the hotel shape so the item survives the mapping, but say
// out loud that the type was guessed. Only here: a valid pick by the model is
// a real answer, and flagging it would push AI-parsed hotels into the
// transport form whenever the document never says the word "hotel".
const flat: FlatLike = picked
? { ...out, type: picked }
: { ...out, type: 'hotel' as FlatType, type_guessed: true };
return fixArrivalDate(normalizeDates(flat));
}
/**
@@ -23,6 +23,13 @@ export const FLAT_TYPES: FlatType[] = ['flight', 'train', 'bus', 'ferry', 'car',
* are the ones the router reads directly; the index signature carries the rest unchanged. */
export interface FlatLike {
type: FlatType;
/**
* The type was not read from the document, it was filled in because neither the
* keyword table nor the model produced a valid one. The extractor still uses the
* hotel shape so the item survives mapping, but the flag rides along so the
* importer opens the form the user was actually importing into (#2076).
*/
type_guessed?: boolean;
booking_reference?: string;
vehicle_number?: string;
from_code?: string;