fix(tours): keep a city walk on foot across the water, mark a crossing by boat apart from the walking time and save it only once taken

This commit is contained in:
Maurice
2026-10-21 13:16:43 +02:00
parent 41f3267503
commit 6e13f7e655
72 changed files with 2312 additions and 109 deletions
+41
View File
@@ -202,6 +202,47 @@ describe('Tours fixed legs', () => {
});
});
describe('Tours ferry legs (CW-12)', () => {
const ferry = (crossing: [number, number], minutes: number | null = 7) => ({
kind: 'ferry' as const,
geometry: [
[48, 11],
[48.004, 11.008],
[48.006, 11.012],
[48.01, 11.02],
] as [number, number][],
crossing,
minutes,
walk_minutes: 2,
});
const withLeg = (leg: ReturnType<typeof ferry>, type: 'walk' | 'hike') => ({
...baseRequest,
tour_type: type,
...(type === 'walk' ? { max_hiking_difficulty: null } : {}),
waypoints: [
{ lat: 48, lng: 11, role: 'start' as const, sequence: 0, fixed_leg: leg },
{ lat: 48.01, lng: 11.02, role: 'end' as const, sequence: 1 },
],
});
it('takes a crossing by boat on a city walk, with where on its leg the boat runs and its minutes apart', () => {
expect(tourCreateRequestSchema.parse(withLeg(ferry([1, 2]), 'walk')).waypoints[0]?.fixed_leg).toEqual(
ferry([1, 2]),
);
expect(tourCreateRequestSchema.parse(withLeg(ferry([1, 2], null), 'walk')).waypoints[0]?.fixed_leg).toMatchObject({
minutes: null,
});
});
it('refuses a crossing on any other type, or one that does not run forwards between two points of its leg', () => {
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([1, 2]), 'hike'))).toThrow(
/ferry leg belongs to a city walk/,
);
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([2, 1]), 'walk'))).toThrow(/crossing runs between/);
expect(() => tourCreateRequestSchema.parse(withLeg(ferry([1, 4]), 'walk'))).toThrow(/crossing runs between/);
});
});
describe('Tours free legs', () => {
const free = (from: [number, number], to: [number, number]) => ({ kind: 'free' as const, geometry: [from, to] });
+26
View File
@@ -366,6 +366,9 @@ export const TOUR_FIXED_LEG_END_TOLERANCE_M = 60;
*/
export const TOUR_WRITE_MAX_BYTES = 2 * 1024 * 1024;
/** The longest a ferry leg's crossing or its walk may take, a whole day. */
const FERRY_LEG_MAX_MINUTES = 24 * 60;
const fixedLegGeometrySchema = z
.array(z.tuple([z.number().finite().min(-90).max(90), z.number().finite().min(-180).max(180)]))
.min(2)
@@ -383,6 +386,9 @@ const fixedLegGeometrySchema = z
* section (HOR-01) is a stretch of a signposted horse route from
* OpenStreetMap, taken in the direction the rider chose, with the `horse=*`
* tags its ways carried then; being on the route is no permission to ride it.
* A ferry leg (CW-12) is a city walk's crossing by boat the travellers took on
* purpose: the router's way from the station to the next, with where on it the
* boat runs, so the boat's time never counts as walking.
*/
export const tourFixedLegSchema = z.discriminatedUnion('kind', [
z.object({
@@ -416,6 +422,16 @@ export const tourFixedLegSchema = z.discriminatedUnion('kind', [
/** The `horse=*` tags along the section when it was taken, in metres per value. */
access: horseAccessSharesSchema.optional(),
}),
z.object({
kind: z.literal('ferry'),
geometry: fixedLegGeometrySchema,
/** The points of the line the boat leaves from and lands at, by their index. */
crossing: z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()]),
/** The crossing's time as the router gave it; null when it gave none. */
minutes: z.number().int().min(0).max(FERRY_LEG_MAX_MINUTES).nullable(),
/** The walk to the boat and on from it along this leg, by the router. */
walk_minutes: z.number().int().min(0).max(FERRY_LEG_MAX_MINUTES),
}),
]);
export type TourFixedLeg = z.infer<typeof tourFixedLegSchema>;
export type TourFixedLegKind = TourFixedLeg['kind'];
@@ -589,6 +605,13 @@ export const tourCreateRequestSchema = z
message: `Waypoint ${index}'s fixed leg must run from it to the next waypoint`,
});
}
if (leg.kind === 'ferry' && !(leg.crossing[0] < leg.crossing[1] && leg.crossing[1] < leg.geometry.length)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['waypoints', index, 'fixed_leg', 'crossing'],
message: 'a crossing runs between two points of its leg, the first before the second',
});
}
}
const expectedRole: TourWaypointRole =
index === 0 ? 'start' : index === value.waypoints.length - 1 ? 'end' : 'via';
@@ -731,6 +754,9 @@ function tourTypeIssues(value: {
kind === 'ferrata'
)
issues.push({ path: ['waypoints', index, 'fixed_leg'], message: `${named} has no via ferrata` });
// CW-12: a crossing by boat is taken on a city walk only, where the way on foot has none.
if (type !== 'walk' && kind === 'ferry')
issues.push({ path: ['waypoints', index, 'fixed_leg'], message: 'a ferry leg belongs to a city walk' });
if (type !== 'horse' && kind === 'horse_route')
issues.push({
path: ['waypoints', index, 'fixed_leg'],
+72
View File
@@ -0,0 +1,72 @@
import { boatSpansOf, ferryCrossingsOf } from './walk-ferry';
import { stationShares } from './walk-hours';
import { describe, expect, it } from 'vitest';
const line: Array<[number, number, number]> = [
[45.4296, 12.3264, 2],
[45.4291, 12.3266, 1],
[45.4275, 12.3282, 1],
[45.4268, 12.33, 2],
];
describe('ferry legs of a city walk (CW-12)', () => {
it('reads the boat part of each ferry leg, and nothing of any other leg', () => {
expect(
ferryCrossingsOf([
{
fixed_leg: {
kind: 'free',
geometry: [
[1, 1],
[2, 2],
],
},
},
{
fixed_leg: {
kind: 'ferry',
geometry: line.map(([lat, lng]): [number, number] => [lat, lng]),
crossing: [1, 2],
minutes: 7,
walk_minutes: 2,
},
},
{},
]),
).toEqual([
[
[45.4291, 12.3266],
[45.4275, 12.3282],
],
]);
});
it('finds each crossing on the saved line by its own points, and leaves out one it cannot find', () => {
const crossing: Array<[number, number]> = [
[45.4291, 12.3266],
[45.4275, 12.3282],
];
expect(boatSpansOf(line, [crossing])).toEqual([[1, 2]]);
expect(
boatSpansOf(line, [
[
[1, 1],
[2, 2],
],
]),
).toEqual([]);
});
it('counts no distance along a stretch crossed by boat when sharing a walk out', () => {
const stops = [
{ lat: 45.4296, lng: 12.3264 },
{ lat: 45.4275, lng: 12.3282 },
];
const walked = stationShares(stops, line)?.[1] ?? 0;
// The stop where the boat lands is passed after the walk to the pier only.
const byBoat = stationShares(stops, line, [[1, 2]])?.[1] ?? 0;
expect(byBoat).toBeLessThan(walked);
expect(stationShares(stops, line, [])).toEqual(stationShares(stops, line));
});
});
+50
View File
@@ -0,0 +1,50 @@
import type { TourFixedLeg } from './tours.schema';
type LinePoint = readonly [number, number, ...number[]];
/** Closer than this, in degrees, a point of the saved line is the point of a leg it was built from. */
const SAME_POINT_DEG = 1e-6;
/** CW-12: the boat part of each ferry leg of a city walk, in the order of the legs. */
export function ferryCrossingsOf(
points: ReadonlyArray<{ fixed_leg?: TourFixedLeg | null }>,
): Array<Array<[number, number]>> {
return points.flatMap((point) => {
const leg = point.fixed_leg;
if (leg?.kind !== 'ferry') return [];
return [leg.geometry.slice(leg.crossing[0], leg.crossing[1] + 1).map(([lat, lng]): [number, number] => [lat, lng])];
});
}
function indexOfPoint(line: ReadonlyArray<LinePoint>, point: readonly [number, number], from: number): number {
for (let index = from; index < line.length; index += 1) {
const at = line[index];
if (at && Math.abs(at[0] - point[0]) < SAME_POINT_DEG && Math.abs(at[1] - point[1]) < SAME_POINT_DEG) return index;
}
return -1;
}
/**
* Where on a walk's saved line its crossings by boat run, as the indices of the
* points the boat leaves from and lands at. The line was put together from the
* legs as they are, so each crossing is found by its own points in turn; one
* that cannot be found is left out rather than guessed.
*/
export function boatSpansOf(
line: ReadonlyArray<LinePoint>,
crossings: ReadonlyArray<ReadonlyArray<readonly [number, number]>>,
): Array<[number, number]> {
const spans: Array<[number, number]> = [];
let from = 0;
for (const crossing of crossings) {
const first = crossing[0];
const last = crossing[crossing.length - 1];
if (!first || !last || crossing.length < 2) continue;
const start = indexOfPoint(line, first, from);
const end = start < 0 ? -1 : indexOfPoint(line, last, start + 1);
if (end < 0) continue;
spans.push([start, end]);
from = end;
}
return spans;
}
+11 -3
View File
@@ -325,14 +325,22 @@ function passedAt(stops: readonly WalkStop[], flat: ReadonlyArray<[number, numbe
/**
* How far along the route each stop is passed, from 0 at its start to 1 at its
* end, by distance, the stops matched in their order as `passedAt` does. Null
* for a route of fewer than two points.
* for a route of fewer than two points. The stretches of `boatSpans` (CW-12,
* from the index the boat leaves at to the one it lands at) are crossed by
* boat and add no walking distance.
*/
export function stationShares(stops: readonly WalkStop[], route: readonly RoutePoint[]): number[] | null {
export function stationShares(
stops: readonly WalkStop[],
route: readonly RoutePoint[],
boatSpans: ReadonlyArray<readonly [number, number]> = [],
): number[] | null {
if (route.length < 2) return null;
const flat = flatRoute(route);
const byBoat = (i: number) => boatSpans.some(([from, to]) => i > from && i <= to);
const along = [0];
for (let i = 1; i < flat.length; i += 1) {
along.push((along[i - 1] ?? 0) + Math.sqrt(flatGap(flat[i] ?? [0, 0], flat[i - 1] ?? [0, 0])));
const step = byBoat(i) ? 0 : Math.sqrt(flatGap(flat[i] ?? [0, 0], flat[i - 1] ?? [0, 0]));
along.push((along[i - 1] ?? 0) + step);
}
const total = along[along.length - 1] || 1;
const indices = passedAt(stops, flat, Math.cos((route[0]?.[0] ?? 0) * RAD));
+12
View File
@@ -157,4 +157,16 @@ describe('walkRemainderOf (CW-13)', () => {
expect(noTime.open_stations[0]?.walk_minutes_from_reference).toBeNull();
expect(noTime.stays.remaining_known_minutes).toBe(20);
});
it('shares no walking time out along a crossing by boat (CW-12)', () => {
// The stretch from the Cathedral to the Market is crossed by boat: the walk is the other three stretches.
const stations = walk(['visited', 'planned', 'planned', 'planned', 'planned']);
const crossings = [[line[1], line[2]] as Array<[number, number]>];
const result = walkRemainderSchema.parse(walkRemainderOf({ stations, line, walkingMinutes: 60, crossings }));
expect(result.open_stations.map((station) => station.walk_minutes_from_reference)).toEqual([20, 20, 40, 60]);
// Without the crossing every stretch counts alike.
expect(remainder(stations, 60).open_stations.map((station) => station.walk_minutes_from_reference)).toEqual([
15, 30, 45, 60,
]);
});
});
+6 -2
View File
@@ -1,5 +1,6 @@
import type { WalkRemainder, WalkStationRef } from './tour-walk.schema';
import type { StationImportance } from './tours.schema';
import { boatSpansOf } from './walk-ferry';
import { stationShares, type WalkStop } from './walk-hours';
/** A station of a walk with its status on one day; planned is a station nobody checked off. */
@@ -16,6 +17,8 @@ export interface WalkRemainderInput {
/** The saved line; empty or null while the walk waits for its way. */
line: ReadonlyArray<readonly [number, number, ...number[]]> | null;
walkingMinutes: number | null;
/** CW-12: the boat part of each ferry leg the walk takes; no walking time is shared out along them. */
crossings?: ReadonlyArray<ReadonlyArray<readonly [number, number]>>;
}
function refOf(stations: readonly WalkRemainderStop[], index: number): WalkStationRef {
@@ -56,14 +59,15 @@ function gapOf({ stations, line, walkingMinutes }: WalkRemainderInput, ambiguous
* are open. A station skipped ahead keeps the line through it, so the time is
* an upper bound; a station planned before the last one visited leaves the
* progress unclear and the time unknown. Stays are counted apart, an unknown
* one listed rather than taken as nothing.
* one listed rather than taken as nothing. A crossing by boat (CW-12) is no
* walking and takes no share of the walking time.
*/
export function walkRemainderOf(input: WalkRemainderInput): WalkRemainder {
const { stations, line, walkingMinutes } = input;
const { last, openBefore } = progressOf(stations);
const ambiguous = openBefore.length > 0;
const gap = gapOf(input, ambiguous);
const shares = gap === null && line ? stationShares(stations, line) : null;
const shares = gap === null && line ? stationShares(stations, line, boatSpansOf(line, input.crossings ?? [])) : null;
const walking = walkingMinutes ?? 0;
const passed = (index: number) => Math.round(walking * (shares?.[index] ?? 0));
const fromReference = last < 0 ? 0 : passed(last);