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.

46.1 KB
Raw Blame
import { DayNotes } from '../../db/entities/DayNotes.entity';
import { Days } from '../../db/entities/Days.entity';
import { Reservations } from '../../db/entities/Reservations.entity';
import { Trips } from '../../db/entities/Trips.entity';
import { RESERVATION_METADATA } from '../../db/json-columns';
import type { DayNotesRepository } from '../../db/repositories/DayNotes.repository';
import type { DaysRepository } from '../../db/repositories/Days.repository';
import type {
  CalendarReservationRow,
  CalendarStopRow,
  ReservationsRepository,
} from '../../db/repositories/Reservations.repository';
import type { TripsRepository } from '../../db/repositories/Trips.repository';
import { decodeJson } from '../../utils/json-column';
import { NotFoundError } from '../common/domain-errors';
import { resolveTimeZone } from '../common/timezoneService';
import { addDays } from '../days/days.service';
import { ReservationsService } from '../reservations/reservations.service';
import { buildVTimezone, isValidTimeZone } from './calendar-timezones.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import { isTransportReservationType, type TripCalendarQuery } from '@trek/shared';

/** The VCALENDAR preamble every TREK calendar starts with, single-trip or merged. */
export const CALENDAR_HEADER =
  'BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//TREK//Travel Planner//EN\r\nCALSCALE:GREGORIAN\r\nMETHOD:PUBLISH\r\n';

/** One trip's calendar in parts, so callers can merge several without re-parsing text. */
export interface TripCalendar {
  /** Already escaped for the X-WR-CALNAME line. */
  calName: string;
  /** Filename for the Content-Disposition of the one-time download. */
  filename: string;
  /** VTIMEZONE block per TZID. Merging calendars means merging these by key. */
  timezones: Map<string, string>;
  /** One complete BEGIN:VEVENT…END:VEVENT block each, unfolded, in emission order. */
  events: string[];
}

/** What a trip's calendar holds beyond the trip itself, its timed stops and its bookings. */
export interface TripCalendarOptions {
  /** The all-day summary per day with untimed stops or notes ("Day 1", ...). On unless set to false (#2602). */
  dayEvents?: boolean;
}

/** The options a calendar request asks for: `days=0` leaves out the per-day summaries. */
export function calendarOptionsFromQuery(query: TripCalendarQuery): TripCalendarOptions {
  return { dayEvents: query.days !== '0' };
}

// ── ICS folding ─────────────────────────────────────────────────────────────

// RFC 5545 §3.1: content lines longer than 75 octets must be folded with a CRLF
// followed by a single leading space. We fold on UTF-8 *octet* boundaries and
// never split a multi-byte codepoint, so non-ASCII titles/notes (accents, CJK,
// emoji) stay intact. Applied to the whole calendar, so both the one-time
// download and the subscribable feed emit spec-compliant output.
export function foldICS(ics: string): string {
  const foldLine = (line: string): string => {
    const bytes = Buffer.from(line, 'utf8');
    if (bytes.length <= 75) return line;
    const parts: Buffer[] = [];
    let start = 0;
    let limit = 75; // first physical line may use 75 octets
    while (start < bytes.length) {
      let end = Math.min(start + limit, bytes.length);
      // Back off so we never cut a multi-byte UTF-8 sequence (0x80–0xBF = continuation byte).
      while (end < bytes.length && (bytes[end] & 0xc0) === 0x80) end--;
      parts.push(bytes.subarray(start, end));
      start = end;
      limit = 74; // continuation lines spend one octet on the leading space
    }
    return parts.map((b, i) => (i === 0 ? '' : ' ') + b.toString('utf8')).join('\r\n');
  };
  return ics.split('\r\n').map(foldLine).join('\r\n');
}

/** Rows of several days, by day id; each day keeps the order the rows came in. */
function groupByDay<T extends { day_id: number }>(rows: T[]): Map<number, T[]> {
  const byDay = new Map<number, T[]>();
  for (const row of rows) {
    const list = byDay.get(row.day_id);
    if (list) list.push(row);
    else byDay.set(row.day_id, [row]);
  }
  return byDay;
}

/** A wall clock `minutes` later, carried over midnight onto the following date. */
function plusMinutes(date: string, time: string, minutes: number): { date: string; time: string } {
  const [h, m] = time.slice(0, 5).split(':').map(Number);
  const total = h * 60 + m + minutes;
  const dayShift = Math.floor(total / (24 * 60));
  const rest = ((total % (24 * 60)) + 24 * 60) % (24 * 60);
  return {
    date: dayShift ? addDays(date, dayShift) : date,
    time: `${String(Math.floor(rest / 60)).padStart(2, '0')}:${String(rest % 60).padStart(2, '0')}`,
  };
}

/**
 * Where a timed stop ends. Without an end the event would have no length, and
 * clients put their own default (mostly an hour) in its place, so a 20 minute
 * stop came out as an hour (#2641). The place's duration says how long it lasts.
 */
function stopEnd(a: CalendarStopRow, date: string): { date: string; time: string } | null {
  if (a.effective_end_time) return { date, time: a.effective_end_time };
  const start = a.effective_time ?? '';
  const minutes = a.place_duration_minutes;
  return minutes && minutes > 0 && /^\d{2}:\d{2}/.test(start) ? plusMinutes(date, start, minutes) : null;
}

/**
 * Everything TREK knows how to say in iCalendar. Moved out of TripsService
 * unchanged: same statements, same escaping, same folding, same VTIMEZONE
 * fallback, so the emitted bytes are identical for both consumers (the one-time
 * download on the trip route and the subscribable feeds).
 *
 * It is its own domain rather than a method on trips because FeedsService needs
 * calendars without needing the trip aggregate, and because the ICS rules
 * (RFC 5545 folding, floating vs. zoned times) have nothing to do with trips.
 */
@Injectable()
export class CalendarService {
  constructor(
    private readonly reservations: ReservationsService,
    @InjectRepository(Trips) private readonly tripsRepo: TripsRepository,
    @InjectRepository(Days) private readonly daysRepo: DaysRepository,
    @InjectRepository(DayNotes) private readonly dayNotesRepo: DayNotesRepository,
    @InjectRepository(Reservations) private readonly reservationsRepo: ReservationsRepository,
  ) {}

  // ── ICS export ────────────────────────────────────────────────────────────

  /**
   * A trip's calendar as parts rather than as one string.
   *
   * The all-trips feed needs to merge many trips into one document: it has to
   * drop each trip's VCALENDAR wrapper, keep the VEVENTs, and emit each
   * VTIMEZONE once. It used to do that by scanning the finished text back apart
   * line by line — and that scan had to be structural rather than a regex,
   * because a user-supplied SUMMARY can legitimately contain the literal
   * "END:VEVENT". Handing out the parts removes the need to reassemble them.
   */
  async buildTripCalendar(tripId: string | number, options: TripCalendarOptions = {}): Promise<TripCalendar> {
    const trip = await this.tripsRepo.findRaw(tripId);
    if (!trip) throw new NotFoundError('Trip not found');

    // A hotel keeps its dates on the linked stay, not on the reservation: the
    // booking form writes reservation_time = NULL for type 'hotel' and lets
    // day_accommodations carry start day, end day and the check-in/out clock.
    // Joining them here is what lets a stay span its whole range (#1586).
    const reservations = await this.reservationsRepo.listForCalendar(trip.id);

    const esc = (s: string) =>
      s
        .replaceAll(/\\/g, '\\\\')
        .replaceAll(';', '\\;')
        .replaceAll(',', '\\,')
        .replace(/\r?\n/g, '\\n')
        .replaceAll(/\r/g, '');
    const fmtDate = (d: string) => d.replaceAll('-', '');
    const now = new Date().toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
    const uid = (id: number, type: string) => `trek-${type}-${id}@trek`;

    // Format datetime: handles full ISO "2026-03-30T09:00" and time-only "10:00"
    // iCal requires exactly YYYYMMDDTHHMMSS format
    const fmtDateTime = (d: string, refDate?: string) => {
      if (d.includes('T')) {
        const raw = d.replace(/[-:]/g, '').split('.')[0];
        // Pad to 15 chars (YYYYMMDDTHHMMSS) — add missing seconds
        return raw.length === 13 ? raw + '00' : raw;
      }
      // Time-only: combine with reference date. Pad the same way the branch above
      // does rather than unconditionally, because the value can already carry
      // seconds ("10:00:00" is what the booking import stores). Appending
      // regardless made it 17 characters, which fails dtLine's shape check, drops
      // the TZID and leaves a floating time in the feed (#1453 again).
      if (refDate && d.match(/^\d{2}:\d{2}/)) {
        const datePart = refDate.split('T')[0];
        const raw = `${datePart}T${d.replaceAll(':', '')}`.replaceAll('-', '');
        return raw.length === 13 ? raw + '00' : raw;
      }
      return d.replace(/[-:]/g, '');
    };

    // Zones referenced by timed events → the first and last YYYYMMDD they are
    // used on, the span the VTIMEZONE has to cover. Populated by dtLine; emitted
    // once as VTIMEZONE blocks.
    const usedZones = new Map<string, { first: string; last: string }>();
    // Off while the bookings are only looked at (see startsAtClock), so each zone
    // is recorded once, in the order the events are emitted.
    let recordZones = true;

    // Emit a DTSTART/DTEND line, attaching TZID when the event's zone is known so
    // subscribers see the time in TREK's zone. Falls back to a floating local time
    // (unchanged behavior) when no zone resolves or the value is not a date-time.
    const dtLine = (prop: 'DTSTART' | 'DTEND', wallClock: string, zone: string | null, refDate?: string): string => {
      const val = fmtDateTime(wallClock, refDate);
      if (zone && isValidTimeZone(zone) && /^\d{8}T\d{6}$/.test(val)) {
        const day = val.slice(0, 8);
        const span = usedZones.get(zone);
        if (recordZones && !span) usedZones.set(zone, { first: day, last: day });
        else if (recordZones && span) {
          if (day < span.first) span.first = day;
          if (day > span.last) span.last = day;
        }
        return `${prop};TZID=${zone}:${val}\r\n`;
      }
      return `${prop}:${val}\r\n`;
    };

    const events: string[] = [];

    // Trip as all-day event. DTEND is exclusive, so it must be the day *after* the last
    // day. addDays() stays in UTC — building a local-time Date here dropped the trip's
    // last day on any server east of Greenwich (#1453).
    if (trip.start_date && trip.end_date) {
      const endStr = fmtDate(addDays(trip.end_date, 1));
      let ev = `BEGIN:VEVENT\r\nUID:${uid(trip.id, 'trip')}\r\nDTSTAMP:${now}\r\nDTSTART;VALUE=DATE:${fmtDate(trip.start_date)}\r\nDTEND;VALUE=DATE:${endStr}\r\nSUMMARY:${esc(trip.title || 'Trip')}\r\n`;
      if (trip.description) ev += `DESCRIPTION:${esc(trip.description)}\r\n`;
      ev += `END:VEVENT\r\n`;
      events.push(ev);
    }

    // Days with their stops and notes, each read for all days at once.
    const days = await this.daysRepo.listByTrip(trip.id);
    const datedDayIds = days.filter((d) => d.date).map((d) => d.id);
    // A booked night puts a stop of its own on its check-in day, so the route
    // can reach the hotel. That stop is the booking, not a place the traveller
    // planned to visit, and the booking already comes through below as the
    // stay block or its check-in and check-out markers. Read here as well it
    // would put the hotel on the day a second time. The stops of undated days
    // are read too, since a booking linked to one takes its zone from it (#3150);
    // those days are skipped when emitting.
    const stops = await this.reservationsRepo.listCalendarStopsForDays(days.map((d) => d.id));
    const stopsByDay = groupByDay(stops);
    const notesByDay = groupByDay(await this.dayNotesRepo.listByDayIds(datedDayIds));
    const stopById = new Map(stops.map((a) => [a.id, a]));
    const linkedStop = (r: CalendarReservationRow) =>
      r.assignment_id == null ? undefined : stopById.get(Number(r.assignment_id));
    // The bookings whose event stands in for their linked stop, decided below.
    const stopOfBooking = new Map<number, CalendarStopRow>();

    // Transport/flight reservations carry no top-level reservation_time; their
    // times live per endpoint (local_date + local_time) in reservation_endpoints.
    const endpointsMap = await this.reservations.loadEndpointsByTrip(tripId);
    const isDate = (s: string | null | undefined) => !!s && /^\d{4}-\d{2}-\d{2}$/.test(s);
    const isTime = (s: string | null | undefined) => !!s && /^\d{2}:\d{2}/.test(s);

    // "YYYY-MM-DD", full ISO, or a bare "HH:MM" → date/time parts. Endpoints carry
    // local_date/local_time separately; reservation_time and reservation_end_time
    // are combined strings, and the end is frequently just a bare clock alongside
    // the reservation's own date.
    const dateOf = (s: string | null | undefined): string | null => {
      if (!s) return null;
      const d = s.includes('T') ? s.split('T')[0] : s;
      return isDate(d) ? d : null;
    };
    const timeOf = (s: string | null | undefined): string | null => {
      if (!s) return null;
      const t = s.includes('T') ? s.split('T')[1] : s;
      return t && isTime(t) ? t : null;
    };

    // The one zone a set of stops agrees on, or null when they name none or several.
    const soleZone = (list: CalendarStopRow[]): string | null => {
      const zones = new Set(list.map((a) => resolveTimeZone(a.place_lat, a.place_lng)).filter((z) => z !== null));
      return zones.size === 1 ? [...zones][0] : null;
    };
    const tripZone = soleZone(stops);
    // A booking's own place gives its zone. One without, a restaurant booked
    // against a plan stop, takes the stop's instead of floating (#3150). One
    // with neither takes the zone its day's stops agree on, else the one the
    // whole trip agrees on. A transport is left out of that guess: its two
    // ends can sit in different zones, and its endpoints say which.
    const placeZoneOf = (r: CalendarReservationRow): string | null => {
      const stop = linkedStop(r);
      const own =
        resolveTimeZone(r.place_lat, r.place_lng) ?? (stop ? resolveTimeZone(stop.place_lat, stop.place_lng) : null);
      if (own || isTransportReservationType(r.type)) return own;
      const startDate = dateOf(r.reservation_time);
      const dayId = r.day_id ?? days.find((d) => startDate && d.date === startDate)?.id;
      return (dayId == null ? null : soleZone(stopsByDay.get(Number(dayId)) ?? [])) ?? tripZone;
    };

    // Per stay, the booking whose all-day block its two markers replace. Decided
    // once here rather than twice, because the markers have to hand on exactly
    // what the block they replaced would have said (#2136).
    const stayCarriedByMarkers = new Map<number, any>();
    for (const r of reservations) {
      if (isTime(r.stay_check_in) && isTime(r.stay_check_out) && r.stay_first_reservation_id === r.id) {
        stayCarriedByMarkers.set(Number(r.accommodation_id), r);
      }
    }

    // Build the DTSTART/DTEND lines for a reservation, or null when it has no
    // calendar-placeable time. Transports keep a per-side wall clock + IANA zone
    // on their endpoints, so consult a timed departure endpoint FIRST: transports
    // also carry a top-level reservation_time (TransportModal stamps it), whose
    // only zone is the linked place — flights have none — so that branch floats
    // both ends in the subscribed feed (#1453). Hotels/restaurants have no
    // endpoints and fall through to reservation_time.
    const buildReservationTimeLines = (r: any): string | null => {
      // A stay wins over everything below: it is the only source that knows how
      // long the booking lasts. Emitted as an all-day range over every night, so
      // the hotel sits above the day in a subscribed calendar instead of
      // appearing once on the arrival day (#1586).
      // end_day_id is the CHECK-OUT day, and the block is meant to cover it too:
      // a 26th-to-30th booking should read as a five-day block, not as the four
      // nights it contains. DTEND is exclusive, so it is check-out plus one day.
      // Dropping that +1 hides the departure day; it is not a stray off-by-one
      // (#1869).
      // Unless the stay records BOTH ends of its clock, in which case the two
      // timed markers below already say everything the block would, and saying
      // it twice buries a week of calendar under a bar nobody can act on
      // (#2136). Knowing only one end still needs the block: it is the only
      // thing carrying the other end's date.
      //
      // Only for the booking the markers actually stand in for, though. They are
      // emitted once per stay and titled from its lowest-id reservation, so a
      // second room on the same stay is represented by nothing else and keeps
      // its block.
      const markersCover = stayCarriedByMarkers.get(Number(r.accommodation_id)) === r;
      if (isDate(r.stay_start_date) && !markersCover) {
        const lastDay =
          isDate(r.stay_end_date) && r.stay_end_date >= r.stay_start_date ? r.stay_end_date : r.stay_start_date;
        return (
          `DTSTART;VALUE=DATE:${fmtDate(r.stay_start_date)}\r\n` +
          `DTEND;VALUE=DATE:${fmtDate(addDays(lastDay, 1))}\r\n`
        );
      }
      // A fully timed stay is carried by its markers alone, so the booking row
      // itself has nothing left to place.
      if (isDate(r.stay_start_date)) return null;

      const eps = endpointsMap.get(r.id);
      const ordered = eps && eps.length > 0 ? [...eps].sort((a, b) => a.sequence - b.sequence) : null;
      const first = ordered?.[0];

      if (first && isDate(first.local_date) && isTime(first.local_time)) {
        // Transport: departure endpoint zone drives DTSTART, arrival drives DTEND.
        // Prefer the stored IANA zone; fall back to the endpoint's coordinates.
        const last = ordered![ordered!.length - 1];
        const startZone = first.timezone || resolveTimeZone(first.lat, first.lng);
        const startWallClock = `${first.local_date}T${first.local_time}`;
        let out = dtLine('DTSTART', startWallClock, startZone);
        if (last !== first && isDate(last.local_date) && isTime(last.local_time)) {
          const endZone = last.timezone || resolveTimeZone(last.lat, last.lng);
          out += dtLine('DTEND', `${last.local_date}T${last.local_time}`, endZone);
        } else if (r.reservation_end_time) {
          // No second timed endpoint, so the arrival side still lives in
          // reservation_end_time — a rental car imported with only a geocoded
          // pickup is the common shape. Taking the endpoint branch without this
          // would drop the DTEND the reservation_time branch used to emit and
          // shrink a multi-day booking to a point. The departure zone is the
          // best one on hand for that end too.
          const endDt = fmtDateTime(r.reservation_end_time, startWallClock);
          if (endDt.length >= 15) out += dtLine('DTEND', r.reservation_end_time, startZone, startWallClock);
        }
        return out;
      }

      if (r.reservation_time) {
        const datePart = r.reservation_time.includes('T') ? r.reservation_time.split('T')[0] : r.reservation_time;
        if (!isDate(datePart)) return null; // time-only (relative "Day N" trips)
        if (r.reservation_time.includes('T')) {
          // Hotels/restaurants: the zone of the booking's place, else its stop's.
          const zone = placeZoneOf(r);
          let out = dtLine('DTSTART', r.reservation_time, zone);
          if (r.reservation_end_time) {
            const endDt = fmtDateTime(r.reservation_end_time, r.reservation_time);
            if (endDt.length >= 15) out += dtLine('DTEND', r.reservation_end_time, zone, r.reservation_time);
          }
          return out;
        }
        // Date-only start. RFC 5545 makes a DATE event without DTEND exactly one
        // day long, so a booking that does record an end date still collapsed
        // onto its first day (#1869); an all-day multi-day event coming through
        // the booking import (kitinerary-mapper passes date-only start/end
        // straight through) is the common shape. Same rule as the stay branch:
        // DTEND is exclusive, hence the end day plus one. Only the date part is
        // used, because DTSTART;VALUE=DATE and a timed DTEND may not be mixed.
        const endDatePart = r.reservation_end_time ? String(r.reservation_end_time).split('T')[0] : '';
        if (isDate(endDatePart) && endDatePart >= r.reservation_time) {
          return (
            `DTSTART;VALUE=DATE:${fmtDate(r.reservation_time)}\r\n` +
            `DTEND;VALUE=DATE:${fmtDate(addDays(endDatePart, 1))}\r\n`
          );
        }
        return `DTSTART;VALUE=DATE:${fmtDate(r.reservation_time)}\r\n`;
      }

      // Untimed transport (endpoint has a date but no clock, no reservation_time).
      if (first && isDate(first.local_date)) {
        return `DTSTART;VALUE=DATE:${fmtDate(first.local_date)}\r\n`;
      }

      // Last resort: the days the booking is pinned to. TransportModal writes
      // reservation_time = NULL when its optional time pickers are left blank
      // while still setting day_id/end_day_id, so for a hand-typed rental car —
      // or bus, train, ferry, anything from that form — the day rows are the ONLY
      // record of when it happens, and reading nothing else kept those bookings
      // out of the subscribed calendar entirely (#2068).
      if (isDate(r.day_date)) {
        const lastDay = isDate(r.end_day_date) && r.end_day_date >= r.day_date ? r.end_day_date : r.day_date;
        return `DTSTART;VALUE=DATE:${fmtDate(r.day_date)}\r\n` + `DTEND;VALUE=DATE:${fmtDate(addDays(lastDay, 1))}\r\n`;
      }
      return null;
    };

    // A booking that is a WINDOW rather than an activity: something is handed over
    // and handed back, and the days in between carry nothing. Read as one block
    // from drop-off to pick-up, a week of airport parking sat across the whole
    // week of a subscribed calendar (#2068). The day plan already draws this
    // distinction for parking (client/src/utils/dayMerge.ts, #1937); the exporter
    // never learned it. A rental is the mirror image — you pick it up first.
    const WINDOW_WORDING: Record<string, { start: string; end: string }> = {
      car: { start: 'Pickup', end: 'Drop-off' },
      parking: { start: 'Drop-off', end: 'Pickup' },
    };
    /**
     * How long a hand-over — and a check-in/check-out marker without an
     * until-clock — reads as. Zero-length events collapse in most clients.
     */
    const HANDOVER_MINUTES = 60;

    interface WindowSide {
      date: string;
      time: string | null;
      zone: string | null;
    }

    // Which endpoint is which side. The ROLE decides, because an import can drop
    // one (failed geocoding) and a surviving return endpoint must not masquerade
    // as the pickup. Positional first/last is only a fallback when no role is
    // present at all, and only with more than one endpoint, so a lone endpoint is
    // never both sides (#1721).
    const endpointOf = (reservationId: number, side: 'from' | 'to') => {
      const eps = endpointsMap.get(reservationId);
      const ordered = eps && eps.length > 0 ? [...eps].sort((a, b) => a.sequence - b.sequence) : [];
      const byRole = ordered.find((e) => e.role === side);
      if (byRole) return byRole;
      const noRoles = !ordered.some((e) => e.role === 'from' || e.role === 'to');
      if (!noRoles || ordered.length < 2) return undefined;
      return side === 'from' ? ordered[0] : ordered[ordered.length - 1];
    };
    const windowSidesOf = (r: any): { start: WindowSide | null; end: WindowSide | null } => {
      const startEp = endpointOf(r.id, 'from');
      const endEp = endpointOf(r.id, 'to');

      const fromEp = (ep: typeof startEp): WindowSide | null =>
        ep && isDate(ep.local_date) && isTime(ep.local_time)
          ? { date: ep.local_date!, time: ep.local_time!, zone: ep.timezone || resolveTimeZone(ep.lat, ep.lng) }
          : null;

      const placeZone = placeZoneOf(r);
      const start =
        fromEp(startEp) ??
        (() => {
          const date = dateOf(r.reservation_time) ?? (isDate(r.day_date) ? r.day_date : null);
          return date ? { date, time: timeOf(r.reservation_time), zone: placeZone } : null;
        })();
      const end =
        fromEp(endEp) ??
        (() => {
          const date =
            dateOf(r.reservation_end_time) ??
            (isDate(r.end_day_date) ? r.end_day_date : null) ??
            (timeOf(r.reservation_end_time) ? (start?.date ?? null) : null);
          // The return side rarely carries a zone of its own. Inheriting the
          // pickup's is what the single block did, and letting it float instead
          // renders it in the subscriber's zone rather than the trip's (#1453).
          return date ? { date, time: timeOf(r.reservation_end_time), zone: placeZone ?? start?.zone ?? null } : null;
        })();
      return { start, end };
    };

    // Split only when BOTH hand-overs resolve on DIFFERENT days. A same-day
    // booking is one sitting and keeps its single event; a one-sided one — only
    // the pickup was geocoded — keeps the block, which is then the only carrier
    // of the return time at all.
    const windowSplit = new Map<number, { start: WindowSide; end: WindowSide }>();
    for (const r of reservations) {
      if (!WINDOW_WORDING[r.type as string]) continue;
      const { start, end } = windowSidesOf(r);
      if (start && end && start.date !== end.date) windowSplit.set(r.id, { start, end });
    }

    // A flight or train with connections, as one event per leg (#2389), so each
    // segment shows its own departure and arrival and the layover between them is
    // visible in the calendar. Only when every leg has a dated departure clock:
    // anything less keeps the single event, which is then the only carrier of the
    // times there are. Each leg takes its zones from the stop endpoints when the
    // booking has one per airport or station, and floats otherwise.
    const dayDate = new Map<number, string>();
    for (const d of days) if (isDate(d.date)) dayDate.set(Number(d.id), d.date);
    interface LegTimes {
      from: string | null;
      to: string | null;
      label: string | null;
      confirmation: string | null;
      dep: { date: string; time: string; zone: string | null };
      arr: { date: string; time: string; zone: string | null } | null;
    }
    const legsOf = (r: any): LegTimes[] | null => {
      if (r.type !== 'flight' && r.type !== 'train' && r.type !== 'cruise') return null;
      const meta = decodeJson(RESERVATION_METADATA, r.metadata, `reservation ${r.id}`);
      const legs = Array.isArray(meta.legs) ? meta.legs : [];
      if (legs.length < 2) return null;
      const eps = endpointsMap.get(r.id);
      const ordered = eps && eps.length === legs.length + 1 ? [...eps].sort((a, b) => a.sequence - b.sequence) : null;
      const zoneAt = (i: number): string | null => {
        const ep = ordered?.[i];
        return ep ? ep.timezone || resolveTimeZone(ep.lat, ep.lng) : null;
      };
      const out: LegTimes[] = [];
      for (let i = 0; i < legs.length; i++) {
        const leg = legs[i] ?? {};
        const depDate = dayDate.get(Number(leg.dep_day_id));
        if (!depDate || !isTime(leg.dep_time)) return null;
        const arrDate = dayDate.get(Number(leg.arr_day_id ?? leg.dep_day_id));
        const label = [leg.airline, leg.flight_number ?? leg.train_number].filter(Boolean).join(' ') || null;
        out.push({
          from: leg.from ?? ordered?.[i]?.code ?? ordered?.[i]?.name ?? null,
          to: leg.to ?? ordered?.[i + 1]?.code ?? ordered?.[i + 1]?.name ?? null,
          label,
          confirmation: leg.confirmation_number ?? null,
          dep: { date: depDate, time: leg.dep_time, zone: zoneAt(i) },
          arr: arrDate && isTime(leg.arr_time) ? { date: arrDate, time: leg.arr_time, zone: zoneAt(i + 1) } : null,
        });
      }
      return out;
    };

    // Where a transport takes the traveller, as a LOCATION (and GEO) a calendar can
    // navigate to (#2909): the route in the description is no address. The side is
    // the one the traveller has to get to, the destination of a drive of their own
    // and the departure of a ride they board, as the per-leg events do. A
    // location the booking states itself still wins.
    const SELF_DRIVEN_TYPES = new Set(['car', 'bicycle']);
    const locationLines = (
      r: { id: number; type?: string | null; location?: string | null },
      side: 'from' | 'to' = SELF_DRIVEN_TYPES.has(r.type ?? '') ? 'to' : 'from',
    ): string => {
      if (r.location) return `LOCATION:${esc(r.location)}\r\n`;
      const ep = isTransportReservationType(r.type) ? endpointOf(r.id, side) : undefined;
      const name = ep?.name || ep?.code;
      // A booking that replaced its plan stop is where the stop was (#3150), by
      // its address or, for a place without one, by its name.
      const stop = stopOfBooking.get(r.id);
      const stopAddress = stop ? stop.place_address || stop.place_name : null;
      if ((!ep || !name) && stopAddress) return `LOCATION:${esc(stopAddress)}\r\n`;
      if (!ep || !name) return '';
      const geo = Number.isFinite(ep.lat) && Number.isFinite(ep.lng) ? `GEO:${ep.lat};${ep.lng}\r\n` : '';
      return `LOCATION:${esc(name)}\r\n${geo}`;
    };

    // A booking linked to a plan stop and the stop are one appointment (#3150).
    // Where the booking starts at a clock on the stop's own day, its event wins
    // and the stop is left out, as a booked night's stop is; the booking then
    // carries what the stop said and it does not (place, zone, notes, end). A
    // booking without a clock, or on another day, leaves the stop alone, since
    // the stop is then the only record of the visit on its day.
    const clockStartDate = (r: CalendarReservationRow): string | null => {
      const split = windowSplit.get(r.id);
      if (split) return split.start.time === null ? null : split.start.date;
      const legs = legsOf(r);
      if (legs) return legs[0].dep.date;
      const lines = buildReservationTimeLines(r);
      const start = lines ? /^DTSTART(?:;TZID=[^:]+)?:(\d{4})(\d{2})(\d{2})T/.exec(lines) : null;
      return start ? `${start[1]}-${start[2]}-${start[3]}` : null;
    };
    recordZones = false;
    for (const r of reservations) {
      const stop = linkedStop(r);
      const date = stop ? clockStartDate(r) : null;
      if (stop && date && date === dayDate.get(Number(stop.day_id))) stopOfBooking.set(r.id, stop);
    }
    recordZones = true;
    const replacedStops = new Set([...stopOfBooking.values()].map((a) => a.id));

    // The stop's end for the booking that replaced it and records none, when
    // both start at the same moment; without it the booking is only a point.
    const borrowedEnd = (timeLines: string, a: CalendarStopRow): string => {
      const start = /^DTSTART(?:;TZID=([^:]+))?:(\d{8}T\d{4})/.exec(timeLines);
      const date = dayDate.get(Number(a.day_id));
      if (!start || timeLines.includes('DTEND') || !date || !a.effective_time) return '';
      if (start[2] !== `${fmtDate(date)}T${a.effective_time.slice(0, 5).replace(':', '')}`) return '';
      const end = stopEnd(a, date);
      return end ? dtLine('DTEND', end.time, start[1] || null, `${end.date}T00:00`) : '';
    };

    // Each dated day: its timed stops as events, the rest in one all-day summary.
    for (const day of days) {
      if (!day.date) continue;
      const assignments = (stopsByDay.get(day.id) ?? []).filter((a) => !replacedStops.has(a.id));
      const notes = notesByDay.get(day.id) ?? [];

      const timed = assignments.filter((a) => a.effective_time);
      const untimed = assignments.filter((a) => !a.effective_time);

      // Timed assignments → individual events
      for (const a of timed) {
        const zone = resolveTimeZone(a.place_lat, a.place_lng);
        let ev = `BEGIN:VEVENT\r\nUID:${uid(a.id, 'assign')}\r\nDTSTAMP:${now}\r\n`;
        ev += dtLine('DTSTART', a.effective_time, zone, day.date + 'T00:00');
        const end = stopEnd(a, day.date);
        if (end) ev += dtLine('DTEND', end.time, zone, end.date + 'T00:00');
        ev += `SUMMARY:${esc(a.place_name)}\r\n`;
        let desc = '';
        if (a.notes) desc += a.notes;
        if (a.place_address) desc += (desc ? '\n' : '') + a.place_address;
        if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
        if (a.place_address) ev += `LOCATION:${esc(a.place_address)}\r\n`;
        ev += `END:VEVENT\r\n`;
        events.push(ev);
      }

      // Build all-day summary event if there are untimed activities or notes,
      // unless the subscriber asked for a calendar without them: the summary
      // sits above every day and can crowd out everything else there (#2602).
      if (options.dayEvents !== false && (untimed.length > 0 || notes.length > 0)) {
        const dayTitle = day.title || `Day ${day.day_number}`;
        const endStr = fmtDate(addDays(day.date, 1));

        let ev = `BEGIN:VEVENT\r\nUID:${uid(day.id, 'day')}\r\nDTSTAMP:${now}\r\n`;
        ev += `DTSTART;VALUE=DATE:${fmtDate(day.date)}\r\nDTEND;VALUE=DATE:${endStr}\r\n`;
        ev += `SUMMARY:${esc(dayTitle)}\r\n`;

        let desc = '';
        if (untimed.length > 0) {
          desc += untimed
            .map((a) => {
              let line = `• ${a.place_name}`;
              if (a.place_address) line += ` (${a.place_address})`;
              if (a.notes) line += ` — ${a.notes}`;
              return line;
            })
            .join('\n');
        }
        if (notes.length > 0) {
          if (desc) desc += '\n\n';
          desc +=
            'Notes:\n' +
            notes
              .map((n) => {
                const line = n.time ? `${n.time} — ${n.text}` : `• ${n.text}`;
                return line;
              })
              .join('\n');
        }
        if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
        ev += `END:VEVENT\r\n`;
        events.push(ev);
      }
    }

    // Reservations as events
    for (const r of reservations) {
      // The two hand-over events below stand in for this booking entirely.
      if (windowSplit.has(r.id)) continue;
      const legs = legsOf(r);
      if (legs) {
        const desc = describeReservation(r);
        legs.forEach((leg, i) => {
          const route = [leg.from, leg.to].filter(Boolean).join(' → ');
          let ev = `BEGIN:VEVENT\r\nUID:${uid(r.id, `res-leg${i + 1}`)}\r\nDTSTAMP:${now}\r\n`;
          ev += dtLine('DTSTART', leg.dep.time, leg.dep.zone, `${leg.dep.date}T00:00`);
          if (leg.arr) ev += dtLine('DTEND', leg.arr.time, leg.arr.zone ?? leg.dep.zone, `${leg.arr.date}T00:00`);
          ev += `SUMMARY:${esc([r.title, route].filter(Boolean).join(': '))}\r\n`;
          const legLines = [
            leg.label,
            leg.confirmation ? `Confirmation: ${leg.confirmation}` : null,
            `Leg ${i + 1} of ${legs.length}`,
          ]
            .filter(Boolean)
            .join('\n');
          ev += `DESCRIPTION:${esc([legLines, desc].filter(Boolean).join('\n'))}\r\n`;
          if (leg.from) ev += `LOCATION:${esc(leg.from)}\r\n`;
          ev += `END:VEVENT\r\n`;
          events.push(ev);
        });
        continue;
      }
      const timeLines = buildReservationTimeLines(r);
      if (!timeLines) continue;

      let ev = `BEGIN:VEVENT\r\nUID:${uid(r.id, 'res')}\r\nDTSTAMP:${now}\r\n`;
      const stop = stopOfBooking.get(r.id);
      ev += timeLines + (stop ? borrowedEnd(timeLines, stop) : '');
      ev += `SUMMARY:${esc(r.title)}\r\n`;

      const desc = describeReservation(r);
      if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
      ev += locationLines(r);
      ev += `END:VEVENT\r\n`;
      events.push(ev);
    }

    // Everything a booking says about itself, minus its times. Hoisted out of the
    // event loop because a window booking's two hand-over events carry the same
    // lines: dropping the block must not drop the route or the confirmation with
    // it (#2068).
    function describeReservation(r: any): string {
      const meta = decodeJson(RESERVATION_METADATA, r.metadata, `reservation ${r.id}`);
      let desc = r.type ? `Type: ${r.type}` : '';
      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 (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(' → ')}`;
        // A segment booked under its own reference gets its own line (#1943): at
        // the gate it is that code the airline asks for, not the booking's. No
        // leg reference, no extra line, so an existing feed stays byte-identical.
        for (const leg of meta.legs as { from?: string; to?: string; confirmation_number?: string }[]) {
          if (!leg.confirmation_number) continue;
          const segment = [leg.from, leg.to].filter(Boolean).join('-');
          desc += `\nConfirmation${segment ? ` ${segment}` : ''}: ${leg.confirmation_number}`;
        }
      } else if (meta.departure_airport || meta.arrival_airport) {
        if (meta.departure_airport) desc += `\nFrom: ${meta.departure_airport}`;
        if (meta.arrival_airport) desc += `\nTo: ${meta.arrival_airport}`;
      } else {
        // Endpoint-based transport without route metadata: derive it from endpoints.
        const eps = endpointsMap.get(r.id);
        if (eps && eps.length > 1) {
          const stops = [...eps]
            .sort((a, b) => a.sequence - b.sequence)
            .map((e) => e.code || e.name)
            .filter(Boolean);
          if (stops.length > 1) desc += `\nRoute: ${stops.join(' → ')}`;
        }
      }
      if (meta.train_number) desc += `\nTrain: ${meta.train_number}`;
      if (r.notes) desc += `\n${r.notes}`;
      const stopNotes = stopOfBooking.get(r.id)?.notes;
      if (stopNotes && stopNotes !== r.notes) desc += (desc ? '\n' : '') + stopNotes;
      return desc;
    }

    // Check-in and check-out as their own timed events, when the stay records the
    // clock (#1586). They are separate from the all-day stay above on purpose: an
    // all-day event cannot carry a time, and "be there at 15:00" is the part a
    // subscriber actually wants a reminder for. Emitted per stay rather than per
    // reservation so a stay whose reservation was deleted still shows them.
    // The reservation is read through a subquery rather than a LEFT JOIN: nothing
    // stops two bookings from pointing at the same accommodation, and a join fans
    // the stay out into one row per booking. Since the check-in/check-out UIDs are
    // keyed by the stay, that emitted the same UID twice and clients then pick one
    // of the duplicates at random (#1869). Lowest id wins so the title is stable
    // across exports.
    const stays = await this.reservationsRepo.listPublicStaysForCalendar(trip.id);

    for (const stay of stays) {
      const name = stay.reservation_title || stay.place_name || 'Accommodation';
      const zone = resolveTimeZone(stay.place_lat, stay.place_lng);
      // No end day (the day row was removed) → check out on the arrival day.
      const checkOutDate = isDate(stay.end_date) ? stay.end_date : stay.start_date;
      // Where these markers ARE the booking, they inherit what its block used to
      // carry: confirmation number, notes, and (for a stay whose place holds no
      // address) the booking's own location. Otherwise the block still says all
      // of that, and repeating it would change a feed that already went out: the
      // same rule the hand-overs follow (#2068, #2136).
      const booking = stayCarriedByMarkers.get(stay.id);
      const desc = booking ? describeReservation(booking) : '';
      const address = stay.place_address || (booking ? booking.location : null);

      const marker = (
        kind: 'checkin' | 'checkout',
        date: string,
        time: string,
        summary: string,
        endTime?: string | null,
      ) => {
        const ref = `${date}T00:00`;
        let ev = `BEGIN:VEVENT\r\nUID:${uid(stay.id, kind)}\r\nDTSTAMP:${now}\r\n`;
        ev += dtLine('DTSTART', time, zone, ref);
        if (isTime(endTime)) {
          // An until-clock that is not later than the check-in is a late-arrival
          // window running past midnight ("22:00 to 02:00"): nothing on the way
          // in orders the two, and emitting it as recorded puts the DTEND before
          // the DTSTART, which clients drop outright. Since the stay lost its
          // all-day block there is nothing left to fall back on, so the window
          // ends on the following day (#2136).
          const endDate = endTime!.slice(0, 5) <= time.slice(0, 5) ? addDays(date, 1) : date;
          ev += dtLine('DTEND', endTime!, zone, `${endDate}T00:00`);
        } else {
          // No recorded end → the same default hour the hand-overs read as.
          // Without a DTEND the marker is a zero-length point, and since a fully
          // timed stay is represented by nothing else, several clients rendered
          // the whole booking as clutter or hid it outright (#2136). plusMinutes
          // carries the date across midnight, so a late check-out ends on the
          // following day instead of before it started.
          const stop = plusMinutes(date, time, HANDOVER_MINUTES);
          ev += dtLine('DTEND', stop.time, zone, `${stop.date}T00:00`);
        }
        ev += `SUMMARY:${esc(summary)}\r\n`;
        if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
        if (address) ev += `LOCATION:${esc(address)}\r\n`;
        ev += `END:VEVENT\r\n`;
        events.push(ev);
      };

      if (isDate(stay.start_date) && isTime(stay.check_in)) {
        marker('checkin', stay.start_date, stay.check_in, `Check-in: ${name}`, stay.check_in_end);
      }
      if (isDate(checkOutDate) && isTime(stay.check_out)) {
        marker('checkout', checkOutDate, stay.check_out, `Check-out: ${name}`);
      }
    }

    // The two hand-overs of a window booking, as their own events.
    //
    // For a rental this is the car-rental analogue of the check-in/check-out
    // markers above (#1721): additive, sitting beside the booking's own block.
    // For a booking whose two ends fall on DIFFERENT days it is not additive —
    // `windowSplit` dropped the block, and these two ARE the booking (#2068), so
    // they carry its description and a real duration instead of being points.
    //
    // Parking only ever appears here split. A same-day parking is one sitting and
    // keeps the single event it has always had.
    for (const r of reservations) {
      const wording = WINDOW_WORDING[r.type as string];
      if (!wording) continue;
      const split = windowSplit.get(r.id);
      if (!split && r.type !== 'car') continue;

      const { start, end } = split ?? windowSidesOf(r);
      const desc = split ? describeReservation(r) : '';

      const handover = (kind: 'pickup' | 'dropoff', side: WindowSide, summary: string) => {
        let ev = `BEGIN:VEVENT\r\nUID:${uid(r.id, kind)}\r\nDTSTAMP:${now}\r\n`;
        if (side.time) {
          const ref = `${side.date}T00:00`;
          ev += dtLine('DTSTART', side.time, side.zone, ref);
          // Only where these events replace the block: adding a DTEND to the
          // additive markers would change a feed that already went out.
          if (split) {
            const stop = plusMinutes(side.date, side.time, HANDOVER_MINUTES);
            ev += dtLine('DTEND', stop.time, side.zone, `${stop.date}T00:00`);
          }
        } else if (split) {
          // No clock anywhere — a rental typed into the planner with the optional
          // time pickers left blank. One all-day event per hand-over still beats a
          // block across the whole window.
          ev += `DTSTART;VALUE=DATE:${fmtDate(side.date)}\r\n`;
          ev += `DTEND;VALUE=DATE:${fmtDate(addDays(side.date, 1))}\r\n`;
        } else {
          return;
        }
        ev += `SUMMARY:${esc(summary)}\r\n`;
        if (desc) ev += `DESCRIPTION:${esc(desc)}\r\n`;
        // A hand-over happens where the car is collected or returned.
        ev += locationLines(r, kind === 'pickup' ? 'from' : 'to');
        ev += `END:VEVENT\r\n`;
        events.push(ev);
      };

      // The wording is per type, the UID is per side: a rental is picked up first
      // and dropped off at the end, a parking is the other way round, but the
      // first side of the window keeps the same UID either way so an existing
      // subscription does not grow a duplicate.
      if (start) handover('pickup', start, `${wording.start}: ${r.title}`);
      if (end) handover('dropoff', end, `${wording.end}: ${r.title}`);
    }

    // Every referenced zone gets a VTIMEZONE. They are emitted before the first
    // event so the TZID references resolve; keyed by TZID so a merged calendar
    // can define each one once.
    const timezones = new Map<string, string>();
    for (const [zone, span] of usedZones) timezones.set(zone, buildVTimezone(zone, span.first, span.last));

    // \w + space/tab, not \s: JS \s admits U+3000 and friends — codepoints
    // Node's header validation refuses, so they 500'd the export (#2165).
    const safeFilename = (trip.title || 'trek-trip').replace(/["\r\n]/g, '').replace(/[^\w \t.-]/g, '_');
    return {
      calName: esc(trip.title || 'TREK Trip'),
      filename: `${safeFilename}.ics`,
      timezones,
      events,
    };
  }

  /** One trip's calendar as a finished, foldable VCALENDAR document. */
  async exportICS(
    tripId: string | number,
    options: TripCalendarOptions = {},
  ): Promise<{ ics: string; filename: string }> {
    const cal = await this.buildTripCalendar(tripId, options);
    const ics =
      CALENDAR_HEADER +
      `X-WR-CALNAME:${cal.calName}\r\n` +
      [...cal.timezones.values()].join('') +
      cal.events.join('') +
      'END:VCALENDAR\r\n';
    return { ics: foldICS(ics), filename: cal.filename };
  }
}