Files
TREK/shared/src/tours/tours.schema.ts
T

243 lines
9.5 KiB
TypeScript

import { z } from 'zod';
/**
* Tours contracts — the generalisation of "hike" into a domain of self-contained,
* single-day, non-motorized activities that follow a track (hike, bike, run, ski,
* kayak, city walk, food tour, ...). Tour types use a controlled key list.
*
* Isolated bounded context:
* no columns on `places`/`days`/`users`. A tour is a Place (route_geometry reused
* as-is) plus a day_assignments row (reused as-is, `assignPlaceToDay`) plus this
* facet table keyed by place_id. Boundary vs. Road-Trip: Tours = non-motorized +
* single-day, Road-Trip = motorized + multi-day.
*/
export const tourTypeKeySchema = z.enum(['hike', 'bike', 'run', 'ski', 'kayak', 'walk', 'food']);
export type TourTypeKey = z.infer<typeof tourTypeKeySchema>;
export const tourMaxHikingDifficultySchema = z.number().int().min(1).max(6);
export type TourMaxHikingDifficulty = z.infer<typeof tourMaxHikingDifficultySchema>;
/** Tours are single-day activities, so a planned total is bounded to 24 hours. */
export const MAX_PLANNED_TOUR_DURATION_MINUTES = 24 * 60;
export const plannedTourDurationMinutesSchema = z
.number()
.int()
.min(0)
.max(MAX_PLANNED_TOUR_DURATION_MINUTES)
.nullable();
export const tourWebsiteSchema = z
.string()
.trim()
.max(500)
.url()
.superRefine((value, ctx) => {
let parsed: URL;
try {
parsed = new URL(value);
} catch {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'must be a valid URL' });
return;
}
if (parsed.protocol !== 'https:') {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'must be an HTTPS URL' });
}
if (parsed.username || parsed.password) {
ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'must not contain URL credentials' });
}
})
.transform((value) => new URL(value).toString());
export const tourTypeSchema = z.object({
key: tourTypeKeySchema,
label_key: z.string(),
icon: z.string(),
color: z.string(),
/** NULL = no engine routing (e.g. kayak — manual waypoints only). */
routing_profile: z.string().nullable(),
is_sport: z.boolean(),
enabled: z.boolean(),
sort_order: z.number().int(),
});
export type TourType = z.infer<typeof tourTypeSchema>;
export const tourSchema = z.object({
place_id: z.number().int().positive(),
tour_type: tourTypeKeySchema,
distance: z.number().nullable(),
elevation_gain: z.number().nullable(),
elevation_loss: z.number().nullable(),
duration: z.number().nullable(),
planned_duration_minutes: plannedTourDurationMinutesSchema.optional(),
break_additional_minutes: plannedTourDurationMinutesSchema.optional(),
difficulty: z.string().nullable(),
// Nullable reference to a tour in wanderer.
wanderer_ref: z.string().nullable(),
match_confidence: z.number().min(0).max(1).nullable(),
// NULL for a GPX import: the track carries no difficulty. A drawn tour always has one.
max_hiking_difficulty: tourMaxHikingDifficultySchema.nullable(),
});
export type Tour = z.infer<typeof tourSchema>;
export const tourTypeListResponseSchema = z.object({
tourTypes: z.array(tourTypeSchema),
});
export type TourTypeListResponse = z.infer<typeof tourTypeListResponseSchema>;
/**
* A tour as shown in the Tours selection list: the `tours` facet joined with
* its owning place's name, plus
* two read-model-only fields the list needs and the facet table does not carry:
* `planned` (whether the place already has a day_assignments row — the same
* "attach only" fact PlacesSidebar's All/Unplanned/Planned filter uses) and
* `caution` (derived from match_confidence < 0.5, the "use with caution"
* threshold — surfaced as a badge instead of making the client re-derive it).
*/
export const tourListItemSchema = tourSchema.extend({
name: z.string(),
description: z.string().nullable().optional(),
website: z.string().nullable().optional(),
planned: z.boolean(),
caution: z.boolean(),
/** Read-model provenance signal: planner-authored tours persist routing controls; GPX imports do not. */
has_waypoints: z.boolean().optional(),
});
export type TourListItem = z.infer<typeof tourListItemSchema>;
export const tourListResponseSchema = z.object({
tours: z.array(tourListItemSchema),
});
export type TourListResponse = z.infer<typeof tourListResponseSchema>;
export const tourWaypointRoleSchema = z.enum(['start', 'via', 'end']);
export type TourWaypointRole = z.infer<typeof tourWaypointRoleSchema>;
/** The most points a fixed leg may carry: a long via ferrata is a few hundred. */
export const TOUR_FIXED_LEG_MAX_POINTS = 5000;
/** How far a fixed leg's ends may lie from the waypoints it joins, in metres. */
export const TOUR_FIXED_LEG_END_TOLERANCE_M = 60;
/**
* A leg the router does not plan: the line from this waypoint to the next is
* taken as it stands. Today that is a via ferrata put onto the tour from the
* map, whose own line from OpenStreetMap the tour follows, since a router
* walks around a ferrata wherever it can.
*/
export const tourFixedLegSchema = z.object({
kind: z.literal('ferrata'),
/** The OSM way or group the line came from, `way/<id>` style. */
ref: z.string().trim().min(1).max(64),
name: z.string().trim().max(255).nullable(),
geometry: z
.array(z.tuple([z.number().finite().min(-90).max(90), z.number().finite().min(-180).max(180)]))
.min(2)
.max(TOUR_FIXED_LEG_MAX_POINTS),
});
export type TourFixedLeg = z.infer<typeof tourFixedLegSchema>;
export const tourWaypointSchema = z.object({
lat: z.number().finite().min(-90).max(90),
lng: z.number().finite().min(-180).max(180),
role: tourWaypointRoleSchema,
sequence: z.number().int().nonnegative(),
/** The leg to the next waypoint as a fixed line; absent or null for a routed one. */
fixed_leg: tourFixedLegSchema.nullable().optional(),
});
export type TourWaypoint = z.infer<typeof tourWaypointSchema>;
/**
* Metres between two `[lat, lng]` points, close enough at the length of a
* leg's end gap. Read as plain arrays: a workspace compiled without strict
* mode sees the schema's tuples as "maybe two numbers".
*/
function fixedLegGapM(a: readonly unknown[], b: readonly unknown[]): number {
const [aLat, aLng, bLat, bLng] = [Number(a[0]), Number(a[1]), Number(b[0]), Number(b[1])];
const rad = Math.PI / 180;
const x = (bLng - aLng) * rad * Math.cos(((aLat + bLat) / 2) * rad);
const y = (bLat - aLat) * rad;
return Math.hypot(x, y) * 6_371_000;
}
const enrichedRoutePointSchema = z.tuple([
z.number().finite().min(-90).max(90),
z.number().finite().min(-180).max(180),
z.number().finite(),
]);
export const tourCreateRequestSchema = z
.object({
name: z.string().trim().min(1).max(255),
tour_type: z.literal('hike').default('hike'),
route_geometry: z.array(enrichedRoutePointSchema).min(2),
waypoints: z.array(tourWaypointSchema).min(2),
max_hiking_difficulty: tourMaxHikingDifficultySchema.default(2),
duration_seconds: z.number().finite().nonnegative().nullable().optional(),
planned_duration_minutes: plannedTourDurationMinutesSchema.optional(),
break_additional_minutes: plannedTourDurationMinutesSchema.optional(),
description: z.string().trim().max(2000).nullable().optional(),
website: tourWebsiteSchema.nullable().optional(),
})
.superRefine((value, ctx) => {
if (
value.planned_duration_minutes == null &&
value.duration_seconds != null &&
value.break_additional_minutes != null &&
Math.round(value.duration_seconds / 60) + value.break_additional_minutes > MAX_PLANNED_TOUR_DURATION_MINUTES
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['break_additional_minutes'],
message: 'walking time plus breaks must be 1440 minutes or less unless a total is overridden',
});
}
value.waypoints.forEach((point, index) => {
const leg = point.fixed_leg;
const next = value.waypoints[index + 1];
if (leg) {
const first = leg.geometry[0];
const last = leg.geometry[leg.geometry.length - 1];
const joins =
!!next &&
!!first &&
!!last &&
fixedLegGapM(first, [point.lat, point.lng]) <= TOUR_FIXED_LEG_END_TOLERANCE_M &&
fixedLegGapM(last, [next.lat, next.lng]) <= TOUR_FIXED_LEG_END_TOLERANCE_M;
if (!joins) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['waypoints', index, 'fixed_leg'],
message: `Waypoint ${index}'s fixed leg must run from it to the next waypoint`,
});
}
}
const expectedRole: TourWaypointRole =
index === 0 ? 'start' : index === value.waypoints.length - 1 ? 'end' : 'via';
if (point.sequence !== index || point.role !== expectedRole) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['waypoints', index],
message: `Waypoint ${index} must be ${expectedRole} with sequence ${index}`,
});
}
});
});
export type TourCreateRequest = z.infer<typeof tourCreateRequestSchema>;
export const tourCreateResponseSchema = z.object({
tour: tourListItemSchema,
waypoints: z.array(tourWaypointSchema),
});
export type TourCreateResponse = z.infer<typeof tourCreateResponseSchema>;
/** Saved-tour editor payload: list metadata plus its persisted routing controls. */
export const tourDetailResponseSchema = tourCreateResponseSchema;
export type TourDetailResponse = z.infer<typeof tourDetailResponseSchema>;
export const tourImportGpxResponseSchema = z.object({
tours: z.array(tourListItemSchema),
caution: z.boolean(),
skipped: z.number().int(),
});
export type TourImportGpxResponse = z.infer<typeof tourImportGpxResponseSchema>;