Support multi-leg (layover) flights (#1146)

* feat(transport): support multi-leg (layover) flights in the booking form

A flight booking can now hold an ordered chain of airports (e.g. FRA -> BER ->
HND) instead of a single departure/arrival pair. The route is entered as a list
of waypoints with a '+ add stop' button; each stop carries its own arrival and
departure time plus the airline/flight number of the segment leaving it, while
the whole booking keeps one price.

Stored without a schema change: the existing reservation_endpoints rows carry the
ordered waypoints (from/stop/to by sequence) and a metadata.legs array holds the
per-leg detail. Top-level metadata (departure_airport/arrival_airport/airline/
flight_number) mirrors the first and last leg, so a single-leg flight persists
exactly as before and legacy readers keep working.

* feat(planner): show each flight leg as its own day-plan entry, ordered by time

A multi-leg flight now expands into one entry per leg (BER -> FRA, then FRA ->
HND), each on its own day with its own times, instead of a single span. Each leg
is an addressable slot (reservation id + leg index) so places and notes can be
dropped into the layover gap between legs; the per-leg position is persisted in
metadata.legs[i].day_positions and survives a reload.

Day-plan items are now ordered chronologically: anything with a time (a place's
time, a flight leg, a timed note) sorts by that time, and untimed items inherit
the time of the item before them so they stay where they were placed.

* feat(planner): show the full multi-stop route in the bookings panel

The route row now lists every waypoint (FRA -> BER -> HND) by sequence instead of
just the first and last airport.

* feat(map): draw multi-leg flights as connected legs with a marker per airport

Both the Leaflet and Mapbox overlays now render a flight over all its waypoints:
one great-circle arc per leg and a marker at every airport, with the label
showing the full route and the summed distance. A single-leg flight is unchanged.

Also drops the floating stats badge that was drawn on transport arcs.

* fix(map): centre a clicked place above the bottom inspector panel

Selecting a place panned/flew it to the dead centre of the screen, where it sat
behind the detail card. Both overlays now bias the target into the visible area
above the bottom panel (Leaflet offsets the pan by the inspector inset; Mapbox
passes the padding to flyTo).

* feat: show the full multi-stop flight route in PDF and calendar export

The PDF day list and the ICS export now render the whole route (FRA → BER → HND)
for a multi-leg flight instead of just the first and last airport, falling back to
the flat metadata for single-leg flights. The ICS keeps a single event per booking.

* feat(import): group connecting flight legs into one multi-leg booking

When a booking confirmation contains several flight legs sharing a PNR that
connect at the same airport with a short layover (under 24h), they are now
imported as a single multi-leg booking (from/stop/to endpoints + metadata.legs)
instead of one booking per leg. A round trip (same PNR, multi-day gap) stays two
separate bookings, and a single flight is unchanged.

* i18n: translate the new flight-route strings into all languages

* i18n: translate the Costs page into every language

The Budget → Costs rework left the new costs.* strings untranslated in every
non-English locale (they fell back to English). Translate them across all
supported languages.

* Revert "fix(map): centre a clicked place above the bottom inspector panel"

This reverts commit 0936103f04.
This commit is contained in:
Maurice
2026-06-11 22:17:14 +02:00
committed by GitHub
parent e65acb3de7
commit bb477645a3
50 changed files with 2144 additions and 1508 deletions
@@ -90,6 +90,90 @@ function mapFlight(r: KiReservation, source: ParsedBookingItem['source']): Parse
};
}
/** True when flight `b` is a short layover connection that continues flight `a`. */
function sameConnection(a: KiReservation, b: KiReservation): boolean {
const fa = a.reservationFor as KiFlight | undefined;
const fb = b.reservationFor as KiFlight | undefined;
if (!fa || !fb) return false;
const arrIata = fa.arrivalAirport?.iataCode?.toUpperCase();
const depIata = fb.departureAirport?.iataCode?.toUpperCase();
if (!arrIata || !depIata || arrIata !== depIata) return false; // must connect at the same airport
const arrIso = toIsoString(fa.arrivalTime);
const depIso = toIsoString(fb.departureTime);
if (arrIso && depIso) {
const gapMs = new Date(depIso).getTime() - new Date(arrIso).getTime();
// A real layover is forward in time and short — anything longer (e.g. a
// round-trip return days later) stays a separate booking.
if (gapMs < 0 || gapMs > 24 * 3600 * 1000) return false;
}
return true;
}
/** Collapse several connecting flight legs (same PNR) into one multi-leg booking. */
function mapFlightGroup(legs: KiReservation[], source: ParsedBookingItem['source']): ParsedBookingItem | null {
const flights = legs.map(l => l.reservationFor as KiFlight | undefined);
if (flights.some(f => !f)) return mapFlight(legs[0], source); // malformed → fall back to single
const fs = flights as KiFlight[];
const iataOf = (ap: KiFlight['departureAirport']) => ap?.iataCode?.toUpperCase() ?? null;
const makeEndpoint = (
ap: KiFlight['departureAirport'], role: 'from' | 'stop' | 'to', time: string | null, date: string | null,
): ParsedEndpoint | null => {
const iata = iataOf(ap);
const found = iata ? findByIata(iata) : null;
const label = found ? (found.city ? `${found.city} (${found.iata})` : found.name) : (ap?.name ?? iata ?? 'Unknown');
if (found) return { role, sequence: 0, name: label, code: found.iata, lat: found.lat, lng: found.lng, timezone: found.tz, local_time: time, local_date: date };
const c = coords(ap?.geo);
if (c) return { role, sequence: 0, name: label, code: iata, lat: c.lat, lng: c.lng, timezone: null, local_time: time, local_date: date };
return null;
};
const endpoints: ParsedEndpoint[] = [];
const metaLegs: Record<string, unknown>[] = [];
const first = fs[0];
const firstDep = splitIso(first.departureTime);
const originEp = makeEndpoint(first.departureAirport, 'from', firstDep.time, firstDep.date);
if (originEp) endpoints.push(originEp);
fs.forEach((f, i) => {
const isLast = i === fs.length - 1;
const arr = splitIso(f.arrivalTime);
const arrEp = makeEndpoint(f.arrivalAirport, isLast ? 'to' : 'stop', arr.time, arr.date);
if (arrEp) endpoints.push(arrEp);
const airline = f.airline?.name ?? f.airline?.iataCode ?? '';
metaLegs.push({
from: iataOf(f.departureAirport),
to: iataOf(f.arrivalAirport),
...(airline ? { airline } : {}),
...(f.flightNumber ? { flight_number: f.flightNumber } : {}),
dep_time: splitIso(f.departureTime).time,
arr_time: arr.time,
});
});
endpoints.forEach((e, i) => { e.sequence = i; });
const last = fs[fs.length - 1];
const airline = first.airline?.name ?? first.airline?.iataCode ?? '';
const route = [iataOf(first.departureAirport), ...fs.map(f => iataOf(f.arrivalAirport))].filter(Boolean).join(' → ');
return {
type: 'flight',
title: airline ? `${airline} ${route}` : `Flight ${route}`,
reservation_time: toIsoString(first.departureTime),
reservation_end_time: toIsoString(last.arrivalTime),
confirmation_number: legs[0].reservationNumber ?? null,
metadata: {
...(airline ? { airline } : {}),
...(first.flightNumber ? { flight_number: first.flightNumber } : {}),
...(iataOf(first.departureAirport) ? { departure_airport: iataOf(first.departureAirport) } : {}),
...(iataOf(last.arrivalAirport) ? { arrival_airport: iataOf(last.arrivalAirport) } : {}),
legs: metaLegs,
},
endpoints,
needs_review: endpoints.length < fs.length + 1,
source,
};
}
function mapTrain(r: KiReservation, source: ParsedBookingItem['source']): ParsedBookingItem | null {
const t = r.reservationFor as KiTrainTrip | undefined;
if (!t) return null;
@@ -233,8 +317,25 @@ export function mapReservations(kiItems: KiReservation[], fileName: string): { i
const source = { fileName, index: i };
let item: ParsedBookingItem | null = null;
// Group consecutive connecting flight legs that share a PNR into one booking.
if (r['@type'] === 'FlightReservation') {
const pnr = r.reservationNumber ?? null;
const group = [r];
while (
i + 1 < kiItems.length &&
kiItems[i + 1]['@type'] === 'FlightReservation' &&
pnr != null &&
(kiItems[i + 1].reservationNumber ?? null) === pnr &&
sameConnection(group[group.length - 1], kiItems[i + 1])
) {
group.push(kiItems[++i]);
}
item = group.length > 1 ? mapFlightGroup(group, source) : mapFlight(r, source);
if (item) items.push(item);
continue;
}
switch (r['@type']) {
case 'FlightReservation': item = mapFlight(r, source); break;
case 'TrainReservation': item = mapTrain(r, source); break;
case 'BusReservation': item = mapBus(r, source); break;
case 'BoatReservation': item = mapBoat(r, source); break;
+8 -2
View File
@@ -543,8 +543,14 @@ export function exportICS(tripId: string | number): { ics: string; filename: str
if (r.confirmation_number) desc += `\nConfirmation: ${r.confirmation_number}`;
if (meta.airline) desc += `\nAirline: ${meta.airline}`;
if (meta.flight_number) desc += `\nFlight: ${meta.flight_number}`;
if (meta.departure_airport) desc += `\nFrom: ${meta.departure_airport}`;
if (meta.arrival_airport) desc += `\nTo: ${meta.arrival_airport}`;
if (Array.isArray(meta.legs) && meta.legs.length > 1) {
// Multi-leg flight: show the whole route (FRA → BER → HND) on one event.
const stops = [meta.legs[0]?.from, ...meta.legs.map((l: { to?: string }) => l.to)].filter(Boolean);
if (stops.length) desc += `\nRoute: ${stops.join(' → ')}`;
} else {
if (meta.departure_airport) desc += `\nFrom: ${meta.departure_airport}`;
if (meta.arrival_airport) desc += `\nTo: ${meta.arrival_airport}`;
}
if (meta.train_number) desc += `\nTrain: ${meta.train_number}`;
if (r.notes) desc += `\n${r.notes}`;
if (desc) ics += `DESCRIPTION:${esc(desc)}\r\n`;
@@ -0,0 +1,70 @@
import { describe, it, expect } from 'vitest';
import { mapReservations } from '../../../src/nest/booking-import/kitinerary-mapper';
const airport = (iata: string, lat: number, lng: number) => ({
iataCode: iata,
name: iata,
geo: { latitude: lat, longitude: lng },
});
const flight = (pnr: string, dep: any, arr: any, depTime: string, arrTime: string, flightNumber: string) => ({
'@type': 'FlightReservation',
reservationNumber: pnr,
reservationFor: {
departureAirport: dep,
arrivalAirport: arr,
departureTime: depTime,
arrivalTime: arrTime,
airline: { name: 'Lufthansa', iataCode: 'LH' },
flightNumber,
},
});
const FRA = airport('FRA', 50.04, 8.57);
const BER = airport('BER', 52.36, 13.50);
const HND = airport('HND', 35.55, 139.78);
describe('kitinerary mapper — multi-leg flight grouping', () => {
it('groups two connecting same-PNR legs into one multi-leg booking', () => {
const { items } = mapReservations([
flight('ABC123', FRA, BER, '2026-06-11T10:00:00', '2026-06-11T12:00:00', 'LH 100'),
flight('ABC123', BER, HND, '2026-06-11T14:30:00', '2026-06-11T23:30:00', 'LH 200'),
] as any, 'test.json');
expect(items).toHaveLength(1);
const booking = items[0];
expect(booking.type).toBe('flight');
expect(booking.endpoints).toHaveLength(3);
expect(booking.endpoints!.map(e => e.role)).toEqual(['from', 'stop', 'to']);
expect(booking.endpoints!.map(e => e.sequence)).toEqual([0, 1, 2]);
const meta = booking.metadata as any;
expect(meta.legs).toHaveLength(2);
expect(meta.legs[0]).toMatchObject({ from: 'FRA', to: 'BER', flight_number: 'LH 100' });
expect(meta.legs[1]).toMatchObject({ from: 'BER', to: 'HND', flight_number: 'LH 200' });
expect(meta.departure_airport).toBe('FRA');
expect(meta.arrival_airport).toBe('HND');
expect(booking.reservation_time).toContain('10:00');
expect(booking.reservation_end_time).toContain('23:30');
});
it('keeps a round trip (same PNR, multi-day gap) as two separate bookings', () => {
const { items } = mapReservations([
flight('RT999', FRA, HND, '2026-06-11T10:00:00', '2026-06-11T20:00:00', 'LH 700'),
flight('RT999', HND, FRA, '2026-06-20T10:00:00', '2026-06-20T18:00:00', 'LH 701'),
] as any, 'test.json');
expect(items).toHaveLength(2);
expect((items[0].metadata as any).legs).toBeUndefined();
expect((items[1].metadata as any).legs).toBeUndefined();
});
it('leaves a single flight unchanged (two endpoints, no legs array)', () => {
const { items } = mapReservations([
flight('S1', FRA, BER, '2026-06-11T10:00:00', '2026-06-11T12:00:00', 'LH 1'),
] as any, 'test.json');
expect(items).toHaveLength(1);
expect(items[0].endpoints).toHaveLength(2);
expect((items[0].metadata as any).legs).toBeUndefined();
});
});