feat(tours): bike tours in the contract and on the server (BIK-01 to BIK-06, RTE-01)

A tour can be a bike tour with a routing profile (touring, road, gravel,
mtb), stored per tour by a new migration. The server grades the ways of a
mountain bike route from OpenStreetMap (mtb:scale) through one shared
Overpass client, offers CyclOSM behind its own admin switch, and exports a
bike tour's GPX with the activity of its profile. A hike's route choices
are now exactly the three the card names: steep climbs, steps and ferries.
This commit is contained in:
Maurice
2026-10-19 21:33:40 +02:00
parent c3229afcba
commit adcaca3c5f
126 changed files with 3112 additions and 237 deletions
+16 -8
View File
@@ -1,4 +1,9 @@
import { paddleBoatTypeSchema, paddleWaterContextSchema, plannableTourTypeSchema } from './tours.schema';
import {
bikeProfileSchema,
paddleBoatTypeSchema,
paddleWaterContextSchema,
plannableTourTypeSchema,
} from './tours.schema';
import { z } from 'zod';
@@ -33,21 +38,24 @@ export type TourGpxPreviewResponse = z.infer<typeof tourGpxPreviewResponseSchema
/**
* The fields of the multipart import beside the file, as strings the way a
* form sends them. Left out, the import is a hike, as it always was; a paddle
* import names its boat and water like a planned paddle tour does.
* import names its boat and water, and a bike import its profile, like a
* planned tour of that type does.
*/
export const tourGpxImportFieldsSchema = z
.object({
tour_type: plannableTourTypeSchema.default('hike'),
bike_profile: bikeProfileSchema.optional(),
boat_type: paddleBoatTypeSchema.optional(),
water_context: paddleWaterContextSchema.optional(),
})
.superRefine((value, ctx) => {
const paddle = value.tour_type === 'kayak';
for (const field of ['boat_type', 'water_context'] as const) {
if (paddle && value[field] === undefined)
ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message: `a paddle import needs ${field}` });
if (!paddle && value[field] !== undefined)
ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message: `${field} belongs to a paddle import` });
const owners = { bike_profile: 'bike', boat_type: 'kayak', water_context: 'kayak' } as const;
for (const [field, owner] of Object.entries(owners) as Array<[keyof typeof owners, string]>) {
const name = owner === 'bike' ? 'a bike import' : 'a paddle import';
if (value.tour_type === owner && value[field] === undefined)
ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message: `${name} needs ${field}` });
if (value.tour_type !== owner && value[field] !== undefined)
ctx.addIssue({ code: z.ZodIssueCode.custom, path: [field], message: `${field} belongs to ${name}` });
}
});
export type TourGpxImportFields = z.infer<typeof tourGpxImportFieldsSchema>;
@@ -37,7 +37,7 @@ describe('tour POI search contracts (PLN-02)', () => {
],
}).success,
).toBe(false);
expect(tourPoiSearchRequestSchema.safeParse({ ...ok, tour_type: 'bike' }).success).toBe(false);
expect(tourPoiSearchRequestSchema.safeParse({ ...ok, tour_type: 'run' }).success).toBe(false);
expect(tourPoiSearchRequestSchema.safeParse({ ...ok, add: true }).success).toBe(false);
});
+3 -1
View File
@@ -8,7 +8,7 @@ import { z } from 'zod';
* the line as drawn, never a detour someone walked or paddled.
*/
/** What can be looked for along a tour on foot or on the water. */
/** What can be looked for along a tour on foot, by bike or on the water. */
export const TOUR_POI_CATEGORIES = [
'viewpoint',
'peak',
@@ -21,6 +21,7 @@ export const TOUR_POI_CATEGORIES = [
'sights',
'slipway',
'boat_rental',
'bike_repair',
] as const;
export const tourPoiCategorySchema = z.enum(TOUR_POI_CATEGORIES);
export type TourPoiCategory = z.infer<typeof tourPoiCategorySchema>;
@@ -28,6 +29,7 @@ export type TourPoiCategory = z.infer<typeof tourPoiCategorySchema>;
/** The categories each planned tour type offers, the most asked first. */
export const TOUR_POI_CATEGORIES_BY_TYPE: Record<PlannableTourType, readonly TourPoiCategory[]> = {
hike: ['viewpoint', 'shelter', 'drinking_water', 'food', 'peak', 'toilets', 'picnic', 'campsite', 'sights'],
bike: ['drinking_water', 'bike_repair', 'food', 'viewpoint', 'toilets', 'shelter', 'picnic', 'campsite', 'sights'],
kayak: ['slipway', 'boat_rental', 'drinking_water', 'food', 'toilets', 'picnic', 'campsite', 'shelter'],
};
@@ -0,0 +1,49 @@
import { z } from 'zod';
/**
* BIK-05: the trail grades OpenStreetMap carries for the ways a mountain bike
* tour runs on, asked for by the ways' ids. A read: nothing about the tour
* changes. A way without a grade is unknown, never easy; a way that could not
* be asked about is named, so the planner can say so.
*/
/** The most ways one question names; a longer tour asks for its first ones. */
export const TOUR_TRAIL_GRADE_MAX_WAYS = 2000;
export const tourTrailGradeRequestSchema = z
.object({
way_ids: z.array(z.number().int().positive()).min(1).max(TOUR_TRAIL_GRADE_MAX_WAYS),
})
.strict();
export type TourTrailGradeRequest = z.infer<typeof tourTrailGradeRequestSchema>;
/**
* One way's grades as OpenStreetMap tags them, read to the scale's own steps:
* `mtb:scale` 0 to 6 (a + or - kept), `mtb:scale:uphill` 0 to 5,
* `mtb:scale:imba` 0 to 4. Null where the way has no such tag or one that is
* no step of the scale.
*/
export const tourTrailGradeSchema = z.object({
id: z.number().int().positive(),
mtb_scale: z
.string()
.regex(/^[0-6][+-]?$/)
.nullable(),
mtb_scale_uphill: z
.string()
.regex(/^[0-5][+-]?$/)
.nullable(),
mtb_scale_imba: z
.string()
.regex(/^[0-4]$/)
.nullable(),
});
export type TourTrailGrade = z.infer<typeof tourTrailGradeSchema>;
export const tourTrailGradeResponseSchema = z.object({
/** The ways asked about that carry at least one grade. */
ways: z.array(tourTrailGradeSchema),
/** The ways the data could not be asked about this time: their grade is unknown, not absent. */
unanswered: z.array(z.number().int().positive()),
});
export type TourTrailGradeResponse = z.infer<typeof tourTrailGradeResponseSchema>;
+74 -4
View File
@@ -1,4 +1,7 @@
import { tourGpxImportFieldsSchema } from './tour-gpx-import.schema';
import {
BIKE_PROFILES,
HIKING_PREFERENCE_KEYS,
hikingPreferencesOf,
MAX_PADDLE_SPEED_KMH,
MAX_PLANNED_TOUR_DURATION_MINUTES,
@@ -275,7 +278,7 @@ describe('Tours paddle type', () => {
it('refuses boat fields on a hike, and a type nobody can plan yet', () => {
expect(() => tourCreateRequestSchema.parse({ ...baseRequest, boat_type: 'sup' })).toThrow(/paddle tour/);
expect(() => tourCreateRequestSchema.parse({ ...baseRequest, paddle_speed_kmh: 4 })).toThrow(/paddle tour/);
expect(() => tourCreateRequestSchema.parse({ ...baseRequest, tour_type: 'bike' })).toThrow();
expect(() => tourCreateRequestSchema.parse({ ...baseRequest, tour_type: 'run' })).toThrow();
});
it('suggests 4 km/h for kayak, canoe and SUP, and nothing for any other boat', () => {
@@ -318,17 +321,23 @@ describe('hiking preferences (MF-08)', () => {
};
it('keeps only the preferences switched on, and none as null', () => {
expect(hikingPreferencesOf({ avoid_steps: true, shortest: false })).toEqual({ avoid_steps: true });
expect(hikingPreferencesOf({ avoid_steps: true, avoid_climbs: false })).toEqual({ avoid_steps: true });
expect(hikingPreferencesOf({ avoid_steps: false })).toBeNull();
expect(hikingPreferencesOf(null)).toBeNull();
const parsed = tourCreateRequestSchema.parse({
...hike,
hiking_preferences: { prefer_paths: true, avoid_ferries: false },
hiking_preferences: { avoid_climbs: true, avoid_ferries: false },
});
expect(hikingPreferencesOf(parsed.hiking_preferences)).toEqual({ prefer_paths: true });
expect(hikingPreferencesOf(parsed.hiking_preferences)).toEqual({ avoid_climbs: true });
expect(tourCreateRequestSchema.parse(hike).hiking_preferences).toBeUndefined();
});
it('RTE-01: offers exactly the three preferences, and refuses a key it does not know', () => {
expect(HIKING_PREFERENCE_KEYS).toEqual(['avoid_climbs', 'avoid_steps', 'avoid_ferries']);
const unknown = tourCreateRequestSchema.safeParse({ ...hike, hiking_preferences: { shortest: true } });
expect(unknown.success).toBe(false);
});
it('refuses a preference it does not know, and any on a paddle tour', () => {
expect(tourCreateRequestSchema.safeParse({ ...hike, hiking_preferences: { avoid_hills: true } }).success).toBe(
false,
@@ -342,3 +351,64 @@ describe('hiking preferences (MF-08)', () => {
);
});
});
describe('bike tours (BIK-01 to BIK-04)', () => {
const bike = { ...baseRequest, tour_type: 'bike' as const, bike_profile: 'gravel' as const };
const ferrata = {
kind: 'ferrata' as const,
ref: 'way/1',
name: null,
geometry: [
[48, 11],
[48.01, 11.02],
],
};
it('saves a bike tour with its one profile and nothing of a hike or a paddle tour', () => {
expect(BIKE_PROFILES).toEqual(['touring', 'road', 'gravel', 'mtb']);
expect(tourCreateRequestSchema.parse(bike)).toMatchObject({
tour_type: 'bike',
bike_profile: 'gravel',
max_hiking_difficulty: null,
});
});
it('refuses a bike tour without a profile, with a hike or a paddler field, or over a via ferrata', () => {
expect(() => tourCreateRequestSchema.parse({ ...bike, bike_profile: null })).toThrow(/bike profile/);
expect(() => tourCreateRequestSchema.parse({ ...bike, bike_profile: 'ebike' })).toThrow();
expect(() => tourCreateRequestSchema.parse({ ...bike, max_hiking_difficulty: 3 })).toThrow(/hiking difficulty/);
expect(() => tourCreateRequestSchema.parse({ ...bike, hiking_preferences: { avoid_steps: true } })).toThrow(
/hiking preferences/,
);
expect(() => tourCreateRequestSchema.parse({ ...bike, boat_type: 'sup' })).toThrow(/paddle tour/);
const overFerrata = {
...bike,
waypoints: [{ ...bike.waypoints[0], fixed_leg: ferrata }, bike.waypoints[1]],
};
expect(() => tourCreateRequestSchema.parse(overFerrata)).toThrow(/via ferrata/);
});
it('keeps a profile to a bike tour', () => {
expect(() => tourCreateRequestSchema.parse({ ...baseRequest, bike_profile: 'road' })).toThrow(/bike tour/);
const paddle = {
...baseRequest,
tour_type: 'kayak',
boat_type: 'kayak',
water_context: 'lake',
bike_profile: 'mtb',
};
expect(() => tourCreateRequestSchema.parse(paddle)).toThrow(/bike tour/);
});
it('imports a GPX file as a bike tour only with its profile, and a profile only for one', () => {
expect(tourGpxImportFieldsSchema.parse({ tour_type: 'bike', bike_profile: 'road' })).toMatchObject({
tour_type: 'bike',
bike_profile: 'road',
});
expect(tourGpxImportFieldsSchema.safeParse({ tour_type: 'bike' }).success).toBe(false);
expect(tourGpxImportFieldsSchema.safeParse({ bike_profile: 'road' }).success).toBe(false);
expect(
tourGpxImportFieldsSchema.safeParse({ tour_type: 'kayak', boat_type: 'sup', water_context: 'lake' }).success,
).toBe(true);
});
});
+64 -33
View File
@@ -27,11 +27,23 @@ export type TourTypeKey = z.infer<typeof tourTypeKeySchema>;
/**
* The types a tour can be planned, saved and imported as. `kayak` is the key
* the paddle tour has had in `tour_types` from the start; the app calls it a
* paddle tour, and the boat is a field of its own.
* paddle tour, and the boat is a field of its own. A bike tour (BIK-01) names
* its profile the same way.
*/
export const plannableTourTypeSchema = z.enum(['hike', 'kayak']);
export const plannableTourTypeSchema = z.enum(['hike', 'bike', 'kayak']);
export type PlannableTourType = z.infer<typeof plannableTourTypeSchema>;
/**
* BIK-01 to BIK-04: what a bike tour is ridden on, the one profile it is routed
* for. Touring/city keeps to paved ways, cycle paths and quiet roads; road
* keeps to asphalt; gravel takes gravel and farm tracks; mtb takes rough tracks
* as they come. Each asks the router for something else (see the client's
* bike routing for what was measured); none says a way is rideable or safe.
*/
export const BIKE_PROFILES = ['touring', 'road', 'gravel', 'mtb'] as const;
export const bikeProfileSchema = z.enum(BIKE_PROFILES);
export type BikeProfile = z.infer<typeof bikeProfileSchema>;
/** PAD-01: the one boat a paddle tour is planned for. */
export const paddleBoatTypeSchema = z.enum(['kayak', 'canoe', 'sup', 'other']);
export type PaddleBoatType = z.infer<typeof paddleBoatTypeSchema>;
@@ -60,24 +72,22 @@ export const tourMaxHikingDifficultySchema = z.number().int().min(1).max(6);
export type TourMaxHikingDifficulty = z.infer<typeof tourMaxHikingDifficultySchema>;
/**
* MF-08: what a hiker asks the router for besides the difficulty limit. Only
* preferences whose effect on the router was measured are offered; each is a
* weighting that gives way where there is no other path, never a ban, and
* none says anything about how hard the path is. A hike without any keeps
* null, which is what every tour saved before had.
* MF-08, RTE-01: what a hiker asks the router for besides the difficulty
* limit: steep climbs, steps and ferries, each avoided where there is a way
* round. Each is a weighting whose effect on the router was measured, never a
* ban, and none says anything about how hard the path is. A hike without any
* keeps null, which is what every tour saved before had.
*/
export const HIKING_PREFERENCE_KEYS = ['avoid_steps', 'avoid_ferries', 'prefer_paths', 'shortest'] as const;
export const HIKING_PREFERENCE_KEYS = ['avoid_climbs', 'avoid_steps', 'avoid_ferries'] as const;
export type HikingPreferenceKey = (typeof HIKING_PREFERENCE_KEYS)[number];
export const hikingPreferencesSchema = z
.object({
/** Gentler ways where there are some, even when they are longer. */
avoid_climbs: z.boolean().optional(),
/** Steps and stairs only where there is no way round. */
avoid_steps: z.boolean().optional(),
/** A ferry only where there is no way round over land. */
avoid_ferries: z.boolean().optional(),
/** Footpaths of their own over roads and their pavements, where there are some. */
prefer_paths: z.boolean().optional(),
/** The way chosen by its length, not by the time it takes. */
shortest: z.boolean().optional(),
})
.strict();
export type HikingPreferences = z.infer<typeof hikingPreferencesSchema>;
@@ -151,6 +161,8 @@ export const tourSchema = z.object({
hiking_preferences: hikingPreferencesSchema.nullable().optional(),
/** The import (a GPX file, a wanderer snapshot) this tour was planned from, while it is still in the trip. */
derived_from_place_id: z.number().int().positive().nullable().optional(),
/** BIK-01: a bike tour's profile; null for every other type. Absent in a list cached before it existed. */
bike_profile: bikeProfileSchema.nullable().optional(),
/** A paddle tour's boat and water; null for every other type. Absent in a list cached before they existed. */
boat_type: paddleBoatTypeSchema.nullable().optional(),
water_context: paddleWaterContextSchema.nullable().optional(),
@@ -327,6 +339,8 @@ export const tourCreateRequestSchema = z
max_hiking_difficulty: tourMaxHikingDifficultySchema.nullable().optional(),
/** MF-08, a hike's only: what it asks the router for besides its limit. */
hiking_preferences: hikingPreferencesSchema.nullable().optional(),
/** BIK-01, a bike tour's only, and its one requirement. */
bike_profile: bikeProfileSchema.nullable().optional(),
boat_type: paddleBoatTypeSchema.nullable().optional(),
water_context: paddleWaterContextSchema.nullable().optional(),
paddle_speed_kmh: paddleSpeedKmhSchema.nullable().optional(),
@@ -399,49 +413,66 @@ export type TourCreateRequest = z.infer<typeof tourCreateRequestSchema>;
/** What a client sends: the fields the server fills in may be left out. */
export type TourCreateInput = z.input<typeof tourCreateRequestSchema>;
type Issue = { path: Array<string | number>; message: string };
const PADDLE_FIELDS = [
'boat_type',
'water_context',
'paddle_speed_kmh',
'portage_speed_kmh',
'paddle_lake_style',
] as const;
/**
* What belongs to which type: a hike carries a routing limit and no boat; a
* paddle tour carries exactly one boat and its water, and no hiking limit.
* bike tour exactly one profile and nothing of a hike's or a paddler's; a
* paddle tour exactly one boat and its water, and no hiking limit.
*/
function tourTypeIssues(value: {
tour_type: PlannableTourType;
max_hiking_difficulty?: number | null;
hiking_preferences?: HikingPreferences | null;
bike_profile?: BikeProfile | null;
boat_type?: PaddleBoatType | null;
water_context?: PaddleWaterContext | null;
paddle_speed_kmh?: number | null;
portage_speed_kmh?: number | null;
paddle_lake_style?: PaddleLakeStyle | null;
waypoints?: ReadonlyArray<{ fixed_leg?: { kind: string } | null; lock?: unknown }>;
}): Array<{ path: Array<string | number>; message: string }> {
const issues: Array<{ path: Array<string | number>; message: string }> = [];
if (value.tour_type === 'kayak') {
}): Issue[] {
const issues: Issue[] = [];
const type = value.tour_type;
const named = type === 'kayak' ? 'a paddle tour' : type === 'bike' ? 'a bike tour' : 'a hike';
if (type === 'kayak') {
if (value.boat_type == null) issues.push({ path: ['boat_type'], message: 'a paddle tour needs a boat type' });
if (value.water_context == null)
issues.push({ path: ['water_context'], message: 'a paddle tour needs a water context' });
} else {
for (const field of PADDLE_FIELDS) {
if (value[field] != null) issues.push({ path: [field], message: `${field} belongs to a paddle tour` });
}
}
if (type === 'hike') {
if (value.max_hiking_difficulty === null)
issues.push({ path: ['max_hiking_difficulty'], message: 'a hike needs a hiking difficulty' });
} else {
if (value.max_hiking_difficulty != null)
issues.push({ path: ['max_hiking_difficulty'], message: 'a paddle tour has no hiking difficulty' });
issues.push({ path: ['max_hiking_difficulty'], message: `${named} has no hiking difficulty` });
if (hikingPreferencesOf(value.hiking_preferences) !== null)
issues.push({ path: ['hiking_preferences'], message: 'a paddle tour has no hiking preferences' });
return issues;
issues.push({ path: ['hiking_preferences'], message: `${named} has no hiking preferences` });
}
if (value.max_hiking_difficulty === null)
issues.push({ path: ['max_hiking_difficulty'], message: 'a hike needs a hiking difficulty' });
for (const field of [
'boat_type',
'water_context',
'paddle_speed_kmh',
'portage_speed_kmh',
'paddle_lake_style',
] as const) {
if (value[field] != null) issues.push({ path: [field], message: `${field} belongs to a paddle tour` });
}
// A portage and a lock are a paddler's: a hike carries no boat.
if (type === 'bike' && value.bike_profile == null)
issues.push({ path: ['bike_profile'], message: 'a bike tour needs a bike profile' });
if (type !== 'bike' && value.bike_profile != null)
issues.push({ path: ['bike_profile'], message: 'bike_profile belongs to a bike tour' });
// A portage and a lock are a paddler's; a via ferrata is climbed, never ridden.
(value.waypoints ?? []).forEach((point, index) => {
if (point.fixed_leg?.kind === 'portage')
if (type !== 'kayak' && point.fixed_leg?.kind === 'portage')
issues.push({ path: ['waypoints', index, 'fixed_leg'], message: 'a portage belongs to a paddle tour' });
if (point.lock != null)
if (type !== 'kayak' && point.lock != null)
issues.push({ path: ['waypoints', index, 'lock'], message: 'a lock belongs to a paddle tour' });
if (type === 'bike' && point.fixed_leg?.kind === 'ferrata')
issues.push({ path: ['waypoints', index, 'fixed_leg'], message: 'a bike tour has no via ferrata' });
});
return issues;
}