mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-25 22:27:32 +00:00
feat(tours): plan, create and change hikes on the server, for the assistant too
The hiking costing moves to shared, so the planner and the server ask the router the same way. The road trip router learns to plan a hike on foot with that costing (Valhalla only: OSRM knows no trail difficulty), to read heights along a line in chunks and to read the OSM ways a line follows, all through its one paced queue. A hike router builds on it: the way, its heights, distance, climb and DIN walking time, and the SAC grades of its stretches from the trail grade service, each part best effort. New MCP tools in HikePlanMcp, in the assistant's tours group: - propose_hike plans a hike without saving it. - create_hike saves a confirmed hike through the planner's own creation; a router that does not answer leaves it pending for the planner, a way that cannot be planned is refused and nothing is saved. - update_tour changes a saved hike against its revision, keeping linked stations and refusing what would silently drop drawn legs or stages. - import_tour_gpx takes a GPX file's text in as tours, like the import. Same permission checks as REST, broadcasts from the services. In the assistant a new hike or city walk is an "Add tour" card with its route and difficulty, undone through delete_place while the tour is untouched, and a hike being planned shows as a live step.
This commit is contained in:
@@ -220,6 +220,34 @@ function boxArea(value: unknown): BoxArea | null {
|
||||
return { type: 'bbox', south, west, north, east };
|
||||
}
|
||||
|
||||
/** How far the box round a hike's points reaches past them, in degrees, so points on one line still make a box. */
|
||||
const HIKE_BOX_MARGIN = 0.005;
|
||||
|
||||
/**
|
||||
* Where a hike is being planned: named by its goal, the last point after the
|
||||
* start that has a name, and the box round its points.
|
||||
*/
|
||||
function hikeLook(args: Row): { label: string | null; area: AssistantActivityArea | null } {
|
||||
const points = Array.isArray(args.waypoints) ? args.waypoints.map(recordOf) : [];
|
||||
const goal = points
|
||||
.slice(1)
|
||||
.map((point) => clipped(point.name, MAX_LABEL_CHARS))
|
||||
.filter((name): name is string => name !== null)
|
||||
.pop();
|
||||
const lats = points.map((point) => finite(point.lat)).filter(isLat);
|
||||
const lngs = points.map((point) => finite(point.lng)).filter(isLng);
|
||||
const area =
|
||||
lats.length === points.length && lngs.length === points.length && points.length > 0
|
||||
? boxArea({
|
||||
south: Math.min(...lats) - HIKE_BOX_MARGIN,
|
||||
west: Math.min(...lngs) - HIKE_BOX_MARGIN,
|
||||
north: Math.max(...lats) + HIKE_BOX_MARGIN,
|
||||
east: Math.max(...lngs) + HIKE_BOX_MARGIN,
|
||||
})
|
||||
: null;
|
||||
return { label: goal ?? null, area };
|
||||
}
|
||||
|
||||
/** The name and the area of a step that looks somewhere, as its arguments say. */
|
||||
function lookOf(
|
||||
toolName: string,
|
||||
@@ -236,6 +264,7 @@ function lookOf(
|
||||
const centre = area ? nearbyName(card, (area.south + area.north) / 2, (area.west + area.east) / 2) : null;
|
||||
return { label: centre, area };
|
||||
}
|
||||
if (toolName === 'propose_hike') return hikeLook(args);
|
||||
if (toolName === 'search_place') {
|
||||
const bias = recordOf(args.locationBias);
|
||||
const area = pointArea(bias.lat, bias.lng, bias.radius, BIAS_RADIUS_M);
|
||||
|
||||
@@ -111,11 +111,13 @@ export function checkDenylist(names: Iterable<string>): string[] {
|
||||
export const ASSISTANT_TOOL_GROUPS: Readonly<Record<string, { about: string; controllers: readonly string[] }>> = {
|
||||
tours: {
|
||||
about:
|
||||
'Tours: hikes, bike tours, city walks, paddling and ski routes; plan, create, change and export them, ' +
|
||||
'their packing, the tour library and imports from Google Maps.',
|
||||
'Tours: hikes, bike tours, city walks, paddling and ski routes; plan, create, change and export them ' +
|
||||
'(hikes with their heights and SAC grades), their packing, the tour library and imports from GPX files ' +
|
||||
'and Google Maps.',
|
||||
controllers: [
|
||||
'ToursMcp',
|
||||
'CityWalkMcp',
|
||||
'HikePlanMcp',
|
||||
'TourChangeMcp',
|
||||
'TourChangeUndoMcp',
|
||||
'TourLibraryMcp',
|
||||
|
||||
@@ -96,6 +96,11 @@ export const ASSISTANT_WRITE_TOOLS: Readonly<Record<string, AssistantWriteTool>>
|
||||
create_budget_item: { verbKey: 'addBudgetItem', entity: 'budget' },
|
||||
update_budget_item: { verbKey: 'updateBudgetItem', entity: 'budget' },
|
||||
create_reservation: { verbKey: 'addReservation', entity: 'reservation' },
|
||||
// A tour is a place with a route: its id is its place's.
|
||||
create_hike: { verbKey: 'addTour', entity: 'tour' },
|
||||
create_city_walk: { verbKey: 'addTour', entity: 'tour' },
|
||||
update_tour: { verbKey: 'updateTour', entity: 'tour' },
|
||||
import_tour_gpx: { verbKey: 'importTour', entity: 'tour' },
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -195,6 +200,13 @@ function idIn(value: unknown, key: string): number | null {
|
||||
return typeof id === 'number' && Number.isInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
/** The place id of a tour a create answered with (`{ tour: { place_id } }`). */
|
||||
function tourIdIn(value: unknown): number | null {
|
||||
const tour = value && typeof value === 'object' ? (value as Record<string, unknown>).tour : undefined;
|
||||
const id = tour && typeof tour === 'object' ? (tour as Record<string, unknown>).place_id : undefined;
|
||||
return typeof id === 'number' && Number.isInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
function argId(args: ToolArgs, key: string): number | null {
|
||||
const id = args[key];
|
||||
return typeof id === 'number' && Number.isInteger(id) && id > 0 ? id : null;
|
||||
@@ -213,6 +225,15 @@ interface AssistantUndo {
|
||||
args: (args: ToolArgs, result: unknown) => ToolArgs | null;
|
||||
}
|
||||
|
||||
/** A created tour taken back with its place, which takes its route and points along. */
|
||||
const DELETE_CREATED_TOUR: AssistantUndo = {
|
||||
tool: 'delete_place',
|
||||
args: (_args, result) => {
|
||||
const placeId = tourIdIn(result);
|
||||
return placeId ? { placeId } : null;
|
||||
},
|
||||
};
|
||||
|
||||
export const ASSISTANT_UNDO_MAP: Readonly<Record<string, AssistantUndo>> = {
|
||||
create_place: {
|
||||
tool: 'delete_place',
|
||||
@@ -265,4 +286,6 @@ export const ASSISTANT_UNDO_MAP: Readonly<Record<string, AssistantUndo>> = {
|
||||
return itemId ? { itemId } : null;
|
||||
},
|
||||
},
|
||||
create_hike: DELETE_CREATED_TOUR,
|
||||
create_city_walk: DELETE_CREATED_TOUR,
|
||||
};
|
||||
|
||||
@@ -65,9 +65,29 @@ function placeUnchanged(result: Row, snapshot: TripSnapshot): boolean {
|
||||
return !plannedElsewhere && !referenced;
|
||||
}
|
||||
|
||||
/**
|
||||
* A created tour, unchanged and on no day: its place still has the name and
|
||||
* description it was created with, has not been written since it was made,
|
||||
* and nothing plans, books or pays for it. Every write of a tour's route or
|
||||
* name (a change over MCP, the planner's save, a rename) stamps its place's
|
||||
* `updated_at`, which the create left equal to `created_at`; the revision is
|
||||
* not in the snapshot. A tour planned on a day since is kept too.
|
||||
*/
|
||||
function tourUnchanged(result: Row, snapshot: TripSnapshot): boolean {
|
||||
const tour = recordOf(result.tour);
|
||||
const current = byId(rowsOf(recordOf(snapshot.places).places), tour.place_id);
|
||||
const untouched = typeof current?.created_at === 'string' && current.updated_at === current.created_at;
|
||||
return (
|
||||
untouched &&
|
||||
placeUnchanged({ place: { id: tour.place_id, name: tour.name, description: tour.description ?? null } }, snapshot)
|
||||
);
|
||||
}
|
||||
|
||||
const CHECKS: Readonly<Record<string, (result: Row, snapshot: TripSnapshot) => boolean>> = {
|
||||
create_place: placeUnchanged,
|
||||
create_and_assign_place: placeUnchanged,
|
||||
create_hike: tourUnchanged,
|
||||
create_city_walk: tourUnchanged,
|
||||
assign_place_to_day: (result, snapshot) => {
|
||||
const created = recordOf(result.assignment);
|
||||
return same(created, byId(assignments(snapshot), created.id), STABLE_FIELDS.assignment);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { AssistantChangeLabelKey, AssistantChangeRow } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The pieces every change card is written with: a value cut to what a row
|
||||
* shows, an argument read as an id, and the rows themselves. Shared by the
|
||||
* cards of the trip's own tools (tool-call-preview.helpers.ts) and of the
|
||||
* tours (tour-call-preview.helpers.ts).
|
||||
*/
|
||||
|
||||
type Args = Record<string, unknown>;
|
||||
|
||||
/** Longest value a row shows; URLs keep their start, so the host stays visible. */
|
||||
const MAX_VALUE_CHARS = 160;
|
||||
|
||||
const CHECKED = '✓';
|
||||
export const UNCHECKED = '✗';
|
||||
|
||||
export function clip(value: string): string {
|
||||
const line = value.replace(/\s+/g, ' ').trim();
|
||||
return line.length > MAX_VALUE_CHARS ? `${line.slice(0, MAX_VALUE_CHARS - 1)}…` : line;
|
||||
}
|
||||
|
||||
export function id(args: Args, key: string): number | null {
|
||||
const value = args[key];
|
||||
return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null;
|
||||
}
|
||||
|
||||
export function text(value: unknown): string {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'boolean') return value ? CHECKED : UNCHECKED;
|
||||
return clip(String(value));
|
||||
}
|
||||
|
||||
export class Rows {
|
||||
readonly rows: AssistantChangeRow[] = [];
|
||||
|
||||
add(labelKey: AssistantChangeLabelKey, after: string): this {
|
||||
if (after !== '') this.rows.push({ op: 'add', labelKey, before: null, after });
|
||||
return this;
|
||||
}
|
||||
|
||||
change(labelKey: AssistantChangeLabelKey, before: string | null, after: string): this {
|
||||
this.rows.push({ op: 'change', labelKey, before: before || null, after });
|
||||
return this;
|
||||
}
|
||||
|
||||
move(labelKey: AssistantChangeLabelKey, before: string, after: string): this {
|
||||
this.rows.push({ op: 'move', labelKey, before: before || null, after });
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,14 @@ import {
|
||||
writeToolOf,
|
||||
} from './assistant-tools.constants';
|
||||
import type { ToolHint } from './assistant-tools.service';
|
||||
import { clip, id, Rows, text, UNCHECKED } from './preview-rows.helpers';
|
||||
import { describeGeneric } from './tool-call-generic.helpers';
|
||||
import { TOUR_DESCRIBERS } from './tour-call-preview.helpers';
|
||||
import type {
|
||||
AssistantApplied,
|
||||
AssistantChangeEffect,
|
||||
AssistantChangeLabelKey,
|
||||
AssistantChangePreview,
|
||||
AssistantChangeRow,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
@@ -35,23 +36,8 @@ export interface PreviewContext {
|
||||
hintOf?: (toolName: string) => ToolHint | null;
|
||||
}
|
||||
|
||||
/** Longest value a row shows; URLs keep their start, so the host stays visible. */
|
||||
const MAX_VALUE_CHARS = 160;
|
||||
const MAX_ROWS = 12;
|
||||
|
||||
const CHECKED = '✓';
|
||||
const UNCHECKED = '✗';
|
||||
|
||||
function clip(value: string): string {
|
||||
const line = value.replace(/\s+/g, ' ').trim();
|
||||
return line.length > MAX_VALUE_CHARS ? `${line.slice(0, MAX_VALUE_CHARS - 1)}…` : line;
|
||||
}
|
||||
|
||||
function id(args: Args, key: string): number | null {
|
||||
const value = args[key];
|
||||
return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null;
|
||||
}
|
||||
|
||||
function has(args: Args, key: string): boolean {
|
||||
return args[key] !== undefined;
|
||||
}
|
||||
@@ -107,12 +93,6 @@ function money(ctx: PreviewContext, amount: number, currency: string | null): st
|
||||
return new Intl.NumberFormat(localeOf(ctx)).format(amount);
|
||||
}
|
||||
|
||||
function text(value: unknown): string {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'boolean') return value ? CHECKED : UNCHECKED;
|
||||
return clip(String(value));
|
||||
}
|
||||
|
||||
function openingHours(ctx: PreviewContext, value: unknown): string {
|
||||
if (!Array.isArray(value)) return '';
|
||||
const weekday = new Intl.DateTimeFormat(localeOf(ctx), { weekday: 'short', timeZone: 'UTC' });
|
||||
@@ -132,25 +112,6 @@ function memberNames(ctx: PreviewContext, ids: unknown): string {
|
||||
return clip(ids.map((memberId) => ctx.card.members.get(Number(memberId)) ?? `#${String(memberId)}`).join(', '));
|
||||
}
|
||||
|
||||
class Rows {
|
||||
readonly rows: AssistantChangeRow[] = [];
|
||||
|
||||
add(labelKey: AssistantChangeLabelKey, after: string): this {
|
||||
if (after !== '') this.rows.push({ op: 'add', labelKey, before: null, after });
|
||||
return this;
|
||||
}
|
||||
|
||||
change(labelKey: AssistantChangeLabelKey, before: string | null, after: string): this {
|
||||
this.rows.push({ op: 'change', labelKey, before: before || null, after });
|
||||
return this;
|
||||
}
|
||||
|
||||
move(labelKey: AssistantChangeLabelKey, before: string, after: string): this {
|
||||
this.rows.push({ op: 'move', labelKey, before: before || null, after });
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
function coordinates(args: Args): string {
|
||||
const { lat, lng } = args;
|
||||
return typeof lat === 'number' && typeof lng === 'number' ? `${lat.toFixed(5)}, ${lng.toFixed(5)}` : '';
|
||||
@@ -273,7 +234,7 @@ interface Described {
|
||||
placeIds: number[];
|
||||
}
|
||||
|
||||
type Describer = (ctx: PreviewContext, args: Args) => Described;
|
||||
export type Describer = (ctx: PreviewContext, args: Args) => Described;
|
||||
|
||||
/** Who shares an expense: the uneven split's members, else the equal one's. */
|
||||
function splitOf(args: Args): unknown {
|
||||
@@ -430,6 +391,7 @@ const DESCRIBERS: Readonly<Record<string, Describer>> = {
|
||||
};
|
||||
},
|
||||
[IMPORT_BOOKING_TOOL]: describeBooking,
|
||||
...TOUR_DESCRIBERS,
|
||||
};
|
||||
|
||||
/** A held write of the model's tools or of the server's own (a booking from a file). */
|
||||
@@ -518,14 +480,28 @@ export function describeToolCall(
|
||||
const RESULT_KEYS = ['place', 'assignment', 'note', 'item', 'reservation'] as const;
|
||||
const ARG_KEYS = ['placeId', 'assignmentId', 'noteId', 'itemId'] as const;
|
||||
|
||||
function createdId(result: unknown): number | null {
|
||||
if (!result || typeof result !== 'object') return null;
|
||||
/**
|
||||
* The tours an answer names: a tour created or changed (`tour`), or those a
|
||||
* file brought in (`tours`). A tour's id is its place's.
|
||||
*/
|
||||
function tourIds(result: Args): number[] {
|
||||
const tours = Array.isArray(result.tours) ? result.tours : [result.tour];
|
||||
return tours.flatMap((tour: unknown) => {
|
||||
const placeId = tour && typeof tour === 'object' ? id(tour as Args, 'place_id') : null;
|
||||
return placeId === null ? [] : [placeId];
|
||||
});
|
||||
}
|
||||
|
||||
function createdIds(result: unknown): number[] {
|
||||
if (!result || typeof result !== 'object') return [];
|
||||
const tours = tourIds(result as Args);
|
||||
if (tours.length > 0) return tours;
|
||||
for (const key of RESULT_KEYS) {
|
||||
const created = (result as Args)[key];
|
||||
const value = created && typeof created === 'object' ? id(created as Args, 'id') : null;
|
||||
if (value !== null) return value;
|
||||
if (value !== null) return [value];
|
||||
}
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
|
||||
/** The day a created booking landed on, when its answer names one. */
|
||||
@@ -550,11 +526,12 @@ export function appliedChange(
|
||||
): AssistantApplied | null {
|
||||
// A tool without a card of its own touched something the client has no view for.
|
||||
const tool = writeTool(writeToolOf(toolName, args)) ?? { entity: 'other' as const };
|
||||
const touched = createdId(result) ?? ARG_KEYS.map((key) => id(args, key)).find((value) => value !== null) ?? null;
|
||||
const created = createdIds(result);
|
||||
const named = ARG_KEYS.map((key) => id(args, key)).filter((value): value is number => value !== null);
|
||||
return {
|
||||
toolCallId,
|
||||
entity: tool.entity,
|
||||
ids: touched === null ? [] : [touched],
|
||||
ids: created.length > 0 ? created : named.slice(0, 1),
|
||||
dayId: dayId ?? bookedDay(result),
|
||||
undoUntil,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { clip, id, Rows, text } from './preview-rows.helpers';
|
||||
import type { Describer, PreviewContext } from './tool-call-preview.helpers';
|
||||
import { TOURS_MAX_HIKING_DIFFICULTY } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The change cards of the tours an assistant creates and changes: a hike, a
|
||||
* city walk, a change to a saved hike, tours taken in from a GPX file. The
|
||||
* route reads as the names of its points in order, a hike's limit as its SAC
|
||||
* grade (T1 to T6), a planned time in hours and minutes.
|
||||
*/
|
||||
|
||||
type Args = Record<string, unknown>;
|
||||
|
||||
function recordOf(value: unknown): Args {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? (value as Args) : {};
|
||||
}
|
||||
|
||||
/** A point's name: its own, else the name of the trip's place it stands for. */
|
||||
function pointName(ctx: PreviewContext, point: unknown): string {
|
||||
const record = recordOf(point);
|
||||
const linked = id(record, 'linked_place_id');
|
||||
return text(record.name) || (linked === null ? '' : (ctx.card.places.get(linked)?.name ?? ''));
|
||||
}
|
||||
|
||||
/** "Car park → Hut → Summit": the named points in order, a round trip back to its start. */
|
||||
function routeOf(ctx: PreviewContext, points: unknown, roundTrip: unknown): string {
|
||||
if (!Array.isArray(points)) return '';
|
||||
const names = points.map((point: unknown) => pointName(ctx, point));
|
||||
if (roundTrip === true && names.length > 0) names.push(names[0]);
|
||||
return clip(names.filter((name) => name !== '').join(' → '));
|
||||
}
|
||||
|
||||
/** The trip's places a tour's points stand for. */
|
||||
function linkedPlaceIds(ctx: PreviewContext, points: unknown): number[] {
|
||||
if (!Array.isArray(points)) return [];
|
||||
const ids = points.map((point: unknown) => id(recordOf(point), 'linked_place_id'));
|
||||
return [...new Set(ids.filter((placeId): placeId is number => placeId !== null && ctx.card.places.has(placeId)))];
|
||||
}
|
||||
|
||||
/** A hike's limit as its SAC grade, T1 to T6. */
|
||||
function grade(value: unknown): string {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 6 ? `T${value}` : '';
|
||||
}
|
||||
|
||||
/** Minutes as hours and minutes, "5:30 h". */
|
||||
function hours(value: unknown): string {
|
||||
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) return '';
|
||||
return `${Math.floor(value / 60)}:${String(value % 60).padStart(2, '0')} h`;
|
||||
}
|
||||
|
||||
/** The first name a GPX text gives, a track's or the file's own. */
|
||||
function gpxName(gpx: unknown): string {
|
||||
if (typeof gpx !== 'string') return '';
|
||||
const open = gpx.indexOf('<name>');
|
||||
const close = open < 0 ? -1 : gpx.indexOf('</name>', open);
|
||||
return close < 0 ? '' : text(gpx.slice(open + '<name>'.length, close));
|
||||
}
|
||||
|
||||
export const TOUR_DESCRIBERS: Readonly<Record<string, Describer>> = {
|
||||
create_hike: (ctx, args) => {
|
||||
const rows = new Rows()
|
||||
.add('route', routeOf(ctx, args.waypoints, args.round_trip))
|
||||
.add('difficulty', grade(args.max_hiking_difficulty ?? TOURS_MAX_HIKING_DIFFICULTY))
|
||||
.add('time', hours(args.planned_duration_minutes))
|
||||
.add('description', text(args.description));
|
||||
return { subject: text(args.name), rows, dayId: null, placeIds: [] };
|
||||
},
|
||||
create_city_walk: (ctx, args) => {
|
||||
const rows = new Rows().add('route', routeOf(ctx, args.stations, false)).add('description', text(args.description));
|
||||
return { subject: text(args.name), rows, dayId: null, placeIds: linkedPlaceIds(ctx, args.stations) };
|
||||
},
|
||||
update_tour: (ctx, args) => {
|
||||
const placeId = id(args, 'placeId');
|
||||
const current = placeId === null ? undefined : ctx.card.places.get(placeId);
|
||||
const rows = new Rows();
|
||||
if (args.name !== undefined) rows.change('name', current?.name ?? null, text(args.name));
|
||||
if (args.description !== undefined)
|
||||
rows.change('description', current?.description ?? null, text(args.description));
|
||||
rows
|
||||
.add('route', routeOf(ctx, args.waypoints, false))
|
||||
.add('difficulty', grade(args.max_hiking_difficulty))
|
||||
.add('time', hours(args.planned_duration_minutes));
|
||||
return {
|
||||
subject: current?.name ?? text(args.name),
|
||||
rows,
|
||||
dayId: null,
|
||||
placeIds: placeId === null ? [] : [placeId],
|
||||
};
|
||||
},
|
||||
import_tour_gpx: (_ctx, args) => {
|
||||
const rows = new Rows().add('type', text(args.tour_type));
|
||||
return { subject: text(args.file_name) || gpxName(args.gpx) || 'GPX', rows, dayId: null, placeIds: [] };
|
||||
},
|
||||
};
|
||||
@@ -2,12 +2,23 @@ import { Plugins } from '../../db/entities/Plugins.entity';
|
||||
import type { PluginsRepository } from '../../db/repositories/Plugins.repository';
|
||||
import { readCappedJson, discardBody } from '../../utils/cappedFetch';
|
||||
import { safeFetchAdminConfigured } from '../../utils/ssrfGuard';
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { normalize, declaredProfiles } from '../plugins/contributions/plugin-route-normalize';
|
||||
import { pluginsEnabled } from '../plugins/kill-switch';
|
||||
import { PluginHooks } from '../plugins/plugin-hooks.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import {
|
||||
HEIGHT_CHUNK_SIZE,
|
||||
heightBody,
|
||||
heightsOf,
|
||||
TRACE_TIMEOUT_MS,
|
||||
traceBody,
|
||||
tracedWaysOf,
|
||||
type TracedWay,
|
||||
} from './valhalla-hike.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { GeometryPoint } from '@trek/shared';
|
||||
import {
|
||||
formatDurationShort,
|
||||
haversineKm,
|
||||
@@ -16,6 +27,7 @@ import {
|
||||
type SnappedWaypoint,
|
||||
} from '@trek/shared/roadtrip';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
|
||||
const coordinate = z.tuple([z.number().min(-180).max(180), z.number().min(-90).max(90)]);
|
||||
@@ -88,6 +100,79 @@ export interface RouteOptions {
|
||||
* boat said. A city walk asks this; a road trip day never does.
|
||||
*/
|
||||
footOnly?: boolean;
|
||||
/**
|
||||
* A hike's own pedestrian costing (its hiking limit and preferences, as
|
||||
* `hikingCosting` builds them), sent to Valhalla as the planner in the
|
||||
* browser sends it. Only Valhalla knows a hiking limit: OSRM's foot profile
|
||||
* takes a T5 ridge as readily as a forest road. So a walk asked with one is
|
||||
* asked of Valhalla alone and fails rather than fall back to OSRM, with a
|
||||
* `RouteRefusal` of `no_valhalla` where there is no Valhalla to ask.
|
||||
*/
|
||||
costingOptions?: Readonly<Record<string, number>>;
|
||||
}
|
||||
|
||||
export type { TracedWay };
|
||||
|
||||
/**
|
||||
* Why a route asked of Valhalla has none, as opposed to a router that did not
|
||||
* answer: no Valhalla to ask (an own OSRM without one), Valhalla's own word
|
||||
* that no way joins the points (`no_way`: points in regions no edge connects,
|
||||
* a point with no edge near it, or no path between them, within the hiking
|
||||
* limit where one was asked), or that the way is longer than it plans for
|
||||
* one costing (`too_long`). Asking again gives the same answer.
|
||||
*/
|
||||
export class RouteRefusal extends Error {
|
||||
constructor(
|
||||
readonly why: 'no_valhalla' | 'no_way' | 'too_long',
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'RouteRefusal';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Valhalla's refusals that are about the way rather than the host: locations
|
||||
* in regions no edge connects (170), no edge near a location (171), no path
|
||||
* (442), and a way past the instance's distance limit for the costing (154).
|
||||
*/
|
||||
const REFUSAL_CODES: ReadonlyMap<number, 'no_way' | 'too_long'> = new Map([
|
||||
[154, 'too_long'],
|
||||
[170, 'no_way'],
|
||||
[171, 'no_way'],
|
||||
[442, 'no_way'],
|
||||
]);
|
||||
const refusalSchema = z.object({ error_code: z.number() });
|
||||
/** The most of a refusal's body that is read to tell which one it is. */
|
||||
const REFUSAL_MAX_BYTES = 64 * 1024;
|
||||
|
||||
/** Valhalla's word in a router's 400 that the way cannot be had, or null where the 400 says something else. */
|
||||
async function refusalOf(response: Response): Promise<'no_way' | 'too_long' | null> {
|
||||
const refusal = refusalSchema.safeParse(await readCappedJson(response, REFUSAL_MAX_BYTES));
|
||||
return refusal.success ? (REFUSAL_CODES.get(refusal.data.error_code) ?? null) : null;
|
||||
}
|
||||
|
||||
/** How often a piece of a line whose heights could not be read is asked again, as the planner asks a route again. */
|
||||
const HEIGHT_RETRIES = 1;
|
||||
/** How long a line's heights are kept, as long as a route is: a proposal and the hike created from it ask once. */
|
||||
const HEIGHTS_TTL_MS = 300_000;
|
||||
/** The most lines whose heights are kept; a line of ten thousand points keeps that many numbers. */
|
||||
const HEIGHTS_CACHE_MAX = 20;
|
||||
|
||||
/** The heights of a line kept under: who asked, the Valhalla asked, and the line itself as a digest. */
|
||||
function heightsKey(userId: number, valhalla: string, line: ReadonlyArray<readonly [number, number]>): string {
|
||||
const digest = createHash('sha256').update(JSON.stringify(line)).digest('hex');
|
||||
return `${userId} ${valhalla} ${digest}`;
|
||||
}
|
||||
|
||||
/** The routers a user's settings name: their own OSRM (blank for the public hosts) and the Valhalla to ask, if any. */
|
||||
function routersOf(settings: Record<string, unknown>): { base: string; valhalla: string } {
|
||||
const base =
|
||||
typeof settings.routing_base_url === 'string' ? settings.routing_base_url.trim().replace(/\/+$/, '') : '';
|
||||
const configuredValhalla =
|
||||
typeof settings.valhalla_base_url === 'string' ? settings.valhalla_base_url.trim().replace(/\/+$/, '') : '';
|
||||
// An own OSRM without a Valhalla means no Valhalla at all, as in the browser (`valhallaBase`).
|
||||
return { base, valhalla: configuredValhalla || (base ? '' : 'https://valhalla1.openstreetmap.de') };
|
||||
}
|
||||
|
||||
/** Valhalla's maneuver type for boarding a ferry. */
|
||||
@@ -154,6 +239,7 @@ export class RoadtripRouterService {
|
||||
private nextRequest = 0;
|
||||
private queue: Promise<void> = Promise.resolve();
|
||||
private cache = new Map<string, { at: number; route: RoadtripRoute }>();
|
||||
private heightsCache = new Map<string, { at: number; heights: Array<number | null> }>();
|
||||
|
||||
constructor(
|
||||
private readonly settings: SettingsService,
|
||||
@@ -174,7 +260,7 @@ export class RoadtripRouterService {
|
||||
return ['driving', 'walking', 'cycling', ...plugin];
|
||||
}
|
||||
|
||||
private async request(url: string, body?: unknown): Promise<unknown> {
|
||||
private async request(url: string, body?: unknown, timeoutMs = 20000): Promise<unknown> {
|
||||
const before = this.queue;
|
||||
let release!: () => void;
|
||||
this.queue = new Promise<void>((resolve) => {
|
||||
@@ -186,12 +272,17 @@ export class RoadtripRouterService {
|
||||
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
this.nextRequest = Date.now() + 1100;
|
||||
const response = await safeFetchAdminConfigured(url, {
|
||||
signal: AbortSignal.timeout(20000),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
headers: { 'User-Agent': 'TREK Roadtrip', 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
|
||||
...(body ? { method: 'POST', body: JSON.stringify(body) } : {}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
discardBody(response);
|
||||
// A 400 from Valhalla says why: a way that does not exist is no failure of the host.
|
||||
if (response.status !== 400) discardBody(response);
|
||||
else {
|
||||
const why = await refusalOf(response);
|
||||
if (why) throw new RouteRefusal(why, 'Routing provider returned 400');
|
||||
}
|
||||
throw new Error(`Routing provider returned ${response.status}`);
|
||||
}
|
||||
const payload = await readCappedJson<unknown>(response, 8 * 1024 * 1024);
|
||||
@@ -213,6 +304,7 @@ export class RoadtripRouterService {
|
||||
): Promise<RoadtripRoute> {
|
||||
const settings = await this.settings.getUserSettings(userId);
|
||||
const footOnly = options.footOnly === true && profile === 'walking';
|
||||
const hiking = profile === 'walking' ? options.costingOptions : undefined;
|
||||
const key = JSON.stringify([
|
||||
userId,
|
||||
tripId,
|
||||
@@ -223,6 +315,7 @@ export class RoadtripRouterService {
|
||||
settings.routing_base_url,
|
||||
settings.valhalla_base_url,
|
||||
...(footOnly ? ['foot-only'] : []),
|
||||
...(hiking ? [{ hiking }] : []),
|
||||
]);
|
||||
const cached = this.cache.get(key);
|
||||
if (!profile.startsWith('plugin:') && cached && Date.now() - cached.at < 300000) return cached.route;
|
||||
@@ -252,13 +345,14 @@ export class RoadtripRouterService {
|
||||
parts = route.legs;
|
||||
} else {
|
||||
const mode = profile === 'walking' || profile === 'cycling' ? profile : 'driving';
|
||||
const base =
|
||||
typeof settings.routing_base_url === 'string' ? settings.routing_base_url.trim().replace(/\/+$/, '') : '';
|
||||
const configuredValhalla =
|
||||
typeof settings.valhalla_base_url === 'string' ? settings.valhalla_base_url.trim().replace(/\/+$/, '') : '';
|
||||
const valhalla = configuredValhalla || (base ? '' : 'https://valhalla1.openstreetmap.de');
|
||||
const { base, valhalla } = routersOf(settings);
|
||||
let weighted = false;
|
||||
if (footOnly && valhalla) {
|
||||
if (hiking) {
|
||||
if (!valhalla) throw new RouteRefusal('no_valhalla', 'No Valhalla is set to plan a hike with');
|
||||
const legs = await this.valhallaLegs(valhalla, points, 'pedestrian', { ...hiking });
|
||||
({ line, distance, duration, parts, snapped } = routeOfLegs(points, legs));
|
||||
weighted = true;
|
||||
} else if (footOnly && valhalla) {
|
||||
try {
|
||||
const legs = await this.valhallaLegs(valhalla, points, 'pedestrian', { use_ferry: 0 }, true);
|
||||
({ line, distance, duration, parts, snapped } = routeOfLegs(points, legs));
|
||||
@@ -401,4 +495,97 @@ export class RoadtripRouterService {
|
||||
if (legs.length !== points.length - 1) throw new Error('Routing response has mismatched legs');
|
||||
return legs;
|
||||
}
|
||||
|
||||
/** The Valhalla a user's routes are asked of, or null where there is none to ask. */
|
||||
private async valhallaFor(userId: number): Promise<string | null> {
|
||||
return routersOf(await this.settings.getUserSettings(userId)).valhalla || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The height of every point of a line, from Valhalla's /height, the way the
|
||||
* planner in the browser reads it (enrichTourElevations): in pieces of 500
|
||||
* points that overlap by one, one after another through the paced queue.
|
||||
* A point the terrain data has no height for stays `[lat, lng]`. A piece
|
||||
* whose question fails is asked once more; one that fails again ends the
|
||||
* reading, and the points after it stay without heights. A line read whole
|
||||
* is kept for five minutes, so a hike created from a proposal does not ask
|
||||
* the host again. Null where there is no Valhalla to ask, or nothing to
|
||||
* measure.
|
||||
*/
|
||||
async heights(userId: number, line: ReadonlyArray<readonly [number, number]>): Promise<GeometryPoint[] | null> {
|
||||
const valhalla = await this.valhallaFor(userId);
|
||||
if (!valhalla || line.length < 2) return null;
|
||||
const key = heightsKey(userId, valhalla, line);
|
||||
const kept = this.heightsCache.get(key);
|
||||
const heights =
|
||||
kept && Date.now() - kept.at < HEIGHTS_TTL_MS ? kept.heights : await this.readHeights(key, valhalla, line);
|
||||
return line.map(([lat, lng], index): GeometryPoint => {
|
||||
const height = heights[index];
|
||||
return height === null ? [lat, lng] : [lat, lng, height];
|
||||
});
|
||||
}
|
||||
|
||||
/** The heights of a line asked piece by piece, kept under `key` where every piece was answered. */
|
||||
private async readHeights(
|
||||
key: string,
|
||||
valhalla: string,
|
||||
line: ReadonlyArray<readonly [number, number]>,
|
||||
): Promise<Array<number | null>> {
|
||||
const heights: Array<number | null> = line.map(() => null);
|
||||
const step = HEIGHT_CHUNK_SIZE - 1;
|
||||
const offsets = Array.from({ length: Math.ceil((line.length - 1) / step) }, (_, index) => index * step);
|
||||
// One piece after another through the queue; the first that fails twice ends the reading.
|
||||
const whole = await offsets.reduce<Promise<boolean>>(async (going, offset) => {
|
||||
if (!(await going)) return false;
|
||||
const read = await this.pieceHeights(valhalla, line.slice(offset, offset + HEIGHT_CHUNK_SIZE), offset);
|
||||
// The point a piece shares with the one before keeps the height it already has.
|
||||
read?.forEach((height, index) => {
|
||||
if (index > 0 || heights[offset] === null) heights[offset + index] = height;
|
||||
});
|
||||
return read !== null;
|
||||
}, Promise.resolve(true));
|
||||
if (whole) {
|
||||
this.heightsCache.set(key, { at: Date.now(), heights });
|
||||
const [oldest] = this.heightsCache.keys();
|
||||
if (this.heightsCache.size > HEIGHTS_CACHE_MAX && oldest !== undefined) this.heightsCache.delete(oldest);
|
||||
}
|
||||
return heights;
|
||||
}
|
||||
|
||||
/**
|
||||
* The heights of one piece of a line, starting at `offset`, asked again
|
||||
* `retries` times where its question fails, or null where it failed every time.
|
||||
*/
|
||||
private async pieceHeights(
|
||||
valhalla: string,
|
||||
piece: ReadonlyArray<readonly [number, number]>,
|
||||
offset: number,
|
||||
retries = HEIGHT_RETRIES,
|
||||
): Promise<Array<number | null> | null> {
|
||||
let why: string;
|
||||
try {
|
||||
const read = heightsOf(await this.request(`${valhalla}/height`, heightBody(piece)), piece.length);
|
||||
if (read) return read;
|
||||
why = 'the answer does not name every point';
|
||||
} catch (err: unknown) {
|
||||
why = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
if (retries > 0) return await this.pieceHeights(valhalla, piece, offset, retries - 1);
|
||||
logWarn(`[Router] heights stop at point ${offset}: ${why}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The OpenStreetMap ways under a line, in the order they are walked, each
|
||||
* with the metres of the line it runs along: Valhalla's trace_attributes,
|
||||
* matched on foot with every grade of path open, the line thinned to at
|
||||
* most 4000 points as the planner thins it. Throws where there is no
|
||||
* Valhalla or it gives no answer: a description is an addition beside a
|
||||
* route that already exists, and its caller decides what its absence means.
|
||||
*/
|
||||
async wayIds(userId: number, line: ReadonlyArray<readonly [number, number]>): Promise<TracedWay[]> {
|
||||
const valhalla = await this.valhallaFor(userId);
|
||||
if (!valhalla) throw new RouteRefusal('no_valhalla', 'No Valhalla is set to describe a line with');
|
||||
return tracedWaysOf(await this.request(`${valhalla}/trace_attributes`, traceBody(line), TRACE_TIMEOUT_MS));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { GeometryPoint } from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* What the router asks Valhalla about a hike besides its way, and how it
|
||||
* reads the answers: the heights along a line (/height) and the OpenStreetMap
|
||||
* ways under it (/trace_attributes). The request shapes are the planner's in
|
||||
* the browser (enrichTourElevations and valhallaTraceAttributes on the
|
||||
* client), so a hike planned on the server is measured as one planned there.
|
||||
* Pure: the requests themselves go through the router's one paced queue.
|
||||
*/
|
||||
|
||||
/** Points one /height question carries; a longer line is asked in pieces that overlap by one point. */
|
||||
export const HEIGHT_CHUNK_SIZE = 500;
|
||||
/** 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: the matcher is slower than the router. */
|
||||
export const TRACE_TIMEOUT_MS = 30_000;
|
||||
/** The most edges a description is read with; a line of 4000 points has far fewer. */
|
||||
const TRACE_MAX_EDGES = 20_000;
|
||||
|
||||
type LinePoint = GeometryPoint | readonly [number, number];
|
||||
|
||||
/** The /height question for one piece of a line: every point, and the distance along it asked back. */
|
||||
export function heightBody(piece: readonly LinePoint[]) {
|
||||
return { shape: piece.map(([lat, lng]) => ({ lat, lon: lng })), range: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* /height with `range` answers `[metres along, height]` per point; the height
|
||||
* is null where the terrain data has none.
|
||||
*/
|
||||
const heightAnswerSchema = z.object({
|
||||
range_height: z.array(z.tuple([z.number(), z.number().nullable()])).max(HEIGHT_CHUNK_SIZE),
|
||||
});
|
||||
|
||||
/**
|
||||
* The height of each point of a piece, null where there is none, or null for
|
||||
* the whole piece when the answer is no answer of that kind or does not name
|
||||
* every point it was asked about.
|
||||
*/
|
||||
export function heightsOf(answer: unknown, expected: number): Array<number | null> | null {
|
||||
const parsed = heightAnswerSchema.safeParse(answer);
|
||||
if (!parsed.success || parsed.data.range_height.length !== expected) return null;
|
||||
return parsed.data.range_height.map(([, height]) => height);
|
||||
}
|
||||
|
||||
/** The line thinned evenly to at most `TRACE_MAX_POINTS`, its last point always kept. */
|
||||
function traceShape(line: readonly LinePoint[]) {
|
||||
const step = Math.max(1, Math.ceil(line.length / TRACE_MAX_POINTS));
|
||||
return line
|
||||
.filter((_, index) => index % step === 0 || index === line.length - 1)
|
||||
.map(([lat, lng]) => ({ lat, lon: lng }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The trace_attributes question for a hike's line: matched on foot with every
|
||||
* grade of path open, since a hike may run on a T6 ridge the matcher must not
|
||||
* refuse (matching is no routing: the limit the hike was planned with plays
|
||||
* no part), asking only for the way behind each edge and the edge's length.
|
||||
*/
|
||||
export function traceBody(line: readonly LinePoint[]) {
|
||||
return {
|
||||
shape: traceShape(line),
|
||||
costing: 'pedestrian',
|
||||
costing_options: { pedestrian: { max_hiking_difficulty: 6 } },
|
||||
shape_match: 'map_snap',
|
||||
filters: { attributes: ['edge.way_id', 'edge.length'], action: 'include' },
|
||||
};
|
||||
}
|
||||
|
||||
const traceAnswerSchema = z.object({
|
||||
edges: z
|
||||
.array(
|
||||
z.object({
|
||||
way_id: z.number().int().nonnegative().optional(),
|
||||
/** Kilometres. */
|
||||
length: z.number().nonnegative().optional(),
|
||||
}),
|
||||
)
|
||||
.max(TRACE_MAX_EDGES),
|
||||
});
|
||||
|
||||
/** One stretch of a described line: the OpenStreetMap way it runs on, where the router names one, and its length. */
|
||||
export interface TracedWay {
|
||||
wayId: number | null;
|
||||
metres: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ways under a line in the order they are walked. An edge without a
|
||||
* length is left out, since it cannot be placed along the line; one without a
|
||||
* way keeps its length, so the stretches still add up to the line.
|
||||
*/
|
||||
export function tracedWaysOf(answer: unknown): TracedWay[] {
|
||||
const { edges } = traceAnswerSchema.parse(answer);
|
||||
return edges.flatMap((edge) =>
|
||||
edge.length === undefined
|
||||
? []
|
||||
: [{ wayId: edge.way_id !== undefined && edge.way_id > 0 ? edge.way_id : null, metres: edge.length * 1000 }],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { addStretch, metresAlong } from './hike-routing.helpers';
|
||||
import type { PlannedHike } from './hike-routing.service';
|
||||
import type { TourCreateCommand } from './tours.service';
|
||||
import {
|
||||
haversineMetres,
|
||||
HIKE_PROPOSAL_SAC_SEGMENTS,
|
||||
hikingPreferencesOf,
|
||||
TOUR_MAX_SNAP_M,
|
||||
type GeometryPoint,
|
||||
type HikeCreateRequest,
|
||||
type HikePlan,
|
||||
type HikePlanPoint,
|
||||
type HikeProposal,
|
||||
type HikeProposalSac,
|
||||
type HikeProposeRequest,
|
||||
type HikeRouteOutcome,
|
||||
type HikeSacSegment,
|
||||
type HikeTrailGrades,
|
||||
type TourWaypoint,
|
||||
type UnroutedHikePlan,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The pure halves of a hike an assistant plans over MCP (HikePlanService):
|
||||
* the points it is planned through, the proposal shown from a plan, the way
|
||||
* a saved hike keeps from a plan, and the write a created hike makes.
|
||||
*/
|
||||
|
||||
/** The points a hike is planned through: as asked, and for a round trip back to its start. */
|
||||
export function hikePointsOf(waypoints: readonly HikePlanPoint[], roundTrip: boolean | undefined): HikePlanPoint[] {
|
||||
const [start] = waypoints;
|
||||
return roundTrip === true && start ? [...waypoints, { ...start }] : [...waypoints];
|
||||
}
|
||||
|
||||
/** Whether the way was planned, and why not, as the answers name it. */
|
||||
export function routeOutcomeOf(plan: HikePlan): HikeRouteOutcome {
|
||||
return plan.kind === 'routed' ? { planned: true } : { planned: false, why: plan.why, position: plan.position };
|
||||
}
|
||||
|
||||
/** The points as a tour keeps them: in order, the first the start and the last the end, with their names. */
|
||||
export function hikeWaypointsOf(points: readonly HikePlanPoint[]): TourWaypoint[] {
|
||||
const last = points.length - 1;
|
||||
return points.map(({ lat, lng, name }, sequence) => ({
|
||||
lat,
|
||||
lng,
|
||||
...(name ? { name } : {}),
|
||||
role: sequence === 0 ? 'start' : sequence === last ? 'end' : 'via',
|
||||
sequence,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The way a saved hike keeps from a plan: its whole line and walking time, or none, and how the planning went. */
|
||||
export interface KeptWay {
|
||||
line: GeometryPoint[] | null;
|
||||
seconds: number | null;
|
||||
route: HikeRouteOutcome;
|
||||
}
|
||||
|
||||
/**
|
||||
* The way a hike is saved with from its plan, as the planner saves one: the
|
||||
* whole line with the height of every point, and its walking time. A way
|
||||
* whose heights could not all be read is not kept: the planner saves no
|
||||
* hike without them, and the router that did not answer for them is asked
|
||||
* again when the hike is next planned, so it reads as `router_unavailable`.
|
||||
*/
|
||||
export function keptWayOf({ plan, line }: PlannedHike): KeptWay {
|
||||
if (plan.kind === 'routed' && plan.has_heights && line) {
|
||||
return { line, seconds: plan.duration_minutes * 60, route: { planned: true } };
|
||||
}
|
||||
const route: HikeRouteOutcome =
|
||||
plan.kind === 'routed' ? { planned: false, why: 'router_unavailable', position: null } : routeOutcomeOf(plan);
|
||||
return { line: null, seconds: null, route };
|
||||
}
|
||||
|
||||
/**
|
||||
* The write of a hike created from its points, the way the planner's save
|
||||
* writes one: the way it keeps (the whole line with its heights and its
|
||||
* walking time) and its routing limit. Without a way it is saved with its
|
||||
* points only, and the planner plans the way when it is opened.
|
||||
*/
|
||||
export function hikeCreateCommandOf(
|
||||
request: HikeCreateRequest,
|
||||
points: readonly HikePlanPoint[],
|
||||
way: KeptWay,
|
||||
limit: number,
|
||||
): TourCreateCommand {
|
||||
return {
|
||||
name: request.name,
|
||||
description: request.description,
|
||||
tour_type: 'hike',
|
||||
route_geometry: way.line,
|
||||
duration_seconds: way.seconds,
|
||||
max_hiking_difficulty: limit,
|
||||
hiking_preferences: hikingPreferencesOf(request.hiking_preferences),
|
||||
...(request.planned_duration_minutes !== undefined
|
||||
? { planned_duration_minutes: request.planned_duration_minutes }
|
||||
: {}),
|
||||
waypoints: hikeWaypointsOf(points),
|
||||
};
|
||||
}
|
||||
|
||||
/** How near a new point of a hike stands to a saved one to be the same point, in metres. */
|
||||
const SAME_POINT_M = 25;
|
||||
|
||||
/** The saved point nearest to `point`, where one stands within SAME_POINT_M of it. */
|
||||
function savedPointAt(point: { lat: number; lng: number }, saved: readonly TourWaypoint[]): TourWaypoint | undefined {
|
||||
let nearest: TourWaypoint | undefined;
|
||||
let nearestGap = Number.POSITIVE_INFINITY;
|
||||
for (const old of saved) {
|
||||
const gap = haversineMetres(point.lat, point.lng, old.lat, old.lng);
|
||||
if (gap <= SAME_POINT_M && gap < nearestGap) {
|
||||
nearest = old;
|
||||
nearestGap = gap;
|
||||
}
|
||||
}
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/**
|
||||
* New points as a hike keeps them, in order. A point that stands where a
|
||||
* saved one stood (within SAME_POINT_M, the nearest) is that point still: it
|
||||
* keeps its link to the trip's place it stands for, and its name where the
|
||||
* new one gives none. A saved point no new one stands on goes, with its link.
|
||||
*/
|
||||
export function repointedWaypoints(points: readonly HikePlanPoint[], saved: readonly TourWaypoint[]): TourWaypoint[] {
|
||||
return hikeWaypointsOf(points).map((point) => {
|
||||
const same = savedPointAt(point, saved);
|
||||
if (!same) return point;
|
||||
const name = point.name ?? same.name;
|
||||
return {
|
||||
...point,
|
||||
...(name ? { name } : {}),
|
||||
...(same.linked_place_id ? { linked_place_id: same.linked_place_id } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* How much nearer than the nearest pass a later one may be and still lose to
|
||||
* an earlier one: a way that comes by a point twice (a summit walked up and
|
||||
* down the same path) places it on the first pass.
|
||||
*/
|
||||
const PASS_SLACK_M = 30;
|
||||
|
||||
/**
|
||||
* Where each point lies along the line, in metres: at the line's nearest
|
||||
* point at or after the one before it, so the points keep their order and a
|
||||
* round trip's end lies at the end of the way, not at its start.
|
||||
*/
|
||||
export function positionsAlong(line: readonly GeometryPoint[], points: readonly HikePlanPoint[]): number[] {
|
||||
const along = metresAlong(line);
|
||||
let from = 0;
|
||||
return points.map(({ lat, lng }) => {
|
||||
const gaps = line.slice(from).map(([pointLat, pointLng]) => haversineMetres(lat, lng, pointLat, pointLng));
|
||||
const nearest = gaps.reduce((low, gap) => Math.min(low, gap), Number.POSITIVE_INFINITY);
|
||||
from += Math.max(
|
||||
0,
|
||||
gaps.findIndex((gap) => gap <= nearest + PASS_SLACK_M),
|
||||
);
|
||||
return Math.round(along[from]);
|
||||
});
|
||||
}
|
||||
|
||||
/** The lowest and highest point of a line with heights, in whole metres. */
|
||||
export function heightRangeOf(line: readonly GeometryPoint[]): { min: number; max: number } | null {
|
||||
const heights = line.flatMap((point) => (point.length === 3 ? [point[2]] : []));
|
||||
if (heights.length === 0 || heights.length !== line.length) return null;
|
||||
return {
|
||||
min: Math.round(heights.reduce((low, height) => Math.min(low, height))),
|
||||
max: Math.round(heights.reduce((high, height) => Math.max(high, height))),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Neighbouring stretches joined in pairs, each pair taking the harder of its
|
||||
* grades, so a joined stretch never reads easier than a path in it. Only
|
||||
* stretches that touch are paired unless `acrossGaps`: a stretch of unknown
|
||||
* grade between two stays unknown, rather than read as either's grade.
|
||||
*/
|
||||
function pairedUp(segments: readonly HikeSacSegment[], acrossGaps: boolean): HikeSacSegment[] {
|
||||
const paired: HikeSacSegment[] = [];
|
||||
let held: HikeSacSegment | null = null;
|
||||
for (const segment of segments) {
|
||||
if (held && (acrossGaps || held.to_m === segment.from_m)) {
|
||||
addStretch(paired, { from_m: held.from_m, to_m: segment.to_m, sac: Math.max(held.sac, segment.sac) });
|
||||
held = null;
|
||||
} else {
|
||||
if (held) addStretch(paired, held);
|
||||
held = segment;
|
||||
}
|
||||
}
|
||||
if (held) addStretch(paired, held);
|
||||
return paired;
|
||||
}
|
||||
|
||||
/**
|
||||
* The SAC grades a proposal shows: at most HIKE_PROPOSAL_SAC_SEGMENTS
|
||||
* stretches. Where a long way holds more, touching neighbours are joined in
|
||||
* pairs, the harder grade kept, until they fit; the stretches of unknown grade
|
||||
* between stay as they are. Only a way with more graded stretches than that,
|
||||
* each apart from the next, has them joined over the gaps as well. How much
|
||||
* of the line is unknown stays as measured.
|
||||
*/
|
||||
export function proposalSacOf(grades: HikeTrailGrades | null): HikeProposalSac | null {
|
||||
if (!grades) return null;
|
||||
let segments = grades.segments.reduce<HikeSacSegment[]>(addStretch, []);
|
||||
while (segments.length > HIKE_PROPOSAL_SAC_SEGMENTS) {
|
||||
const touching = pairedUp(segments, false);
|
||||
segments = touching.length < segments.length ? touching : pairedUp(segments, true);
|
||||
}
|
||||
return { highest: grades.highest, segments, unknown_share: grades.unknown_share };
|
||||
}
|
||||
|
||||
/** Where a point lies further from any way than a tour allows: which one, and how far the router had to move it. */
|
||||
function unreachableOf(plan: HikePlan): HikeProposal['unreachable'] {
|
||||
if (plan.kind !== 'unrouted' || plan.position === null || plan.snapped_m === null) return null;
|
||||
return { position: plan.position, snapped_m: plan.snapped_m };
|
||||
}
|
||||
|
||||
/**
|
||||
* The proposal of a hike as a plan gives it: the way and its measures, its
|
||||
* profile and grades, each point with where it lies along the way, and the
|
||||
* request's own words given back. Without a way the points are still shown,
|
||||
* with why there is none.
|
||||
*/
|
||||
export function hikeProposalOf(
|
||||
request: HikeProposeRequest,
|
||||
points: readonly HikePlanPoint[],
|
||||
{ plan, line }: PlannedHike,
|
||||
): HikeProposal {
|
||||
const routed = plan.kind === 'routed' ? plan : null;
|
||||
const positions = routed && line ? positionsAlong(line, points) : null;
|
||||
const heights = routed?.has_heights && line ? heightRangeOf(line) : null;
|
||||
return {
|
||||
name: request.name ?? null,
|
||||
variant_label: request.variant_label ?? null,
|
||||
route: routeOutcomeOf(plan),
|
||||
unreachable: unreachableOf(plan),
|
||||
distance_m: routed?.distance_m ?? null,
|
||||
ascent_m: routed?.ascent_m ?? null,
|
||||
descent_m: routed?.descent_m ?? null,
|
||||
duration_minutes: routed?.duration_minutes ?? null,
|
||||
duration_basis: routed?.duration_basis ?? null,
|
||||
heights_known: heights !== null,
|
||||
min_ele_m: heights?.min ?? null,
|
||||
max_ele_m: heights?.max ?? null,
|
||||
line: routed?.line ?? [],
|
||||
profile: routed?.profile ?? [],
|
||||
sac: proposalSacOf(routed?.grades ?? null),
|
||||
waypoints: points.map(({ lat, lng, name }, index) => ({
|
||||
lat,
|
||||
lng,
|
||||
name: name || null,
|
||||
at_m: positions?.[index] ?? null,
|
||||
})),
|
||||
max_hiking_difficulty: plan.max_hiking_difficulty,
|
||||
hiking_preferences: routed ? routed.hiking_preferences : hikingPreferencesOf(request.hiking_preferences),
|
||||
round_trip: request.round_trip === true,
|
||||
date: request.date ?? null,
|
||||
start_time: request.start_time ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Why no way was planned, in words that say what to do about it. */
|
||||
const UNPLANNED: Readonly<Record<UnroutedHikePlan['why'], (position: number | null) => string>> = {
|
||||
no_valhalla: () =>
|
||||
'TREK has no Valhalla router here to plan a hike with (a routing server of its own knows no hiking limit).',
|
||||
router_unavailable: () => 'The router did not answer, for the way or for its heights; try again in a moment.',
|
||||
no_way: () => 'No way within the hiking limit joins these points: raise the limit or move the points.',
|
||||
point_off_the_way: (position) =>
|
||||
`Point ${position ?? ''} is further than ${TOUR_MAX_SNAP_M} m from any way: move it onto a path.`,
|
||||
too_long: () => 'The way is too long to plan as one hike: split it into shorter hikes.',
|
||||
};
|
||||
|
||||
type Unplanned = Pick<UnroutedHikePlan, 'why' | 'position'>;
|
||||
|
||||
/** The refusal of a hike whose way could not be planned for a reason the planner would meet too: nothing is saved. */
|
||||
export function unplannedCreateMessage({ why, position }: Unplanned): string {
|
||||
return `${UNPLANNED[why](position)} Nothing was saved.`;
|
||||
}
|
||||
|
||||
/** The refusal of a change whose new way could not be planned: the hike keeps the way it has. */
|
||||
export function unplannedChangeMessage({ why, position }: Unplanned): string {
|
||||
return `${UNPLANNED[why](position)} Nothing was saved and the hike keeps its way.`;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
errorResult,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { HikePlanService } from './hike-plan.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
hikeCreateRequestSchema,
|
||||
hikeProposeRequestSchema,
|
||||
idSchema,
|
||||
tourGpxImportRequestSchema,
|
||||
tourUpdateRequestSchema,
|
||||
type HikeCreateRequest,
|
||||
type HikeProposeRequest,
|
||||
type TourGpxImportRequest,
|
||||
type TourUpdateRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* A hike planned with the traveller over MCP. The proposal reads only, so a
|
||||
* way turned down changes nothing and several can be compared; the hike is
|
||||
* created, changed or taken in from a GPX file once the traveller said yes,
|
||||
* through the writes the planner and the file import use, with 'place_edit'
|
||||
* on the trip as REST asks (ToursController for a create and an edit,
|
||||
* ToursImportController for the file). Those writes tell the trip about the
|
||||
* tour (tours:changed with place:created or place:updated) without leaving
|
||||
* out any socket, so the tab that asked shows it too. A refusal of the
|
||||
* service is a DomainError, which the registry answers as an error result
|
||||
* with the text REST sends.
|
||||
*/
|
||||
@McpController()
|
||||
export class HikePlanMcp {
|
||||
constructor(
|
||||
private readonly hikes: HikePlanService,
|
||||
private readonly access: TripAccessService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'propose_hike',
|
||||
description:
|
||||
"Plan a hike for a trip and show it to the traveller, without saving anything. The way on foot runs through waypoints in order (the start, the points on the way such as a hut or a summit, the end; with round_trip it comes back to the start) and takes no path harder than max_hiking_difficulty on the SAC scale (1 for T1 hiking to 6 for T6 difficult alpine hiking, 2 when left out), avoiding steep climbs, steps or ferries where there is a way round when hiking_preferences asks so. TREK's router plans it as the tour planner does. The answer gives distance_m, ascent_m and descent_m, the walking time without breaks (duration_minutes: by DIN 33466, the rule hiking signposts use, where the heights are known, duration_basis din33466; else the router's, duration_basis router), min_ele_m and max_ele_m, the SAC grades OpenStreetMap records along the way (sac: highest, the graded stretches in metres along the way, and unknown_share, the part with no grade, which is unknown and never easy), every point with at_m, where it lies along the way, and the line and height profile for display. Where no way was planned, route says why: no_valhalla (this TREK has no router that knows hiking grades), router_unavailable (try again later), no_way (nothing within the limit joins the points: a higher limit or other points may), point_off_the_way (unreachable names the point and how far it is from any way) or too_long (longer than one hike is planned for: split it into shorter hikes). To compare ways, propose each one with its own variant_label, such as 'short and steep' or 'by the lake'; date and start_time are given back for the schedule. The chat shows the route, its profile and grades as a card: never list coordinates or the profile, sum the hike up in a sentence and say which grade it reaches. Propose first and create the hike with create_hike only after the traveller said yes.",
|
||||
inputSchema: { tripId: idSchema, ...hikeProposeRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async proposeHike({ tripId, ...request }: { tripId: number } & HikeProposeRequest, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
return ok(await this.hikes.propose(ctx.userId, tripId, request));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'create_hike',
|
||||
description:
|
||||
"Create a hike in a trip from points the traveller confirmed, usually the waypoints of a proposal of propose_hike with its max_hiking_difficulty, hiking_preferences and round_trip. It is saved the way the planner saves a new hike: a tour of type hike with its points in order (start, points on the way, end), the way on foot planned by the same router as the proposal and kept whole, with its heights where every point has one, its distance, ascent, descent and walking time, its hiking limit and preferences, and planned_duration_minutes (the time out, breaks included) where given. Where the router did not answer, for the way or its heights (route planned false, why router_unavailable), the hike is saved with its points only (route_pending true) and TREK plans the way when someone opens it in the planner; no straight line is stored. Any other reason the proposal names (no_valhalla, no_way, point_off_the_way, too_long) refuses the hike with why, and nothing is saved. The answer is the tour as list_tours reads it (tour.place_id is the tour's id, its revision 1) and route. Put it on a day with assign_place_to_day, link it to the packing list with link_tour_packing, export it with export_tour_gpx, change it with update_tour. Needs place editing permission on the trip. Create it only after the traveller said yes.",
|
||||
inputSchema: { tripId: idSchema.describe('The trip to create the hike in'), ...hikeCreateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async createHike({ tripId, ...request }: { tripId: number } & HikeCreateRequest, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
return ok(await this.hikes.create(ctx.userId, tripId, request));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'update_tour',
|
||||
description:
|
||||
"Change a saved hike (tour_type hike) against the revision it was read at: expected_revision is tour.revision from get_tour_plan or list_tours. A new name, description or planned_duration_minutes keeps the hike's way. New waypoints (start to end; a round trip ends on its start), a new max_hiking_difficulty or new hiking_preferences plan the way anew as propose_hike plans it, and so does a hike still waiting for its way (route_pending); propose the new way to the traveller first. A hike changed since that revision is refused as a conflict: read it again and show the traveller what changed. Where the new way cannot be planned, or not with its heights, nothing is saved and the hike keeps its way; the error says why. A new point standing where a saved one stood (within 25 m) keeps that point's link to a place of the trip and its name. A hike with a section drawn by hand (a via ferrata, a free line, a ferry) or split into stages takes new points only in the planner, and the hand-drawn one no new limit or preferences either: those changes are refused here. A recorded track without points of its own (an import) takes only new waypoints, which plan it over and keep the recording. Any other type is refused: change a city walk with prepare_tour_change and save_tour_change. The hike stays on its days. The answer is the tour as saved, with its new revision, route and replanned. Needs place editing permission on the trip. Change it only after the traveller said yes.",
|
||||
inputSchema: { tripId: idSchema, ...tourUpdateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async updateTour({ tripId, ...request }: { tripId: number } & TourUpdateRequest, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
try {
|
||||
return ok(await this.hikes.update(ctx.userId, tripId, request));
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NotFoundException) return errorResult('Tour not found.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'import_tour_gpx',
|
||||
description:
|
||||
"Import the tracks and routes of a GPX file as tours of a trip, one tour each, as the planner's file import does: gpx is the file's text (its XML as it is, up to 1,000,000 characters) and file_name the name the travellers know it by. Without a type each one is a hike; a bike import names bike_profile, a run run_profile, a paddle import boat_type and water_context, a ski import ski_discipline (and for cross-country ski_technique). A track already in the trip under the same name and start is skipped and counted in skipped. The answer lists the tours created (each tour's place_id is its id), caution (a track without heights, its climb unknown) and skipped. A file without a single track or route is refused. Needs place editing permission on the trip. Import only a file the traveller gave and asked to import.",
|
||||
inputSchema: { tripId: idSchema, ...tourGpxImportRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async importTourGpx({ tripId, ...request }: { tripId: number } & TourGpxImportRequest, ctx: McpContext) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
return ok(await this.hikes.importGpx(tripId, request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { badRequest, DomainError } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import {
|
||||
hikeCreateCommandOf,
|
||||
hikePointsOf,
|
||||
hikeProposalOf,
|
||||
keptWayOf,
|
||||
repointedWaypoints,
|
||||
unplannedChangeMessage,
|
||||
unplannedCreateMessage,
|
||||
type KeptWay,
|
||||
} from './hike-plan.helpers';
|
||||
import { HikeRoutingService, type PlannedHike } from './hike-routing.service';
|
||||
import { noTrackFound } from './tour-file-import.helpers';
|
||||
import { tourRevisionConflict } from './tour-revision';
|
||||
import { ToursService, type ImportGpxAsTourResult, type TourCreateCommand } from './tours.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
HIKE_PLAN_MAX_WAYPOINTS,
|
||||
hikingPreferencesOf,
|
||||
tourGpxImportFieldsSchema,
|
||||
TOURS_MAX_HIKING_DIFFICULTY,
|
||||
type HikeCreateRequest,
|
||||
type HikePlanPoint,
|
||||
type HikeProposal,
|
||||
type HikeProposeRequest,
|
||||
type HikingPreferences,
|
||||
type TourCreateResponse,
|
||||
type TourDetailResponse,
|
||||
type TourGpxImportRequest,
|
||||
type HikeRouteOutcome,
|
||||
type TourUpdateRequest,
|
||||
type TourWaypoint,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** What a hike created over MCP answers: the tour as the planner's save answers it, and whether its way was planned. */
|
||||
export type HikeCreated = TourCreateResponse & { route: HikeRouteOutcome };
|
||||
|
||||
/** What a change answers: the tour as now saved, whether its way was planned anew, and how that went. */
|
||||
export type HikeChanged = TourDetailResponse & { route: HikeRouteOutcome; replanned: boolean };
|
||||
|
||||
/** The name an import keeps when the request gives none, and the ending that has the text read as GPX. */
|
||||
const GPX_NAME = 'import.gpx';
|
||||
|
||||
function gpxFileName(name: string | undefined): string {
|
||||
if (!name) return GPX_NAME;
|
||||
return name.toLowerCase().endsWith('.gpx') ? name : `${name}.gpx`;
|
||||
}
|
||||
|
||||
/** Whether two sets of preferences ask the router for the same, each as a hike keeps it. */
|
||||
function samePreferences(a: HikingPreferences | null, b: HikingPreferences | null): boolean {
|
||||
return JSON.stringify(a) === JSON.stringify(b);
|
||||
}
|
||||
|
||||
/** A hike whose way cannot be planned: refused with why, as a 422 the tools answer with its text. */
|
||||
function notRouted(message: string): DomainError {
|
||||
return new DomainError(422, message, { code: 'hike_not_routed' });
|
||||
}
|
||||
|
||||
/** A section of the hike's way drawn by hand, which the planner alone plans around. */
|
||||
const HAND_DRAWN =
|
||||
'This hike has a section drawn by hand (a via ferrata, a free line or a ferry) that only the planner plans around: change its way there. A new name, description or planned time is changed here.';
|
||||
|
||||
/**
|
||||
* Why new points are refused for a saved hike: a section drawn by hand or the
|
||||
* ends of its stages would go with the points they belong to, and a stage
|
||||
* that goes would leave its day. Null where new points take nothing away.
|
||||
*/
|
||||
function repointingRefusal(saved: readonly TourWaypoint[]): string | null {
|
||||
if (saved.some((point) => point.fixed_leg)) return HAND_DRAWN;
|
||||
if (saved.some((point) => point.stage_end)) {
|
||||
return 'This hike is split into stages over several days, which new points would end: change its points in the planner. A new limit or new preferences plan it anew here, its stages kept.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A hike planned with the traveller over MCP, end to end on the server: the
|
||||
* proposal reads only and may be asked for as often as ways are compared;
|
||||
* the hike is created once the traveller said yes, through the creation the
|
||||
* planner's save uses (one write, the trip told); a saved hike is changed
|
||||
* through the route write the planner's edit uses, against the revision it
|
||||
* was read at; a GPX file's text is taken in through the tours' file import.
|
||||
* The way is planned by HikeRoutingService under the hike's limit and
|
||||
* preferences. Refusals are DomainErrors, which REST and the MCP registry
|
||||
* answer with their text.
|
||||
*/
|
||||
@Injectable()
|
||||
export class HikePlanService {
|
||||
constructor(
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly routing: HikeRoutingService,
|
||||
private readonly tours: ToursService,
|
||||
) {}
|
||||
|
||||
/** The way through the points; `grades` for a proposal only, which shows them. */
|
||||
private async plan(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
points: HikePlanPoint[],
|
||||
limit: number | undefined,
|
||||
preferences: HikingPreferences | null | undefined,
|
||||
grades: boolean,
|
||||
): Promise<PlannedHike> {
|
||||
return await this.routing.plan(
|
||||
userId,
|
||||
tripId,
|
||||
{ waypoints: points, max_hiking_difficulty: limit, hiking_preferences: preferences },
|
||||
{ grades },
|
||||
);
|
||||
}
|
||||
|
||||
async propose(userId: number, tripId: number, request: HikeProposeRequest): Promise<HikeProposal> {
|
||||
const points = hikePointsOf(request.waypoints, request.round_trip);
|
||||
const { max_hiking_difficulty: limit, hiking_preferences: preferences } = request;
|
||||
const planned = await this.plan(userId, tripId, points, limit, preferences, true);
|
||||
return hikeProposalOf(request, points, planned);
|
||||
}
|
||||
|
||||
/**
|
||||
* The hike created from its points with the way planned on the server and
|
||||
* kept whole with its heights. Where the router did not answer, for the way
|
||||
* or for its heights, it is saved with its points only (route_pending), and
|
||||
* the planner plans the way when it is opened. Any other reason stands in
|
||||
* the planner as well (no Valhalla, no way within the limit, a point off
|
||||
* every way, a way too long), so the hike is refused and nothing is saved.
|
||||
*/
|
||||
async create(userId: number, tripId: number, request: HikeCreateRequest): Promise<HikeCreated> {
|
||||
const points = hikePointsOf(request.waypoints, request.round_trip);
|
||||
const { max_hiking_difficulty: limit, hiking_preferences: preferences } = request;
|
||||
const planned = await this.plan(userId, tripId, points, limit, preferences, false);
|
||||
const way = keptWayOf(planned);
|
||||
if ('why' in way.route && way.route.why !== 'router_unavailable') {
|
||||
throw notRouted(unplannedCreateMessage(way.route));
|
||||
}
|
||||
const command = hikeCreateCommandOf(request, points, way, planned.plan.max_hiking_difficulty);
|
||||
const created = await this.tours.createTour(String(tripId), command);
|
||||
return { ...created, route: way.route };
|
||||
}
|
||||
|
||||
/**
|
||||
* A saved hike changed against the revision it was read at; a change based
|
||||
* on an older one is refused before the router is asked (the write checks it
|
||||
* again). New points, a new limit or new preferences plan the way anew, and
|
||||
* so does a hike still waiting for its way; a name, a description or a
|
||||
* planned time alone keep the way it has. A new way that cannot be planned,
|
||||
* or not with its heights, refuses the change rather than drop the way the
|
||||
* hike has; a hike still waiting for its way keeps waiting. New points keep
|
||||
* the links of the saved points they stand on, and are refused for a hike
|
||||
* with a section drawn by hand or with stages, which they would take away.
|
||||
* Only a hike planned in TREK takes it: a recorded track without points of
|
||||
* its own is planned over only with points given, and every other type is
|
||||
* changed in the planner (a city walk through prepare_tour_change and
|
||||
* save_tour_change).
|
||||
*/
|
||||
async update(userId: number, tripId: number, request: TourUpdateRequest): Promise<HikeChanged> {
|
||||
const { placeId } = request;
|
||||
const saved = await this.tours.getTour(String(tripId), String(placeId));
|
||||
const { tour } = saved;
|
||||
if (tour.tour_type !== 'hike') {
|
||||
throw badRequest(
|
||||
'Only a hike is changed here. A city walk is changed with prepare_tour_change and save_tour_change, any other tour in the planner.',
|
||||
);
|
||||
}
|
||||
if (tour.revision !== undefined && tour.revision !== request.expected_revision) {
|
||||
throw tourRevisionConflict(tour.revision);
|
||||
}
|
||||
if (tour.has_waypoints !== true && request.waypoints === undefined) {
|
||||
throw badRequest(
|
||||
'This hike is a recorded track without points of its own: give waypoints to plan it over (the recorded track is kept), or rename it with update_place.',
|
||||
);
|
||||
}
|
||||
const repointing = request.waypoints ? repointingRefusal(saved.waypoints) : null;
|
||||
if (repointing) throw badRequest(repointing);
|
||||
const kept = hikingPreferencesOf(tour.hiking_preferences);
|
||||
// A recorded track keeps no limit of its own; planned over, it takes the planner's.
|
||||
const keptLimit = tour.max_hiking_difficulty ?? TOURS_MAX_HIKING_DIFFICULTY;
|
||||
const limit = request.max_hiking_difficulty ?? keptLimit;
|
||||
const preferences =
|
||||
request.hiking_preferences === undefined ? kept : hikingPreferencesOf(request.hiking_preferences);
|
||||
const line = await this.tours.savedLine(tripId, placeId);
|
||||
const replan =
|
||||
request.waypoints !== undefined ||
|
||||
line.length === 0 ||
|
||||
limit !== keptLimit ||
|
||||
!samePreferences(preferences, kept);
|
||||
|
||||
let way: KeptWay;
|
||||
if (replan) {
|
||||
// New points were refused above for such a hike; a new limit or new preferences are refused here.
|
||||
if (saved.waypoints.some((point) => point.fixed_leg)) throw badRequest(HAND_DRAWN);
|
||||
if (!request.waypoints && saved.waypoints.length > HIKE_PLAN_MAX_WAYPOINTS) {
|
||||
throw badRequest(
|
||||
`This hike has more than ${HIKE_PLAN_MAX_WAYPOINTS} points, more than its way is planned through here: change it in the planner, or give new waypoints.`,
|
||||
);
|
||||
}
|
||||
const points = request.waypoints ?? saved.waypoints.map(({ lat, lng }) => ({ lat, lng }));
|
||||
way = keptWayOf(await this.plan(userId, tripId, points, limit, preferences, false));
|
||||
if ('why' in way.route && line.length > 0) throw notRouted(unplannedChangeMessage(way.route));
|
||||
} else {
|
||||
way = { line, seconds: tour.duration == null ? null : tour.duration * 60, route: { planned: true } };
|
||||
}
|
||||
|
||||
const command: TourCreateCommand = {
|
||||
name: request.name ?? tour.name,
|
||||
...(request.description !== undefined ? { description: request.description } : {}),
|
||||
tour_type: 'hike',
|
||||
route_geometry: way.line,
|
||||
duration_seconds: way.seconds,
|
||||
max_hiking_difficulty: limit,
|
||||
hiking_preferences: preferences,
|
||||
...(request.planned_duration_minutes !== undefined
|
||||
? { planned_duration_minutes: request.planned_duration_minutes }
|
||||
: {}),
|
||||
waypoints: request.waypoints ? repointedWaypoints(request.waypoints, saved.waypoints) : saved.waypoints,
|
||||
expected_revision: request.expected_revision,
|
||||
};
|
||||
const write = await this.tours.routeWrite(command);
|
||||
const drops = await this.uow.transactional(() => this.tours.replaceRoute(tripId, placeId, write));
|
||||
const detail = await this.tours.announceRouteUpdate(String(tripId), placeId, drops);
|
||||
return { ...detail, route: way.route, replanned: replan };
|
||||
}
|
||||
|
||||
/**
|
||||
* A GPX file's text taken in as tours, one for each of its tracks and
|
||||
* routes, through the tours' file import, with the fields the multipart
|
||||
* import takes beside the file and the same refusals.
|
||||
*/
|
||||
async importGpx(tripId: number, { gpx, file_name, ...fields }: TourGpxImportRequest): Promise<ImportGpxAsTourResult> {
|
||||
const checked = tourGpxImportFieldsSchema.safeParse(fields);
|
||||
if (!checked.success) throw badRequest(checked.error.issues.map((issue) => issue.message).join('; '));
|
||||
const fileName = gpxFileName(file_name);
|
||||
const imported = await this.tours.importGpxAsTour(
|
||||
String(tripId),
|
||||
Buffer.from(gpx, 'utf8'),
|
||||
fileName,
|
||||
undefined,
|
||||
checked.data,
|
||||
);
|
||||
if (!imported) throw noTrackFound(fileName);
|
||||
return imported;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { TracedWay } from '../roadtrip/roadtrip-router.service';
|
||||
import { thinnedLine } from './tours.helpers';
|
||||
import {
|
||||
haversineMetres,
|
||||
type GeometryPoint,
|
||||
type HikeSacSegment,
|
||||
type HikeTrailGrades,
|
||||
type SacStep,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The pure halves of a hike planned on the server (HikeRoutingService): the
|
||||
* routed line as one line, its height profile for display, and the SAC
|
||||
* grades of the ways under it laid onto the line as stretches. The measures
|
||||
* along a line and the joining of stretches are here once, for the proposal
|
||||
* (hike-plan.helpers) as well.
|
||||
*/
|
||||
|
||||
type HeightPoint = [number, number, number];
|
||||
|
||||
function hasHeight(point: GeometryPoint): point is HeightPoint {
|
||||
return point.length === 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* The router's line with every point that repeats the one before it left
|
||||
* out: each leg starts on the point the one before ended at, and the planner
|
||||
* in the browser joins its legs the same way. A line that would be left with
|
||||
* a single point stays as it was.
|
||||
*/
|
||||
export function joinedLine(line: ReadonlyArray<readonly [number, number]>): Array<[number, number]> {
|
||||
const kept: Array<[number, number]> = [];
|
||||
for (const [lat, lng] of line) {
|
||||
const last = kept[kept.length - 1];
|
||||
if (!last || last[0] !== lat || last[1] !== lng) kept.push([lat, lng]);
|
||||
}
|
||||
return kept.length >= 2 ? kept : line.map(([lat, lng]): [number, number] => [lat, lng]);
|
||||
}
|
||||
|
||||
/** The line with its heights where every point has one, else as it was without any. */
|
||||
export function heightsOrNone(
|
||||
flat: ReadonlyArray<[number, number]>,
|
||||
measured: readonly GeometryPoint[] | null,
|
||||
): GeometryPoint[] {
|
||||
return measured && measured.length === flat.length && measured.every(hasHeight) ? [...measured] : [...flat];
|
||||
}
|
||||
|
||||
/** Metres along the line at each of its points, the first at 0. */
|
||||
export function metresAlong(line: readonly GeometryPoint[]): number[] {
|
||||
let along = 0;
|
||||
return line.map(([lat, lng], index) => {
|
||||
const before = line[index - 1];
|
||||
if (before) along += haversineMetres(before[0], before[1], lat, lng);
|
||||
return along;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The height profile for display: `[metres along the line, height]` at most
|
||||
* `most` times, spread evenly over the points, the first and the last kept.
|
||||
* Empty where the line has no heights.
|
||||
*/
|
||||
export function profileOf(line: readonly GeometryPoint[], most: number): Array<[number, number]> {
|
||||
const measured = line.filter(hasHeight);
|
||||
if (measured.length < 2 || measured.length !== line.length) return [];
|
||||
const along = metresAlong(measured);
|
||||
const samples = measured.map(([, , height], index): [number, number] => [along[index], height]);
|
||||
return thinnedLine(samples, most).map(([metres, height]): [number, number] => [
|
||||
Math.round(metres),
|
||||
Math.round(height),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A stretch added after the ones before it: joined to the last where it has
|
||||
* the same grade and starts where that one ends, so a stretch of unknown
|
||||
* grade between two of one grade keeps them apart. Changes `stretches`.
|
||||
*/
|
||||
export function addStretch(stretches: HikeSacSegment[], stretch: HikeSacSegment): HikeSacSegment[] {
|
||||
const last = stretches[stretches.length - 1];
|
||||
if (last && last.sac === stretch.sac && last.to_m === stretch.from_m) last.to_m = stretch.to_m;
|
||||
else stretches.push({ ...stretch });
|
||||
return stretches;
|
||||
}
|
||||
|
||||
/** The ways under the line OpenStreetMap could grade, each once, in the order they are walked, at most `limit`. */
|
||||
export function gradableWayIds(ways: readonly TracedWay[], limit: number): number[] {
|
||||
const ids = new Set<number>();
|
||||
for (const way of ways) {
|
||||
if (ids.size === limit) break;
|
||||
if (way.wayId !== null) ids.add(way.wayId);
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
/**
|
||||
* The SAC grades laid onto the line: each way's grade over the stretch it
|
||||
* runs along, neighbours of one grade joined, how much of the line has none,
|
||||
* and the hardest grade found. The described line is matched by the router
|
||||
* and so a little longer or shorter than the planned one; its stretches are
|
||||
* scaled onto the planned length, so they meet the height profile. A way
|
||||
* without a grade, or one no source could be asked about, is unknown, never
|
||||
* easy.
|
||||
*/
|
||||
export function gradesAlong(
|
||||
ways: readonly TracedWay[],
|
||||
steps: ReadonlyMap<number, SacStep>,
|
||||
lengthM: number,
|
||||
): HikeTrailGrades {
|
||||
const traced = ways.reduce((sum, way) => sum + way.metres, 0);
|
||||
const scale = traced > 0 && lengthM > 0 ? lengthM / traced : 1;
|
||||
const segments: HikeSacSegment[] = [];
|
||||
let at = 0;
|
||||
let unknown = 0;
|
||||
for (const way of ways) {
|
||||
const from = at;
|
||||
at += way.metres * scale;
|
||||
const sac = way.wayId === null ? undefined : steps.get(way.wayId);
|
||||
if (sac === undefined) unknown += at - from;
|
||||
else if (at > from) addStretch(segments, { from_m: from, to_m: at, sac });
|
||||
}
|
||||
const total = traced * scale;
|
||||
return {
|
||||
segments: segments.map((segment) => ({
|
||||
...segment,
|
||||
from_m: Math.round(segment.from_m),
|
||||
to_m: Math.round(segment.to_m),
|
||||
})),
|
||||
highest: segments.length > 0 ? Math.max(...segments.map(({ sac }) => sac)) : null,
|
||||
unknown_share: total > 0 ? Math.min(1, Math.round((unknown / total) * 1000) / 1000) : 1,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { badRequest } from '../common/domain-error';
|
||||
import { RoadtripRouterService, RouteRefusal, type RoadtripRoute } from '../roadtrip/roadtrip-router.service';
|
||||
import { gradableWayIds, gradesAlong, heightsOrNone, joinedLine, profileOf } from './hike-routing.helpers';
|
||||
import { TourTrailGradeService } from './tour-trail-grade.service';
|
||||
import { thinnedLine } from './tours.helpers';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
computeTourMetrics,
|
||||
HIKE_MAX_LINE_POINTS,
|
||||
HIKE_PLAN_LINE_POINTS,
|
||||
HIKE_PLAN_PROFILE_SAMPLES,
|
||||
hikePlanRequestSchema,
|
||||
hikingCosting,
|
||||
hikingPreferencesOf,
|
||||
hikingTimeMinutes,
|
||||
sacStepOf,
|
||||
TOUR_MAX_SNAP_M,
|
||||
TOUR_TRAIL_GRADE_MAX_WAYS,
|
||||
TOURS_MAX_HIKING_DIFFICULTY,
|
||||
type GeometryPoint,
|
||||
type HikePlan,
|
||||
type HikePlanRequest,
|
||||
type HikeTrailGrades,
|
||||
type SacStep,
|
||||
type UnroutedHikePlan,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The day the router is asked for. A hike's way does not depend on the day:
|
||||
* the router only keys its cache by one and hands it to a routing plugin,
|
||||
* which a hike never asks.
|
||||
*/
|
||||
const ANY_DAY = 0;
|
||||
|
||||
/** A hike as planned: what the plan shows, and the whole line a tour created from it keeps. */
|
||||
export interface PlannedHike {
|
||||
plan: HikePlan;
|
||||
/**
|
||||
* Every point of the routed line, each with its height or none with one;
|
||||
* null where no way was planned.
|
||||
*/
|
||||
line: GeometryPoint[] | null;
|
||||
}
|
||||
|
||||
/** What a plan asks for besides the way and its heights. */
|
||||
export interface HikePlanOptions {
|
||||
/**
|
||||
* Whether the SAC grades are read (one more question to the router and the
|
||||
* trail grades): a proposal shows them, a hike being saved keeps none.
|
||||
*/
|
||||
grades: boolean;
|
||||
}
|
||||
|
||||
/** What went wrong, for the log. */
|
||||
function reasonOf(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
/** Why a router that gave no way gave none, in the plan's words. */
|
||||
function whyNot(err: unknown): UnroutedHikePlan['why'] {
|
||||
return err instanceof RouteRefusal ? err.why : 'router_unavailable';
|
||||
}
|
||||
|
||||
/**
|
||||
* A hike planned on the server the way the tour planner plans one in the
|
||||
* browser: the way on foot through its points under its hiking limit and
|
||||
* preferences (Valhalla only, through the router the road trip and the city
|
||||
* walks use, so its one paced queue and its choice of Valhalla hold), a point
|
||||
* the router had to move further onto a way than a tour allows named instead
|
||||
* of taken, the heights along the line, its length, climb, descent and the
|
||||
* walking time by the signposts' rule, and the SAC grades OpenStreetMap
|
||||
* records for the ways under it. Heights and grades are best effort: without
|
||||
* heights the line stays flat and its climb unknown, without grades the plan
|
||||
* says they could not be read. A way of more points than HIKE_MAX_LINE_POINTS
|
||||
* is not measured: its heights alone would hold the router's queue up for
|
||||
* every user. Writes nothing.
|
||||
*/
|
||||
@Injectable()
|
||||
export class HikeRoutingService {
|
||||
constructor(
|
||||
private readonly router: RoadtripRouterService,
|
||||
private readonly trailGrades: TourTrailGradeService,
|
||||
) {}
|
||||
|
||||
async plan(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
request: HikePlanRequest,
|
||||
{ grades: withGrades }: HikePlanOptions = { grades: true },
|
||||
): Promise<PlannedHike> {
|
||||
// The tools check their own requests; a change plans through the points a hike has saved, held here to the same.
|
||||
const checked = hikePlanRequestSchema.safeParse(request);
|
||||
if (!checked.success) throw badRequest(checked.error.issues.map((issue) => issue.message).join('; '));
|
||||
const limit = request.max_hiking_difficulty ?? TOURS_MAX_HIKING_DIFFICULTY;
|
||||
const preferences = hikingPreferencesOf(request.hiking_preferences);
|
||||
const unrouted = (why: UnroutedHikePlan['why'], position: number | null = null, snapped: number | null = null) => ({
|
||||
plan: { kind: 'unrouted' as const, max_hiking_difficulty: limit, why, position, snapped_m: snapped },
|
||||
line: null,
|
||||
});
|
||||
let route: RoadtripRoute;
|
||||
try {
|
||||
const points = request.waypoints.map(({ lat, lng }) => ({ lat, lng }));
|
||||
const costingOptions = hikingCosting(limit, preferences);
|
||||
route = await this.router.route(userId, tripId, ANY_DAY, points, 'walking', [], { costingOptions });
|
||||
} catch (err: unknown) {
|
||||
if (!(err instanceof RouteRefusal)) logWarn(`[Hike] no way for trip ${tripId}: ${reasonOf(err)}`);
|
||||
return unrouted(whyNot(err));
|
||||
}
|
||||
const snapped = route.snapped ?? [];
|
||||
const off = snapped.findIndex((point) => point.meters > TOUR_MAX_SNAP_M);
|
||||
if (off >= 0) return unrouted('point_off_the_way', off + 1, Math.round(snapped[off].meters));
|
||||
|
||||
const flat = joinedLine(route.leg.line);
|
||||
if (flat.length > HIKE_MAX_LINE_POINTS) return unrouted('too_long');
|
||||
const lengthM = computeTourMetrics(flat).distanceKm * 1000;
|
||||
const [line, grades] = await Promise.all([
|
||||
this.withHeights(userId, flat),
|
||||
withGrades ? this.gradesOf(userId, flat, lengthM) : null,
|
||||
]);
|
||||
const metrics = computeTourMetrics(line);
|
||||
const ascent = metrics.elevationGainM;
|
||||
const descent = metrics.elevationLossM;
|
||||
const heights = ascent !== null && descent !== null;
|
||||
return {
|
||||
plan: {
|
||||
kind: 'routed',
|
||||
max_hiking_difficulty: limit,
|
||||
hiking_preferences: preferences,
|
||||
distance_m: Math.round(lengthM),
|
||||
ascent_m: heights ? Math.round(ascent) : null,
|
||||
descent_m: heights ? Math.round(descent) : null,
|
||||
duration_minutes: heights
|
||||
? hikingTimeMinutes(metrics.distanceKm, ascent, descent)
|
||||
: Math.round(route.leg.seg.duration / 60),
|
||||
duration_basis: heights ? 'din33466' : 'router',
|
||||
has_heights: heights,
|
||||
line: thinnedLine(line, HIKE_PLAN_LINE_POINTS),
|
||||
profile: profileOf(line, HIKE_PLAN_PROFILE_SAMPLES),
|
||||
grades,
|
||||
},
|
||||
line,
|
||||
};
|
||||
}
|
||||
|
||||
/** The line with the height of every point, or as it was where the heights could not all be read. */
|
||||
private async withHeights(userId: number, flat: Array<[number, number]>): Promise<GeometryPoint[]> {
|
||||
try {
|
||||
return heightsOrNone(flat, await this.router.heights(userId, flat));
|
||||
} catch (err: unknown) {
|
||||
logWarn(`[Hike] no heights: ${reasonOf(err)}`);
|
||||
return heightsOrNone(flat, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The SAC grades along the line: the ways under it from the router, their
|
||||
* grades from OpenStreetMap. Null where either could not be read at all.
|
||||
*/
|
||||
private async gradesOf(
|
||||
userId: number,
|
||||
flat: Array<[number, number]>,
|
||||
lengthM: number,
|
||||
): Promise<HikeTrailGrades | null> {
|
||||
try {
|
||||
const ways = await this.router.wayIds(userId, flat);
|
||||
if (ways.length === 0) return null;
|
||||
const ids = gradableWayIds(ways, TOUR_TRAIL_GRADE_MAX_WAYS);
|
||||
const steps = new Map<number, SacStep>();
|
||||
if (ids.length > 0) {
|
||||
const answer = await this.trailGrades.grades({ way_ids: ids });
|
||||
if (answer.unanswered.length === ids.length) return null;
|
||||
for (const way of answer.ways) if (way.sac_scale) steps.set(way.id, sacStepOf(way.sac_scale));
|
||||
}
|
||||
return gradesAlong(ways, steps, lengthM);
|
||||
} catch (err: unknown) {
|
||||
logWarn(`[Hike] no trail grades: ${reasonOf(err)}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,9 @@ import { CityWalkMcp } from './city-walk.mcp';
|
||||
import { CollectionTourTakeOverController, CollectionToursController } from './collection-tours.controller';
|
||||
import { CollectionToursMcp } from './collection-tours.mcp';
|
||||
import { CollectionToursService } from './collection-tours.service';
|
||||
import { HikePlanMcp } from './hike-plan.mcp';
|
||||
import { HikePlanService } from './hike-plan.service';
|
||||
import { HikeRoutingService } from './hike-routing.service';
|
||||
import { TourActivitiesController } from './tour-activities.controller';
|
||||
import { TourActivitiesMcp } from './tour-activities.mcp';
|
||||
import { TourActivitiesService } from './tour-activities.service';
|
||||
@@ -90,9 +93,12 @@ import { Module } from '@nestjs/common';
|
||||
* link followed by the narrow resolver there (CW-06). A city walk an assistant
|
||||
* prepares from a briefing reads the day and places of the trip through the
|
||||
* tours' own repositories, is planned on foot by RoadtripModule's router and
|
||||
* is created through ToursService (CW-11). A change to a saved city walk an
|
||||
* assistant prepares for review is laid onto its saved points and planned on
|
||||
* foot by the same router, and saves nothing (MCP-T02); once the traveller
|
||||
* is created through ToursService (CW-11). A hike an assistant plans with the
|
||||
* traveller is proposed, created, changed or taken in from a GPX file through
|
||||
* the same writes, its way planned on the server by HikeRoutingService. A
|
||||
* change to a saved city walk an assistant prepares for review is laid onto
|
||||
* its saved points and planned on foot by the same router, and saves nothing
|
||||
* (MCP-T02); once the traveller
|
||||
* confirmed it, it is saved through the tour's own write, which records the
|
||||
* step for a later undo (MCP-T03). The recorded tracks assigned to a tour
|
||||
* (ACT-01) are read with its detail and written through
|
||||
@@ -126,7 +132,8 @@ import { Module } from '@nestjs/common';
|
||||
WandererModule,
|
||||
// The obstacle data a paddle tour's checklist reads (PAD-06, PAD-09).
|
||||
PaddleObstaclesModule,
|
||||
// A city walk prepared over MCP is planned on foot by the router the road trip uses (CW-11).
|
||||
// A city walk prepared over MCP is planned on foot by the router the road trip uses (CW-11),
|
||||
// and a hike planned on the server under its hiking limit, with its heights and the ways under it.
|
||||
RoadtripModule,
|
||||
// A saved change takes the stages a tour no longer has off their days (MDT-02).
|
||||
AssignmentsDomainModule,
|
||||
@@ -190,6 +197,8 @@ import { Module } from '@nestjs/common';
|
||||
TourWalkImportService,
|
||||
CityWalkFootWayService,
|
||||
CityWalkBriefingService,
|
||||
HikeRoutingService,
|
||||
HikePlanService,
|
||||
TourChangePreviewService,
|
||||
TourChangeSaveService,
|
||||
TourChangeUndoService,
|
||||
@@ -203,6 +212,7 @@ import { Module } from '@nestjs/common';
|
||||
TourLibraryMcp,
|
||||
TourWalkImportMcp,
|
||||
CityWalkMcp,
|
||||
HikePlanMcp,
|
||||
TourChangeMcp,
|
||||
TourChangeUndoMcp,
|
||||
TourActivitiesMcp,
|
||||
|
||||
Reference in New Issue
Block a user