mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 00:43:15 +00:00
fix(mail-ingest): keep flight-like IDs from overriding bookings
Recognize compound booking references separately from flight numbers. Require flight evidence before overriding named lodging or restaurant types so a local mail reader keeps the intended schema. Closes #3271
This commit is contained in:
@@ -17,6 +17,7 @@
|
||||
* flight take minutes on a CPU host. The flat results map into the kitinerary pipeline via the
|
||||
* existing `nuExtractToKiReservations` mapper, so nothing downstream changes.
|
||||
*/
|
||||
import { airportByCode } from '../../airports/airports.contract';
|
||||
import type { KiReservation } from '../../booking-import/kitinerary.types';
|
||||
import { nuExtractToKiReservations } from '../clients/nuextract';
|
||||
import { parseLenientJson } from '../lenient-json';
|
||||
@@ -109,6 +110,22 @@ const TYPE_KEYWORDS: [FlatType, RegExp][] = [
|
||||
*/
|
||||
const EVENT_KEYWORDS = /\b(ticket|concert|konzert|veranstaltung|eintritt|admission)\b/i;
|
||||
|
||||
const FLIGHT_NUMBER_LABEL =
|
||||
/\b(?:flight(?:[ \t]+(?:number|no\.?))?|(?:hin|rück|rueck)?flug(?:nummer|nr\.?)?)[ \t\r\n:#]*$/i;
|
||||
const BOOKING_REFERENCE_LABEL =
|
||||
/\b(?:(?:trip|booking|reservation)[ \t]+(?:id|ref(?:erence)?|code|no\.?|number)|confirmation(?:[ \t]+(?:id|code|number))?|pnr|reference|buchungs(?:code|nummer|referenz)|reservierungsnummer|reiseplan|best(?:ä|ae)tigungs[- \t]?(?:code|nummer))[ \t\r\n:#]*$/i;
|
||||
const AIRPORT_PAIR = /\b([A-Z]{3})[ \t]*(?:->|[–—/→-])[ \t]*([A-Z]{3})\b/g;
|
||||
const FLIGHT_CONTEXT = 64;
|
||||
|
||||
/** Itinerary tables may put their route beside or on the line next to the flight number. */
|
||||
function hasNearbyAirportPair(before: string, number: string, after: string): boolean {
|
||||
const context = before.split('\n').slice(-2).join('\n') + number + after.split('\n').slice(0, 2).join('\n');
|
||||
for (const [, from, to] of context.matchAll(AIRPORT_PAIR)) {
|
||||
if (from && to && from !== to && airportByCode(from) && airportByCode(to)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The transport half of the table, for the flight gate in readType. */
|
||||
const TRANSPORT_FLAT_TYPES = new Set<FlatType>(['train', 'bus', 'ferry', 'car']);
|
||||
|
||||
@@ -126,10 +143,9 @@ interface TypeReading {
|
||||
function readType(text: string): TypeReading {
|
||||
const named = TYPE_KEYWORDS.filter(([, re]) => re.test(text)).map(([type]) => type);
|
||||
// The flight path forces type 'flight' on everything it returns, so it must not
|
||||
// claim a document that names another kind of transport: a German rail ticket
|
||||
// carries numbers like "IC 2023" or "RE 4711", which the two-letters-plus-digits
|
||||
// test cannot tell from an airline code (#2076).
|
||||
if (detectFlightNumbers(text).length > 0 && !named.some((type) => TRANSPORT_FLAT_TYPES.has(type))) {
|
||||
// claim another transport booking (#2076). A code alone cannot override a
|
||||
// named non-transport type either: it may be that booking's reference (#3271).
|
||||
if (!named.some((type) => TRANSPORT_FLAT_TYPES.has(type)) && detectFlightNumbers(text, named.length > 0).length > 0) {
|
||||
return { type: 'flight', candidates: [] };
|
||||
}
|
||||
if (named.length > 1) return { type: null, candidates: named };
|
||||
@@ -137,14 +153,23 @@ function readType(text: string): TypeReading {
|
||||
return { type: EVENT_KEYWORDS.test(text) ? 'event' : null, candidates: [] };
|
||||
}
|
||||
|
||||
/** Detect flight numbers (order-preserving, deduped) — also the "is this a flight doc" test. */
|
||||
export function detectFlightNumbers(text: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const m of text.matchAll(/\b([A-Z]{2})\s?(\d{2,4})\b/g)) {
|
||||
const fn = `${m[1]}${m[2]}`;
|
||||
if (!out.includes(fn)) out.push(fn);
|
||||
/** Flight numbers in document order. When another type is named, require evidence beside each code. */
|
||||
export function detectFlightNumbers(text: string, requireDetails = false): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const match of text.matchAll(/\b([A-Z]{2})\s?(\d{2,4})\b/g)) {
|
||||
const start = match.index;
|
||||
const end = start + match[0].length;
|
||||
const before = text.slice(Math.max(0, start - FLIGHT_CONTEXT), start);
|
||||
if (BOOKING_REFERENCE_LABEL.test(before)) continue;
|
||||
const labelled = FLIGHT_NUMBER_LABEL.test(before);
|
||||
const after = text.slice(end, end + FLIGHT_CONTEXT);
|
||||
// A numeric segment joined by a hyphen usually belongs to a compound reference.
|
||||
// An explicit flight label still allows a number followed by a date.
|
||||
if (!labelled && (/\d-$/.test(before) || /^-\d/.test(after))) continue;
|
||||
if (requireDetails && !labelled && !hasNearbyAirportPair(before, match[0], after)) continue;
|
||||
out.add(`${match[1]}${match[2]}`);
|
||||
}
|
||||
return out;
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
routeImageExtraction,
|
||||
} from '../../../../src/nest/llm-parse/router/extraction-router';
|
||||
import { FLAT_SCHEMA_BY_TYPE, FLIGHTS_ARRAY_SCHEMA } from '../../../../src/nest/llm-parse/router/flat-schemas';
|
||||
import { fitTextWindow } from '../../../../src/nest/llm-parse/text-window';
|
||||
import { fitTextWindow, LOCAL_TEXT_WINDOW } from '../../../../src/nest/llm-parse/text-window';
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
@@ -88,6 +88,14 @@ describe('detectFlightNumbers', () => {
|
||||
it('returns [] when there is no flight-number pattern', () => {
|
||||
expect(detectFlightNumbers('A hotel booking with no flight codes')).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores flight-like fragments of compound numeric references (#3271)', () => {
|
||||
expect(detectFlightNumbers('ZO-AX1234-00001, 00002-AX2345-ZO, then LH400-FRA.')).toEqual(['LH400']);
|
||||
});
|
||||
|
||||
it('keeps a labelled flight number before a date and skips labelled booking references (#3271)', () => {
|
||||
expect(detectFlightNumbers('Trip ID: AX1234\nFlight number: LH400-12 DEC\nBooking No.: AX4567')).toEqual(['LH400']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fixArrivalDate', () => {
|
||||
@@ -155,6 +163,40 @@ describe('routeExtraction', () => {
|
||||
expect(flats[0].type).toBe('hotel');
|
||||
});
|
||||
|
||||
it.each([
|
||||
'Trip ID: ZO-AX1234-00001',
|
||||
'Trip ID: AX1234',
|
||||
'Trip ID: AX1234\nPlease send your flight number for airport pickup.',
|
||||
'Rate AX1234\nVAT-REG: 123456',
|
||||
])('reads a hotel confirmation with a reference line %j (#3271)', async (reference) => {
|
||||
const header = `Hotel Sol\n${reference}\nCheck-in: 3 Dec 2026\nCheck-out: 6 Dec 2026\n`;
|
||||
const boilerplate = 'Booking conditions apply.\n'.repeat(250);
|
||||
const { text } = fitTextWindow(`${header}${boilerplate}Cruise offers\n${boilerplate}`, LOCAL_TEXT_WINDOW);
|
||||
expect(text).not.toContain('Cruise offers');
|
||||
const hotel = { name: 'Hotel Sol', checkin_time: '2026-12-03T15:00:00', checkout_time: '2026-12-06T11:00:00' };
|
||||
extractEnforced.mockImplementation(async ({ schema }) =>
|
||||
schema === FLAT_SCHEMA_BY_TYPE.hotel ? hotel : { flights: [] },
|
||||
);
|
||||
mapToKi.mockImplementationOnce((flats) => (flats.length ? [{ '@type': 'LodgingReservation' }] : []));
|
||||
|
||||
const result = await routeExtraction(text, CTX);
|
||||
|
||||
expect(extractEnforced).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ schema: FLAT_SCHEMA_BY_TYPE.hotel }),
|
||||
);
|
||||
expect(mapToKi.mock.calls[0][0]).toEqual([{ ...hotel, type: 'hotel' }]);
|
||||
expect(result).toEqual({ kiItems: [{ '@type': 'LodgingReservation' }], warnings: [], outcome: 'ok' });
|
||||
});
|
||||
|
||||
it('keeps a restaurant booking with a flight-like reference on its own schema (#3271)', async () => {
|
||||
extractEnforced.mockResolvedValue({ name: 'Sol', start_time: '2026-12-03T19:00:00' });
|
||||
await routeExtraction('Restaurant Sol\nBooking No.: AX1234\nPlease add your flight number if arriving today.', CTX);
|
||||
expect(extractEnforced).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ schema: FLAT_SCHEMA_BY_TYPE.restaurant }),
|
||||
);
|
||||
expect(mapToKi.mock.calls[0][0][0].type).toBe('restaurant');
|
||||
});
|
||||
|
||||
it('falls back to the union schema and the model-picked type for an unclear document', async () => {
|
||||
extractEnforced.mockResolvedValue({ type: 'event', name: 'Concert' });
|
||||
const res = await routeExtraction('A document with no obvious type keywords', CTX);
|
||||
@@ -389,6 +431,20 @@ describe('documents that name more than one type', () => {
|
||||
expect(mapToKi.mock.calls[0][0][0].type).toBe('flight');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['Lufthansa LH 400 FRA-JFK. Hotels in New York.', 'LH400', 'FRA', 'JFK'],
|
||||
['Confirmación de vuelo\nIB 3178\nMAD / LIS\nHotel recomendado', 'IB3178', 'MAD', 'LIS'],
|
||||
['Flight number: LH400-12 DEC\nHotels in New York.', 'LH400', 'FRA', 'JFK'],
|
||||
])(
|
||||
'keeps the itinerary %j with hotel offers on the flight path (#3271)',
|
||||
async (itinerary, vehicle_number, from_code, to_code) => {
|
||||
extractEnforced.mockResolvedValue({ flights: [{ vehicle_number, from_code, to_code }] });
|
||||
await routeExtraction(itinerary, CTX);
|
||||
expect(sentSchema()).toBe(FLIGHTS_ARRAY_SCHEMA);
|
||||
expect(mapToKi.mock.calls[0][0][0].type).toBe('flight');
|
||||
},
|
||||
);
|
||||
|
||||
it('reads the event words only when the document names no other type', async () => {
|
||||
extractEnforced.mockResolvedValue({ name: 'Concert' });
|
||||
await routeExtraction('Concert ticket. Doors open 19:00.', CTX);
|
||||
|
||||
Reference in New Issue
Block a user