feat(tours): the assistant edits stations, reverses and closes tours, sets breaks, colour and copies, and writes ski and paddle plans

City walk changes take edit, reverse and close_loop; edits alone keep the
saved way and never ask the router. update_tour turns a hike round or closes
its loop with reshape. New MCP tools mirror the Tours tab's REST writes and
reads: update_tour_details, set_tour_route_color, copy_tour,
classify_ski_track, set_paddle_plan, decide_paddle_obstacles,
restore_recorded_track, get_tour_trail_details and find_horse_routes, with
change cards, undo where the answer keeps the values before, and broadcast
parity cases.
This commit is contained in:
Maurice
2026-10-23 21:07:41 +02:00
parent c6b3f609b7
commit 767d91146a
68 changed files with 3574 additions and 39 deletions
@@ -162,6 +162,12 @@ export interface TourInsert {
}
/** What a route edit replaces on an existing tour: the type and everything that belongs to it. */
/** The planned times of a tour as P8 writes them, null where there is none. */
interface TourTimesUpdate {
planned_duration_minutes: number | null;
break_additional_minutes: number | null;
}
export type TourUpdate = Omit<
TourInsert,
| 'place_id'
@@ -883,6 +889,23 @@ export class ToursRepository extends TrekRepository<Tours> {
return Number(result.numUpdatedRows ?? 0) > 0;
}
/**
* P8: a tour's planned times alone, as update_tour_details changes them;
* nothing else of the tour is touched. Returns whether a row of that trip was updated.
*/
async updateTimesInTrip(trip_id: number, place_id: number, input: TourTimesUpdate): Promise<boolean> {
const result = await this.db()
.updateTable('tours')
.set({
planned_duration_minutes: input.planned_duration_minutes,
break_additional_minutes: input.break_additional_minutes,
})
.where('place_id', '=', place_id)
.where('place_id', 'in', (eb) => eb.selectFrom('places').select('id').where('trip_id', '=', trip_id))
.executeTakeFirst();
return Number(result.numUpdatedRows ?? 0) > 0;
}
/**
* The paddle plan of a recorded track of the trip: its speeds, the marks
* laid onto it and the moving time they make. The track itself is not
+11 -1
View File
@@ -12,6 +12,7 @@ import {
type TourLoaded,
} from './tour-change.cards';
import { TOUR_DESCRIBERS } from './tour-describe';
import { TOUR_EDIT_CARDS } from './tour-edit.cards';
import { tourListCard } from './tour-lists.cards';
import { proposalCard, savedTourCard } from './tour-route.cards';
import {
@@ -116,6 +117,13 @@ export const TOUR_CARDS: DomainCards = {
},
update_tour: updateTour,
...TOUR_WRITE_CARDS,
...TOUR_EDIT_CARDS,
// A copy is a tour of its own, taken back by deleting it while it is as it was made.
copy_tour: {
write: { verbKey: 'copyTour', entity: 'tour' },
describe: TOUR_DESCRIBERS.copy_tour,
undo: DELETE_CREATED_TOUR,
},
set_city_walk_visit: {
write: { verbKey: 'markVisited', entity: 'tour' },
load: loadVisit,
@@ -135,6 +143,8 @@ export const TOUR_CARDS: DomainCards = {
},
prompt: [
"Every tour type can be planned and saved. Pick the tool by what the user does: a hike (also a trek over several days) propose_hike then create_hike; a bike tour or a run propose_tour (activity bike or run) then create_tour; a city walk propose_city_walk then create_city_walk; a paddle tour plan_paddle_route then create_paddle_tour (it needs water_context river or lake); a ski or winter tour (alpine, snowboard, cross-country, ski touring, snowshoe, winter hike) plan_ski_route then create_ski_tour with the same points, discipline and options, passing the plan's points in order (the from of the first leg and the to of every leg). Profiles: a bike tour is touring (city or trekking bike, the default), road (asphalt only), gravel (gravel and farm tracks) or mtb (rough tracks and trails); a run is running (mostly paved, the default) or trail; ask when it is not clear. A run needs the runner's pace (run_pace_seconds_per_km, 330 for 5:30 min/km): ask for it, never guess one. A hike: propose_hike with a name, and day_id and start_time when known; to compare ways call it up to three times in one step, each with a variant_label and along false, the way you recommend first; create_hike only once the user chose a way. A hike over several days is one hike: stage_end on each stop a day ends at (no day_id), then each stage on its day with assign_place_to_day and tourStageKey.",
'The app draws a proposed, planned or saved tour (route, profile, stops, times, weather, warnings) and lists of tours as cards: do not repeat their figures or list them again, say in one sentence what matters. Once a tour is planned, offer what goes with it: places along it (search_tour_pois), what to pack (get_tour_packing, link_tour_packing), the GPX file (export_tour_gpx).',
"The app draws a proposed, planned or saved tour (route, profile, stops, times, weather, warnings) and lists of tours as cards: do not repeat their figures or list them again, say in one sentence what matters. Once a tour is planned, offer what goes with it: places along it (search_tour_pois), what to pack (get_tour_packing, link_tour_packing), the GPX file (export_tour_gpx). To change a saved tour: a city walk's stations (name, stay, importance, protection, opening hours), its direction or its loop through prepare_tour_change and save_tour_change (edit, reverse, close_loop); a hike's direction or loop with update_tour and reshape; breaks, website, words and planned time of any tour with update_tour_details; its colour with set_tour_route_color; a variant with copy_tour first.",
],
// P8, P9: edits besides the route, and the writes and reads a ski, paddle or horse tour has of its own.
toolControllers: { tours: ['TourEditMcp', 'TourSportWritesMcp'] },
};
@@ -81,12 +81,21 @@ export function replans(args: ToolArgs, saved: unknown): boolean {
: hikingPreferencesOf(recordOf(args.hiking_preferences) as HikingPreferences);
return (
args.waypoints !== undefined ||
args.reshape !== undefined ||
plan.line === null ||
limit !== kept.limit ||
canonicalJson(preferences) !== canonicalJson(kept.preferences)
);
}
/** The points update_tour plans a reshape through: the saved ones turned round, or with the way back to the start. */
export function reshapedPoints(reshape: unknown, points: readonly Row[]): Row[] | null {
const first = points[0];
if (reshape === 'reverse') return [...points].reverse();
if (reshape === 'close_loop' && first) return [...points, { lat: first.lat, lng: first.lng }];
return null;
}
/**
* update_tour: the saved tour, and where the change plans the way anew the
* way it will plan, through the new points or the saved ones under the saved
@@ -100,7 +109,8 @@ export async function loadUpdateTour(args: ToolArgs, read: CardReader): Promise<
if (!saved || !replans(args, saved)) return { plan: null, saved };
const tour = recordOf(recordOf(saved).tour);
const kept = keptSettings(tour);
const points = args.waypoints ?? rowsIn(recordOf(saved).waypoints).map(({ lat, lng }) => ({ lat, lng }));
const savedPoints = rowsIn(recordOf(saved).waypoints).map(({ lat, lng }) => ({ lat, lng }));
const points = args.waypoints ?? reshapedPoints(args.reshape, savedPoints) ?? savedPoints;
const plan = await read('propose_hike', {
name: args.name ?? tour.name,
waypoints: points,
@@ -228,7 +238,8 @@ export function updateTourCard(ctx: PreviewContext, args: ToolArgs, loaded: Tour
const previous = previousOf(loaded.saved);
const planned = hikeCard(loaded.plan, args, ctx.card, 'pending');
if (planned?.routed) return fitted({ ...planned, placeId, name, label: null, previous });
const points = args.waypoints === undefined ? rowsIn(recordOf(loaded.saved).waypoints) : rowsIn(args.waypoints);
const saved = rowsIn(recordOf(loaded.saved).waypoints);
const points = args.waypoints === undefined ? (reshapedPoints(args.reshape, saved) ?? saved) : rowsIn(args.waypoints);
const straight = straightCard(points, 'hike', { placeId, name, previous, problem: heldProblem(planned) });
return straight ? fitted(straight) : null;
}
@@ -104,6 +104,20 @@ export const TOUR_DESCRIBERS = {
rows,
dayId: null,
placeIds: placeId === null ? [] : [placeId],
// PR1-01, PR1-02: a hike turned round or taken back to its start says so as its verb.
...(args.reshape === 'reverse' ? { verbKey: 'reverseTour' as const } : {}),
...(args.reshape === 'close_loop' ? { verbKey: 'closeLoop' as const } : {}),
};
},
// A tour of the trip saved again as a new one: the copy's name, the tour it is made from.
copy_tour: (ctx, args) => {
const source = id(args, 'placeId');
const from = source === null ? '' : (ctx.card.places.get(source)?.name ?? '');
return {
subject: text(args.name),
rows: new Rows().add('route', from),
dayId: null,
placeIds: source !== null && ctx.card.places.has(source) ? [source] : [],
};
},
// A tour of another trip copied in; its own name stays unless the copy is given one.
@@ -0,0 +1,187 @@
import type { Described, PreviewContext, ToolArgs, ToolCards, UndoCall, UndoSnapshot } from '../card-types';
import { argId, readKey, recordOf, type Row } from '../card-values';
import { Rows, text, UNCHECKED } from '../preview-format';
import { byId, snapshotPlaces } from '../undo-snapshot';
import type { AssistantChangeVerbKey } from '@trek/shared';
/**
* P8 and P9 in the chat: the edits of a saved tour besides its route (its
* words and times, the colour of its line, a copy), and the writes a ski or
* paddle tour has of its own. A card names the tour by the trip's place.
* Where the answer keeps what was there before, the way back writes that
* again, while the tour is still at the revision the change raised it to
* (the colour, which raises none, while the place still has it).
*/
/** A place of the trip by its id, '' where the trip card does not hold it. */
function placeName(ctx: PreviewContext, id: number | null): string {
return id === null ? '' : (ctx.card.places.get(id)?.name ?? '');
}
function described(ctx: PreviewContext, args: ToolArgs, rows: Rows, verbKey: AssistantChangeVerbKey): Described {
const placeId = argId(args, 'placeId');
return {
subject: placeName(ctx, placeId),
rows,
dayId: null,
placeIds: placeId === null || !ctx.card.places.has(placeId) ? [] : [placeId],
verbKey,
};
}
/** Minutes as hours and minutes, "1:30 h"; '' for none. */
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 plan of the tour read for an undo, by the call's own arguments. */
function planRead(snapshot: UndoSnapshot, call: UndoCall | undefined): Row {
return recordOf(snapshot.reads.get(readKey('get_tour_plan', { placeId: call?.args.placeId })));
}
/** The tour is still at the revision the change raised it to: nothing was saved on top of it since. */
function stillAtRevision(result: unknown, snapshot: UndoSnapshot, call?: UndoCall): boolean {
if (!call) return false;
const revision = recordOf(recordOf(result).tour).revision;
return typeof revision === 'number' && recordOf(planRead(snapshot, call).tour).revision === revision;
}
const READ_PLAN = (args: ToolArgs) => [{ tool: 'get_tour_plan', args: { placeId: args.placeId } }];
/** The revision the change raised the tour to, the one its way back names. */
function raisedRevision(result: unknown): number | null {
const revision = recordOf(recordOf(result).tour).revision;
return typeof revision === 'number' && Number.isInteger(revision) && revision > 0 ? revision : null;
}
// update_tour_details
const DETAIL_FIELDS = [
'name',
'description',
'website',
'break_additional_minutes',
'planned_duration_minutes',
] as const;
const updateTourDetails: ToolCards = {
write: { verbKey: 'updateTour', entity: 'tour' },
describe: (ctx, args) => {
const current = ctx.card.places.get(argId(args, 'placeId') ?? 0);
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));
// A field cleared reads as cleared, not as left out.
const cleared = (value: string) => value || UNCHECKED;
if (args.website !== undefined) rows.add('website', cleared(text(args.website)));
if (args.break_additional_minutes !== undefined) rows.add('breaks', cleared(hours(args.break_additional_minutes)));
if (args.planned_duration_minutes !== undefined) rows.add('time', cleared(hours(args.planned_duration_minutes)));
return described(ctx, args, rows, 'updateTour');
},
undo: {
tool: 'update_tour_details',
args: (args, result) => {
const revision = raisedRevision(result);
const previous = recordOf(recordOf(result).previous);
const changed = DETAIL_FIELDS.filter((field) => args[field] !== undefined && field in previous);
if (revision === null || changed.length === 0) return null;
return {
placeId: args.placeId,
expected_revision: revision,
...Object.fromEntries(changed.map((field) => [field, previous[field]])),
};
},
reads: READ_PLAN,
unchanged: stillAtRevision,
},
};
// set_tour_route_color
const setRouteColor: ToolCards = {
write: { verbKey: 'setRouteColor', entity: 'tour' },
describe: (ctx, args) => described(ctx, args, new Rows().add('color', text(args.route_color)), 'setRouteColor'),
undo: {
tool: 'set_tour_route_color',
args: (args, result) => {
const answer = recordOf(result);
const previous = answer.previous_route_color;
return previous === undefined ? null : { placeId: args.placeId, route_color: previous };
},
unchanged: (result, snapshot) => {
const answer = recordOf(result);
const place = byId(snapshotPlaces(snapshot), answer.place_id);
return place !== undefined && (place.route_color ?? null) === (answer.route_color ?? null);
},
},
};
// classify_ski_track
const classifySki: ToolCards = {
write: { verbKey: 'classifySki', entity: 'tour' },
describe: (ctx, args) => {
const technique = text(args.ski_technique);
const type = technique ? `${text(args.ski_discipline)} (${technique})` : text(args.ski_discipline);
return described(ctx, args, new Rows().add('type', type), 'classifySki');
},
undo: {
tool: 'classify_ski_track',
args: (args, result) => {
const revision = raisedRevision(result);
const previous = recordOf(recordOf(result).previous);
if (revision === null || typeof previous.ski_discipline !== 'string') return null;
return {
placeId: args.placeId,
ski_discipline: previous.ski_discipline,
ski_technique: previous.ski_technique ?? null,
expected_revision: revision,
};
},
reads: READ_PLAN,
unchanged: stillAtRevision,
},
};
// set_paddle_plan
const setPaddlePlan: ToolCards = {
write: { verbKey: 'setPaddlePlan', entity: 'tour' },
// The portages and locks are drawn on the track's own plan card; the change names the tour.
describe: (ctx, args) => described(ctx, args, new Rows(), 'setPaddlePlan'),
undo: {
tool: 'set_paddle_plan',
args: (args, result) => {
const revision = raisedRevision(result);
const previous = recordOf(recordOf(result).previous);
if (revision === null || !previous.track_marks) return null;
return {
placeId: args.placeId,
paddle_speed_kmh: previous.paddle_speed_kmh ?? null,
portage_speed_kmh: previous.portage_speed_kmh ?? null,
track_marks: previous.track_marks,
expected_revision: revision,
};
},
reads: READ_PLAN,
unchanged: stillAtRevision,
},
};
/** A write on one tour that the card names and nothing takes back on its own. */
function plainWrite(verbKey: AssistantChangeVerbKey): ToolCards {
return { write: { verbKey, entity: 'tour' }, describe: (ctx, args) => described(ctx, args, new Rows(), verbKey) };
}
export const TOUR_EDIT_CARDS: Readonly<Record<string, ToolCards>> = {
update_tour_details: updateTourDetails,
set_tour_route_color: setRouteColor,
classify_ski_track: classifySki,
set_paddle_plan: setPaddlePlan,
// The decisions are bound to the data the travellers saw; taking them back is a decision of its own.
decide_paddle_obstacles: plainWrite('decideObstacles'),
// The planning it drops is gone; copy_tour first keeps it.
restore_recorded_track: plainWrite('restoreTrack'),
};
+1 -1
View File
@@ -88,7 +88,7 @@ export class HikePlanMcp {
@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) takes new points, a new limit or new preferences only in the planner: those changes are refused here. A hike split into stages takes new points only with stage_end given again on each stop a day ends at, and its stages keep their days where a stop stays where it was. 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.",
"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. reshape turns the saved points instead of new ones: reverse runs the hike the other way round (its last point starts it), close_loop adds the way back from its last point to its start; either plans the way anew and keeps each point's name and link (a hike split into stages is not reversed here, nor one that already ends at its start). 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) takes new points, a new limit or new preferences only in the planner: those changes are refused here. A hike split into stages takes new points only with stage_end given again on each stop a day ends at, and its stages keep their days where a stop stays where it was. 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 (which reverse it and close its loop too), its words, breaks and website with update_tour_details. 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),
+14 -2
View File
@@ -32,6 +32,7 @@ import {
unplannedTourMessage,
} from './tour-plan.helpers';
import { TourPoiSearchService } from './tour-poi-search.service';
import { reshapedHikePoints } from './tour-reshape.helpers';
import { tourRevisionConflict } from './tour-revision';
import { thinnedLine } from './tours.helpers';
import { ToursService, type ImportGpxAsTourResult, type TourCreateCommand } from './tours.service';
@@ -136,6 +137,15 @@ function repointingRefusal(saved: readonly TourWaypoint[], points: readonly Hike
return null;
}
/** The change with the saved points reshaped as its new points, or refused with why (a hike only). */
function withReshape(request: TourUpdateRequest, saved: readonly TourWaypoint[], type: string): TourUpdateRequest {
const { reshape, ...rest } = request;
if (!reshape || type !== 'hike') return rest;
const reshaped = reshapedHikePoints(saved, reshape);
if ('refused' in reshaped) throw badRequest(reshaped.refused);
return { ...rest, waypoints: reshaped.points };
}
/** Stage ends that do not hold (at the start or the end, too many stages): refused with their reason. */
function refuseBadStages(points: readonly HikeStop[], roundTrip: boolean | undefined): void {
const issues = hikeStageIssues(points, roundTrip);
@@ -381,9 +391,11 @@ export class HikePlanService {
* 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;
async update(userId: number, tripId: number, asked: TourUpdateRequest): Promise<HikeChanged> {
const { placeId } = asked;
const saved = await this.tours.getTour(String(tripId), String(placeId));
// PR1-01, PR1-02: a reshape is the saved points turned or closed, then planned as new points are.
const request = asked.reshape ? withReshape(asked, saved.waypoints, saved.tour.tour_type) : asked;
const { tour } = saved;
if (tour.tour_type !== 'hike') {
throw badRequest(
+163 -9
View File
@@ -22,6 +22,7 @@
import {
CITY_WALK_MAX_STATIONS,
isClosedLoop,
TOUR_STATION_EDIT_FIELDS,
type CityWalkStation,
type TourChange,
type TourChangeOp,
@@ -36,7 +37,7 @@ import {
const CHANGEABLE_TYPES: ReadonlySet<string> = new Set(['walk']);
/** How a point of the changed plan came to be: kept from the saved tour, or brought in by a change. */
type DraftOrigin = 'saved' | 'added' | 'replacing' | 'moved';
type DraftOrigin = 'saved' | 'added' | 'replacing' | 'moved' | 'edited' | 'loop';
/** A point of the plan as the changes leave it. */
export type DraftPoint = TourWaypoint & {
@@ -73,7 +74,10 @@ type RefusalReason =
| 'fixed_leg'
| 'place_not_linkable'
| 'too_few_stations'
| 'too_many_stations';
| 'too_many_stations'
| 'reshape_not_alone'
| 'walk_under_way'
| 'already_loop';
/** Why a change, or the whole proposal (change null), cannot be prepared. */
interface ChangeRefusal {
@@ -130,26 +134,32 @@ function newStation(station: CityWalkStation, change: number): DraftPoint {
/** The work in progress: the points without the way back of a loop, and what the changes did so far. */
class ChangeRun {
readonly body: DraftPoint[];
private body: DraftPoint[];
readonly removed: DraftPoint[] = [];
readonly replaced: DraftPoint[] = [];
readonly shapingDropped: DraftPoint[] = [];
readonly refused: ChangeRefusal[] = [];
/** The saved stations a change removed or replaced, which no later change can name. */
private readonly gone = new Set<string>();
/** The way back of a loop as the walk ends: the saved one, turned by a reverse, or the one a close_loop adds. */
private back: DraftPoint | null;
constructor(
private readonly basis: ChangeBasis,
private readonly loop: boolean,
private loop: boolean,
) {
const points = basis.points.map(savedPoint);
this.body = loop ? points.slice(0, -1) : points;
this.back = loop ? (points[points.length - 1] ?? null) : null;
}
apply(change: TourChange, index: number): void {
const number = index + 1;
const refuse = (reason: RefusalReason, key: string | null, days?: StationDone[]) =>
this.refused.push({ change: number, op: change.op, key, reason, ...(days ? { days } : {}) });
if (change.op === 'edit') return this.edit(change, number, refuse);
if (change.op === 'reverse') return this.reverse(number, refuse);
if (change.op === 'close_loop') return this.closeLoop(number, refuse);
const before = this.refused.length;
if ('station' in change) this.checkLink(change.station, (reason) => refuse(reason, null));
if (change.op === 'add') {
@@ -173,6 +183,72 @@ class ChangeRun {
(change.op === 'remove' ? this.removed : this.replaced).push({ ...point, change: number });
}
/**
* The fields an edit names written onto its station, which stays where it
* is: an edit moves nothing, so a protected station or one already done
* takes it too.
*/
private edit(
change: Extract<TourChange, { op: 'edit' }>,
number: number,
refuse: (reason: RefusalReason, key: string) => void,
): void {
const index = this.indexOfStation(change.key, refuse);
if (index === null) return;
const point = this.body[index] as DraftPoint;
const edited: DraftPoint = { ...point, origin: point.origin === 'saved' ? 'edited' : point.origin, change: number };
for (const field of TOUR_STATION_EDIT_FIELDS) {
const value = change[field];
if (value !== undefined) Object.assign(edited, { [field]: value });
}
this.body[index] = edited;
}
/**
* PR1-02 for a city walk: the walk the other way round, as the planner
* turns it. A loop stays a loop from the same start, its start the station
* there; a leg drawn by hand stays on the stretch it covers, its line turned
* with it. Refused once the travellers checked a station off on a day.
*/
private reverse(number: number, refuse: (reason: RefusalReason, key: string | null) => void): void {
if ([...this.basis.done.values()].some((days) => days.length > 0)) {
refuse('walk_under_way', null);
return;
}
// A protected station keeps its place; turned round, every station but the start of a loop moves.
const kept = this.body.filter((point, at) => point.protected === true && !(this.back && at === 0));
for (const point of kept) refuse('protected', point.key ?? null);
if (kept.length > 0) return;
const whole = this.back ? [...this.body, this.back] : this.body;
const turned = reversedPoints(whole).map((point, at): DraftPoint => {
const was = whole.findIndex((one) => one.ref === point.ref);
return was !== at && point.origin === 'saved' ? { ...point, origin: 'moved', change: number } : point;
});
this.body = this.back ? turned.slice(0, -1) : turned;
this.back = this.back ? (turned[turned.length - 1] ?? null) : null;
}
/** PR1-01 for a city walk: a way back from its last station to its start, no station of its own. */
private closeLoop(number: number, refuse: (reason: RefusalReason, key: string | null) => void): void {
const first = this.body[0];
if (this.loop || !first) {
refuse('already_loop', null);
return;
}
this.loop = true;
this.back = {
lat: first.lat,
lng: first.lng,
role: 'end',
sequence: 0,
ref: `new:${number}`,
origin: 'loop',
change: number,
after: null,
replaces: null,
};
}
private replacing(station: CityWalkStation, change: number, key: string): DraftPoint {
return { ...newStation(station, change), origin: 'replacing', replaces: key };
}
@@ -294,8 +370,7 @@ class ChangeRun {
/** The changed points in order with their roles and sequence, the way back of a loop at its start again. */
finished(): DraftPoint[] {
const first = this.body[0];
const last = this.basis.points[this.basis.points.length - 1];
const back = this.loop && first && last ? [{ ...savedPoint(last), lat: first.lat, lng: first.lng }] : [];
const back = this.loop && first && this.back ? [{ ...this.back, lat: first.lat, lng: first.lng }] : [];
const points = [...this.body, ...back];
const end = points.length - 1;
return points.map((point, sequence): DraftPoint => ({
@@ -306,6 +381,74 @@ class ChangeRun {
}
}
type FixedLeg = NonNullable<TourWaypoint['fixed_leg']>;
/** A fixed leg run the other way: its line turned, a crossing by boat between the same points of it. */
export function turnedLeg(leg: FixedLeg): FixedLeg {
const geometry = [...leg.geometry].reverse();
if (leg.kind !== 'ferry') return { ...leg, geometry };
const last = geometry.length - 1;
const crossings = leg.crossings.map(([from, to]): [number, number] => [last - to, last - from]).reverse();
return { ...leg, geometry, crossings };
}
/** What makes a point a station, kept apart so the start of a loop stays the station there. */
const STATION_PARTS = [
'key',
'name',
'stay_minutes',
'importance',
'protected',
'opening_hours',
'poi_category',
] as const;
function stationPartsOf(point: DraftPoint): Partial<DraftPoint> {
return Object.fromEntries(STATION_PARTS.flatMap((part) => (point[part] === undefined ? [] : [[part, point[part]]])));
}
function withoutStationParts(point: DraftPoint): DraftPoint {
const rest = { ...point };
for (const part of STATION_PARTS) delete rest[part];
return rest;
}
/**
* The points the other way round: the leg after a point is the one that led
* into it before, turned. In a loop the way back and the start trade what
* makes each a station (and the ref the changes know it by), so the start
* keeps its key, name and stay (CW-03).
*/
export function reversedPoints(points: readonly DraftPoint[]): DraftPoint[] {
const reversed = points.map((_, index): DraftPoint => {
const point = points[points.length - 1 - index] as DraftPoint;
const before = points[points.length - 2 - index];
const { fixed_leg: _old, ...rest } = point;
const leg = before?.fixed_leg;
return leg && index < points.length - 1 ? { ...rest, fixed_leg: turnedLeg(leg) } : rest;
});
if (!isClosedLoop(points) || reversed.length < 2) return reversed;
const start = reversed[0] as DraftPoint;
const back = reversed[reversed.length - 1] as DraftPoint;
return [
{ ...withoutStationParts(start), ...stationPartsOf(back), ref: back.ref, origin: back.origin },
...reversed.slice(1, -1),
{ ...withoutStationParts(back), ...stationPartsOf(start), ref: start.ref, origin: start.origin },
];
}
/** A reverse or a close_loop goes with edits only: anything else would be laid onto points it turned. */
function reshapeNotAlone(changes: readonly TourChange[]): boolean {
const reshapes = changes.filter((change) => change.op === 'reverse' || change.op === 'close_loop').length;
const others = changes.filter((change) => change.op !== 'edit').length - reshapes;
return reshapes > 1 || (reshapes === 1 && others > 0);
}
/** Whether every change only edits stations, so the walk keeps its way as saved. */
export function editsOnly(changes: readonly TourChange[]): boolean {
return changes.every((change) => change.op === 'edit');
}
/** The whole numbers from `from` up to, not including, `to`. */
function range(from: number, to: number): number[] {
return Array.from({ length: Math.max(0, to - from) }, (_, offset) => from + offset);
@@ -323,12 +466,13 @@ export function applyChanges(basis: ChangeBasis, changes: readonly TourChange[])
});
if (!CHANGEABLE_TYPES.has(basis.tourType)) return whole('type_not_supported');
if (basis.recorded) return whole('recorded_track');
if (reshapeNotAlone(changes)) return whole('reshape_not_alone');
const loop = isClosedLoop(basis.points);
const run = new ChangeRun(basis, loop);
changes.forEach((change, index) => run.apply(change, index));
if (run.refused.length > 0) return { kind: 'refused', refused: run.refused };
const points = run.finished();
const count = stationCount(points, loop);
const count = stationCount(points, isClosedLoop(points));
if (count < 2) return whole('too_few_stations');
if (count > CITY_WALK_MAX_STATIONS && count > stationCount(basis.points.map(savedPoint), loop)) {
return whole('too_many_stations');
@@ -359,12 +503,22 @@ const REFUSAL_TEXT: Record<RefusalReason, string> = {
place_not_linkable: 'the new station names a place that is not a place of this trip, or is a tour',
too_few_stations: 'a city walk keeps at least two stations',
too_many_stations: `a city walk holds at most ${CITY_WALK_MAX_STATIONS} stations`,
reshape_not_alone:
'a reverse or a close_loop is the only change of its proposal besides edits; prepare the other changes apart',
walk_under_way:
'the travellers already visited or skipped stations of this walk; it is not turned round while it is under way',
already_loop: 'this walk already ends where it starts',
};
/** How a refusal names the change it is about: its op and the station it names, where it names one. */
function changeLabel(refusal: ChangeRefusal): string {
if (refusal.key) return `${refusal.op} ${refusal.key}`;
return refusal.op === 'reverse' || refusal.op === 'close_loop' ? refusal.op : `${refusal.op} station`;
}
/** One refusal as a sentence the assistant can pass on. */
function refusalLine(refusal: ChangeRefusal): string {
const about =
refusal.change === null ? 'The proposal' : `Change ${refusal.change} (${refusal.op} ${refusal.key ?? 'station'})`;
const about = refusal.change === null ? 'The proposal' : `Change ${refusal.change} (${changeLabel(refusal)})`;
const days = refusal.days ? `, day ids ${refusal.days.map((day) => `${day.day_id} ${day.status}`).join(', ')}` : '';
return `${about}: ${REFUSAL_TEXT[refusal.reason]}${days}.`;
}
+4 -1
View File
@@ -24,13 +24,16 @@ interface ChangeEffectsInput {
stored: { distance_km: number | null; walking_minutes: number | null };
}
type StationChange = 'kept' | 'added' | 'replaced' | 'moved';
type StationChange = 'kept' | 'added' | 'replaced' | 'moved' | 'edited';
const CHANGE_OF: Record<DraftPoint['origin'], StationChange> = {
saved: 'kept',
added: 'added',
replacing: 'replaced',
moved: 'moved',
edited: 'edited',
// The way back a close_loop adds is no station, so no station row ever names it.
loop: 'added',
};
/** The key a point is saved under; null for a station a change brings in, which gets one when saved. */
@@ -4,7 +4,7 @@ import type { TourStationVisitsRepository } from '../../db/repositories/TourStat
import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
import { DomainError } from '../common/domain-error';
import { CityWalkFootWayService } from './city-walk-foot-way.service';
import { applyChanges, refusalText, type RefusedAction, type StationDone } from './tour-change-apply';
import { applyChanges, editsOnly, refusalText, type RefusedAction, type StationDone } from './tour-change-apply';
import { describeChange } from './tour-change-effects';
import { proposalIdOf, staleProposal } from './tour-change-proposal';
import { ToursService } from './tours.service';
@@ -96,10 +96,13 @@ export class TourChangePreviewService {
async prepare(tripId: number, placeId: number, userId: number, { changes }: TourChangeRequest) {
const { tour, waypoints, outcome } = await this.lay(tripId, placeId, changes, { action: 'prepared' });
const [wayBefore, wayAfter] = await Promise.all([
this.footWays.plan(userId, tripId, waypoints),
this.footWays.plan(userId, tripId, outcome.points),
]);
// Edits alone move no station, so the way after is the way before and the router is asked once.
const [wayBefore, wayAfter] = editsOnly(changes)
? await this.footWays.plan(userId, tripId, waypoints).then((way) => [way, way] as const)
: await Promise.all([
this.footWays.plan(userId, tripId, waypoints),
this.footWays.plan(userId, tripId, outcome.points),
]);
const revision = tour.revision ?? null;
return {
prepared_only: true,
@@ -6,7 +6,7 @@ import { DomainError } from '../common/domain-error';
import { UnitOfWork } from '../database/unit-of-work';
import type { FootWay } from './city-walk-briefing.helpers';
import { CityWalkFootWayService } from './city-walk-foot-way.service';
import type { DraftPoint } from './tour-change-apply';
import { editsOnly, type DraftPoint } from './tour-change-apply';
import { asWaypoint } from './tour-change-effects';
import { TourChangePreviewService } from './tour-change-preview.service';
import { proposalIdOf } from './tour-change-proposal';
@@ -14,7 +14,13 @@ import { tourWriteOf, writtenStations, writtenTour } from './tour-change-write';
import { ToursService, type TourCreateCommand, type TourRouteDrops } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { TourChangeSaveRequest, TourDetailResponse, TourListItem, TourWaypoint } from '@trek/shared';
import type {
GeometryPoint,
TourChangeSaveRequest,
TourDetailResponse,
TourListItem,
TourWaypoint,
} from '@trek/shared';
/** The refusal of a save naming a proposal other than the one these changes were prepared as. */
export const TOUR_CHANGE_NOT_PREPARED = 'tour_change_not_prepared';
@@ -25,6 +31,12 @@ interface ChangedTour {
points: readonly DraftPoint[];
way: FootWay;
preparedOn: number;
/**
* Edits alone move no station: the walk keeps its saved line (heights and
* all) and its walking time, and the router is not asked, so a router that
* is down never takes the way of a walk whose stays were changed.
*/
kept?: { line: GeometryPoint[] | null; seconds: number | null };
}
/** The step a save recorded: its id and the revision it raised the tour to. */
@@ -42,11 +54,11 @@ type SaveOutcome = { earlier: TourChangeStepRow } | ({ step: SavedStep } & TourR
* only, as a created one does (CW-11): no line, no distance and no walking
* time until the planner plans the way.
*/
function writeOf({ tour, points, way, preparedOn }: ChangedTour): TourCreateCommand {
function writeOf({ tour, points, way, preparedOn, kept }: ChangedTour): TourCreateCommand {
const routed = way.kind === 'routed' ? way : null;
return tourWriteOf(tour, {
route_geometry: routed?.line ?? null,
duration_seconds: routed?.seconds ?? null,
route_geometry: kept ? kept.line : (routed?.line ?? null),
duration_seconds: kept ? kept.seconds : (routed?.seconds ?? null),
waypoints: points.map(asWaypoint),
expected_revision: preparedOn,
});
@@ -129,8 +141,14 @@ export class TourChangeSaveService {
const earlier = await this.stepsRepo.findSavedProposal(placeId, proposalId, preparedOn);
if (earlier) return alreadySavedAnswer(earlier);
const laid = await this.preview.lay(tripId, placeId, changes, { action: 'saved', preparedOn });
const way = await this.footWays.plan(userId, tripId, laid.outcome.points);
const changed: ChangedTour = { tour: laid.tour, points: laid.outcome.points, way, preparedOn };
const changed: ChangedTour = editsOnly(changes)
? await this.keptWay(tripId, placeId, laid.tour, laid.outcome.points, preparedOn)
: {
tour: laid.tour,
points: laid.outcome.points,
way: await this.footWays.plan(userId, tripId, laid.outcome.points),
preparedOn,
};
const write = await this.tours.routeWrite(writeOf(changed));
const saved = await this.uow.transactional(async (): Promise<SaveOutcome> => {
// The same proposal saved by a save sent alongside this one while the way was planned.
@@ -159,6 +177,23 @@ export class TourChangeSaveService {
return savedAnswer(detail, saved.step, changed);
}
/** A change of edits only, written with the walk's saved line and walking time. */
private async keptWay(
tripId: number,
placeId: number,
tour: TourListItem,
points: readonly DraftPoint[],
preparedOn: number,
): Promise<ChangedTour> {
const line = await this.tours.savedLine(tripId, placeId);
const way: FootWay =
line.length >= 2
? { kind: 'routed', line: line.map(([lat, lng]): [number, number] => [lat, lng]), legs: [], seconds: 0 }
: { kind: 'unrouted', why: 'nothing_to_route', position: null };
const seconds = tour.duration == null ? null : tour.duration * 60;
return { tour, points, way, preparedOn, kept: { line: line.length >= 2 ? line : null, seconds } };
}
/** The tour as it is before the change, as the step keeps it: its line, its points and its measures. */
private async beforeState(
tripId: number,
+10 -1
View File
@@ -24,7 +24,9 @@ export interface TourLineWrite {
/**
* The write of a tour's line and points, everything else of the tour as it
* is: a change of stations, or taking one back, changes nothing else.
* is: a change of stations, or taking one back, changes nothing else. Every
* setting of every type goes along, so a type that is no city walk keeps its
* profile, pace, discipline or boat through such a write as well.
*/
export function tourWriteOf(tour: TourListItem, line: TourLineWrite): TourCreateCommand {
return {
@@ -35,6 +37,13 @@ export function tourWriteOf(tour: TourListItem, line: TourLineWrite): TourCreate
max_hiking_difficulty: tour.max_hiking_difficulty,
hiking_preferences: tour.hiking_preferences,
bike_profile: tour.bike_profile,
run_profile: tour.run_profile,
run_pace_seconds_per_km: tour.run_pace_seconds_per_km,
ski_discipline: tour.ski_discipline,
ski_technique: tour.ski_technique,
ski_options: tour.ski_options,
ski_route_build: tour.ski_route_build,
ski_planned_legs: tour.ski_planned_legs,
boat_type: tour.boat_type,
water_context: tour.water_context,
paddle_speed_kmh: tour.paddle_speed_kmh,
+1 -1
View File
@@ -54,7 +54,7 @@ export class TourChangeMcp {
@Tool({
name: 'prepare_tour_change',
description:
"Prepare a change to a saved tour for the traveller to review, without saving anything: no tour, station, visit or day plan changes, and turning it down keeps the plan as it is. Read the tour with get_tour_plan first. A city walk (tour_type walk) takes changes so far; every other type, and a walk that is a recorded track without stations of its own, is refused with the reason. changes apply in order, each naming saved stations by their key: add (a new station after after_key; a spontaneous stop is an add after the station the traveller is at), remove, replace (a new station in the place of key) and move (key to after after_key). Stops put after the same station keep the order given. A station protected, or visited or skipped on any day of the walk, is never removed, replaced or moved, nothing is put before the last station already done, and a leg drawn by hand stays as drawn (the closing leg of a loop included); such a change is refused, and so is the whole proposal, with every reason in the error. The answer: prepared_only (always true), base (the tour and the revision it was prepared on: a save has to name it, and a tour changed since is refused rather than overwritten, so prepare again), stations_after (each with its key, null for a new one, change kept, added, replaced or moved, by_change, was_position and what it replaces), removed, effects (walking: the whole way on foot before and after planned by TREK's router and the change in metres and minutes, the distance and walking time stored with the walk apart; stays: known minutes and unknown stays before and after; legs: each leg after, new ones marked), data_gaps (what could not be worked out and why: no way from the router, stays not known, no arrival times, shaping points dropped because the leg they steered changed), warnings (a must station removed or replaced), for_later (each new station not yet a place of the trip as create_place takes it, to keep it as a place instead; a station with linked_place_id already is one and is left out) and waypoints_after. proposal_id names this very proposal for save_tour_change. Show every change and its effects to the traveller and save nothing without their yes. can_save says whether they may change the trip's places.",
"Prepare a change to a saved tour for the traveller to review, without saving anything: no tour, station, visit or day plan changes, and turning it down keeps the plan as it is. Read the tour with get_tour_plan first. A city walk (tour_type walk) takes changes so far; every other type, and a walk that is a recorded track without stations of its own, is refused with the reason. changes apply in order, each naming saved stations by their key: add (a new station after after_key; a spontaneous stop is an add after the station the traveller is at), remove, replace (a new station in the place of key), move (key to after after_key) and edit (what station key says of itself: name, stay_minutes with 0 for a point passed through and null for not known, importance optional or must with null for normal, protected, opening_hours; only the fields given change, the station stays where it is, and a protected or already visited station takes an edit too). reverse turns the whole walk round (a loop stays a loop from the same start) and close_loop adds the way back from its last station to its start; each of them is the only change of its proposal besides edits, a walk under way (a station visited or skipped) is not reversed, nor one with a protected station off its start. Stops put after the same station keep the order given. Edits alone keep the walk's saved way and walking time. A station protected, or visited or skipped on any day of the walk, is never removed, replaced or moved, nothing is put before the last station already done, and a leg drawn by hand stays as drawn (the closing leg of a loop included); such a change is refused, and so is the whole proposal, with every reason in the error. The answer: prepared_only (always true), base (the tour and the revision it was prepared on: a save has to name it, and a tour changed since is refused rather than overwritten, so prepare again), stations_after (each with its key, null for a new one, change kept, added, replaced or moved, by_change, was_position and what it replaces), removed, effects (walking: the whole way on foot before and after planned by TREK's router and the change in metres and minutes, the distance and walking time stored with the walk apart; stays: known minutes and unknown stays before and after; legs: each leg after, new ones marked), data_gaps (what could not be worked out and why: no way from the router, stays not known, no arrival times, shaping points dropped because the leg they steered changed), warnings (a must station removed or replaced), for_later (each new station not yet a place of the trip as create_place takes it, to keep it as a place instead; a station with linked_place_id already is one and is left out) and waypoints_after. proposal_id names this very proposal for save_tour_change. Show every change and its effects to the traveller and save nothing without their yes. can_save says whether they may change the trip's places.",
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
@@ -0,0 +1,134 @@
import { Tours } from '../../db/entities/Tours.entity';
import type { ToursRepository } from '../../db/repositories/Tours.repository';
import { isUpdateConflict } from '../common/conflictResult';
import { badRequest } from '../common/domain-error';
import { UnitOfWork } from '../database/unit-of-work';
import { PlacesService } from '../places/places.service';
import { advanceTourRevision } from './tour-revision';
import { ToursService } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, NotFoundException } from '@nestjs/common';
import {
maxTourMinutesFor,
plannedTimeLimitMessage,
tourStageCountOf,
type TourDetailsUpdateRequest,
type TourListItem,
} from '@trek/shared';
/** A tour's words and planned times, as update_tour_details reads and writes them. */
interface TourDetails {
name: string;
description: string | null;
website: string | null;
break_additional_minutes: number | null;
planned_duration_minutes: number | null;
}
function detailsOf(tour: TourListItem): TourDetails {
return {
name: tour.name,
description: tour.description ?? null,
website: tour.website ?? null,
break_additional_minutes: tour.break_additional_minutes ?? null,
planned_duration_minutes: tour.planned_duration_minutes ?? null,
};
}
/** The value a change gives a field, or the one it keeps. */
function next<K extends keyof TourDetails>(request: TourDetailsUpdateRequest, before: TourDetails, key: K) {
const value = request[key];
return (value === undefined ? before[key] : value) as TourDetails[K];
}
/**
* P8: the edits of a saved tour besides its route, for every type, a
* recorded track included. Its words (name, description, website) are the
* place's, written through the places' own update; its planned times are
* the tour's, held to the limit the planner's save holds them to (the moving
* time and the breaks within a day, a day a stage for a tour over several
* days, unless a planned total is set). Both go in one transaction that
* raises the tour's revision against the one it was read at, and the trip
* hears tours:changed and place:updated as after the planner's save. The
* route, the points and the days stay as they are.
*
* Also the two writes the tour detail makes on the place: the colour of its
* line, and the copy of the tour as a new one of the trip.
*/
@Injectable()
export class TourDetailsService {
constructor(
private readonly uow: UnitOfWork,
private readonly tours: ToursService,
private readonly places: PlacesService,
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
) {}
async update(tripId: number, request: TourDetailsUpdateRequest) {
const { placeId } = request;
const detail = await this.tours.getTour(String(tripId), String(placeId));
const before = detailsOf(detail.tour);
const after: TourDetails = {
name: next(request, before, 'name'),
description: next(request, before, 'description'),
website: next(request, before, 'website'),
break_additional_minutes: next(request, before, 'break_additional_minutes'),
planned_duration_minutes: next(request, before, 'planned_duration_minutes'),
};
const stages = tourStageCountOf(detail.waypoints);
const moving = detail.tour.duration;
if (
after.planned_duration_minutes == null &&
moving != null &&
after.break_additional_minutes != null &&
moving + after.break_additional_minutes > maxTourMinutesFor(stages)
) {
throw badRequest(plannedTimeLimitMessage(stages));
}
const words = request.name !== undefined || request.description !== undefined || request.website !== undefined;
const times = request.break_additional_minutes !== undefined || request.planned_duration_minutes !== undefined;
const revision = await this.uow.transactional(async () => {
const raised = await advanceTourRevision(this.toursRepo, placeId, request.expected_revision);
if (words) {
// The places' update keeps a field it is not handed; website and description clear with null.
const place = await this.places.update(String(tripId), String(placeId), {
name: after.name,
description: after.description,
website: after.website,
} as Parameters<PlacesService['update']>[2]);
if (!place) throw new NotFoundException('Tour not found');
}
if (times) {
const { planned_duration_minutes, break_additional_minutes } = after;
await this.toursRepo.updateTimesInTrip(tripId, placeId, { planned_duration_minutes, break_additional_minutes });
}
return raised;
});
const saved = await this.tours.announceRouteUpdate(String(tripId), placeId, {
visitsDropped: [],
stagesDropped: [],
});
return {
tour: { place_id: placeId, tour_type: saved.tour.tour_type, revision, ...detailsOf(saved.tour) },
previous: { revision: detail.tour.revision ?? null, ...before },
};
}
/**
* The colour the tour's line is drawn in, as the tour detail sets it on the
* place: through the places' update and its place:updated, without raising
* the tour's revision (the route is not touched). Null draws it in the
* colour of its type again.
*/
async setRouteColor(tripId: number, placeId: number, color: string | null) {
if (!(await this.toursRepo.findInTrip(tripId, placeId))) throw new NotFoundException('Tour not found');
const current = await this.places.get(String(tripId), String(placeId));
if (!current) throw new NotFoundException('Tour not found');
const place = await this.places.update(String(tripId), String(placeId), { route_color: color });
// No base version is sent, so the update never answers a conflict; the check only narrows the type.
if (!place || isUpdateConflict(place)) throw new NotFoundException('Tour not found');
this.places.broadcast(String(tripId), 'place:updated', { place }, undefined);
await this.places.onUpdated(place.id);
return { place_id: placeId, route_color: color, previous_route_color: current.route_color ?? null };
}
}
+115
View File
@@ -0,0 +1,115 @@
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import {
McpController,
Tool,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
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 { TourDetailsService } from './tour-details.service';
import { ToursService } from './tours.service';
import { NotFoundException } from '@nestjs/common';
import {
idSchema,
tourCopyToolRequestSchema,
tourDetailsUpdateRequestSchema,
tourRouteColorRequestSchema,
type TourCopyToolRequest,
type TourDetailsUpdateRequest,
type TourRouteColorRequest,
} from '@trek/shared';
/** A tour the trip does not hold answers as not found, as REST answers its 404. */
async function orNotFound<T>(write: () => Promise<T>) {
try {
return ok(await write());
} catch (err: unknown) {
if (err instanceof NotFoundException) return errorResult('Tour not found.');
throw err;
}
}
/**
* P8: the edits of a saved tour besides its route, for every type: its words
* and planned times (the planner's editor fields, saved over REST with the
* tour's PUT), the colour of its line (the tour detail's colour picker, the
* places' PUT) and a copy of it as a new tour of the trip (POST .../copy).
* Each asks 'place_edit' on the trip as those routes do, and a refusal of the
* service (a time past the day's limit, a tour changed since it was read) is
* a DomainError the registry answers with the text REST sends.
*/
@McpController()
export class TourEditMcp {
constructor(
private readonly details: TourDetailsService,
private readonly tours: ToursService,
private readonly access: TripAccessService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
/** Trip access, then 'place_edit', as the REST routes check them; null when both hold. */
private async refusal(tripId: number, userId: number) {
if (!(await this.access.findAccessible(tripId, userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, userId))) return permissionDenied();
return null;
}
@Tool({
name: 'update_tour_details',
description:
'Change the words and planned times of a saved tour of any type (a hike, a city walk, a bike tour, a run, a paddle, ski or horse tour, a recorded track too) without touching its route, its points or its days: name, description, website (an https URL), break_additional_minutes (the breaks on top of the moving time) and planned_duration_minutes (the time out in all the travellers set themselves, breaks included); only the fields given change, null clears one. expected_revision is tour.revision from get_tour_plan or list_tours: a tour changed since is refused as a conflict, read it again. The moving time and the breaks stay within a day (a day a stage for a tour over several days) unless a planned total is set, as in the planner. The answer gives the tour as now saved with its new revision, and previous, the values before. Needs place editing permission on the trip. Change it only after the traveller said yes.',
inputSchema: { tripId: idSchema, ...tourDetailsUpdateRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async updateTourDetails({ tripId, ...request }: { tripId: number } & TourDetailsUpdateRequest, ctx: McpContext) {
const refused = await this.refusal(tripId, ctx.userId);
if (refused) return refused;
const checked = tourDetailsUpdateRequestSchema.safeParse(request);
if (!checked.success) return errorResult(checked.error.issues.map((issue) => issue.message).join('; '));
return await orNotFound(() => this.details.update(tripId, checked.data));
}
@Tool({
name: 'set_tour_route_color',
description:
'Draw the line of a saved tour in another colour on the map, as the colour picker of the tour detail does: route_color is a hex colour such as "#e11d48", null draws it in the colour of its tour type again. Only the colour changes: the route, the revision and the days stay as they are. The answer gives route_color and previous_route_color. Needs place editing permission on the trip.',
inputSchema: { tripId: idSchema, ...tourRouteColorRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async setTourRouteColor(
{ tripId, placeId, route_color }: { tripId: number } & TourRouteColorRequest,
ctx: McpContext,
) {
const refused = await this.refusal(tripId, ctx.userId);
if (refused) return refused;
return await orNotFound(() => this.details.setRouteColor(tripId, placeId, route_color));
}
@Tool({
name: 'copy_tour',
description:
'Save a tour of the trip again as a new, independent tour of the same trip under its own name, as the planner\'s "save as new tour" does: the copy has its own id, line and control points, the same type, measures and settings, its stops keep their links to the trip\'s places, and it is on no day yet (put it on one with assign_place_to_day). Use it to try a variant without losing the original: copy first, then change the copy. The answer is the copy as list_tours reads it (tour.place_id is its id, revision 1). Needs place editing permission on the trip. Copy only when the traveller asked for it.',
inputSchema: { tripId: idSchema, ...tourCopyToolRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async copyTour({ tripId, placeId, name }: { tripId: number } & TourCopyToolRequest, ctx: McpContext) {
const refused = await this.refusal(tripId, ctx.userId);
if (refused) return refused;
return await orNotFound(() => this.tours.copyTour(String(tripId), String(placeId), name));
}
}
@@ -0,0 +1,43 @@
/**
* PR1-01 and PR1-02 for a saved hike changed over MCP: its points the other
* way round, or taken back to its start, as the planner's route tools turn
* them. Only the points are worked out here; update_tour plans the way
* through them anew, under the hike's limit and preferences, and keeps each
* point's name, key and link where it stands where a saved one stood.
*/
import { isClosedLoop, type HikeStop, type TourReshape, type TourWaypoint } from '@trek/shared';
/** The points a reshaped hike is planned through, or why it cannot be reshaped. */
type Reshaped = { points: HikeStop[] } | { refused: string };
/** A saved point as update_tour takes a new one: where it is, what it is, and whether a stage ends there. */
function stopOf(point: TourWaypoint): HikeStop {
return {
lat: point.lat,
lng: point.lng,
...(point.name ? { name: point.name } : {}),
...(point.poi_category ? { poi_category: point.poi_category } : {}),
...(point.stage_end ? { stage_end: true } : {}),
};
}
export function reshapedHikePoints(saved: readonly TourWaypoint[], reshape: TourReshape): Reshaped {
if (saved.length < 2) {
return {
refused:
'This hike is a recorded track without points of its own, so there is nothing to turn: give waypoints to plan it over first.',
};
}
if (reshape === 'reverse') {
if (saved.some((point) => point.stage_end)) {
return {
refused:
'This hike is split into stages over several days, which keep their days by the stop each starts at: turn it round in the planner, where its stages are put on their days again.',
};
}
return { points: [...saved].reverse().map(stopOf) };
}
if (isClosedLoop(saved)) return { refused: 'This hike already ends where it starts.' };
const first = saved[0] as TourWaypoint;
return { points: [...saved.map(stopOf), { lat: first.lat, lng: first.lng }] };
}
@@ -0,0 +1,255 @@
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import {
McpController,
Tool,
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 { parseHorseRoutesQuery } from './tour-horse-routes.controller';
import { TourHorseRoutesService } from './tour-horse-routes.service';
import { TourObstacleReviewsService } from './tour-obstacle-reviews.service';
import { TourPaddlePlanService } from './tour-paddle-plan.service';
import { TourSkiService } from './tour-ski.service';
import { TourTrailDetailsService } from './tour-trail-details.service';
import { ToursService } from './tours.service';
import { NotFoundException } from '@nestjs/common';
import {
horseRoutesToolRequestSchema,
idSchema,
obstacleDecisionsToolRequestSchema,
skiClassifyToolRequestSchema,
tourObstacleReviewsRequestSchema,
tourPaddlePlanRequestSchema,
tourRefToolRequestSchema,
tourSkiClassificationRequestSchema,
type HorseRoute,
type HorseRoutesToolRequest,
type ObstacleDecisionsToolRequest,
type SkiClassifyToolRequest,
type TourDetailResponse,
type TourPaddlePlanRequest,
type TourRefToolRequest,
} from '@trek/shared';
import type { ZodError } from 'zod';
const plan = tourPaddlePlanRequestSchema.shape;
/** A request the shared contract refuses, answered with every reason as REST's pipe gives them. */
function refusedBy(error: ZodError) {
return errorResult(error.issues.map((issue) => issue.message).join('; '));
}
/** The tour of a write's answer without what only the planner draws: its line, its points, its checklist. */
function tourOf(detail: TourDetailResponse) {
return detail.tour;
}
/** A horse route as the assistant reads it: each section's length, access and signposting, and where it starts and ends. */
function routeInBrief(route: HorseRoute) {
return {
id: route.id,
name: route.name,
ref: route.ref,
osm_url: route.osmUrl,
continues: route.continues,
sections: route.sections.map(({ geometry, ...section }) => ({
...section,
from: geometry[0] ?? null,
to: geometry[geometry.length - 1] ?? null,
})),
};
}
/**
* P9: the writes and reads of the Tours tab that are a type's own, over MCP
* with the services and checks of their REST routes: a ski track classified
* again (PUT .../ski), the paddle plan of a recorded paddle track (PUT
* .../paddle-plan) and the decisions about a paddle tour's obstacles (PUT
* .../obstacle-reviews), an import planned over taken back to its recording
* (POST .../restore-recorded), each with 'place_edit' on the trip; and two
* reads anyone who sees the trip may make, the trail details along a saved
* tour (the planner's trail grades) and the signposted horse routes in a
* map view (GET .../horse-routes). A refusal of a service is a DomainError
* the registry answers with the text REST sends.
*/
@McpController()
export class TourSportWritesMcp {
constructor(
private readonly tours: ToursService,
private readonly ski: TourSkiService,
private readonly paddlePlans: TourPaddlePlanService,
private readonly obstacleReviews: TourObstacleReviewsService,
private readonly trailDetails: TourTrailDetailsService,
private readonly horseRoutes: TourHorseRoutesService,
private readonly access: TripAccessService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
/** Trip access, then 'place_edit', as the REST routes check them; null when both hold. */
private async editRefusal(tripId: number, userId: number) {
if (!(await this.access.findAccessible(tripId, userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, userId))) return permissionDenied();
return null;
}
/** The write, answered with a tour the trip does not hold as not found, as REST answers its 404. */
private async orNotFound<T>(write: () => Promise<T>) {
try {
return ok(await write());
} catch (err: unknown) {
if (err instanceof NotFoundException) return errorResult('Tour not found.');
throw err;
}
}
@Tool({
name: 'classify_ski_track',
description:
'Classify a ski and winter tour (tour_type ski, usually an imported track) again when its discipline is not the right one: ski_discipline alpine, snowboard, cross_country, touring for ski touring, snowshoe or winter_hike, and for cross_country only ski_technique (classic, skating, or unknown when the travellers do not know). Only the classification changes: the track, its measures, its days and where it came from stay as they are, and nothing is planned. Any other type is refused. expected_revision (tour.revision of get_tour_plan) refuses it once the tour changed since. The answer gives the tour as now saved and previous, the discipline and technique before. Needs place editing permission on the trip. Change it only after the traveller said yes.',
inputSchema: { tripId: idSchema, ...skiClassifyToolRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async classifySkiTrack(
{ tripId, placeId, ...request }: { tripId: number } & SkiClassifyToolRequest,
ctx: McpContext,
) {
const refused = await this.editRefusal(tripId, ctx.userId);
if (refused) return refused;
const checked = tourSkiClassificationRequestSchema.safeParse(request);
if (!checked.success) return refusedBy(checked.error);
return await this.orNotFound(async () => {
const before = await this.tours.getTour(String(tripId), String(placeId));
const after = await this.ski.classify(String(tripId), String(placeId), checked.data);
return {
tour: tourOf(after),
previous: {
revision: before.tour.revision ?? null,
ski_discipline: before.tour.ski_discipline ?? null,
ski_technique: before.tour.ski_technique ?? null,
},
};
});
}
@Tool({
name: 'set_paddle_plan',
description:
"Lay the paddle plan onto a recorded paddle track (tour_type kayak without control points of its own, an import), as the track's plan card does: the portages (from_m and to_m, metres from the start of the track, and extra_minutes for getting out and back in, null for TREK's starting value) and locks (at_m with wait_minutes and transit_minutes, null where not known) in track_marks, the paddle_speed_kmh (null for the boat's suggested speed) and the portage_speed_kmh (null for the starting value). The track is never redrawn; its moving time is reckoned anew from the plan. The plan given replaces the whole plan: send every portage and lock to keep. A planned paddle tour saves its portages and locks with its route in the planner and is refused here, and so is a mark past the end of the track. The answer gives the tour as now saved and previous, the plan before. Needs place editing permission on the trip. Change it only after the traveller said yes.",
inputSchema: {
tripId: idSchema,
placeId: tourRefToolRequestSchema.shape.placeId,
paddle_speed_kmh: plan.paddle_speed_kmh,
portage_speed_kmh: plan.portage_speed_kmh,
track_marks: plan.track_marks,
expected_revision: plan.expected_revision,
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async setPaddlePlan(
{ tripId, placeId, ...request }: { tripId: number; placeId: number } & TourPaddlePlanRequest,
ctx: McpContext,
) {
const refused = await this.editRefusal(tripId, ctx.userId);
if (refused) return refused;
const checked = tourPaddlePlanRequestSchema.safeParse(request);
if (!checked.success) return refusedBy(checked.error);
return await this.orNotFound(async () => {
const before = await this.tours.getTour(String(tripId), String(placeId));
const after = await this.paddlePlans.update(String(tripId), String(placeId), checked.data);
return {
tour: tourOf(after),
previous: {
revision: before.tour.revision ?? null,
paddle_speed_kmh: before.tour.paddle_speed_kmh ?? null,
portage_speed_kmh: before.tour.portage_speed_kmh ?? null,
track_marks: before.tour.track_marks ?? { portages: [], locks: [] },
},
};
});
}
@Tool({
name: 'decide_paddle_obstacles',
description:
"Record what the paddlers decided about the obstacles of a paddle tour (tour_type kayak), as its obstacle checklist does: read get_tour_plan first and take each entry's key and basis from its obstacle_check, since a decision is bound to the route and the data the travellers saw. op decide stores decision pass, portage, reroute or not_affected with that basis (and a note), note changes the note only, clear takes the decision back, keep keeps a decision about an object the data no longer holds; each obstacle at most once. A decision is the paddlers' own planning, never a safety or legal clearance, and a ban in the data counts whatever was decided. The answer is the checklist as it now stands (obstacle_check) with the tour. Refused while the obstacle data cannot be read. Needs place editing permission on the trip. Decide only what the traveller decided.",
inputSchema: { tripId: idSchema, ...obstacleDecisionsToolRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async decidePaddleObstacles(
{ tripId, placeId, ops }: { tripId: number } & ObstacleDecisionsToolRequest,
ctx: McpContext,
) {
const refused = await this.editRefusal(tripId, ctx.userId);
if (refused) return refused;
const checked = tourObstacleReviewsRequestSchema.safeParse({ ops });
if (!checked.success) return refusedBy(checked.error);
return await this.orNotFound(async () => {
const after = await this.obstacleReviews.save(String(tripId), String(placeId), checked.data, ctx.userId);
return { tour: tourOf(after), obstacle_check: after.obstacle_check ?? null };
});
}
@Tool({
name: 'restore_recorded_track',
description:
'Take an import that was planned over in place (tour.has_recorded_track true) back to the track it was recorded with: its line, the distance and heights read from it and the grade its source gave, without control points; the planning is dropped and cannot be brought back here (copy_tour it first to keep it). The tour keeps its id, days and notes; a split into stages ends, so a day that held a stage no longer does. A tour without a recorded track to go back to is refused. The answer is the tour as now saved. Needs place editing permission on the trip. Do it only after the traveller said yes.',
inputSchema: { tripId: idSchema, ...tourRefToolRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async restoreRecordedTrack({ tripId, placeId }: { tripId: number } & TourRefToolRequest, ctx: McpContext) {
const refused = await this.editRefusal(tripId, ctx.userId);
if (refused) return refused;
return await this.orNotFound(async () => ({
tour: tourOf(await this.tours.restoreRecordedTrack(String(tripId), String(placeId))),
}));
}
@Tool({
name: 'get_tour_trail_details',
description:
"Read what OpenStreetMap records for the ways a saved tour runs on, along its saved line, as the planner's trail details show it: sac (the SAC hiking grades: highest from 1 for T1 to 6 for T6, the graded stretches in metres along the line, unknown_share), mtb (the mountain bike scale mtb:scale, its hardest value and the metres of each), surface and highway (the metres and share of each value as OpenStreetMap writes it, such as asphalt, gravel, path or track), unknown_share (the part whose way carries none of these or could not be asked about) and length_m. A way without a value is unknown, never easy, paved or rideable; ways_unanswered counts ways the data could not be asked about this time, truncated says a very long line was only read in part. A tour saved with its points only has no line yet and is refused. Reading changes nothing.",
inputSchema: { tripId: idSchema, ...tourRefToolRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'read' },
})
async getTourTrailDetails({ tripId, placeId }: { tripId: number } & TourRefToolRequest, ctx: McpContext) {
// A read, like the REST route: seeing the trip is enough.
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
return await this.orNotFound(() => this.trailDetails.details(ctx.userId, tripId, placeId));
}
@Tool({
name: 'find_horse_routes',
description:
'Find the signposted horse routes OpenStreetMap knows inside a map view, as the horse tour planner shows them: each route (id relation/<n>, name, ref, osm_url, continues when it runs on past the view) with its sections, the stretches a ride can take whole (number, length_m, from and to as [lat, lng], access: the metres of each horse=* value its ways carry, unknown where untagged, and signposted: with or against the direction it is listed in, null both ways). bbox is the view as south,west,north,east; a view too large is refused with the advice to zoom in. Being on a horse route is no permission to ride it. truncated says the view held more than one answer carries. Reading changes nothing; nothing about the trip goes out.',
inputSchema: { tripId: idSchema, ...horseRoutesToolRequestSchema.shape },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'read' },
})
async findHorseRoutes({ tripId, bbox }: { tripId: number } & HorseRoutesToolRequest, ctx: McpContext) {
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
const found = await this.horseRoutes.list(parseHorseRoutesQuery({ bbox }).bbox);
return ok({ ...found, routes: found.routes.map(routeInBrief) });
}
}
@@ -0,0 +1,83 @@
/**
* BIK-05, MAP-03 and MAP-04 for a saved tour read over MCP: what
* OpenStreetMap records for the ways under its line, summed along it. The
* ways come from the router's description of the saved line and their tags
* from the trail grades the planner asks for; this half only lays them onto
* the line. A way without a value is unknown, never easy or paved.
*/
import type { TracedWay } from '../roadtrip/roadtrip-router.service';
import { gradesAlong } from './hike-routing.helpers';
import { sacStepOf, type HikeTrailGrades, type SacStep, type TourTrailGrade } from '@trek/shared';
/** How many metres of the line one written value covers, and its share of the whole line. */
interface ValueShare {
value: string;
metres: number;
share: number;
}
/** Everything the trail details answer, worked out from the ways and their tags. */
export interface TrailDetails {
length_m: number;
/** The SAC grades along the line, as a proposed hike carries them. */
sac: HikeTrailGrades;
/** The mountain bike scale (mtb:scale), the hardest step found and the metres of each; unknown where untagged. */
mtb: { highest: string | null; values: ValueShare[] };
surface: ValueShare[];
highway: ValueShare[];
/** The part of the line whose way has none of these tags or could not be asked about, 0 to 1. */
unknown_share: number;
}
const roundShare = (value: number) => Math.min(1, Math.round(value * 1000) / 1000);
/** The metres each value covers, the most first, scaled onto the saved length like the SAC stretches. */
function sharesOf(
ways: readonly TracedWay[],
valueOf: (grade: TourTrailGrade) => string | null,
grades: ReadonlyMap<number, TourTrailGrade>,
scale: number,
total: number,
): ValueShare[] {
const metres = new Map<string, number>();
for (const way of ways) {
const grade = way.wayId === null ? undefined : grades.get(way.wayId);
const value = grade ? valueOf(grade) : null;
if (value) metres.set(value, (metres.get(value) ?? 0) + way.metres * scale);
}
return [...metres]
.map(([value, along]) => ({ value, metres: Math.round(along), share: total > 0 ? roundShare(along / total) : 0 }))
.sort((a, b) => b.metres - a.metres || a.value.localeCompare(b.value));
}
/** The harder of two mtb:scale values, by their step (a + or - only between equal steps). */
function harderMtb(a: string | null, b: string): string {
if (a === null) return b;
const step = (value: string) => Number(value[0]) * 3 + (value.endsWith('+') ? 2 : value.endsWith('-') ? 0 : 1);
return step(b) > step(a) ? b : a;
}
/** The ways under the saved line with their tags, laid onto its length. */
export function trailDetailsOf(
ways: readonly TracedWay[],
grades: ReadonlyMap<number, TourTrailGrade>,
lengthM: number,
): TrailDetails {
const traced = ways.reduce((sum, way) => sum + way.metres, 0);
const scale = traced > 0 && lengthM > 0 ? lengthM / traced : 1;
const total = traced * scale;
const steps = new Map<number, SacStep>();
for (const [id, grade] of grades) if (grade.sac_scale) steps.set(id, sacStepOf(grade.sac_scale));
const mtb = sharesOf(ways, (grade) => grade.mtb_scale, grades, scale, total);
const known = ways
.filter((way) => way.wayId !== null && grades.has(way.wayId))
.reduce((sum, way) => sum + way.metres * scale, 0);
return {
length_m: Math.round(total),
sac: gradesAlong(ways, steps, lengthM),
mtb: { highest: mtb.reduce<string | null>((hardest, { value }) => harderMtb(hardest, value), null), values: mtb },
surface: sharesOf(ways, (grade) => grade.surface, grades, scale, total),
highway: sharesOf(ways, (grade) => grade.highway, grades, scale, total),
unknown_share: total > 0 ? roundShare(1 - known / total) : 1,
};
}
@@ -0,0 +1,77 @@
import { logWarn } from '../audit/audit-log.logger';
import { DomainError } from '../common/domain-error';
import { RoadtripRouterService, type TracedWay } from '../roadtrip/roadtrip-router.service';
import { gradableWayIds } from './hike-routing.helpers';
import { trailDetailsOf, type TrailDetails } from './tour-trail-details.helpers';
import { TourTrailGradeService } from './tour-trail-grade.service';
import { computeTourMetrics } from './tours.helpers';
import { ToursService } from './tours.service';
import { Injectable } from '@nestjs/common';
import { TOUR_TRAIL_GRADE_MAX_WAYS, type TourTrailGrade } from '@trek/shared';
/** The refusal of a tour without a saved line to read the ways under. */
const TOUR_TRAIL_NO_LINE = 'tour_trail_no_line';
/** The refusal while the router or the OpenStreetMap data cannot be asked. */
const TOUR_TRAIL_UNAVAILABLE = 'tour_trail_unavailable';
/** What get_tour_trail_details answers: the tour it read, and what its ways carry. */
interface TourTrailDetailsAnswer extends TrailDetails {
place_id: number;
tour_type: string;
/** Ways the data could not be asked about this time: their values are unknown, not absent. */
ways_unanswered: number;
/** The line ran over more ways than one question names; the rest were not read. */
truncated: boolean;
}
function reasonOf(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/**
* BIK-05, MAP-03 and MAP-04 for a saved tour: the ways under its saved line,
* as the router describes it (the planner's own description of a draft), and
* what OpenStreetMap records for them, through the trail grades the planner's
* POST /api/trips/:tripId/tours/trail-grades reads. A read: nothing about
* the tour changes. A tour saved with its points only has no line to read.
*/
@Injectable()
export class TourTrailDetailsService {
constructor(
private readonly tours: ToursService,
private readonly router: RoadtripRouterService,
private readonly trailGrades: TourTrailGradeService,
) {}
async details(userId: number, tripId: number, placeId: number): Promise<TourTrailDetailsAnswer> {
const { tour } = await this.tours.getTour(String(tripId), String(placeId));
const line = await this.tours.savedLine(tripId, placeId);
if (line.length < 2) {
throw new DomainError(422, 'This tour has no saved line yet: open it in the planner to plan its way first.', {
code: TOUR_TRAIL_NO_LINE,
});
}
const flat = line.map(([lat, lng]): [number, number] => [lat, lng]);
let ways: TracedWay[];
try {
ways = await this.router.wayIds(userId, flat);
} catch (err: unknown) {
logWarn(`[Tours] no ways under tour ${placeId}: ${reasonOf(err)}`);
throw new DomainError(503, 'The ways under this tour cannot be read right now: ask again later.', {
code: TOUR_TRAIL_UNAVAILABLE,
});
}
const ids = gradableWayIds(ways, TOUR_TRAIL_GRADE_MAX_WAYS);
const answer = ids.length > 0 ? await this.trailGrades.grades({ way_ids: ids }) : { ways: [], unanswered: [] };
const grades = new Map<number, TourTrailGrade>(answer.ways.map((way) => [way.id, way]));
const lengthM = computeTourMetrics(line).distanceKm * 1000;
const distinct = new Set(ways.flatMap((way) => (way.wayId === null ? [] : [way.wayId])));
return {
place_id: tour.place_id,
tour_type: tour.tour_type,
...trailDetailsOf(ways, grades, lengthM),
ways_unanswered: answer.unanswered.length,
truncated: distinct.size > ids.length,
};
}
}
+9
View File
@@ -52,8 +52,10 @@ import { TourChangeSaveService } from './tour-change-save.service';
import { TourChangeUndoMcp } from './tour-change-undo.mcp';
import { TourChangeUndoService } from './tour-change-undo.service';
import { TourChangeMcp } from './tour-change.mcp';
import { TourDetailsService } from './tour-details.service';
import { TourDraftsController } from './tour-drafts.controller';
import { TourDraftsService } from './tour-drafts.service';
import { TourEditMcp } from './tour-edit.mcp';
import { TourGpxExportService } from './tour-gpx-export.service';
import { TourHorseRoutesController } from './tour-horse-routes.controller';
import { TourHorseRoutesService } from './tour-horse-routes.service';
@@ -72,6 +74,8 @@ import { TourPoiSearchController } from './tour-poi-search.controller';
import { TourPoiSearchService } from './tour-poi-search.service';
import { TourSkiController } from './tour-ski.controller';
import { TourSkiService } from './tour-ski.service';
import { TourSportWritesMcp } from './tour-sport-writes.mcp';
import { TourTrailDetailsService } from './tour-trail-details.service';
import { TourTrailGradeController } from './tour-trail-grade.controller';
import { TourTrailGradeService } from './tour-trail-grade.service';
import { TourVisitsController } from './tour-visits.controller';
@@ -215,6 +219,9 @@ import { Module } from '@nestjs/common';
TourPoiSearchService,
TourSkiService,
TourTrailGradeService,
// P8, P9: a tour's words, times and colour, and the trail details along a saved one.
TourDetailsService,
TourTrailDetailsService,
TourVisitsService,
TourWalkImportService,
CityWalkFootWayService,
@@ -244,6 +251,8 @@ import { Module } from '@nestjs/common';
TourActivityStatsMcp,
CollectionToursMcp,
TourPackingMcp,
TourEditMcp,
TourSportWritesMcp,
],
})
export class ToursModule {}