Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

10.0 KB
Raw Blame
// Multi-leg (layover) flight support.
//
// A flight booking is ONE reservation whose route is an ordered chain of airports
// (e.g. FRA -> BER -> HND). The geometry + order are the source of truth in
// `reservation.endpoints` (role 'from' for the first airport, 'stop' for each
// intermediate one, 'to' for the last, ordered by `sequence`). The per-leg detail
// — airline, flight number, and each segment's own day/time — lives in
// `metadata.legs`. The top-level metadata (`departure_airport`/`arrival_airport`/
// `airline`/`flight_number`) and `day_id`/`end_day_id` mirror the FIRST and LAST
// leg so legacy readers keep working.
//
// A legacy single-leg flight (two endpoints, flat metadata, no `metadata.legs`)
// is normalised here into a one-leg chain, so every renderer can use one path.

import type { Reservation, ReservationEndpoint } from '../types'

export interface FlightLeg {
  from: string | null // IATA code (or null)
  to: string | null
  airline?: string
  flight_number?: string
  /** This leg's own seat; the first leg falls back to the booking's flat seat (see legSeat). */
  seat?: string
  /** This segment's own booking reference, when it was booked separately (#1943). */
  confirmation_number?: string
  dep_day_id?: number | null
  dep_time?: string | null // 'HH:mm'
  arr_day_id?: number | null
  arr_time?: string | null
}

/** reservation.metadata may be a JSON string or an already-parsed object. */
export function parseReservationMetadata(r: Pick<Reservation, 'metadata'>): Record<string, any> {
  const m = r.metadata
  if (!m) return {}
  if (typeof m === 'string') {
    try {
      let parsed = JSON.parse(m || '{}')
      // Defensive: an earlier bug could double-encode metadata (a JSON string of a
      // JSON string) — unwrap it once more so saved flights heal on read.
      if (typeof parsed === 'string') { try { parsed = JSON.parse(parsed) } catch { /* keep */ } }
      return (parsed && typeof parsed === 'object') ? parsed : {}
    } catch { return {} }
  }
  return m as Record<string, any>
}

/** Endpoints ordered by `sequence` (geometry + order source of truth). */
export function orderedEndpoints(r: Pick<Reservation, 'endpoints'>): ReservationEndpoint[] {
  return (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
}

/**
 * An airport endpoint's name without the code every writer appends to it:
 * "Paris Charles de Gaulle (CDG)" → "Paris Charles de Gaulle". Done as a trim plus an
 * anchored test instead of /\s*\([A-Z]{3}\)\s*$/, because the leading \s* backtracks over
 * every space in a long name for a quadratic worst case.
 */
export function stripAirportCode(name: string): string {
  const trimmed = name.trimEnd()
  return /\([A-Z]{3}\)$/.test(trimmed) ? trimmed.slice(0, -5).trimEnd() : name
}

/**
 * Ordered legs of a flight. `metadata.legs` is preferred; otherwise a single leg
 * is derived from the endpoints (and finally the flat metadata) so that legacy
 * single-leg flights — and flights created before this feature — still work.
 */
export function getFlightLegs(r: Reservation): FlightLeg[] {
  const meta = parseReservationMetadata(r)
  if (Array.isArray(meta.legs) && meta.legs.length > 0) {
    return meta.legs.map((l: any, i: number): FlightLeg => ({
      from: l.from ?? null,
      to: l.to ?? null,
      airline: l.airline || undefined,
      flight_number: l.flight_number || undefined,
      seat: legSeat(l, i, meta),
      confirmation_number: l.confirmation_number || undefined,
      dep_day_id: l.dep_day_id ?? null,
      dep_time: l.dep_time ?? null,
      arr_day_id: l.arr_day_id ?? null,
      arr_time: l.arr_time ?? null,
    }))
  }
  // Legacy fallback: one leg from the endpoints / flat metadata.
  const eps = orderedEndpoints(r)
  const first = eps[0]
  const last = eps[eps.length - 1]
  const fromCode = first?.code ?? meta.departure_airport ?? null
  const toCode = last?.code ?? meta.arrival_airport ?? null
  if (!fromCode && !toCode) return []
  return [{
    from: fromCode,
    to: toCode,
    airline: meta.airline || undefined,
    flight_number: meta.flight_number || undefined,
    seat: meta.seat || undefined,
    // The single segment IS the booking, so its reference is the booking's.
    confirmation_number: r.confirmation_number || undefined,
    dep_day_id: r.day_id ?? null,
    dep_time: first?.local_time ?? null,
    arr_day_id: r.end_day_id ?? r.day_id ?? null,
    arr_time: last?.local_time ?? null,
  }]
}

/**
 * A train booking mirrors the flight leg model (#1150), but its stops are
 * STATIONS (labels, not IATA codes) and each leg carries a train number +
 * platform instead of an airline + flight number.
 */
export interface TrainLeg {
  from: string | null // station label (or null)
  to: string | null
  train_number?: string
  platform?: string
  seat?: string
  /** This segment's own booking reference, when it was booked separately (#1943). */
  confirmation_number?: string
  dep_day_id?: number | null
  dep_time?: string | null
  arr_day_id?: number | null
  arr_time?: string | null
}

/**
 * Ordered legs of a train booking. Prefers `metadata.legs`; otherwise derives a
 * single leg from the endpoints + flat metadata, so single-leg trains — and
 * trains created before this feature — still work.
 */
export function getTrainLegs(r: Reservation): TrainLeg[] {
  const meta = parseReservationMetadata(r)
  if (Array.isArray(meta.legs) && meta.legs.length > 0) {
    return meta.legs.map((l: any, i: number): TrainLeg => ({
      from: l.from ?? null,
      to: l.to ?? null,
      train_number: l.train_number || undefined,
      platform: l.platform || undefined,
      seat: legSeat(l, i, meta),
      confirmation_number: l.confirmation_number || undefined,
      dep_day_id: l.dep_day_id ?? null,
      dep_time: l.dep_time ?? null,
      arr_day_id: l.arr_day_id ?? null,
      arr_time: l.arr_time ?? null,
    }))
  }
  const eps = orderedEndpoints(r)
  const first = eps[0]
  const last = eps[eps.length - 1]
  const fromLabel = first ? (first.code || first.name) : null
  const toLabel = last ? (last.code || last.name) : null
  if (!fromLabel && !toLabel && !meta.train_number) return []
  return [{
    from: fromLabel,
    to: toLabel,
    train_number: meta.train_number || undefined,
    platform: meta.platform || undefined,
    seat: meta.seat || undefined,
    // The single segment IS the booking, so its reference is the booking's.
    confirmation_number: r.confirmation_number || undefined,
    dep_day_id: r.day_id ?? null,
    dep_time: first?.local_time ?? null,
    arr_day_id: r.end_day_id ?? r.day_id ?? null,
    arr_time: last?.local_time ?? null,
  }]
}

/**
 * A leg's own seat. The flat `metadata.seat` mirrors the first leg's, so a
 * booking saved before legs carried seats, or one an import gave only the flat
 * seat, still shows it on its first leg, as the booking form reads it.
 */
function legSeat(leg: { seat?: unknown } | null | undefined, index: number, meta: { seat?: unknown }): string | undefined {
  if (typeof leg?.seat === 'string' && leg.seat) return leg.seat
  return index === 0 && typeof meta.seat === 'string' && meta.seat ? meta.seat : undefined
}

/**
 * The seats of a booking, each with the route of the leg it belongs to. A flight
 * or train with a stop lists one per leg that has a seat, so a seat booked only
 * on the second leg is not lost behind the first leg's empty one; any other
 * booking gives its own seat with no route.
 */
export function bookingSeats(r: Reservation): { route: string | null; seat: string }[] {
  const legs: (FlightLeg | TrainLeg)[] =
    r.type === 'flight' ? getFlightLegs(r) : usesStationRoute(r.type) ? getTrainLegs(r) : []
  return seatsOfLegs(legs, parseReservationMetadata(r).seat)
}

/** bookingSeats for legs already read (getFlightLegs or getTrainLegs) and the booking's flat seat. */
export function seatsOfLegs(legs: readonly (FlightLeg | TrainLeg)[], flatSeat: unknown): { route: string | null; seat: string }[] {
  if (legs.length > 1) {
    return legs.flatMap((l) => (l.seat ? [{ route: [l.from, l.to].filter(Boolean).join(' → ') || null, seat: l.seat }] : []))
  }
  return typeof flatSeat === 'string' && flatSeat ? [{ route: null, seat: flatSeat }] : []
}

/** The label of one of bookingSeats' seats: "Seat", or "Seat FRA → IST" for a leg. */
export function seatLabel(seatWord: string, route: string | null): string {
  return route ? `${seatWord} ${route}` : seatWord
}

/**
 * bookingSeats as the one Seat cell of a booking's field grid: every leg's seat
 * in route order, then `suffix` (its class). One cell, because a card cuts its
 * grid after a few cells and a route in the label does not fit a narrow one;
 * the detail views name each leg's seat under its route.
 */
export function seatCells(r: Reservation, seatWord: string, suffix = ''): { label: string; value: string }[] {
  const seats = bookingSeats(r)
  return seats.length ? [{ label: seatWord, value: seats.map((s) => s.seat).join(', ') + suffix }] : []
}

/** Number of flight segments. 1 for a simple from -> to booking. */
export function legCount(r: Reservation): number {
  return getFlightLegs(r).length
}

/**
 * Types whose route is a row of stations, each with its own arrival and
 * departure: trains, and cruises with their ports of call (#1807). Both use
 * the station form and the legs getTrainLegs reads.
 */
export function usesStationRoute(type: string | null | undefined): boolean {
  return type === 'train' || type === 'cruise'
}

export function isMultiLegTrain(r: Reservation): boolean {
  return usesStationRoute(r.type) && getTrainLegs(r).length > 1
}

export function isMultiLegFlight(r: Reservation): boolean {
  return r.type === 'flight' && legCount(r) > 1
}

/**
 * Ordered route labels (IATA codes, or names when no code) for display, e.g.
 * ['FRA','BER','HND']. Uses endpoints; falls back to the flat metadata pair.
 */
export function routeStops(r: Reservation): string[] {
  const eps = orderedEndpoints(r)
  if (eps.length >= 2) return eps.map(e => e.code || e.name)
  const meta = parseReservationMetadata(r)
  return [meta.departure_airport, meta.arrival_airport].filter(Boolean) as string[]
}