fix(import): a booking the AI reads without its venue is asked for one, and a failed import does not look like a success

Gemini behind the OpenAI-compatible provider decodes against the JSON schema
TREK sends and fills declared properties only. reservationFor was an open
object without any, so the model left it out: a Booking.com stay came back
with its dates and price but no hotel name, and the mapper had to drop it
(#2477). It is the same cause as #1638, whose fix only made the JSON readable.

The schema now declares every field the prompt names inside reservationFor,
for venues, flights, trains, buses, boats, events and rental cars, at most two
levels deep, and requires it; the car desks at the root get the same venue
fields. Every object stays open to keys the prompt does not name.

On the cloud AI path an answer is cleaned up before it is mapped. Exact
duplicate nodes are dropped, so one stay is one booking. priceCurrency is read
as an ISO 4217 code ("EURials" is EUR, a lone symbol maps to its code); when
the model names none, a priced node takes the currency of the document's
total, and otherwise the field goes instead of saving a code nobody can
convert. The kitinerary path is untouched.

The import upload decodes file names as UTF-8 like every other upload route.
"Bestätigung.pdf" reached the warnings as mojibake, and the review could not
attach the file to the booking it created, because it matches on the name.
The OpenAI-compatible client logs which response_format the answering
attempt carried, metadata only, so the next report shows whether the schema
reached the model at all.

The background import card showed a green tick beside "no reservations could
be extracted". A parse that found nothing now wears the warning mark instead;
it is the same card on the desktop and on the phone.
This commit is contained in:
Maurice
2026-09-23 15:50:43 +02:00
parent 05f533dd0d
commit 41b14ebc2a
14 changed files with 752 additions and 18 deletions
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpException } from '@nestjs/common';
import { HttpException, type Type } from '@nestjs/common';
import { INTERCEPTORS_METADATA } from '@nestjs/common/constants';
import { ReservationImportController } from '../../../../src/nest/reservation-import/reservation-import.controller';
import type { BookingImportService } from '../../../../src/nest/booking-import/booking-import.service';
import type { User } from '../../../../src/types';
@@ -60,3 +61,22 @@ describe('ReservationImportController.preview', () => {
expect(svc.preview).toHaveBeenCalledWith([expect.anything()], 'no-ai', 1);
});
});
/**
* Multer decodes a multipart filename as latin1 unless told otherwise, and the
* booking import did not tell it: "Bestätigung.pdf" reached the warnings as
* "Bestätigung.pdf", and the review could not attach the file it no longer
* recognised by name (#2477). Read off the interceptor both upload routes carry.
*/
describe('ReservationImportController upload options', () => {
const multerOf = (handler: keyof ReservationImportController) => {
const [Interceptor] = Reflect.getMetadata(INTERCEPTORS_METADATA, ReservationImportController.prototype[handler]) as Type<{ multer: { defParamCharset: string; limits: unknown } }>[];
return new Interceptor().multer;
};
it.each(['preview', 'previewAsync'] as const)('%s decodes non-ASCII filenames as UTF-8', (handler) => {
const multer = multerOf(handler);
expect(multer.defParamCharset).toBe('utf8');
expect(multer.limits).toEqual({ fileSize: 10 * 1024 * 1024, files: 5 });
});
});
@@ -287,6 +287,38 @@ describe('OpenAiCompatibleClient', () => {
parts = JSON.parse((fetchFn.mock.calls[1][1] as RequestInit).body as string).messages[1].content;
expect(parts.every((p: any) => p.type !== 'file' && p.type !== 'image_url')).toBe(true);
});
/**
* A report could not say whether the schema ever reached the model or the
* ladder had fallen back to the prompt alone (#2477). The debug line names
* the rung that answered, and nothing of the booking.
*/
it('logs which response_format the answering attempt carried (#2477)', async () => {
const debug = vi.spyOn(console, 'debug').mockImplementation(() => {});
const ok = () => jsonResponse({ choices: [{ message: { content: '{"reservations":[]}' } }] });
const refused = () => jsonResponse({ error: 'no' }, false, 400);
const lines = () => debug.mock.calls.map(c => String(c[0])).filter(l => l.includes('response_format='));
try {
safeFetchLlmMock.mockResolvedValueOnce(ok());
await new OpenAiCompatibleClient().extract(baseInput);
safeFetchLlmMock.mockResolvedValueOnce(refused()).mockResolvedValueOnce(ok());
await new OpenAiCompatibleClient().extract(baseInput);
safeFetchLlmMock.mockResolvedValueOnce(refused()).mockResolvedValueOnce(refused()).mockResolvedValueOnce(ok());
await new OpenAiCompatibleClient().extract(baseInput);
safeFetchLlmMock.mockResolvedValueOnce(jsonResponse({ choices: [{ message: { content: '{}' } }] }));
await new OpenAiCompatibleClient().extract({ ...baseInput, model: 'hf.co/numind/NuExtract-2.0-2B-GGUF:latest' });
expect(lines()).toEqual([
'[DEBUG] LLM answered with response_format=json_schema',
'[DEBUG] LLM answered with response_format=json_object',
'[DEBUG] LLM answered with response_format=none',
'[DEBUG] LLM answered with response_format=none',
]);
expect(debug.mock.calls.flat().join(' ')).not.toContain('Flight AB123');
} finally {
debug.mockRestore();
}
});
});
describe('OpenAiCompatibleClient — NuExtract path', () => {
@@ -0,0 +1,52 @@
import { describe, it, expect } from 'vitest';
import { toIsoCurrency } from '../../../../src/nest/llm-parse/currency-code';
describe('toIsoCurrency', () => {
it('keeps an ISO 4217 code in any case and spacing', () => {
expect(toIsoCurrency('EUR')).toBe('EUR');
expect(toIsoCurrency('eur')).toBe('EUR');
expect(toIsoCurrency(' chf ')).toBe('CHF');
expect(toIsoCurrency('ALL')).toBe('ALL');
});
it('reads a value that starts with a real code as that code (#2477)', () => {
expect(toIsoCurrency('EURials')).toBe('EUR');
expect(toIsoCurrency('Euros')).toBe('EUR');
expect(toIsoCurrency('EUR 89,35')).toBe('EUR');
});
it('maps a currency symbol that stands alone', () => {
expect(toIsoCurrency('€')).toBe('EUR');
expect(toIsoCurrency('£')).toBe('GBP');
expect(toIsoCurrency('¥')).toBe('JPY');
expect(toIsoCurrency(' $ ')).toBe('USD');
});
it('answers undefined for anything that is not a currency it can name', () => {
// The lek is ALL; LEK is no code, and its prefix is none either.
expect(toIsoCurrency('LEK')).toBeUndefined();
expect(toIsoCurrency('XYZ')).toBeUndefined();
// A dollar with a country in front is not guessed as USD.
expect(toIsoCurrency('CA$')).toBeUndefined();
expect(toIsoCurrency('US$')).toBeUndefined();
expect(toIsoCurrency('€€')).toBeUndefined();
expect(toIsoCurrency('')).toBeUndefined();
expect(toIsoCurrency(' ')).toBeUndefined();
});
it('answers undefined for a value that is not a string', () => {
expect(toIsoCurrency(null)).toBeUndefined();
expect(toIsoCurrency(undefined)).toBeUndefined();
expect(toIsoCurrency(978)).toBeUndefined();
expect(toIsoCurrency({ code: 'EUR' })).toBeUndefined();
});
it('settles for the shape of a code when the runtime lists no currencies', () => {
const none = new Set<string>();
expect(toIsoCurrency('eur', none)).toBe('EUR');
expect(toIsoCurrency('EURials', none)).toBe('EUR');
expect(toIsoCurrency('XYZ', none)).toBe('XYZ');
expect(toIsoCurrency('€', none)).toBe('EUR');
expect(toIsoCurrency('CA$', none)).toBeUndefined();
});
});
@@ -20,7 +20,12 @@ const { routeExtraction, detectFlightNumbers } = vi.hoisted(() => ({
routeExtraction: vi.fn(),
detectFlightNumbers: vi.fn(() => [] as string[]),
}));
vi.mock('../../../../src/nest/llm-parse/router/extraction-router', () => ({ routeExtraction, detectFlightNumbers }));
// The router's pure helpers stay real: the currency fallback reads the document's
// total through extractTotalPrice.
vi.mock('../../../../src/nest/llm-parse/router/extraction-router', async (orig) => {
const actual = await orig() as Record<string, unknown>;
return { ...actual, routeExtraction, detectFlightNumbers };
});
import { LlmParseService } from '../../../../src/nest/llm-parse/llm-parse.service';
import type { LlmConfigResolver } from '../../../../src/nest/llm-parse/llm-config.resolver';
@@ -188,3 +193,94 @@ describe('LlmParseService', () => {
expect(res.warnings[0]).toContain('corrupt pdf');
});
});
/**
* What a schema-bound provider answered for one Booking.com stay (#2477): the
* same node twice, and a currency the model made up. Synthetic values in the
* reporter's shape.
*/
describe('LlmParseService: cleaning up an AI answer (#2477)', () => {
const stay = (over: Record<string, unknown> = {}) => ({
'@type': 'LodgingReservation',
checkinTime: '2026-09-06T13:00:00',
checkoutTime: '2026-09-07T11:00:00',
price: 89.35,
priceCurrency: 'EURials',
reservationFor: { name: 'Harbour View Inn', address: 'Example Road 1' },
...over,
});
const PRINT = ['Harbour View Inn', 'PREIS', '1 Zimmer € 74,46', 'Preis', '(für 2 Gäste)', '€ 89,35'].join('\n');
it('collapses exact duplicate nodes from one AI answer', async () => {
extractText.mockResolvedValue(PRINT);
extract.mockResolvedValue([stay(), stay()]);
const res = await svc().parse(file('Bestätigung_1.pdf', '%PDF'), 1);
expect(res.kiItems).toHaveLength(1);
expect(res.warnings).toEqual([]);
});
it("collapses the reporter's two nodes without a venue into one as well", async () => {
extractText.mockResolvedValue(PRINT);
const bare = { '@type': 'LodgingReservation', checkinTime: '2026-09-06T13:00:00', checkoutTime: '2026-09-07T11:00:00', price: 89.35, priceCurrency: 'EURials' };
extract.mockResolvedValue([bare, { ...bare }]);
const res = await svc().parse(file('Bestätigung_1.pdf', '%PDF'), 1);
expect(res.kiItems).toEqual([{ ...bare, priceCurrency: 'EUR' }]);
});
it('treats the same fields in another key order as the same node', async () => {
const a = stay();
const b = { reservationFor: { address: 'Example Road 1', name: 'Harbour View Inn' }, priceCurrency: 'EURials', price: 89.35, checkoutTime: a.checkoutTime, checkinTime: a.checkinTime, '@type': a['@type'] };
extract.mockResolvedValue([a, b]);
const res = await svc().parse(file('a.txt'), 1);
expect(res.kiItems).toHaveLength(1);
});
it('keeps distinct nodes that only look alike', async () => {
extract.mockResolvedValue([stay(), stay({ checkinTime: '2026-09-07T13:00:00', checkoutTime: '2026-09-08T11:00:00' })]);
const res = await svc().parse(file('a.txt'), 1);
expect(res.kiItems).toHaveLength(2);
});
it('turns a garbled priceCurrency into the code it starts with', async () => {
extract.mockResolvedValue([stay()]);
const res = await svc().parse(file('a.txt'), 1);
expect(res.kiItems[0].priceCurrency).toBe('EUR');
});
it("falls back to the document's currency symbol when the model named no currency", async () => {
extractText.mockResolvedValue(PRINT);
extract.mockResolvedValue([stay({ priceCurrency: 'ZZZ' }), stay({ priceCurrency: undefined, checkinTime: '2026-10-01T15:00:00' })]);
const res = await svc().parse(file('b.pdf', '%PDF'), 1);
expect(res.kiItems.map((n) => n.priceCurrency)).toEqual(['EUR', 'EUR']);
});
it('drops the currency when neither the model nor the document names one', async () => {
extractText.mockResolvedValue('Harbour View Inn, 89.35 total');
extract.mockResolvedValue([stay({ priceCurrency: 'ZZZ' })]);
const res = await svc().parse(file('b.txt'), 1);
expect(res.kiItems[0]).not.toHaveProperty('priceCurrency');
expect(res.kiItems[0].price).toBe(89.35);
});
it('asks the document only when the node has a price', async () => {
extractText.mockResolvedValue(PRINT);
extract.mockResolvedValue([stay({ price: undefined, priceCurrency: 'Pesos' })]);
const res = await svc().parse(file('b.pdf', '%PDF'), 1);
expect(res.kiItems[0]).not.toHaveProperty('priceCurrency');
});
it('has no document to ask on the native PDF path', async () => {
resolveLlmConfig.mockReturnValue(cfg({ provider: 'anthropic' }));
extract.mockResolvedValue([stay({ priceCurrency: 'ZZZ' })]);
const res = await svc().parse(file('b.pdf', '%PDF'), 1);
expect(extractText).not.toHaveBeenCalled();
expect(res.kiItems[0]).not.toHaveProperty('priceCurrency');
});
it('leaves a node without price and currency as it came', async () => {
const plain = { '@type': 'FlightReservation', reservationFor: { flightNumber: 'X1' } };
extract.mockResolvedValue([plain]);
const res = await svc().parse(file('a.txt'), 1);
expect(res.kiItems).toEqual([plain]);
});
});
@@ -2,6 +2,18 @@ import { describe, it, expect } from 'vitest';
import { buildSystemPrompt, KI_RESERVATION_JSON_SCHEMA } from '../../../../src/nest/llm-parse/llm-prompt';
import { KI_RESERVATION_TYPES } from '@trek/shared';
/** The slice of JSON Schema these assertions read. */
interface SchemaNode {
type?: string | readonly string[];
properties?: Record<string, SchemaNode>;
items?: SchemaNode;
required?: readonly string[];
additionalProperties?: boolean;
}
const root = KI_RESERVATION_JSON_SCHEMA as SchemaNode;
const item = root.properties.reservations.items;
describe('llm-prompt', () => {
it('names every recognized @type the mapper supports', () => {
const prompt = buildSystemPrompt();
@@ -23,4 +35,54 @@ describe('llm-prompt', () => {
expect(item.properties['@type'].enum).toEqual([...KI_RESERVATION_TYPES]);
expect(item.required).toContain('@type');
});
/**
* Gemini decodes against the schema and fills declared properties only. An
* open `reservationFor` without any came back missing, and every hotel lost
* its name (#1638, #2477).
*/
it('declares the venue fields on reservationFor so a schema-constrained provider can fill them (#2477)', () => {
const rf = item.properties.reservationFor;
expect(item.required).toEqual(['@type', 'reservationFor']);
expect(rf.type).toBe('object');
expect(rf.additionalProperties).toBe(true);
for (const field of ['name', 'address', 'telephone', 'url']) expect(rf.properties[field]).toEqual({ type: 'string' });
expect(rf.properties.geo.properties).toEqual({ latitude: { type: 'number' }, longitude: { type: 'number' } });
});
it('declares every nested object the prompt names, per type (#2477)', () => {
const rf = item.properties.reservationFor.properties;
const keys = (node: SchemaNode) => Object.keys(node.properties ?? {});
expect(keys(rf.departureAirport)).toEqual(['iataCode', 'name', 'geo']);
expect(keys(rf.airline)).toEqual(['name', 'iataCode']);
for (const stop of ['departureStation', 'arrivalBusStop', 'arrivalBoatTerminal']) {
expect(keys(rf[stop])).toEqual(['name', 'geo']);
}
expect(keys(rf.location)).toEqual(['name', 'address', 'geo', 'telephone', 'url']);
expect(keys(rf.rentalCompany)).toEqual(['name']);
// The car desks sit at the root, as the prompt says, with the same venue fields.
expect(item.properties.pickupLocation).toEqual(rf.location);
expect(item.properties.dropoffLocation).toEqual(rf.location);
});
it('nests no object deeper than two levels below reservationFor (#2477)', () => {
const depth = (node: SchemaNode): number =>
node.type === 'object' && node.properties
? 1 + Math.max(0, ...Object.values(node.properties).map(depth))
: 0;
// reservationFor itself, then e.g. departureAirport, then its geo.
expect(depth(item.properties.reservationFor)).toBe(3);
});
it('every object in the schema but the root stays open to extra fields', () => {
const walk = (node: SchemaNode | undefined, path: string): string[] => {
if (!node) return [];
const own = node.type === 'object' && path !== '' && node.additionalProperties !== true ? [path] : [];
const children = Object.entries(node.properties ?? {}).flatMap(([k, v]) => walk(v, `${path}.${k}`));
return [...own, ...children, ...walk(node.items, `${path}[]`)];
};
expect(walk(root, '')).toEqual([]);
});
});
@@ -166,3 +166,39 @@ describe('kitinerary mapper — a recognised type that cannot be mapped (#2375)'
expect(warnings).toEqual(['Unknown type "RocketLaunchReservation" in mars.eml[0] — skipped']);
});
});
/**
* The node a schema-bound provider writes once `reservationFor` has declared
* fields: the venue inside it, times and price at the root, as the prompt asks.
* Synthetic data in the shape of a Booking.com print (#2477).
*/
describe('kitinerary mapper: a prompt-shaped AI lodging (#2477)', () => {
it('maps a LodgingReservation with reservationFor.name to one hotel with its stay and price', () => {
const { items, warnings } = mapReservations([
{
'@type': 'LodgingReservation',
checkinTime: '2026-09-06T13:00:00',
checkoutTime: '2026-09-07T11:00:00',
price: 89.35,
priceCurrency: 'EUR',
reservationFor: {
name: 'Harbour View Inn',
address: 'Example Road 1, 1000 Sample Town',
telephone: '+00 000 000 000',
},
},
] as Parameters<typeof mapReservations>[0], 'Bestätigung_1.pdf');
expect(warnings).toEqual([]);
expect(items).toHaveLength(1);
expect(items[0]).toMatchObject({
type: 'hotel',
title: 'Harbour View Inn',
location: 'Example Road 1, 1000 Sample Town',
_venue: { name: 'Harbour View Inn', phone: '+00 000 000 000' },
_accommodation: { check_in: '2026-09-06T13:00', check_out: '2026-09-07T11:00' },
metadata: { check_in_time: '13:00', check_out_time: '11:00', price: 89.35, priceCurrency: 'EUR' },
source: { fileName: 'Bestätigung_1.pdf', index: 0 },
});
});
});