Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(tours): tell a router that did not answer from a walk no way joins, count each boat of a leg on its own into the day and its arrivals

Maurice8a75712041d8
diff --git a/client/src/components/Map/valhallaRoute.test.ts b/client/src/components/Map/valhallaRoute.test.ts
index 635948f9f..a356929af 100644
--- a/client/src/components/Map/valhallaRoute.test.ts
+++ b/client/src/components/Map/valhallaRoute.test.ts
@@ -687,4 +687,21 @@ describe('crossings by boat on a walk (CW-12)', () => {
expect(bodies[0].locations.map(location => location.search_filter)).toEqual([{ exclude_ferry: true }, { exclude_ferry: true }])
expect(bodies[1].locations.every(location => !('search_filter' in location))).toBe(true)
})
+
+ it('VALHALLA-FERRY-006: a "no path" from the router reads apart from a refusal about anything else, asked once', async () => {
+ const points = [{ lat: 45.4342798, lng: 12.338111 }, { lat: 45.4367609, lng: 12.3287531 }]
+ let calls = 0
+ setSettings({ valhalla_base_url: 'https://valhalla.test' })
+ server.use(http.post('https://valhalla.test/route', () => {
+ calls++
+ return HttpResponse.json({ error_code: 442, error: 'No path could be found for input', status_code: 400 }, { status: 400 })
+ }))
+ expect(await valhallaRunOnFoot(points, undefined, { use_ferry: 0 }, { exclude_ferry: true })).toEqual({ noPath: true })
+ expect(calls).toBe(1)
+ expect(await valhallaRun(points, 'walking', [])).toBeNull()
+
+ server.use(http.post('https://valhalla.test/route', () =>
+ HttpResponse.json({ error_code: 154, error: 'Path distance exceeds the max distance limit' }, { status: 400 })))
+ expect(await valhallaRunOnFoot(points, undefined, { use_ferry: 0 }, { exclude_ferry: true })).toBeNull()
+ })
})
diff --git a/client/src/components/Map/valhallaRoute.ts b/client/src/components/Map/valhallaRoute.ts
index 0ce46dc11..03eb43a50 100644
--- a/client/src/components/Map/valhallaRoute.ts
+++ b/client/src/components/Map/valhallaRoute.ts
@@ -136,6 +136,22 @@ export interface ValhallaLeg {
ferrySpans?: FerrySpan[]
}
+/**
+ * CW-12: the router's own word that no way joins the points, apart from a
+ * router that gave no answer at all: down, rate limited, or not asked.
+ */
+export interface ValhallaNoPath {
+ noPath: true
+}
+
+/**
+ * The refusals that are about the way rather than the host: points in
+ * regions no edge connects (170), a point with no edge near it (171), and no
+ * path found between them (442).
+ */
+const NO_PATH_CODES = new Set([170, 171, 442])
+const NO_PATH: ValhallaNoPath = { noPath: true }
+
/** A routed chain: one leg per pair of consecutive waypoints, plus the whole of it. */
export interface ValhallaRun {
legs: ValhallaLeg[]
@@ -219,21 +235,24 @@ export async function valhallaRun(
signal?: AbortSignal,
costingOptions: Readonly<CostingOptions> = {},
): Promise<ValhallaRun | null> {
- return chainRun(waypoints, profile, avoid, signal, { costingOptions, searchFilter: null })
+ const run = await chainRun(waypoints, profile, avoid, signal, { costingOptions, searchFilter: null })
+ if (!run || 'noPath' in run) return null
+ return run
}
/**
* CW-12: a chain walked on foot, every point bound off the boat lines. Measured
* on Venice: a stop by a vaporetto pier bound onto the boat line ended the
* route on the ferry to its next landing, which `use_ferry` cannot weigh away
- * because the edge is where the route starts, not a choice along it.
+ * because the edge is where the route starts, not a choice along it. Tells a
+ * walk no way joins (`noPath`) from a router that did not answer (null).
*/
export function valhallaRunOnFoot(
waypoints: Waypoint[],
signal: AbortSignal | undefined,
costingOptions: Readonly<CostingOptions>,
searchFilter: Readonly<SearchFilter>,
-): Promise<ValhallaRun | null> {
+): Promise<ValhallaRun | ValhallaNoPath | null> {
return chainRun(waypoints, 'walking', [], signal, { costingOptions, searchFilter })
}
@@ -249,7 +268,7 @@ async function chainRun(
avoid: readonly AvoidClass[],
signal: AbortSignal | undefined,
ask: RunAsk,
-): Promise<ValhallaRun | null> {
+): Promise<ValhallaRun | ValhallaNoPath | null> {
const base = valhallaBase()
if (!base || notValhalla.has(base) || waypoints.length < 2) return null
@@ -267,6 +286,7 @@ async function chainRun(
// the schedule chains leg times blindly and cannot tell that it is missing some, so
// it would print a complete, plausible, wrong timetable rather than a gap.
if (!run) return null
+ if ('noPath' in run) return run
legs.push(...run.legs)
}
if (legs.length !== waypoints.length - 1) return null
@@ -395,7 +415,7 @@ function routeBody(
}
}
-/** The parsed answer to one POST, or null for every failure. */
+/** The parsed answer to one POST, `NO_PATH` when the router found no way, or null for every other failure. */
async function postRoute(base: string, body: Record<string, unknown>, signal?: AbortSignal): Promise<unknown> {
try {
await valhallaTurn(base, signal)
@@ -414,6 +434,7 @@ async function postRoute(base: string, body: Record<string, unknown>, signal?: A
// 400 carries the real refusals (unroutable point, over 1500 km apart) and 429
// is the public instance's one-per-second.
if (response.status === 404 || response.status === 405) notValhalla.add(base)
+ if (response.status === 400 && (await refusesTheWay(response))) return NO_PATH
return null
}
return await response.json()
@@ -422,6 +443,15 @@ async function postRoute(base: string, body: Record<string, unknown>, signal?: A
}
}
+async function refusesTheWay(response: Response): Promise<boolean> {
+ try {
+ const code = ((await response.json()) as { error_code?: unknown })?.error_code
+ return typeof code === 'number' && NO_PATH_CODES.has(code)
+ } catch {
+ return false
+ }
+}
+
/** The most points a description of a line asks about; a longer line is thinned evenly, its ends kept. */
const TRACE_MAX_POINTS = 4000
/** How long a description may take before it counts as failed, so a router that hangs does not leave its card waiting. */
@@ -507,8 +537,9 @@ async function requestRun(
avoid: readonly AvoidClass[],
signal: AbortSignal | undefined,
{ costingOptions, searchFilter }: RunAsk,
-): Promise<Omit<ValhallaRun, 'snapped'> | null> {
+): Promise<Omit<ValhallaRun, 'snapped'> | ValhallaNoPath | null> {
const data = await postRoute(base, routeBody(waypoints, profile, avoid, costingOptions, searchFilter), signal)
+ if (data === NO_PATH) return NO_PATH
return data === null ? null : runFrom(data)
}
diff --git a/client/src/components/Tours/planner/TourPlannerPanels.tsx b/client/src/components/Tours/planner/TourPlannerPanels.tsx
index c5d8073d0..4899a20e2 100644
--- a/client/src/components/Tours/planner/TourPlannerPanels.tsx
+++ b/client/src/components/Tours/planner/TourPlannerPanels.tsx
@@ -733,7 +733,7 @@ function plannerTimeFields(planner: TourPlannerController, t: Translate): TourMe
}
if (planner.stationStays) {
return walkTimeFields({ walking: estimate, walkingMinutes: planner.walkingDurationMinutes, stays: planner.stationStays,
- manualMinutes: planner.plannedDurationMinutes, ferries: planner.walkFerries.crossings, t })
+ manualMinutes: planner.plannedDurationMinutes, t })
}
return [
{
diff --git a/client/src/components/Tours/planner/stationModel.ts b/client/src/components/Tours/planner/stationModel.ts
index cbc6c6322..ca87e0c7c 100644
--- a/client/src/components/Tours/planner/stationModel.ts
+++ b/client/src/components/Tours/planner/stationModel.ts
@@ -16,21 +16,29 @@ export interface WalkTimes {
unknownStays: number;
/** The walk's stations, so that some stays unknown and all of them unknown read apart. */
stations: number;
- /** Walking and the known stays; the known stays alone while the walking time is not known, null while nothing is. */
+ /**
+ * CW-12: the minutes its crossings by boat take, never walking; null while
+ * the router gave one of them no time, absent for a walk without any.
+ */
+ ferryMinutes?: number | null;
+ /** Walking, the boat and the known stays; what is known of them while the walking time is not, null while nothing is. */
totalMinutes: number | null;
- /** The total leaves out a stay or the walking time that is not known. */
+ /** The total leaves out a stay, a boat's time or the walking time that is not known. */
partial: boolean;
}
/** The times of a walk from its parts: the walking time, the stays entered, how many are unknown and of how many. */
export function walkTimesOf(parts: Omit<WalkTimes, 'totalMinutes' | 'partial'>): WalkTimes {
- const { walkingMinutes, stayMinutes, unknownStays, stations } = parts;
+ const { walkingMinutes, stayMinutes, unknownStays, stations, ferryMinutes } = parts;
// Without a walking time the stays entered are still part of the whole: at least that much, never nothing.
- const totalMinutes = walkingMinutes !== null ? walkingMinutes + stayMinutes : stayMinutes > 0 ? stayMinutes : null;
+ const known = stayMinutes + (ferryMinutes ?? 0);
+ const totalMinutes = walkingMinutes !== null ? walkingMinutes + known : known > 0 ? known : null;
return {
...parts,
totalMinutes,
- partial: totalMinutes !== null && (someStaysUnknown({ unknownStays, stations }) || walkingMinutes === null),
+ partial:
+ totalMinutes !== null &&
+ (someStaysUnknown({ unknownStays, stations }) || walkingMinutes === null || ferryMinutes === null),
};
}
diff --git a/client/src/components/Tours/planner/tourPlannerFacts.ts b/client/src/components/Tours/planner/tourPlannerFacts.ts
index d0fe866d7..6f5e52b34 100644
--- a/client/src/components/Tours/planner/tourPlannerFacts.ts
+++ b/client/src/components/Tours/planner/tourPlannerFacts.ts
@@ -76,7 +76,7 @@ export interface TourPlannerFactsInput {
* CW-02: a city walk's stays as far as known, and of how many stations; null
* for any other type, which takes its breaks.
*/
- stays?: Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations'> | null;
+ stays?: Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations' | 'ferryMinutes'> | null;
/** The router's own time, seconds: a bike tour's riding time; stands in for a hike until the heights are in. */
durationSeconds: number | null;
/** MDT-01: the stages the tour is split into, one for a day tour; a day each is what the times may take. */
diff --git a/client/src/components/Tours/planner/tourRouting.test.ts b/client/src/components/Tours/planner/tourRouting.test.ts
index 36adde2e9..ab100eacf 100644
--- a/client/src/components/Tours/planner/tourRouting.test.ts
+++ b/client/src/components/Tours/planner/tourRouting.test.ts
@@ -300,7 +300,7 @@ describe('a city walk across the water (CW-12)', () => {
expect(routed.durationSeconds).toBe(1005)
expect(routed.distanceMeters).toBe(2700)
expect(routed.ferries).toEqual([
- { leg: 1, geometry: boatLeg.coordinates, crossing: [1, 2], metres: 1236, seconds: 745, walkSeconds: 355, accepted: false },
+ { leg: 1, geometry: boatLeg.coordinates, crossings: [[1, 2]], metres: 1236, seconds: 745, walkSeconds: 355, accepted: false },
])
})
@@ -321,7 +321,7 @@ describe('a city walk across the water (CW-12)', () => {
const ferry = {
kind: 'ferry' as const,
geometry: boatLeg.coordinates as [number, number][],
- crossing: [1, 2] as [number, number],
+ crossings: [[1, 2]] as [number, number][],
minutes: 12,
walk_minutes: 6,
}
@@ -331,18 +331,47 @@ describe('a city walk across the water (CW-12)', () => {
expect(valhallaRunOnFoot).toHaveBeenCalledTimes(1)
expect(routed.durationSeconds).toBe(650 + 6 * 60)
expect(routed.parts.map((part) => part.mark ?? null)).toEqual([null, 'ferry', null])
- expect(routed.ferries).toMatchObject([{ leg: 1, crossing: [1, 2], seconds: 720, walkSeconds: 360, accepted: true }])
+ expect(routed.ferries).toMatchObject([{ leg: 1, crossings: [[1, 2]], seconds: 720, walkSeconds: 360, accepted: true }])
})
+ it('TOUR-ROUTING-041: two boats on one leg stay two crossings, the walk between them walking, before and after they are taken', async () => {
+ const line = [[45.4368, 12.3288], [45.4352, 12.3275], [45.4331, 12.3262], [45.434, 12.325], [45.4345, 12.323], [45.4361, 12.3214]]
+ const twoBoats = { coordinates: line, distance: 2000, duration: 1200, hasFerry: true,
+ ferrySpans: [{ from: 0, to: 1, metres: 200, seconds: 120 }, { from: 3, to: 4, metres: 150, seconds: 90 }] }
+ valhallaRunOnFoot.mockResolvedValueOnce({ legs: [twoBoats], total: twoBoats, snapped: [3, 4].map((meters) => ({ asked: [0, 0], at: [0, 0], meters })) })
+ const routed = (await routeCityWalk([saoneri, moresco])) as TourRouteResult
+ expect(routed.ferries?.[0]).toMatchObject({ crossings: [[0, 1], [3, 4]], metres: 350, seconds: 210, walkSeconds: 990 })
+ const drawn = routed.parts.map((part) => [part.coordinates.length, part.mark ?? null])
+ expect(drawn).toEqual([[2, 'ferry'], [3, null], [2, 'ferry'], [2, null]])
+
+ valhallaRunOnFoot.mockReset()
+ const taken = { kind: 'ferry' as const, geometry: line as [number, number][], crossings: [[0, 1], [3, 4]] as [number, number][], minutes: 4, walk_minutes: 17 }
+ const kept = (await routeCityWalk([{ ...saoneri, fixedLeg: taken }, moresco])) as TourRouteResult
+ expect(kept.parts.map((part) => [part.coordinates.length, part.mark ?? null])).toEqual(drawn)
+ expect(kept.ferries?.[0]).toMatchObject({ crossings: [[0, 1], [3, 4]], accepted: true })
+ })
+
+ const answered = { total: { coordinates: [[0, 0], [1, 1]], distance: 1, duration: 1 }, legs: [], snapped: [] }
+ const noPath = { noPath: true }
+ const stops = [sanMarco, saoneri, moresco, { lat: 45.43, lng: 12.31 }, { lat: 45.42, lng: 12.3 }]
+
it('TOUR-ROUTING-039: two stops no way joins are named by halving the walk, and a host that answers after all names none', async () => {
- const answered = { total: { coordinates: [[0, 0], [1, 1]], distance: 1, duration: 1 }, legs: [], snapped: [] }
- const stops = [sanMarco, saoneri, moresco, { lat: 45.43, lng: 12.31 }, { lat: 45.42, lng: 12.3 }]
- // The whole walk fails, its first half [0..2] answers, then [2..3] fails: the gap is the leg from stop 2.
- valhallaRunOnFoot.mockResolvedValueOnce(null).mockResolvedValueOnce(answered).mockResolvedValueOnce(null)
+ // The whole walk has no way, its first half [0..2] answers, then [2..3] has none: the gap is the leg from stop 2.
+ valhallaRunOnFoot.mockResolvedValueOnce(noPath).mockResolvedValueOnce(answered).mockResolvedValueOnce(noPath)
expect(await routeCityWalk(stops)).toEqual({ gap: 2 })
expect(valhallaRunOnFoot.mock.calls.map((call) => (call[0] as unknown[]).length)).toEqual([5, 3, 2])
- valhallaRunOnFoot.mockReset().mockResolvedValueOnce(null).mockResolvedValue(answered)
+ valhallaRunOnFoot.mockReset().mockResolvedValueOnce(noPath).mockResolvedValue(answered)
expect(await routeCityWalk([sanMarco, saoneri])).toBeNull()
})
+
+ it('TOUR-ROUTING-040: a router that does not answer names no gap and asks no more, the walk failing as a routing error', async () => {
+ expect(await routeCityWalk(stops)).toBeNull()
+ expect(valhallaRunOnFoot).toHaveBeenCalledTimes(1)
+
+ // No way through the whole walk, but the host goes quiet while the halves are asked: nothing is known about the way.
+ valhallaRunOnFoot.mockReset().mockResolvedValueOnce(noPath).mockResolvedValue(null)
+ expect(await routeCityWalk(stops)).toBeNull()
+ expect(valhallaRunOnFoot).toHaveBeenCalledTimes(2)
+ })
})
diff --git a/client/src/components/Tours/planner/tourRouting.ts b/client/src/components/Tours/planner/tourRouting.ts
index 6c5821a6b..8cbf7be72 100644
--- a/client/src/components/Tours/planner/tourRouting.ts
+++ b/client/src/components/Tours/planner/tourRouting.ts
@@ -17,6 +17,8 @@ import {
type FerrySpan,
type SearchFilter,
type ValhallaLeg,
+ type ValhallaNoPath,
+ type ValhallaRun,
} from '../../Map/valhallaRoute'
import { hikingCosting, TOURS_MAX_HIKING_DIFFICULTY } from './hikingCosting'
import { densifyLine, lineLengthM } from './tourFixedLegs'
@@ -50,8 +52,8 @@ export interface WalkFerryCrossing {
/** The leg, by the place along the tour of the point it starts at. */
leg: number
geometry: [number, number][]
- /** The points of `geometry` the boat leaves from and lands at. */
- crossing: [number, number]
+ /** Each stretch of `geometry` by boat, as the points the boat leaves from and lands at, in order. */
+ crossings: Array<[number, number]>
metres: number
/** Null where the router gave no time for the boat. */
seconds: number | null
@@ -227,19 +229,22 @@ function splitAtCrossings(coordinates: [number, number][], spans: readonly Pick<
return parts
}
+/** The length of a leg's stretches by boat, measured along its line. */
+function boatMetresOf(geometry: [number, number][], crossings: ReadonlyArray<[number, number]>): number {
+ return crossings.reduce((sum, [from, to]) => sum + lineLengthM(geometry.slice(from, to + 1)), 0)
+}
+
/**
- * CW-12: the crossing of a routed leg, from where its first boat stretch
- * leaves to where its last one lands. The walk on the leg is the router's time
- * less the boat's; where the router gave the boat no time, the walk is the
- * leg's time shared out by the length walked.
+ * CW-12: the crossing of a routed leg, each of its stretches by boat kept on
+ * its own, so a walk between two boats stays walking. The walk on the leg is
+ * the router's time less the boat's; where the router gave the boat no time,
+ * the walk is the leg's time shared out by the length walked.
*/
function crossingOf(leg: ValhallaLeg, index: number): WalkFerryCrossing | null {
const spans = leg.ferrySpans ?? []
- const first = spans[0]
- const last = spans[spans.length - 1]
- if (!first || !last) return null
- const crossing: [number, number] = [first.from, last.to]
- const metres = spans.reduce((sum, span) => sum + span.metres, 0) || lineLengthM(leg.coordinates.slice(first.from, last.to + 1))
+ if (spans.length === 0) return null
+ const crossings = spans.map(({ from, to }): [number, number] => [from, to])
+ const metres = spans.reduce((sum, span) => sum + span.metres, 0) || boatMetresOf(leg.coordinates, crossings)
const seconds = spans.every((span) => span.seconds !== null)
? spans.reduce((sum, span) => sum + (span.seconds ?? 0), 0)
: null
@@ -247,18 +252,18 @@ function crossingOf(leg: ValhallaLeg, index: number): WalkFerryCrossing | null {
const walkSeconds = seconds !== null
? Math.max(0, leg.duration - seconds)
: length > 0 ? leg.duration * Math.max(0, 1 - metres / length) : 0
- return { leg: index, geometry: leg.coordinates, crossing, metres, seconds, walkSeconds, accepted: false }
+ return { leg: index, geometry: leg.coordinates, crossings, metres, seconds, walkSeconds, accepted: false }
}
/** CW-12: a ferry leg the travellers took, as the walk counts it: the boat apart from the walk. */
function acceptedCrossing(leg: Extract<TourFixedLeg, { kind: 'ferry' }>, index: number): WalkFerryCrossing {
const geometry = leg.geometry.map(([lat, lng]): [number, number] => [lat, lng])
- const crossing: [number, number] = [leg.crossing[0], leg.crossing[1]]
+ const crossings = leg.crossings.map(([from, to]): [number, number] => [from, to])
return {
leg: index,
geometry,
- crossing,
- metres: lineLengthM(geometry.slice(crossing[0], crossing[1] + 1)),
+ crossings,
+ metres: boatMetresOf(geometry, crossings),
seconds: leg.minutes === null ? null : leg.minutes * 60,
walkSeconds: leg.walk_minutes * 60,
accepted: true,
@@ -267,13 +272,14 @@ function acceptedCrossing(leg: Extract<TourFixedLeg, { kind: 'ferry' }>, index:
/**
* CW-12: the leg of a run no way joins, found by halving the run: whichever
- * half still fails holds it. Null where every piece answers after all, a
- * failure of the host rather than of the way, or once the run is called off.
+ * half the router still finds no way through holds it. Null where every piece
+ * answers after all, where the router stops answering at all (a host that is
+ * down says nothing about the way), or once the run is called off.
*/
async function gapOf(
run: Array<Pick<Waypoint, 'lat' | 'lng'>>,
first: number,
- ask: (points: Array<Pick<Waypoint, 'lat' | 'lng'>>) => Promise<unknown>,
+ ask: (points: Array<Pick<Waypoint, 'lat' | 'lng'>>) => Promise<ValhallaRun | ValhallaNoPath | null>,
signal?: AbortSignal,
): Promise<TourRouteGap | null> {
let low = 0
@@ -282,15 +288,18 @@ async function gapOf(
while (high - low > 1) {
const middle = Math.floor((low + high) / 2)
const answer = await ask(run.slice(low, middle + 1))
- if (signal?.aborted) return null
- if (answer) {
- low = middle
- } else {
+ if (!answer || signal?.aborted) return null
+ if ('noPath' in answer) {
high = middle
failed = true
+ } else {
+ low = middle
}
}
- if (!failed && (await ask(run.slice(low, high + 1)))) return null
+ if (!failed) {
+ const last = await ask(run.slice(low, high + 1))
+ if (!last || !('noPath' in last)) return null
+ }
return signal?.aborted ? null : { gap: first + low }
}
@@ -321,7 +330,7 @@ async function routeOnLand(
let durationSeconds = 0
let unreachable: TourRouteUnreachable | TourRouteGap | null = null
// A city walk binds no point to a boat line (CW-12); no other type asks for that.
- const ask = (points: Array<Pick<Waypoint, 'lat' | 'lng'>>) => {
+ const ask = (points: Array<Pick<Waypoint, 'lat' | 'lng'>>): Promise<ValhallaRun | ValhallaNoPath | null> => {
const asked = points.map(({ lat, lng }) => ({ lat, lng }))
return searchFilter
? valhallaRunOnFoot(asked, signal, costingOptions, searchFilter)
@@ -331,8 +340,9 @@ async function routeOnLand(
const routeRun = async (run: Array<Pick<Waypoint, 'lat' | 'lng'>>, first: number) => {
if (run.length < 2) return true
const routed = await ask(run)
- if (!routed) {
- if (searchFilter && !signal?.aborted) unreachable = await gapOf(run, first, ask, signal)
+ if (!routed || 'noPath' in routed) {
+ // Only the router's own "no way" names a leg; no answer at all stays a routing failure, with its retry.
+ if (routed && !signal?.aborted) unreachable = await gapOf(run, first, ask, signal)
return false
}
const far = routed.snapped.findIndex((point) => point.meters > MAX_TOUR_SNAP_M)
@@ -366,7 +376,7 @@ async function routeOnLand(
if (!(await routeRun(run, runStart))) return unreachable
if (leg.kind === 'ferry') {
const crossing = acceptedCrossing(leg, i)
- lines.push(...splitAtCrossings(crossing.geometry, [{ from: crossing.crossing[0], to: crossing.crossing[1] }]))
+ lines.push(...splitAtCrossings(crossing.geometry, crossing.crossings.map(([from, to]) => ({ from, to }))))
ferries.push(crossing)
distanceMeters += lineLengthM(crossing.geometry)
durationSeconds += crossing.walkSeconds
diff --git a/client/src/components/Tours/planner/useTourPlanner.ts b/client/src/components/Tours/planner/useTourPlanner.ts
index dcc61dc14..9d85da228 100644
--- a/client/src/components/Tours/planner/useTourPlanner.ts
+++ b/client/src/components/Tours/planner/useTourPlanner.ts
@@ -6,7 +6,6 @@ import { randomId } from '../../../utils/randomId'
import { analyzeRouteGeometry, type RouteProfileFocus } from '../../../utils/routeGeometry'
import { closeLoop, reverseRoute, toggleFreeLeg, withPointAppended } from './tourRouteActions'
import { holdsHorseSection } from '../horse/horseLegs'
-import { walkTimes } from './stationModel'
import { hasCompleteElevation, useTourRoute } from './useTourRoute'
import { normalizePlannerWaypoints, plannerWaypointsOf, ridablePoints, routeInputsKey, sameWaypointSnapshot, savedWaypointsOf, unlinkedPoint, withSavedKeys, type TourPlannerWaypoint } from './tourPlannerWaypoints'
import { openedTourFields, tourPlannerFacts } from './tourPlannerFacts'
@@ -29,7 +28,7 @@ import { savedSkiSeed } from '../ski/savedSkiRoute'
import { useSkiFields } from '../ski/useSkiFields'
import { lostStageEnds } from '../stages/tourStages'
import { useTourStages } from '../stages/useTourStages'
-import { useWalkFerries } from '../walk/useWalkFerries'
+import { useWalkFerries, useWalkStays } from '../walk/useWalkFerries'
/** What a tour planned from an import starts with. */
export interface DerivedTourDraft {
@@ -523,8 +522,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const routedLegLengths = paddleRoute && routeCurrent ? paddleRoute.legLengths : undefined
const paddleEstimate = useMemo(() => isPaddle ? paddleEstimateOf(waypoints, { effectiveSpeedKmh, portageSpeedKmh }, paddleSpeedInvalid, routedLegLengths) : null,
[effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, routedLegLengths, waypoints])
- // CW-02: a city walk's stays, what of them is known.
- const stays = useMemo(() => (tourType === 'walk' ? walkTimes(waypoints, null) : null), [tourType, waypoints])
+ // CW-02: a city walk's stays, what of them is known; CW-12: and the minutes of its boats, never walking.
+ const stays = useWalkStays(tourType, waypoints, routeCurrent ? routing.ferries : null)
const runPaceSecondsPerKm = runPace.paceSecondsPerKm
// MDT-01: the stages, cut from the route while it is the one planned for these points.
const stagePaddle = useMemo(() => isPaddle
diff --git a/client/src/components/Tours/planner/useTourPlanner.walkFerry.test.tsx b/client/src/components/Tours/planner/useTourPlanner.walkFerry.test.tsx
index 1caeeb710..74d93b5a0 100644
--- a/client/src/components/Tours/planner/useTourPlanner.walkFerry.test.tsx
+++ b/client/src/components/Tours/planner/useTourPlanner.walkFerry.test.tsx
@@ -30,7 +30,7 @@ const boatLine: [number, number][] = [ZATTERE, [45.4291, 12.3266], [45.4275, 12.
const crossing = (accepted: boolean): WalkFerryCrossing => ({
leg: 1,
geometry: boatLine,
- crossing: [1, 2],
+ crossings: [[1, 2]],
metres: 268,
seconds: 396,
walkSeconds: 120,
@@ -118,7 +118,7 @@ describe('useTourPlanner, a city walk across the water (CW-12)', () => {
expect(result.current.waypoints[1]?.fixedLeg).toEqual({
kind: 'ferry',
geometry: boatLine,
- crossing: [1, 2],
+ crossings: [[1, 2]],
minutes: 7,
walk_minutes: 2,
});
@@ -130,7 +130,7 @@ describe('useTourPlanner, a city walk across the water (CW-12)', () => {
await result.current.save();
});
const body = createTour.mock.calls[0]?.[1] as TourCreateRequest;
- expect(body.waypoints[1]?.fixed_leg).toMatchObject({ kind: 'ferry', crossing: [1, 2], minutes: 7 });
+ expect(body.waypoints[1]?.fixed_leg).toMatchObject({ kind: 'ferry', crossings: [[1, 2]], minutes: 7 });
// The walking time saved is the walk alone; the boat's minutes stay on the leg.
expect(body.duration_seconds).toBe(17 * 60);
});
diff --git a/client/src/components/Tours/tourPresentation.ts b/client/src/components/Tours/tourPresentation.ts
index 5b1408ca8..7905ea665 100644
--- a/client/src/components/Tours/tourPresentation.ts
+++ b/client/src/components/Tours/tourPresentation.ts
@@ -36,7 +36,7 @@ export interface TourPlannedTimes {
}
type PlannedTimesSource = Pick<TourListItem, 'duration' | 'planned_duration_minutes' | 'break_additional_minutes'>
- & Partial<Pick<TourListItem, 'tour_type' | 'station_count' | 'station_stay_minutes' | 'station_stays_unknown'>>
+ & Partial<Pick<TourListItem, 'tour_type' | 'station_count' | 'station_stay_minutes' | 'station_stays_unknown' | 'walk_ferry_minutes'>>
& Partial<Pick<TourListItem, 'distance' | 'elevation_gain' | 'elevation_loss' | 'run_pace_seconds_per_km'>>
/** TIME-01: the estimate of a tour, by the rule `@trek/shared` keeps for the app and the server alike. */
@@ -60,6 +60,8 @@ function walkTimesOfTour(tour: PlannedTimesSource): WalkTimes | null {
stayMinutes: tour.station_stay_minutes,
unknownStays: tour.station_stays_unknown ?? 0,
stations: tour.station_count ?? 0,
+ // CW-12: the boat is part of the day, never of the walking time.
+ ...(tour.walk_ferry_minutes !== undefined ? { ferryMinutes: tour.walk_ferry_minutes } : {}),
})
}
diff --git a/client/src/components/Tours/walk/WalkFerryNotice.test.tsx b/client/src/components/Tours/walk/WalkFerryNotice.test.tsx
index d3065cb6f..95b3f4d75 100644
--- a/client/src/components/Tours/walk/WalkFerryNotice.test.tsx
+++ b/client/src/components/Tours/walk/WalkFerryNotice.test.tsx
@@ -4,7 +4,7 @@ import type { WalkFerryCrossing } from '../planner/tourRouting';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { WalkFerryNotice } from './WalkFerryNotice';
-// FE-WALK-FERRY-NOTICE-001 to FE-WALK-FERRY-NOTICE-003: a city walk's crossings by boat in the planner (CW-12).
+// FE-WALK-FERRY-NOTICE-001 to FE-WALK-FERRY-NOTICE-005: a city walk's crossings by boat in the planner (CW-12).
const crossing = (extra: Partial<WalkFerryCrossing> = {}): WalkFerryCrossing => ({
leg: 0,
@@ -13,7 +13,7 @@ const crossing = (extra: Partial<WalkFerryCrossing> = {}): WalkFerryCrossing =>
[45.429, 12.329],
[45.427, 12.33],
],
- crossing: [1, 2],
+ crossings: [[1, 2]],
metres: 268,
seconds: 396,
walkSeconds: 120,
@@ -21,14 +21,27 @@ const crossing = (extra: Partial<WalkFerryCrossing> = {}): WalkFerryCrossing =>
...extra,
});
-function plannerWith(walkFerries: Partial<TourPlannerController['walkFerries']>) {
+const ZATTERE_TO_STOP_2 = [
+ { id: 'a', lat: 45.43, lng: 12.33, role: 'start', name: 'Zattere' },
+ { id: 'b', lat: 45.427, lng: 12.33, role: 'end', name: null },
+];
+
+function plannerWith(
+ walkFerries: Partial<TourPlannerController['walkFerries']>,
+ waypoints: unknown[] = ZATTERE_TO_STOP_2
+) {
const actions = { accept: vi.fn(), release: vi.fn(), show: vi.fn(), select: vi.fn() };
const planner = {
- walkFerries: { crossings: [], pending: [], blocksSave: false, gap: null, ...actions, ...walkFerries },
- waypoints: [
- { id: 'a', lat: 45.43, lng: 12.33, role: 'start', name: 'Zattere' },
- { id: 'b', lat: 45.427, lng: 12.33, role: 'end', name: null },
- ],
+ walkFerries: {
+ crossings: [],
+ pending: [],
+ blocksSave: false,
+ gap: null,
+ acceptable: () => true,
+ ...actions,
+ ...walkFerries,
+ },
+ waypoints,
setSelectedWaypointId: actions.select,
canEdit: true,
isSaving: false,
@@ -71,4 +84,35 @@ describe('WalkFerryNotice (CW-12)', () => {
fireEvent.click(screen.getByRole('button', { name: 'Select stop 2' }));
expect(actions.select).toHaveBeenCalledWith('b');
});
+
+ it('FE-WALK-FERRY-NOTICE-004: a leg through a shaping point is named by the stations around it, numbered as the stop list numbers them', () => {
+ const { planner, actions } = plannerWith({ gap: { leg: 1 } }, [
+ { id: 'a', lat: 45.43, lng: 12.33, role: 'start', name: 'Zattere' },
+ { id: 's', lat: 45.429, lng: 12.331, role: 'via', shaping: true },
+ { id: 'b', lat: 45.428, lng: 12.332, role: 'via', name: null },
+ { id: 'c', lat: 45.427, lng: 12.33, role: 'end', name: 'Redentore' },
+ ]);
+ render(<WalkFerryNotice planner={planner} />);
+ expect(screen.getByTestId('walk-ferry-gap')).toHaveTextContent(
+ 'No way joins Zattere and Stop 2, neither on foot nor by ferry.'
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Select stop 2' }));
+ expect(actions.select).toHaveBeenCalledWith('b');
+ });
+
+ it('FE-WALK-FERRY-NOTICE-005: a crossing too long to keep cannot be taken, and says why', () => {
+ const pending = crossing();
+ const { planner, actions } = plannerWith({
+ crossings: [pending],
+ pending: [pending],
+ blocksSave: true,
+ acceptable: () => false,
+ });
+ render(<WalkFerryNotice planner={planner} />);
+ const take = screen.getByRole('button', { name: 'Take ferry' });
+ expect(take).toBeDisabled();
+ fireEvent.click(take);
+ expect(actions.accept).not.toHaveBeenCalled();
+ expect(screen.getByTestId('walk-ferry-accept-too-long')).toBeInTheDocument();
+ });
});
diff --git a/client/src/components/Tours/walk/WalkFerryNotice.tsx b/client/src/components/Tours/walk/WalkFerryNotice.tsx
index 0cfcc4490..8cc9e367a 100644
--- a/client/src/components/Tours/walk/WalkFerryNotice.tsx
+++ b/client/src/components/Tours/walk/WalkFerryNotice.tsx
@@ -4,21 +4,43 @@ import { useSettingsStore } from '../../../store/settingsStore';
import { formatDistance } from '../../../utils/units';
import { SoftPill } from '../../Planner/planParts';
import { Tooltip } from '../../shared/Tooltip';
+import { stopNumbersOf, type TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
import type { WalkFerryCrossing } from '../planner/tourRouting';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { CardAction, TourNotice } from '../tourParts';
import { formatPlannedTourDuration } from '../tourPresentation';
-import { ferryMinutesOf } from './walkFerry';
+import { useLinkedPlaceOf } from './useWalkSchedule';
+import { ferryMinutesOf, legStationsOf } from './walkFerry';
import { FERRY_CSS_COLOR } from './walkRoutePaint';
type Planner = Pick<
TourPlannerController,
'walkFerries' | 'waypoints' | 'setSelectedWaypointId' | 'canEdit' | 'isSaving'
>;
-type Translate = ReturnType<typeof useTranslation>['t'];
-function pointName(planner: Planner, index: number, t: Translate): string {
- return planner.waypoints[index]?.name?.trim() || t('tours.walk.stationNumbered', { number: index + 1 });
+/** A leg's two stations as the stop list shows them: by name, the trip place they stand for, else their number. */
+interface LegStop {
+ id: string | null;
+ name: string;
+ number: number;
+}
+
+function useLegStops(planner: Planner): (leg: number) => { from: LegStop; to: LegStop } {
+ const { t } = useTranslation();
+ const placeOf = useLinkedPlaceOf();
+ const numbers = stopNumbersOf(planner.waypoints);
+ const stopOf = (point: TourPlannerWaypoint | null): LegStop => {
+ const number = point ? (numbers.get(point.id) ?? 0) : 0;
+ return {
+ id: point?.id ?? null,
+ name: point?.name?.trim() || (point && placeOf(point)?.name) || t('tours.walk.stationNumbered', { number }),
+ number,
+ };
+ };
+ return (leg) => {
+ const { from, to } = legStationsOf(planner.waypoints, leg);
+ return { from: stopOf(from), to: stopOf(to) };
+ };
}
/** The crossing's length and time as badges; a time the router did not give says so, dimmed. */
@@ -44,13 +66,37 @@ function CrossingFacts({ crossing }: { crossing: WalkFerryCrossing }) {
);
}
-function selectAction(planner: Planner, index: number, t: Translate) {
- const select = () => planner.setSelectedWaypointId(planner.waypoints[index]?.id ?? null);
+function SelectStop({ planner, stop }: { planner: Planner; stop: LegStop }) {
+ const { t } = useTranslation();
return (
- <CardAction icon={<MapPin size={12} strokeWidth={2} />} onClick={select}>
- {t('tours.walk.ferry.selectStop', { number: index + 1 })}
+ <CardAction icon={<MapPin size={12} strokeWidth={2} />} onClick={() => planner.setSelectedWaypointId(stop.id)}>
+ {t('tours.walk.ferry.selectStop', { number: stop.number })}
+ </CardAction>
+ );
+}
+
+/** Take ferry; one whose line is too long to keep as a leg is dimmed, with why and what to do instead. */
+function AcceptAction({ planner, crossing }: { planner: Planner; crossing: WalkFerryCrossing }) {
+ const { t } = useTranslation();
+ const { accept, acceptable } = planner.walkFerries;
+ const fits = acceptable(crossing);
+ const action = (
+ <CardAction
+ icon={<Check size={12} strokeWidth={2} />}
+ onClick={() => accept(crossing)}
+ disabled={!planner.canEdit || planner.isSaving || !fits}
+ >
+ {t('tours.walk.ferry.accept')}
</CardAction>
);
+ if (fits) return action;
+ return (
+ <Tooltip label={t('tours.walk.ferry.acceptTooLong')}>
+ <span className="inline-flex" data-testid="walk-ferry-accept-too-long">
+ {action}
+ </span>
+ </Tooltip>
+ );
}
/**
@@ -63,26 +109,23 @@ function selectAction(planner: Planner, index: number, t: Translate) {
*/
export function WalkFerryNotice({ planner }: { planner: Planner }) {
const { t } = useTranslation();
- const { gap, crossings, accept, show } = planner.walkFerries;
- const locked = !planner.canEdit || planner.isSaving;
+ const { gap, crossings, show } = planner.walkFerries;
+ const stopsOf = useLegStops(planner);
+ const gapStops = gap ? stopsOf(gap.leg) : null;
return (
<>
- {gap && (
+ {gapStops && (
<TourNotice tone="warning" icon={<Unlink size={13} strokeWidth={2} />}>
<span className="flex flex-col items-start gap-1.5" data-testid="walk-ferry-gap">
- <span>
- {t('tours.walk.ferry.gap', {
- from: pointName(planner, gap.leg, t),
- to: pointName(planner, gap.leg + 1, t),
- })}
- </span>
+ <span>{t('tours.walk.ferry.gap', { from: gapStops.from.name, to: gapStops.to.name })}</span>
<span className="text-content-muted">{t('tours.walk.ferry.gapHint')}</span>
- {selectAction(planner, gap.leg + 1, t)}
+ <SelectStop planner={planner} stop={gapStops.to} />
</span>
</TourNotice>
)}
{crossings.map((crossing) => {
- const names = { from: pointName(planner, crossing.leg, t), to: pointName(planner, crossing.leg + 1, t) };
+ const stops = stopsOf(crossing.leg);
+ const names = { from: stops.from.name, to: stops.to.name };
return (
<TourNotice
key={`${crossing.leg}:${crossing.accepted ? 'kept' : 'open'}`}
@@ -94,19 +137,11 @@ export function WalkFerryNotice({ planner }: { planner: Planner }) {
<CrossingFacts crossing={crossing} />
{!crossing.accepted && <span className="text-content-muted">{t('tours.walk.ferry.pendingHint')}</span>}
<span className="flex flex-wrap gap-1.5">
- {!crossing.accepted && (
- <CardAction
- icon={<Check size={12} strokeWidth={2} />}
- onClick={() => accept(crossing)}
- disabled={locked}
- >
- {t('tours.walk.ferry.accept')}
- </CardAction>
- )}
+ {!crossing.accepted && <AcceptAction planner={planner} crossing={crossing} />}
<CardAction icon={<Eye size={12} strokeWidth={2} />} onClick={() => show(crossing)}>
{t('tours.walk.ferry.show')}
</CardAction>
- {!crossing.accepted && selectAction(planner, crossing.leg + 1, t)}
+ {!crossing.accepted && <SelectStop planner={planner} stop={stops.to} />}
</span>
</span>
</TourNotice>
diff --git a/client/src/components/Tours/walk/WalkStations.tsx b/client/src/components/Tours/walk/WalkStations.tsx
index ea8ee750c..bf27b54cf 100644
--- a/client/src/components/Tours/walk/WalkStations.tsx
+++ b/client/src/components/Tours/walk/WalkStations.tsx
@@ -200,15 +200,17 @@ export function WalkStationsCard({
const { t } = useTranslation();
const toast = useToast();
const isWalk = tour.tour_type === 'walk';
- const stations = useWalkStations(tripId, tour.place_id, isWalk, tour.revision);
+ const walk = useWalkStations(tripId, tour.place_id, isWalk, tour.revision);
+ const stations = walk?.stations ?? null;
+ const ferries = walk?.ferries;
const assignmentId = assignment?.id ?? null;
const visits = useDayVisits(assignmentId);
const mark = useTourVisitStore((state) => state.mark);
const placeOf = useLinkedPlaceOf();
const choice = useWalkDay(isWalk ? tour.place_id : null, days, assignments, assignment?.day_id ?? null);
const walkingMinutes = tour.duration ?? null;
- const schedule = useWalkSchedule({ stations, route, walkingMinutes, day: choice.day, placeOf });
- const remainder = useWalkRemaining({ stations, visits, route, walkingMinutes, placeOf });
+ const schedule = useWalkSchedule({ stations, route, walkingMinutes, day: choice.day, placeOf, ferries });
+ const remainder = useWalkRemaining({ stations, visits, route, walkingMinutes, placeOf, ferries });
if (!isWalk) return null;
const onMark = (key: string, status: TourVisitStatus | 'planned') => {
if (assignmentId === null) return;
diff --git a/client/src/components/Tours/walk/useWalkFerries.ts b/client/src/components/Tours/walk/useWalkFerries.ts
index 303349af0..d3dd4e10b 100644
--- a/client/src/components/Tours/walk/useWalkFerries.ts
+++ b/client/src/components/Tours/walk/useWalkFerries.ts
@@ -1,9 +1,10 @@
import type { PlannableTourType } from '@trek/shared';
-import { useCallback } from 'react';
+import { useCallback, useMemo } from 'react';
import { focusPaddleArea } from '../../../store/paddleObstacleStore';
+import { walkTimes, type WalkTimes } from '../planner/stationModel';
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
import type { WalkFerryCrossing } from '../planner/tourRouting';
-import { crossingLine, ferryLegOf } from './walkFerry';
+import { crossingLine, crossingsMinutesOf, ferryLegOf } from './walkFerry';
interface WalkFerriesInput {
tourType: PlannableTourType;
@@ -14,12 +15,38 @@ interface WalkFerriesInput {
editWaypoints: (change: (current: TourPlannerWaypoint[]) => TourPlannerWaypoint[]) => void;
}
+/**
+ * CW-02, CW-12: a city walk's stays, what of them is known, with the minutes
+ * of its crossings by boat, taken or not, which are never walking; null for
+ * any other type.
+ */
+export function useWalkStays(
+ tourType: PlannableTourType,
+ waypoints: readonly TourPlannerWaypoint[],
+ ferries: readonly WalkFerryCrossing[] | null
+): WalkTimes | null {
+ const ferryMinutes = tourType === 'walk' && ferries ? crossingsMinutesOf(ferries) : undefined;
+ return useMemo(() => {
+ if (tourType !== 'walk') return null;
+ const known = walkTimes(waypoints, null);
+ return ferryMinutes === undefined ? known : { ...known, ferryMinutes };
+ }, [ferryMinutes, tourType, waypoints]);
+}
+
+/** The ferry leg a crossing would be kept as; null where its line is longer than a leg may keep. */
+function legOf(crossing: WalkFerryCrossing, points: readonly TourPlannerWaypoint[]) {
+ const from = points[crossing.leg];
+ const to = points[crossing.leg + 1];
+ return from && to && !from.fixedLeg ? ferryLegOf(crossing, from, to) : null;
+}
+
/**
* CW-12: a city walk's crossings by boat as the planner handles them. A
* crossing the router took is shown and explained but not saved until the
* travellers take it as a ferry leg (`accept`, one step of the history), so
- * the boat never passes for walking unnoticed. `gap` is the leg no way
- * joins at all, while that is why the route failed.
+ * the boat never passes for walking unnoticed; `acceptable` is false for one
+ * too long to keep. `gap` is the leg no way joins at all, while that is why
+ * the route failed.
*/
export function useWalkFerries({
tourType,
@@ -29,15 +56,17 @@ export function useWalkFerries({
waypoints,
editWaypoints,
}: WalkFerriesInput) {
- const crossings = tourType === 'walk' && routeCurrent ? (ferries ?? []) : [];
- const pending = crossings.filter((crossing) => !crossing.accepted);
+ const crossings = useMemo(
+ () => (tourType === 'walk' && routeCurrent ? (ferries ?? []) : []),
+ [ferries, routeCurrent, tourType]
+ );
+ const pending = useMemo(() => crossings.filter((crossing) => !crossing.accepted), [crossings]);
+ const acceptable = useCallback((crossing: WalkFerryCrossing) => legOf(crossing, waypoints) !== null, [waypoints]);
const accept = useCallback(
(crossing: WalkFerryCrossing) => {
editWaypoints((current) => {
- const from = current[crossing.leg];
- const to = current[crossing.leg + 1];
- const leg = from && to && !from.fixedLeg ? ferryLegOf(crossing, from, to) : null;
+ const leg = legOf(crossing, current);
return leg
? current.map((point, index) => (index === crossing.leg ? { ...point, fixedLeg: leg } : point))
: current;
@@ -68,6 +97,7 @@ export function useWalkFerries({
/** Save waits while a crossing is not taken on purpose. */
blocksSave: pending.length > 0,
gap: tourType === 'walk' && walkGap !== null && waypoints[walkGap + 1] ? { leg: walkGap } : null,
+ acceptable,
accept,
release,
show,
diff --git a/client/src/components/Tours/walk/useWalkSchedule.ts b/client/src/components/Tours/walk/useWalkSchedule.ts
index 871a48274..90d550d05 100644
--- a/client/src/components/Tours/walk/useWalkSchedule.ts
+++ b/client/src/components/Tours/walk/useWalkSchedule.ts
@@ -1,16 +1,18 @@
-import { walkStationsOf } from '@trek/shared';
+import { walkStationsOf, type WalkFerryLeg } from '@trek/shared';
import { useCallback, useMemo } from 'react';
import { useTripStore } from '../../../store/tripStore';
import type { AssignmentsMap, Day, Place } from '../../../types';
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { useWalkDay, type WalkDayChoice } from './useWalkDay';
+import { ferryLegsOfCrossings } from './walkFerry';
import { walkScheduleOf, type LinkedPlaceOf, type WalkSchedule, type WalkScheduleInput } from './walkSchedule';
const NO_PLACES: Place[] = [];
const NO_DAYS: Day[] = [];
const NO_ASSIGNMENTS: AssignmentsMap = {};
const NO_STATIONS: TourPlannerWaypoint[] = [];
+const NO_FERRIES: WalkFerryLeg[] = [];
/** PR1-10: the trip place a point stands for, while the trip still has it. */
export function useLinkedPlaceOf(): (point: Pick<TourPlannerWaypoint, 'linkedPlaceId'>) => Place | null {
@@ -24,10 +26,17 @@ export function useLinkedPlaceOf(): (point: Pick<TourPlannerWaypoint, 'linkedPla
}
/** CW-04: `walkScheduleOf`, worked out again only when one of its parts changes. */
-export function useWalkSchedule({ stations, route, walkingMinutes, day, placeOf }: WalkScheduleInput): WalkSchedule {
+export function useWalkSchedule({
+ stations,
+ route,
+ walkingMinutes,
+ day,
+ placeOf,
+ ferries = NO_FERRIES,
+}: WalkScheduleInput): WalkSchedule {
return useMemo(
- () => walkScheduleOf({ stations, route, walkingMinutes, day, placeOf }),
- [day, placeOf, route, stations, walkingMinutes]
+ () => walkScheduleOf({ stations, route, walkingMinutes, day, placeOf, ferries }),
+ [day, ferries, placeOf, route, stations, walkingMinutes]
);
}
@@ -48,22 +57,24 @@ export interface PlannerWalkSchedule {
export function usePlannerWalkSchedule(
planner: Pick<
TourPlannerController,
- 'tourType' | 'editingPlaceId' | 'waypoints' | 'route' | 'routeCurrent' | 'walkingDurationMinutes'
+ 'tourType' | 'editingPlaceId' | 'waypoints' | 'route' | 'routeCurrent' | 'walkingDurationMinutes' | 'walkFerries'
>,
placeOf: LinkedPlaceOf
): PlannerWalkSchedule {
const days = useTripStore((state) => state.days) ?? NO_DAYS;
const assignments = useTripStore((state) => state.assignments) ?? NO_ASSIGNMENTS;
- const { tourType, editingPlaceId, waypoints, route, routeCurrent, walkingDurationMinutes } = planner;
+ const { tourType, editingPlaceId, waypoints, route, routeCurrent, walkingDurationMinutes, walkFerries } = planner;
const enabled = tourType === 'walk';
const choice = useWalkDay(enabled ? (editingPlaceId ?? null) : null, days, assignments, null);
const stations = useMemo(() => (enabled ? walkStationsOf(waypoints) : NO_STATIONS), [enabled, waypoints]);
+ const ferries = useMemo(() => ferryLegsOfCrossings(walkFerries.crossings), [walkFerries.crossings]);
const schedule = useWalkSchedule({
stations,
route: routeCurrent ? (route ?? null) : null,
walkingMinutes: walkingDurationMinutes ?? null,
day: choice.day,
placeOf,
+ ferries,
});
return { enabled, choice, schedule, stationCount: stations.length };
}
diff --git a/client/src/components/Tours/walk/useWalkStations.ts b/client/src/components/Tours/walk/useWalkStations.ts
index 105c288ec..0e8bdd3bd 100644
--- a/client/src/components/Tours/walk/useWalkStations.ts
+++ b/client/src/components/Tours/walk/useWalkStations.ts
@@ -1,31 +1,33 @@
import { useEffect, useState } from 'react';
-import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
-import { readWalkStations } from './walkStationsRead';
+import { readWalkPoints, type WalkPoints } from './walkStationsRead';
+
+const UNREAD: WalkPoints = { stations: [], ferries: [] };
/**
- * CW-03: a saved walk's stations in order: null while they load, none where
- * they could not be read. Read again when the walk is saved (its revision
- * moves on), here or by someone else, so the detail never shows the stations
- * of before; the ones shown stay until the new ones are in.
+ * CW-03: a saved walk's stations in order, with its ferry legs (CW-12): null
+ * while they load, none where they could not be read. Read again when the
+ * walk is saved (its revision moves on), here or by someone else, so the
+ * detail never shows the stations of before; the ones shown stay until the
+ * new ones are in.
*/
export function useWalkStations(
tripId: number | string,
placeId: number,
enabled: boolean,
revision?: number
-): TourPlannerWaypoint[] | null {
- const [stations, setStations] = useState<{ placeId: number; points: TourPlannerWaypoint[] } | null>(null);
+): WalkPoints | null {
+ const [walk, setWalk] = useState<{ placeId: number; points: WalkPoints } | null>(null);
useEffect(() => {
if (!enabled) return;
const controller = new AbortController();
- readWalkStations(tripId, placeId, controller.signal)
+ readWalkPoints(tripId, placeId, controller.signal)
.then((points) => {
- if (!controller.signal.aborted) setStations({ placeId, points });
+ if (!controller.signal.aborted) setWalk({ placeId, points });
})
.catch(() => {
- if (!controller.signal.aborted) setStations({ placeId, points: [] });
+ if (!controller.signal.aborted) setWalk({ placeId, points: UNREAD });
});
return () => controller.abort();
}, [enabled, placeId, revision, tripId]);
- return enabled && stations?.placeId === placeId ? stations.points : null;
+ return enabled && walk?.placeId === placeId ? walk.points : null;
}
diff --git a/client/src/components/Tours/walk/walkFerry.ts b/client/src/components/Tours/walk/walkFerry.ts
index 7a2635d05..d3bcf1ca3 100644
--- a/client/src/components/Tours/walk/walkFerry.ts
+++ b/client/src/components/Tours/walk/walkFerry.ts
@@ -1,4 +1,4 @@
-import { TOUR_FIXED_LEG_MAX_POINTS, type PlannableTourType, type TourFixedLeg } from '@trek/shared';
+import { TOUR_FIXED_LEG_MAX_POINTS, type PlannableTourType, type TourFixedLeg, type WalkFerryLeg } from '@trek/shared';
import { haversineKm } from '../../../utils/geo';
import type { WalkFerryCrossing } from '../planner/tourRouting';
@@ -44,18 +44,54 @@ export function ferryLegOf(crossing: WalkFerryCrossing, from: LegPoint, to: LegP
return {
kind: 'ferry',
geometry,
- crossing: [crossing.crossing[0] + shift, crossing.crossing[1] + shift],
- minutes: crossing.seconds === null ? null : Math.round(crossing.seconds / 60),
+ crossings: crossing.crossings.map(([from, to]): [number, number] => [from + shift, to + shift]),
+ minutes: ferryMinutesOf(crossing),
walk_minutes: Math.round(crossing.walkSeconds / 60),
};
}
-/** The crossing as a line of its own, for the map to show it. */
+/** The stretch of the leg from where its first boat leaves to where its last lands, for the map to show it. */
export function crossingLine(crossing: WalkFerryCrossing): [number, number][] {
- return crossing.geometry.slice(crossing.crossing[0], crossing.crossing[1] + 1);
+ const first = crossing.crossings[0];
+ const last = crossing.crossings[crossing.crossings.length - 1];
+ return first && last ? crossing.geometry.slice(first[0], last[1] + 1) : crossing.geometry;
}
/** The minutes a crossing takes by boat, null where the router gave none. */
export function ferryMinutesOf(crossing: Pick<WalkFerryCrossing, 'seconds'>): number | null {
return crossing.seconds === null ? null : Math.max(1, Math.round(crossing.seconds / 60));
}
+
+/** The planner's crossings as the ferry legs a walk's times read: the boat parts of each leg and their minutes. */
+export function ferryLegsOfCrossings(crossings: readonly WalkFerryCrossing[]): WalkFerryLeg[] {
+ return crossings.map((crossing) => ({
+ crossings: crossing.crossings.map(([from, to]) => crossing.geometry.slice(from, to + 1)),
+ minutes: ferryMinutesOf(crossing),
+ }));
+}
+
+/**
+ * The stations a leg runs between as the stop list shows them: a leg from or
+ * to a shaping point is named by the station before it and the one after it.
+ */
+export function legStationsOf<T extends { shaping?: boolean }>(
+ points: readonly T[],
+ leg: number
+): { from: T | null; to: T | null } {
+ let from = leg;
+ while (from > 0 && points[from]?.shaping) from -= 1;
+ let to = leg + 1;
+ while (to < points.length - 1 && points[to]?.shaping) to += 1;
+ return { from: points[from] ?? null, to: points[to] ?? null };
+}
+
+/** The minutes a walk's crossings take by boat: their sum, null while one has no time, undefined without any. */
+export function crossingsMinutesOf(
+ crossings: readonly Pick<WalkFerryCrossing, 'seconds'>[]
+): number | null | undefined {
+ if (crossings.length === 0) return undefined;
+ const minutes = crossings.map(ferryMinutesOf);
+ return minutes.every((value) => value !== null)
+ ? minutes.reduce<number>((sum, value) => sum + (value ?? 0), 0)
+ : null;
+}
diff --git a/client/src/components/Tours/walk/walkRemaining.test.ts b/client/src/components/Tours/walk/walkRemaining.test.ts
index e3d2596ca..95479731e 100644
--- a/client/src/components/Tours/walk/walkRemaining.test.ts
+++ b/client/src/components/Tours/walk/walkRemaining.test.ts
@@ -74,6 +74,14 @@ describe('walkRemainingOf', () => {
it('reads every station as planned before anything is checked off', () => {
expect(walkRemainingOf(input())?.walking).toMatchObject({ remaining_minutes: 40, upper_bound: false });
});
+
+ it('leaves out a ferry leg that starts at a shaping point, as the server reads it off all the points (CW-12)', () => {
+ const visits = { 'stop-museum': 'visited', 'stop-square': 'visited' } as const;
+ // The boat from a shaping point by the square to the cafe: the last stretch is no walking.
+ const ferries = [{ crossings: [ROUTE.slice(1)], minutes: 6 }];
+ expect(walkRemainingOf(input({ visits }))?.walking.remaining_minutes).toBe(20);
+ expect(walkRemainingOf(input({ visits, ferries }))?.walking.remaining_minutes).toBe(0);
+ });
});
describe('walkRemainingText', () => {
diff --git a/client/src/components/Tours/walk/walkRemaining.ts b/client/src/components/Tours/walk/walkRemaining.ts
index 4e2236be2..5f979030f 100644
--- a/client/src/components/Tours/walk/walkRemaining.ts
+++ b/client/src/components/Tours/walk/walkRemaining.ts
@@ -1,4 +1,4 @@
-import { ferryCrossingsOf, walkRemainderOf, type WalkRemainder, type WalkStationRef } from '@trek/shared';
+import { walkRemainderOf, type WalkFerryLeg, type WalkRemainder, type WalkStationRef } from '@trek/shared';
import { useMemo } from 'react';
import type { useTranslation } from '../../../i18n';
import type { VisitsByStation } from '../../../store/tourVisitStore';
@@ -16,8 +16,15 @@ export interface WalkRemainingInput {
route: ReadonlyArray<readonly [number, number]> | null;
walkingMinutes: number | null;
placeOf: LinkedPlaceOf;
+ /**
+ * CW-12: the walk's ferry legs, read off all its points as the server reads
+ * them, so one from a shaping point counts too.
+ */
+ ferries?: readonly WalkFerryLeg[];
}
+const NO_FERRIES: readonly WalkFerryLeg[] = [];
+
/**
* CW-13: what is left of a walk on the day it was opened from, by the same
* rule the assistant reads over MCP (`walk-remaining.ts` in `@trek/shared`),
@@ -30,6 +37,7 @@ export function walkRemainingOf({
route,
walkingMinutes,
placeOf,
+ ferries = NO_FERRIES,
}: WalkRemainingInput): WalkRemainder | null {
if (!stations || stations.length === 0) return null;
return walkRemainderOf({
@@ -44,8 +52,8 @@ export function walkRemainingOf({
})),
line: route,
walkingMinutes,
- // CW-12: a ferry leg taken from a station is crossed by boat and takes none of the walking time.
- crossings: ferryCrossingsOf(stations.map((station) => ({ fixed_leg: station.fixedLeg }))),
+ // CW-12: a ferry leg is crossed by boat and takes none of the walking time.
+ crossings: ferries.flatMap((leg) => leg.crossings),
});
}
@@ -55,10 +63,11 @@ export function useWalkRemaining({
route,
walkingMinutes,
placeOf,
+ ferries = NO_FERRIES,
}: WalkRemainingInput): WalkRemainder | null {
return useMemo(
- () => walkRemainingOf({ stations, visits, route, walkingMinutes, placeOf }),
- [placeOf, route, stations, visits, walkingMinutes]
+ () => walkRemainingOf({ stations, visits, route, walkingMinutes, placeOf, ferries }),
+ [ferries, placeOf, route, stations, visits, walkingMinutes]
);
}
diff --git a/client/src/components/Tours/walk/walkSchedule.test.ts b/client/src/components/Tours/walk/walkSchedule.test.ts
index d2a55ea83..e05096304 100644
--- a/client/src/components/Tours/walk/walkSchedule.test.ts
+++ b/client/src/components/Tours/walk/walkSchedule.test.ts
@@ -80,6 +80,18 @@ describe('walkScheduleOf', () => {
expect(schedule.byStation.get('square')?.fit).toEqual({ kind: 'open', source: 'place', window: [540, 1410] });
});
+ it('reaches a station after a crossing by boat its minutes later, the walk shared out on land only (CW-12)', () => {
+ // 20 min of walking to the square, then the boat to the cafe.
+ const stations = [museum, { ...square, stayMinutes: 0 }, cafe];
+ const boat = (minutes: number | null) => [{ crossings: [ROUTE.slice(1)], minutes }];
+ const crossed = walkScheduleOf(input({ stations, walkingMinutes: 20, ferries: boat(12) }));
+ expect(crossed.byStation.get('square')).toMatchObject({ arrival: 680, atLeast: false });
+ expect(crossed.byStation.get('cafe')).toMatchObject({ arrival: 692, atLeast: false, leave: 722 });
+
+ const untimed = walkScheduleOf(input({ stations, walkingMinutes: 20, ferries: boat(null) }));
+ expect(untimed.byStation.get('cafe')).toMatchObject({ arrival: 680, atLeast: true });
+ });
+
it('knows no hours where no station has any', () => {
const schedule = walkScheduleOf(input({ stations: [{ ...museum, openingHours: null }, square, cafe] }));
expect(schedule.state).toBe('ready');
diff --git a/client/src/components/Tours/walk/walkSchedule.ts b/client/src/components/Tours/walk/walkSchedule.ts
index 782e51294..cbe5372e1 100644
--- a/client/src/components/Tours/walk/walkSchedule.ts
+++ b/client/src/components/Tours/walk/walkSchedule.ts
@@ -1,4 +1,12 @@
-import { minutesOf, stationArrivals, stationFit, stationHoursOn, type StationFit } from '@trek/shared';
+import {
+ boatsAlong,
+ minutesOf,
+ stationArrivals,
+ stationFit,
+ stationHoursOn,
+ type StationFit,
+ type WalkFerryLeg,
+} from '@trek/shared';
import type { Assignment, Day, Place } from '../../../types';
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
@@ -44,6 +52,8 @@ export interface WalkScheduleInput {
/** The day it is looked at, with the walk's start that day; null when it is on none. */
day: { day: Pick<Day, 'date'>; start: string | null } | null;
placeOf: LinkedPlaceOf;
+ /** CW-12: the walk's ferry legs; a station after a boat lands is reached the boat's minutes later. */
+ ferries?: readonly WalkFerryLeg[];
}
/**
@@ -67,11 +77,18 @@ function startOf(day: WalkScheduleInput['day']): { date: string; start: number }
return start === null ? 'noStart' : { date: day.day.date, start };
}
-export function walkScheduleOf({ stations, route, walkingMinutes, day, placeOf }: WalkScheduleInput): WalkSchedule {
+export function walkScheduleOf({
+ stations,
+ route,
+ walkingMinutes,
+ day,
+ placeOf,
+ ferries = [],
+}: WalkScheduleInput): WalkSchedule {
const from = startOf(day);
if (typeof from === 'string') return emptySchedule(from);
if (!stations || !route) return emptySchedule('noRoute');
- const arrivals = stationArrivals(stations, route, from.start, walkingMinutes);
+ const arrivals = stationArrivals(stations, route, from.start, walkingMinutes, boatsAlong(route, ferries));
if (!arrivals) return emptySchedule('noRoute');
const byStation = new Map<string, StationSchedule>();
let anyHours = false;
diff --git a/client/src/components/Tours/walk/walkStationsRead.ts b/client/src/components/Tours/walk/walkStationsRead.ts
index 1aae9861b..9bb7f9932 100644
--- a/client/src/components/Tours/walk/walkStationsRead.ts
+++ b/client/src/components/Tours/walk/walkStationsRead.ts
@@ -1,4 +1,4 @@
-import { walkStationsOf } from '@trek/shared';
+import { ferryLegsOf, walkStationsOf, type WalkFerryLeg } from '@trek/shared';
import { tourRepo } from '../../../repo/tourRepo';
import { randomId } from '../../../utils/randomId';
import { plannerWaypointsOf, type TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
@@ -23,6 +23,23 @@ export async function readWalkStations(
placeId: number,
signal?: AbortSignal
): Promise<TourPlannerWaypoint[]> {
+ return (await readWalkPoints(tripId, placeId, signal)).stations;
+}
+
+/** A saved walk's stations with its ferry legs (CW-12), which may run from any of its points, a shaping point too. */
+export interface WalkPoints {
+ stations: TourPlannerWaypoint[];
+ ferries: WalkFerryLeg[];
+}
+
+export async function readWalkPoints(
+ tripId: number | string,
+ placeId: number,
+ signal?: AbortSignal
+): Promise<WalkPoints> {
const detail = await tourRepo.detail(tripId, placeId, signal);
- return ownStations(walkStationsOf(plannerWaypointsOf(detail.waypoints, randomId)), placeId);
+ return {
+ stations: ownStations(walkStationsOf(plannerWaypointsOf(detail.waypoints, randomId)), placeId),
+ ferries: ferryLegsOf(detail.waypoints),
+ };
}
diff --git a/client/src/components/Tours/walk/walkTimeFields.ts b/client/src/components/Tours/walk/walkTimeFields.ts
index 1d49423ab..8253d7d87 100644
--- a/client/src/components/Tours/walk/walkTimeFields.ts
+++ b/client/src/components/Tours/walk/walkTimeFields.ts
@@ -1,13 +1,11 @@
import { someStaysUnknown, walkTimesOf, type WalkTimes } from '../planner/stationModel';
-import type { WalkFerryCrossing } from '../planner/tourRouting';
import type { TourMetricField } from '../tourParts';
import { formatPlannedTourDuration, plannedTotalText } from '../tourPresentation';
-import { ferryMinutesOf } from './walkFerry';
type Translate = (key: string, params?: Record<string, unknown>) => string;
-/** What a city walk's stays are known of: how many, how many have no stay entered, and the stays entered. */
-type WalkStays = Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations'>;
+/** What a city walk's stays are known of: how many, how many have no stay entered, and the stays entered; with its boats (CW-12). */
+type WalkStays = Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations' | 'ferryMinutes'>;
/**
* A city walk's stays as said: their sum, and at least the sum while some
@@ -29,22 +27,16 @@ export interface WalkTimeFieldsInput {
stays: WalkStays;
/** A total entered by hand, which stays apart from the one worked out; null when there is none. */
manualMinutes: number | null;
- /** CW-12: the walk's crossings by boat, whose time is never walking time. */
- ferries?: readonly Pick<WalkFerryCrossing, 'seconds'>[];
t: Translate;
}
/** CW-12: the time of a walk's crossings by boat, as a field of its own; none without a crossing. */
-function ferryField(ferries: readonly Pick<WalkFerryCrossing, 'seconds'>[], t: Translate): TourMetricField[] {
- if (ferries.length === 0) return [];
- const minutes = ferries.map(ferryMinutesOf);
- const known = minutes.every((value) => value !== null);
+function ferryField(minutes: number | null | undefined, t: Translate): TourMetricField[] {
+ if (minutes === undefined) return [];
return [
{
label: t('tours.walk.ferry.field'),
- value: known
- ? formatPlannedTourDuration(minutes.reduce<number>((sum, value) => sum + (value ?? 0), 0))
- : t('tours.walk.ferry.timeUnknown'),
+ value: minutes === null ? t('tours.walk.ferry.timeUnknown') : formatPlannedTourDuration(minutes),
info: { label: t('tours.walk.ferry.fieldInfoLabel'), description: t('tours.walk.ferry.fieldInfo') },
},
];
@@ -52,7 +44,8 @@ function ferryField(ferries: readonly Pick<WalkFerryCrossing, 'seconds'>[], t: T
/**
* CW-02: a city walk's times as fields, in one wording for the planner and the
- * tour detail: the walking time, the stays, and the planned total of both. A
+ * tour detail: the walking time, the boat apart (CW-12), the stays, and the
+ * planned total of them. A
* total entered by hand keeps its own label, and the total worked out shows
* beside it as computed, so the two never read as one. 45 min of walking, a
* museum of 90 min and a cafe of 30 min read 45 min, 2 h and 2 h 45 min.
@@ -62,18 +55,17 @@ export function walkTimeFields({
walkingMinutes,
stays,
manualMinutes,
- ferries = [],
t,
}: WalkTimeFieldsInput): TourMetricField[] {
const notCalculated = t('tours.planner.walkingTimeUnknown');
- const { stayMinutes, unknownStays, stations } = stays;
- const times = walkTimesOf({ walkingMinutes, stayMinutes, unknownStays, stations });
+ const { stayMinutes, unknownStays, stations, ferryMinutes } = stays;
+ const times = walkTimesOf({ walkingMinutes, stayMinutes, unknownStays, stations, ferryMinutes });
const computed =
plannedTotalText({ plannedTotalMinutes: times.totalMinutes, atLeast: times.partial }, t) ?? notCalculated;
const staysText = walkStaysText(stays, t);
const parts: TourMetricField[] = [
{ ...walking, value: walkingMinutes == null ? notCalculated : formatPlannedTourDuration(walkingMinutes) },
- ...ferryField(ferries, t),
+ ...ferryField(ferryMinutes, t),
...(staysText ? [{ label: t('tours.walk.stays'), value: staysText }] : []),
];
const planned = t('tours.planner.plannedShort');
diff --git a/client/src/pages/tripPlanner/useTripPlannerPage.ts b/client/src/pages/tripPlanner/useTripPlannerPage.ts
index 20dd10a1f..1d77184c7 100644
--- a/client/src/pages/tripPlanner/useTripPlannerPage.ts
+++ b/client/src/pages/tripPlanner/useTripPlannerPage.ts
@@ -72,8 +72,8 @@ export function useTripPlannerPage() {
// What no router planned is dotted; a paddle tour's portages brown, whitewater amber, gaps red, a walk's ferry blue.
const paddlePaint = usePaddlePaint()
const walkPaint = useWalkRoutePaint()
- // A route kept from before a plan that failed no longer stands for the points: greyed, not hidden.
- const staleRoute = editingRoute && !tourPlanner.routeCurrent && tourPlanner.status === 'routing-failed'
+ // CW-12: a walk kept from before a leg no way joins no longer stands for its stations: greyed, not hidden.
+ const staleRoute = editingRoute && !tourPlanner.routeCurrent && tourPlanner.error === 'walk-gap'
const partStyle = tourRouteStyle(
!wandererBrowser.open && editingRoute ? tourPlanner.routeParts : !tourConversion.line ? trackParts : null,
tourPlanner.isPaddle || !!trackParts,
diff --git a/client/tests/helpers/tourPlannerStub.ts b/client/tests/helpers/tourPlannerStub.ts
index b36577d42..e7d2079b8 100644
--- a/client/tests/helpers/tourPlannerStub.ts
+++ b/client/tests/helpers/tourPlannerStub.ts
@@ -79,6 +79,17 @@ export function hikePlannerDefaults() {
toggleStageEnd: vi.fn(),
canEnd: vi.fn(() => false),
},
+ // CW-12: a walk with no crossing by boat and no leg it cannot join.
+ walkFerries: {
+ crossings: [],
+ pending: [],
+ blocksSave: false,
+ gap: null,
+ acceptable: vi.fn(() => true),
+ accept: vi.fn(),
+ release: vi.fn(),
+ show: vi.fn(),
+ },
// P2C-03: a tour opened at its first revision, with nothing known about others.
revision: {
base: null,
diff --git a/server/src/nest/tours/tour-plan-read.ts b/server/src/nest/tours/tour-plan-read.ts
index 971628059..cefae15db 100644
--- a/server/src/nest/tours/tour-plan-read.ts
+++ b/server/src/nest/tours/tour-plan-read.ts
@@ -188,6 +188,7 @@ export function derivedFields(detail: TourDetailResponse, { controlsFromTrack, l
...(line ? ['line.preview'] : []),
...(controlsFromTrack ? ['waypoints'] : []),
...(type === 'walk' ? ['tour.station_count', 'tour.station_stay_minutes', 'tour.station_stays_unknown'] : []),
+ ...(detail.tour.walk_ferry_minutes !== undefined ? ['tour.walk_ferry_minutes'] : []),
...(run ? ['run.open'] : []),
...(type === 'kayak' ? ['tour.paddle_check', 'obstacle_check'] : []),
...((detail.activities?.length ?? 0) > 0 ? ['activities[].metrics'] : []),
diff --git a/server/src/nest/tours/tours.mcp.ts b/server/src/nest/tours/tours.mcp.ts
index f9a37de20..2f612981e 100644
--- a/server/src/nest/tours/tours.mcp.ts
+++ b/server/src/nest/tours/tours.mcp.ts
@@ -117,7 +117,7 @@ export class ToursMcp {
@Tool({
name: 'list_tours',
description:
- "List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski and winter tours planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski and winter tour; a ride has no time worked out, so its duration is null), where it came from (origin: trek, gpx for an imported GPX, KML or KMZ file, or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the discipline of a ski tour (ski_discipline: alpine, snowboard, cross_country, touring for ski touring, snowshoe or winter_hike; snowshoeing and winter hiking are ski tours, a hike is summer only; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a planned ski tour has its legs planned by the piste router along the runs, lifts and trails of OpenStreetMap where that data reaches (ski_options: the router options it was planned with, ski_route_build: the piste data build, ski_planned_legs: the legs it planned, each by the index of the control point it starts at, null when the save did not say) and drawn straight elsewhere, an imported one is kept as recorded; its duration is the router's estimate only when every leg was planned by it, else null, and nothing in it says anything about snow, avalanches or whether a run or trail is open), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), for a multi-day tour the number of stages its route is split into (stage_count: one route planned whole, each stage ending at a stop marked as its end; null for a tour of one day) and the stops they run between (stage_stops, in route order with key and coordinates: stage n runs from stop n-1 to stop n, and is known by the key of the stop it starts at), the revision (raised by every saved change of the tour), the recorded tracks assigned to a tour (activity_tracks) and, for a recorded track, the tour it documents (activity_of), when an imported track was recorded (track_started_at, track_ended_at; null when the file carried no times), the time a tour without a planned time (an import) is estimated to take (time_estimate: minutes and basis, din33466 for a hike by the hiking signpost rule DIN 33466 from its distance, ascent and descent, run_pace for a run at the pace entered; worked out on reading and without breaks, never a recorded or planned time; minutes null when the track has no heights, and time_estimate null where nothing estimates it, a tour the planner timed among them, whose duration is its time), and the days of the trip each tour is on (tour_stage_key names the stage a day holds by its starting stop, null where the day holds the whole tour; a stage may also be on no day yet).",
+ "List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski and winter tours planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski and winter tour; a ride has no time worked out, so its duration is null), where it came from (origin: trek, gpx for an imported GPX, KML or KMZ file, or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the discipline of a ski tour (ski_discipline: alpine, snowboard, cross_country, touring for ski touring, snowshoe or winter_hike; snowshoeing and winter hiking are ski tours, a hike is summer only; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a planned ski tour has its legs planned by the piste router along the runs, lifts and trails of OpenStreetMap where that data reaches (ski_options: the router options it was planned with, ski_route_build: the piste data build, ski_planned_legs: the legs it planned, each by the index of the control point it starts at, null when the save did not say) and drawn straight elsewhere, an imported one is kept as recorded; its duration is the router's estimate only when every leg was planned by it, else null, and nothing in it says anything about snow, avalanches or whether a run or trail is open), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), and where it takes ferry legs the minutes they take by boat (walk_ferry_minutes, never part of its walking time duration; null while the router gave one of them no time), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), for a multi-day tour the number of stages its route is split into (stage_count: one route planned whole, each stage ending at a stop marked as its end; null for a tour of one day) and the stops they run between (stage_stops, in route order with key and coordinates: stage n runs from stop n-1 to stop n, and is known by the key of the stop it starts at), the revision (raised by every saved change of the tour), the recorded tracks assigned to a tour (activity_tracks) and, for a recorded track, the tour it documents (activity_of), when an imported track was recorded (track_started_at, track_ended_at; null when the file carried no times), the time a tour without a planned time (an import) is estimated to take (time_estimate: minutes and basis, din33466 for a hike by the hiking signpost rule DIN 33466 from its distance, ascent and descent, run_pace for a run at the pace entered; worked out on reading and without breaks, never a recorded or planned time; minutes null when the track has no heights, and time_estimate null where nothing estimates it, a tour the planner timed among them, whose duration is its time), and the days of the trip each tour is on (tour_stage_key names the stage a day holds by its starting stop, null where the day holds the whole tour; a stage may also be on no day yet).",
inputSchema: { tripId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
@@ -132,7 +132,7 @@ export class ToursMcp {
@Tool({
name: 'get_tour_plan',
description:
- 'Read one saved tour of a trip as the travellers saved it: its facts (tour: place_id, name, tour_type, distance, heights and walking time as stored, null when not known; the routing options as list_tours describes them; revision, raised by every saved change; the days it is on), its ordered control points (start, via and end, each with its sequence and its key, the same across saves; an import without its own shows the two ends of its track), where it came from (provenance) and its legs. Drafts in a browser are never visible: only saved tours exist here, and reading changes nothing, not the tour, its revision nor any visit. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. A control point with stage_end true ends a stage of a multi-day tour, and the next stage begins there; the stages run in the order of the route, the first from the start, the last to the end, and a tour without such a point is a tour of one day. legs lists every step from one control point to the next (from_sequence, to_sequence, from_key, to_key) with its kind: routed (planned by the router), track (part of a recorded line, an import without control points of its own, which no router planned), ferrata (follows a via ferrata, name gives it), free (drawn by hand and checked by nothing; a leg of a planned ski tour is routed where the piste router planned it and free, a straight line between its points, where it did not), ferry (a city walk only: a crossing by boat the travellers took on purpose in the planner where no way on foot joins the two stations; the fixed_leg of its control point says where on the line of the leg the boat runs (crossing, the indices of the points it leaves from and lands at), minutes, the time of the boat as the router gave it, null when it gave none, and walk_minutes, the walk to the boat and on from it; the walking time of the walk holds walk_minutes and never the time of the boat), portage (a paddle tour carried over land) or horse_route (a ride only: a section of a signposted horse route from OpenStreetMap in the direction the rider chose; the fixed_leg of its control point says signposted, with or against the direction the route is signposted in, null where it is not signposted one way, and access, the metres of each horse=* value its ways carried when it was taken, unknown where untagged; being on a horse route is no permission to ride it); length_km is the length of the line a fixed leg keeps (for the leg of a ski tour the straight line) and null for a routed or track leg, whose length is not stored apart. line gives the saved line in brief: point_count, has_heights and a preview thinned to 200 points; null while the tour waits for its way to be planned. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app), opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known) and visit_status. Visits belong to one day of the walk: name that day with dayId (one of its days) to read the status of each station that day (planned, visited or skipped) and run (the day, its assignment and what is still open); without dayId visit_status and run are null. A station visited or skipped that day is done: do not ask about it again or move it to another day. dayId is for a city walk only. The recorded tracks assigned to the tour (activities, ACT-01) each name their execution (assignment_id and day_id, null for none), the recording (track: its tour in the trip, origin, file name, when it came in) and what the recording measures (metrics: distance_km, elevation_gain_m and elevation_loss_m, null without heights; started_at, ended_at and elapsed_minutes from the first to the last time on its points, pauses included, null when the file carried no times, never estimated); these are the values of the recording, the planned values of the tour stay apart and unchanged. derived names the fields worked out on reading rather than stored with the tour: never present them as saved facts. tour.time_estimate is one of them where present: an estimate from distance and heights (or the pace of a run), never a time the travellers planned or recorded.',
+ 'Read one saved tour of a trip as the travellers saved it: its facts (tour: place_id, name, tour_type, distance, heights and walking time as stored, null when not known; the routing options as list_tours describes them; revision, raised by every saved change; the days it is on), its ordered control points (start, via and end, each with its sequence and its key, the same across saves; an import without its own shows the two ends of its track), where it came from (provenance) and its legs. Drafts in a browser are never visible: only saved tours exist here, and reading changes nothing, not the tour, its revision nor any visit. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. A control point with stage_end true ends a stage of a multi-day tour, and the next stage begins there; the stages run in the order of the route, the first from the start, the last to the end, and a tour without such a point is a tour of one day. legs lists every step from one control point to the next (from_sequence, to_sequence, from_key, to_key) with its kind: routed (planned by the router), track (part of a recorded line, an import without control points of its own, which no router planned), ferrata (follows a via ferrata, name gives it), free (drawn by hand and checked by nothing; a leg of a planned ski tour is routed where the piste router planned it and free, a straight line between its points, where it did not), ferry (a city walk only: a crossing by boat the travellers took on purpose in the planner where no way on foot joins the two stations; the fixed_leg of its control point says where on the line of the leg the boat runs (crossings, each stretch by boat as the indices of the points it leaves from and lands at, in order; a walk between two of them is walking), minutes, the time of all its boats as the router gave it, null when it gave none for one of them, and walk_minutes, the walk to the boat and on from it; the walking time of the walk holds walk_minutes and never the time of the boat), portage (a paddle tour carried over land) or horse_route (a ride only: a section of a signposted horse route from OpenStreetMap in the direction the rider chose; the fixed_leg of its control point says signposted, with or against the direction the route is signposted in, null where it is not signposted one way, and access, the metres of each horse=* value its ways carried when it was taken, unknown where untagged; being on a horse route is no permission to ride it); length_km is the length of the line a fixed leg keeps (for the leg of a ski tour the straight line) and null for a routed or track leg, whose length is not stored apart. line gives the saved line in brief: point_count, has_heights and a preview thinned to 200 points; null while the tour waits for its way to be planned. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app), opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known) and visit_status. Visits belong to one day of the walk: name that day with dayId (one of its days) to read the status of each station that day (planned, visited or skipped) and run (the day, its assignment and what is still open); without dayId visit_status and run are null. A station visited or skipped that day is done: do not ask about it again or move it to another day. dayId is for a city walk only. The recorded tracks assigned to the tour (activities, ACT-01) each name their execution (assignment_id and day_id, null for none), the recording (track: its tour in the trip, origin, file name, when it came in) and what the recording measures (metrics: distance_km, elevation_gain_m and elevation_loss_m, null without heights; started_at, ended_at and elapsed_minutes from the first to the last time on its points, pauses included, null when the file carried no times, never estimated); these are the values of the recording, the planned values of the tour stay apart and unchanged. derived names the fields worked out on reading rather than stored with the tour: never present them as saved facts. tour.time_estimate is one of them where present: an estimate from distance and heights (or the pace of a run), never a time the travellers planned or recorded.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
diff --git a/server/tests/e2e/tours-walk.e2e.test.ts b/server/tests/e2e/tours-walk.e2e.test.ts
index a459ce773..7079e69fe 100644
--- a/server/tests/e2e/tours-walk.e2e.test.ts
+++ b/server/tests/e2e/tours-walk.e2e.test.ts
@@ -378,7 +378,7 @@ describe('City walks e2e (real guards + temp SQLite)', () => {
[48.12, 11.52],
[48.13, 11.53],
],
- crossing: [0, 1],
+ crossings: [[0, 1]],
minutes: 7,
walk_minutes: 3,
};
@@ -398,13 +398,15 @@ describe('City walks e2e (real guards + temp SQLite)', () => {
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie(VIEWER));
expect(detail.body.waypoints[1].fixed_leg).toEqual(FERRY);
expect(detail.body.tour.duration).toBe(60);
+ // The boat is part of the day apart from the walking time, so a list can count it into the planned total.
+ expect(detail.body.tour.walk_ferry_minutes).toBe(7);
});
it('refuses it on any other type, and a crossing that does not run forwards within its leg', async () => {
const bodies = [
across(FERRY, 'hike'),
- across({ ...FERRY, crossing: [1, 0] }),
- across({ ...FERRY, crossing: [1, 3] }),
+ across({ ...FERRY, crossings: [[1, 0]] }),
+ across({ ...FERRY, crossings: [[1, 3]] }),
across({ ...FERRY, minutes: -1 }),
];
const statuses = await bodies.reduce<Promise<number[]>>(
diff --git a/server/tests/helpers/factories/tours.ts b/server/tests/helpers/factories/tours.ts
index ce617dfe2..30ce3c5d5 100644
--- a/server/tests/helpers/factories/tours.ts
+++ b/server/tests/helpers/factories/tours.ts
@@ -34,8 +34,6 @@ interface StationColumns {
opening_hours?: string | null;
/** 1 for a shaping point. */
shaping?: number;
- /** The leg to the next point as a fixed line, as JSON. */
- fixed_leg?: string | null;
/** MDT-01: 1 for a stop that ends a stage of a multi-day tour. */
stage_end?: number;
/** The id of the place of the trip the point stands for. */
diff --git a/server/tests/unit/nest/tour-visits.service.test.ts b/server/tests/unit/nest/tour-visits.service.test.ts
index e510cac2f..1e9531b68 100644
--- a/server/tests/unit/nest/tour-visits.service.test.ts
+++ b/server/tests/unit/nest/tour-visits.service.test.ts
@@ -383,7 +383,7 @@ describe('TourVisitsService', () => {
[48.11, 11.51],
[48.12, 11.52],
],
- crossing: [0, 1],
+ crossings: [[0, 1]],
minutes: 7,
walk_minutes: 0,
};
diff --git a/shared/src/i18n/ar/tours.ts b/shared/src/i18n/ar/tours.ts
index 5693ba145..2640685f0 100644
--- a/shared/src/i18n/ar/tours.ts
+++ b/shared/src/i18n/ar/tours.ts
@@ -763,6 +763,7 @@ const tours: TranslationStrings = {
'لا يُحتسب العبور وقتَ مشي. للحفظ، اعتمد العبّارة أو انقل محطة كي يربطهما طريق سيرًا.',
'tours.walk.ferry.accepted': 'عبّارة من {from} إلى {to}، اعتُمدت عن قصد. يبقى وقتها منفصلًا عن وقت المشي.',
'tours.walk.ferry.accept': 'اعتماد العبّارة',
+ 'tours.walk.ferry.acceptTooLong': 'خط هذا العبور أطول من أن يُحفظ كمقطع واحد. أضف محطة في الطريق أو انقل واحدة.',
'tours.walk.ferry.show': 'إظهار العبور',
'tours.walk.ferry.selectStop': 'اختيار المحطة {number}',
'tours.walk.ferry.time': '{time} بالقارب',
@@ -771,7 +772,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'عبّارة',
'tours.walk.ferry.fieldInfoLabel': 'عن وقت العبّارة',
'tours.walk.ferry.fieldInfo':
- 'الوقت الذي تستغرقه العبورات بالقارب كما يعطيه الموجّه. يبقى منفصلًا عن وقت المشي وليس ضمن الإجمالي المخطط.',
+ 'الوقت الذي تستغرقه العبورات بالقارب كما يعطيه الموجّه. يبقى منفصلًا عن وقت المشي لكنه يُحسب في الإجمالي المخطط؛ وبدونه يكون الإجمالي حدًا أدنى.',
'tours.walk.ferry.leg': 'عبور بالعبّارة',
'tours.walk.ferry.legInfo': 'عُبر بالقارب لا سيرًا. وقته ليس ضمن وقت المشي.',
'tours.walk.ferry.release': 'التخطيط سيرًا من جديد',
diff --git a/shared/src/i18n/az/tours.ts b/shared/src/i18n/az/tours.ts
index d23407cbc..13b42cc6a 100644
--- a/shared/src/i18n/az/tours.ts
+++ b/shared/src/i18n/az/tours.ts
@@ -765,6 +765,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'{from}-dan {to}-a bərə, qəsdən qəbul edilib. Onun vaxtı yürüş vaxtından ayrı saxlanılır.',
'tours.walk.ferry.accept': 'Bərəni qəbul et',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Bu keçidin xətti bir hissə kimi saxlanmaq üçün çox uzundur. Yolda bir dayanacaq əlavə et və ya birini köçür.',
'tours.walk.ferry.show': 'Keçidi göstər',
'tours.walk.ferry.selectStop': '{number} nömrəli dayanacağı seç',
'tours.walk.ferry.time': 'Qayıqla {time}',
@@ -773,7 +775,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Bərə',
'tours.walk.ferry.fieldInfoLabel': 'Bərə vaxtı haqqında',
'tours.walk.ferry.fieldInfo':
- 'Qayıqla keçidlərin vaxtı, marşrutlaşdırıcının verdiyi kimi. Yürüş vaxtından ayrı saxlanılır və planlanan cəmə daxil deyil.',
+ 'Qayıqla keçidlərin vaxtı, marşrutlaşdırıcının verdiyi kimi. Yürüş vaxtından ayrı saxlanılır, amma planlanan cəmə daxildir; o olmadan cəm minimum həddir.',
'tours.walk.ferry.leg': 'Bərə keçidi',
'tours.walk.ferry.legInfo': 'Qayıqla keçilib, piyada deyil. Vaxtı yürüş vaxtına daxil deyil.',
'tours.walk.ferry.release': 'Yenidən piyada planla',
diff --git a/shared/src/i18n/br/tours.ts b/shared/src/i18n/br/tours.ts
index b9ea661f9..1f08059d4 100644
--- a/shared/src/i18n/br/tours.ts
+++ b/shared/src/i18n/br/tours.ts
@@ -773,6 +773,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Balsa de {from} a {to}, aceita de propósito. O tempo dela fica separado do tempo de caminhada.',
'tours.walk.ferry.accept': 'Aceitar balsa',
+ 'tours.walk.ferry.acceptTooLong':
+ 'A linha desta travessia é longa demais para ser guardada como um trecho. Adicione uma parada no caminho ou mova uma.',
'tours.walk.ferry.show': 'Mostrar travessia',
'tours.walk.ferry.selectStop': 'Selecionar parada {number}',
'tours.walk.ferry.time': '{time} de barco',
@@ -781,7 +783,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Balsa',
'tours.walk.ferry.fieldInfoLabel': 'Sobre o tempo de balsa',
'tours.walk.ferry.fieldInfo':
- 'O tempo das travessias de barco, como o roteador o informa. Fica separado do tempo de caminhada e não entra no total planejado.',
+ 'O tempo das travessias de barco, como o roteador o informa. Fica separado do tempo de caminhada, mas entra no total planejado; sem ele, o total é um mínimo.',
'tours.walk.ferry.leg': 'Travessia de balsa',
'tours.walk.ferry.legInfo': 'Atravessado de barco, não a pé. O tempo não está no tempo de caminhada.',
'tours.walk.ferry.release': 'Planejar a pé de novo',
diff --git a/shared/src/i18n/ca/tours.ts b/shared/src/i18n/ca/tours.ts
index 89a5266f2..f76ecfb40 100644
--- a/shared/src/i18n/ca/tours.ts
+++ b/shared/src/i18n/ca/tours.ts
@@ -777,6 +777,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Ferri de {from} a {to}, acceptat expressament. El seu temps es manté a part del temps a peu.',
'tours.walk.ferry.accept': 'Acceptar el ferri',
+ 'tours.walk.ferry.acceptTooLong':
+ "La línia d'aquesta travessia és massa llarga per desar-la com un sol tram. Afegeix una parada pel camí o mou-ne una.",
'tours.walk.ferry.show': 'Mostrar la travessia',
'tours.walk.ferry.selectStop': 'Tria la parada {number}',
'tours.walk.ferry.time': '{time} en vaixell',
@@ -785,7 +787,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Ferri',
'tours.walk.ferry.fieldInfoLabel': 'Sobre el temps de ferri',
'tours.walk.ferry.fieldInfo':
- 'El temps de les travessies en vaixell, tal com el dona el router. Es manté a part del temps a peu i no és al total planificat.',
+ 'El temps de les travessies en vaixell, tal com el dona el router. Es manté a part del temps a peu però compta al total planificat; sense ell, el total és un mínim.',
'tours.walk.ferry.leg': 'Travessia en ferri',
'tours.walk.ferry.legInfo': 'Travessat en vaixell, no a peu. El seu temps no és al temps a peu.',
'tours.walk.ferry.release': 'Tornar a planificar a peu',
diff --git a/shared/src/i18n/cs/tours.ts b/shared/src/i18n/cs/tours.ts
index 2c3fcb92c..f6f410887 100644
--- a/shared/src/i18n/cs/tours.ts
+++ b/shared/src/i18n/cs/tours.ts
@@ -759,6 +759,8 @@ const tours: TranslationStrings = {
'Přeprava se nepočítá do doby chůze. Pro uložení převezmi trajekt nebo přesuň zastávku, aby je spojila pěší cesta.',
'tours.walk.ferry.accepted': 'Trajekt z {from} do {to}, převzatý záměrně. Jeho čas je oddělen od doby chůze.',
'tours.walk.ferry.accept': 'Převzít trajekt',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Trasa této přepravy je příliš dlouhá na to, aby se uložila jako jeden úsek. Přidej zastávku po cestě, nebo jednu přesuň.',
'tours.walk.ferry.show': 'Ukázat přepravu',
'tours.walk.ferry.selectStop': 'Vybrat zastávku {number}',
'tours.walk.ferry.time': '{time} lodí',
@@ -767,7 +769,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Trajekt',
'tours.walk.ferry.fieldInfoLabel': 'O čase trajektu',
'tours.walk.ferry.fieldInfo':
- 'Čas přeprav lodí, jak ho udává plánovač. Je oddělen od doby chůze a není v plánovaném celku.',
+ 'Čas přeprav lodí, jak ho udává plánovač. Je oddělen od doby chůze, ale počítá se do plánovaného celku; bez něj je celek jen spodní hranice.',
'tours.walk.ferry.leg': 'Přeprava trajektem',
'tours.walk.ferry.legInfo': 'Přepluto lodí, ne prošlo. Jeho čas není v době chůze.',
'tours.walk.ferry.release': 'Znovu naplánovat pěšky',
diff --git a/shared/src/i18n/de/tours.ts b/shared/src/i18n/de/tours.ts
index 36878848d..dc880cb4a 100644
--- a/shared/src/i18n/de/tours.ts
+++ b/shared/src/i18n/de/tours.ts
@@ -781,6 +781,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Fähre von {from} nach {to}, bewusst übernommen. Ihre Zeit steht getrennt von der Gehzeit.',
'tours.walk.ferry.accept': 'Fähre übernehmen',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Die Linie dieser Überfahrt ist zu lang, um sie als einen Abschnitt zu speichern. Setze unterwegs eine Station oder verschiebe eine.',
'tours.walk.ferry.show': 'Überfahrt zeigen',
'tours.walk.ferry.selectStop': 'Station {number} wählen',
'tours.walk.ferry.time': '{time} mit dem Boot',
@@ -789,7 +791,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Fähre',
'tours.walk.ferry.fieldInfoLabel': 'Zur Fährzeit',
'tours.walk.ferry.fieldInfo':
- 'Die Zeit der Überfahrten mit dem Boot, so wie der Router sie angibt. Sie steht getrennt von der Gehzeit und ist nicht in der geplanten Gesamtzeit.',
+ 'Die Zeit der Überfahrten mit dem Boot, so wie der Router sie angibt. Sie steht getrennt von der Gehzeit, zählt aber zur geplanten Gesamtzeit; fehlt sie, ist die Gesamtzeit ein Mindestwert.',
'tours.walk.ferry.leg': 'Überfahrt mit der Fähre',
'tours.walk.ferry.legInfo': 'Mit dem Boot übergesetzt, nicht gegangen. Ihre Zeit ist nicht in der Gehzeit.',
'tours.walk.ferry.release': 'Wieder zu Fuß planen',
diff --git a/shared/src/i18n/en/tours.ts b/shared/src/i18n/en/tours.ts
index cefb971c2..8fc40dc1f 100644
--- a/shared/src/i18n/en/tours.ts
+++ b/shared/src/i18n/en/tours.ts
@@ -760,6 +760,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Ferry from {from} to {to}, taken on purpose. Its time is kept apart from the walking time.',
'tours.walk.ferry.accept': 'Take ferry',
+ 'tours.walk.ferry.acceptTooLong':
+ 'The line of this crossing is too long to keep as one leg. Add a stop on the way, or move one.',
'tours.walk.ferry.show': 'Show crossing',
'tours.walk.ferry.selectStop': 'Select stop {number}',
'tours.walk.ferry.time': '{time} by boat',
@@ -768,7 +770,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Ferry',
'tours.walk.ferry.fieldInfoLabel': 'About the ferry time',
'tours.walk.ferry.fieldInfo':
- 'The time the crossings by boat take, as the router gives it. It is kept apart from the walking time and is not in the planned total.',
+ 'The time the crossings by boat take, as the router gives it. It is kept apart from the walking time but counted in the planned total; without it, the total is a lower bound.',
'tours.walk.ferry.leg': 'Ferry crossing',
'tours.walk.ferry.legInfo': 'Crossed by boat, not walked. Its time is not in the walking time.',
'tours.walk.ferry.release': 'Plan on foot again',
diff --git a/shared/src/i18n/es/tours.ts b/shared/src/i18n/es/tours.ts
index 915d48b11..1fe79b827 100644
--- a/shared/src/i18n/es/tours.ts
+++ b/shared/src/i18n/es/tours.ts
@@ -773,6 +773,8 @@ const tours: TranslationStrings = {
'La travesía no cuenta como tiempo a pie. Para guardar, acepta el ferri o mueve una parada para que un camino a pie las una.',
'tours.walk.ferry.accepted': 'Ferri de {from} a {to}, aceptado a propósito. Su tiempo queda aparte del tiempo a pie.',
'tours.walk.ferry.accept': 'Aceptar ferri',
+ 'tours.walk.ferry.acceptTooLong':
+ 'La línea de esta travesía es demasiado larga para guardarla como un solo tramo. Añade una parada en el camino o mueve una.',
'tours.walk.ferry.show': 'Mostrar travesía',
'tours.walk.ferry.selectStop': 'Elegir parada {number}',
'tours.walk.ferry.time': '{time} en barco',
@@ -781,7 +783,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Ferri',
'tours.walk.ferry.fieldInfoLabel': 'Sobre el tiempo en ferri',
'tours.walk.ferry.fieldInfo':
- 'El tiempo de las travesías en barco, tal como lo da el enrutador. Queda aparte del tiempo a pie y no está en el total planificado.',
+ 'El tiempo de las travesías en barco, tal como lo da el enrutador. Queda aparte del tiempo a pie, pero cuenta en el total planificado; sin él, el total es un mínimo.',
'tours.walk.ferry.leg': 'Travesía en ferri',
'tours.walk.ferry.legInfo': 'Cruzado en barco, no a pie. Su tiempo no está en el tiempo a pie.',
'tours.walk.ferry.release': 'Planificar a pie de nuevo',
diff --git a/shared/src/i18n/et/tours.ts b/shared/src/i18n/et/tours.ts
index cc1890b8e..fde277867 100644
--- a/shared/src/i18n/et/tours.ts
+++ b/shared/src/i18n/et/tours.ts
@@ -761,6 +761,8 @@ const tours: TranslationStrings = {
'Ülesõitu ei loeta kõndimisajaks. Salvestamiseks võta praam üle või liiguta peatust, et jalgtee need ühendaks.',
'tours.walk.ferry.accepted': 'Praam {from} kuni {to}, meelega üle võetud. Selle aeg on kõndimisajast eraldi.',
'tours.walk.ferry.accept': 'Võta praam',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Selle ülesõidu joon on liiga pikk, et seda ühe lõiguna hoida. Lisa teele peatus või liiguta mõnda.',
'tours.walk.ferry.show': 'Näita ülesõitu',
'tours.walk.ferry.selectStop': 'Vali peatus {number}',
'tours.walk.ferry.time': '{time} paadiga',
@@ -769,7 +771,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Praam',
'tours.walk.ferry.fieldInfoLabel': 'Praamiajast',
'tours.walk.ferry.fieldInfo':
- 'Paadiga ülesõitude aeg, nagu marsruutija selle annab. See on kõndimisajast eraldi ega kuulu planeeritud koguaega.',
+ 'Paadiga ülesõitude aeg, nagu marsruutija selle annab. See on kõndimisajast eraldi, kuid kuulub planeeritud koguaega; ilma selleta on koguaeg alampiir.',
'tours.walk.ferry.leg': 'Praamiga ülesõit',
'tours.walk.ferry.legInfo': 'Ületatud paadiga, mitte jalgsi. Selle aeg pole kõndimisajas.',
'tours.walk.ferry.release': 'Planeeri uuesti jalgsi',
diff --git a/shared/src/i18n/fr/tours.ts b/shared/src/i18n/fr/tours.ts
index b9b981b66..f475fe637 100644
--- a/shared/src/i18n/fr/tours.ts
+++ b/shared/src/i18n/fr/tours.ts
@@ -787,6 +787,8 @@ const tours: TranslationStrings = {
"La traversée ne compte pas comme temps de marche. Pour enregistrer, prends le ferry ou déplace une étape pour qu'un chemin à pied les relie.",
'tours.walk.ferry.accepted': 'Ferry de {from} à {to}, pris exprès. Son temps reste à part du temps de marche.',
'tours.walk.ferry.accept': 'Prendre le ferry',
+ 'tours.walk.ferry.acceptTooLong':
+ 'La ligne de cette traversée est trop longue pour être gardée comme un seul tronçon. Ajoute une étape en chemin ou déplace-en une.',
'tours.walk.ferry.show': 'Montrer la traversée',
'tours.walk.ferry.selectStop': "Choisir l'étape {number}",
'tours.walk.ferry.time': '{time} en bateau',
@@ -796,7 +798,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Ferry', // same-as-en
'tours.walk.ferry.fieldInfoLabel': 'À propos du temps de ferry',
'tours.walk.ferry.fieldInfo':
- "Le temps des traversées en bateau, tel que le calculateur le donne. Il reste à part du temps de marche et n'entre pas dans le total prévu.",
+ 'Le temps des traversées en bateau, tel que le calculateur le donne. Il reste à part du temps de marche mais entre dans le total prévu. Sans lui, le total est un minimum.',
'tours.walk.ferry.leg': 'Traversée en ferry',
'tours.walk.ferry.legInfo': "Traversé en bateau, pas à pied. Son temps n'est pas dans le temps de marche.",
'tours.walk.ferry.release': 'Replanifier à pied',
diff --git a/shared/src/i18n/gr/tours.ts b/shared/src/i18n/gr/tours.ts
index 1ef42fa92..a9af03eac 100644
--- a/shared/src/i18n/gr/tours.ts
+++ b/shared/src/i18n/gr/tours.ts
@@ -792,6 +792,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Φέρι από {from} προς {to}, κρατημένο σκόπιμα. Ο χρόνος του μένει χωριστά από τον χρόνο περπατήματος.',
'tours.walk.ferry.accept': 'Κράτηση φέρι',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Η γραμμή αυτής της διάβασης είναι πολύ μεγάλη για να κρατηθεί ως ένα τμήμα. Πρόσθεσε μια στάση στη διαδρομή ή μετακίνησε μία.',
'tours.walk.ferry.show': 'Εμφάνιση διάβασης',
'tours.walk.ferry.selectStop': 'Επιλογή στάσης {number}',
'tours.walk.ferry.time': '{time} με σκάφος',
@@ -800,7 +802,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Φέρι',
'tours.walk.ferry.fieldInfoLabel': 'Σχετικά με τον χρόνο φέρι',
'tours.walk.ferry.fieldInfo':
- 'Ο χρόνος των διαβάσεων με σκάφος, όπως τον δίνει η δρομολόγηση. Μένει χωριστά από τον χρόνο περπατήματος και δεν μπαίνει στο προγραμματισμένο σύνολο.',
+ 'Ο χρόνος των διαβάσεων με σκάφος, όπως τον δίνει η δρομολόγηση. Μένει χωριστά από τον χρόνο περπατήματος, αλλά μετρά στο προγραμματισμένο σύνολο· χωρίς αυτόν, το σύνολο είναι ελάχιστο.',
'tours.walk.ferry.leg': 'Διάβαση με φέρι',
'tours.walk.ferry.legInfo': 'Διασχίστηκε με σκάφος, όχι με τα πόδια. Ο χρόνος του δεν είναι στον χρόνο περπατήματος.',
'tours.walk.ferry.release': 'Ξανά σχεδιασμός με τα πόδια',
diff --git a/shared/src/i18n/hu/tours.ts b/shared/src/i18n/hu/tours.ts
index 020bc5952..fd0732290 100644
--- a/shared/src/i18n/hu/tours.ts
+++ b/shared/src/i18n/hu/tours.ts
@@ -774,6 +774,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Komp {from} és {to} között, szándékosan elfogadva. Az ideje külön áll a gyaloglási időtől.',
'tours.walk.ferry.accept': 'Komp elfogadása',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Ennek az átkelésnek a vonala túl hosszú ahhoz, hogy egy szakaszként megmaradjon. Adj hozzá egy megállót útközben, vagy helyezz át egyet.',
'tours.walk.ferry.show': 'Átkelés mutatása',
'tours.walk.ferry.selectStop': '{number}. megálló kiválasztása',
'tours.walk.ferry.time': '{time} hajóval',
@@ -782,7 +784,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Komp',
'tours.walk.ferry.fieldInfoLabel': 'A kompidőről',
'tours.walk.ferry.fieldInfo':
- 'A hajós átkelések ideje, ahogy az útvonaltervező megadja. Külön áll a gyaloglási időtől, és nincs benne a tervezett összidőben.',
+ 'A hajós átkelések ideje, ahogy az útvonaltervező megadja. Külön áll a gyaloglási időtől, de beleszámít a tervezett összidőbe; nélküle az összidő csak alsó becslés.',
'tours.walk.ferry.leg': 'Kompos átkelés',
'tours.walk.ferry.legInfo': 'Hajóval átkelve, nem gyalog. Az ideje nincs a gyaloglási időben.',
'tours.walk.ferry.release': 'Újratervezés gyalog',
diff --git a/shared/src/i18n/id/tours.ts b/shared/src/i18n/id/tours.ts
index 079c07af4..c25e01c51 100644
--- a/shared/src/i18n/id/tours.ts
+++ b/shared/src/i18n/id/tours.ts
@@ -772,6 +772,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Feri dari {from} ke {to}, diambil dengan sengaja. Waktunya dipisahkan dari waktu jalan kaki.',
'tours.walk.ferry.accept': 'Ambil feri',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Garis penyeberangan ini terlalu panjang untuk disimpan sebagai satu ruas. Tambahkan perhentian di jalan atau pindahkan salah satunya.',
'tours.walk.ferry.show': 'Tampilkan penyeberangan',
'tours.walk.ferry.selectStop': 'Pilih perhentian {number}',
'tours.walk.ferry.time': '{time} dengan perahu',
@@ -781,7 +783,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Feri',
'tours.walk.ferry.fieldInfoLabel': 'Tentang waktu feri',
'tours.walk.ferry.fieldInfo':
- 'Waktu penyeberangan dengan perahu, seperti yang diberikan perute. Dipisahkan dari waktu jalan kaki dan tidak termasuk total yang direncanakan.',
+ 'Waktu penyeberangan dengan perahu, seperti yang diberikan perute. Dipisahkan dari waktu jalan kaki, tetapi dihitung dalam total yang direncanakan; tanpanya, total adalah batas bawah.',
'tours.walk.ferry.leg': 'Penyeberangan feri',
'tours.walk.ferry.legInfo': 'Diseberangi dengan perahu, bukan berjalan. Waktunya tidak termasuk waktu jalan kaki.',
'tours.walk.ferry.release': 'Rencanakan jalan kaki lagi',
diff --git a/shared/src/i18n/it/tours.ts b/shared/src/i18n/it/tours.ts
index 9df435fc4..2e5544c69 100644
--- a/shared/src/i18n/it/tours.ts
+++ b/shared/src/i18n/it/tours.ts
@@ -779,6 +779,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Traghetto da {from} a {to}, accettato di proposito. Il suo tempo resta separato dal tempo a piedi.',
'tours.walk.ferry.accept': 'Accetta traghetto',
+ 'tours.walk.ferry.acceptTooLong':
+ 'La linea di questa traversata è troppo lunga per essere tenuta come un solo tratto. Aggiungi una tappa lungo il percorso o spostane una.',
'tours.walk.ferry.show': 'Mostra traversata',
'tours.walk.ferry.selectStop': 'Scegli la tappa {number}',
'tours.walk.ferry.time': '{time} in barca',
@@ -787,7 +789,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Traghetto',
'tours.walk.ferry.fieldInfoLabel': 'Sul tempo in traghetto',
'tours.walk.ferry.fieldInfo':
- 'Il tempo delle traversate in barca, come lo indica il calcolatore. Resta separato dal tempo a piedi e non è nel totale pianificato.',
+ 'Il tempo delle traversate in barca, come lo indica il calcolatore. Resta separato dal tempo a piedi ma conta nel totale pianificato; senza di esso, il totale è un minimo.',
'tours.walk.ferry.leg': 'Traversata in traghetto',
'tours.walk.ferry.legInfo': 'Attraversato in barca, non a piedi. Il suo tempo non è nel tempo a piedi.',
'tours.walk.ferry.release': 'Ripianifica a piedi',
diff --git a/shared/src/i18n/ja/tours.ts b/shared/src/i18n/ja/tours.ts
index 03b927af2..65bdf10f4 100644
--- a/shared/src/i18n/ja/tours.ts
+++ b/shared/src/i18n/ja/tours.ts
@@ -750,6 +750,8 @@ const tours: TranslationStrings = {
'渡航は歩行時間に数えません。保存するには、フェリーを採用するか、徒歩の道でつながるよう立ち寄り先を動かしてください。',
'tours.walk.ferry.accepted': '{from} から {to} へのフェリー、意図して採用済み。その時間は歩行時間とは別です。',
'tours.walk.ferry.accept': 'フェリーを採用',
+ 'tours.walk.ferry.acceptTooLong':
+ 'この渡航の線は長すぎて1つの区間として保存できません。途中に立ち寄り先を追加するか、どれかを動かしてください。',
'tours.walk.ferry.show': '渡航を表示',
'tours.walk.ferry.selectStop': '立ち寄り先 {number} を選択',
'tours.walk.ferry.time': '船で {time}',
@@ -758,7 +760,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'フェリー',
'tours.walk.ferry.fieldInfoLabel': 'フェリーの時間について',
'tours.walk.ferry.fieldInfo':
- '船での渡航にかかる時間で、ルート検索が示すものです。歩行時間とは別で、予定合計にも含まれません。',
+ '船での渡航にかかる時間で、ルート検索が示すものです。歩行時間とは別ですが、予定合計には含まれます。不明な場合、合計は最低値です。',
'tours.walk.ferry.leg': 'フェリーで渡航',
'tours.walk.ferry.legInfo': '歩かずに船で渡ります。その時間は歩行時間に含まれません。',
'tours.walk.ferry.release': 'もう一度徒歩で計画',
diff --git a/shared/src/i18n/ko/tours.ts b/shared/src/i18n/ko/tours.ts
index 1e5f5f4ca..dde5c851d 100644
--- a/shared/src/i18n/ko/tours.ts
+++ b/shared/src/i18n/ko/tours.ts
@@ -744,6 +744,8 @@ const tours: TranslationStrings = {
'횡단은 도보 시간에 포함되지 않습니다. 저장하려면 페리를 채택하거나 도보 길이 이어지도록 정류지를 옮기세요.',
'tours.walk.ferry.accepted': '{from}에서 {to}까지의 페리, 의도적으로 채택됨. 그 시간은 도보 시간과 따로 둡니다.',
'tours.walk.ferry.accept': '페리 채택',
+ 'tours.walk.ferry.acceptTooLong':
+ '이 횡단의 경로가 너무 길어 한 구간으로 저장할 수 없습니다. 중간에 정류지를 추가하거나 하나를 옮기세요.',
'tours.walk.ferry.show': '횡단 보기',
'tours.walk.ferry.selectStop': '정류지 {number} 선택',
'tours.walk.ferry.time': '배로 {time}',
@@ -752,7 +754,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': '페리',
'tours.walk.ferry.fieldInfoLabel': '페리 시간 안내',
'tours.walk.ferry.fieldInfo':
- '배로 건너는 데 걸리는 시간으로, 경로 탐색이 알려 준 값입니다. 도보 시간과 따로 두며 계획 총계에도 들어가지 않습니다.',
+ '배로 건너는 데 걸리는 시간으로, 경로 탐색이 알려 준 값입니다. 도보 시간과 따로 두지만 계획 총계에는 들어갑니다. 알 수 없으면 총계는 최소값입니다.',
'tours.walk.ferry.leg': '페리 횡단',
'tours.walk.ferry.legInfo': '걷지 않고 배로 건넙니다. 그 시간은 도보 시간에 없습니다.',
'tours.walk.ferry.release': '다시 도보로 계획',
diff --git a/shared/src/i18n/nl/tours.ts b/shared/src/i18n/nl/tours.ts
index 5b3b9886b..60a875049 100644
--- a/shared/src/i18n/nl/tours.ts
+++ b/shared/src/i18n/nl/tours.ts
@@ -777,6 +777,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Veerpont van {from} naar {to}, bewust overgenomen. De tijd ervan staat los van de looptijd.',
'tours.walk.ferry.accept': 'Veerpont overnemen',
+ 'tours.walk.ferry.acceptTooLong':
+ 'De lijn van deze overtocht is te lang om als één stuk te bewaren. Voeg onderweg een halte toe of verplaats er een.',
'tours.walk.ferry.show': 'Overtocht tonen',
'tours.walk.ferry.selectStop': 'Halte {number} kiezen',
'tours.walk.ferry.time': '{time} per boot',
@@ -785,7 +787,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Veerpont',
'tours.walk.ferry.fieldInfoLabel': 'Over de veerponttijd',
'tours.walk.ferry.fieldInfo':
- 'De tijd van de overtochten per boot, zoals de routeplanner die geeft. Staat los van de looptijd en zit niet in het geplande totaal.',
+ 'De tijd van de overtochten per boot, zoals de routeplanner die geeft. Staat los van de looptijd, maar telt mee in het geplande totaal; zonder die tijd is het totaal een minimum.',
'tours.walk.ferry.leg': 'Overtocht met veerpont',
'tours.walk.ferry.legInfo': 'Per boot overgestoken, niet gelopen. De tijd zit niet in de looptijd.',
'tours.walk.ferry.release': 'Opnieuw te voet plannen',
diff --git a/shared/src/i18n/pl/tours.ts b/shared/src/i18n/pl/tours.ts
index cb9836f5a..fa086ff55 100644
--- a/shared/src/i18n/pl/tours.ts
+++ b/shared/src/i18n/pl/tours.ts
@@ -781,6 +781,8 @@ const tours: TranslationStrings = {
'Przeprawa nie liczy się jako czas marszu. Aby zapisać, przyjmij prom albo przesuń przystanek, żeby łączyła je droga piesza.',
'tours.walk.ferry.accepted': 'Prom z {from} do {to}, przyjęty celowo. Jego czas jest oddzielony od czasu marszu.',
'tours.walk.ferry.accept': 'Przyjmij prom',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Linia tej przeprawy jest zbyt długa, by zachować ją jako jeden odcinek. Dodaj przystanek po drodze lub przesuń któryś.',
'tours.walk.ferry.show': 'Pokaż przeprawę',
'tours.walk.ferry.selectStop': 'Wybierz przystanek {number}',
'tours.walk.ferry.time': '{time} łodzią',
@@ -789,7 +791,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Prom',
'tours.walk.ferry.fieldInfoLabel': 'O czasie promu',
'tours.walk.ferry.fieldInfo':
- 'Czas przepraw łodzią, tak jak podaje go wyznaczanie trasy. Jest oddzielony od czasu marszu i nie wchodzi do planowanej sumy.',
+ 'Czas przepraw łodzią, tak jak podaje go wyznaczanie trasy. Jest oddzielony od czasu marszu, ale wlicza się do planowanej sumy; bez niego suma jest wartością minimalną.',
'tours.walk.ferry.leg': 'Przeprawa promem',
'tours.walk.ferry.legInfo': 'Przepłynięte łodzią, nie przebyte pieszo. Jego czas nie jest w czasie marszu.',
'tours.walk.ferry.release': 'Zaplanuj znów pieszo',
diff --git a/shared/src/i18n/ru/tours.ts b/shared/src/i18n/ru/tours.ts
index ed9237b97..b5f7c9fc5 100644
--- a/shared/src/i18n/ru/tours.ts
+++ b/shared/src/i18n/ru/tours.ts
@@ -783,6 +783,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Паром от {from} до {to}, принят намеренно. Его время учитывается отдельно от времени ходьбы.',
'tours.walk.ferry.accept': 'Принять паром',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Линия этой переправы слишком длинная, чтобы сохранить её одним участком. Добавьте остановку по пути или переместите одну.',
'tours.walk.ferry.show': 'Показать переправу',
'tours.walk.ferry.selectStop': 'Выбрать остановку {number}',
'tours.walk.ferry.time': '{time} на лодке',
@@ -791,7 +793,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Паром',
'tours.walk.ferry.fieldInfoLabel': 'О времени на пароме',
'tours.walk.ferry.fieldInfo':
- 'Время переправ на лодке, как его даёт маршрутизатор. Учитывается отдельно от времени ходьбы и не входит в плановый итог.',
+ 'Время переправ на лодке, как его даёт маршрутизатор. Учитывается отдельно от времени ходьбы, но входит в плановый итог; без него итог является минимальным.',
'tours.walk.ferry.leg': 'Переправа на пароме',
'tours.walk.ferry.legInfo': 'Пересечено на лодке, не пешком. Его время не входит во время ходьбы.',
'tours.walk.ferry.release': 'Снова спланировать пешком',
diff --git a/shared/src/i18n/sk/tours.ts b/shared/src/i18n/sk/tours.ts
index 9becc8091..a7c8abd5f 100644
--- a/shared/src/i18n/sk/tours.ts
+++ b/shared/src/i18n/sk/tours.ts
@@ -761,6 +761,8 @@ const tours: TranslationStrings = {
'Prevoz sa nepočíta do času chôdze. Na uloženie prevezmi trajekt alebo presuň zastávku, aby ich spojila pešia cesta.',
'tours.walk.ferry.accepted': 'Trajekt z {from} do {to}, prevzatý zámerne. Jeho čas je oddelený od času chôdze.',
'tours.walk.ferry.accept': 'Prevziať trajekt',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Trasa tohto prevozu je príliš dlhá na to, aby sa uložila ako jeden úsek. Pridaj zastávku po ceste alebo jednu presuň.',
'tours.walk.ferry.show': 'Ukázať prevoz',
'tours.walk.ferry.selectStop': 'Vybrať zastávku {number}',
'tours.walk.ferry.time': '{time} loďou',
@@ -769,7 +771,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Trajekt',
'tours.walk.ferry.fieldInfoLabel': 'O čase trajektu',
'tours.walk.ferry.fieldInfo':
- 'Čas prevozov loďou, ako ho uvádza plánovač. Je oddelený od času chôdze a nie je v plánovanom súčte.',
+ 'Čas prevozov loďou, ako ho uvádza plánovač. Je oddelený od času chôdze, ale započítava sa do plánovaného súčtu; bez neho je súčet len dolná hranica.',
'tours.walk.ferry.leg': 'Prevoz trajektom',
'tours.walk.ferry.legInfo': 'Preplávané loďou, nie prejdené. Jeho čas nie je v čase chôdze.',
'tours.walk.ferry.release': 'Znova naplánovať pešo',
diff --git a/shared/src/i18n/sv/tours.ts b/shared/src/i18n/sv/tours.ts
index a15544900..711185ece 100644
--- a/shared/src/i18n/sv/tours.ts
+++ b/shared/src/i18n/sv/tours.ts
@@ -759,6 +759,8 @@ const tours: TranslationStrings = {
'Överfarten räknas inte som gångtid. För att spara, ta färjan eller flytta ett stopp så att en gångväg förbinder dem.',
'tours.walk.ferry.accepted': 'Färja från {from} till {to}, tagen med avsikt. Dess tid hålls skild från gångtiden.',
'tours.walk.ferry.accept': 'Ta färjan',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Linjen för den här överfarten är för lång för att sparas som en sträcka. Lägg till ett stopp på vägen eller flytta ett.',
'tours.walk.ferry.show': 'Visa överfarten',
'tours.walk.ferry.selectStop': 'Välj stopp {number}',
'tours.walk.ferry.time': '{time} med båt',
@@ -767,7 +769,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Färja',
'tours.walk.ferry.fieldInfoLabel': 'Om färjetiden',
'tours.walk.ferry.fieldInfo':
- 'Tiden som överfarterna med båt tar, som ruttplaneraren anger den. Den hålls skild från gångtiden och ingår inte i den planerade summan.',
+ 'Tiden som överfarterna med båt tar, som ruttplaneraren anger den. Den hålls skild från gångtiden men räknas in i den planerade summan; utan den är summan ett minimum.',
'tours.walk.ferry.leg': 'Överfart med färja',
'tours.walk.ferry.legInfo': 'Korsat med båt, inte gånget. Tiden ingår inte i gångtiden.',
'tours.walk.ferry.release': 'Planera till fots igen',
diff --git a/shared/src/i18n/th/tours.ts b/shared/src/i18n/th/tours.ts
index 76b013684..d5ea1f71b 100644
--- a/shared/src/i18n/th/tours.ts
+++ b/shared/src/i18n/th/tours.ts
@@ -732,6 +732,8 @@ const tours: TranslationStrings = {
'การข้ามฟากไม่นับเป็นเวลาเดิน หากจะบันทึก ให้รับเรือข้ามฟากนี้ หรือย้ายจุดแวะให้มีทางเดินเท้าเชื่อมกัน',
'tours.walk.ferry.accepted': 'เรือข้ามฟากจาก {from} ไป {to} รับไว้โดยตั้งใจ เวลาของเรือแยกจากเวลาเดิน',
'tours.walk.ferry.accept': 'รับเรือข้ามฟาก',
+ 'tours.walk.ferry.acceptTooLong':
+ 'เส้นทางข้ามฟากนี้ยาวเกินกว่าจะเก็บเป็นช่วงเดียว เพิ่มจุดแวะระหว่างทางหรือย้ายจุดหนึ่ง',
'tours.walk.ferry.show': 'แสดงการข้ามฟาก',
'tours.walk.ferry.selectStop': 'เลือกจุดแวะ {number}',
'tours.walk.ferry.time': 'ทางเรือ {time}',
@@ -740,7 +742,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'เรือข้ามฟาก',
'tours.walk.ferry.fieldInfoLabel': 'เกี่ยวกับเวลาเรือข้ามฟาก',
'tours.walk.ferry.fieldInfo':
- 'เวลาที่ใช้ข้ามฟากทางเรือตามที่ตัวหาเส้นทางให้ไว้ แยกจากเวลาเดินและไม่รวมในเวลารวมที่วางแผน',
+ 'เวลาที่ใช้ข้ามฟากทางเรือตามที่ตัวหาเส้นทางให้ไว้ แยกจากเวลาเดินแต่รวมอยู่ในเวลารวมที่วางแผน หากไม่ทราบเวลา เวลารวมจะเป็นค่าต่ำสุด',
'tours.walk.ferry.leg': 'ข้ามฟากด้วยเรือ',
'tours.walk.ferry.legInfo': 'ข้ามด้วยเรือ ไม่ได้เดิน เวลาของมันไม่รวมในเวลาเดิน',
'tours.walk.ferry.release': 'วางแผนเดินเท้าอีกครั้ง',
diff --git a/shared/src/i18n/tours-locales.spec.ts b/shared/src/i18n/tours-locales.spec.ts
index d765adc34..9fb1b16b3 100644
--- a/shared/src/i18n/tours-locales.spec.ts
+++ b/shared/src/i18n/tours-locales.spec.ts
@@ -20,7 +20,7 @@ const toursModules = import.meta.glob<{ default: TranslationStrings }>('./*/tour
const TOUR_DOMAINS: { file: string; generalKeyCount: number; modules: DomainModules }[] = [
{
file: 'tours',
- generalKeyCount: 1335,
+ generalKeyCount: 1336,
modules: toursModules,
},
{
diff --git a/shared/src/i18n/tr/tours.ts b/shared/src/i18n/tr/tours.ts
index b5ffc636d..8a895bd18 100644
--- a/shared/src/i18n/tr/tours.ts
+++ b/shared/src/i18n/tr/tours.ts
@@ -763,6 +763,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'{from} noktasından {to} noktasına feribot, bilerek kabul edildi. Süresi yürüyüş süresinden ayrı tutulur.',
'tours.walk.ferry.accept': 'Feribotu kabul et',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Bu geçişin çizgisi tek bir bölüm olarak saklanamayacak kadar uzun. Yol üzerine bir durak ekle veya birini taşı.',
'tours.walk.ferry.show': 'Geçişi göster',
'tours.walk.ferry.selectStop': '{number}. durağı seç',
'tours.walk.ferry.time': 'Tekneyle {time}',
@@ -771,7 +773,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Feribot',
'tours.walk.ferry.fieldInfoLabel': 'Feribot süresi hakkında',
'tours.walk.ferry.fieldInfo':
- 'Tekneyle geçişlerin süresi, yönlendiricinin verdiği gibi. Yürüyüş süresinden ayrı tutulur ve planlanan toplamda yer almaz.',
+ 'Tekneyle geçişlerin süresi, yönlendiricinin verdiği gibi. Yürüyüş süresinden ayrı tutulur ama planlanan toplama dahildir; o olmadan toplam bir alt sınırdır.',
'tours.walk.ferry.leg': 'Feribotla geçiş',
'tours.walk.ferry.legInfo': 'Yürünmedi, tekneyle geçildi. Süresi yürüyüş süresinde yok.',
'tours.walk.ferry.release': 'Yeniden yürüyerek planla',
diff --git a/shared/src/i18n/uk/tours.ts b/shared/src/i18n/uk/tours.ts
index fbfed9716..fcded912a 100644
--- a/shared/src/i18n/uk/tours.ts
+++ b/shared/src/i18n/uk/tours.ts
@@ -777,6 +777,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Пором від {from} до {to}, прийнятий навмисно. Його час рахується окремо від часу ходьби.',
'tours.walk.ferry.accept': 'Прийняти пором',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Лінія цієї переправи задовга, щоб зберегти її одним відрізком. Додайте зупинку дорогою або перемістіть одну.',
'tours.walk.ferry.show': 'Показати переправу',
'tours.walk.ferry.selectStop': 'Вибрати зупинку {number}',
'tours.walk.ferry.time': '{time} човном',
@@ -785,7 +787,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Пором',
'tours.walk.ferry.fieldInfoLabel': 'Про час на поромі',
'tours.walk.ferry.fieldInfo':
- 'Час переправ човном, як його дає маршрутизатор. Рахується окремо від часу ходьби і не входить до планового підсумку.',
+ 'Час переправ човном, як його дає маршрутизатор. Рахується окремо від часу ходьби, але входить до планового підсумку; без нього підсумок є мінімальним.',
'tours.walk.ferry.leg': 'Переправа поромом',
'tours.walk.ferry.legInfo': 'Перетнуто човном, не пішки. Його час не входить у час ходьби.',
'tours.walk.ferry.release': 'Знову спланувати пішки',
diff --git a/shared/src/i18n/vi/tours.ts b/shared/src/i18n/vi/tours.ts
index b40f7deb1..ff4d14d84 100644
--- a/shared/src/i18n/vi/tours.ts
+++ b/shared/src/i18n/vi/tours.ts
@@ -761,6 +761,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.accepted':
'Phà từ {from} đến {to}, đã nhận có chủ ý. Thời gian của nó được tách khỏi thời gian đi bộ.',
'tours.walk.ferry.accept': 'Nhận phà',
+ 'tours.walk.ferry.acceptTooLong':
+ 'Đường của chuyến qua này quá dài để giữ thành một chặng. Hãy thêm một điểm dừng trên đường hoặc di chuyển một điểm.',
'tours.walk.ferry.show': 'Hiện chuyến qua',
'tours.walk.ferry.selectStop': 'Chọn điểm dừng {number}',
'tours.walk.ferry.time': '{time} bằng thuyền',
@@ -769,7 +771,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.field': 'Phà',
'tours.walk.ferry.fieldInfoLabel': 'Về thời gian đi phà',
'tours.walk.ferry.fieldInfo':
- 'Thời gian các chuyến qua bằng thuyền, như bộ tìm đường đưa ra. Được tách khỏi thời gian đi bộ và không nằm trong tổng đã lập.',
+ 'Thời gian các chuyến qua bằng thuyền, như bộ tìm đường đưa ra. Được tách khỏi thời gian đi bộ nhưng vẫn tính vào tổng đã lập; nếu thiếu, tổng chỉ là mức tối thiểu.',
'tours.walk.ferry.leg': 'Qua bằng phà',
'tours.walk.ferry.legInfo': 'Qua bằng thuyền, không đi bộ. Thời gian không nằm trong thời gian đi bộ.',
'tours.walk.ferry.release': 'Lập lại theo đi bộ',
diff --git a/shared/src/i18n/zh-TW/tours.ts b/shared/src/i18n/zh-TW/tours.ts
index e99c13f7e..94c8dcb10 100644
--- a/shared/src/i18n/zh-TW/tours.ts
+++ b/shared/src/i18n/zh-TW/tours.ts
@@ -706,6 +706,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.pendingHint': '渡船不計入步行時間。要儲存,請採用渡輪,或移動一個站點,讓步行道路連通它們。',
'tours.walk.ferry.accepted': '從 {from} 到 {to} 的渡輪,已有意採用。其時間與步行時間分開。',
'tours.walk.ferry.accept': '採用渡輪',
+ 'tours.walk.ferry.acceptTooLong': '這段渡船的路線太長,無法作為一段保存。請在途中新增一個站點,或移動一個站點。',
'tours.walk.ferry.show': '顯示渡船',
'tours.walk.ferry.selectStop': '選擇站點 {number}',
'tours.walk.ferry.time': '搭船 {time}',
@@ -713,7 +714,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.timeHint': '為路線規劃給出的渡船時間。不屬於步行時間。',
'tours.walk.ferry.field': '渡輪',
'tours.walk.ferry.fieldInfoLabel': '關於渡輪時間',
- 'tours.walk.ferry.fieldInfo': '搭船過水所需的時間,由路線規劃給出。與步行時間分開,也不計入計畫總時長。',
+ 'tours.walk.ferry.fieldInfo':
+ '搭船過水所需的時間,由路線規劃給出。與步行時間分開,但計入計畫總時長;時間未知時,總時長為最少值。',
'tours.walk.ferry.leg': '渡輪過水',
'tours.walk.ferry.legInfo': '搭船而過,並非步行。其時間不計入步行時間。',
'tours.walk.ferry.release': '重新按步行規劃',
diff --git a/shared/src/i18n/zh/tours.ts b/shared/src/i18n/zh/tours.ts
index 1132a5aa6..4f6b68cd3 100644
--- a/shared/src/i18n/zh/tours.ts
+++ b/shared/src/i18n/zh/tours.ts
@@ -707,6 +707,7 @@ const tours: TranslationStrings = {
'tours.walk.ferry.pendingHint': '渡船不计入步行时间。要保存,请采用渡轮,或移动一个站点,让步行道路连通它们。',
'tours.walk.ferry.accepted': '从 {from} 到 {to} 的渡轮,已有意采用。其时间与步行时间分开。',
'tours.walk.ferry.accept': '采用渡轮',
+ 'tours.walk.ferry.acceptTooLong': '这段渡船的线路太长,无法作为一段保存。请在途中添加一个站点,或移动一个站点。',
'tours.walk.ferry.show': '显示渡船',
'tours.walk.ferry.selectStop': '选择站点 {number}',
'tours.walk.ferry.time': '乘船 {time}',
@@ -714,7 +715,8 @@ const tours: TranslationStrings = {
'tours.walk.ferry.timeHint': '为路线规划给出的渡船时间。不属于步行时间。',
'tours.walk.ferry.field': '渡轮',
'tours.walk.ferry.fieldInfoLabel': '关于渡轮时间',
- 'tours.walk.ferry.fieldInfo': '乘船过水所需的时间,由路线规划给出。与步行时间分开,也不计入计划总时长。',
+ 'tours.walk.ferry.fieldInfo':
+ '乘船过水所需的时间,由路线规划给出。与步行时间分开,但计入计划总时长;时间未知时,总时长为最少值。',
'tours.walk.ferry.leg': '渡轮过水',
'tours.walk.ferry.legInfo': '乘船而过,并非步行。其时间不计入步行时间。',
'tours.walk.ferry.release': '重新按步行规划',
diff --git a/shared/src/tours/tour-walk.spec.ts b/shared/src/tours/tour-walk.spec.ts
index d5efd3fb8..dfb1dcf66 100644
--- a/shared/src/tours/tour-walk.spec.ts
+++ b/shared/src/tours/tour-walk.spec.ts
@@ -60,6 +60,31 @@ describe('walkStationFacts (CW-02, CW-03)', () => {
});
});
+ it('sums the minutes its ferry legs take by boat apart, unknown while one has no time (CW-12)', () => {
+ const ferry = (minutes: number | null) => ({
+ kind: 'ferry' as const,
+ geometry: [
+ [48.1, 11.5],
+ [48.105, 11.505],
+ [48.11, 11.51],
+ ] as [number, number][],
+ crossings: [[0, 1]] as [number, number][],
+ minutes,
+ walk_minutes: 3,
+ });
+ expect(
+ walkStationFacts('walk', [{ ...cathedral, fixed_leg: ferry(12) }, { ...market, fixed_leg: ferry(5) }, park]),
+ ).toMatchObject({
+ walk_ferry_minutes: 17,
+ });
+ expect(
+ walkStationFacts('walk', [{ ...cathedral, fixed_leg: ferry(12) }, { ...market, fixed_leg: ferry(null) }, park]),
+ ).toMatchObject({
+ walk_ferry_minutes: null,
+ });
+ expect(walkStationFacts('walk', [cathedral, market])).not.toHaveProperty('walk_ferry_minutes');
+ });
+
it('says nothing of the stations of any other type', () => {
expect(walkStationFacts('hike', [cathedral, { ...market, stay_minutes: 30 }])).toEqual({
station_count: null,
diff --git a/shared/src/tours/tour-walk.ts b/shared/src/tours/tour-walk.ts
index 1be888ae1..652ed5570 100644
--- a/shared/src/tours/tour-walk.ts
+++ b/shared/src/tours/tour-walk.ts
@@ -1,3 +1,6 @@
+import type { TourFixedLeg } from './tours.schema';
+import { walkFerryMinutesOf } from './walk-ferry';
+
/** Closer than this, in degrees, two points of a tour stand on the same spot (about a centimetre). */
const SAME_SPOT_DEG = 1e-7;
@@ -32,11 +35,16 @@ export function walkStationsOf<T extends Spot & { shaping?: boolean | null }>(po
return route.filter((point) => !point.shaping);
}
-/** What a list says of a city walk's stations: how many, their stays as far as entered, and how many have none. */
+/**
+ * What a list says of a city walk's stations: how many, their stays as far as
+ * entered, and how many have none; with the minutes of its ferry legs by boat
+ * where it takes any (CW-12).
+ */
interface WalkStationFacts {
station_count: number | null;
station_stay_minutes: number | null;
station_stays_unknown: number | null;
+ walk_ferry_minutes?: number | null;
}
/**
@@ -48,13 +56,19 @@ interface WalkStationFacts {
*/
export function walkStationFacts(
tourType: string,
- points: readonly (Spot & { shaping?: boolean | null; stay_minutes?: number | null })[],
+ points: readonly (Spot & {
+ shaping?: boolean | null;
+ stay_minutes?: number | null;
+ fixed_leg?: TourFixedLeg | null;
+ })[],
): WalkStationFacts {
if (tourType !== 'walk') return { station_count: null, station_stay_minutes: null, station_stays_unknown: null };
const stations = walkStationsOf(points);
+ const ferryMinutes = walkFerryMinutesOf(points);
return {
station_count: stations.length,
station_stay_minutes: stations.reduce((sum, station) => sum + (station.stay_minutes ?? 0), 0),
station_stays_unknown: stations.filter((station) => station.stay_minutes == null).length,
+ ...(ferryMinutes !== undefined ? { walk_ferry_minutes: ferryMinutes } : {}),
};
}
diff --git a/shared/src/tours/tours.schema.test.ts b/shared/src/tours/tours.schema.test.ts
index 6b04acb2a..ff42b5b46 100644
--- a/shared/src/tours/tours.schema.test.ts
+++ b/shared/src/tours/tours.schema.test.ts
@@ -203,7 +203,7 @@ describe('Tours fixed legs', () => {
});
describe('Tours ferry legs (CW-12)', () => {
- const ferry = (crossing: [number, number], minutes: number | null = 7) => ({
+ const ferry = (crossings: Array<[number, number]>, minutes: number | null = 7) => ({
kind: 'ferry' as const,
geometry: [
[48, 11],
@@ -211,7 +211,7 @@ describe('Tours ferry legs (CW-12)', () => {
[48.006, 11.012],
[48.01, 11.02],
] as [number, number][],
- crossing,
+ crossings,
minutes,
walk_minutes: 2,
});
@@ -226,20 +226,34 @@ describe('Tours ferry legs (CW-12)', () => {
});
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]]), '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,
- });
+ expect(tourCreateRequestSchema.parse(withLeg(ferry([[1, 2]], null), 'walk')).waypoints[0]?.fixed_leg).toMatchObject(
+ {
+ minutes: null,
+ },
+ );
+ // Two boats on one leg with a walk between them: each stretch is kept on its own.
+ const twice = ferry([
+ [0, 1],
+ [2, 3],
+ ]);
+ expect(tourCreateRequestSchema.parse(withLeg(twice, 'walk')).waypoints[0]?.fixed_leg).toEqual(twice);
});
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(
+ 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/);
+ expect(() => tourCreateRequestSchema.parse(withLeg(ferry([[2, 1]]), 'walk'))).toThrow(/crossing runs between/);
+ expect(() => tourCreateRequestSchema.parse(withLeg(ferry([[1, 4]]), 'walk'))).toThrow(/crossing runs between/);
+ const overlapping = ferry([
+ [0, 2],
+ [1, 3],
+ ]);
+ expect(() => tourCreateRequestSchema.parse(withLeg(overlapping, 'walk'))).toThrow(/crossing runs between/);
+ expect(() => tourCreateRequestSchema.parse(withLeg(ferry([]), 'walk'))).toThrow();
});
});
diff --git a/shared/src/tours/tours.schema.ts b/shared/src/tours/tours.schema.ts
index f4ebc5d5c..7d54f855d 100644
--- a/shared/src/tours/tours.schema.ts
+++ b/shared/src/tours/tours.schema.ts
@@ -307,6 +307,12 @@ export const tourListItemSchema = tourSchema.extend({
station_stay_minutes: z.number().int().nonnegative().nullable().optional(),
/** CW-02: how many of a city walk's stations have no stay entered yet; null for any other type. */
station_stays_unknown: z.number().int().nonnegative().nullable().optional(),
+ /**
+ * CW-12: the minutes a city walk's ferry legs take by boat, never part of
+ * its walking time; null while the router gave one of them no time, absent
+ * for a walk without any.
+ */
+ walk_ferry_minutes: z.number().int().nonnegative().nullable().optional(),
/**
* CW-11: a tour saved with its points only, its way not planned yet (a city
* walk an assistant created). The planner plans the way when the tour is
@@ -368,6 +374,8 @@ 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;
+/** The most stretches by boat one ferry leg keeps; a leg between two stations rarely boards more than twice. */
+const FERRY_LEG_MAX_CROSSINGS = 20;
const fixedLegGeometrySchema = z
.array(z.tuple([z.number().finite().min(-90).max(90), z.number().finite().min(-180).max(180)]))
@@ -425,9 +433,15 @@ export const tourFixedLegSchema = z.discriminatedUnion('kind', [
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. */
+ /**
+ * Each stretch of the line by boat, as the indices of the points the boat
+ * leaves from and lands at, in order; the walk between two of them stays walking.
+ */
+ crossings: z
+ .array(z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()]))
+ .min(1)
+ .max(FERRY_LEG_MAX_CROSSINGS),
+ /** The time of all its crossings as the router gave it; null when it gave none for one of them. */
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),
@@ -605,11 +619,12 @@ 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)) {
+ if (leg.kind === 'ferry' && !crossingsInOrder(leg.crossings, 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',
+ path: ['waypoints', index, 'fixed_leg', 'crossings'],
+ message:
+ 'a crossing runs between two points of its leg, the first before the second, after the one before it',
});
}
}
@@ -635,6 +650,16 @@ export type TourCreateInput = z.input<typeof tourCreateRequestSchema>;
type Issue = { path: Array<string | number>; message: string };
+function crossingsInOrder(crossings: ReadonlyArray<readonly unknown[]>, points: number): boolean {
+ let after = 0;
+ for (const crossing of crossings) {
+ const [from, to] = [Number(crossing[0]), Number(crossing[1])];
+ if (!(from >= after && from < to && to < points)) return false;
+ after = to;
+ }
+ return true;
+}
+
/** How a refusal names each type. */
const TYPE_NAMED: Record<PlannableTourType, string> = {
kayak: 'a paddle tour',
diff --git a/shared/src/tours/walk-ferry.spec.ts b/shared/src/tours/walk-ferry.spec.ts
index b13c48ff6..41764463a 100644
--- a/shared/src/tours/walk-ferry.spec.ts
+++ b/shared/src/tours/walk-ferry.spec.ts
@@ -1,5 +1,5 @@
-import { boatSpansOf, ferryCrossingsOf } from './walk-ferry';
-import { stationShares } from './walk-hours';
+import { boatSpansOf, boatsAlong, ferryCrossingsOf, ferryLegsOf, walkFerryMinutesOf } from './walk-ferry';
+import { stationArrivals, stationShares } from './walk-hours';
import { describe, expect, it } from 'vitest';
@@ -27,7 +27,7 @@ describe('ferry legs of a city walk (CW-12)', () => {
fixed_leg: {
kind: 'ferry',
geometry: line.map(([lat, lng]): [number, number] => [lat, lng]),
- crossing: [1, 2],
+ crossings: [[1, 2]],
minutes: 7,
walk_minutes: 2,
},
@@ -58,6 +58,50 @@ describe('ferry legs of a city walk (CW-12)', () => {
).toEqual([]);
});
+ it('keeps two stretches by boat of one leg apart, the walk between them walking', () => {
+ const points = [
+ {
+ fixed_leg: {
+ kind: 'ferry' as const,
+ geometry: line.map(([lat, lng]): [number, number] => [lat, lng]),
+ crossings: [
+ [0, 1],
+ [2, 3],
+ ] as [number, number][],
+ minutes: 9,
+ walk_minutes: 2,
+ },
+ },
+ ];
+ expect(ferryCrossingsOf(points)).toHaveLength(2);
+ expect(ferryLegsOf(points)[0]?.minutes).toBe(9);
+ expect(walkFerryMinutesOf(points)).toBe(9);
+ expect(walkFerryMinutesOf([{}])).toBeUndefined();
+ expect(boatsAlong(line, ferryLegsOf(points))).toEqual({
+ spans: [
+ [0, 1],
+ [2, 3],
+ ],
+ landings: [{ at: 3, minutes: 9 }],
+ });
+ });
+
+ it('reaches a stop after the boat lands that many minutes later, and only as a lower bound without its time', () => {
+ const stops = [
+ { lat: 45.4296, lng: 12.3264, stayMinutes: 0 },
+ { lat: 45.4275, lng: 12.3282, stayMinutes: 0 },
+ { lat: 45.4268, lng: 12.33, stayMinutes: 0 },
+ ];
+ const boats = { spans: [[1, 2]] as Array<[number, number]>, landings: [{ at: 2, minutes: 12 }] };
+ const walked = stationArrivals(stops, line, 600, 20, { ...boats, landings: [] }) ?? [];
+ const crossed = stationArrivals(stops, line, 600, 20, boats) ?? [];
+ expect(crossed[0]).toEqual(walked[0]);
+ expect(crossed[1]?.arrival).toBe((walked[1]?.arrival ?? 0) + 12);
+ expect(crossed[2]?.arrival).toBe((walked[2]?.arrival ?? 0) + 12);
+ const unknown = stationArrivals(stops, line, 600, 20, { ...boats, landings: [{ at: 2, minutes: null }] }) ?? [];
+ expect(unknown.map((arrival) => arrival.atLeast)).toEqual([false, true, true]);
+ });
+
it('counts no distance along a stretch crossed by boat when sharing a walk out', () => {
const stops = [
{ lat: 45.4296, lng: 12.3264 },
diff --git a/shared/src/tours/walk-ferry.ts b/shared/src/tours/walk-ferry.ts
index 836b61e55..acf7d208d 100644
--- a/shared/src/tours/walk-ferry.ts
+++ b/shared/src/tours/walk-ferry.ts
@@ -1,21 +1,52 @@
import type { TourFixedLeg } from './tours.schema';
+import type { WalkBoats } from './walk-hours';
type LinePoint = readonly [number, number, ...number[]];
+type FerryLeg = Extract<TourFixedLeg, { kind: 'ferry' }>;
/** 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]>> {
+/** CW-12: a ferry leg of a city walk as its times read it: the boat parts of its line in order, and their minutes. */
+export interface WalkFerryLeg {
+ crossings: Array<Array<[number, number]>>;
+ /** Null where the router gave the boat no time. */
+ minutes: number | null;
+}
+
+function crossingLines(leg: FerryLeg): Array<Array<[number, number]>> {
+ return leg.crossings.map(([from, to]) =>
+ leg.geometry.slice(from, to + 1).map(([lat, lng]): [number, number] => [lat, lng]),
+ );
+}
+
+/** CW-12: the ferry legs of a city walk, in the order of its legs. */
+export function ferryLegsOf(points: ReadonlyArray<{ fixed_leg?: TourFixedLeg | null }>): WalkFerryLeg[] {
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])];
+ return leg?.kind === 'ferry' ? [{ crossings: crossingLines(leg), minutes: leg.minutes }] : [];
});
}
+/** CW-12: the boat part of each ferry leg of a city walk, each stretch by boat on its own, in the order of the legs. */
+export function ferryCrossingsOf(
+ points: ReadonlyArray<{ fixed_leg?: TourFixedLeg | null }>,
+): Array<Array<[number, number]>> {
+ return ferryLegsOf(points).flatMap((leg) => leg.crossings);
+}
+
+/**
+ * CW-12: the minutes a city walk spends on the boat: the sum over its ferry
+ * legs, null while one of them has no time, undefined for a walk without any.
+ */
+export function walkFerryMinutesOf(
+ points: ReadonlyArray<{ fixed_leg?: TourFixedLeg | null }>,
+): number | null | undefined {
+ const legs = ferryLegsOf(points);
+ if (legs.length === 0) return undefined;
+ return legs.every((leg) => leg.minutes !== null) ? legs.reduce((sum, leg) => sum + (leg.minutes ?? 0), 0) : null;
+}
+
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];
@@ -24,6 +55,20 @@ function indexOfPoint(line: ReadonlyArray<LinePoint>, point: readonly [number, n
return -1;
}
+/** One crossing's span on the line, searched from `from` on; null where its points are not found in turn. */
+function spanOf(
+ line: ReadonlyArray<LinePoint>,
+ crossing: ReadonlyArray<readonly [number, number]>,
+ from: number,
+): [number, number] | null {
+ const first = crossing[0];
+ const last = crossing[crossing.length - 1];
+ if (!first || !last || crossing.length < 2) return null;
+ const start = indexOfPoint(line, first, from);
+ const end = start < 0 ? -1 : indexOfPoint(line, last, start + 1);
+ return end < 0 ? null : [start, end];
+}
+
/**
* 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
@@ -34,17 +79,36 @@ export function boatSpansOf(
line: ReadonlyArray<LinePoint>,
crossings: ReadonlyArray<ReadonlyArray<readonly [number, number]>>,
): Array<[number, number]> {
- const spans: Array<[number, number]> = [];
+ return boatsAlong(
+ line,
+ crossings.map((crossing) => ({ crossings: [crossing], minutes: null })),
+ ).spans;
+}
+
+/**
+ * CW-12: a walk's ferry legs found on its saved line: the spans by boat, and
+ * for each leg the point its last boat lands at with the minutes of its boats,
+ * so a stop after it is reached that much later. A leg none of whose
+ * crossings is found adds no time rather than a guessed one.
+ */
+export function boatsAlong(
+ line: ReadonlyArray<LinePoint>,
+ legs: ReadonlyArray<
+ Pick<WalkFerryLeg, 'minutes'> & { crossings: ReadonlyArray<ReadonlyArray<readonly [number, number]>> }
+ >,
+): WalkBoats {
+ const boats: WalkBoats = { spans: [], landings: [] };
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;
+ for (const leg of legs) {
+ let landed = -1;
+ for (const crossing of leg.crossings) {
+ const span = spanOf(line, crossing, from);
+ if (!span) continue;
+ boats.spans.push(span);
+ landed = span[1];
+ from = span[1];
+ }
+ if (landed >= 0) boats.landings.push({ at: landed, minutes: leg.minutes });
}
- return spans;
+ return boats;
}
diff --git a/shared/src/tours/walk-hours.ts b/shared/src/tours/walk-hours.ts
index 1c056d833..4817a2844 100644
--- a/shared/src/tours/walk-hours.ts
+++ b/shared/src/tours/walk-hours.ts
@@ -323,17 +323,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. 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.
+ * CW-12: a walk's crossings by boat along its route: the spans the boat runs,
+ * from the index it leaves at to the one it lands at, and for each ferry leg
+ * the index its last boat lands at with the minutes of its boats (null where
+ * the router gave none).
*/
-export function stationShares(
+export interface WalkBoats {
+ spans: Array<[number, number]>;
+ landings: Array<{ at: number; minutes: number | null }>;
+}
+
+/** Each stop's share of the walk with the index of the route's point it is passed at. */
+function walkedAlong(
stops: readonly WalkStop[],
route: readonly RoutePoint[],
- boatSpans: ReadonlyArray<readonly [number, number]> = [],
-): number[] | null {
+ boatSpans: ReadonlyArray<readonly [number, number]>,
+): { shares: number[]; indices: number[] } | null {
if (route.length < 2) return null;
const flat = flatRoute(route);
const byBoat = (i: number) => boatSpans.some(([from, to]) => i > from && i <= to);
@@ -344,29 +349,53 @@ export function stationShares(
}
const total = along[along.length - 1] || 1;
const indices = passedAt(stops, flat, Math.cos((route[0]?.[0] ?? 0) * RAD));
- return indices.map((index) => (along[index] ?? 0) / total);
+ return { shares: indices.map((index) => (along[index] ?? 0) / total), indices };
+}
+
+/**
+ * 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. 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[],
+ boatSpans: ReadonlyArray<readonly [number, number]> = [],
+): number[] | null {
+ return walkedAlong(stops, route, boatSpans)?.shares ?? null;
}
/**
* The estimated arrival at each stop, in minutes after midnight and whole: the
* start, the walking time shared out by how far along the route the stop is
* passed, and the stays before it. A stay not known counts as nothing and
- * makes every later arrival a lower bound; a stay of 0 is known. Null when the
- * start, the walking time or the route is not known.
+ * makes every later arrival a lower bound; a stay of 0 is known. A crossing by
+ * boat (CW-12) takes no share of the walking time; a stop after it lands is
+ * reached its minutes later, a lower bound where the boat's time is not known.
+ * Null when the start, the walking time or the route is not known.
*/
export function stationArrivals(
stops: readonly WalkStop[],
route: readonly RoutePoint[],
start: number | null,
walkingMinutes: number | null,
+ boats: Readonly<WalkBoats> = { spans: [], landings: [] },
): WalkArrival[] | null {
if (start === null || walkingMinutes === null) return null;
- const shares = stationShares(stops, route);
- if (!shares) return null;
+ const walked = walkedAlong(stops, route, boats.spans);
+ if (!walked) return null;
let stays = 0;
let unknown = false;
return stops.map((stop, index) => {
- const arrival = { arrival: Math.round(start + walkingMinutes * (shares[index] ?? 0) + stays), atLeast: unknown };
+ const at = walked.indices[index] ?? 0;
+ const landed = boats.landings.filter((landing) => landing.at <= at);
+ const boat = landed.reduce((sum, landing) => sum + (landing.minutes ?? 0), 0);
+ const arrival = {
+ arrival: Math.round(start + walkingMinutes * (walked.shares[index] ?? 0) + boat + stays),
+ atLeast: unknown || landed.some((landing) => landing.minutes === null),
+ };
if (stop.stayMinutes == null) unknown = true;
else stays += stop.stayMinutes;
return arrival;