mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 00:43:15 +00:00
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.
This commit is contained in:
@@ -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(),
|
||||
|
||||
@@ -118,11 +118,16 @@ describe('assembleRoadtrip connected days', () => {
|
||||
],
|
||||
});
|
||||
|
||||
function assembleTwoDays(connectDays: boolean, opensSecond: Partial<RoadtripStop> = {}) {
|
||||
const first = [stop({ ownerIndex: 0 }), stop({ ownerIndex: 1 }), stop({ ownerIndex: 2 })];
|
||||
function assembleTwoDays(
|
||||
connectDays: boolean,
|
||||
opensSecond: Partial<RoadtripStop> = {},
|
||||
closesFirst: Partial<RoadtripStop> = {},
|
||||
closesSecond: Partial<RoadtripStop> = {},
|
||||
) {
|
||||
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<string, RoutedLeg> = {};
|
||||
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<RoadtripStop['carrier']> = {
|
||||
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);
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -73,6 +73,7 @@ export interface CarrierBooking {
|
||||
/** JSON as stored, or the parsed object; only `legs` is read here. */
|
||||
metadata?: string | Record<string, unknown> | 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<string, number> | null | undefined, dayId:
|
||||
|
||||
type Endpoint = NonNullable<CarrierBooking['endpoints']>[number];
|
||||
type LocatedEndpoint = Endpoint & { lat: number; lng: number };
|
||||
type CarrierWaypoint = Pick<LocatedEndpoint, 'id' | 'lat' | 'lng' | 'name'>;
|
||||
|
||||
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<CarrierTerminal['role'], 'stop'>;
|
||||
|
||||
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<number, number> {
|
||||
const offsets = new Map<number, number>();
|
||||
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) {
|
||||
|
||||
Reference in New Issue
Block a user