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.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(planner): order flights across time zones by when they actually leave
Maurice1b6a156969cb
diff --git a/client/src/utils/dayMerge.test.ts b/client/src/utils/dayMerge.test.tsindex 5f99670af..9511a8b22 100644--- a/client/src/utils/dayMerge.test.ts+++ b/client/src/utils/dayMerge.test.ts@@ -648,3 +648,95 @@ describe('seatTimedDrop', () => {})})++// The report behind #2929: Auckland to Los Angeles leaves at 20:20 and lands at 12:25 the+// same date, local time at each end; the flight on to Seattle leaves Los Angeles at 17:00.+// By the clock alone 17:00 comes first, so the second flight was drawn above the first.+describe('getMergedItems: bookings in different time zones (#2929)', () => {+ const DAY = 5+ const days = [{ id: DAY, day_number: 1, date: '2026-11-20' }]+ const flight = (id: number, time: string, end: string, from: string | null, to: string | null) => ({+ id, type: 'flight', day_id: DAY, end_day_id: DAY,+ reservation_time: `2026-11-20T${time}`, reservation_end_time: `2026-11-20T${end}`,+ metadata: JSON.stringify({ ...(from ? { departure_timezone: from } : {}), ...(to ? { arrival_timezone: to } : {}) }),+ })+ const toLA = flight(1, '20:20', '12:25', 'Pacific/Auckland', 'America/Los_Angeles')+ const toSeattle = flight(2, '17:00', '19:45', 'America/Los_Angeles', 'America/Los_Angeles')+ const ids = (items: MergedItem[]) => items.map(i => i.data.id)++ it('puts the Auckland flight ahead of the Los Angeles one it connects to', () => {+ for (const dayTransports of [[toLA, toSeattle], [toSeattle, toLA]]) {+ expect(ids(getMergedItems({ dayAssignments: [], dayNotes: [], dayTransports, dayId: DAY }))).toEqual([1, 2])+ }+ })++ it('keeps the stops of the day where their clock puts them', () => {+ const dayAssignments = [+ { id: 10, order_index: 0, place: { place_time: '09:00' } },+ { id: 11, order_index: 1, place: { place_time: '18:00' } },+ ]+ const result = getMergedItems({ dayAssignments, dayNotes: [], dayTransports: [toSeattle, toLA], dayId: DAY })+ // The flights swap the slots they hold between them (17:00 and 20:20); the stops stay put.+ expect(result.map(i => `${i.type}:${i.data.id}`)).toEqual(['place:10', 'transport:1', 'place:11', 'transport:2'])+ })++ it('reads the zone from the endpoints when the metadata names none', () => {+ const endpointsOf = (fromTz: string, toTz: string) => [+ { role: 'from', sequence: 0, name: 'A', code: null, lat: 0, lng: 0, timezone: fromTz, local_time: null, local_date: null },+ { role: 'to', sequence: 1, name: 'B', code: null, lat: 0, lng: 0, timezone: toTz, local_time: null, local_date: null },+ ]+ const a = { ...flight(1, '20:20', '12:25', null, null), endpoints: endpointsOf('Pacific/Auckland', 'America/Los_Angeles') }+ const b = { ...flight(2, '17:00', '19:45', null, null), endpoints: endpointsOf('America/Los_Angeles', 'America/Los_Angeles') }+ expect(ids(getMergedItems({ dayAssignments: [], dayNotes: [], dayTransports: [b, a], dayId: DAY }))).toEqual([1, 2])+ })++ it('orders the legs of one multi-leg booking by when they leave', () => {+ const booking = {+ id: 3, type: 'flight', day_id: DAY, end_day_id: DAY,+ reservation_time: '2026-11-20T20:20', reservation_end_time: '2026-11-20T19:45',+ endpoints: [+ { role: 'from', sequence: 0, name: 'Auckland', code: 'AKL', lat: -37.0, lng: 174.8, timezone: 'Pacific/Auckland', local_time: null, local_date: null },+ { role: 'stop', sequence: 1, name: 'Los Angeles', code: 'LAX', lat: 33.9, lng: -118.4, timezone: 'America/Los_Angeles', local_time: null, local_date: null },+ { role: 'to', sequence: 2, name: 'Seattle', code: 'SEA', lat: 47.4, lng: -122.3, timezone: 'America/Los_Angeles', local_time: null, local_date: null },+ ],+ metadata: JSON.stringify({ legs: [+ { from: 'AKL', to: 'LAX', dep_day_id: DAY, dep_time: '20:20', arr_day_id: DAY, arr_time: '12:25' },+ { from: 'LAX', to: 'SEA', dep_day_id: DAY, dep_time: '17:00', arr_day_id: DAY, arr_time: '19:45' },+ ] }),+ }+ const dayTransports = getTransportForDay({ reservations: [booking], dayId: DAY, dayAssignmentIds: [], days })+ const legs = getMergedItems({ dayAssignments: [], dayNotes: [], dayTransports, dayId: DAY }).map(i => i.data.__leg.from)+ expect(legs).toEqual(['AKL', 'LAX'])+ })++ it('orders by the clock when a booking names no zone', () => {+ const noZone = flight(1, '20:20', '12:25', null, null)+ expect(ids(getMergedItems({ dayAssignments: [], dayNotes: [], dayTransports: [noZone, toSeattle], dayId: DAY }))).toEqual([2, 1])+ })++ it('orders by the clock when the time carries no date', () => {+ const a = { ...toLA, reservation_time: '20:20' }+ const b = { ...toSeattle, reservation_time: '17:00' }+ expect(ids(getMergedItems({ dayAssignments: [], dayNotes: [], dayTransports: [a, b], dayId: DAY }))).toEqual([2, 1])+ })++ it('reads the arrival zone on the day an overnight flight lands', () => {+ const NEXT = 6+ // Leaves Auckland the evening before and lands in Los Angeles at 12:25 local (20:25 UTC).+ // A flight out of New York at 14:00 local (19:00 UTC) left before it, though its clock+ // reads later, and 12:25 read in Auckland's zone would put the landing a day early.+ const overnight = {+ id: 1, type: 'flight', day_id: DAY, end_day_id: NEXT,+ reservation_time: '2026-11-19T20:20', reservation_end_time: '2026-11-21T12:25',+ metadata: JSON.stringify({ departure_timezone: 'Pacific/Auckland', arrival_timezone: 'America/Los_Angeles' }),+ }+ const hop = { id: 2, type: 'flight', day_id: NEXT, end_day_id: NEXT, reservation_time: '2026-11-21T14:00',+ metadata: JSON.stringify({ departure_timezone: 'America/New_York' }) }+ expect(ids(getMergedItems({ dayAssignments: [], dayNotes: [], dayTransports: [overnight, hop], dayId: NEXT }))).toEqual([2, 1])+ })++ it('seats a dragged flight where its zone puts it', () => {+ const order = getMergedItems({ dayAssignments: [], dayNotes: [], dayTransports: [toLA, toSeattle], dayId: DAY })+ expect(ids(seatTimedDrop([order[1], order[0]], 0, DAY))).toEqual([1, 2])+ })+})diff --git a/client/src/utils/dayMerge.ts b/client/src/utils/dayMerge.tsindex e94ef0014..5f10c3d0c 100644--- a/client/src/utils/dayMerge.ts+++ b/client/src/utils/dayMerge.ts@@ -3,7 +3,8 @@ import { nightVisits, rideSeatAfter, sameDayRide, type CarrierBooking, type Seat// `orderedEndpoints` is the geometry order's single source of truth, in the module// that documents the multi-leg model. Sorting endpoints a second time here is how// the two drift.-import { orderedEndpoints } from './flightLegs'+import { orderedEndpoints, parseReservationMetadata } from './flightLegs'+import { zonedInstant } from './zonedTime'export const TRANSPORT_TYPES = new Set(['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'cable_car', 'transit', 'transport_other'])@@ -352,11 +353,62 @@ function applyChronoOrder(dayId: number,getDisplayTime: (r: any, dayId: number) => string | null): MergedItem[] {- return chronoOrder(items, it => {+ const clockOf = (it: MergedItem): number | null => {if (it.type === 'place') return parseTimeToMinutes(it.data?.place?.place_time)if (it.type === 'note') return parseTimeToMinutes(it.data?.time)return parseTimeToMinutes(getDisplayTime(it.data, dayId))+ }+ const zoned = zonedClockSlots(items, dayId, getDisplayTime, clockOf)+ return chronoOrder(items, it => (zoned.has(it) ? zoned.get(it) : clockOf(it)))+}++/**+ * The zone a booking's time on this day is read in: the departure's on the day it+ * leaves, the arrival's on the day it lands. A leg of a multi-leg booking reads its+ * own pair of endpoints, and only when they line up one per stop with the legs (see+ * getTransportRouteEndpoints); the booking-wide zones belong to its outermost two.+ */+function transportTimeZone(r: any, dayId: number): string | null {+ const side = getSpanPhase(r, dayId) === 'end' ? 'to' : 'from'+ if (r?.__leg) {+ const ordered = orderedEndpoints(r)+ if (ordered.length !== r.__leg.total + 1) return null+ return ordered[r.__leg.index + (side === 'to' ? 1 : 0)]?.timezone || null+ }+ const meta = parseReservationMetadata(r)+ const fromMeta = side === 'from' ? meta.departure_timezone : meta.arrival_timezone+ if (typeof fromMeta === 'string' && fromMeta) return fromMeta+ return (r?.endpoints || []).find((e: { role?: string; timezone?: string | null }) => e.role === side)?.timezone || null+}++/**+ * The clock slots of the day's bookings whose time names an instant: a dated time in a+ * known zone. Each local time reads in its own zone, so across zones the clock can run+ * backwards: a flight leaving Auckland at 20:20 lands in Los Angeles at 12:25 the same+ * date, and the 17:00 flight on from there sorted ahead of it (#2929). Such bookings+ * keep the clock slots they hold between them and take them in the order they happen,+ * so stops, notes and bookings without a zone stay where the clock puts them. With fewer+ * than two the map is empty and the day orders by the clock as before.+ */+function zonedClockSlots(+ items: MergedItem[],+ dayId: number,+ getDisplayTime: (r: any, dayId: number) => string | null,+ clockOf: (it: MergedItem) => number | null+): Map<MergedItem, number> {+ const zoned = items.flatMap((it, index) => {+ if (it.type !== 'transport') return []+ const clock = clockOf(it)+ const instant = zonedInstant(getDisplayTime(it.data, dayId), transportTimeZone(it.data, dayId))+ return clock === null || instant === null ? [] : [{ it, index, clock, instant }]})+ const slots = new Map<MergedItem, number>()+ if (zoned.length < 2) return slots+ const clocks = zoned.map(z => z.clock).sort((a, b) => a - b)+ zoned+ .sort((a, b) => a.instant - b.instant || a.clock - b.clock || a.index - b.index)+ .forEach((z, i) => slots.set(z.it, clocks[i]))+ return slots}/**diff --git a/client/src/utils/zonedTime.test.ts b/client/src/utils/zonedTime.test.tsnew file mode 100644index 000000000..16c5a3f8d--- /dev/null+++ b/client/src/utils/zonedTime.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { zonedInstant } from './zonedTime';++describe('zonedInstant', () => {+ it('reads a wall-clock time in its own zone', () => {+ // NZDT is UTC+13 and PST UTC-8 in late November.+ expect(zonedInstant('2026-11-20T20:20', 'Pacific/Auckland')).toBe(Date.UTC(2026, 10, 20, 7, 20));+ expect(zonedInstant('2026-11-20T17:00', 'America/Los_Angeles')).toBe(Date.UTC(2026, 10, 21, 1, 0));+ });++ it('puts the Auckland departure before the Los Angeles one of the same date (#2929)', () => {+ const fromAuckland = zonedInstant('2026-11-20T20:20', 'Pacific/Auckland') as number;+ const fromLosAngeles = zonedInstant('2026-11-20T17:00', 'America/Los_Angeles') as number;+ expect(fromAuckland).toBeLessThan(fromLosAngeles);+ });++ it('follows daylight saving time', () => {+ expect(zonedInstant('2026-07-01T12:00', 'Europe/Berlin')).toBe(Date.UTC(2026, 6, 1, 10, 0));+ expect(zonedInstant('2026-01-01T12:00', 'Europe/Berlin')).toBe(Date.UTC(2026, 0, 1, 11, 0));+ });++ it('accepts a time with seconds', () => {+ expect(zonedInstant('2026-01-01T12:00:00', 'UTC')).toBe(Date.UTC(2026, 0, 1, 12, 0));+ });++ it('names no instant without a date or a zone', () => {+ expect(zonedInstant('17:00', 'America/Los_Angeles')).toBeNull();+ expect(zonedInstant('2026-11-20T17:00', null)).toBeNull();+ expect(zonedInstant('2026-11-20T17:00', '')).toBeNull();+ expect(zonedInstant(null, 'America/Los_Angeles')).toBeNull();+ });++ it('names no instant for an unknown zone', () => {+ expect(zonedInstant('2026-11-20T17:00', 'Not/AZone')).toBeNull();+ });+});diff --git a/client/src/utils/zonedTime.ts b/client/src/utils/zonedTime.tsnew file mode 100644index 000000000..a659af853--- /dev/null+++ b/client/src/utils/zonedTime.ts@@ -0,0 +1,53 @@+const WALL_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/;++// A formatter per zone: the day list reads every booking's zone on each render.+const formatters = new Map<string, Intl.DateTimeFormat>();++function formatterFor(timeZone: string): Intl.DateTimeFormat {+ let fmt = formatters.get(timeZone);+ if (!fmt) {+ fmt = new Intl.DateTimeFormat('en-US', {+ timeZone,+ hourCycle: 'h23',+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ });+ formatters.set(timeZone, fmt);+ }+ return fmt;+}++/** How far the wall clock in `timeZone` runs ahead of UTC at `utcMs`, in milliseconds. */+function zoneOffsetMs(utcMs: number, timeZone: string): number {+ const parts = formatterFor(timeZone).formatToParts(new Date(utcMs));+ const get = (type: Intl.DateTimeFormatPartTypes): number => Number(parts.find((p) => p.type === type)?.value);+ const wall = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second'));+ return wall - Math.floor(utcMs / 1000) * 1000;+}++/**+ * The instant a wall-clock time `YYYY-MM-DDTHH:MM` names in an IANA time zone, as epoch+ * milliseconds. Null when the time carries no date, or the zone is empty or unknown: a+ * clock time alone names no instant, so the caller keeps reading it as a clock time.+ *+ * Read twice because the zone's offset depends on the instant itself; the second read+ * settles a time near a daylight-saving switch.+ */+export function zonedInstant(wallTime: string | null | undefined, timeZone: string | null | undefined): number | null {+ if (!wallTime || !timeZone) return null;+ const m = WALL_TIME.exec(wallTime);+ if (!m) return null;+ const asUtc = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]));+ if (Number.isNaN(asUtc)) return null;+ try {+ const first = asUtc - zoneOffsetMs(asUtc, timeZone);+ return asUtc - zoneOffsetMs(first, timeZone);+ } catch {+ // An unknown zone name: Intl throws a RangeError. The time stays a plain clock time.+ return null;+ }+}