feat(roadtrip): plan and edit trips through MCP without a browser

This commit is contained in:
Maurice
2026-09-11 23:25:06 +02:00
parent 491cfccc56
commit fccc55732b
51 changed files with 4545 additions and 3369 deletions
+2
View File
@@ -76,3 +76,5 @@ export * from './i18n/languages';
export * from './plugin-permissions';
// Plugin settings contracts: the settings-field descriptor + admin instance-config wire shapes.
export * from './plugins/plugins.schema';
export * from './roadtrip/preferences.schema';
export * from './roadtrip/planning.schema';
+7 -4
View File
@@ -15,6 +15,7 @@ import { describe, it, expect } from 'vitest';
* fixture map cannot silently shrink relative to the registry.
*/
const FIXTURES: Record<TrekWsEventName, Record<string, unknown>> = {
'roadtripPreferences:changed': { preferences: { roadtrip_day_start: '08:00' } },
'place:created': { place: { id: 3, name: 'Louvre' } },
'place:updated': { place: { id: 3, name: 'Louvre' } },
'place:deleted': { placeId: 3 },
@@ -30,7 +31,9 @@ const FIXTURES: Record<TrekWsEventName, Record<string, unknown>> = {
'day:reordered': { orderedIds: [2, 1] },
'roadtripVia:changed': { dayId: 2, vias: [{ id: 9, lat: 53.5, lng: 9.9 }] },
'roadtripTrack:changed': { dayId: 2, track: null },
'roadtripBoundary:changed': { boundaries: [{ day_number: 1, from_assignment_id: 9, to_assignment_id: null, fraction: 1 }] },
'roadtripBoundary:changed': {
boundaries: [{ day_number: 1, from_assignment_id: 9, to_assignment_id: null, fraction: 1 }],
},
'dayNote:created': { dayId: 2, note: { id: 5 } },
'dayNote:updated': { dayId: 2, note: { id: 5 } },
'dayNote:deleted': { noteId: 5, dayId: 2 },
@@ -141,12 +144,12 @@ const DRIFT_VARIANTS: Partial<Record<TrekWsEventName, Record<string, unknown>[]>
};
describe('@trek/shared realtime event registry', () => {
it('WSEVT-REG-001: pins the authoritative inventory counts (72 trip + 32 user = 104)', () => {
it('WSEVT-REG-001: pins the authoritative inventory counts (72 trip + 33 user = 105)', () => {
// 67th to 69th trip event: the three collab:link:* a shared link emits.
// 70th and 71st: the road trip's vias and tracks, which used to be written silently.
expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(72);
expect(TREK_WS_USER_EVENT_NAMES).toHaveLength(32);
expect(TREK_WS_EVENT_NAMES).toHaveLength(104);
expect(TREK_WS_USER_EVENT_NAMES).toHaveLength(33);
expect(TREK_WS_EVENT_NAMES).toHaveLength(105);
});
it('WSEVT-REG-002: every name is domain:action shaped and outside the reserved plugin: namespace', () => {
+12 -7
View File
@@ -1,5 +1,7 @@
import { z } from 'zod';
import { roadtripDayBoundaryListSchema } from '../roadtrip/day-boundary.schema';
import { roadtripPreferencesSchema } from '../roadtrip/preferences.schema';
import { z } from 'zod';
/**
* WS event contract registry — the single source of truth for every realtime
@@ -257,6 +259,7 @@ export const TREK_WS_EVENTS = {
'memories:updated': { scope: 'trip', payload: z.object({ userId: id }) },
// ── Notifications (user-scoped) ──────────────────────────────────────────
'roadtripPreferences:changed': { scope: 'user', payload: z.object({ preferences: roadtripPreferencesSchema }) },
'notification:new': { scope: 'user', payload: z.object({ notification: entity }) },
'notification:updated': { scope: 'user', payload: z.object({ notification: entity }) },
@@ -333,12 +336,14 @@ export const TREK_WS_EVENTS = {
scope: 'user',
payload: z.object({
journeyId: id,
peers: z.array(z.object({
socketId: z.number(),
userId: id,
username: z.string(),
avatar: z.string().nullable().optional(),
})),
peers: z.array(
z.object({
socketId: z.number(),
userId: id,
username: z.string(),
avatar: z.string().nullable().optional(),
}),
),
}),
},
+15
View File
@@ -0,0 +1,15 @@
import type { SnappedWaypoint } from './planning-types';
export const ACCESS_SPUR_MIN_M = 30;
export const ACCESS_LABEL_MIN_M = 250;
export function spurFor(snapped: SnappedWaypoint | undefined | null): [[number, number], [number, number]] | null {
if (!snapped) return null;
if (!(snapped.meters >= ACCESS_SPUR_MIN_M)) return null;
return [snapped.asked, snapped.at];
}
export function spurWorthLabelling(meters: number | null | undefined): boolean {
return typeof meters === 'number' && meters >= ACCESS_LABEL_MIN_M;
}
+253
View File
@@ -0,0 +1,253 @@
import { spurFor } from './accessSpur';
import { pointAtMeters } from './corridor';
import type { RoadtripDayBoundary } from './day-boundary.schema';
import { planDayWindow, type DayWindow } from './dayWindow';
import { spillChains } from './nightSpill';
import type {
PlanDay,
QuietDay,
RoadtripStop,
RoadtripDay,
RoadtripRoutes,
RoutedLeg,
RouteSegment,
SnappedWaypoint,
RouteAvoidClass,
DistanceUnit,
} from './planning-types';
import {
computeSchedule,
deriveDriveWarnings,
refuelsRange,
isServiceStopType,
type DryPoint,
type DriveLimits,
type VehicleKind,
} from './roadtripModel';
const stopKey = (s: RoadtripStop): string =>
`${s.lat.toFixed(5)},${s.lng.toFixed(5)},${s.legMode ?? ''},${s.incomingLegMode ?? ''}`;
const legKey = (from: RoadtripStop, to: RoadtripStop): string => `${stopKey(from)}>${stopKey(to)}`;
export function assembleRoadtrip({
plan,
quietDays,
window,
distanceUnit,
allLegs,
snapByDay,
missedByDay,
loading,
limits,
vehicleKind,
connectDays,
boundaries,
labels,
}: {
plan: PlanDay[];
quietDays: QuietDay[];
window: DayWindow | null;
distanceUnit: DistanceUnit;
allLegs: Record<string, RoutedLeg>;
snapByDay: Record<number, Record<string, SnappedWaypoint>>;
missedByDay: Record<number, RouteAvoidClass[]>;
loading: boolean;
limits: DriveLimits;
vehicleKind: VehicleKind | null;
connectDays: boolean;
boundaries: RoadtripDayBoundary[];
labels: { start: string; end: string };
}): RoadtripRoutes {
const chains = spillChains(plan, quietDays, (a, b) => allLegs[legKey(a, b)]);
const allSnaps: Record<string, SnappedWaypoint> = {};
for (const day of plan) Object.assign(allSnaps, snapByDay[day.dayId] ?? {});
const storedLegFor = (from: RoadtripStop, to: RoadtripStop): RoutedLeg | undefined => allLegs[legKey(from, to)];
const timed = window
? planDayWindow(
[...plan, ...quietDays],
window,
storedLegFor,
distanceUnit,
{ start: labels.start, end: labels.end },
boundaries,
)
: null;
const automaticSchedule = !!timed && timed.issue === null;
const displayChains = automaticSchedule
? timed.chains
: timed?.issue
? [...plan, ...quietDays]
.sort((a, b) => a.dayNumber - b.dayNumber)
.filter((d) => d.stops.length)
.map((d) => ({
...d,
spills: [],
schedule: computeSchedule(
d.stops.map((s) => ({ anchor: s.time, dwellMinutes: s.dwellMinutes })),
d.stops.slice(0, -1).map((s, i) => storedLegFor(s, d.stops[i + 1]!)?.seg.duration),
),
}))
: chains;
const legFor = automaticSchedule ? timed.legFor : storedLegFor;
const lines: [number, number][][] = [];
const lineDays: number[] = [];
const segments: RouteSegment[] = [];
const accessLines: RoadtripRoutes['accessLines'] = [];
const out: RoadtripDay[] = [];
let carryKm: number | null = 0;
let previousStop: RoadtripStop | undefined;
let previousDayNumber: number | undefined;
for (const chain of displayChains) {
const routed = chain.stops.slice(0, -1).map((s, i) => legFor(s, chain.stops[i + 1]!));
const inboundAt = new Map<number, { seg: RouteSegment | undefined; line: [number, number][]; drawnAs: number }>();
if (connectDays && !automaticSchedule) {
for (const spill of chain.spills) {
inboundAt.set(spill.at, { seg: spill.leg, line: spill.line, drawnAs: spill.fromDayNumber });
}
const joined = inboundAt.has(0) ? undefined : previousStop && legFor(previousStop, chain.stops[0]!);
if (joined)
inboundAt.set(0, { seg: joined.seg, line: joined.line, drawnAs: previousDayNumber ?? chain.dayNumber });
}
previousStop = chain.stops[chain.stops.length - 1]! ?? previousStop;
previousDayNumber = chain.stops.length ? chain.dayNumber : previousDayNumber;
for (let i = 0; i < chain.stops.length; i++) {
const inbound = inboundAt.get(i);
if (inbound) {
if (inbound.line.length > 1) {
lines.push(inbound.line);
lineDays.push(inbound.drawnAs);
}
if (inbound.seg) segments.push(inbound.seg);
}
const leg = routed[i];
if (!leg) continue;
if (leg.line.length > 1) {
lines.push(leg.line);
lineDays.push(chain.dayNumber);
}
segments.push(leg.seg);
}
const geometry: [number, number][] = [];
for (let i = 0; i < chain.stops.length; i++) {
const inbound = inboundAt.get(i);
if (inbound) geometry.push(...inbound.line);
geometry.push(...(routed[i]?.line ?? []));
}
const legs = routed.map((l) => l?.seg);
const inbound = [...inboundAt.values()].map((l) => l.seg);
const distance =
legs.reduce((sum, l) => sum + (l?.distance ?? 0), 0) + inbound.reduce((sum, l) => sum + (l?.distance ?? 0), 0);
const duration =
legs.reduce((sum, l) => sum + (l?.duration ?? 0), 0) + inbound.reduce((sum, l) => sum + (l?.duration ?? 0), 0);
const schedule = chain.schedule;
const legVias = routed.map((l) => l?.vias ?? []);
const stops = chain.stops.map((s) => {
const snap = s.automaticNight ? undefined : allSnaps[stopKey(s)];
const line = spurFor(snap);
if (line) accessLines.push({ line, meters: snap!.meters, stopKey: stopKey(s) });
return { ...s, offRoadMeters: line ? snap!.meters : null };
});
const inboundKm =
inbound
.filter((l) => l && (l.mode === undefined || l.mode === 'driving'))
.reduce((sum, l) => sum + (l?.distance ?? 0), 0) / 1000;
const startKm = carryKm === null ? null : carryKm + inboundKm;
const drive = deriveDriveWarnings(
legs,
stops.map((s) => refuelsRange(s.stopType, vehicleKind)),
limits,
startKm,
stops.map((s) => s.fillPercent),
);
carryKm = drive.carryKm;
const drivingLine = routed
.filter((l) => l && l.seg.mode !== undefined && l.seg.mode === 'driving')
.flatMap((l) => l?.line ?? []);
const dryPoints = drive.emptyAt
.map((dry) => {
const at = pointAtMeters(
drivingLine.map(([lat, lng]) => ({ lat, lng })),
dry.drivenMeters,
);
return at ? { ...dry, lat: at.lat, lng: at.lng } : null;
})
.filter((d): d is DryPoint & { lat: number; lng: number } => d !== null);
const drivingGeometry = drivingLine.length === geometry.length ? geometry : drivingLine;
out.push({
automaticSchedule,
dayId: chain.dayId,
dayNumber: chain.dayNumber,
date: chain.date,
title: chain.title,
avoidMissed: missedByDay[chain.dayId],
spills: chain.spills,
stops,
legs,
legVias,
schedule,
geometry,
distance,
duration,
dryPoints,
drivingGeometry,
driveWarnings: drive.warnings,
dayWarning: drive.day,
});
}
const drives = out.filter((d) => d.stops.length > 1 || d.stops.some((s) => s.automaticNight));
const originalStops = [...plan, ...quietDays].sort((a, b) => a.dayNumber - b.dayNumber).flatMap((day) => day.stops);
const boundaryPath = originalStops.slice(0, -1).flatMap((from, position) => {
const to = originalStops[position + 1]!;
const leg = storedLegFor(from, to);
return leg && (!leg.seg.mode || leg.seg.mode === 'driving') && from.assignmentId > 0 && to.assignmentId > 0
? [{ from, to, position, line: leg.line }]
: [];
});
return {
boundaryPath,
validateBoundaries: (next: RoadtripDayBoundary[]) =>
window
? planDayWindow(
[...plan, ...quietDays],
window,
storedLegFor,
distanceUnit,
{ start: labels.start, end: labels.end },
next,
).issue
: 'conflict',
dayWindowIssue: timed?.issue ?? null,
days: drives,
lines,
lineDays,
segments,
accessLines,
vias: out.flatMap((d) => d.legVias.flat()),
totalDistance: drives.reduce((s, d) => s + d.distance, 0),
totalDuration: drives.reduce((s, d) => s + d.duration, 0),
totalStops: drives.reduce(
(s, d) => s + d.stops.filter((st) => !st.automaticNight && !isServiceStopType(st.stopType)).length,
0,
),
quietDays: out
.filter((d) => d.stops.length < 2 && !d.stops.some((s) => s.automaticNight))
.map((d) => ({ dayId: d.dayId, dayNumber: d.dayNumber, date: d.date, title: d.title, stops: d.stops })),
loading,
};
}
+285
View File
@@ -0,0 +1,285 @@
import {
boxAround,
corridorTiles,
distanceToSegmentKm,
haversineKm,
pointAtMeters,
projectOntoRoute,
sliceAtMeters,
simplifyLine,
type LatLng,
} from './corridor';
import { describe, it, expect } from 'vitest';
const BERLIN: LatLng = { lat: 52.52, lng: 13.405 };
const DRESDEN: LatLng = { lat: 51.05, lng: 13.74 };
const PRAGUE: LatLng = { lat: 50.088, lng: 14.42 };
describe('haversineKm', () => {
it('measures a known distance', () => {
// Berlin → Dresden is about 165 km as the crow flies.
expect(haversineKm(BERLIN, DRESDEN)).toBeGreaterThan(160);
expect(haversineKm(BERLIN, DRESDEN)).toBeLessThan(170);
});
it('is zero for the same point', () => {
expect(haversineKm(BERLIN, BERLIN)).toBe(0);
});
});
describe('distanceToSegmentKm', () => {
const a: LatLng = { lat: 52, lng: 13 };
const b: LatLng = { lat: 52, lng: 14 };
it('measures perpendicular distance to the line', () => {
const p: LatLng = { lat: 52.09, lng: 13.5 };
// 0.09° of latitude is about 10 km, whatever the longitude does.
expect(distanceToSegmentKm(p, a, b)).toBeGreaterThan(9);
expect(distanceToSegmentKm(p, a, b)).toBeLessThan(11);
});
it('measures to the end, not to the infinite line, for a point beyond it', () => {
const beyond: LatLng = { lat: 52, lng: 16 };
const d = distanceToSegmentKm(beyond, a, b);
// Two degrees of longitude past the end at 52° north — roughly 137 km.
expect(d).toBeGreaterThan(120);
expect(d).toBeLessThan(150);
});
it('falls back to point distance for a zero-length segment', () => {
expect(distanceToSegmentKm(DRESDEN, a, a)).toBeCloseTo(haversineKm(DRESDEN, a), 5);
});
});
describe('projectOntoRoute', () => {
const line = [BERLIN, DRESDEN, PRAGUE];
it('reports how far off the route a point is', () => {
const onRoute = projectOntoRoute({ lat: 51.8, lng: 13.5 }, line);
expect(onRoute!.offRouteKm).toBeLessThan(15);
const wayOff = projectOntoRoute({ lat: 53.55, lng: 10.0 }, line);
expect(wayOff!.offRouteKm).toBeGreaterThan(150);
});
it('orders points by how far into the drive they come', () => {
const early = projectOntoRoute({ lat: 52.3, lng: 13.45 }, line)!;
const late = projectOntoRoute({ lat: 50.4, lng: 14.2 }, line)!;
expect(early.alongKm).toBeLessThan(late.alongKm);
});
it('tells two points on the same long straight apart', () => {
// The petrol stations along one motorway segment must not all report the same
// position in the drive, which is what taking the segment midpoint produced.
const straight = [
{ lat: 52, lng: 13 },
{ lat: 52, lng: 15 },
];
const early = projectOntoRoute({ lat: 52.01, lng: 13.3 }, straight)!;
const late = projectOntoRoute({ lat: 52.01, lng: 14.7 }, straight)!;
expect(late.alongKm - early.alongKm).toBeGreaterThan(80);
});
it('returns nothing for a line that is not one', () => {
expect(projectOntoRoute(BERLIN, [])).toBeNull();
expect(projectOntoRoute(BERLIN, [BERLIN])).toBeNull();
});
});
describe('corridorTiles', () => {
it('covers a short route with a single box', () => {
const tiles = corridorTiles([BERLIN, { lat: 52.4, lng: 13.5 }], 5);
expect(tiles).toHaveLength(1);
expect(tiles[0]!.south).toBeLessThan(52.4);
expect(tiles[0]!.north).toBeGreaterThan(52.52);
});
it('splits a long route into boxes the server will not clamp', () => {
const tiles = corridorTiles([BERLIN, DRESDEN, PRAGUE], 10);
expect(tiles.length).toBeGreaterThan(1);
for (const t of tiles) {
expect(t.north - t.south).toBeLessThanOrEqual(0.45);
expect(t.east - t.west).toBeLessThanOrEqual(0.45);
}
});
it('pads longitude more the further north it goes', () => {
const south = corridorTiles([{ lat: 0, lng: 0 }], 10)[0]!;
const north = corridorTiles([{ lat: 60, lng: 0 }], 10)[0]!;
expect(north.east - north.west).toBeGreaterThan(south.east - south.west);
});
it('covers the middle of a long straight leg, not only its two ends', () => {
// A motorway with no bend in it reduces to two points, 250 km apart. Tiling walks
// point to point, so without splitting the step everything between them goes
// unsearched while the search still reports itself complete.
const straight = [
{ lat: 53.55, lng: 9.99 },
{ lat: 52.52, lng: 13.4 },
];
const tiles = corridorTiles(straight, 10);
expect(tiles.length).toBeGreaterThan(4);
// A box somewhere over the middle of the drive, which is what was missing.
const midLat = 53.03;
const midLng = 11.7;
expect(tiles.some((t) => t.south <= midLat && t.north >= midLat && t.west <= midLng && t.east >= midLng)).toBe(
true,
);
});
it('leaves no gap between consecutive boxes along a route', () => {
const tiles = corridorTiles(
[
{ lat: 53.55, lng: 9.99 },
{ lat: 52.52, lng: 13.4 },
],
10,
);
for (let i = 1; i < tiles.length; i++) {
const a = tiles[i - 1]!;
const b = tiles[i]!;
// Overlapping or touching in both axes: a hole here is a stretch nobody looks at.
expect(Math.min(a.north, b.north) - Math.max(a.south, b.south)).toBeGreaterThanOrEqual(0);
expect(Math.min(a.east, b.east) - Math.max(a.west, b.west)).toBeGreaterThanOrEqual(0);
}
});
it('has nothing to cover for an empty route', () => {
expect(corridorTiles([], 10)).toEqual([]);
});
});
describe('simplifyLine', () => {
it('keeps the ends and drops what sits on the line between them', () => {
const straight = [
{ lat: 52, lng: 13 },
{ lat: 52, lng: 13.5 },
{ lat: 52, lng: 14 },
];
expect(simplifyLine(straight, 1)).toEqual([straight[0]!, straight[2]!]);
});
it('keeps a point that actually bends the route', () => {
const bent = [
{ lat: 52, lng: 13 },
{ lat: 52.5, lng: 13.5 },
{ lat: 52, lng: 14 },
];
expect(simplifyLine(bent, 1)).toHaveLength(3);
});
it('leaves a two-point line alone', () => {
expect(simplifyLine([BERLIN, DRESDEN], 5)).toEqual([BERLIN, DRESDEN]);
});
});
describe('pointAtMeters', () => {
// A straight run due east along one parallel, so the arithmetic is checkable by hand:
// at 52° north a degree of longitude is about 68.5 km.
const WEST: LatLng = { lat: 52, lng: 13 };
const EAST: LatLng = { lat: 52, lng: 14 };
const LEG = haversineKm(WEST, EAST) * 1000;
it('lands halfway along a single segment', () => {
const mid = pointAtMeters([WEST, EAST], LEG / 2)!;
expect(mid.lat).toBeCloseTo(52, 5);
expect(mid.lng).toBeCloseTo(13.5, 3);
});
it('walks past the first segment into the second', () => {
const line = [WEST, EAST, { lat: 52, lng: 15 }];
const at = pointAtMeters(line, LEG * 1.5)!;
// One and a half segments in, so halfway through the second.
expect(at.lng).toBeGreaterThan(14);
expect(at.lng).toBeLessThan(15);
});
it('returns the last point past the end rather than nothing', () => {
// A tank that runs out after the day's final stop still ran out somewhere; the
// caller decides what to do about that, so this must not answer null.
expect(pointAtMeters([WEST, EAST], LEG * 10)).toEqual(EAST);
});
it('answers the first point for zero, and nothing for an empty line', () => {
expect(pointAtMeters([WEST, EAST], 0)).toEqual(WEST);
expect(pointAtMeters([WEST, EAST], -5)).toEqual(WEST);
expect(pointAtMeters([], 100)).toBeNull();
expect(pointAtMeters([WEST], 100)).toEqual(WEST);
});
it('survives a repeated vertex without dividing by zero', () => {
// A route line concatenated from several runs does contain these.
const at = pointAtMeters([WEST, WEST, EAST], LEG / 2)!;
expect(at.lng).toBeCloseTo(13.5, 3);
});
});
describe('boxAround', () => {
it('reaches the asked radius on all four sides', () => {
const box = boxAround(BERLIN, 10);
// North and south are the easy ones: a degree of latitude is constant.
expect(haversineKm(BERLIN, { lat: box.north, lng: BERLIN.lng })).toBeCloseTo(10, 0);
expect(haversineKm(BERLIN, { lat: BERLIN.lat, lng: box.east })).toBeCloseTo(10, 0);
});
it('widens the longitude span the further north it sits', () => {
// The same radius is more degrees of longitude in Tromsø than in Berlin.
const berlin = boxAround(BERLIN, 10);
const tromso = boxAround({ lat: 69.65, lng: 18.96 }, 10);
expect(tromso.east - tromso.west).toBeGreaterThan(berlin.east - berlin.west);
});
});
describe('sliceAtMeters', () => {
// A degree of latitude is about 111 km, so this line is roughly 111 km long and every
// figure below can be read off it without a calculator.
const line: LatLng[] = [
{ lat: 52, lng: 13 },
{ lat: 53, lng: 13 },
];
it('cuts a stretch out of the middle and interpolates both ends', () => {
const out = sliceAtMeters(line, 30_000, 60_000);
expect(out).toHaveLength(2);
expect(haversineKm(out[0]!, out[1]!) * 1000).toBeGreaterThan(29_000);
expect(haversineKm(out[0]!, out[1]!) * 1000).toBeLessThan(31_000);
});
it('two adjacent slices meet exactly, so the parts rebuild the whole', () => {
// The reason this exists: a day's line is its legs end to end, and a night drive
// takes its own leg to the next card. A gap at the join would draw as a break in
// the road.
const first = sliceAtMeters(line, 0, 40_000);
const second = sliceAtMeters(line, 40_000, 80_000);
const end = first[first.length - 1]!;
expect(haversineKm(end, second[0]!)).toBeLessThan(0.001);
});
it('clamps to the line rather than running past its end', () => {
const out = sliceAtMeters(line, 0, 999_000_000);
expect(out[out.length - 1]!).toEqual(line[line.length - 1]!);
});
it('is empty for a zero-length or backwards range', () => {
expect(sliceAtMeters(line, 50_000, 50_000)).toEqual([]);
expect(sliceAtMeters(line, 60_000, 30_000)).toEqual([]);
});
it('is empty for a line that is not one', () => {
expect(sliceAtMeters([], 0, 100)).toEqual([]);
expect(sliceAtMeters([{ lat: 52, lng: 13 }], 0, 100)).toEqual([]);
});
it('survives a repeated vertex without producing NaN', () => {
// A concatenated route line really does contain these, and dividing by a zero-length
// segment is how a route full of NaN reaches the map.
const doubled: LatLng[] = [
{ lat: 52, lng: 13 },
{ lat: 52, lng: 13 },
{ lat: 53, lng: 13 },
];
const out = sliceAtMeters(doubled, 10_000, 20_000);
expect(out.every((p) => Number.isFinite(p.lat) && Number.isFinite(p.lng))).toBe(true);
});
});
+226
View File
@@ -0,0 +1,226 @@
export interface LatLng {
lat: number;
lng: number;
}
export interface Bbox {
south: number;
west: number;
north: number;
east: number;
}
const EARTH_RADIUS_KM = 6371;
const KM_PER_DEG_LAT = 111.32;
const toRad = (deg: number): number => (deg * Math.PI) / 180;
export function haversineKm(a: LatLng, b: LatLng): number {
const dLat = toRad(b.lat - a.lat);
const dLng = toRad(b.lng - a.lng);
const lat1 = toRad(a.lat);
const lat2 = toRad(b.lat);
const h = Math.sin(dLat / 2) ** 2 + Math.sin(dLng / 2) ** 2 * Math.cos(lat1) * Math.cos(lat2);
return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h)));
}
export function distanceToSegmentKm(p: LatLng, a: LatLng, b: LatLng): number {
return projectOnSegment(p, a, b).distanceKm;
}
const DEGENERATE_SEGMENT_KM2 = 1e-12;
export function projectOnSegment(p: LatLng, a: LatLng, b: LatLng): { distanceKm: number; t: number } {
const latScale = KM_PER_DEG_LAT;
const lngScale = KM_PER_DEG_LAT * Math.cos(toRad((a.lat + b.lat) / 2));
const ax = a.lng * lngScale;
const ay = a.lat * latScale;
const bx = b.lng * lngScale;
const by = b.lat * latScale;
const px = p.lng * lngScale;
const py = p.lat * latScale;
const dx = bx - ax;
const dy = by - ay;
const lenSq = dx * dx + dy * dy;
if (lenSq < DEGENERATE_SEGMENT_KM2) return { distanceKm: haversineKm(p, a), t: 0 };
const t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / lenSq));
const cx = ax + t * dx;
const cy = ay + t * dy;
return { distanceKm: Math.hypot(px - cx, py - cy), t };
}
export interface CorridorHit {
offRouteKm: number;
alongKm: number;
}
export function projectOntoRoute(p: LatLng, line: LatLng[]): CorridorHit | null {
if (line.length < 2) return null;
let best = Number.POSITIVE_INFINITY;
let bestAlong = 0;
let travelled = 0;
for (let i = 0; i < line.length - 1; i++) {
const a = line[i]!;
const b = line[i + 1]!;
const segment = haversineKm(a, b);
const { distanceKm: d, t } = projectOnSegment(p, a, b);
if (d < best) {
best = d;
bestAlong = travelled + t * segment;
}
travelled += segment;
}
return { offRouteKm: best, alongKm: bestAlong };
}
function densify(line: LatLng[], maxStepDeg: number): LatLng[] {
if (line.length < 2) return line;
const out: LatLng[] = [line[0]!];
for (let i = 1; i < line.length; i++) {
const a = line[i - 1]!;
const b = line[i]!;
const span = Math.max(Math.abs(b.lat - a.lat), Math.abs(b.lng - a.lng));
const steps = Math.max(1, Math.ceil(span / maxStepDeg));
for (let s = 1; s <= steps; s++) {
out.push({
lat: a.lat + ((b.lat - a.lat) * s) / steps,
lng: a.lng + ((b.lng - a.lng) * s) / steps,
});
}
}
return out;
}
export function corridorTiles(line: LatLng[], widthKm: number, maxSpanDeg = 0.45): Bbox[] {
if (line.length === 0) return [];
const padLat = widthKm / KM_PER_DEG_LAT;
const tiles: Bbox[] = [];
let current: Bbox | null = null;
const padded = (b: Bbox): Bbox => {
const midLat = (b.north + b.south) / 2;
const padLng = padLat / Math.max(0.2, Math.cos(toRad(midLat)));
return {
south: b.south - padLat,
north: b.north + padLat,
west: b.west - padLng,
east: b.east + padLng,
};
};
let previous: LatLng | null = null;
for (const p of densify(line, maxSpanDeg / 2)) {
if (!current) {
current = { south: p.lat, north: p.lat, west: p.lng, east: p.lng };
previous = p;
continue;
}
const next: Bbox = {
south: Math.min(current.south, p.lat),
north: Math.max(current.north, p.lat),
west: Math.min(current.west, p.lng),
east: Math.max(current.east, p.lng),
};
const grown = padded(next);
if (grown.north - grown.south > maxSpanDeg || grown.east - grown.west > maxSpanDeg) {
tiles.push(padded(current));
const from = previous ?? p;
current = {
south: Math.min(from.lat, p.lat),
north: Math.max(from.lat, p.lat),
west: Math.min(from.lng, p.lng),
east: Math.max(from.lng, p.lng),
};
} else {
current = next;
}
previous = p;
}
if (current) tiles.push(padded(current));
return tiles;
}
export function simplifyLine(line: LatLng[], toleranceKm: number): LatLng[] {
if (line.length < 3) return line.slice();
let maxDist = 0;
let index = 0;
const first = line[0]!;
const last = line[line.length - 1]!;
for (let i = 1; i < line.length - 1; i++) {
const d = distanceToSegmentKm(line[i]!, first, last);
if (d > maxDist) {
maxDist = d;
index = i;
}
}
if (maxDist <= toleranceKm) return [first, last];
const left = simplifyLine(line.slice(0, index + 1), toleranceKm);
const right = simplifyLine(line.slice(index), toleranceKm);
return [...left.slice(0, -1), ...right];
}
export function pointAtMeters(line: LatLng[], metres: number): LatLng | null {
if (!line.length) return null;
if (line.length === 1 || metres <= 0) return line[0]!;
let covered = 0;
for (let i = 1; i < line.length; i++) {
const step = haversineKm(line[i - 1]!, line[i]!) * 1000;
if (covered + step >= metres) {
const t = step > 0 ? (metres - covered) / step : 0;
return {
lat: line[i - 1]!.lat + (line[i]!.lat - line[i - 1]!.lat) * t,
lng: line[i - 1]!.lng + (line[i]!.lng - line[i - 1]!.lng) * t,
};
}
covered += step;
}
return line[line.length - 1]!;
}
export function lineMetres(line: LatLng[]): number {
let total = 0;
for (let i = 1; i < line.length; i++) total += haversineKm(line[i - 1]!, line[i]!) * 1000;
return total;
}
export function sliceAtMeters(line: LatLng[], fromMetres: number, toMetres: number): LatLng[] {
if (line.length < 2 || toMetres <= fromMetres) return [];
const from = Math.max(0, fromMetres);
const out: LatLng[] = [];
let covered = 0;
for (let i = 1; i < line.length; i++) {
const step = haversineKm(line[i - 1]!, line[i]!) * 1000;
const segStart = covered;
const segEnd = covered + step;
covered = segEnd;
if (segEnd < from) continue;
if (segStart > toMetres) break;
const at = (m: number): LatLng => {
const t = step > 0 ? (m - segStart) / step : 0;
return {
lat: line[i - 1]!.lat + (line[i]!.lat - line[i - 1]!.lat) * t,
lng: line[i - 1]!.lng + (line[i]!.lng - line[i - 1]!.lng) * t,
};
};
if (!out.length) out.push(segStart >= from ? line[i - 1]! : at(from));
out.push(segEnd <= toMetres ? line[i]! : at(toMetres));
}
return out.length > 1 ? out : [];
}
export function boxAround(point: LatLng, radiusKm: number): Bbox {
const dLat = radiusKm / KM_PER_DEG_LAT;
const dLng = radiusKm / (KM_PER_DEG_LAT * Math.max(0.01, Math.cos(toRad(point.lat))));
return {
south: point.lat - dLat,
west: point.lng - dLng,
north: point.lat + dLat,
east: point.lng + dLng,
};
}
+8 -6
View File
@@ -1,11 +1,13 @@
import { z } from 'zod';
export const roadtripDayBoundarySchema = z.object({
day_number: z.number().int().min(1).max(366),
from_assignment_id: z.number().int().positive(),
to_assignment_id: z.number().int().positive().nullable(),
fraction: z.number().min(0).max(1),
}).refine(b => b.to_assignment_id !== b.from_assignment_id, 'A boundary needs two different stops');
export const roadtripDayBoundarySchema = z
.object({
day_number: z.number().int().min(1).max(366),
from_assignment_id: z.number().int().positive(),
to_assignment_id: z.number().int().positive().nullable(),
fraction: z.number().min(0).max(1),
})
.refine((b) => b.to_assignment_id !== b.from_assignment_id, 'A boundary needs two different stops');
export const roadtripDayBoundaryListSchema = z.object({
boundaries: z.array(roadtripDayBoundarySchema),
+367
View File
@@ -0,0 +1,367 @@
import { dayWindow, planDayWindow, roadtripInsertion } from './dayWindow';
import type { RoadtripStop, RoutedLeg } from './planning-types';
import { describe, expect, it } from 'vitest';
const hours = { start: 480, end: 1080 };
const labels = { start: 'Continue', end: 'End of day' };
const stop = (id: number, patch: Partial<RoadtripStop> = {}): RoadtripStop => ({
assignmentId: id,
placeId: id,
ownerDayId: 1,
ownerIndex: id - 1,
lat: 0,
lng: id - 1,
name: `Stop ${id}`,
time: null,
dwellMinutes: 0,
legMode: null,
incomingLegMode: null,
stopType: null,
...patch,
});
const day = (number: number, stops: RoadtripStop[] = []) => ({
dayId: number,
dayNumber: number,
date: `2026-09-${String(number + 10).padStart(2, '0')}`,
title: null,
stops,
});
const leg = (minutes: number, from: RoadtripStop, to: RoadtripStop): RoutedLeg => ({
line: [
[from.lat, from.lng],
[to.lat, to.lng],
],
vias: [],
seg: {
from: [from.lat, from.lng],
to: [to.lat, to.lng],
mid: [0, (from.lng + to.lng) / 2],
distance: minutes * 1000,
duration: minutes * 60,
mode: 'driving',
distanceText: '',
drivingText: '',
walkingText: '',
},
});
const calculate = (stops: RoadtripStop[], minutes: number[] = [720], extra = [day(2)]) =>
planDayWindow(
[day(1, stops), ...extra],
hours,
(a, b) => leg(minutes[stops.indexOf(a)]! ?? 60, a, b),
'metric',
labels,
);
describe('daily travel window', () => {
it('pulls an unpinned visit back into day one and ends after its full stay', () => {
const stops = [stop(1, { time: '07:00' }), stop(2, { dwellMinutes: 90 }), stop(3)];
const lookup = (a: RoadtripStop, b: RoadtripStop) => leg(720, a, b);
const automatic = planDayWindow([day(1, stops)], hours, lookup, 'metric', labels);
expect(automatic.chains[0]!.stops).not.toContain(stops[1]!);
const manual = planDayWindow([day(1, stops)], hours, lookup, 'metric', labels, [
{ day_number: 1, from_assignment_id: 2, to_assignment_id: null, fraction: 1 },
]);
expect(manual.issue).toBeNull();
expect(manual.chains[0]!.stops).toContain(stops[1]!);
expect(manual.chains[0]!.schedule.entries.map((e) => e.arrival)).toEqual(['07:00', '19:00', '20:30']);
expect(manual.chains[1]!.schedule.entries[0]!.arrival).toBe('08:00');
expect(stops[0]!.time).toBe('07:00');
});
it.each([0.25, 0.9])('moves the cut in either direction and preserves the whole drive (%s)', (fraction) => {
const stops = [stop(1), stop(2)];
const manual = planDayWindow([day(1, stops)], hours, (a, b) => leg(720, a, b), 'metric', labels, [
{ day_number: 1, from_assignment_id: 1, to_assignment_id: 2, fraction },
]);
expect(manual.issue).toBeNull();
const end = manual.chains[0]!.stops[1]!;
expect(end.lng).toBeCloseTo(fraction);
expect(end.automaticNight).toMatchObject({ manual: true, position: fraction });
const start = manual.chains[1]!.stops[0]!;
expect(manual.legFor(stops[0]!, end)!.seg.duration + manual.legFor(start, stops[1]!)!.seg.duration).toBeCloseTo(
720 * 60,
);
});
it('does not pull a visit with a fixed time out of its stored day', () => {
const pinned = stop(2, { ownerDayId: 2, time: '12:00' });
const manual = planDayWindow(
[day(1, [stop(1)]), day(2, [pinned])],
hours,
(a, b) => leg(60, a, b),
'metric',
labels,
[{ day_number: 1, from_assignment_id: 2, to_assignment_id: null, fraction: 1 }],
);
expect(manual.issue).toBe('conflict');
expect(pinned.time).toBe('12:00');
});
it('rejects crossed or disconnected manual boundaries', () => {
const stops = [stop(1), stop(2), stop(3)];
for (const boundaries of [
[{ day_number: 1, from_assignment_id: 1, to_assignment_id: 3, fraction: 0.5 }],
[
{ day_number: 1, from_assignment_id: 3, to_assignment_id: null, fraction: 1 },
{ day_number: 2, from_assignment_id: 2, to_assignment_id: null, fraction: 1 },
],
])
expect(planDayWindow([day(1, stops)], hours, (a, b) => leg(60, a, b), 'metric', labels, boundaries).issue).toBe(
'conflict',
);
});
it('mixes an explicit stop end with automatic cuts on later drives', () => {
const visited = stop(2, { endDay: true, dwellMinutes: 60 });
const planned = calculate([stop(1), visited, stop(3)], [120, 720], []);
expect(planned.issue).toBeNull();
expect(planned.chains.map((d) => d.schedule.entries.map((e) => e.arrival))).toEqual([
['08:00', '10:00', '11:00'],
['08:00', '18:00'],
['08:00', '10:00'],
]);
expect(planned.chains[0]!.stops[2]!).toMatchObject({ lat: visited.lat, lng: visited.lng });
expect(visited.endDay).toBe(true);
});
it('removing an explicit end restores the automatic schedule without adding a final night', () => {
const planned = calculate([stop(1), stop(2, { endDay: false }), stop(3, { endDay: true })], [120, 60], []);
expect(planned.chains).toHaveLength(1);
expect(planned.chains[0]!.schedule.entries.map((e) => e.arrival)).toEqual(['08:00', '10:00', '11:00']);
});
it('keeps manual times when an explicit end would move their day', () => {
const pinned = stop(2, { time: '12:00' });
const planned = calculate([stop(1, { endDay: true }), pinned], [60], []);
expect(planned.issue).toBe('conflict');
expect(pinned.time).toBe('12:00');
});
it('honors an earlier manual arrival on the following stored day', () => {
const first = stop(1, { endDay: true });
const next = stop(2, { time: '07:00', ownerDayId: 2 });
const planned = planDayWindow([day(1, [first]), day(2, [next])], hours, (a, b) => leg(60, a, b), 'metric', labels);
expect(planned.issue).toBeNull();
expect(planned.chains[1]!.schedule.entries.map((e) => e.arrival)).toEqual(['06:00', '07:00']);
expect(next.time).toBe('07:00');
});
it('requires two valid increasing HH:mm values', () => {
expect(dayWindow('08:00', '18:00')).toEqual(hours);
expect(dayWindow('00:00', '00:01')).toEqual({ start: 0, end: 1 });
for (const pair of [
[null, '18:00'],
['08:00', ''],
['8:00', '18:00'],
['24:00', '25:00'],
['18:00', '08:00'],
['08:00', '08:00'],
[800, 1800],
]) {
expect(dayWindow(...(pair as [unknown, unknown]))).toBeNull();
}
});
it('splits the drive at day end and resumes at the same point next morning', () => {
const first = stop(1);
const last = stop(2, { lng: 12 });
const planned = calculate([first, last]);
expect(planned.issue).toBeNull();
const today = planned.chains[0]!;
const tomorrow = planned.chains[1]!;
const end = today.stops[1]!;
const start = tomorrow.stops[0]!;
expect(today.schedule.entries[0]!.arrival).toBe('08:00');
expect(today.schedule.entries[1]!.arrival).toBe('18:00');
expect(end.lng).toBeCloseTo(10);
expect([start.lat, start.lng]).toEqual([end.lat, end.lng]);
expect(tomorrow.schedule.entries.map((e) => e.arrival)).toEqual(['08:00', '10:00']);
expect(tomorrow.stops[1]!).toBe(last);
expect(tomorrow.spills[0]!).toMatchObject({ automatic: true, fromDayNumber: 1, at: 1 });
const before = planned.legFor(first, end)!;
const after = planned.legFor(start, last)!;
expect(before.seg.duration + after.seg.duration).toBe(720 * 60);
expect(before.seg.distance + after.seg.distance).toBe(720000);
expect(before.line[before.line.length - 1]!).toEqual(after.line[0]!);
expect(first.time).toBeNull();
expect(last.ownerDayId).toBe(1);
});
it('ends at the last visited place after its stay when the next drive will not fit', () => {
const first = stop(1);
const visited = stop(2, { dwellMinutes: 60 });
const next = stop(3);
const route = [first, visited, next];
const lookup = (a: RoadtripStop, b: RoadtripStop) => leg(a === first ? 480 : 120, a, b);
const planned = planDayWindow([day(1, route)], { ...hours, endMode: 'stop' }, lookup, 'metric', labels);
expect(planned.issue).toBeNull();
expect(planned.chains[0]!.schedule.entries.map((e) => e.arrival)).toEqual(['08:00', '16:00', '17:00']);
expect(planned.chains[0]!.stops[2]!).toMatchObject({ lat: visited.lat, lng: visited.lng });
expect(planned.chains[1]!.schedule.entries.map((e) => e.arrival)).toEqual(['08:00', '10:00']);
expect(planned.legFor(planned.chains[1]!.stops[0]!, next)?.seg.duration).toBe(7200);
expect(visited.dwellMinutes).toBe(60);
expect(next.ownerDayId).toBe(1);
const alongRoute = planDayWindow([day(1, route)], hours, lookup, 'metric', labels);
expect(alongRoute.chains[0]!.schedule.entries[2]!.arrival).toBe('18:00');
expect(alongRoute.chains[1]!.schedule.entries[1]!.arrival).toBe('09:00');
});
it('reaches a last place exactly at the cutoff and still respects manual times', () => {
const first = stop(1, { time: '07:00' });
const next = stop(2);
const calculateAtStop = (minutes: number) =>
planDayWindow(
[day(1, [first, next])],
{ ...hours, endMode: 'stop' },
(a, b) => leg(minutes, a, b),
'metric',
labels,
);
expect(calculateAtStop(660).chains[0]!.schedule.entries.map((e) => e.arrival)).toEqual(['07:00', '18:00']);
next.time = '19:00';
expect(calculateAtStop(720).chains[0]!.schedule.entries.map((e) => e.arrival)).toEqual(['07:00', '19:00']);
expect(first.time).toBe('07:00');
});
it('reports an indivisible drive that cannot fit rather than adding endless empty days', () => {
const planned = planDayWindow(
[day(1, [stop(1), stop(2)])],
{ ...hours, endMode: 'stop' },
(a, b) => leg(720, a, b),
'metric',
labels,
);
expect(planned.issue).toBe('legTooLong');
expect(planned.chains).toEqual([]);
expect(dayWindow('08:00', '18:00', 'stop')).toEqual({ ...hours, endMode: 'stop' });
expect(dayWindow('08:00', '18:00', 'unknown')).toEqual(hours);
});
it('starts at a manually pinned 07:00 despite an automatic 08:00 start', () => {
const first = stop(1, { time: '07:00' });
const planned = calculate([first, stop(2, { lng: 12 })]);
expect(planned.chains[0]!.schedule.entries[0]!).toMatchObject({ arrival: '07:00', anchored: true });
expect(planned.chains[0]!.stops[1]!.lng).toBeCloseTo(11);
expect(planned.chains[1]!.schedule.entries[1]!.arrival).toBe('09:00');
expect(first.time).toBe('07:00');
});
it('accounts for stays and recalculates the pause position without mutating places', () => {
const first = stop(1, { dwellMinutes: 120 });
const destination = stop(2, { lng: 12 });
const planned = calculate([first, destination]);
expect(planned.chains[0]!.stops[1]!.lng).toBeCloseTo(8);
expect(planned.chains[1]!.schedule.entries[1]!.arrival).toBe('12:00');
const shortened = calculate([{ ...first, dwellMinutes: 0 }, destination]);
expect(shortened.chains[0]!.stops[1]!.lng).toBeCloseTo(10);
const shortDrive = calculate([first, destination], [120]);
expect(shortDrive.chains.flatMap((d) => d.stops).some((s) => s.automaticNight)).toBe(false);
expect(first.dwellMinutes).toBe(120);
});
it('does not move an arrival exactly at day end to tomorrow', () => {
const last = stop(2);
const planned = calculate([stop(1), last], [600]);
expect(planned.chains[0]!.stops).toHaveLength(2);
expect(planned.chains[0]!.schedule.entries[1]!.arrival).toBe('18:00');
expect(planned.chains[1]!.stops).toEqual([]);
});
it('continues across multiple nights and creates preview dates beyond the trip', () => {
const planned = calculate([stop(1), stop(2, { lng: 30 })], [1800], []);
expect(planned.chains.map((d) => d.date)).toEqual(['2026-09-11', '2026-09-12', '2026-09-13']);
expect(planned.chains[2]!.schedule.entries[1]!.arrival).toBe('18:00');
expect(planned.chains[2]!.dayId).toBeLessThan(0);
expect(planned.chains.flatMap((d) => d.stops).filter((s) => !s.automaticNight)).toHaveLength(2);
});
it('keeps fixed appointments and reports an impossible schedule without partial relocation', () => {
const fixed = stop(2, { time: '10:00' });
const impossible = calculate([stop(1), fixed], [180]);
expect(impossible.issue).toBe('conflict');
expect(impossible.chains).toEqual([]);
expect(fixed.time).toBe('10:00');
const possible = calculate([stop(1), fixed], [60]);
expect(possible.chains[0]!.schedule.entries[1]!).toMatchObject({ arrival: '10:00', anchored: true });
});
it('allows a manual late appointment to override the automatic end', () => {
const fixed = stop(2, { time: '19:00' });
const planned = calculate([stop(1), fixed], [660]);
expect(planned.issue).toBeNull();
expect(planned.chains[0]!.schedule.entries[1]!.arrival).toBe('19:00');
expect(planned.chains[0]!.stops).toHaveLength(2);
});
it('keeps a pinned next-day start at 07:00 and leaves the pause point early enough', () => {
const a = stop(1);
const b = stop(2, { ownerDayId: 2, ownerIndex: 0, time: '07:00' });
const planned = planDayWindow([day(1, [a]), day(2, [b])], hours, (from, to) => leg(60, from, to), 'metric', labels);
expect(planned.issue).toBeNull();
expect(planned.chains[1]!.schedule.entries.map((e) => e.arrival)).toEqual(['06:00', '07:00']);
});
it('does not silently move a fixed appointment onto a later date after a previous spill', () => {
const planned = calculate([stop(1), stop(2), stop(3, { time: '17:00' })], [720, 60]);
expect(planned.issue).toBe('conflict');
});
it('pauses a long visit at its location and carries the remaining stay into tomorrow', () => {
const first = stop(1, { dwellMinutes: 660 });
const planned = calculate([first, stop(2)], [60]);
expect(planned.chains[0]!.stops[1]!).toMatchObject({ lat: first.lat, lng: first.lng });
expect(planned.chains[0]!.schedule.entries[0]!.departure).toBe('18:00');
expect(planned.chains[1]!.schedule.entries[0]!.departure).toBe('09:00');
expect(planned.chains[1]!.schedule.entries[1]!.arrival).toBe('10:00');
expect(first.dwellMinutes).toBe(660);
});
it('does not place a night pause halfway through a ferry crossing', () => {
const a = stop(1);
const b = stop(2);
const ferry = leg(720, a, b);
ferry.seg.mode = 'ferry';
const planned = planDayWindow([day(1, [a, b])], hours, () => ferry, 'metric', labels);
expect(planned.chains[0]!.stops).toHaveLength(2);
expect(planned.chains[0]!.schedule.entries[1]!.arrival).toBe('20:00');
});
it('does not invent times or points for missing routes', () => {
const planned = planDayWindow([day(1, [stop(1), stop(2)])], hours, () => undefined, 'metric', labels);
expect(planned.issue).toBe('incomplete');
expect(planned.chains).toEqual([]);
expect(planDayWindow([], hours, () => undefined, 'metric', labels).chains).toEqual([]);
});
it('bounds extreme driving and stay durations', () => {
expect(calculate([stop(1), stop(2)], [600 * 367]).issue).toBe('tooLong');
expect(calculate([stop(1, { dwellMinutes: 600 * 367 }), stop(2)], [1]).issue).toBe('tooLong');
});
it('maps insertions on generated days back to real stored stops', () => {
const planned = calculate([stop(1), stop(2)]);
expect(roadtripInsertion(planned.chains[1]!, 0)).toEqual({ dayId: 1, position: 1 });
expect(roadtripInsertion(planned.chains[1]!, 1)).toEqual({ dayId: 1, position: 1 });
expect(roadtripInsertion({ stops: [] }, 0)).toBeNull();
expect(roadtripInsertion(planned.chains[1]!, 2)).toEqual({ dayId: 1, position: 2 });
});
it('rounds fractional route minutes across the hour boundary', () => {
const planned = calculate([stop(1), stop(2)], [59.8]);
expect(planned.chains[0]!.schedule.entries[1]!.arrival).toBe('09:00');
});
it('keeps a zero-distance timed leg at its location when split', () => {
const a = stop(1);
const b = stop(2, { lng: a.lng });
const timed = leg(720, a, b);
timed.seg.distance = 0;
timed.line = [];
const planned = planDayWindow([day(1, [a, b])], hours, () => timed, 'metric', labels);
expect(planned.issue).toBeNull();
expect(planned.chains[1]!.stops[0]!).toMatchObject({ lat: a.lat, lng: a.lng });
expect(planned.chains[1]!.schedule.entries[1]!.arrival).toBe('10:00');
});
});
+334
View File
@@ -0,0 +1,334 @@
import { lineMetres, projectOntoRoute, sliceAtMeters } from './corridor';
import type { RoadtripDayBoundary } from './day-boundary.schema';
import type { SpillChain } from './nightSpill';
import type { RoadtripDay, RoadtripStop, RoutedLeg } from './planning-types';
import type { DistanceUnit } from './planning-types';
import { formatClock, parseClock } from './roadtripModel';
import { formatDurationShort } from './roadtripModel';
import { formatDistance } from './units';
export interface DayWindow {
start: number;
end: number;
endMode?: 'route' | 'stop';
}
export interface AutomaticNight {
phase: 'start' | 'end';
fromDayNumber: number;
position?: number;
manual?: boolean;
}
type PlanDay = Pick<RoadtripDay, 'dayId' | 'dayNumber' | 'date' | 'title' | 'stops'>;
type LegLookup = (from: RoadtripStop, to: RoadtripStop) => RoutedLeg | undefined;
export function dayWindow(start: unknown, end: unknown, endMode?: unknown): DayWindow | null {
const minutes = (clock: unknown): number | null => {
if (typeof clock !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(clock)) return null;
return Number(clock.slice(0, 2)) * 60 + Number(clock.slice(3));
};
const from = minutes(start);
const to = minutes(end);
return from !== null && to !== null && to > from
? { start: from, end: to, ...(endMode === 'stop' ? ({ endMode } as const) : {}) }
: null;
}
function portion(leg: RoutedLeg, from: number, to: number, unit: DistanceUnit): RoutedLeg {
if (from === 0 && to === 1) return leg;
const coordinates = leg.line.length ? leg.line : [leg.seg.from, leg.seg.to];
const spine = coordinates.map(([lat, lng]) => ({ lat, lng }));
const metres = lineMetres(spine);
const line =
metres === 0
? coordinates
: sliceAtMeters(spine, from * metres, to * metres).map((p) => [p.lat, p.lng] as [number, number]);
const distance = leg.seg.distance * (to - from);
const duration = leg.seg.duration * (to - from);
const durationText = formatDurationShort(duration);
const distanceText = formatDistance(distance / 1000, unit);
return {
seg: {
...leg.seg,
distance,
duration,
distanceText,
durationText,
drivingText: `${distanceText} · ${durationText}`,
walkingText: `${distanceText} · ${durationText}`,
from: line[0]!,
to: line[line.length - 1]!,
mid: line[Math.floor(line.length / 2)]!,
},
line,
vias: leg.vias.filter((v) => {
const along = (projectOntoRoute(v, spine)?.alongKm ?? 0) * 1000;
return along >= from * metres && (to === 1 ? along <= metres : along < to * metres);
}),
};
}
function stationary(stop: RoadtripStop): RoutedLeg {
const at: [number, number] = [stop.lat, stop.lng];
return {
line: [],
vias: [],
seg: {
from: at,
to: at,
mid: at,
distance: 0,
duration: 0,
mode: 'driving',
walkingText: '',
drivingText: '',
distanceText: '',
},
};
}
export interface WindowPlan {
chains: SpillChain[];
legFor: LegLookup;
issue: 'incomplete' | 'conflict' | 'tooLong' | 'legTooLong' | null;
}
export function planDayWindow(
days: PlanDay[],
window: DayWindow,
lookup: LegLookup,
unit: DistanceUnit,
labels: { start: string; end: string },
boundaries: RoadtripDayBoundary[] = [],
): WindowPlan {
const ordered = [...days].sort((a, b) => a.dayNumber - b.dayNumber);
const stops = ordered.flatMap((day) => day.stops.map((stop) => ({ stop, day })));
const failed = (issue: WindowPlan['issue']): WindowPlan => ({ chains: [], legFor: lookup, issue });
if (!stops.length) return { chains: [], legFor: lookup, issue: null };
const positions = new Map(stops.map(({ stop }, i) => [stop.assignmentId, i]));
const targets = new Map<number, number>();
let lastTarget = -1;
for (const boundary of [...boundaries].sort((a, b) => a.day_number - b.day_number)) {
const from = positions.get(boundary.from_assignment_id);
const to = boundary.to_assignment_id === null ? null : positions.get(boundary.to_assignment_id);
if (from === undefined || (to !== null && to !== from + 1)) return failed('conflict');
const target = from + (to === null ? 0 : boundary.fraction);
if (target <= lastTarget) return failed('conflict');
targets.set(boundary.day_number, target);
lastTarget = target;
}
const legs = stops.slice(0, -1).map((s, i) => lookup(s.stop, stops[i + 1]!.stop));
if (
legs.some(
(l) => !l || !Number.isFinite(l.seg.duration) || l.seg.duration < 0 || (l.line.length < 2 && l.seg.distance > 0),
)
) {
return failed('incomplete');
}
const chains = new Map<number, SpillChain>();
const pieces = new Map<RoadtripStop, Map<RoadtripStop, RoutedLeg>>();
const firstDay = stops[0]!.day.dayNumber;
let number = firstDay;
let clock = window.start;
let issue: WindowPlan['issue'] = null;
let position = 0;
const chainAt = (n: number): SpillChain => {
const existing = chains.get(n);
if (existing) return existing;
const stored = ordered.find((d) => d.dayNumber === n);
const dated = ordered.find((d) => d.date);
let date = stored?.date ?? null;
if (!stored && dated?.date) {
const dayDate = new Date(`${dated.date}T12:00:00Z`);
dayDate.setUTCDate(dayDate.getUTCDate() + n - dated.dayNumber);
date = dayDate.toISOString().slice(0, 10);
}
const chain: SpillChain = {
dayId: stored?.dayId ?? -1000000000 - n,
dayNumber: n,
date,
title: stored?.title ?? null,
stops: [],
schedule: { entries: [], warnings: [] },
spills: [],
};
chains.set(n, chain);
return chain;
};
const putLeg = (from: RoadtripStop, to: RoadtripStop, leg: RoutedLeg) => {
if (!pieces.has(from)) pieces.set(from, new Map());
pieces.get(from)!.set(to, leg);
};
const append = (stop: RoadtripStop, arrival: number, departure = arrival) => {
const chain = chainAt(number);
chain.stops.push(stop);
chain.schedule.entries.push({
arrival: formatClock(Math.round(arrival)),
departure: formatClock(Math.round(departure)),
anchored: !stop.automaticNight && stop.time !== null,
dayOffset: Math.floor(arrival / 1440),
});
};
const night = (at: RoadtripStop, final = false): RoadtripStop => {
const chain = chainAt(number);
const last = chain.stops[chain.stops.length - 1]!;
const end: RoadtripStop = {
...at,
assignmentId: -2000000000 - number * 2,
name: labels.end,
time: null,
dwellMinutes: 0,
stopType: null,
fillPercent: null,
automaticNight: { phase: 'end', fromDayNumber: number, position, manual: targets.has(number) },
};
append(end, clock);
if (last) putLeg(last, end, stationary(at));
if (final) return end;
number += 1;
if (number - firstDay > 365) issue = 'tooLong';
clock = window.start;
const start: RoadtripStop = {
...end,
assignmentId: end.assignmentId - 1,
name: labels.start,
automaticNight: { ...end.automaticNight!, phase: 'start' },
};
append(start, clock);
return start;
};
let previous: RoadtripStop | undefined;
for (let i = 0; i < stops.length; i++) {
const { stop, day } = stops[i]!;
const pin = parseClock(stop.time);
if (previous && number < day.dayNumber && !targets.has(number)) {
if (window.endMode !== 'stop') clock = Math.max(clock, window.end);
previous = night(previous);
while (number < day.dayNumber && !issue) {
clock = window.end;
previous = night(previous);
}
} else if (!previous) {
number = day.dayNumber;
clock = pin ?? window.start;
}
if (issue) return failed(issue);
if (pin !== null && day.dayNumber !== number) return failed('conflict');
if (previous) {
const leg = legs[i - 1]!;
const minutes = leg.seg.duration / 60;
if (pin !== null && chainAt(number).stops.every((s) => s.automaticNight)) {
clock = Math.min(clock, pin - minutes);
if (clock < 0) return failed('conflict');
const startEntry = chainAt(number).schedule.entries[0]!;
startEntry.arrival = formatClock(Math.round(clock));
startEntry.departure = formatClock(Math.round(clock));
}
if (pin !== null && clock + minutes > pin + 1) return failed('conflict');
let fraction = 0;
const split = pin === null && (leg.seg.mode === 'driving' || leg.seg.mode === undefined);
if (split && !targets.has(number) && window.endMode === 'stop' && clock + minutes > window.end + 0.000001) {
if (minutes > window.end - window.start) return failed('legTooLong');
previous = night(previous);
if (issue) return failed(issue);
}
while (fraction < 1) {
const target = targets.get(number);
if (target !== undefined && target < i - 1 + fraction - 0.000001) return failed('conflict');
const manualCut = target !== undefined && target < i && target >= i - 1 + fraction;
if (!manualCut && (target !== undefined || !split || clock + minutes * (1 - fraction) <= window.end + 0.000001))
break;
const available = manualCut ? minutes * (target - (i - 1 + fraction)) : Math.max(0, window.end - clock);
if (available === 0) {
previous = night(previous);
} else {
const until = Math.min(1, fraction + available / minutes);
const part = portion(leg, fraction, until, unit);
const at = part.line[part.line.length - 1]!;
const point = { ...previous, lat: at[0], lng: at[1] };
clock += available;
position = i - 1 + until;
const before = previous;
previous = night(point);
const previousStops = chainAt(number - 1).stops;
const ending = previousStops[previousStops.length - 1]!;
putLeg(before, ending, part);
fraction = until;
}
if (issue) return failed(issue);
}
const remainder = portion(leg, fraction, 1, unit);
clock += minutes * (1 - fraction);
putLeg(previous, stop, remainder);
}
position = i;
if (pin !== null && number !== day.dayNumber) return failed('conflict');
const target = targets.get(number);
if (target !== undefined && target < position) return failed('conflict');
if (pin !== null) clock = pin;
append(stop, clock);
previous = stop;
let dwell = Math.max(0, stop.dwellMinutes ?? 0);
while (dwell > 0) {
const remaining = targets.has(number) ? dwell : Math.max(0, window.end - clock);
const spend = Math.min(dwell, remaining);
clock += spend;
dwell -= spend;
const entries = chainAt(number).schedule.entries;
entries[entries.length - 1]!.departure = formatClock(Math.round(clock));
if (dwell > 0) {
previous = night(previous);
if (issue) return failed(issue);
}
}
if (target === position || (!targets.has(number) && stop.endDay && i < stops.length - 1)) {
previous = night(previous, i === stops.length - 1);
if (issue) return failed(issue);
}
}
if ([...targets.keys()].some((day) => !chains.get(day)?.stops.some((stop) => stop.automaticNight?.phase === 'end')))
return failed('conflict');
for (const chain of chains.values()) {
for (let i = 0; i < chain.stops.length; i++) {
const stop = chain.stops[i]!;
if (stop.automaticNight) continue;
const owner = ordered.find((d) => d.dayId === stop.ownerDayId);
if (!owner || owner.dayNumber === chain.dayNumber) continue;
const last = chain.spills[chain.spills.length - 1]!;
if (last?.fromDayNumber === owner.dayNumber && last.at + last.count === i) last.count += 1;
else
chain.spills.push({
automatic: true,
at: i,
count: 1,
fromDayNumber: owner.dayNumber,
departure: null,
leg: undefined,
line: [],
fromStop: undefined,
});
}
}
for (const day of ordered) chainAt(day.dayNumber);
return {
chains: [...chains.values()].sort((a, b) => a.dayNumber - b.dayNumber),
legFor: (from, to) => pieces.get(from)?.get(to),
issue: null,
};
}
export function roadtripInsertion(day: Pick<RoadtripDay, 'stops'>, index: number) {
const stop = day.stops[Math.min(Math.max(0, index), day.stops.length - 1)]!;
return stop
? { dayId: stop.ownerDayId, position: stop.ownerIndex + (stop.automaticNight || index >= day.stops.length ? 1 : 0) }
: null;
}
+279
View File
@@ -0,0 +1,279 @@
import { spillChains } from './nightSpill';
import type { QuietDay, RoadtripDay, RoadtripStop } from './planning-types';
import type { RouteSegment } from './planning-types';
import { describe, it, expect } from 'vitest';
type PlanDay = Pick<RoadtripDay, 'dayId' | 'dayNumber' | 'date' | 'title' | 'stops'>;
function stop(over: Partial<RoadtripStop> & { assignmentId: number; name: string }): RoadtripStop {
return {
ownerDayId: 1,
ownerIndex: 0,
placeId: over.assignmentId * 10,
lat: 53.5,
lng: 9.9,
time: null,
dwellMinutes: null,
legMode: null,
incomingLegMode: null,
stopType: null,
...over,
};
}
/** A day of the plan, with every stop's stored position filled in for it. */
function day(dayId: number, dayNumber: number, stops: RoadtripStop[]): PlanDay {
return {
dayId,
dayNumber,
date: null,
title: null,
stops: stops.map((s, i) => ({ ...s, ownerDayId: dayId, ownerIndex: i })),
};
}
const seg = (minutes: number, km = 100): RouteSegment =>
({
distance: km * 1000,
duration: minutes * 60,
distanceText: `${km} km`,
durationText: `${minutes} min`,
mode: 'driving',
}) as RouteSegment;
/** Every leg the same length, which is all most of these cases need. */
const everyLeg =
(minutes: number, km = 100) =>
() => ({
seg: seg(minutes, km),
line: [
[0, 0],
[1, 1],
] as [number, number][],
});
/** No leg routed at all, which is what an unrouted or offline trip looks like. */
const noLegs = () => undefined;
describe('spillChains', () => {
it('FE-NIGHTSPILL-001: leaves an ordinary day exactly where it is', () => {
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '09:00', dwellMinutes: 60 }),
stop({ assignmentId: 2, name: 'Berlin' }),
]),
];
const chains = spillChains(plan, [], everyLeg(180));
expect(chains).toHaveLength(1);
expect(chains[0]!.stops.map((s) => s.name)).toEqual(['Hamburg', 'Berlin']);
expect(chains[0]!.spills).toEqual([]);
});
it('FE-NIGHTSPILL-002: hands the stops reached after midnight to the next day', () => {
// 21:00 + 1 h 30 stay = 22:30, then a three hour drive arrives at 01:30 tomorrow.
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00', dwellMinutes: 90 }),
stop({ assignmentId: 2, name: 'Neuruppin' }),
]),
day(2, 2, [
stop({ assignmentId: 3, name: 'Wittenberg', time: '10:00' }),
stop({ assignmentId: 4, name: 'Leipzig' }),
]),
];
const chains = spillChains(plan, [], everyLeg(180));
expect(chains[0]!.stops.map((s) => s.name)).toEqual(['Hamburg']);
expect(chains[1]!.stops.map((s) => s.name)).toEqual(['Neuruppin', 'Wittenberg', 'Leipzig']);
});
it('FE-NIGHTSPILL-003: the spill carries the night drive and the time it set off', () => {
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00', dwellMinutes: 90 }),
stop({ assignmentId: 2, name: 'Neuruppin' }),
]),
day(2, 2, [
stop({ assignmentId: 3, name: 'Wittenberg', time: '10:00' }),
stop({ assignmentId: 4, name: 'Leipzig' }),
]),
];
const chains = spillChains(plan, [], everyLeg(180, 240));
expect(chains[1]!.spills).toHaveLength(1);
const spill = chains[1]!.spills[0]!;
expect(spill).toMatchObject({ at: 0, count: 1, fromDayNumber: 1, departure: '22:30' });
// The leg is the drive that crossed midnight, not the one after it: without it the
// card would gain a stop and none of the distance that reaches it.
expect(spill.leg?.distance).toBe(240000);
expect(spill.line.length).toBeGreaterThan(1);
});
it('FE-NIGHTSPILL-004: a stop that moved keeps the day the server stores it on', () => {
const plan = [
day(7, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00', dwellMinutes: 90 }),
stop({ assignmentId: 2, name: 'Neuruppin' }),
]),
day(8, 2, [stop({ assignmentId: 3, name: 'Wittenberg', time: '10:00' })]),
];
const chains = spillChains(plan, [], everyLeg(180));
// Drawn under day 2, stored on day 1 — which is what every callback still names.
const moved = chains[1]!.stops.find((s) => s.name === 'Neuruppin')!;
expect(moved?.ownerDayId).toBe(7);
expect(moved?.ownerIndex).toBe(1);
});
it('FE-NIGHTSPILL-005: the last day of a trip keeps its own crossing, having nowhere to send it', () => {
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00', dwellMinutes: 90 }),
stop({ assignmentId: 2, name: 'Neuruppin' }),
]),
];
const chains = spillChains(plan, [], everyLeg(180));
expect(chains).toHaveLength(1);
expect(chains[0]!.stops.map((s) => s.name)).toEqual(['Hamburg', 'Neuruppin']);
expect(chains[0]!.spills).toEqual([]);
// And it still says so: the arrival is a day past the one the card is under.
expect(chains[0]!.schedule.entries[1]!.dayOffset).toBe(1);
});
it('FE-NIGHTSPILL-006: a pinned time resolved to yesterday does not tear the day apart', () => {
// The case that broke it: 07:00 then 23:00. `computeSchedule` resolves the second pin
// to the occurrence nearest the drive reaching it, so nine hours late reads as nearer
// than fifteen hours of waiting and 23:00 lands on the PREVIOUS day. The whole chain
// is then lifted to stay positive, which leaves the FIRST stop wearing a day offset
// and the one after it none. Placing stops on those offsets moved the early stop to
// tomorrow and left the late one behind, visiting them out of order.
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Cobbelsdorf', time: '07:00', dwellMinutes: 45 }),
stop({ assignmentId: 2, name: 'Wittenberg', time: '23:00', dwellMinutes: 180 }),
stop({ assignmentId: 3, name: 'Leipzig' }),
]),
day(2, 2, [stop({ assignmentId: 4, name: 'Dresden', time: '12:00' })]),
];
const chains = spillChains(plan, [], everyLeg(50));
// Cobbelsdorf and Wittenberg both stay: nothing between them crosses midnight.
expect(chains[0]!.stops.map((s) => s.name)).toEqual(['Cobbelsdorf', 'Wittenberg']);
// Leipzig is reached at 02:50, after the clock went back past 23:00, so it moves.
expect(chains[1]!.stops.map((s) => s.name)).toEqual(['Leipzig', 'Dresden']);
});
it('FE-NIGHTSPILL-007: two nights land on two different days', () => {
// 20:00, then two twelve-hour drives: 08:00 the next day, 20:00 that evening, and
// 08:00 the day after — two backwards jumps of the clock, two days on.
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'A', time: '20:00' }),
stop({ assignmentId: 2, name: 'B' }),
stop({ assignmentId: 3, name: 'C' }),
stop({ assignmentId: 4, name: 'D' }),
]),
day(2, 2, []),
day(3, 3, []),
];
const chains = spillChains(plan, [], everyLeg(12 * 60));
expect(chains[0]!.stops.map((s) => s.name)).toEqual(['A']);
expect(chains[1]!.stops.map((s) => s.name)).toEqual(['B', 'C']);
expect(chains[2]!.stops.map((s) => s.name)).toEqual(['D']);
});
it('FE-NIGHTSPILL-008: a day whose legs never routed moves nothing', () => {
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00' }),
stop({ assignmentId: 2, name: 'Neuruppin' }),
]),
day(2, 2, [stop({ assignmentId: 3, name: 'Wittenberg', time: '10:00' })]),
];
const chains = spillChains(plan, [], noLegs);
// No drive, no arrival, no crossing — and a guess would be worse than nothing.
expect(chains[0]!.stops.map((s) => s.name)).toEqual(['Hamburg', 'Neuruppin']);
expect(chains[1]!.spills).toEqual([]);
});
it('FE-NIGHTSPILL-009: a day that carries no drive of its own still receives one', () => {
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00', dwellMinutes: 90 }),
stop({ assignmentId: 2, name: 'Neuruppin' }),
]),
];
const quiet: QuietDay[] = [{ dayId: 2, dayNumber: 2, date: null, title: null, stops: [] }];
const chains = spillChains(plan, quiet, everyLeg(180));
expect(chains).toHaveLength(2);
expect(chains[1]!.dayId).toBe(2);
expect(chains[1]!.stops.map((s) => s.name)).toEqual(['Neuruppin']);
});
it('FE-NIGHTSPILL-010: the crossing is not marked twice on a stop that moved', () => {
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00', dwellMinutes: 90 }),
stop({ assignmentId: 2, name: 'Neuruppin' }),
]),
day(2, 2, [stop({ assignmentId: 3, name: 'Wittenberg', time: '10:00' })]),
];
const chains = spillChains(plan, [], everyLeg(180));
// The block around it is what says the night happened; a band as well would say it
// twice. And it is not "the next day" once it is drawn under the next day's date.
expect(chains[1]!.schedule.warnings.some((w) => w.code === 'overnight')).toBe(false);
expect(chains[1]!.schedule.entries[0]!.dayOffset).toBe(0);
});
it('FE-NIGHTSPILL-011: a finding about a stop travels with it, renumbered', () => {
// Wittenberg is pinned two hours before the drive can get there, which is a "late"
// finding against index 1 of day 1. It moves to day 2 as index 0.
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00', dwellMinutes: 90 }),
stop({ assignmentId: 2, name: 'Neuruppin', time: '00:30' }),
]),
day(2, 2, [stop({ assignmentId: 3, name: 'Wittenberg', time: '10:00' })]),
];
const chains = spillChains(plan, [], everyLeg(180));
const late = chains[1]!.schedule.warnings.filter((w) => w.code === 'late');
expect(late).toHaveLength(1);
expect(late[0]!.index).toBe(0);
});
it('FE-NIGHTSPILL-012: two stops crossing together are one block, not two', () => {
const plan = [
day(1, 1, [
stop({ assignmentId: 1, name: 'Hamburg', time: '21:00', dwellMinutes: 90 }),
stop({ assignmentId: 2, name: 'Neuruppin' }),
stop({ assignmentId: 3, name: 'Potsdam' }),
]),
day(2, 2, [stop({ assignmentId: 4, name: 'Wittenberg', time: '10:00' })]),
];
const chains = spillChains(plan, [], everyLeg(180));
expect(chains[1]!.stops.map((s) => s.name)).toEqual(['Neuruppin', 'Potsdam', 'Wittenberg']);
expect(chains[1]!.spills).toHaveLength(1);
expect(chains[1]!.spills[0]!).toMatchObject({ at: 0, count: 2, fromDayNumber: 1 });
});
});
+159
View File
@@ -0,0 +1,159 @@
import type { QuietDay, RoadtripDay, RoadtripStop } from './planning-types';
import type { RouteSegment } from './planning-types';
import { computeSchedule, parseClock, type Schedule } from './roadtripModel';
export interface SpillMark {
automatic?: boolean;
at: number;
count: number;
fromDayNumber: number;
departure: string | null;
leg: RouteSegment | undefined;
fromStop: RoadtripStop | undefined;
line: [number, number][];
}
export interface SpillChain {
dayId: number;
dayNumber: number;
date: string | null;
title: string | null;
stops: RoadtripStop[];
schedule: Schedule;
spills: SpillMark[];
}
type PlanDay = Pick<RoadtripDay, 'dayId' | 'dayNumber' | 'date' | 'title' | 'stops'>;
type LegLookup = (from: RoadtripStop, to: RoadtripStop) => { seg: RouteSegment; line: [number, number][] } | undefined;
interface Placed {
stop: RoadtripStop;
arrival: string | null;
departure: string | null;
dayOffset: number;
codes: ('late' | 'overnight' | 'leg' | 'range')[];
lateMinutes: number | null;
fromDayNumber: number | null;
departedAt: string | null;
leg: RouteSegment | undefined;
line: [number, number][];
from: RoadtripStop | undefined;
}
export function spillChains(plan: PlanDay[], quietDays: QuietDay[], legFor: LegLookup): SpillChain[] {
const all: PlanDay[] = [
...plan,
...quietDays.map((d) => ({
dayId: d.dayId,
dayNumber: d.dayNumber,
date: d.date,
title: d.title,
stops: d.stops,
})),
].sort((a, b) => a.dayNumber - b.dayNumber);
const numbers = new Set(all.map((d) => d.dayNumber));
const landing = new Map<number, Placed[]>();
for (const d of all) landing.set(d.dayNumber, []);
for (const d of all) {
const routed = d.stops.slice(0, -1).map((s, i) => legFor(s, d.stops[i + 1]!));
const legs = routed.map((l) => l?.seg);
const schedule = computeSchedule(
d.stops.map((s) => ({ anchor: s.time, dwellMinutes: s.dwellMinutes })),
legs.map((l) => l?.duration),
);
let day = 0;
let previous: number | null = null;
d.stops.forEach((stop, i) => {
const entry = schedule.entries[i]!;
const clock = parseClock(entry?.arrival);
if (clock !== null) {
if (previous !== null && clock < previous) day += 1;
previous = clock;
}
const offset = day;
const marks = schedule.warnings.filter((w) => w.index === i);
const reachable = offset > 0 && numbers.has(d.dayNumber + offset);
const target = reachable ? d.dayNumber + offset : d.dayNumber;
const moved = target !== d.dayNumber;
landing.get(target)?.push({
stop,
arrival: entry?.arrival ?? null,
departure: entry?.departure ?? null,
dayOffset: moved ? 0 : offset,
codes: marks.map((w) => w.code).filter((c) => !(moved && c === 'overnight')),
lateMinutes: marks.find((w) => w.code === 'late')?.minutes ?? null,
fromDayNumber: moved ? d.dayNumber : null,
departedAt: moved ? (schedule.entries[i - 1]?.departure ?? null) : null,
leg: moved ? legs[i - 1] : undefined,
line: moved ? (routed[i - 1]?.line ?? []) : [],
from: moved ? d.stops[i - 1]! : undefined,
});
});
}
const out: SpillChain[] = [];
for (const d of all) {
const placed = landing.get(d.dayNumber) ?? [];
if (!placed.length) continue;
placed.sort((a, b) => (a.fromDayNumber ?? Number.MAX_SAFE_INTEGER) - (b.fromDayNumber ?? Number.MAX_SAFE_INTEGER));
const spills: SpillMark[] = [];
for (let i = 0; i < placed.length; i++) {
const p = placed[i]!;
if (p.fromDayNumber === null) continue;
const last = spills[spills.length - 1]!;
if (last && last.fromDayNumber === p.fromDayNumber && last.at + last.count === i) last.count += 1;
else
spills.push({
at: i,
count: 1,
fromDayNumber: p.fromDayNumber,
departure: p.departedAt,
leg: p.leg,
line: p.line,
fromStop: p.from,
});
}
out.push({
dayId: d.dayId,
dayNumber: d.dayNumber,
date: d.date,
title: d.title,
stops: placed.map((p) => p.stop),
schedule: {
entries: placed.map((p) => ({
arrival: p.arrival,
departure: p.departure,
anchored: p.stop.time !== null && p.stop.time !== undefined,
dayOffset: p.dayOffset,
})),
warnings: placed.flatMap((p, i) =>
p.codes.map((code) =>
code === 'late' ? { index: i, code, minutes: p.lateMinutes ?? 0 } : { index: i, code },
),
),
},
spills,
});
}
return out;
}
+170
View File
@@ -0,0 +1,170 @@
import type { RoadtripDayBoundary } from './day-boundary.schema';
import type { WindowPlan } from './dayWindow';
import type { AutomaticNight } from './dayWindow';
import type { SpillMark } from './nightSpill';
import type { Schedule, ScheduleWarning, DayWarning, DryPoint } from './roadtripModel';
export interface RoadtripStop {
automaticNight?: AutomaticNight;
assignmentId: number;
ownerDayId: number;
ownerIndex: number;
placeId: number;
name: string;
lat: number;
lng: number;
time: string | null;
dwellMinutes: number | null;
endDay?: boolean;
legMode: string | null;
incomingLegMode: string | null;
stopType: string | null;
fillPercent?: number | null;
offRoadMeters?: number | null;
}
export interface RoutedLeg {
seg: RouteSegment;
line: [number, number][];
snapped?: { from: SnappedPoint | null; to: SnappedPoint | null };
vias: RouteVia[];
}
export interface SnappedPoint {
lat: number;
lng: number;
offRoadMeters: number;
}
export interface RouteSegment {
mid: [number, number];
from: [number, number];
to: [number, number];
distance: number;
duration: number;
walkingText: string;
drivingText: string;
distanceText: string;
durationText?: string;
noteText?: string;
mode?: string;
}
export interface RouteVia {
hoverCard?: boolean;
nightPause?: {
day: number;
atPlace: boolean;
position?: number;
manual?: boolean;
minPosition?: number;
maxPosition?: number;
};
lat: number;
lng: number;
label?: string;
tone: 'default' | 'success' | 'warn' | 'danger';
dwellSeconds?: number;
}
export interface SnappedWaypoint {
asked: [number, number];
at: [number, number];
meters: number;
}
export type DistanceUnit = 'metric' | 'imperial';
export type RouteAvoidClass = 'motorway' | 'toll' | 'ferry';
export interface RoadtripDay {
automaticSchedule?: boolean;
dayId: number;
dayNumber: number;
date: string | null;
title: string | null;
stops: RoadtripStop[];
legs: (RouteSegment | undefined)[];
schedule: Schedule;
legVias: RouteVia[][];
avoidMissed?: RouteAvoidClass[];
dryPoints?: (DryPoint & { lat: number; lng: number })[];
drivingGeometry?: [number, number][];
geometry: [number, number][];
distance: number;
duration: number;
driveWarnings: ScheduleWarning[];
dayWarning: DayWarning | null;
spills?: SpillMark[];
}
export type PlanDay = Pick<RoadtripDay, 'dayId' | 'dayNumber' | 'date' | 'title' | 'stops'>;
export interface AccessSpur {
line: [[number, number], [number, number]];
meters: number;
stopKey: string;
}
export interface QuietDay {
dayId: number;
dayNumber: number;
date: string | null;
title: string | null;
stops: RoadtripStop[];
}
export interface RoadtripRoutes {
boundaryPath?: DayBoundaryLeg[];
validateBoundaries?: (boundaries: RoadtripDayBoundary[]) => WindowPlan['issue'];
dayWindowIssue?: 'incomplete' | 'conflict' | 'tooLong' | 'legTooLong' | null;
days: RoadtripDay[];
quietDays: QuietDay[];
lines: [number, number][][];
lineDays: number[];
accessLines: AccessSpur[];
vias: RouteVia[];
segments: RouteSegment[];
totalDistance: number;
totalDuration: number;
totalStops: number;
loading: boolean;
}
export interface DayBoundaryLeg {
from: RoadtripStop;
to: RoadtripStop;
position: number;
line: [number, number][];
}
@@ -0,0 +1,47 @@
import { roadtripPlanRequestSchema, roadtripCorridorRequestSchema, roadtripGpxImportSchema } from './planning.schema';
import { roadtripPreferencesUpdateSchema } from './preferences.schema';
import { describe, expect, it } from 'vitest';
describe('Roadtrip MCP contracts', () => {
it('defaults to a compact read-only calculation', () => {
expect(roadtripPlanRequestSchema.parse({ tripId: 3 })).toEqual({ tripId: 3, includeGeometry: false });
expect(roadtripPlanRequestSchema.safeParse({ tripId: -1 }).success).toBe(false);
});
it.each([
{ roadtrip_day_start: '24:00' },
{ roadtrip_fill_percent: 101 },
{ routing_base_url: 'http://localhost' },
{},
{ roadtrip_range_km: -1 },
{ roadtrip_avoid: 'unknown' },
])('rejects invalid driving preferences %j', (settings) => {
expect(roadtripPreferencesUpdateSchema.safeParse(settings).success).toBe(false);
});
it('allows clearing settings and preserves manual controls', () => {
expect(
roadtripPreferencesUpdateSchema.parse({
roadtrip_day_start: '',
roadtrip_range_km: 0,
roadtrip_day_end_mode: 'stop',
}),
).toMatchObject({ roadtrip_day_start: '' });
});
it('bounds corridor queries', () => {
expect(roadtripCorridorRequestSchema.parse({ tripId: 1, dayNumber: 1, category: 'charging' })).toMatchObject({
offset: 0,
widthKm: 5,
});
expect(
roadtripCorridorRequestSchema.safeParse({ tripId: 1, dayNumber: 1, category: 'charging', widthKm: 500 }).success,
).toBe(false);
});
it('bounds GPX input and defaults all supported import types', () => {
expect(roadtripGpxImportSchema.parse({ tripId: 1, gpx: '<gpx/>' })).toMatchObject({
importTracks: true,
importRoutes: true,
importWaypoints: true,
});
expect(roadtripGpxImportSchema.safeParse({ tripId: 1, gpx: 'x'.repeat(1000001) }).success).toBe(false);
});
});
+44
View File
@@ -0,0 +1,44 @@
import { idSchema } from '../common/primitives.schema';
import { roadtripPreferencesSchema } from './preferences.schema';
import { z } from 'zod';
export const roadtripPlanRequestSchema = z.object({
tripId: idSchema,
includeGeometry: z.boolean().optional().default(false),
settings: roadtripPreferencesSchema.optional().describe('Preview these personal preferences without saving them'),
});
export const roadtripCorridorRequestSchema = z.object({
tripId: idSchema,
dayNumber: z.number().int().positive().max(366),
category: z.enum(['fuel', 'charging', 'rest_area', 'campsite', 'restaurant', 'sights', 'hotel']),
widthKm: z.number().positive().max(10).default(5),
offset: z.number().int().min(0).max(1000).default(0),
name: z.string().max(100).optional(),
socket: z.string().max(50).optional(),
minKw: z.number().nonnegative().max(10000).optional(),
fromKm: z
.number()
.nonnegative()
.max(40000)
.optional()
.describe('Only matches at or after this distance along the day route'),
toKm: z
.number()
.nonnegative()
.max(40000)
.optional()
.describe('Only matches at or before this distance along the day route'),
});
export type RoadtripPlanRequest = z.infer<typeof roadtripPlanRequestSchema>;
export type RoadtripCorridorRequest = z.infer<typeof roadtripCorridorRequestSchema>;
export const roadtripGpxImportSchema = z.object({
tripId: idSchema,
gpx: z.string().min(1).max(1000000).describe('GPX XML text, up to one million characters'),
name: z.string().min(1).max(200).default('Imported track'),
importWaypoints: z.boolean().default(true),
importRoutes: z.boolean().default(true),
importTracks: z.boolean().default(true),
});
export type RoadtripGpxImport = z.infer<typeof roadtripGpxImportSchema>;
+8
View File
@@ -0,0 +1,8 @@
export * from './planning-types';
export * from './roadtripModel';
export * from './corridor';
export * from './nightSpill';
export * from './dayWindow';
export * from './vehicleRange';
export * from './assemble';
export * from './routeRun';
+39
View File
@@ -0,0 +1,39 @@
import { z } from 'zod';
const clock = z.union([z.literal(''), z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/)]);
const amount = z.number().finite().nonnegative();
export const roadtripPreferencesSchema = z
.object({
roadtrip_leg_minutes: amount.max(1440).optional(),
roadtrip_day_minutes: amount.max(1440).optional(),
roadtrip_day_start: clock.optional(),
roadtrip_day_end: clock.optional(),
roadtrip_day_end_mode: z.enum(['route', 'stop']).optional(),
roadtrip_range_km: amount.max(40000).optional(),
roadtrip_vehicle: z.enum(['', 'combustion', 'electric']).optional(),
roadtrip_fill_percent: amount.max(100).optional(),
roadtrip_tank_litres: amount.max(10000).optional(),
roadtrip_litres_per_100: amount.max(1000).optional(),
roadtrip_battery_kwh: amount.max(10000).optional(),
roadtrip_kwh_per_100: amount.max(1000).optional(),
roadtrip_battery_degradation: amount.max(100).optional(),
roadtrip_connect_days: z.boolean().optional(),
roadtrip_day_colors: z.boolean().optional(),
roadtrip_avoid: z
.string()
.max(32)
.refine(
(value) => value === '' || value.split(',').every((part) => ['toll', 'motorway', 'ferry'].includes(part)),
'Expected a comma-separated selection of toll, motorway, ferry',
)
.optional(),
})
.strict();
export const roadtripPreferencesUpdateSchema = roadtripPreferencesSchema.refine(
(value) => Object.keys(value).length > 0,
'Provide at least one driving preference',
);
export type RoadtripPreferences = z.infer<typeof roadtripPreferencesSchema>;
export const ROADTRIP_PREFERENCE_KEYS = Object.keys(roadtripPreferencesSchema.shape) as (keyof RoadtripPreferences)[];
+25 -14
View File
@@ -74,10 +74,14 @@ export type RoadtripViaUpdateRequest = z.infer<typeof roadtripViaUpdateRequestSc
* the leg into it is gone, and a via pinned to it has nowhere left to sit.
*/
export const roadtripViaReanchorRequestSchema = z.object({
vias: z.array(z.object({
id: z.number().int().positive(),
after_order_index: z.number().int().min(0),
})).max(500),
vias: z
.array(
z.object({
id: z.number().int().positive(),
after_order_index: z.number().int().min(0),
}),
)
.max(500),
remove: z.array(z.number().int().positive()).max(500).optional(),
});
export type RoadtripViaReanchorRequest = z.infer<typeof roadtripViaReanchorRequestSchema>;
@@ -95,11 +99,15 @@ export type RoadtripViaReanchorRequest = z.infer<typeof roadtripViaReanchorReque
* then adopts a scenic road for a third has not asked to lose the two.
*/
export const roadtripViaBatchRequestSchema = z.object({
vias: z.array(z.object({
after_order_index: z.number().int().min(0),
lat: latSchema,
lng: lngSchema,
})).max(100),
vias: z
.array(
z.object({
after_order_index: z.number().int().min(0),
lat: latSchema,
lng: lngSchema,
}),
)
.max(100),
/** Legs to clear first, by `after_order_index`. Absent means add to what is there. */
replace_legs: z.array(z.number().int().min(0)).max(100).optional(),
/**
@@ -110,11 +118,14 @@ export const roadtripViaBatchRequestSchema = z.object({
* any more, and an object records the road it now takes. A bare nullable id could not
* tell "do not touch this" apart from "forget it".
*/
track: z.object({
place_id: z.number().int().positive(),
/** How far the fitted route still ran from the track at its worst point. */
stray_km: z.number().min(0).max(40_000).nullable().optional(),
}).nullable().optional(),
track: z
.object({
place_id: z.number().int().positive(),
/** How far the fitted route still ran from the track at its worst point. */
stray_km: z.number().min(0).max(40_000).nullable().optional(),
})
.nullable()
.optional(),
});
export type RoadtripViaBatchRequest = z.infer<typeof roadtripViaBatchRequestSchema>;
+793
View File
@@ -0,0 +1,793 @@
import {
computeSchedule,
formatClock,
formatDurationShort,
insertIndexForAlong,
deriveDriveWarnings,
legIndexForAlong,
refuelsRange,
sectionAnchors,
parseClock,
splitIntoRuns,
sumLegSeconds,
refuelStopTypeFor,
} from './roadtripModel';
import { describe, it, expect } from 'vitest';
describe('formatDurationShort', () => {
it('prints minutes below an hour', () => {
expect(formatDurationShort(45 * 60)).toBe('45 min');
expect(formatDurationShort(0)).toBe('0 min');
});
it('drops the zero minutes on a whole hour', () => {
expect(formatDurationShort(3600)).toBe('1 h');
expect(formatDurationShort(2 * 3600)).toBe('2 h');
});
it('prints hours and minutes together', () => {
expect(formatDurationShort(2 * 3600 + 10 * 60)).toBe('2 h 10 min');
});
it('carries instead of printing sixty minutes', () => {
// 1 h 59 min 40 s rounds the minutes to 60, which must become 2 h.
expect(formatDurationShort(3600 + 59 * 60 + 40)).toBe('2 h');
});
it('treats nonsense as nothing rather than throwing', () => {
expect(formatDurationShort(Number.NaN)).toBe('0 min');
expect(formatDurationShort(-90)).toBe('0 min');
});
});
describe('parseClock', () => {
it('reads wall-clock times', () => {
expect(parseClock('09:45')).toBe(9 * 60 + 45);
expect(parseClock('9:05')).toBe(9 * 60 + 5);
expect(parseClock('00:00')).toBe(0);
});
it('ignores anything trailing, as stored times sometimes carry seconds', () => {
expect(parseClock('14:30:00')).toBe(14 * 60 + 30);
});
it('rejects what is not a time', () => {
expect(parseClock(null)).toBeNull();
expect(parseClock('')).toBeNull();
expect(parseClock('later')).toBeNull();
expect(parseClock('25:00')).toBeNull();
expect(parseClock('12:75')).toBeNull();
});
});
describe('formatClock', () => {
it('pads both halves', () => {
expect(formatClock(9 * 60 + 5)).toBe('09:05');
expect(formatClock(0)).toBe('00:00');
});
it('wraps past midnight instead of printing a 25th hour', () => {
expect(formatClock(25 * 60)).toBe('01:00');
expect(formatClock(-30)).toBe('23:30');
});
});
describe('computeSchedule', () => {
const hours = (h: number): number => h * 3600;
it('walks arrival and departure forward from the first pinned time', () => {
// The example from discussion #1797: leave at 8:00, drive 1 h 45, stay 2 h, drive 1 h 10.
const { entries } = computeSchedule(
[
{ anchor: '08:00', dwellMinutes: 0 },
{ anchor: null, dwellMinutes: 120 },
{ anchor: null, dwellMinutes: 45 },
],
[hours(1.75), hours(1) + 10 * 60],
);
expect(entries[0]!).toMatchObject({ arrival: '08:00', departure: '08:00', anchored: true });
expect(entries[1]!).toMatchObject({ arrival: '09:45', departure: '11:45', anchored: false });
expect(entries[2]!).toMatchObject({ arrival: '12:55', departure: '13:40', anchored: false });
});
it('works back from the first pinned time to say when to set off', () => {
// The museum opens at ten and we want an hour at the stop before it, an hour of
// driving in between: be there at eight. Answering that is the reason to pin a time
// on the second stop at all.
const { entries } = computeSchedule(
[
{ anchor: null, dwellMinutes: 60 },
{ anchor: '10:00', dwellMinutes: 30 },
],
[hours(1)],
);
expect(entries[0]!).toMatchObject({ arrival: '08:00', departure: '09:00', anchored: false });
expect(entries[1]!).toMatchObject({ arrival: '10:00', anchored: true });
});
it('stops working back at a leg that never routed rather than inventing one', () => {
const { entries } = computeSchedule(
[
{ anchor: null, dwellMinutes: 60 },
{ anchor: null, dwellMinutes: 30 },
{ anchor: '10:00', dwellMinutes: 30 },
],
[undefined, hours(1)],
);
expect(entries[0]!).toMatchObject({ arrival: null, departure: null });
// Leaves at 09:00 to arrive at 10:00, and its own half hour puts it there at 08:30.
expect(entries[1]!).toMatchObject({ arrival: '08:30', departure: '09:00' });
expect(entries[2]!).toMatchObject({ arrival: '10:00', anchored: true });
});
it('keeps the earliest stop on day zero when working back crosses midnight', () => {
// Pinned at one in the morning with three hours of driving before it: the stop before
// is the evening before. The chain shifts up a day rather than printing a day below
// zero, so the boundary shows between the two stops instead of under the first one.
const { entries, warnings } = computeSchedule(
[
{ anchor: null, dwellMinutes: 0 },
{ anchor: '01:00', dwellMinutes: 0 },
],
[hours(3)],
);
expect(entries[0]!).toMatchObject({ arrival: '22:00', dayOffset: 0 });
expect(entries[1]!).toMatchObject({ arrival: '01:00', dayOffset: 1, anchored: true });
expect(warnings).toContainEqual({ index: 1, code: 'overnight' });
});
it('restarts the cascade at a pinned stop instead of pushing it', () => {
// The drive would arrive at 09:00, but the museum ticket says 11:00: everything
// after it counts from 11:00, not from the drive.
const { entries } = computeSchedule(
[
{ anchor: '08:00', dwellMinutes: 0 },
{ anchor: '11:00', dwellMinutes: 60 },
{ anchor: null, dwellMinutes: 0 },
],
[hours(1), hours(1)],
);
expect(entries[1]!.arrival).toBe('11:00');
expect(entries[2]!.arrival).toBe('13:00');
});
it('ROADTRIP-MODEL-082: a night drive onto a pinned time after midnight is on time', () => {
// Leave at 20:00, drive six hours, check in at 02:00. The anchor used to be
// placed on the day the cascade had reached so far — and that only advances
// once a computed arrival crosses midnight, which is read before this stop's
// arrival is known. So the stop that does the crossing had its own pin put a
// whole day early: the rail drew a warning-coloured "+24 h" on a plan that
// was exactly on time, and dropped the overnight marker with it.
const { entries, warnings } = computeSchedule(
[
{ anchor: '20:00', dwellMinutes: 0 },
{ anchor: '02:00', dwellMinutes: 0 },
],
[hours(6)],
);
expect(warnings.filter((w) => w.code === 'late')).toEqual([]);
expect(entries[1]!).toMatchObject({ arrival: '02:00', dayOffset: 1, anchored: true });
// The day still turned over, so the rail keeps its carry badge.
expect(warnings.some((w) => w.code === 'overnight' && w.index === 1)).toBe(true);
});
it('ROADTRIP-MODEL-083: a ferry that really is missed is still reported late', () => {
// The other half: picking the nearest occurrence must not swallow a genuine
// delay. Leaving at 21:00 and driving five hours arrives at 02:00, half an
// hour after the 01:30 ferry, and that is what it says.
const { warnings } = computeSchedule(
[
{ anchor: '21:00', dwellMinutes: 0 },
{ anchor: '01:30', dwellMinutes: 0 },
],
[hours(5)],
);
expect(warnings.find((w) => w.code === 'late')!).toMatchObject({ index: 1, minutes: 30 });
});
it('ROADTRIP-MODEL-084: a pinned stop after an untimed leg keeps the day it is on', () => {
// Nothing to be late against, but the day carried so far still applies —
// otherwise the stop prints under a day-1 stop as though it happened first.
const { entries } = computeSchedule(
[
{ anchor: '20:00', dwellMinutes: 0 },
{ anchor: '02:00', dwellMinutes: 0 },
{ anchor: '09:00', dwellMinutes: 0 },
],
[hours(6), undefined],
);
expect(entries[2]!).toMatchObject({ arrival: '09:00', dayOffset: 1 });
});
it('reports a stop the drive cannot reach in time', () => {
const { warnings } = computeSchedule(
[
{ anchor: '08:00', dwellMinutes: 0 },
{ anchor: '09:00', dwellMinutes: 0 },
],
[hours(3)],
);
expect(warnings).toEqual([{ index: 1, code: 'late', minutes: 120 }]);
});
it('does not cry about a minute of rounding', () => {
const { warnings } = computeSchedule(
[
{ anchor: '08:00', dwellMinutes: 0 },
{ anchor: '09:00', dwellMinutes: 0 },
],
[hours(1) + 30],
);
expect(warnings).toEqual([]);
});
it('breaks the chain at a leg that never routed', () => {
const { entries } = computeSchedule(
[
{ anchor: '08:00', dwellMinutes: 30 },
{ anchor: null, dwellMinutes: 30 },
{ anchor: null, dwellMinutes: 0 },
],
[undefined, hours(1)],
);
expect(entries[0]!.arrival).toBe('08:00');
expect(entries[1]!.arrival).toBeNull();
expect(entries[2]!.arrival).toBeNull();
});
it('flags the day rolling past midnight and keeps counting', () => {
const { entries, warnings } = computeSchedule(
[
{ anchor: '22:00', dwellMinutes: 0 },
{ anchor: null, dwellMinutes: 0 },
],
[hours(4)],
);
expect(entries[1]!.arrival).toBe('02:00');
expect(entries[1]!.dayOffset).toBe(1);
expect(warnings).toEqual([{ index: 1, code: 'overnight' }]);
});
it('handles an empty chain', () => {
expect(computeSchedule([], [])).toEqual({ entries: [], warnings: [] });
});
it('treats a missing dwell as no time spent', () => {
const { entries } = computeSchedule(
[
{ anchor: '08:00', dwellMinutes: null },
{ anchor: null, dwellMinutes: null },
],
[hours(1)],
);
expect(entries[0]!.departure).toBe('08:00');
expect(entries[1]!.arrival).toBe('09:00');
});
});
describe('splitIntoRuns', () => {
const drive = (): string => 'driving';
it('asks for a whole day travelled one way in a single run', () => {
const runs = splitIntoRuns(['a', 'b', 'c', 'd'], drive);
expect(runs).toEqual([{ stops: ['a', 'b', 'c', 'd'], mode: 'driving' }]);
});
it('splits where the travel mode changes, and repeats the stop on both sides', () => {
// Drive to b, walk to c, drive on to d: the walk is its own request, and b and c
// each belong to two runs because they are the ends of neighbouring legs.
const modes = ['driving', 'walking', 'driving'];
const runs = splitIntoRuns(['a', 'b', 'c', 'd'], (from) => modes[['a', 'b', 'c'].indexOf(from)]!);
expect(runs).toEqual([
{ stops: ['a', 'b'], mode: 'driving' },
{ stops: ['b', 'c'], mode: 'walking' },
{ stops: ['c', 'd'], mode: 'driving' },
]);
});
it('keeps consecutive legs of the same mode together across a change and back', () => {
const modes = ['driving', 'driving', 'walking', 'walking'];
const runs = splitIntoRuns(['a', 'b', 'c', 'd', 'e'], (from) => modes[['a', 'b', 'c', 'd'].indexOf(from)]!);
expect(runs).toEqual([
{ stops: ['a', 'b', 'c'], mode: 'driving' },
{ stops: ['c', 'd', 'e'], mode: 'walking' },
]);
});
it('has nothing to ask for when there is no leg', () => {
expect(splitIntoRuns([], drive)).toEqual([]);
expect(splitIntoRuns(['a'], drive)).toEqual([]);
});
});
describe('sumLegSeconds', () => {
it('adds only the legs that routed', () => {
expect(sumLegSeconds([600, undefined, 1200])).toBe(1800);
expect(sumLegSeconds([])).toBe(0);
});
});
describe('insertIndexForAlong', () => {
// Hamburg 0, Lueneburg 50, Berlin 290 — the day's stops as distances driven.
const stops = [0, 50, 290];
it('puts a hit between the two stops it falls between', () => {
expect(insertIndexForAlong(stops, 120)).toBe(2);
expect(insertIndexForAlong(stops, 20)).toBe(1);
});
it('never lands before the stop the day starts from', () => {
expect(insertIndexForAlong(stops, 0)).toBe(1);
// A corridor is wider than the road, so a hit can project just behind the start.
expect(insertIndexForAlong(stops, -3)).toBe(1);
});
it('never lands after the stop the day ends at', () => {
expect(insertIndexForAlong(stops, 290)).toBe(2);
expect(insertIndexForAlong(stops, 400)).toBe(2);
});
it('puts a hit exactly on a stop after it, not before', () => {
expect(insertIndexForAlong(stops, 50)).toBe(2);
});
it('has nowhere to insert on a day that is not a drive', () => {
expect(insertIndexForAlong([], 10)).toBe(0);
expect(insertIndexForAlong([0], 10)).toBe(1);
});
});
describe('legIndexForAlong', () => {
// Against the legs' own lengths rather than by projecting the stops as well: leg
// distances come from the router and are exact, while two stops close together project
// onto each other's stretch and would put a charging halt the wrong side of a town.
const legs = [10_000, 25_000, 40_000];
it('FE-ROADTRIP-MODEL-050: a point inside a leg belongs to that leg', () => {
expect(legIndexForAlong(legs, 0)).toBe(0);
expect(legIndexForAlong(legs, 9_999)).toBe(0);
expect(legIndexForAlong(legs, 10_000)).toBe(1);
expect(legIndexForAlong(legs, 24_999)).toBe(1);
expect(legIndexForAlong(legs, 25_000)).toBe(2);
});
it('FE-ROADTRIP-MODEL-051: a point past the end lands in the last leg, not nowhere', () => {
// A rounding edge, not a missing leg: the projection and the router measure the same
// line two different ways and disagree by metres at the very end.
expect(legIndexForAlong(legs, 40_000)).toBe(2);
expect(legIndexForAlong(legs, 99_999)).toBe(2);
});
it('FE-ROADTRIP-MODEL-052: a day with no routed leg has nowhere to put anything', () => {
expect(legIndexForAlong([], 100)).toBe(-1);
});
});
describe('deriveDriveWarnings', () => {
// Worked through the way a traveller reads it: Hamburg, A1, HEM, Berlin. The badge on
// a stop has to agree with the sum of the drive bands above it, or it looks made up.
it('FE-ROADTRIP-MODEL-069: the figure on a stop is what the bands above it add up to', () => {
const out = deriveDriveWarnings(
[leg(20, 21.5), leg(62, 103.4), leg(155, 244.7)],
[false, false, false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 100 },
0,
);
// 21.5 + 103.4 on arrival at HEM, and then it keeps counting, because nothing on this
// trip fills up.
expect(out.warnings).toEqual([
{ index: 2, code: 'range', sinceKm: 125 },
{ index: 3, code: 'range', sinceKm: 370 },
]);
});
it('FE-ROADTRIP-MODEL-070: arriving at a petrol station is the plan, not a warning', () => {
// Same trip, but HEM is marked as fuel. Reaching it with an empty tank is exactly
// what it is there for, so nothing is flagged on it; the budget still starts over,
// and the next stretch is measured from there.
const out = deriveDriveWarnings(
[leg(20, 21.5), leg(62, 103.4), leg(155, 244.7)],
[false, false, true, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 100 },
0,
);
expect(out.warnings).toEqual([{ index: 3, code: 'range', sinceKm: 245 }]);
// 245 and not 370: HEM filled the tank, so Berlin counts from there.
});
const noLimits = { legMinutes: null, dayMinutes: null, rangeKm: null };
const leg = (minutes: number, km: number) => ({ duration: minutes * 60, distance: km * 1000 });
it('FE-ROADTRIP-MODEL-060: no limits set means nothing to report', () => {
const out = deriveDriveWarnings([leg(600, 900)], [false, false], noLimits, 0);
expect(out.warnings).toEqual([]);
expect(out.day).toBeNull();
});
it('FE-ROADTRIP-MODEL-061: a leg over the limit reports how far over, on the stop it arrives at', () => {
// On arrival, not on departure. Both findings are running totals that only become
// true when you get there, and anchored to the departure the number reads as the
// length of the NEXT leg, which is a different figure and the one that looked wrong.
const out = deriveDriveWarnings(
[leg(100, 90), leg(240, 200)],
[false, false, false],
{ ...noLimits, legMinutes: 180 },
0,
);
expect(out.warnings).toEqual([{ index: 2, code: 'leg', overMinutes: 60 }]);
});
it('FE-ROADTRIP-MODEL-062: the day figure is the sum of the legs, and only that', () => {
const out = deriveDriveWarnings(
[leg(200, 180), leg(200, 180)],
[false, false, false],
{ ...noLimits, dayMinutes: 360 },
0,
);
expect(out.day).toEqual({ code: 'dayDriving', minutes: 400, limitMinutes: 360 });
});
it('FE-ROADTRIP-MODEL-063: the figure keeps counting until something actually refuels', () => {
// A warning is not a fill-up. Zeroing the budget at one made every figure after the
// first wrong: the second stop would claim a fresh tank while the same one is still
// in the car.
const out = deriveDriveWarnings(
[leg(60, 300), leg(60, 400), leg(60, 300), leg(60, 400)],
[false, false, false, false, false],
{ ...noLimits, rangeKm: 600 },
0,
);
expect(out.warnings).toEqual([
{ index: 2, code: 'range', sinceKm: 700 },
{ index: 3, code: 'range', sinceKm: 1000 },
{ index: 4, code: 'range', sinceKm: 1400 },
]);
});
it('FE-ROADTRIP-MODEL-071: adding a fuel stop is what stops the run of warnings', () => {
// The same drive with a charger at stop 2. Nothing is flagged there, because reaching
// it on an empty tank is what it is for; everything after counts from zero again, so
// the three-warning run above collapses to one.
const out = deriveDriveWarnings(
[leg(60, 300), leg(60, 400), leg(60, 300), leg(60, 400)],
[false, false, true, false, false],
{ ...noLimits, rangeKm: 600 },
0,
);
expect(out.warnings).toEqual([{ index: 4, code: 'range', sinceKm: 700 }]);
});
it('FE-ROADTRIP-MODEL-064: filling up starts the budget over, resting does not', () => {
const stops = [false, true, false];
const out = deriveDriveWarnings([leg(60, 500), leg(60, 500)], stops, { ...noLimits, rangeKm: 600 }, 0);
// The tank is filled at stop 1, so the second 500 km starts from zero and neither leg
// trips the limit. Without the refuel it would be 1000 km on a 600 km range.
expect(out.warnings).toEqual([]);
});
it('FE-ROADTRIP-MODEL-065: only fuel and charging refuel', () => {
expect(refuelsRange('fuel')).toBe(true);
expect(refuelsRange('charging')).toBe(true);
// A two-hour lunch fills no tank, and TREK does not know whether the restaurant has a
// charger in its car park.
expect(refuelsRange('restaurant')).toBe(false);
expect(refuelsRange('rest_area')).toBe(false);
expect(refuelsRange('campsite')).toBe(false);
expect(refuelsRange(null)).toBe(false);
});
it('FE-ROADTRIP-MODEL-066: the budget carries into the next day, because a tank does not empty overnight', () => {
const first = deriveDriveWarnings([leg(60, 400)], [false, false], { ...noLimits, rangeKm: 600 }, 0);
expect(first.carryKm).toBe(400);
const second = deriveDriveWarnings([leg(60, 300)], [false, false], { ...noLimits, rangeKm: 600 }, first.carryKm);
expect(second.warnings).toEqual([{ index: 1, code: 'range', sinceKm: 700 }]);
});
it('FE-ROADTRIP-MODEL-067: an unrouted leg gives the budget up rather than guessing', () => {
const out = deriveDriveWarnings([undefined, leg(60, 500)], [false, false, false], { ...noLimits, rangeKm: 100 }, 0);
expect(out.warnings).toEqual([]);
expect(out.carryKm).toBeNull();
});
it('FE-ROADTRIP-MODEL-068: filling up at the last stop of the day still counts', () => {
const out = deriveDriveWarnings([leg(60, 400)], [false, true], { ...noLimits, rangeKm: 600 }, 0);
expect(out.carryKm).toBe(0);
});
});
describe('sectionAnchors', () => {
it('FE-ROADTRIP-MODEL-080: every stop, and the middle of every leg between them', () => {
// The leg midpoints are the point of the feature: a break on a five-hour drive is
// planned in the middle of the drive, not at either end of it.
expect(sectionAnchors([0, 100, 250])).toEqual([
{ kind: 'stop', index: 0, alongKm: 0 },
{ kind: 'leg', index: 0, alongKm: 50 },
{ kind: 'stop', index: 1, alongKm: 100 },
{ kind: 'leg', index: 1, alongKm: 175 },
{ kind: 'stop', index: 2, alongKm: 250 },
]);
});
it('FE-ROADTRIP-MODEL-081: a single stop has no leg to sit in the middle of', () => {
expect(sectionAnchors([42])).toEqual([{ kind: 'stop', index: 0, alongKm: 42 }]);
expect(sectionAnchors([])).toEqual([]);
});
});
describe('deriveDriveWarnings — what counts as driving', () => {
const drive = (minutes: number, km: number) => ({ duration: minutes * 60, distance: km * 1000, mode: 'driving' });
const onFoot = (minutes: number, km: number) => ({ duration: minutes * 60, distance: km * 1000, mode: 'walking' });
it('FE-ROADTRIP-MODEL-085: a walk to a viewpoint is not over the longest drive allowed', () => {
// A day may legitimately mix modes — splitIntoRuns exists for exactly that —
// and a two hour hike reported as a leg finding reads as a fault in a plan
// that has none.
const out = deriveDriveWarnings(
[drive(60, 80), onFoot(120, 6)],
[false, false, false],
{ legMinutes: 90, dayMinutes: null, rangeKm: null },
0,
);
expect(out.warnings).toEqual([]);
});
it('FE-ROADTRIP-MODEL-086: walked kilometres are not on the tank', () => {
// Nor does walking fill it: the budget is left exactly as the drive left it.
const out = deriveDriveWarnings(
[drive(60, 80), onFoot(120, 60), drive(30, 30)],
[false, false, false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 100 },
0,
);
// 80 then 110 — the 60 walked kilometres never entered the budget.
expect(out.warnings).toEqual([{ index: 3, code: 'range', sinceKm: 110 }]);
expect(out.carryKm).toBe(110);
});
it('FE-ROADTRIP-MODEL-087: a walk does not count toward the driving time of the day', () => {
const out = deriveDriveWarnings(
[drive(60, 80), onFoot(180, 9)],
[false, false, false],
{ legMinutes: null, dayMinutes: 90, rangeKm: null },
0,
);
expect(out.day).toBeNull();
});
it('FE-ROADTRIP-MODEL-088: a leg with no mode is still a drive', () => {
// Every leg was a drive before the field existed, so an absent mode counts.
// Reading it the other way round would silently switch the warnings off.
const out = deriveDriveWarnings(
[{ duration: 120 * 60, distance: 200 * 1000 }],
[false, false],
{ legMinutes: 90, dayMinutes: null, rangeKm: null },
0,
);
expect(out.warnings).toEqual([{ index: 1, code: 'leg', overMinutes: 30 }]);
});
});
describe('deriveDriveWarnings — where the tank actually runs dry', () => {
const drive = (minutes: number, km: number) => ({ duration: minutes * 60, distance: km * 1000, mode: 'driving' });
const ferry = (minutes: number, km: number) => ({ duration: minutes * 60, distance: km * 1000, mode: 'ferry' });
it('FE-ROADTRIP-MODEL-089: the dry point sits where the fuel ends, not where somebody notices', () => {
// 300 km of range, two legs of 200. The warning lands on stop 2, which is 400 km in;
// the tank was empty 100 km earlier, halfway through the second leg. Suggesting a
// filling station at the warning would suggest one the car cannot reach.
const out = deriveDriveWarnings(
[drive(120, 200), drive(120, 200)],
[false, false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 300 },
0,
);
expect(out.warnings).toEqual([{ index: 2, code: 'range', sinceKm: 400 }]);
expect(out.emptyAt).toEqual([{ legIndex: 1, intoLegKm: 100, drivenMeters: 300000, sinceKm: 300 }]);
});
it('FE-ROADTRIP-MODEL-090: one dry point per tank, however many warnings the stretch produces', () => {
// A long run with nothing on it warns at every stop on purpose, because a warning is
// not a fill-up. One refuel offer per warning would stack three identical offers for
// a single tank down one day.
const out = deriveDriveWarnings(
[drive(60, 400), drive(60, 400), drive(60, 400)],
[false, false, false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 600 },
0,
);
expect(out.warnings).toHaveLength(2);
expect(out.emptyAt).toHaveLength(1);
expect(out.emptyAt[0]!).toMatchObject({ legIndex: 1, drivenMeters: 600000 });
});
it('FE-ROADTRIP-MODEL-091: filling up starts a new tank, and the next one runs dry again', () => {
const out = deriveDriveWarnings(
[drive(60, 400), drive(60, 400), drive(60, 400)],
[false, false, true, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 600 },
0,
);
// Empty once before the fuel stop, then once more after it.
expect(out.emptyAt).toHaveLength(1);
expect(out.emptyAt[0]!.drivenMeters).toBe(600000);
});
it('FE-ROADTRIP-MODEL-092: a ferry carries the car without burning a drop', () => {
// The trap this field exists for. The budget skips a ferry, so the dry point must be
// counted in DRIVING metres only; measuring along the day's drawn line instead would
// overshoot by the whole crossing and put the marker out at sea.
const out = deriveDriveWarnings(
[drive(60, 200), ferry(120, 50), drive(60, 200)],
[false, false, false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 300 },
0,
);
expect(out.emptyAt).toEqual([{ legIndex: 2, intoLegKm: 100, drivenMeters: 300000, sinceKm: 300 }]);
});
it('FE-ROADTRIP-MODEL-093: a tank carried over midnight runs dry earlier the next day', () => {
const out = deriveDriveWarnings(
[drive(60, 200), drive(60, 200)],
[false, false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 300 },
250,
);
// Only 50 km left on arrival, so it empties a quarter into the first leg.
expect(out.emptyAt).toEqual([{ legIndex: 0, intoLegKm: 50, drivenMeters: 50000, sinceKm: 300 }]);
});
it('FE-ROADTRIP-MODEL-094: no range limit and no crossing produce no dry point at all', () => {
const noLimit = deriveDriveWarnings(
[drive(60, 900)],
[false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: null },
0,
);
expect(noLimit.emptyAt).toEqual([]);
const withinRange = deriveDriveWarnings(
[drive(60, 100)],
[false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 300 },
0,
);
expect(withinRange.emptyAt).toEqual([]);
});
it('FE-ROADTRIP-MODEL-095: an unrouted leg gives the tank up rather than guessing where it ends', () => {
// The budget goes null and stays null, so there is no honest dry point to offer.
const out = deriveDriveWarnings(
[drive(60, 200), undefined, drive(60, 400)],
[false, false, false, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 300 },
0,
);
expect(out.emptyAt).toEqual([]);
expect(out.carryKm).toBeNull();
});
});
describe('refuelsRange — what fills which tank', () => {
it('FE-ROADTRIP-MODEL-096: with no vehicle named, either kind fills up', () => {
// What TREK did before the setting existed, and the right answer for somebody who
// never opened the dialog. Anything else would quietly change their warnings.
expect(refuelsRange('fuel')).toBe(true);
expect(refuelsRange('charging')).toBe(true);
expect(refuelsRange('fuel', null)).toBe(true);
expect(refuelsRange('charging', null)).toBe(true);
});
it('FE-ROADTRIP-MODEL-097: a petrol station does not charge a battery', () => {
// The bug this exists for: an electric car pausing at a petrol station had its
// battery refilled on paper, the warnings went quiet for the rest of the day, and
// the driver was told nothing.
expect(refuelsRange('charging', 'electric')).toBe(true);
expect(refuelsRange('fuel', 'electric')).toBe(false);
});
it('FE-ROADTRIP-MODEL-098: and a charger does not fill a tank', () => {
expect(refuelsRange('fuel', 'combustion')).toBe(true);
expect(refuelsRange('charging', 'combustion')).toBe(false);
});
it('FE-ROADTRIP-MODEL-099: nothing else refuels anything, whatever is driven', () => {
for (const vehicle of [null, 'combustion', 'electric'] as const) {
expect(refuelsRange('rest_area', vehicle)).toBe(false);
expect(refuelsRange('restaurant', vehicle)).toBe(false);
expect(refuelsRange(null, vehicle)).toBe(false);
}
});
it('FE-ROADTRIP-MODEL-100: the search looks for what the vehicle actually takes', () => {
expect(refuelStopTypeFor('combustion')).toEqual(['fuel']);
expect(refuelStopTypeFor('electric')).toEqual(['charging']);
expect(refuelStopTypeFor(null)).toEqual(['fuel', 'charging']);
});
});
describe('deriveDriveWarnings — filling only part way', () => {
const drive = (minutes: number, km: number) => ({ duration: minutes * 60, distance: km * 1000, mode: 'driving' });
it('FE-ROADTRIP-MODEL-101: a stop that fills to 80 % leaves a fifth already used', () => {
// Nobody charges to 100 % on the road: the last fifth takes as long as the first
// four. Counting a stop as a full tank overstates what comes after it by that fifth.
const out = deriveDriveWarnings(
[drive(60, 100), drive(60, 450)],
[false, true, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 500, fillPercent: 80 },
0,
);
// After the stop the budget restarts at 100 km rather than 0, so the tank is dry
// 400 km into the second leg. Filled all the way it would have gone the whole 450.
expect(out.emptyAt).toHaveLength(1);
expect(out.emptyAt[0]!).toMatchObject({ legIndex: 1, intoLegKm: 400 });
});
it('FE-ROADTRIP-MODEL-102: filling all the way is what absent, zero and 100 all mean', () => {
const legs = [drive(60, 100), drive(60, 450)];
const refuels = [false, true, false];
const full = { legMinutes: null, dayMinutes: null, rangeKm: 500 };
for (const fillPercent of [undefined, null, 0, 100]) {
const out = deriveDriveWarnings(legs, refuels, { ...full, fillPercent }, 0);
// A full tank after the stop covers the remaining 450 km without a finding.
expect(out.emptyAt).toEqual([]);
expect(out.warnings).toEqual([]);
}
});
it('FE-ROADTRIP-MODEL-103: with no range set, the fill level changes nothing', () => {
const out = deriveDriveWarnings(
[drive(60, 900)],
[true, false],
{ legMinutes: null, dayMinutes: null, rangeKm: null, fillPercent: 50 },
0,
);
expect(out.warnings).toEqual([]);
expect(out.emptyAt).toEqual([]);
});
it('FE-ROADTRIP-MODEL-104: a stop that says how full it fills is read against itself', () => {
// The motorway charger tops up to 60 %; the traveller's own default is 80. Reading
// the default here would promise 100 km the car does not have.
const out = deriveDriveWarnings(
[drive(60, 100), drive(60, 450)],
[false, true, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 500, fillPercent: 80 },
0,
[null, 60, null],
);
// 60 % of 500 km is 300, so the tank is dry 300 km into the second leg rather than
// the 400 the traveller's own figure would have given.
expect(out.emptyAt).toHaveLength(1);
expect(out.emptyAt[0]!).toMatchObject({ legIndex: 1, intoLegKm: 300 });
});
it('FE-ROADTRIP-MODEL-105: a stop with no opinion still follows the traveller', () => {
// Same day, same stop, nothing said about it: the default has to keep applying, or
// adding the field would have quietly changed every trip that never used it.
const out = deriveDriveWarnings(
[drive(60, 100), drive(60, 450)],
[false, true, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 500, fillPercent: 80 },
0,
[null, null, null],
);
expect(out.emptyAt[0]!).toMatchObject({ legIndex: 1, intoLegKm: 400 });
});
it('FE-ROADTRIP-MODEL-106: a stop can also say it fills right up', () => {
// The charger at the hotel: the car stands there all night, so this one goes to 100
// even on a trip whose default stops at 80.
const out = deriveDriveWarnings(
[drive(60, 100), drive(60, 450)],
[false, true, false],
{ legMinutes: null, dayMinutes: null, rangeKm: 500, fillPercent: 80 },
0,
[null, 100, null],
);
expect(out.emptyAt).toEqual([]);
});
});
+448
View File
@@ -0,0 +1,448 @@
import type { RouteAvoidClass } from './planning-types';
export const SERVICE_STOP_TYPES = ['fuel', 'charging', 'rest_area', 'campsite', 'restaurant', 'sights'] as const;
export const SERVICE_COLORS: Record<string, string> = {
fuel: '#E8590C',
charging: '#CA8A04',
rest_area: '#3B82F6',
campsite: '#16A34A',
restaurant: '#EF4444',
sights: '#EC4899',
};
export function serviceColor(stopType: string | null | undefined): string {
return SERVICE_COLORS[stopType ?? ''] ?? '#64748B';
}
export function isServiceStopType(stopType: string | null | undefined): boolean {
return !!stopType && (SERVICE_STOP_TYPES as readonly string[]).includes(stopType);
}
export function formatDurationShort(seconds: number): string {
const safe = Number.isFinite(seconds) && seconds > 0 ? seconds : 0;
const h = Math.floor(safe / 3600);
const m = Math.round((safe % 3600) / 60);
if (m === 60) return `${h + 1} h`;
if (h > 0) return m > 0 ? `${h} h ${m} min` : `${h} h`;
return `${m} min`;
}
export function parseClock(value: string | null | undefined): number | null {
if (!value) return null;
const m = /^(\d{1,2}):(\d{2})/.exec(value.trim());
if (!m) return null;
const h = Number(m[1]);
const min = Number(m[2]);
if (h > 23 || min > 59) return null;
return h * 60 + min;
}
export function formatClock(minutes: number): string {
const day = 24 * 60;
const wrapped = ((minutes % day) + day) % day;
const h = Math.floor(wrapped / 60);
const m = Math.round(wrapped % 60);
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
}
export interface ScheduleStop {
anchor: string | null;
dwellMinutes: number | null;
}
export interface ScheduleWarning {
index: number;
code: 'late' | 'overnight' | 'leg' | 'range';
minutes?: number;
overMinutes?: number;
sinceKm?: number;
}
export const REFUELLING_STOP_TYPES = ['fuel', 'charging'] as const;
export type VehicleKind = 'combustion' | 'electric';
export function refuelStopTypeFor(vehicle: VehicleKind | null | undefined): readonly string[] {
if (vehicle === 'combustion') return ['fuel'];
if (vehicle === 'electric') return ['charging'];
return REFUELLING_STOP_TYPES;
}
export function refuelsRange(stopType: string | null | undefined, vehicle?: VehicleKind | null): boolean {
return refuelStopTypeFor(vehicle).includes(stopType ?? '');
}
export interface DriveLimits {
fillPercent?: number | null;
legMinutes: number | null;
dayMinutes: number | null;
rangeKm: number | null;
}
export interface DayWarning {
code: 'dayDriving';
minutes: number;
limitMinutes: number;
}
export interface ScheduleEntry {
arrival: string | null;
departure: string | null;
anchored: boolean;
dayOffset: number;
}
export interface Schedule {
entries: ScheduleEntry[];
warnings: ScheduleWarning[];
}
const DAY_MINUTES = 24 * 60;
function resolveArrival(
anchor: number | null,
cursor: number | null,
dayOffset: number,
): { arrival: number | null; lateBy: number | null } {
if (anchor === null) return { arrival: cursor, lateBy: null };
if (cursor === null) return { arrival: anchor + dayOffset * DAY_MINUTES, lateBy: null };
const k = Math.round((cursor - anchor) / DAY_MINUTES);
const anchorAt = anchor + k * DAY_MINUTES;
return {
arrival: anchorAt,
lateBy: cursor > anchorAt + 1 ? Math.round(cursor - anchorAt) : null,
};
}
export function computeSchedule(stops: ScheduleStop[], legSeconds: (number | undefined)[]): Schedule {
const warnings: ScheduleWarning[] = [];
const arrivals: (number | null)[] = new Array(stops.length).fill(null);
const anchored: boolean[] = new Array(stops.length).fill(false);
let cursor: number | null = null;
let dayOffset = 0;
for (let i = 0; i < stops.length; i++) {
const stop = stops[i]!;
const anchor = parseClock(stop.anchor);
const { arrival, lateBy } = resolveArrival(anchor, cursor, dayOffset);
if (lateBy !== null) warnings.push({ index: i, code: 'late', minutes: lateBy });
if (arrival === null) continue;
const offset = Math.floor(arrival / DAY_MINUTES);
if (offset > dayOffset) dayOffset = offset;
arrivals[i]! = arrival;
anchored[i]! = anchor !== null;
const leg = legSeconds[i];
cursor = leg === undefined ? null : arrival + (stop.dwellMinutes ?? 0) + Math.round(leg / 60);
}
const firstKnown = arrivals.findIndex((a) => a !== null);
for (let i = firstKnown - 1; i >= 0; i--) {
const leg = legSeconds[i];
const next = arrivals[i + 1]!;
if (leg === undefined || next === null) break;
arrivals[i]! = next - Math.round(leg / 60) - (stops[i]!.dwellMinutes ?? 0);
}
const earliest = arrivals.reduce<number | null>((m, a) => (a === null ? m : m === null || a < m ? a : m), null);
const shift = earliest === null || earliest >= 0 ? 0 : -Math.floor(earliest / DAY_MINUTES) * DAY_MINUTES;
const entries: ScheduleEntry[] = [];
let lastOffset = 0;
for (let i = 0; i < stops.length; i++) {
const raw = arrivals[i]!;
if (raw === null) {
entries.push({ arrival: null, departure: null, anchored: false, dayOffset: 0 });
continue;
}
const arrival = raw + shift;
const offset = Math.floor(arrival / DAY_MINUTES);
if (offset > lastOffset) warnings.push({ index: i, code: 'overnight' });
lastOffset = offset;
entries.push({
arrival: formatClock(arrival),
departure: formatClock(arrival + (stops[i]!.dwellMinutes ?? 0)),
anchored: anchored[i]!,
dayOffset: offset,
});
}
return { entries, warnings };
}
export function splitIntoRuns<T>(stops: T[], modeOfLeg: (from: T, to: T) => string): { stops: T[]; mode: string }[] {
const runs: { stops: T[]; mode: string }[] = [];
let current: T[] = [];
let currentMode: string | null = null;
for (let i = 0; i < stops.length - 1; i++) {
const mode = modeOfLeg(stops[i]!, stops[i + 1]!);
if (currentMode === null) {
current = [stops[i]!, stops[i + 1]!];
currentMode = mode;
} else if (mode === currentMode) {
current.push(stops[i + 1]!);
} else {
runs.push({ stops: current, mode: currentMode });
current = [stops[i]!, stops[i + 1]!];
currentMode = mode;
}
}
if (currentMode !== null && current.length > 1) runs.push({ stops: current, mode: currentMode });
return runs;
}
export function sumLegSeconds(legSeconds: (number | undefined)[]): number {
return legSeconds.reduce<number>((sum, s) => sum + (s ?? 0), 0);
}
export interface DryPoint {
legIndex: number;
intoLegKm: number;
drivenMeters: number;
sinceKm: number;
}
export function deriveDriveWarnings(
legs: ({ duration?: number; distance?: number; mode?: string } | undefined)[],
refuelsAt: boolean[],
limits: DriveLimits,
carryKm: number | null,
fillAt: readonly (number | null | undefined)[] = [],
): { warnings: ScheduleWarning[]; day: DayWarning | null; carryKm: number | null; emptyAt: DryPoint[] } {
const warnings: ScheduleWarning[] = [];
const emptyAt: DryPoint[] = [];
let budget = carryKm;
let totalSeconds = 0;
let drivenMeters = 0;
const usedAfterFilling = (i: number): number => {
const percent = fillAt[i] ?? limits.fillPercent;
return limits.rangeKm && percent && percent > 0 && percent < 100 ? limits.rangeKm * (1 - percent / 100) : 0;
};
for (let i = 0; i < legs.length; i++) {
if (refuelsAt[i]!) budget = usedAfterFilling(i);
const leg = legs[i];
const at = i + 1;
if (leg && leg.mode !== undefined && leg.mode !== 'driving') continue;
const seconds = leg?.duration;
if (typeof seconds === 'number') {
totalSeconds += seconds;
if (limits.legMinutes && seconds / 60 > limits.legMinutes) {
warnings.push({ index: at, code: 'leg', overMinutes: Math.round(seconds / 60 - limits.legMinutes) });
}
}
const metres = leg?.distance;
if (typeof metres !== 'number') {
budget = null;
} else if (budget !== null) {
const before = budget;
budget += metres / 1000;
if (limits.rangeKm && before <= limits.rangeKm && budget > limits.rangeKm) {
const intoLegKm = limits.rangeKm - before;
emptyAt.push({
legIndex: i,
intoLegKm,
drivenMeters: drivenMeters + intoLegKm * 1000,
sinceKm: Math.round(limits.rangeKm),
});
}
if (limits.rangeKm && budget > limits.rangeKm && !refuelsAt[at]!) {
warnings.push({ index: at, code: 'range', sinceKm: Math.round(budget) });
}
drivenMeters += metres;
}
}
if (refuelsAt[legs.length]!) budget = usedAfterFilling(legs.length);
const minutes = Math.round(totalSeconds / 60);
const day =
limits.dayMinutes && minutes > limits.dayMinutes
? { code: 'dayDriving' as const, minutes, limitMinutes: limits.dayMinutes }
: null;
return { warnings, day, carryKm: budget, emptyAt };
}
export function legIndexForAlong(legEndMeters: number[], alongMeters: number): number {
if (!legEndMeters.length) return -1;
for (let i = 0; i < legEndMeters.length; i++) {
if (alongMeters < legEndMeters[i]!) return i;
}
return legEndMeters.length - 1;
}
export interface SectionAnchor {
kind: 'stop' | 'leg';
index: number;
alongKm: number;
}
export function sectionAnchors(stopsAlongKm: number[]): SectionAnchor[] {
const out: SectionAnchor[] = [];
for (let i = 0; i < stopsAlongKm.length; i++) {
out.push({ kind: 'stop', index: i, alongKm: stopsAlongKm[i]! });
if (i + 1 < stopsAlongKm.length) {
out.push({ kind: 'leg', index: i, alongKm: (stopsAlongKm[i]! + stopsAlongKm[i + 1]!) / 2 });
}
}
return out;
}
export function insertIndexForAlong(stopsAlongKm: number[], hitAlongKm: number): number {
if (stopsAlongKm.length < 2) return stopsAlongKm.length;
let i = 0;
while (i < stopsAlongKm.length && stopsAlongKm[i]! <= hitAlongKm) i++;
return Math.min(Math.max(i, 1), stopsAlongKm.length - 1);
}
export interface AnchoredVia {
id: number;
after_order_index: number;
lat: number;
lng: number;
}
export interface ReanchoredVia {
id: number;
after_order_index: number;
}
export interface Reanchoring {
vias: ReanchoredVia[];
remove: number[];
}
const EMPTY_REANCHORING: Reanchoring = { vias: [], remove: [] };
function collect(vias: AnchoredVia[], at: (index: number) => number | null): Reanchoring {
const moved: ReanchoredVia[] = [];
const remove: number[] = [];
for (const via of vias) {
const next = at(via.after_order_index);
if (next === null) remove.push(via.id);
else if (next !== via.after_order_index) moved.push({ id: via.id, after_order_index: next });
}
return { vias: moved, remove };
}
export function reanchorAfterInsert(
vias: AnchoredVia[],
position: number,
liesBeforeInsert: (via: AnchoredVia) => boolean,
): Reanchoring {
if (!vias.length) return EMPTY_REANCHORING;
const split = position - 1;
const moved: ReanchoredVia[] = [];
for (const via of vias) {
const i = via.after_order_index;
let next = i;
if (i === split) next = liesBeforeInsert(via) ? i : i + 1;
else if (i >= position) next = i + 1;
if (next !== i) moved.push({ id: via.id, after_order_index: next });
}
return { vias: moved, remove: [] };
}
export function reanchorAfterRemove(vias: AnchoredVia[], position: number, stopCount: number): Reanchoring {
if (!vias.length) return EMPTY_REANCHORING;
if (stopCount <= 2) return { vias: [], remove: vias.map((v) => v.id) };
return collect(vias, (i) => {
if (position === 0) return i === 0 ? null : i - 1;
if (position === stopCount - 1) return i === position - 1 ? null : i;
if (i === position) return position - 1;
return i > position ? i - 1 : i;
});
}
export function reanchorByStopOrder(vias: AnchoredVia[], previousIds: number[], nextIds: number[]): Reanchoring {
if (!vias.length) return EMPTY_REANCHORING;
const moved: ReanchoredVia[] = [];
const remove: number[] = [];
for (const via of vias) {
const stopId = previousIds[via.after_order_index]!;
const next = stopId === undefined ? -1 : nextIds.indexOf(stopId);
if (next === -1 || next >= nextIds.length - 1) {
remove.push(via.id);
continue;
}
if (next !== via.after_order_index) moved.push({ id: via.id, after_order_index: next });
}
return { vias: moved, remove };
}
export function reanchorAfterReorder(vias: AnchoredVia[], from: number, to: number, stopCount: number): Reanchoring {
if (!vias.length || from === to) return EMPTY_REANCHORING;
if (stopCount <= 2) return EMPTY_REANCHORING;
const afterRemove = reanchorAfterRemove(vias, from, stopCount);
const dropped = new Set(afterRemove.remove);
const movedTo = new Map(afterRemove.vias.map((v) => [v.id, v.after_order_index] as const));
const shifted: AnchoredVia[] = vias
.filter((v) => !dropped.has(v.id))
.map((v) => ({ ...v, after_order_index: movedTo.get(v.id) ?? v.after_order_index }));
const afterInsert = reanchorAfterInsert(shifted, to, () => true);
const finalIndex = new Map(afterInsert.vias.map((v) => [v.id, v.after_order_index] as const));
const result: ReanchoredVia[] = [];
for (const via of vias) {
if (dropped.has(via.id)) continue;
const mid = movedTo.get(via.id) ?? via.after_order_index;
const end = finalIndex.get(via.id) ?? mid;
if (end !== via.after_order_index) result.push({ id: via.id, after_order_index: end });
}
return { vias: result, remove: afterRemove.remove };
}
export function isEmptyReanchoring(r: Reanchoring): boolean {
return r.vias.length === 0 && r.remove.length === 0;
}
export function parseAvoid(raw: unknown): RouteAvoidClass[] {
if (typeof raw !== 'string' || !raw.trim()) return [];
const asked = new Set(raw.split(',').map((part) => part.trim().toLowerCase()));
return AVOIDABLE.filter((cls) => asked.has(cls));
}
export const AVOIDABLE: readonly RouteAvoidClass[] = ['toll', 'motorway', 'ferry'];
export function serializeAvoid(classes: readonly RouteAvoidClass[]): string {
return AVOIDABLE.filter((cls) => classes.includes(cls)).join(',');
}
+53
View File
@@ -0,0 +1,53 @@
import { lineMetres, sliceAtMeters, projectOntoRoute } from './corridor';
import type { RoadtripStop, RouteSegment, RouteVia, RoutedLeg } from './planning-types';
import { legIndexForAlong } from './roadtripModel';
export const roadtripStopKey = (stop: RoadtripStop): string =>
`${stop.lat.toFixed(5)},${stop.lng.toFixed(5)},${stop.legMode ?? ''},${stop.incomingLegMode ?? ''}`;
export const roadtripLegKey = (from: RoadtripStop, to: RoadtripStop): string =>
`${roadtripStopKey(from)}>${roadtripStopKey(to)}`;
export function foldRouteRun(
stops: RoadtripStop[],
stopAt: number[],
route: { coordinates: [number, number][]; legs: RouteSegment[]; vias?: RouteVia[] },
mode: string,
): Record<string, RoutedLeg> {
const spine = route.coordinates.map(([lat, lng]) => ({ lat, lng }));
const cuts: { key: string; from: number; to: number; seg: RouteSegment }[] = [];
let travelled = 0;
for (let index = 0; index < stops.length - 1; index++) {
const parts = route.legs.slice(stopAt[index], stopAt[index + 1]);
if (!parts.length) continue;
const merged =
parts.length === 1
? parts[0]!
: {
...parts[0]!,
distance: parts.reduce((sum, leg) => sum + leg.distance, 0),
duration: parts.reduce((sum, leg) => sum + leg.duration, 0),
};
const from = travelled;
travelled += merged.distance;
cuts.push({ key: roadtripLegKey(stops[index]!, stops[index + 1]!), from, to: travelled, seg: { ...merged, mode } });
}
const scale = travelled > 0 ? lineMetres(spine) / travelled : 0;
const legs: Record<string, RoutedLeg> = {};
for (const cut of cuts)
legs[cut.key] = {
seg: cut.seg,
line: sliceAtMeters(spine, cut.from * scale, cut.to * scale).map((p) => [p.lat, p.lng]),
vias: [],
};
for (const via of route.vias ?? []) {
if (!via.label && via.dwellSeconds == null) continue;
const along = (projectOntoRoute(via, spine)?.alongKm ?? 0) * 1000;
const index = legIndexForAlong(
cuts.map((cut) => cut.to),
along,
);
const cut = cuts[index];
if (cut) legs[cut.key]!.vias.push(via);
}
return legs;
}
+32
View File
@@ -0,0 +1,32 @@
import type { DistanceUnit } from './planning-types';
const KM_TO_MI = 0.621371;
const M_TO_FT = 3.28084;
export function getDistanceUnitLabel(unit: DistanceUnit): 'km' | 'mi' {
return unit === 'imperial' ? 'mi' : 'km';
}
export function formatElevation(meters: number, unit: DistanceUnit): string {
const safe = Number.isFinite(meters) ? meters : 0;
return unit === 'imperial' ? `${Math.round(safe * M_TO_FT)} ft` : `${Math.round(safe)} m`;
}
export function convertDistance(km: number, unit: DistanceUnit): number {
const safeKm = Number.isFinite(km) ? Math.max(0, km) : 0;
return unit === 'imperial' ? safeKm * KM_TO_MI : safeKm;
}
export function formatDistance(km: number, unit: DistanceUnit): string {
const safeKm = Number.isFinite(km) ? Math.max(0, km) : 0;
if (unit === 'metric' && safeKm < 1) {
return `${Math.round(safeKm * 1000)} m`;
}
const value = convertDistance(safeKm, unit);
const label = getDistanceUnitLabel(unit);
const rounded = Math.round(value * 10) / 10;
const text = value > 0 && rounded === 0 ? '<0.1' : String(rounded);
return `${text} ${label}`;
}
+130
View File
@@ -0,0 +1,130 @@
import { rangeFromSpec, effectiveRangeKm, showSpec, storeSpec, specUnit } from './vehicleRange';
import { describe, it, expect } from 'vitest';
/**
* FE-ROADTRIP-VEHRANGE-001..013 — a range stated as the parts it is made of.
*
* Two things are worth guarding here. The arithmetic itself, because it decides where
* every fuel warning lands, and the unit round trip, because an imperial traveller who
* types 15 into a field labelled gallons must not end up with 15 litres in storage.
*/
describe('rangeFromSpec', () => {
it('FE-ROADTRIP-VEHRANGE-001: a tank divided by a consumption is a range', () => {
expect(rangeFromSpec('combustion', { tankLitres: 55, litresPer100: 7 })).toBe(786);
});
it('FE-ROADTRIP-VEHRANGE-002: a battery divided by a consumption is a range', () => {
expect(rangeFromSpec('electric', { batteryKwh: 58, kwhPer100: 16 })).toBe(363);
});
it('FE-ROADTRIP-VEHRANGE-003: age comes off the battery before the division', () => {
// 58 kWh minus a tenth is 52.2, and 52.2 at 16 per hundred is 326.25 km.
expect(rangeFromSpec('electric', { batteryKwh: 58, kwhPer100: 16, degradationPercent: 10 })).toBe(326);
});
it('FE-ROADTRIP-VEHRANGE-004: half a pair is not a range', () => {
// Guessing the missing half would put the warnings at the wrong place while
// looking exact, which is worse than saying nothing.
expect(rangeFromSpec('combustion', { tankLitres: 55 })).toBeNull();
expect(rangeFromSpec('combustion', { litresPer100: 7 })).toBeNull();
expect(rangeFromSpec('electric', { batteryKwh: 58 })).toBeNull();
});
it('FE-ROADTRIP-VEHRANGE-005: figures belong to the kind of car they came from', () => {
// A tank size on an electric car is a leftover from before the picker changed,
// not a battery.
expect(rangeFromSpec('electric', { tankLitres: 55, litresPer100: 7 })).toBeNull();
expect(rangeFromSpec('combustion', { batteryKwh: 58, kwhPer100: 16 })).toBeNull();
expect(rangeFromSpec(null, { tankLitres: 55, litresPer100: 7 })).toBeNull();
});
it('FE-ROADTRIP-VEHRANGE-006: a battery reported as entirely gone is a typo, not a car', () => {
// Capped at 90 %, because zero usable capacity would put the dry point at the
// first metre of the trip and divide by nothing.
expect(rangeFromSpec('electric', { batteryKwh: 58, kwhPer100: 16, degradationPercent: 100 })).toBe(36);
});
it('FE-ROADTRIP-VEHRANGE-007: nonsense in a field is the same as an empty field', () => {
expect(rangeFromSpec('combustion', { tankLitres: 0, litresPer100: 7 })).toBeNull();
expect(rangeFromSpec('combustion', { tankLitres: -55, litresPer100: 7 })).toBeNull();
expect(rangeFromSpec('combustion', { tankLitres: Number.NaN, litresPer100: 7 })).toBeNull();
});
});
describe('effectiveRangeKm', () => {
it('FE-ROADTRIP-VEHRANGE-008: the parts win over a typed round number', () => {
// Somebody who gave a tank size and a consumption said something more exact
// than "about 500", and the dialog shows them the result.
expect(effectiveRangeKm('combustion', { tankLitres: 55, litresPer100: 7 }, 500)).toBe(786);
});
it('FE-ROADTRIP-VEHRANGE-009: an incomplete pair hands the typed number straight back', () => {
expect(effectiveRangeKm('combustion', { tankLitres: 55 }, 500)).toBe(500);
expect(effectiveRangeKm(null, {}, 500)).toBe(500);
});
it('FE-ROADTRIP-VEHRANGE-010: no figures anywhere is no limit', () => {
expect(effectiveRangeKm(null, {}, 0)).toBeNull();
expect(effectiveRangeKm('electric', {}, undefined)).toBeNull();
});
});
describe('unit round trip', () => {
it('FE-ROADTRIP-VEHRANGE-011: metric figures are stored exactly as typed', () => {
expect(storeSpec('tankLitres', 55, false)).toBe(55);
expect(showSpec('tankLitres', 55, false)).toBe(55);
expect(showSpec('litresPer100', 7.4, false)).toBe(7.4);
});
it('FE-ROADTRIP-VEHRANGE-012: gallons go in and come back out as the same gallons', () => {
// 15 US gallons is 56.78 litres, and storage is litres — the same rule the
// range itself follows, where storage is always kilometres.
const stored = storeSpec('tankLitres', 15, true);
expect(stored).toBe(56.78);
expect(showSpec('tankLitres', stored, true)).toBe(15);
});
it('FE-ROADTRIP-VEHRANGE-013: miles per gallon is the inverse, and survives the trip', () => {
// The one field that is not a scale factor: 30 mpg is 7.84 L/100 km, and a
// straight multiplication would have stored a car four times as thirsty.
const stored = storeSpec('litresPer100', 30, true);
expect(stored).toBe(7.84);
expect(showSpec('litresPer100', stored, true)).toBe(30);
expect(specUnit('litresPer100', true)).toBe('mpg');
expect(specUnit('litresPer100', false)).toBe('L/100 km');
});
it('FE-ROADTRIP-VEHRANGE-014: electric consumption is quoted per 100 miles', () => {
// What the EPA prints on the window sticker, so the figure is one a US
// traveller can copy rather than convert.
expect(showSpec('kwhPer100', 16, true)).toBe(25.7);
expect(specUnit('kwhPer100', true)).toBe('kWh/100 mi');
// A capacity is a capacity everywhere.
expect(specUnit('batteryKwh', true)).toBe('kWh');
expect(showSpec('batteryKwh', 58, true)).toBe(58);
});
it('FE-ROADTRIP-VEHRANGE-016: a consumption typed a hundred times too high does not silence the typed range', () => {
// A consumption of 500 rather than 5.0 makes the parts round to nothing. Zero used
// to count as an answer, so the `??` in effectiveRangeKm never reached the 500 km
// the traveller had typed by hand, and every range warning went quiet with nothing
// on screen to say which field did it.
expect(rangeFromSpec('combustion', { tankLitres: 1, litresPer100: 500 })).toBeNull();
expect(effectiveRangeKm('combustion', { tankLitres: 1, litresPer100: 500 }, 500)).toBe(500);
// Same shape on the other kind of car, where a decimal point is just as easy to lose.
expect(rangeFromSpec('electric', { batteryKwh: 0.5, kwhPer100: 200 })).toBeNull();
expect(effectiveRangeKm('electric', { batteryKwh: 0.5, kwhPer100: 200 }, 420)).toBe(420);
// One kilometre is still a figure, so the cut is below it and not at some round guess.
expect(rangeFromSpec('combustion', { tankLitres: 1, litresPer100: 100 })).toBe(1);
});
it('FE-ROADTRIP-VEHRANGE-015: an empty field stays empty rather than becoming a zero', () => {
expect(showSpec('tankLitres', undefined, false)).toBeUndefined();
expect(showSpec('tankLitres', 0, true)).toBeUndefined();
expect(storeSpec('tankLitres', 0, true)).toBe(0);
});
});
+110
View File
@@ -0,0 +1,110 @@
import type { VehicleKind } from './roadtripModel';
export interface VehicleSpec {
tankLitres?: number | null;
litresPer100?: number | null;
batteryKwh?: number | null;
kwhPer100?: number | null;
degradationPercent?: number | null;
}
function positive(value: number | null | undefined): number | null {
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;
}
function atLeastAKilometre(km: number): number | null {
return km >= 1 ? km : null;
}
export function rangeFromSpec(vehicle: VehicleKind | null | undefined, spec: VehicleSpec): number | null {
if (vehicle === 'combustion') {
const tank = positive(spec.tankLitres);
const per100 = positive(spec.litresPer100);
if (!tank || !per100) return null;
return atLeastAKilometre(Math.round((tank / per100) * 100));
}
if (vehicle === 'electric') {
const battery = positive(spec.batteryKwh);
const per100 = positive(spec.kwhPer100);
if (!battery || !per100) return null;
const lost = Math.min(90, Math.max(0, positive(spec.degradationPercent) ?? 0));
const usable = battery * (1 - lost / 100);
return atLeastAKilometre(Math.round((usable / per100) * 100));
}
return null;
}
export function effectiveRangeKm(
vehicle: VehicleKind | null | undefined,
spec: VehicleSpec,
typedKm: number | null | undefined,
): number | null {
return rangeFromSpec(vehicle, spec) ?? positive(typedKm);
}
export type SpecKey = keyof VehicleSpec;
const LITRES_PER_GALLON = 3.785411784;
const MPG_PRODUCT = 235.214583;
const KM_PER_MILE = 1.609344;
export function specUnit(key: SpecKey, imperial: boolean): string {
switch (key) {
case 'tankLitres':
return imperial ? 'gal' : 'L';
case 'litresPer100':
return imperial ? 'mpg' : 'L/100 km';
case 'batteryKwh':
return 'kWh';
case 'kwhPer100':
return imperial ? 'kWh/100 mi' : 'kWh/100 km';
default:
return '%';
}
}
function places(key: SpecKey, imperial: boolean): number {
if (key === 'degradationPercent') return 0;
if (key === 'tankLitres') return imperial ? 1 : 0;
if (key === 'litresPer100') return imperial ? 0 : 1;
return 1;
}
function convert(key: SpecKey, value: number, imperial: boolean, toStorage: boolean): number {
if (!imperial) return value;
switch (key) {
case 'tankLitres':
return toStorage ? value * LITRES_PER_GALLON : value / LITRES_PER_GALLON;
case 'litresPer100':
return MPG_PRODUCT / value;
case 'kwhPer100':
return toStorage ? value / KM_PER_MILE : value * KM_PER_MILE;
default:
return value;
}
}
function round(value: number, decimals: number): number {
const f = 10 ** decimals;
return Math.round(value * f) / f;
}
export function showSpec(key: SpecKey, stored: number | null | undefined, imperial: boolean): number | undefined {
const value = positive(stored);
if (value === null) return undefined;
return round(convert(key, value, imperial, false), places(key, imperial));
}
export function storeSpec(key: SpecKey, shown: number, imperial: boolean): number {
if (!(shown > 0)) return 0;
return round(convert(key, shown, imperial, true), 2);
}