From d0cf936bf62006dec337202cbc867d4982360d4c Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 30 Nov 2026 22:15:12 +0100 Subject: [PATCH] fix(roadtrip): match cross-day returns to their rental Keep located waypoints when the return desk is missing and assign them unique IDs. Join separate days only for the same hire car in both the planner and server. Keep the existing public terminal roles. --- client/src/components/Roadtrip/carrierRide.ts | 2 +- .../components/Roadtrip/useRoadtripRoutes.ts | 29 ++---- .../nest/roadtrip/roadtrip-plan.service.ts | 21 ++--- .../nest/roadtrip/roadtrip-planning.mcp.ts | 5 +- .../unit/nest/roadtrip-plan.service.test.ts | 43 +++++++++ shared/src/assistant/cards/roadtrip.card.ts | 2 +- shared/src/roadtrip/assemble.spec.ts | 52 +++++++++-- shared/src/roadtrip/assemble.ts | 15 ++-- shared/src/roadtrip/carriers.spec.ts | 31 ++++++- shared/src/roadtrip/carriers.ts | 88 +++++++++++++------ 10 files changed, 207 insertions(+), 81 deletions(-) diff --git a/client/src/components/Roadtrip/carrierRide.ts b/client/src/components/Roadtrip/carrierRide.ts index 80e28dc9d..c970c88ee 100644 --- a/client/src/components/Roadtrip/carrierRide.ts +++ b/client/src/components/Roadtrip/carrierRide.ts @@ -122,7 +122,7 @@ function rideEnd(stop: RoadtripStop, entry: ScheduleEntry | undefined, t: Transl placeLine: carrier.code && carrier.code !== place ? place : null, clock, dayOffset: entry?.dayOffset ?? 0, - label: clock ? t(key, { time: clock }) : null, + label: clock && carrier.role !== 'stop' ? t(key, { time: clock }) : null, } } diff --git a/client/src/components/Roadtrip/useRoadtripRoutes.ts b/client/src/components/Roadtrip/useRoadtripRoutes.ts index 06b3e10b0..e0a95fbdc 100644 --- a/client/src/components/Roadtrip/useRoadtripRoutes.ts +++ b/client/src/components/Roadtrip/useRoadtripRoutes.ts @@ -1,5 +1,5 @@ import { useRoadtripSettings } from '../../hooks/useRoadtripSettings' -import { assembleRoadtrip, bookendStaysOf, carrierLegsFor, carrierSeam, foldRouteRun, hotelBookendsOn, isCarrierMode, isStationaryJoin, mergeRouteSegments, oneNightPerStay, seatCarrierStops, seatNightBookends, standsAsDay, terminalAssignmentId, viasOnLeg, type CarrierSeam, type RoadtripStop, type RoadtripRoutes, type PlanDay, type QuietDay, type RoutedLeg } from '@trek/shared/roadtrip' +import { assembleRoadtrip, bookendStaysOf, carrierLegsFor, carrierSeam, foldRouteRun, hotelBookendsOn, incomingDayJoin, isCarrierMode, isStationaryJoin, mergeRouteSegments, oneNightPerStay, seatCarrierStops, seatNightBookends, standsAsDay, terminalAssignmentId, viasOnLeg, type CarrierSeam, type RoadtripStop, type RoadtripRoutes, type PlanDay, type QuietDay, type RoutedLeg } from '@trek/shared/roadtrip' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { avoidedClasses, calculateRouteWithLegs, routeEngineFor, RoutingRefusedError } from '../Map/RouteCalculator' import { routerAsks } from '../Map/routerAsks' @@ -693,26 +693,13 @@ export function useRoadtripRoutes( want(from, to, chain.dayId) } } - // And, when the traveller asks for one continuous drive, the road from each card's - // last stop to the next card's first — the one gap a day-at-a-time routing leaves. - if (connectDays) { - for (let d = 0; d < routingChains.length - 1; d++) { - const from = routingChains[d].stops[routingChains[d].stops.length - 1] - const to = routingChains[d + 1].stops[0] - if (from && to) want(from, to, routingChains[d + 1].dayId) - } - } else { - // The drive back to a hire car's desk is the booking's own road, not the gap - // between two cards, so it is drawn whether or not one continuous drive was asked - // for. A car taken out in the morning and handed back after midnight had the day - // it set out on drawn and nothing from there to the desk, which reads as a drive - // that stops halfway. - for (let d = 1; d < routingChains.length; d++) { - const to = routingChains[d].stops[0] - if (to?.carrier?.role !== 'return') continue - const from = routingChains[d - 1].stops[routingChains[d - 1].stops.length - 1] - if (from) want(from, to, routingChains[d].dayId) - } + for (let d = 1; d < routingChains.length; d++) { + const previous = routingChains[d - 1] + const chain = routingChains[d] + if (!previous || !chain) continue + const to = chain.stops[0] + const from = incomingDayJoin(previous.stops, chain.stops, connectDays) + if (from && to) want(from, to, chain.dayId) } return { seams: out, seamMisses: misses } }, [chains, plan, quietDays, window, legsByDay, seamLegs, rideLegs, viasByDay, connectDays, legModeOf, avoidKey, distanceUnit]) diff --git a/server/src/nest/roadtrip/roadtrip-plan.service.ts b/server/src/nest/roadtrip/roadtrip-plan.service.ts index 49c6df4e1..306fee08f 100644 --- a/server/src/nest/roadtrip/roadtrip-plan.service.ts +++ b/server/src/nest/roadtrip/roadtrip-plan.service.ts @@ -26,6 +26,7 @@ import { carrierSeam, foldRouteRun, hotelBookendsOn, + incomingDayJoin, isStationaryJoin, oneNightPerStay, splitIntoRuns, @@ -288,17 +289,17 @@ export class RoadtripPlanService { for (const run of splitIntoRuns(day.stops, (from) => from.legMode ?? fallback)) await fetchRun(run.stops, day.dayId, run.mode); } + const driveDays = plan.filter((d) => standsAsDay(d.stops)); + const quietDays = plan.filter((d) => !standsAsDay(d.stops)); const chains = window ? plan.filter((d) => d.stops.length) - : spillChains( - plan.filter((d) => d.stops.length > 1), - plan.filter((d) => d.stops.length < 2), - (a, b) => allLegs[stopKey(a) + '>' + stopKey(b)], - ); - let previous: RoadtripStop | undefined; + : spillChains(driveDays, quietDays, (a, b) => allLegs[stopKey(a) + '>' + stopKey(b)]); + let previous: readonly RoadtripStop[] = []; for (const chain of chains) { const pairs = chain.stops.slice(0, -1).map((from, index) => ({ from, to: chain.stops[index + 1] })); - if (connectDays && previous && chain.stops.length) pairs.push({ from: previous, to: chain.stops[0] }); + const to = chain.stops[0]; + const from = incomingDayJoin(previous, chain.stops, connectDays); + if (from && to) pairs.push({ from, to }); for (const { from, to } of pairs) { // A night spent at one hotel is no drive, and no router is asked about it. if (isStationaryJoin(from, to) || asked.has(stopKey(from) + '>' + stopKey(to))) continue; @@ -308,7 +309,7 @@ export class RoadtripPlanService { from.legMode ?? context.days.find((d) => d.id === chain.dayId)?.default_transport_mode ?? 'driving', ); } - previous = chain.stops[chain.stops.length - 1] ?? previous; + if (chain.stops.length) previous = chain.stops; } const vehicleKind = preferences.roadtrip_vehicle || null; const rangeKm = @@ -324,8 +325,8 @@ export class RoadtripPlanService { preferences.roadtrip_range_km, ) || null; const calculated = assembleRoadtrip({ - plan: plan.filter((d) => standsAsDay(d.stops)), - quietDays: plan.filter((d) => !standsAsDay(d.stops)), + plan: driveDays, + quietDays, window, allLegs, snapByDay, diff --git a/server/src/nest/roadtrip/roadtrip-planning.mcp.ts b/server/src/nest/roadtrip/roadtrip-planning.mcp.ts index eae894f20..c1d279484 100644 --- a/server/src/nest/roadtrip/roadtrip-planning.mcp.ts +++ b/server/src/nest/roadtrip/roadtrip-planning.mcp.ts @@ -49,7 +49,7 @@ export class RoadtripPlanningMcp { @Tool({ name: 'calculate_roadtrip', description: - 'Calculate a saved trip without an open browser, using the same daily scheduling and vehicle-range rules as the planner. Returns derived days, arrivals, departures, driving limits, fuel warnings, automatic pauses and routing failures. A flight, train, ferry, cruise or bus booking with located terminals is a seam: its terminals appear as stops carrying `carrier` (role departure or arrival), the road ends at the departure terminal and resumes at the arrival one, and the leg between them is the ride, in the mode of the booking type, with its timetable minutes and no distance. The departure terminal is pinned a check-in ahead of the timetable departure (an hour for a flight); reaching it after that is a late warning with the full minutes, however many, and the ride keeps its own day, so the drive after the arrival terminal goes on from the timetable arrival. On a day a ride leaves and lands on, the stop of a stay checked into that day comes after the arrival terminal when the stay lies nearer to it than to the departure terminal: a check-in is the earliest arrival, not a time that seats the stay ahead of the ride, and it pins the stay only when the ride lands before it. A time set on the stop itself keeps its seat. A hire car booking with a located pick-up desk puts that desk on the road as a stop carrying `carrier` with role pickup, and its return desk with role return when the booking names a return day and place; the road runs through both. A flight, train, ferry, cruise or bus booking that is on none of the days of the trip (saved without a date, or on a day the trip no longer has) is not on the drive at all, although its terminals are located: undatedRides lists each one (id, type, title) so it can be given a date within the trip with the reservation tools, after which the road ends at its terminal. With roadtrip_hotel_bookends switched on (missing means off), a day after a booked night starts at that stay and a day before one ends there. Such stops carry `bookend` {phase, accommodationId, reservationId, checkingOut, checkingIn, checkOut, and checkIn on the evening a stay begins when it has a check-in time}, stopType hotel, the real placeId of the stay and a synthetic negative assignmentId that belongs to no assignment: they cannot be reordered, edited or given via points, and `failures` may name them. The check-out and check-in are labels, never a departure or arrival time. A day between two nights in the same stay with no visit has no drive. Nor does a day with nothing on it but the check-in of the next stay when a flight, train, ferry, cruise or bus is booked on that day, with or without located terminals: the booking is the move between the two stays. A stay is never joined by road to a terminal more than 2000 km away in a straight line. Pass settings {roadtrip_hotel_bookends:true} to preview the drive from and to the stays without saving it. A hotel visited more than once on the check-in day of its stay is the night (night true, checkInTime set) at one visit only: the visit that ends the day, else the stop the booking put on the day, else the last visit; the other visits are ordinary stops. Fixed visit times retain priority. The end time of a visit is when the drive leaves it, in place of its stay; reaching the visit after it is reported as a missedLeave warning. No accommodation or place is created. Optional settings are a read-only preview, not saved. Distances are metres, durations seconds, dwell times minutes. A failed leg or conflicting window means the output is incomplete: never present its totals as a complete route. Up to 150 legs; requests are paced for public routing servers and can take time. Existing place/assignment tools edit stops, stays and ordering, update_roadtrip_settings saves preferences, set_assignment_end_day and set_day_boundary set exceptions. Recalculate after changes. Plugin profiles follow installed route-provider permissions.', + 'Calculate a saved trip without an open browser, using the same daily scheduling and vehicle-range rules as the planner. Returns derived days, arrivals, departures, driving limits, fuel warnings, automatic pauses and routing failures. A flight, train, ferry, cruise or bus booking with located terminals is a seam: its terminals appear as stops carrying `carrier` (role departure or arrival), the road ends at the departure terminal and resumes at the arrival one, and the leg between them is the ride, in the mode of the booking type, with its timetable minutes and no distance. The departure terminal is pinned a check-in ahead of the timetable departure (an hour for a flight); reaching it after that is a late warning with the full minutes, however many, and the ride keeps its own day, so the drive after the arrival terminal goes on from the timetable arrival. On a day a ride leaves and lands on, the stop of a stay checked into that day comes after the arrival terminal when the stay lies nearer to it than to the departure terminal: a check-in is the earliest arrival, not a time that seats the stay ahead of the ride, and it pins the stay only when the ride lands before it. A time set on the stop itself keeps its seat. A hire car booking with a located pick-up desk puts it on the road with role pickup, and its located return desk with role return. Located intermediate stops stay on the road even when the booking has no return desk. Those stops have synthetic negative assignment IDs and no carrier role. A flight, train, ferry, cruise or bus booking that is on none of the days of the trip (saved without a date, or on a day the trip no longer has) is not on the drive at all, although its terminals are located: undatedRides lists each one (id, type, title) so it can be given a date within the trip with the reservation tools, after which the road ends at its terminal. With roadtrip_hotel_bookends switched on (missing means off), a day after a booked night starts at that stay and a day before one ends there. Such stops carry `bookend` {phase, accommodationId, reservationId, checkingOut, checkingIn, checkOut, and checkIn on the evening a stay begins when it has a check-in time}, stopType hotel, the real placeId of the stay and a synthetic negative assignmentId that belongs to no assignment: they cannot be reordered, edited or given via points, and `failures` may name them. The check-out and check-in are labels, never a departure or arrival time. A day between two nights in the same stay with no visit has no drive. Nor does a day with nothing on it but the check-in of the next stay when a flight, train, ferry, cruise or bus is booked on that day, with or without located terminals: the booking is the move between the two stays. A stay is never joined by road to a terminal more than 2000 km away in a straight line. Pass settings {roadtrip_hotel_bookends:true} to preview the drive from and to the stays without saving it. A hotel visited more than once on the check-in day of its stay is the night (night true, checkInTime set) at one visit only: the visit that ends the day, else the stop the booking put on the day, else the last visit; the other visits are ordinary stops. Fixed visit times retain priority. The end time of a visit is when the drive leaves it, in place of its stay; reaching the visit after it is reported as a missedLeave warning. No accommodation or place is created. Optional settings are a read-only preview, not saved. Distances are metres, durations seconds, dwell times minutes. A failed leg or conflicting window means the output is incomplete: never present its totals as a complete route. Up to 150 legs; requests are paced for public routing servers and can take time. Existing place/assignment tools edit stops, stays and ordering, update_roadtrip_settings saves preferences, set_assignment_end_day and set_day_boundary set exceptions. Recalculate after changes. Plugin profiles follow installed route-provider permissions.', inputSchema: roadtripPlanRequestSchema.shape, annotations: TOOL_ANNOTATIONS_READONLY, access: { group: 'trips', mode: 'read' }, @@ -74,7 +74,8 @@ export class RoadtripPlanningMcp { dayNumber: day.dayNumber, date: day.date, title: day.title, - stops: day.stops, + // Waypoints are synthesised stops. Keep the public carrier roles for terminals only. + stops: day.stops.map((stop) => (stop.carrier?.role === 'stop' ? { ...stop, carrier: undefined } : stop)), schedule: day.schedule, legs: day.legs, distanceMetres: day.distance, diff --git a/server/tests/unit/nest/roadtrip-plan.service.test.ts b/server/tests/unit/nest/roadtrip-plan.service.test.ts index 2f298436e..b472a289d 100644 --- a/server/tests/unit/nest/roadtrip-plan.service.test.ts +++ b/server/tests/unit/nest/roadtrip-plan.service.test.ts @@ -454,6 +454,49 @@ describe('a booking the traveller rides (#2428)', () => { expect(card.distance).toBe(240_000); expect(calculated.totalStops).toBe(3); }); + + it('routes a hire car through its waypoint and across days to its own return desk', async () => { + const { user, trip, plans, visits } = await setup(); + const start = await dayOf(visits[0].id); + const end = createDay(db, trip.id); + const destination = createPlace(db, trip.id, { name: 'Destination', lat: 52.51, lng: 13.41 }); + const destinationVisit = createDayAssignment(db, end.id, destination.id); + await setVisit(destinationVisit.id, { assignment_time: '01:00' }); + const car = await addReservation({ + trip: trip.id, + type: 'car', + title: 'Hire car', + day: start.day_id, + endDay: end.id, + reservation_time: '08:00', + reservation_end_time: '02:00', + }); + await addEndpoint(car, 'from', 0, 'Pick-up', null, 53.55, 10.0); + await addEndpoint(car, 'stop', 1, 'On the way', null, 53.43, 10.4); + await addEndpoint(car, 'to', 2, 'Return', null, 52.52, 13.41); + + const { calculated } = await plans.calculate(trip.id, user.id); + + expect(calculated.days[0].stops.map((stop) => stop.name)).toEqual([ + 'Pick-up', + 'On the way', + 'Hamburg', + 'Lueneburg', + 'Celle', + ]); + expect(calculated.days[1].stops.map((stop) => stop.name)).toEqual(['Destination', 'Return']); + expect(calculated.days[1].arrivingFrom).toMatchObject({ name: 'Celle' }); + expect(calculated.days[1].arrivingLeg?.distance).toBe(60_000); + + const tool = new RoadtripPlanningMcp(plans, {} as never, {} as never); + const answer = await tool.calculate({ tripId: trip.id, includeGeometry: true }, { userId: user.id } as McpContext); + const body = JSON.parse(answer.content[0].text); + expect(body.days[0].stops[0].carrier.role).toBe('pickup'); + expect(body.days[0].stops[1]).toMatchObject({ name: 'On the way', lat: 53.43, lng: 10.4 }); + expect(body.days[0].stops[1]).not.toHaveProperty('carrier'); + expect(body.days[1].stops[1].carrier.role).toBe('return'); + expect(body.days[1].distanceMetres).toBe(120_000); + }); }); /** diff --git a/shared/src/assistant/cards/roadtrip.card.ts b/shared/src/assistant/cards/roadtrip.card.ts index bf3c9c024..7334b985d 100644 --- a/shared/src/assistant/cards/roadtrip.card.ts +++ b/shared/src/assistant/cards/roadtrip.card.ts @@ -69,7 +69,7 @@ export const roadtripCardStopSchema = z.object({ .object({ reservationId: idSchema, type: z.string().min(1).max(20), - role: z.enum(['departure', 'arrival', 'pickup', 'return', 'stop']), + role: z.enum(['departure', 'arrival', 'pickup', 'return']), title: cardText(80), code: z.string().min(1).max(8).nullable(), at: cardClockSchema.nullable(), diff --git a/shared/src/roadtrip/assemble.spec.ts b/shared/src/roadtrip/assemble.spec.ts index 3c774babd..e3100f008 100644 --- a/shared/src/roadtrip/assemble.spec.ts +++ b/shared/src/roadtrip/assemble.spec.ts @@ -118,11 +118,16 @@ describe('assembleRoadtrip connected days', () => { ], }); - function assembleTwoDays(connectDays: boolean, opensSecond: Partial = {}) { - const first = [stop({ ownerIndex: 0 }), stop({ ownerIndex: 1 }), stop({ ownerIndex: 2 })]; + function assembleTwoDays( + connectDays: boolean, + opensSecond: Partial = {}, + closesFirst: Partial = {}, + closesSecond: Partial = {}, + ) { + const first = [stop({ ownerIndex: 0 }), stop({ ownerIndex: 1, ...closesFirst }), stop({ ownerIndex: 2 })]; const second = [ stop({ ownerDayId: 2, ownerIndex: 0, assignmentId: 300, placeId: 400, lat: 60, ...opensSecond }), - stop({ ownerDayId: 2, ownerIndex: 1, assignmentId: 301, placeId: 401, lat: 61 }), + stop({ ownerDayId: 2, ownerIndex: 1, assignmentId: 301, placeId: 401, lat: 61, ...closesSecond }), ]; const allLegs: Record = {}; for (const run of [first, second, [first[2]!, second[0]!]]) { @@ -207,9 +212,11 @@ describe('assembleRoadtrip connected days', () => { // day-at-a-time routing leaves. Drawn only for a connected trip, the day it set out // on was drawn and nothing led from there to the desk, which reads as a drive that // stops halfway. - const routes = assembleTwoDays(false, { - carrier: { reservationId: 42, type: 'car', role: 'return', title: 'Sixt Hamburg', code: null, at: '02:00' }, - }); + const routes = assembleTwoDays( + false, + { carrier: { reservationId: 42, type: 'car', role: 'return', title: 'Sixt Hamburg', code: null, at: '02:00' } }, + { carrier: { reservationId: 42, type: 'car', role: 'pickup', title: 'Sixt Hamburg', code: null, at: '06:00' } }, + ); expect(routes.days[1]!.arrivingFrom).toEqual(expect.objectContaining({ ownerDayId: 1, ownerIndex: 2 })); expect(routes.days[1]!.geometry[0]).toEqual([52, 10]); @@ -218,6 +225,39 @@ describe('assembleRoadtrip connected days', () => { expect(routes.lineJoins).toEqual([false, false, true, false]); }); + it('ROADTRIP-ASSEMBLE-029: a return never joins an unrelated day when days are separate', () => { + const desk: NonNullable = { + reservationId: 42, + type: 'car', + role: 'return', + title: 'Sixt Hamburg', + code: null, + at: '02:00', + }; + const unrelated = assembleTwoDays( + false, + { carrier: desk }, + { + carrier: { ...desk, reservationId: 43, role: 'pickup', at: '06:00' }, + }, + ); + expect(unrelated.days[1]!.arrivingFrom).toBeUndefined(); + expect(unrelated.lineJoins).not.toContain(true); + }); + + it('ROADTRIP-ASSEMBLE-030: a planned destination can come before the same hire car’s return', () => { + const desk = { reservationId: 42, type: 'car', title: 'Hire car', code: null, at: null }; + const routes = assembleTwoDays( + false, + { name: 'Destination' }, + { carrier: { ...desk, role: 'pickup' } }, + { carrier: { ...desk, role: 'return' } }, + ); + + expect(routes.days[1]!.arrivingFrom).toMatchObject({ ownerDayId: 1, ownerIndex: 2 }); + expect(routes.days[1]!.stops.map((entry) => entry.carrier?.role ?? entry.name)).toEqual(['Destination', 'return']); + }); + it('ROADTRIP-ASSEMBLE-006: that drive is marked as the connection it is, in the colour of the day it arrives on (#3123)', () => { const routes = assembleTwoDays(true); diff --git a/shared/src/roadtrip/assemble.ts b/shared/src/roadtrip/assemble.ts index 3f14d183a..81dabd95e 100644 --- a/shared/src/roadtrip/assemble.ts +++ b/shared/src/roadtrip/assemble.ts @@ -1,5 +1,5 @@ import { spurFor } from './accessSpur'; -import { carriesTheCar, isCarrierMode, isPickupStop } from './carriers'; +import { carriesTheCar, incomingDayJoin, isCarrierMode, isPickupStop } from './carriers'; import { pointAtMeters } from './corridor'; import type { RoadtripDayBoundary } from './day-boundary.schema'; import { planDayWindow, type DayWindow } from './dayWindow'; @@ -112,7 +112,7 @@ export function assembleRoadtrip({ const out: RoadtripDay[] = []; let carryKm: number | null = 0; - let previousStop: RoadtripStop | undefined; + let previousStops: readonly RoadtripStop[] = []; for (const chain of displayChains) { const routed = chain.stops.slice(0, -1).map((s, i) => legFor(s, chain.stops[i + 1]!)); @@ -121,18 +121,13 @@ export function assembleRoadtrip({ let arrivingLine: [number, number][] | undefined; let arrivingFrom: RoadtripStop | undefined; const first = chain.stops[0]; - // The drive back to a hire car's desk is the booking's own road rather than the gap a - // day-at-a-time routing leaves between two cards, so it is drawn whether or not one - // continuous drive was asked for. A car taken out in the morning and handed back after - // midnight had the day it set out on drawn and nothing from there to the desk, which - // reads as a drive that stops halfway. - const ownDrive = first?.carrier?.role === 'return'; if (connectDays && !automaticSchedule) { for (const spill of chain.spills) { inboundAt.set(spill.at, { seg: spill.leg, line: spill.line }); } } - if ((connectDays || ownDrive) && !automaticSchedule) { + if (!automaticSchedule) { + const previousStop = incomingDayJoin(previousStops, chain.stops, connectDays); // No band for a night spent at one hotel: nothing is driven between the evening and // the morning, and a band would read "0 km" between a hotel and itself. const joined = @@ -146,7 +141,7 @@ export function assembleRoadtrip({ arrivingFrom = previousStop; } } - previousStop = chain.stops[chain.stops.length - 1]! ?? previousStop; + if (chain.stops.length) previousStops = chain.stops; for (let i = 0; i < chain.stops.length; i++) { const inbound = inboundAt.get(i); if (inbound) { diff --git a/shared/src/roadtrip/carriers.spec.ts b/shared/src/roadtrip/carriers.spec.ts index e8a32caa3..655de7c47 100644 --- a/shared/src/roadtrip/carriers.spec.ts +++ b/shared/src/roadtrip/carriers.spec.ts @@ -16,7 +16,6 @@ */ import { assembleRoadtrip } from './assemble'; import { - carrierStopAssignmentId, CHECK_IN_MINUTES, carrierClock, carrierLeg, @@ -1114,7 +1113,6 @@ describe('the stops a hire car names between its desks', () => { lng: 10.4115, }); // An id of its own, below every terminal's, so no stop of the day collides with it. - expect(through.assignmentId).toBe(carrierStopAssignmentId(42, 0)); expect(through.assignmentId).toBeLessThan(terminalAssignmentId(42, 'return')); }); @@ -1166,4 +1164,33 @@ describe('the stops a hire car names between its desks', () => { ]); expect(seated[1]).toMatchObject({ dwellMinutes: 0, time: null }); }); + + it('ROADTRIP-CARRIERS-042: a missing return desk leaves the located stops on the drive', () => { + const endpoints = driven().endpoints ?? []; + for (const route of [ + endpoints.slice(0, 2), + endpoints.map((end) => (end.role === 'to' ? { ...end, lat: null } : end)), + ]) { + const withoutDesk = sameDay({ endpoints: route }); + expect(withoutDesk.arrival).toBeNull(); + expect(seatCarrierStops(1, [], [], [withoutDesk]).map((s) => s.name)).toEqual(['Hamburg', 'Lüneburg']); + } + }); + + it('ROADTRIP-CARRIERS-043: waypoints beyond the 64th have unique ids', () => { + const [from, via, to] = driven().endpoints ?? []; + const saved = { ...via, id: 1, name: 'Saved stop' }; + const stops = Array.from({ length: 65 }, (_, i) => + i === 0 ? { ...saved, sequence: 1 } : { ...via, sequence: i + 1, name: `Stop ${i + 1}` }, + ); + const rental = sameDay({ endpoints: [from, ...stops, { ...to, sequence: 66 }] }); + const day = seatCarrierStops(1, [], [], [rental]); + expect(day).toHaveLength(67); + expect(new Set(day.map((s) => s.assignmentId)).size).toBe(67); + + const reseated = sameDay({ + endpoints: [from, { ...via, name: 'New stop' }, { ...saved, sequence: 2 }, { ...to, sequence: 3 }], + }); + expect(seatCarrierStops(1, [], [], [reseated])[2]?.assignmentId).toBe(day[1]?.assignmentId); + }); }); diff --git a/shared/src/roadtrip/carriers.ts b/shared/src/roadtrip/carriers.ts index ba7ea482e..79d24fafd 100644 --- a/shared/src/roadtrip/carriers.ts +++ b/shared/src/roadtrip/carriers.ts @@ -73,6 +73,7 @@ export interface CarrierBooking { /** JSON as stored, or the parsed object; only `legs` is read here. */ metadata?: string | Record | null; endpoints?: readonly { + id?: number; role: string; sequence?: number | null; name: string; @@ -108,12 +109,11 @@ export interface CarrierSeam { * booking by its own clock, so the seat by geography (`rideSeatAfter`) leaves it alone. */ stopover: boolean; - waypoints: { lat: number; lng: number; name: string }[]; + waypoints: CarrierWaypoint[]; departure: CarrierEnd; /** * A ride always has both ends. A hire car has a return only when the booking says - * where: without a located return desk, nothing is guessed and only the pick-up stands - * on the road. + * where: without a located return desk, the road still holds the pick-up and its stops. */ arrival: CarrierEnd | null; } @@ -161,6 +161,7 @@ function positionOn(positions: Record | null | undefined, dayId: type Endpoint = NonNullable[number]; type LocatedEndpoint = Endpoint & { lat: number; lng: number }; +type CarrierWaypoint = Pick; function isLocated(e: Endpoint): e is LocatedEndpoint { return typeof e.lat === 'number' && typeof e.lng === 'number' && Number.isFinite(e.lat) && Number.isFinite(e.lng); @@ -189,7 +190,12 @@ function seamEnds( : [...located].reverse().find((e) => e.role === 'to'); if (!from) return null; if (kind === 'ride' && (!to || from === to)) return null; - const between = kind === 'rental' && to ? located.slice(located.indexOf(from) + 1, located.indexOf(to)) : []; + const between = + kind === 'rental' + ? located + .slice(located.indexOf(from) + 1, to ? located.indexOf(to) : undefined) + .filter((end) => end.role === 'stop') + : []; return { from, to, between }; } @@ -252,7 +258,7 @@ export function carrierSeam(booking: CarrierBooking): CarrierSeam | null { title: booking.title, kind, stopover: legs.length > 1, - waypoints: between.map((e) => ({ lat: e.lat, lng: e.lng, name: e.name })), + waypoints: between.map(({ id, lat, lng, name }) => ({ id, lat, lng, name })), departure: { dayId: depDayId, position: positionOn(first?.day_positions, depDayId) ?? bookingPosition(depDayId), @@ -427,34 +433,36 @@ function rideMinutes(dep: number | null, arr: number | null, dayDelta: number): /** Below the automatic nights (-2e9 and down): a terminal is no assignment and no night. */ const TERMINAL_ID_BASE = -3_000_000_000; +type TerminalRole = Exclude; export function terminalAssignmentId(reservationId: number, role: CarrierTerminal['role']): number { return TERMINAL_ID_BASE - reservationId * 2 - (role === 'arrival' || role === 'return' ? 1 : 0); } -/** - * Below the terminals, which take two ids per booking: a booking's stops need one id each, - * and there is no room for them between its two desks. A booking names at most - * `MAX_CARRIER_STOPS` of them, so an id of one booking never reaches the next one's. - */ -const CARRIER_STOP_ID_BASE = -4_000_000_000; -const MAX_CARRIER_STOPS = 64; +/** Below the other synthetic stops, even with the largest integer ids in the DB. */ +const CARRIER_STOP_ID_BASE = -12_000_000_000; -export function carrierStopAssignmentId(reservationId: number, sequence: number): number { - return CARRIER_STOP_ID_BASE - reservationId * MAX_CARRIER_STOPS - (sequence % MAX_CARRIER_STOPS); +function carrierStopAssignmentId(endpointId: number | undefined, index: number): number { + // Saved endpoints have globally unique ids. Unsaved endpoints take the odd slots in this trip. + return CARRIER_STOP_ID_BASE - (endpointId && endpointId > 0 ? endpointId * 2 : index * 2 + 1); +} + +function waypointOffsets(seams: readonly CarrierSeam[]): Map { + const offsets = new Map(); + let next = 0; + for (const seam of seams) { + offsets.set(seam.reservationId, next); + next += seam.waypoints.length; + } + return offsets; } /** The two roles of a seam, by which end of it a terminal stands at. */ -function rolesOf(seam: CarrierSeam): { start: CarrierTerminal['role']; end: CarrierTerminal['role'] } { +function rolesOf(seam: CarrierSeam): { start: TerminalRole; end: TerminalRole } { return seam.kind === 'rental' ? { start: 'pickup', end: 'return' } : { start: 'departure', end: 'arrival' }; } -function terminalStop( - seam: CarrierSeam, - role: CarrierTerminal['role'], - dayId: number, - ownerIndex: number, -): RoadtripStop { +function terminalStop(seam: CarrierSeam, role: TerminalRole, dayId: number, ownerIndex: number): RoadtripStop { // The callers only ask for an arrival or a return the seam has. const end = role === 'departure' || role === 'pickup' ? seam.departure : seam.arrival!; const checkIn = CHECK_IN_MINUTES[seam.type] ?? 0; @@ -507,7 +515,7 @@ function terminalStop( */ function carrierWaypointStop( seam: CarrierSeam, - point: CarrierSeam['waypoints'][number], + point: CarrierWaypoint, sequence: number, dayId: number, ownerIndex: number, @@ -521,7 +529,7 @@ function carrierWaypointStop( code: null, at: null, }, - assignmentId: carrierStopAssignmentId(seam.reservationId, sequence), + assignmentId: carrierStopAssignmentId(point.id, sequence), ownerDayId: dayId, ownerIndex, placeId: -seam.reservationId, @@ -585,6 +593,28 @@ export function closesTheDay(role: CarrierTerminal['role'] | undefined): boolean return role === 'departure' || role === 'return'; } +/** The preceding day's tail, if the trip or the same hire car connects it to this day. */ +export function incomingDayJoin( + previous: readonly RoadtripStop[], + next: readonly RoadtripStop[], + connectDays: boolean, +): RoadtripStop | undefined { + const last = previous[previous.length - 1]; + if (!last || !next.length) return undefined; + if (connectDays) return last; + const returning = next.find((stop) => stop.carrier)?.carrier; + if (returning?.role !== 'return') return undefined; + + for (let index = previous.length - 1; index >= 0; index--) { + const carrier = previous[index]?.carrier; + if (!carrier) continue; + return carrier.reservationId === returning.reservationId && (carrier.role === 'pickup' || carrier.role === 'stop') + ? last + : undefined; + } + return undefined; +} + /** * The day's stops with the terminals of its rides, and the desks of its hire cars, seated * among them. @@ -634,7 +664,7 @@ export function seatCarrierStops( type Item = | { kind: 'stop'; index: number; key: number; minutes: number | null } - | { kind: 'end'; seam: CarrierSeam; role: CarrierTerminal['role']; key: number; minutes: number | null }; + | { kind: 'end'; seam: CarrierSeam; role: TerminalRole; key: number; minutes: number | null }; const base: Item[] = stops.flatMap((stop, index): Item[] => behind.has(index) ? [] @@ -647,7 +677,7 @@ export function seatCarrierStops( }, ], ); - const ends: { seam: CarrierSeam; role: CarrierTerminal['role']; end: CarrierEnd }[] = [ + const ends: { seam: CarrierSeam; role: TerminalRole; end: CarrierEnd }[] = [ ...departing.map((seam) => ({ seam, role: rolesOf(seam).start, end: seam.departure })), ...arriving.map((seam) => ({ seam, role: rolesOf(seam).end, end: seam.arrival! })), ]; @@ -675,7 +705,7 @@ export function seatCarrierStops( }; // A car handed back on the day it was picked up, at no stated hour, is seated once every // other desk of the day is: it goes back before the next car is collected (`handOverKey`). - const untimedSameDayReturn = (e: { seam: CarrierSeam; role: CarrierTerminal['role']; minutes: number | null }) => + const untimedSameDayReturn = (e: { seam: CarrierSeam; role: TerminalRole; minutes: number | null }) => e.role === 'return' && e.minutes === null && e.seam.departure.dayId === dayId; ends .map((e) => ({ ...e, minutes: parseClock(e.end.clock) })) @@ -718,7 +748,7 @@ export function seatCarrierStops( // Where each terminal lands: behind the stop before it in the day plan's reading, in // the stored order. Two terminals behind the same stop keep their reading order. - const slots: { seam: CarrierSeam; role: CarrierTerminal['role']; after: number }[] = []; + const slots: { seam: CarrierSeam; role: TerminalRole; after: number }[] = []; let lastStop = -1; for (const item of read) { if (item.kind === 'stop') lastStop = item.index; @@ -731,6 +761,7 @@ export function seatCarrierStops( waiting.set(ride, [...(waiting.get(ride) ?? []), index]); } const out: RoadtripStop[] = []; + const offsets = waypointOffsets(seams); const emit = (slot: (typeof slots)[number]): void => { // The index of the stored stop that follows the one the terminal is seated behind. const insertAt = slot.after + 1; @@ -741,8 +772,9 @@ export function seatCarrierStops( // that is the one day the booking names for the drive; a stop the traveller reaches // on a later day of a long hire is theirs to move, and moving it is what says so. if (slot.role === 'pickup') { + const offset = offsets.get(slot.seam.reservationId) ?? 0; slot.seam.waypoints.forEach((point, sequence) => - out.push(carrierWaypointStop(slot.seam, point, sequence, dayId, insertAt)), + out.push(carrierWaypointStop(slot.seam, point, offset + sequence, dayId, insertAt)), ); } if (slot.role === 'departure' && slot.seam.arrival?.dayId === dayId) {