From 9e13791239dfd491458c73d619526cab15f10e6e Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 20 Aug 2026 17:57:40 +0200 Subject: [PATCH] fix(booking-import): geocode transport endpoints on the path clients use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An imported train, bus or rental car showed its pick-up and drop-off in the review step and then had them gone from the saved booking: no pins, no route, no error. reservation_endpoints.lat and lng are NOT NULL, so saveEndpoints drops an endpoint without coordinates, and kitinerary and the LLM name stations, stops, terminals and rental desks without geo-locating them. Only airports arrive with coordinates, from the mapper's own table. The lookup that was meant to fill them in existed — in confirm(), which no client calls. Both the desktop planner and mobile go preview, review form, ordinary save, so it never ran. It runs in preview() now, through a helper confirm() shares, on the throttled background lane whose own docstring names booking-import as its intended caller. The query ladder matches the venue lookup beside it: the endpoint plus the booking's location first, then the address, then the bare name — name-only is exactly what fails for a desk label like "Curbside Pickup Counter 7", so it goes last. Answers are cached per preview, since a multi-leg train repeats its stations and the lane allows about one request a second. An endpoint that still cannot be placed stays on the item rather than being filtered, so the review form can show and edit it, and the preview says which name it could not locate. That warning needed the widget to change too: it rendered warnings only when a job found nothing at all, which is precisely the case this is not. Reported with the full chain, file by file. Closes #1969 --- .../BackgroundTasksWidget.test.tsx | 17 +++ .../BackgroundTasks/BackgroundTasksWidget.tsx | 26 ++-- .../booking-import/booking-import.service.ts | 112 +++++++++++++++--- .../nest/booking-import/kitinerary-mapper.ts | 4 +- .../booking-import.service.test.ts | 93 +++++++++++++++ 5 files changed, 227 insertions(+), 25 deletions(-) diff --git a/client/src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx b/client/src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx index 6bfbab1ca..a8584af6d 100644 --- a/client/src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx +++ b/client/src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx @@ -133,4 +133,21 @@ describe('BackgroundTasksWidget', () => { expect(reservationsApi.importBookingAsync).toHaveBeenCalledTimes(1) }) }) + + /* + * Warnings used to appear only when nothing at all was found, so a partly + * understood import dropped whatever it could not place without a word — a + * station the geocoder could not locate, say (#1969), whose endpoint then + * disappeared on save. + */ + it('shows the warnings on a job that did produce items', () => { + const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7" — set it manually before saving' + useBackgroundTasksStore.setState({ + tasks: [task({ items: [{ id: 1 } as never], warnings: [warning] })], + }) + render() + expect(screen.getByText(new RegExp('Curbside Pickup Counter 7'))).toBeInTheDocument() + // and the import button is still there — the job did find something + expect(screen.getByRole('button', { name: /import/i })).toBeInTheDocument() + }) }) diff --git a/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx b/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx index 36823ba3f..9d3a5b79f 100644 --- a/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx +++ b/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx @@ -157,13 +157,25 @@ export default function BackgroundTasksWidget() { // Restored from a reload; items are being re-fetched (see the poll backstop).
{t('reservations.import.parsing')}
) : task.items.length > 0 ? ( - +
+ + {/* A partly-understood import warns too. Warnings used to be + shown only when nothing at all was found, so anything the + parse could not place — a station it could not locate, say + (#1969) — was dropped without a word on exactly the imports + that did produce something. */} + {(task.warnings?.length ?? 0) > 0 && ( +
+ {task.warnings!.join('\n')} +
+ )} +
) : (
diff --git a/server/src/nest/booking-import/booking-import.service.ts b/server/src/nest/booking-import/booking-import.service.ts index 92f703654..0643e2184 100644 --- a/server/src/nest/booking-import/booking-import.service.ts +++ b/server/src/nest/booking-import/booking-import.service.ts @@ -64,6 +64,72 @@ export class BookingImportService { * - force-ai: LLM on every file (kitinerary skipped) * LLM-derived items are flagged needs_review. Per-file AI usage is reported. */ + /** + * Give a transport's endpoints coordinates, so they survive the save. + * + * kitinerary and the LLM name stations, stops, terminals and rental desks but + * rarely geo-locate them — only airports come with coordinates, from the + * mapper's own airport table. `reservation_endpoints.lat`/`lng` are NOT NULL, + * so `saveEndpoints` drops anything without them. That guard is right; what + * was missing is this step on the path the clients actually take. + * + * It lived in confirm() alone, which nothing calls: both the desktop planner + * and mobile go preview -> review form -> ordinary save. So an endpoint the + * extractor had named appeared in the review step's From -> To summary and + * then vanished on save, with nothing shown and nothing logged (#1969). + * + * The query ladder matches the venue lookup above: name plus the booking's + * location first, then the location alone, then the bare name. Name-only is + * exactly what fails for a desk label like "Curbside Pickup Counter 7", so it + * comes last rather than first. + * + * Answers are cached for the length of one preview: a multi-leg train repeats + * its station names, and this lane is rate limited to roughly one request a + * second. Returns the names it could not place, for the caller to warn about + * rather than dropping them silently. + */ + private async geocodeEndpoints( + endpoints: { name?: string | null; lat?: number | null; lng?: number | null }[] | undefined, + context: { location?: string | null; address?: string | null }, + cache: Map, + ): Promise { + if (!Array.isArray(endpoints)) return []; + const unresolved: string[] = []; + + for (const ep of endpoints) { + if (ep.lat != null && ep.lng != null) continue; + if (!ep.name) continue; + + const key = ep.name.toLowerCase(); + if (cache.has(key)) { + const hit = cache.get(key); + if (hit) { ep.lat = hit.lat; ep.lng = hit.lng; } else { unresolved.push(ep.name); } + continue; + } + + const queries = [ + context.location ? `${ep.name} ${context.location}` : null, + context.address ? `${ep.name} ${context.address}` : null, + ep.name, + ].filter((q): q is string => !!q); + + let found: { lat: number; lng: number } | null = null; + try { + for (const q of queries) { + const hit = (await this.maps.searchNominatim(q, undefined, 'background'))[0]; + if (hit?.lat != null && hit?.lng != null) { found = { lat: hit.lat, lng: hit.lng }; break; } + } + } catch { + // geocoding failure is non-fatal — the endpoint stays, and is warned about + } + + cache.set(key, found); + if (found) { ep.lat = found.lat; ep.lng = found.lng; } else { unresolved.push(ep.name); } + } + + return unresolved; + } + async preview( files: Express.Multer.File[], mode: BookingImportMode, @@ -78,6 +144,10 @@ export class BookingImportService { const allItems: ParsedBookingItem[] = []; const allWarnings: string[] = []; + // One lookup per distinct endpoint name across the whole preview: a + // multi-leg train repeats its stations, and this lane allows about one + // request a second. + const geoCache = new Map(); const fileReports: BookingImportFileReport[] = []; let processed = 0; @@ -111,6 +181,22 @@ export class BookingImportService { const { items, warnings } = mapReservations(kiItems, file.originalname); // LLM extraction is less certain than kitinerary — always flag for review. if (aiUsed) for (const it of items) it.needs_review = true; + + // Locate the endpoints here, on the path the clients take, rather than + // in confirm() where the code used to sit and nothing reached it. + for (const it of items) { + const missed = await this.geocodeEndpoints( + (it as { endpoints?: { name?: string | null; lat?: number | null; lng?: number | null }[] }).endpoints, + { location: (it as { location?: string | null }).location, address: (it as { _venue?: { address?: string | null } })._venue?.address }, + geoCache, + ); + // Kept on the item rather than filtered, so it is still editable in the + // review form, and said out loud rather than disappearing on save. + for (const name of missed) { + allWarnings.push(`${file.originalname}: could not locate "${name}" — set it manually before saving`); + } + } + allItems.push(...items); allWarnings.push(...warnings); } @@ -133,6 +219,7 @@ export class BookingImportService { socketId: string | undefined, ): Promise { const created: Reservation[] = []; + const confirmGeoCache = new Map(); for (const item of items) { try { @@ -178,23 +265,16 @@ export class BookingImportService { this.realtime.broadcast(tripId, 'place:created', { place }, socketId); } - // Geocode transport endpoints (stations/stops/terminals/rental desks) that - // arrived without coords, so the route draws and map pins appear. The LLM - // and kitinerary rarely supply geo for non-airport endpoints. + // 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)) { - for (const ep of reservationData.endpoints) { - if ((ep.lat == null || ep.lng == null) && ep.name) { - try { - const hit = (await this.maps.searchNominatim(ep.name, undefined, 'background'))[0]; - if (hit?.lat != null && hit?.lng != null) { - ep.lat = hit.lat; - ep.lng = hit.lng; - } - } catch { - // geocoding failure is non-fatal - } - } - } + 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); diff --git a/server/src/nest/booking-import/kitinerary-mapper.ts b/server/src/nest/booking-import/kitinerary-mapper.ts index 71e2a28a1..3f5c21356 100644 --- a/server/src/nest/booking-import/kitinerary-mapper.ts +++ b/server/src/nest/booking-import/kitinerary-mapper.ts @@ -189,7 +189,7 @@ function mapTrain(r: KiReservation, source: ParsedBookingItem['source']): Parsed const endpoints: ParsedEndpoint[] = []; const dc = coords(t.departureStation?.geo); const ac = coords(t.arrivalStation?.geo); - // Push named endpoints even without coords — confirm() geocodes them later. + // Push named endpoints even without coords — preview() geocodes them (#1969). if (t.departureStation?.name) endpoints.push({ role: 'from', sequence: 0, name: depName, code: null, lat: dc?.lat ?? null, lng: dc?.lng ?? null, timezone: null, local_time: depTime, local_date: depDate }); if (t.arrivalStation?.name) endpoints.push({ role: 'to', sequence: 1, name: arrName, code: null, lat: ac?.lat ?? null, lng: ac?.lng ?? null, timezone: null, local_time: arrTime, local_date: arrDate }); @@ -293,7 +293,7 @@ function mapRentalCar(r: KiReservation, source: ParsedBookingItem['source']): Pa const drc = coords(dropoff?.geo); const venue: ParsedVenue | undefined = pickup?.name ? { name: pickup.name, ...(pc ?? {}), address: formatAddress(pickup.address) ?? undefined } : undefined; - // Pickup → return as from/to endpoints (coords optional; confirm() geocodes). + // Pickup → return as from/to endpoints (coords optional; preview() geocodes). const { date: puDate, time: puTime } = splitIso(r.pickupTime); const { date: doDate, time: doTime } = splitIso(r.dropoffTime); const endpoints: ParsedEndpoint[] = []; diff --git a/server/tests/unit/nest/booking-import/booking-import.service.test.ts b/server/tests/unit/nest/booking-import/booking-import.service.test.ts index 316381ecb..908295ae4 100644 --- a/server/tests/unit/nest/booking-import/booking-import.service.test.ts +++ b/server/tests/unit/nest/booking-import/booking-import.service.test.ts @@ -87,3 +87,96 @@ describe('BookingImportService.preview', () => { expect(res.items[0].needs_review).toBe(true); }); }); + +/** + * Endpoints that arrive without coordinates (#1969). + * + * kitinerary and the LLM name stations, stops, terminals and rental desks but + * rarely geo-locate them — only airports come with coordinates, from the + * mapper's own table. `reservation_endpoints.lat`/`lng` are NOT NULL, so + * `saveEndpoints` drops anything without them. + * + * The lookup that was meant to fill them in lived in confirm(), which nothing + * calls: both the desktop planner and mobile go preview -> review form -> + * ordinary save. So a named endpoint showed up in the review step's From -> To + * summary and then vanished on save, with nothing logged and nothing shown. + * + * These run against preview(), because that is the path that exists. + */ +describe('BookingImportService.preview endpoint geocoding (#1969)', () => { + const TRAIN_KI = { + '@type': 'TrainReservation', + reservationNumber: 'TR1', + reservationFor: { + trainNumber: 'ICE 597', + departureStation: { name: 'Berlin Hbf' }, + arrivalStation: { name: 'München Hbf' }, + departureTime: '2026-06-11T08:00:00', + arrivalTime: '2026-06-11T12:00:00', + }, + }; + + const hit = (lat: number, lng: number) => [{ lat, lng, display_name: 'x' }]; + + it('gives a named station coordinates, so it survives the save', async () => { + const { svc, maps } = make({ kit: true, extract: async () => [TRAIN_KI] }); + maps.searchNominatim.mockResolvedValue(hit(52.525, 13.369)); + + const res = await svc.preview([file()], 'no-ai', 1); + const endpoints = (res.items[0] as { endpoints?: { lat: number | null }[] }).endpoints ?? []; + expect(endpoints.length).toBeGreaterThan(0); + for (const ep of endpoints) expect(ep.lat).not.toBeNull(); + }); + + it('asks the same station only once, however often it appears', async () => { + const { svc, maps } = make({ + kit: true, + // Two legs out of and back into the same station. + extract: async () => [TRAIN_KI, TRAIN_KI], + }); + maps.searchNominatim.mockResolvedValue(hit(52.525, 13.369)); + + await svc.preview([file()], 'no-ai', 1); + // Two distinct names across four endpoints — Nominatim allows about one + // request a second on this lane, so repeats have to come from the cache. + expect(maps.searchNominatim).toHaveBeenCalledTimes(2); + }); + + /* + * The half that made this so hard to notice: the endpoint disappeared without + * a word. It stays on the item now, so the review form can still show and + * edit it, and the preview says what it could not place. + */ + it('keeps an endpoint it cannot place, and says so', async () => { + const { svc, maps } = make({ kit: true, extract: async () => [TRAIN_KI] }); + maps.searchNominatim.mockResolvedValue([]); + + const res = await svc.preview([file()], 'no-ai', 1); + const endpoints = (res.items[0] as { endpoints?: { name: string }[] }).endpoints ?? []; + expect(endpoints.map(e => e.name)).toContain('Berlin Hbf'); + expect(res.warnings.some(w => w.includes('Berlin Hbf'))).toBe(true); + }); + + it('survives a geocoder that throws, rather than failing the import', async () => { + const { svc, maps } = make({ kit: true, extract: async () => [TRAIN_KI] }); + maps.searchNominatim.mockRejectedValue(new Error('nominatim down')); + + const res = await svc.preview([file()], 'no-ai', 1); + expect(res.items).toHaveLength(1); + }); + + it('does not look up an endpoint that already knows where it is', async () => { + const withGeo = { + ...TRAIN_KI, + reservationFor: { + ...TRAIN_KI.reservationFor, + departureStation: { name: 'Berlin Hbf', geo: { latitude: 52.525, longitude: 13.369 } }, + arrivalStation: { name: 'München Hbf', geo: { latitude: 48.140, longitude: 11.558 } }, + }, + }; + const { svc, maps } = make({ kit: true, extract: async () => [withGeo] }); + + await svc.preview([file()], 'no-ai', 1); + expect(maps.searchNominatim).not.toHaveBeenCalled(); + }); +});