diff --git a/server/src/db/repositories/TourStationVisits.repository.ts b/server/src/db/repositories/TourStationVisits.repository.ts index 69c8b7053..8192b69f7 100644 --- a/server/src/db/repositories/TourStationVisits.repository.ts +++ b/server/src/db/repositories/TourStationVisits.repository.ts @@ -71,6 +71,24 @@ export class TourStationVisitsRepository extends TrekRepository> { + return await this.db() + .selectFrom('tour_station_visits as v') + .innerJoin('day_assignments as da', 'da.id', 'v.assignment_id') + .innerJoin('days as d', 'd.id', 'da.day_id') + .select(['da.day_id', 'v.assignment_id', 'v.station_key', 'v.status']) + .where('da.place_id', '=', place_id) + .where('d.trip_id', '=', trip_id) + .orderBy('da.day_id', 'asc') + .orderBy('v.station_key', 'asc') + .execute(); + } + /** The visits of one day assignment. */ async listForAssignment(assignment_id: number): Promise { return await this.db() diff --git a/server/src/nest/tours/city-walk-briefing.service.ts b/server/src/nest/tours/city-walk-briefing.service.ts index 1659bfe6e..e55d3c2b1 100644 --- a/server/src/nest/tours/city-walk-briefing.service.ts +++ b/server/src/nest/tours/city-walk-briefing.service.ts @@ -4,21 +4,18 @@ import { Tours } from '../../db/entities/Tours.entity'; import type { PlaceRow, PlacesRepository } from '../../db/repositories/Places.repository'; import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository'; import type { ToursRepository } from '../../db/repositories/Tours.repository'; -import { logWarn } from '../audit/audit-log.logger'; import { notFound } from '../common/domain-error'; -import { RoadtripRouterService } from '../roadtrip/roadtrip-router.service'; import { briefingCategories, describeWalk, - footWayOf, frameOf, planWalk, themeCandidates, - type FootWay, type LeftOut, type LeftOutReason, type WalkCandidate, } from './city-walk-briefing.helpers'; +import { CityWalkFootWayService } from './city-walk-foot-way.service'; import { TourPoiSearchService } from './tour-poi-search.service'; import { ToursService } from './tours.service'; import { InjectRepository } from '@mikro-orm/nestjs'; @@ -34,13 +31,6 @@ import { /** How far from the start, the wishes and the appointments the themes are searched when the briefing does not say. */ const DEFAULT_CORRIDOR_M = 1000; -/** - * The day the router is asked for. A way on foot does not depend on the day: - * the router only keys its cache by one and hands it to a routing plugin, - * which a walk on foot never asks. - */ -const ANY_DAY = 0; - /** The places of the trip a briefing names, and which of them a station may stand for (no tour). */ interface NamedPlaces { rows: Map; @@ -105,7 +95,7 @@ function tripPlaceOf( export class CityWalkBriefingService { constructor( private readonly poiSearch: TourPoiSearchService, - private readonly router: RoadtripRouterService, + private readonly footWays: CityWalkFootWayService, private readonly tours: ToursService, @InjectRepository(Tours) private readonly toursRepo: ToursRepository, @InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository, @@ -146,7 +136,7 @@ export class CityWalkBriefingService { themeLimit: theme.limit, }); return { - ...describeWalk(plan.route, frame, await this.footWay(userId, tripId, plan.route)), + ...describeWalk(plan.route, frame, await this.footWays.plan(userId, tripId, plan.route)), left_out: [...leftOut, ...plan.leftOut], searched: theme.searched, }; @@ -159,7 +149,7 @@ export class CityWalkBriefingService { * stations only and says why; no straight line is stored as a route. */ async create(tripId: number, userId: number, body: CityWalkCreateRequest) { - const way = await this.footWay(userId, tripId, body.stations); + const way = await this.footWays.plan(userId, tripId, body.stations); const created = await this.tours.createCityWalk(String(tripId), body, way.kind === 'routed' ? way : null); return { ...created, @@ -167,22 +157,6 @@ export class CityWalkBriefingService { }; } - /** The way on foot through the stations in their order, or why there is none. */ - private async footWay( - userId: number, - tripId: number, - stations: ReadonlyArray<{ lat: number; lng: number }>, - ): Promise { - if (stations.length < 2) return { kind: 'unrouted', why: 'nothing_to_route', position: null }; - const points = stations.map(({ lat, lng }) => ({ lat, lng })); - try { - return footWayOf(await this.router.route(userId, tripId, ANY_DAY, points, 'walking', [])); - } catch (err: unknown) { - logWarn(`[CityWalk] no way on foot for trip ${tripId}: ${err instanceof Error ? err.message : String(err)}`); - return { kind: 'unrouted', why: 'router_unavailable', position: null }; - } - } - /** The date of the day the walk is for, null without one; a day of another trip is not found. */ private async dateOf(tripId: number, dayId: number | undefined): Promise { if (dayId === undefined) return null; diff --git a/server/src/nest/tours/city-walk-foot-way.service.ts b/server/src/nest/tours/city-walk-foot-way.service.ts new file mode 100644 index 000000000..3ddc58830 --- /dev/null +++ b/server/src/nest/tours/city-walk-foot-way.service.ts @@ -0,0 +1,36 @@ +import { logWarn } from '../audit/audit-log.logger'; +import { RoadtripRouterService } from '../roadtrip/roadtrip-router.service'; +import { footWayOf, type FootWay } from './city-walk-briefing.helpers'; +import { Injectable } from '@nestjs/common'; + +/** + * The day the router is asked for. A way on foot does not depend on the day: + * the router only keys its cache by one and hands it to a routing plugin, + * which a walk on foot never asks. + */ +const ANY_DAY = 0; + +/** + * CW-11, MCP-T02: the way on foot through the points of a city walk, planned + * by the router the road trip uses (the traveller's own routing server where + * they set one). The proposal of a new walk, its creation and a prepared + * change to a saved walk all ask here, so their distances and times come from + * one source. Where the router gives no way, the answer says why instead of + * guessing one. + */ +@Injectable() +export class CityWalkFootWayService { + constructor(private readonly router: RoadtripRouterService) {} + + /** The way on foot through the points in their order, or why there is none. */ + async plan(userId: number, tripId: number, points: ReadonlyArray<{ lat: number; lng: number }>): Promise { + if (points.length < 2) return { kind: 'unrouted', why: 'nothing_to_route', position: null }; + const asked = points.map(({ lat, lng }) => ({ lat, lng })); + try { + return footWayOf(await this.router.route(userId, tripId, ANY_DAY, asked, 'walking', [])); + } catch (err: unknown) { + logWarn(`[CityWalk] no way on foot for trip ${tripId}: ${err instanceof Error ? err.message : String(err)}`); + return { kind: 'unrouted', why: 'router_unavailable', position: null }; + } + } +} diff --git a/server/src/nest/tours/tour-change-apply.ts b/server/src/nest/tours/tour-change-apply.ts new file mode 100644 index 000000000..c116b6e7b --- /dev/null +++ b/server/src/nest/tours/tour-change-apply.ts @@ -0,0 +1,301 @@ +/** + * MCP-T02: a prepared change laid onto the saved points of a tour, by the + * rules of its type, without writing anything. The changes apply one after + * the other, each naming the stations it touches by their keys, and the + * answer is either the points as they would be or every change refused and + * why: a proposal is shown whole or not at all, never half applied. + * + * A city walk is the first type that takes changes. What its travellers have + * already done stays as it is: a station visited or skipped on any of its days + * is neither removed, replaced nor moved, nothing new goes before it, and a + * protected station (CW-10) keeps its place. A leg drawn by hand is kept as + * drawn, so neither of its ends changes and nothing is put into it. + */ +import { + CITY_WALK_MAX_STATIONS, + isClosedLoop, + type CityWalkStation, + type TourChange, + type TourChangeOp, + type TourWaypoint, +} from '@trek/shared'; + +/** + * The types of tour a proposal can change, each with every change. A hike, a + * bike or a paddle tour plans its way in the planner with routing of its own + * that a proposal cannot run, so it takes none yet rather than a way guessed. + */ +const CHANGEABLE_TYPES: ReadonlySet = 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'; + +/** A point of the plan as the changes leave it. */ +export type DraftPoint = TourWaypoint & { + /** + * Its key where it is a saved point that has one; `saved:` for one + * saved before keys existed and `new:` for a station a change brings + * in, neither of which a key can spell. + */ + ref: string; + origin: DraftOrigin; + /** The change (from 1) that brought it in or moved it; null for a point no change touched. */ + change: number | null; + /** The saved station it was put after, so stops put after the same one keep the order they were given in. */ + after: string | null; + /** The saved station a replacing one stands in for. */ + replaces: string | null; +}; + +/** A day the travellers marked a station on, and how. */ +export interface StationDone { + day_id: number; + status: 'visited' | 'skipped'; +} + +type RefusalReason = + | 'type_not_supported' + | 'recorded_track' + | 'unknown_station' + | 'already_changed' + | 'anchor_is_station' + | 'protected' + | 'done' + | 'before_done' + | 'fixed_leg' + | 'place_not_linkable' + | 'too_few_stations' + | 'too_many_stations'; + +/** Why a change, or the whole proposal (change null), cannot be prepared. */ +interface ChangeRefusal { + change: number | null; + op: TourChangeOp | null; + key: string | null; + reason: RefusalReason; + /** For a station already done: the days it was visited or skipped on. */ + days?: StationDone[]; +} + +/** What the changes are laid onto: the saved tour as read, and what its travellers already did. */ +export interface ChangeBasis { + tourType: string; + /** The tour stores no control points of its own: its points are the ends of a recorded track. */ + recorded: boolean; + points: readonly TourWaypoint[]; + /** The stations visited or skipped on any day of the walk, by key. */ + done: ReadonlyMap; + /** The places of this trip a new station may stand for: no tour, none of another trip. */ + linkable: ReadonlySet; +} + +type ChangeOutcome = + | { + kind: 'ready'; + points: DraftPoint[]; + /** The saved stations a remove took out, and those a replace stands in for. */ + removed: DraftPoint[]; + replaced: DraftPoint[]; + } + | { kind: 'refused'; refused: ChangeRefusal[] }; + +/** A saved point as the changes start from it. */ +export function savedPoint(point: TourWaypoint): DraftPoint { + const ref = point.key ?? `saved:${point.sequence}`; + return { ...point, ref, origin: 'saved', change: null, after: null, replaces: null }; +} + +function newStation(station: CityWalkStation, change: number): DraftPoint { + return { + ...station, + role: 'via', + sequence: 0, + ref: `new:${change}`, + origin: 'added', + change, + after: null, + replaces: null, + }; +} + +/** 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[]; + readonly removed: DraftPoint[] = []; + readonly replaced: DraftPoint[] = []; + readonly refused: ChangeRefusal[] = []; + /** The saved stations a change removed or replaced, which no later change can name. */ + private readonly gone = new Set(); + + constructor( + private readonly basis: ChangeBasis, + private readonly loop: boolean, + ) { + const points = basis.points.map(savedPoint); + this.body = loop ? points.slice(0, -1) : points; + } + + 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 } : {}) }); + const before = this.refused.length; + if ('station' in change) this.checkLink(change.station, (reason) => refuse(reason, null)); + if (change.op === 'add') { + const at = this.slotAfter(change.after_key, null, refuse); + if (at !== null && this.refused.length === before) { + this.body.splice(at, 0, { ...newStation(change.station, number), after: change.after_key }); + } + return; + } + const station = this.station(change.key, refuse); + if (station === null) return; + if (change.op === 'move') { + const at = this.slotAfter(change.after_key, change.key, refuse); + if (at === null || this.refused.length > before) return; + const moved = this.body.splice(station, 1)[0] as DraftPoint; + this.body.splice(at > station ? at - 1 : at, 0, { + ...moved, + origin: 'moved', + change: number, + after: change.after_key, + }); + return; + } + if (this.refused.length > before) return; + this.gone.add(change.key); + const replacing = change.op === 'replace' ? [this.replacing(change.station, number, change.key)] : []; + const gone = this.body.splice(station, 1, ...replacing)[0] as DraftPoint; + (change.op === 'remove' ? this.removed : this.replaced).push({ ...gone, change: number }); + } + + private replacing(station: CityWalkStation, change: number, key: string): DraftPoint { + return { ...newStation(station, change), origin: 'replacing', replaces: key }; + } + + /** The index of the saved station a change touches, once its rules allow it; null when they do not. */ + private station(key: string, refuse: (reason: RefusalReason, key: string, days?: StationDone[]) => void) { + const index = this.indexOfStation(key, refuse); + if (index === null) return null; + const point = this.body[index] as DraftPoint; + const done = this.basis.done.get(key); + if (point.protected === true) refuse('protected', key); + if (done && done.length > 0) refuse('done', key, [...done]); + if (point.fixed_leg || this.body[index - 1]?.fixed_leg) refuse('fixed_leg', key); + return index; + } + + /** Where a saved station stands now, or why it cannot be named. */ + private indexOfStation(key: string, refuse: (reason: RefusalReason, key: string) => void): number | null { + const index = this.body.findIndex((point) => point.ref === key && !point.shaping); + if (index >= 0) return index; + refuse(this.gone.has(key) ? 'already_changed' : 'unknown_station', key); + return null; + } + + /** + * Where something put after a saved station goes: right after it and after + * the stops already put there, never into a hand-drawn leg and never before + * a station the travellers already did. + */ + private slotAfter( + anchor: string, + moving: string | null, + refuse: (reason: RefusalReason, key: string) => void, + ): number | null { + if (anchor === moving) { + refuse('anchor_is_station', anchor); + return null; + } + const index = this.indexOfStation(anchor, refuse); + if (index === null) return null; + let at = index + 1; + while (this.body[at]?.after === anchor && this.body[at]?.ref !== moving) at += 1; + if (this.body[index]?.fixed_leg) refuse('fixed_leg', anchor); + if (at <= this.lastDoneIndex()) refuse('before_done', anchor); + return at; + } + + private lastDoneIndex(): number { + let last = -1; + this.body.forEach((point, index) => { + if ((this.basis.done.get(point.ref)?.length ?? 0) > 0) last = index; + }); + return last; + } + + private checkLink(station: { linked_place_id?: number | null }, refuse: (reason: RefusalReason) => void): void { + const id = station.linked_place_id; + if (id != null && !this.basis.linkable.has(id)) refuse('place_not_linkable'); + } + + /** 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 points = [...this.body, ...back]; + const end = points.length - 1; + return points.map((point, sequence): DraftPoint => ({ + ...point, + sequence, + role: sequence === 0 ? 'start' : sequence === end ? 'end' : 'via', + })); + } +} + +function stationCount(points: readonly DraftPoint[], loop: boolean): number { + return (loop ? points.slice(0, -1) : points).filter((point) => !point.shaping).length; +} + +/** The changes laid onto the saved points, or every reason they cannot be. */ +export function applyChanges(basis: ChangeBasis, changes: readonly TourChange[]): ChangeOutcome { + const whole = (reason: RefusalReason): ChangeOutcome => ({ + kind: 'refused', + refused: [{ change: null, op: null, key: null, reason }], + }); + if (!CHANGEABLE_TYPES.has(basis.tourType)) return whole('type_not_supported'); + if (basis.recorded) return whole('recorded_track'); + 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); + 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'); + } + return { kind: 'ready', points, removed: run.removed, replaced: run.replaced }; +} + +const REFUSAL_TEXT: Record = { + type_not_supported: + 'only a city walk takes prepared changes so far; this type plans its way with routing of its own in the planner', + recorded_track: + 'this walk is a recorded track without stations of its own; open it in the planner to plan stations onto it', + unknown_station: 'no station of the saved walk has this key (a shaping point or the way back of a loop is none)', + already_changed: 'an earlier change of this proposal already removed or replaced this station', + anchor_is_station: 'a station cannot be moved after itself', + protected: 'this station is protected: it keeps its place, and only the travellers can change it in the app', + done: 'the travellers already visited or skipped this station on a day of the walk; what was done stays as it is', + before_done: + 'this would put a station before one the travellers already visited or skipped; add it after the last of those', + fixed_leg: 'a leg drawn by hand in the planner starts or ends here and stays as drawn; change it in the planner', + 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`, +}; + +/** 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 days = refusal.days ? `, day ids ${refusal.days.map((day) => `${day.day_id} ${day.status}`).join(', ')}` : ''; + return `${about}: ${REFUSAL_TEXT[refusal.reason]}${days}.`; +} + +/** Every refusal of a proposal, one per line, under a line saying nothing was prepared or saved. */ +export function refusalText(refused: readonly ChangeRefusal[]): string { + return ['Nothing was prepared and nothing changed.', ...refused.map(refusalLine)].join('\n'); +} diff --git a/server/src/nest/tours/tour-change-effects.ts b/server/src/nest/tours/tour-change-effects.ts new file mode 100644 index 000000000..e048f2593 --- /dev/null +++ b/server/src/nest/tours/tour-change-effects.ts @@ -0,0 +1,187 @@ +/** + * MCP-T02: what a prepared change does to a city walk, set against the saved + * walk. The way on foot before and after is planned by the same router, so + * the two are compared on one source; the distance and walking time stored + * with the walk come from the planner and are given apart, never mixed in. + * Stays are counted where they are known and an unknown one stays unknown. + * Whatever cannot be worked out is named in `data_gaps` instead of guessed. + */ +import type { FootWay } from './city-walk-briefing.helpers'; +import { savedPoint, type DraftPoint } from './tour-change-apply'; +import { walkStationsOf, type TourWaypoint } from '@trek/shared'; + +/** Everything the description of a prepared change reads. */ +interface ChangeEffectsInput { + saved: readonly TourWaypoint[]; + after: readonly DraftPoint[]; + removed: readonly DraftPoint[]; + replaced: readonly DraftPoint[]; + wayBefore: FootWay; + wayAfter: FootWay; + /** As stored with the walk when it was last saved: kilometres and minutes, null when not known. */ + stored: { distance_km: number | null; walking_minutes: number | null }; +} + +type StationChange = 'kept' | 'added' | 'replaced' | 'moved'; + +const CHANGE_OF: Record = { + saved: 'kept', + added: 'added', + replacing: 'replaced', + moved: 'moved', +}; + +/** The key a point is saved under; null for a station a change brings in, which gets one when saved. */ +function keyOf(point: DraftPoint): string | null { + return point.key ?? null; +} + +/** The names of the saved points by ref, for the station a replacing one stands in for. */ +type Names = ReadonlyMap; + +/** One station of the changed walk, with where it stood before and what changed it. */ +function stationAfter(point: DraftPoint, index: number, wasAt: ReadonlyMap, names: Names) { + return { + position: index + 1, + key: keyOf(point), + name: point.name ?? null, + change: CHANGE_OF[point.origin], + by_change: point.change, + was_position: wasAt.get(point.ref) ?? null, + replaces: point.replaces ? { key: point.replaces, name: names.get(point.replaces) ?? null } : null, + stay_minutes: point.stay_minutes ?? null, + importance: point.importance ?? null, + protected: point.protected === true, + opening_hours: point.opening_hours ?? null, + linked_place_id: point.linked_place_id ?? null, + }; +} + +/** The way on foot through all points, its whole length and walking time, or why there is none. */ +function wayTotal(way: FootWay) { + if (way.kind === 'unrouted') return { planned: false as const, why: way.why, position: way.position }; + return { + planned: true as const, + metres: way.legs.reduce((sum, leg) => sum + leg.metres, 0), + minutes: Math.round(way.seconds / 60), + }; +} + +function walkingOf(input: ChangeEffectsInput) { + const before = wayTotal(input.wayBefore); + const after = wayTotal(input.wayAfter); + return { + planned_by: 'router_on_foot' as const, + before, + after, + change: + before.planned && after.planned + ? { metres: after.metres - before.metres, minutes: after.minutes - before.minutes } + : null, + stored: input.stored, + }; +} + +/** The stays of the stations as far as entered, and how many are not known. */ +function staysOf(stations: readonly DraftPoint[]) { + return { + minutes_known: stations.reduce((sum, station) => sum + (station.stay_minutes ?? 0), 0), + unknown: stations.filter((station) => station.stay_minutes == null).length, + }; +} + +function staysChange(before: readonly DraftPoint[], after: readonly DraftPoint[]) { + const was = staysOf(before); + const now = staysOf(after); + return { + before: was, + after: now, + change_minutes_known: now.minutes_known - was.minutes_known, + complete: was.unknown === 0 && now.unknown === 0, + }; +} + +/** Every leg of the changed walk from one point to the next, the way on foot gives it, and whether it is new. */ +function legsOf(saved: readonly DraftPoint[], after: readonly DraftPoint[], way: FootWay) { + const kept = new Set(saved.slice(1).map((to, index) => `${saved[index]?.ref}>${to.ref}`)); + return after.slice(1).map((to, index) => { + const from = after[index] as DraftPoint; + const leg = way.kind === 'routed' ? way.legs[index] : undefined; + return { + from: { key: keyOf(from), name: from.name ?? null }, + to: { key: keyOf(to), name: to.name ?? null }, + metres: leg?.metres ?? null, + minutes: leg?.minutes ?? null, + new: !kept.has(`${from.ref}>${to.ref}`), + }; + }); +} + +/** What could not be worked out, each with why, so nothing missing reads as nothing. */ +function gapsOf(input: ChangeEffectsInput, stationsAfter: readonly DraftPoint[]) { + const unrouted = (side: 'before' | 'after', way: FootWay) => + way.kind === 'unrouted' ? [{ about: 'walking' as const, side, why: way.why, position: way.position }] : []; + const unknownStays = stationsAfter.filter((station) => station.stay_minutes == null); + return [ + ...unrouted('before', input.wayBefore), + ...unrouted('after', input.wayAfter), + ...(input.saved.some((point) => point.fixed_leg) + ? [{ about: 'walking' as const, why: 'hand_drawn_leg_routed' as const }] + : []), + ...(unknownStays.length > 0 + ? [ + { + about: 'stays' as const, + why: 'stay_not_known' as const, + stations: unknownStays.map((station) => ({ key: keyOf(station), name: station.name ?? null })), + }, + ] + : []), + { about: 'arrival_times' as const, why: 'no_start_time' as const }, + ]; +} + +/** A station of importance must that the change removes or replaces, for the traveller to confirm on purpose. */ +function warningsOf(gone: readonly DraftPoint[]) { + return gone + .filter((point) => point.importance === 'must') + .map((point) => ({ change: point.change, key: point.key ?? null, name: point.name ?? null, why: 'must_station' })); +} + +/** The points as a save takes them: a kept point with its key, a new one without, the server gives it one. */ +function asWaypoint(draft: DraftPoint): TourWaypoint { + const { ref: _ref, origin: _origin, change: _change, after: _after, replaces: _replaces, ...point } = draft; + return point; +} + +/** A new station as create_place takes it, to keep it as a place of the trip instead of putting it in the walk. */ +function forLater(point: DraftPoint) { + return { change: point.change, name: point.name ?? null, lat: point.lat, lng: point.lng }; +} + +/** The changed walk set against the saved one: its stations, what went, the effects and the gaps. */ +export function describeChange(input: ChangeEffectsInput) { + const saved = input.saved.map(savedPoint); + const stationsBefore = walkStationsOf(saved); + const stationsAfter = walkStationsOf(input.after); + const wasAt = new Map(stationsBefore.map((station, index) => [station.ref, index + 1])); + const names: Names = new Map(saved.map((point) => [point.ref, point.name ?? null])); + return { + stations_after: stationsAfter.map((station, index) => stationAfter(station, index, wasAt, names)), + removed: input.removed.map((point) => ({ + key: point.key ?? null, + name: point.name ?? null, + was_position: wasAt.get(point.ref) ?? null, + by_change: point.change, + })), + effects: { + walking: walkingOf(input), + stays: staysChange(stationsBefore, stationsAfter), + legs: legsOf(saved, input.after, input.wayAfter), + }, + data_gaps: gapsOf(input, stationsAfter), + warnings: warningsOf([...input.removed, ...input.replaced]), + for_later: input.after.filter((point) => point.origin === 'added' || point.origin === 'replacing').map(forLater), + waypoints_after: input.after.map(asWaypoint), + }; +} diff --git a/server/src/nest/tours/tour-change-preview.service.ts b/server/src/nest/tours/tour-change-preview.service.ts new file mode 100644 index 000000000..5e1b96e17 --- /dev/null +++ b/server/src/nest/tours/tour-change-preview.service.ts @@ -0,0 +1,94 @@ +import { TourStationVisits } from '../../db/entities/TourStationVisits.entity'; +import { TourWaypoints } from '../../db/entities/TourWaypoints.entity'; +import type { TourStationVisitsRepository } from '../../db/repositories/TourStationVisits.repository'; +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 StationDone } from './tour-change-apply'; +import { describeChange } from './tour-change-effects'; +import { ToursService } from './tours.service'; +import { InjectRepository } from '@mikro-orm/nestjs'; +import { Injectable } from '@nestjs/common'; +import type { TourChange, TourChangeRequest } from '@trek/shared'; + +/** The refusal of a proposal the rules of its tour do not allow; its text names every change and why. */ +export const TOUR_CHANGE_REFUSED = 'tour_change_refused'; + +/** The places of the trip the new stations of a proposal name. */ +function linkedIds(changes: readonly TourChange[]): number[] { + return changes.flatMap((change) => { + const id = 'station' in change ? change.station.linked_place_id : null; + return id ? [id] : []; + }); +} + +/** The stations visited or skipped on any day of the walk, by key, each with the days. */ +function doneByKey(visits: ReadonlyArray): Map { + const done = new Map(); + for (const { station_key, day_id, status } of visits) { + done.set(station_key, [...(done.get(station_key) ?? []), { day_id, status }]); + } + return done; +} + +/** + * MCP-T02: a change to a saved tour prepared for the traveller to review. + * It reads the saved tour, the visits of all its days and the places the new + * stations name, lays the changes onto the saved points by the rules of the + * tour's type and works out the effects with the way on foot the router + * plans before and after. It writes nothing: no tour, station, visit or day + * plan changes, and turning the proposal down leaves the plan as it is. The + * proposal names the revision it was prepared on, so a save of it can be + * refused once the tour has moved on. + */ +@Injectable() +export class TourChangePreviewService { + constructor( + private readonly tours: ToursService, + private readonly footWays: CityWalkFootWayService, + @InjectRepository(TourStationVisits) private readonly visitsRepo: TourStationVisitsRepository, + @InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository, + ) {} + + async prepare(tripId: number, placeId: number, userId: number, { changes }: TourChangeRequest) { + const { tour, waypoints } = await this.tours.getTour(String(tripId), String(placeId)); + const [visits, linkable] = await Promise.all([ + this.visitsRepo.listForPlace(tripId, placeId), + this.waypointsRepo.linkablePlaceIds(tripId, linkedIds(changes)), + ]); + const outcome = applyChanges( + { + tourType: tour.tour_type, + recorded: tour.has_waypoints !== true, + points: waypoints, + done: doneByKey(visits), + linkable, + }, + changes, + ); + if (outcome.kind === 'refused') { + throw new DomainError(422, refusalText(outcome.refused), { + code: TOUR_CHANGE_REFUSED, + details: { refused: outcome.refused }, + }); + } + const [wayBefore, wayAfter] = await Promise.all([ + this.footWays.plan(userId, tripId, waypoints), + this.footWays.plan(userId, tripId, outcome.points), + ]); + return { + prepared_only: true, + base: { place_id: tour.place_id, name: tour.name, tour_type: tour.tour_type, revision: tour.revision ?? null }, + changes, + ...describeChange({ + saved: waypoints, + after: outcome.points, + removed: outcome.removed, + replaced: outcome.replaced, + wayBefore, + wayAfter, + stored: { distance_km: tour.distance, walking_minutes: tour.duration }, + }), + }; + } +} diff --git a/server/src/nest/tours/tour-change.mcp.ts b/server/src/nest/tours/tour-change.mcp.ts new file mode 100644 index 000000000..392d94a1c --- /dev/null +++ b/server/src/nest/tours/tour-change.mcp.ts @@ -0,0 +1,59 @@ +import { ADDON_IDS } from '../../addons'; +import { noAccess } from '../../mcp/tools/_shared'; +import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, 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 { TourChangePreviewService } from './tour-change-preview.service'; +import { NotFoundException } from '@nestjs/common'; +import { idSchema, tourChangeRequestSchema, type TourChangeRequest } from '@trek/shared'; + +/** + * MCP-T02: a change to a saved tour prepared for the traveller to review, + * read only like propose_city_walk: nothing is saved while it is prepared, + * and turning it down leaves the plan as it was. A change the rules of the + * tour refuse is the service's DomainError, which the registry answers as an + * error result naming every refused change and why. can_save tells the + * assistant whether this traveller may save changes to the trip's places at + * all, so a proposal is never offered as something they could apply when + * they cannot. + */ +@McpController() +export class TourChangeMcp { + constructor( + private readonly preview: TourChangePreviewService, + private readonly access: TripAccessService, + private readonly guards: McpToolGuardsService, + // Read by the addon gate of the tool here. + readonly addons: AddonsService, + ) {} + + @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; 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), warnings (a must station removed or replaced), for_later (each new station as create_place takes it, to keep it as a place of the trip instead) and waypoints_after. 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'), + changes: tourChangeRequestSchema.shape.changes, + }, + annotations: TOOL_ANNOTATIONS_READONLY, + when: addonGate(ADDON_IDS.TOURS), + access: { group: 'trips', mode: 'read' }, + }) + async prepareTourChange( + { tripId, placeId, changes }: { tripId: number; placeId: number } & TourChangeRequest, + ctx: McpContext, + ) { + if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess(); + try { + const proposal = await this.preview.prepare(tripId, placeId, ctx.userId, { changes }); + const canSave = await this.guards.hasTripPermission('place_edit', tripId, ctx.userId); + return ok({ ...proposal, can_save: canSave }); + } catch (err: unknown) { + if (err instanceof NotFoundException) return errorResult('Tour not found.'); + throw err; + } + } +} diff --git a/server/src/nest/tours/tours.module.ts b/server/src/nest/tours/tours.module.ts index 88ba91597..951f0d431 100644 --- a/server/src/nest/tours/tours.module.ts +++ b/server/src/nest/tours/tours.module.ts @@ -17,7 +17,10 @@ import { RoadtripModule } from '../roadtrip/roadtrip.module'; import { TripMembershipModule } from '../trip-membership/trip-membership.module'; import { WandererModule } from '../wanderer/wanderer.module'; import { CityWalkBriefingService } from './city-walk-briefing.service'; +import { CityWalkFootWayService } from './city-walk-foot-way.service'; import { CityWalkMcp } from './city-walk.mcp'; +import { TourChangePreviewService } from './tour-change-preview.service'; +import { TourChangeMcp } from './tour-change.mcp'; import { TourGpxExportService } from './tour-gpx-export.service'; import { TourHorseRoutesController } from './tour-horse-routes.controller'; import { TourHorseRoutesService } from './tour-horse-routes.service'; @@ -58,7 +61,9 @@ 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). + * 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). */ @Module({ imports: [ @@ -118,11 +123,14 @@ import { Module } from '@nestjs/common'; TourTrailGradeService, TourVisitsService, TourWalkImportService, + CityWalkFootWayService, CityWalkBriefingService, + TourChangePreviewService, ToursMcp, TourLibraryMcp, TourWalkImportMcp, CityWalkMcp, + TourChangeMcp, ], }) export class ToursModule {} diff --git a/server/tests/unit/db/repositories/TourStationVisits.repository.test.ts b/server/tests/unit/db/repositories/TourStationVisits.repository.test.ts index 953f68de9..774cb4521 100644 --- a/server/tests/unit/db/repositories/TourStationVisits.repository.test.ts +++ b/server/tests/unit/db/repositories/TourStationVisits.repository.test.ts @@ -124,7 +124,23 @@ describe('TourStationVisitsRepository', () => { ]); }); - it('TSVREPO-006: dropStationsNotIn keeps the named stations on every day, drops the rest, leaves other walks alone and names the days', async () => { + it('TSVREPO-008: listForPlace lists the visits of one walk on all its days with the day, none of another walk or trip', async () => { + const { trip, day1, day2, walk, onDay1, onDay2, other, otherWalk, foreign } = await fixture(); + await markStationVisit(t, onDay2.id, 'stop-a', 'skipped'); + await markStationVisit(t, onDay1.id, 'stop-b', 'visited'); + await markStationVisit(t, onDay1.id, 'stop-a', 'visited'); + await markStationVisit(t, foreign.id, 'stop-a', 'visited'); + + expect(await repo.listForPlace(trip.id, walk.id)).toEqual([ + { day_id: day1.id, assignment_id: onDay1.id, station_key: 'stop-a', status: 'visited' }, + { day_id: day1.id, assignment_id: onDay1.id, station_key: 'stop-b', status: 'visited' }, + { day_id: day2.id, assignment_id: onDay2.id, station_key: 'stop-a', status: 'skipped' }, + ]); + expect(await repo.listForPlace(other.id, walk.id)).toEqual([]); + expect(await repo.listForPlace(trip.id, otherWalk.id)).toEqual([]); + }); + + it('TSVREPO-006:dropStationsNotIn keeps the named stations on every day, drops the rest, leaves other walks alone and names the days', async () => { const { walk, onDay1, onDay2, foreign } = await fixture(); await markStationVisit(t, onDay1.id, 'stop-a', 'visited'); await markStationVisit(t, onDay1.id, 'stop-b', 'visited'); diff --git a/server/tests/unit/nest/tour-change-apply.test.ts b/server/tests/unit/nest/tour-change-apply.test.ts new file mode 100644 index 000000000..8c980d77c --- /dev/null +++ b/server/tests/unit/nest/tour-change-apply.test.ts @@ -0,0 +1,191 @@ +import { + applyChanges, + refusalText, + type ChangeBasis, + type DraftPoint, +} from '../../../src/nest/tours/tour-change-apply'; +import { CITY_WALK_MAX_STATIONS, type TourChange, type TourWaypoint } from '@trek/shared'; + +import { describe, expect, it } from 'vitest'; + +// TCHG-APPLY-001 to TCHG-APPLY-007 + +const point = (key: string, sequence: number, extra: Partial = {}): TourWaypoint => ({ + lat: 48 + sequence * 0.01, + lng: 11, + role: 'via', + sequence, + key, + name: key.replace('stop-', ''), + ...extra, +}); + +/** A walk from the gate past the museum, a shaping point and the park to its end. */ +const walk = (): TourWaypoint[] => [ + point('stop-gate', 0, { role: 'start' }), + point('stop-museum', 1, { stay_minutes: 45, importance: 'must' }), + point('shape-0001', 2, { shaping: true, name: null }), + point('stop-park', 3), + point('stop-end', 4, { role: 'end' }), +]; + +const basis = (over: Partial = {}): ChangeBasis => ({ + tourType: 'walk', + recorded: false, + points: walk(), + done: new Map(), + linkable: new Set([7]), + ...over, +}); + +const cafe = { lat: 48.015, lng: 11.001, name: 'Cafe', stay_minutes: 20 }; + +function ready(outcome: ReturnType) { + if (outcome.kind !== 'ready') throw new Error(`refused: ${JSON.stringify(outcome.refused)}`); + return outcome; +} + +const refs = (points: readonly DraftPoint[]) => points.map((p) => p.ref); + +describe('a change laid onto a saved walk (MCP-T02)', () => { + it('TCHG-APPLY-001: an add goes right after its station, stops after the same one keep their order, roles follow', () => { + const changes: TourChange[] = [ + { op: 'add', station: cafe, after_key: 'stop-museum' }, + { op: 'add', station: { ...cafe, name: 'Bakery', linked_place_id: 7 }, after_key: 'stop-museum' }, + ]; + const { points, removed, replaced } = ready(applyChanges(basis(), changes)); + expect(refs(points)).toEqual(['stop-gate', 'stop-museum', 'new:1', 'new:2', 'shape-0001', 'stop-park', 'stop-end']); + expect(points.map((p) => [p.sequence, p.role])).toEqual([ + [0, 'start'], + [1, 'via'], + [2, 'via'], + [3, 'via'], + [4, 'via'], + [5, 'via'], + [6, 'end'], + ]); + expect(points[2]).toMatchObject({ name: 'Cafe', origin: 'added', change: 1, after: 'stop-museum', replaces: null }); + expect(points[2]?.key).toBeUndefined(); + expect(points[3]).toMatchObject({ name: 'Bakery', linked_place_id: 7, change: 2 }); + expect([removed, replaced]).toEqual([[], []]); + }); + + it('TCHG-APPLY-002: remove, replace and move each say what they did, and a move goes before or after where it was', () => { + const changes: TourChange[] = [ + { op: 'remove', key: 'stop-park' }, + { op: 'replace', key: 'stop-museum', station: cafe }, + { op: 'move', key: 'stop-end', after_key: 'stop-gate' }, + { op: 'move', key: 'stop-gate', after_key: 'stop-end' }, + ]; + const { points, removed, replaced } = ready(applyChanges(basis(), changes)); + expect(refs(points)).toEqual(['stop-end', 'stop-gate', 'new:2', 'shape-0001']); + expect(points[0]).toMatchObject({ origin: 'moved', change: 3, role: 'start' }); + expect(points[2]).toMatchObject({ origin: 'replacing', replaces: 'stop-museum', name: 'Cafe' }); + expect(points[3]?.role).toBe('end'); + expect(removed.map((p) => [p.ref, p.change])).toEqual([['stop-park', 1]]); + expect(replaced.map((p) => [p.ref, p.change, p.importance])).toEqual([['stop-museum', 2, 'must']]); + }); + + it('TCHG-APPLY-003: what the travellers did, a protected station and a hand-drawn leg stay as they are', () => { + const points = walk(); + points[3] = { ...points[3], protected: true } as TourWaypoint; + points[0] = { + ...points[0], + fixed_leg: { + kind: 'free', + geometry: [ + [48, 11], + [48.01, 11], + ], + }, + } as TourWaypoint; + const done = new Map([['stop-end', [{ day_id: 7, status: 'visited' as const }]]]); + const outcome = applyChanges(basis({ points, done }), [ + { op: 'remove', key: 'stop-park' }, + { op: 'move', key: 'stop-end', after_key: 'stop-gate' }, + { op: 'replace', key: 'stop-museum', station: cafe }, + { op: 'add', station: cafe, after_key: 'stop-museum' }, + ]); + expect(outcome).toEqual({ + kind: 'refused', + refused: [ + { change: 1, op: 'remove', key: 'stop-park', reason: 'protected' }, + { change: 2, op: 'move', key: 'stop-end', reason: 'done', days: [{ day_id: 7, status: 'visited' }] }, + { change: 2, op: 'move', key: 'stop-gate', reason: 'fixed_leg' }, + { change: 2, op: 'move', key: 'stop-gate', reason: 'before_done' }, + { change: 3, op: 'replace', key: 'stop-museum', reason: 'fixed_leg' }, + { change: 4, op: 'add', key: 'stop-museum', reason: 'before_done' }, + ], + }); + if (outcome.kind !== 'refused') return; + const text = refusalText(outcome.refused); + expect(text.split('\n')[0]).toBe('Nothing was prepared and nothing changed.'); + expect(text).toContain('Change 2 (move stop-end): the travellers already visited or skipped'); + expect(text).toContain('day ids 7 visited.'); + }); + + it('TCHG-APPLY-004: a station is named by its key, once gone it cannot be named again, and nothing moves after itself', () => { + const outcome = applyChanges(basis({ linkable: new Set() }), [ + { op: 'remove', key: 'stop-nowhere' }, + { op: 'remove', key: 'shape-0001' }, + { op: 'remove', key: 'stop-park' }, + { op: 'move', key: 'stop-park', after_key: 'stop-gate' }, + { op: 'move', key: 'stop-gate', after_key: 'stop-gate' }, + { op: 'add', station: { ...cafe, linked_place_id: 7 }, after_key: 'stop-gate' }, + ]); + expect(outcome.kind === 'refused' && outcome.refused.map((r) => [r.change, r.key, r.reason])).toEqual([ + [1, 'stop-nowhere', 'unknown_station'], + [2, 'shape-0001', 'unknown_station'], + [4, 'stop-park', 'already_changed'], + [5, 'stop-gate', 'anchor_is_station'], + [6, null, 'place_not_linkable'], + ]); + }); + + it('TCHG-APPLY-005: a type without changes, a recorded track and a walk left with too few or too many stations are refused whole', () => { + const whole = (outcome: ReturnType) => + outcome.kind === 'refused' ? outcome.refused.map((r) => [r.change, r.reason]) : outcome.kind; + const remove: TourChange[] = [{ op: 'remove', key: 'stop-park' }]; + expect(whole(applyChanges(basis({ tourType: 'hike' }), remove))).toEqual([[null, 'type_not_supported']]); + expect(whole(applyChanges(basis({ recorded: true }), remove))).toEqual([[null, 'recorded_track']]); + const removeAllBut = ['stop-gate', 'stop-museum', 'stop-park'].map((key): TourChange => ({ op: 'remove', key })); + expect(whole(applyChanges(basis(), removeAllBut))).toEqual([[null, 'too_few_stations']]); + + const full = Array.from({ length: CITY_WALK_MAX_STATIONS }, (_, i) => point(`stop-${1000 + i}`, i)); + const add: TourChange[] = [{ op: 'add', station: cafe, after_key: 'stop-1000' }]; + expect(whole(applyChanges(basis({ points: full }), add))).toEqual([[null, 'too_many_stations']]); + // A walk already past the limit can still lose a station or swap one. + const over = [...full, point('stop-2000', CITY_WALK_MAX_STATIONS)]; + const shrink: TourChange[] = [{ op: 'remove', key: 'stop-1001' }]; + const swap: TourChange[] = [{ op: 'replace', key: 'stop-1001', station: cafe }]; + expect(whole(applyChanges(basis({ points: over }), shrink))).toBe('ready'); + expect(whole(applyChanges(basis({ points: over }), swap))).toBe('ready'); + }); + + it('TCHG-APPLY-006: a loop keeps ending where it starts, and its way back is no station to name', () => { + const loop = [ + point('stop-gate', 0, { role: 'start' }), + point('stop-museum', 1), + point('stop-park', 2), + point('stop-back', 3, { role: 'end', lat: 48 }), + ]; + const moved = ready( + applyChanges(basis({ points: loop }), [ + { op: 'move', key: 'stop-gate', after_key: 'stop-park' }, + { op: 'add', station: cafe, after_key: 'stop-gate' }, + ]), + ); + expect(refs(moved.points)).toEqual(['stop-museum', 'stop-park', 'stop-gate', 'new:2', 'stop-back']); + expect(moved.points[4]).toMatchObject({ lat: moved.points[0]?.lat, lng: 11, role: 'end', origin: 'saved' }); + const back = applyChanges(basis({ points: loop }), [{ op: 'remove', key: 'stop-back' }]); + expect(back.kind === 'refused' && back.refused[0]?.reason).toBe('unknown_station'); + }); + + it('TCHG-APPLY-007: a point saved before keys existed keeps a ref no key can spell, and stays untouched', () => { + const points = walk(); + points[3] = { ...points[3], key: undefined } as TourWaypoint; + const add: TourChange[] = [{ op: 'add', station: cafe, after_key: 'stop-gate' }]; + const { points: after } = ready(applyChanges(basis({ points }), add)); + expect(refs(after)).toEqual(['stop-gate', 'new:1', 'stop-museum', 'shape-0001', 'saved:3', 'stop-end']); + }); +}); diff --git a/server/tests/unit/nest/tour-change-effects.test.ts b/server/tests/unit/nest/tour-change-effects.test.ts new file mode 100644 index 000000000..526517c4f --- /dev/null +++ b/server/tests/unit/nest/tour-change-effects.test.ts @@ -0,0 +1,158 @@ +import type { FootWay } from '../../../src/nest/tours/city-walk-briefing.helpers'; +import { applyChanges } from '../../../src/nest/tours/tour-change-apply'; +import { describeChange } from '../../../src/nest/tours/tour-change-effects'; +import type { TourChange, TourWaypoint } from '@trek/shared'; + +import { describe, expect, it } from 'vitest'; + +// TCHG-EFFECTS-001 to TCHG-EFFECTS-003 + +const point = (key: string, sequence: number, extra: Partial = {}): TourWaypoint => ({ + lat: 48 + sequence * 0.01, + lng: 11, + role: 'via', + sequence, + key, + name: key.replace('stop-', ''), + ...extra, +}); + +/** A walk from the gate past the museum (45 minutes, a must) and the park (stay unknown) to the end (passed). */ +const saved: TourWaypoint[] = [ + point('stop-gate', 0, { role: 'start', stay_minutes: 0 }), + point('stop-museum', 1, { stay_minutes: 45, importance: 'must' }), + point('stop-park', 2), + point('stop-end', 3, { role: 'end', stay_minutes: 0 }), +]; + +const cafe = { lat: 48.015, lng: 11.001, name: 'Cafe', stay_minutes: 20, opening_hours: 'Mo-Su 08:00-18:00' }; + +/** The walk with a cafe after the gate and the museum swapped for a gallery of unknown stay. */ +function changed(points: TourWaypoint[] = saved) { + const changes: TourChange[] = [ + { op: 'add', station: cafe, after_key: 'stop-gate' }, + { op: 'replace', key: 'stop-museum', station: { lat: 48.012, lng: 11, name: 'Gallery' } }, + { op: 'remove', key: 'stop-park' }, + ]; + const outcome = applyChanges( + { tourType: 'walk', recorded: false, points, done: new Map(), linkable: new Set() }, + changes, + ); + if (outcome.kind !== 'ready') throw new Error('refused'); + return outcome; +} + +const routed = (metres: number[], seconds: number): FootWay => ({ + kind: 'routed', + line: [], + legs: metres.map((m) => ({ metres: m, minutes: Math.ceil(m / 75) })), + seconds, +}); + +describe('what a prepared change does to a walk (MCP-T02)', () => { + it('TCHG-EFFECTS-001: sets the stations, the way on foot and the stays after against before, from one router', () => { + const outcome = changed(); + const described = describeChange({ + saved, + after: outcome.points, + removed: outcome.removed, + replaced: outcome.replaced, + wayBefore: routed([800, 900, 700], 1860), + wayAfter: routed([300, 450, 1500], 1700), + stored: { distance_km: 2.3, walking_minutes: 32 }, + }); + + const after = described.stations_after; + expect(after.map((s) => [s.position, s.key, s.name, s.change, s.by_change, s.was_position])).toEqual([ + [1, 'stop-gate', 'gate', 'kept', null, 1], + [2, null, 'Cafe', 'added', 1, null], + [3, null, 'Gallery', 'replaced', 2, null], + [4, 'stop-end', 'end', 'kept', null, 4], + ]); + expect(after[2]?.replaces).toEqual({ key: 'stop-museum', name: 'museum' }); + expect(after[1]).toMatchObject({ stay_minutes: 20, opening_hours: 'Mo-Su 08:00-18:00' }); + expect(described.removed).toEqual([{ key: 'stop-park', name: 'park', was_position: 3, by_change: 3 }]); + expect(described.effects.walking).toEqual({ + planned_by: 'router_on_foot', + before: { planned: true, metres: 2400, minutes: 31 }, + after: { planned: true, metres: 2250, minutes: 28 }, + change: { metres: -150, minutes: -3 }, + stored: { distance_km: 2.3, walking_minutes: 32 }, + }); + expect(described.effects.stays).toEqual({ + before: { minutes_known: 45, unknown: 1 }, + after: { minutes_known: 20, unknown: 1 }, + change_minutes_known: -25, + complete: false, + }); + expect(described.effects.legs.map((leg) => [leg.from.name, leg.to.name, leg.metres, leg.new])).toEqual([ + ['gate', 'Cafe', 300, true], + ['Cafe', 'Gallery', 450, true], + ['Gallery', 'end', 1500, true], + ]); + expect(described.warnings).toEqual([{ change: 2, key: 'stop-museum', name: 'museum', why: 'must_station' }]); + expect(described.for_later).toEqual([ + { change: 1, name: 'Cafe', lat: 48.015, lng: 11.001 }, + { change: 2, name: 'Gallery', lat: 48.012, lng: 11 }, + ]); + expect(described.data_gaps).toEqual([ + { about: 'stays', why: 'stay_not_known', stations: [{ key: null, name: 'Gallery' }] }, + { about: 'arrival_times', why: 'no_start_time' }, + ]); + }); + + it('TCHG-EFFECTS-002: hands over the points as a save takes them, a new station without a key', () => { + const outcome = changed(); + const { waypoints_after } = describeChange({ + saved, + after: outcome.points, + removed: outcome.removed, + replaced: outcome.replaced, + wayBefore: routed([1], 60), + wayAfter: routed([1], 60), + stored: { distance_km: null, walking_minutes: null }, + }); + expect(waypoints_after.map((p) => [p.key, p.name, p.role, p.sequence])).toEqual([ + ['stop-gate', 'gate', 'start', 0], + [undefined, 'Cafe', 'via', 1], + [undefined, 'Gallery', 'via', 2], + ['stop-end', 'end', 'end', 3], + ]); + for (const waypoint of waypoints_after) { + expect(['ref', 'origin', 'change', 'after', 'replaces'].some((field) => field in waypoint)).toBe(false); + } + }); + + it('TCHG-EFFECTS-003: a way the router could not plan stays unknown with why, and a hand-drawn leg is named', () => { + // A leg drawn by hand from the end, which no change here touches. + const free = { + kind: 'free', + geometry: [ + [48.03, 11], + [48.04, 11], + ], + }; + const withLeg = saved.map((p, i) => (i === 3 ? ({ ...p, fixed_leg: free } as TourWaypoint) : p)); + const outcome = changed(withLeg); + const described = describeChange({ + saved: withLeg, + after: outcome.points, + removed: outcome.removed, + replaced: outcome.replaced, + wayBefore: { kind: 'unrouted', why: 'router_unavailable', position: null }, + wayAfter: { kind: 'unrouted', why: 'station_off_the_way', position: 2 }, + stored: { distance_km: 2.3, walking_minutes: null }, + }); + expect(described.effects.walking).toMatchObject({ + before: { planned: false, why: 'router_unavailable', position: null }, + after: { planned: false, why: 'station_off_the_way', position: 2 }, + change: null, + }); + expect(described.effects.legs.every((leg) => leg.metres === null && leg.minutes === null)).toBe(true); + expect(described.data_gaps.slice(0, 3)).toEqual([ + { about: 'walking', side: 'before', why: 'router_unavailable', position: null }, + { about: 'walking', side: 'after', why: 'station_off_the_way', position: 2 }, + { about: 'walking', why: 'hand_drawn_leg_routed' }, + ]); + }); +}); diff --git a/server/tests/unit/nest/tour-change.mcp.test.ts b/server/tests/unit/nest/tour-change.mcp.test.ts new file mode 100644 index 000000000..98dfa47af --- /dev/null +++ b/server/tests/unit/nest/tour-change.mcp.test.ts @@ -0,0 +1,294 @@ +/** + * TourChangeMcp (MCP-T02): a change to a saved city walk prepared for the + * traveller to review. It reads the saved walk, the visits of all its days + * and the places the new stations name, plans the way on foot before and + * after with the road trip's router (a stub here), and writes nothing. The + * suite takes its subject from the container over a snapshot test db and + * seeds through the ORM factories. + */ +import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity'; +import { Places } from '../../../src/db/entities/Places.entity'; +import { TourStationVisits } from '../../../src/db/entities/TourStationVisits.entity'; +import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity'; +import { Tours } from '../../../src/db/entities/Tours.entity'; +import type { McpContext } from '../../../src/nest-mcp'; +import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata'; +import { catchDomainError, DomainError } from '../../../src/nest/common/domain-error'; +import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service'; +import { RoadtripRouterService } from '../../../src/nest/roadtrip/roadtrip-router.service'; +import { CityWalkFootWayService } from '../../../src/nest/tours/city-walk-foot-way.service'; +import { TOUR_CHANGE_REFUSED, TourChangePreviewService } from '../../../src/nest/tours/tour-change-preview.service'; +import { TourChangeMcp } from '../../../src/nest/tours/tour-change.mcp'; +import { ToursModule } from '../../../src/nest/tours/tours.module'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { makeDayAssignment } from '../../helpers/factories/itinerary'; +import { makePlace } from '../../helpers/factories/places'; +import { countRows, findRow } from '../../helpers/factories/rows'; +import { addTourWaypoints, makeTour, markStationVisit } from '../../helpers/factories/tours'; +import { makeDay, makeTrip } from '../../helpers/factories/trips'; +import { makeUser } from '../../helpers/factories/users'; +import { resetTestDb } from '../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../helpers/test-module'; +import { MikroORM } from '@mikro-orm/core'; +import type { TourChange } from '@trek/shared'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +const route = vi.fn(); +let t: TestModule; +let mcp: TourChangeMcp; +const orm = () => t.get(MikroORM); + +beforeAll(async () => { + t = await createTestModule({ + db, + imports: [ToursModule], + overrides: [{ provide: RoadtripRouterService, useValue: { route } }], + }); + mcp = t.get(TourChangeMcp); +}); +beforeEach(() => { + resetTestDb(db); + // Every leg the router plans is 500 m and 400 s on foot. + route.mockReset().mockImplementation( + async (_userId: number, _tripId: number, _dayId: number, points: Array<{ lat: number; lng: number }>) => ({ + leg: { line: points.map((point): [number, number] => [point.lat, point.lng]) }, + parts: points.slice(1).map(() => ({ distance: 500, duration: 400 })), + snapped: points.map(() => ({ meters: 4 })), + avoidMissed: [], + }), + ); +}); +afterAll(async () => { + await t.close(); + db.close(); +}); + +const ctx = (userId: number) => ({ userId }) as McpContext; + +/** The JSON a tool answered, or the error text it refused with. */ +function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) { + const text = result.content[0]?.text ?? ''; + return result.isError ? { error: text } : JSON.parse(text); +} + +/** + * A city walk at revision 3 from the gate past the protected cathedral and + * the market to the park (a must), on day 1 where the gate was visited and + * the market skipped; a hike, a bakery of the trip and a place of another trip. + */ +async function fixture() { + const { user } = await makeUser(orm()); + const { user: outsider } = await makeUser(orm()); + const trip = await makeTrip(orm(), user.id); + const other = await makeTrip(orm(), user.id); + const day1 = await makeDay(orm(), trip.id, { day_number: 1 }); + const walk = await makePlace(orm(), trip.id, { name: 'Old town' }); + await makeTour(orm(), walk.id, { tourTypeRef: 'walk', revision: 3, distance: 1.6, duration: 22 }); + await addTourWaypoints(orm(), walk.id, [ + { lat: 48.1, lng: 11.5, station_key: 'stop-gate', name: 'Gate', stay_minutes: 0 }, + { lat: 48.104, lng: 11.5, station_key: 'stop-cathedral', name: 'Cathedral', stay_minutes: 30, protected: 1 }, + { lat: 48.108, lng: 11.5, station_key: 'stop-market', name: 'Market', stay_minutes: 20 }, + { lat: 48.112, lng: 11.5, station_key: 'stop-park', name: 'Park', importance: 'must' }, + ]); + const onDay1 = await makeDayAssignment(orm(), day1.id, walk.id); + await markStationVisit(orm(), onDay1.id, 'stop-gate', 'visited'); + await markStationVisit(orm(), onDay1.id, 'stop-market', 'skipped'); + const ridge = await makePlace(orm(), trip.id, { name: 'Ridge' }); + await makeTour(orm(), ridge.id); + await addTourWaypoints(orm(), ridge.id, [ + { lat: 47, lng: 11, station_key: 'pt-start' }, + { lat: 47.1, lng: 11, station_key: 'pt-end' }, + ]); + const bakery = await makePlace(orm(), trip.id, { name: 'Bakery', lat: 48.109, lng: 11.501 }); + const foreign = await makePlace(orm(), other.id, { name: 'Foreign' }); + return { user, outsider, trip, day1, walk, ridge, bakery, foreign }; +} + +/** Everything a preparation must leave as it is. */ +const untouched = async (placeId: number) => [ + await countRows(orm(), Places, {}), + await countRows(orm(), Tours, {}), + await countRows(orm(), TourWaypoints, {}), + await countRows(orm(), TourStationVisits, {}), + await countRows(orm(), DayAssignments, {}), + (await findRow(orm(), Tours, { place: placeId }))?.revision, +]; + +/** prepare_tour_change of one tour, as one traveller. */ +const prepare = (tripId: number, placeId: number, changes: TourChange[], userId: number) => + mcp.prepareTourChange({ tripId, placeId, changes }, ctx(userId)); + +/** The refusal a preparation raised, which the registry answers with its text. */ +async function refusal(promise: Promise): Promise { + const err = await catchDomainError(() => promise); + if (!(err instanceof DomainError)) throw new Error('no refusal'); + return err; +} + +describe('TourChangeMcp (MCP-T02)', () => { + it('TCHG-MCP-001: a spontaneous stop and a swap are prepared against the saved walk with their effects, and nothing is written', async () => { + const f = await fixture(); + const before = await untouched(f.walk.id); + const changes: TourChange[] = [ + { + op: 'add', + station: { lat: 48.109, lng: 11.501, name: 'Bakery', stay_minutes: 15, linked_place_id: f.bakery.id }, + after_key: 'stop-market', + }, + { op: 'replace', key: 'stop-park', station: { lat: 48.113, lng: 11.502, name: 'Beer garden' } }, + ]; + const proposal = read(await prepare(f.trip.id, f.walk.id, changes, f.user.id)); + + expect(proposal).toMatchObject({ + prepared_only: true, + can_save: true, + base: { place_id: f.walk.id, name: 'Old town', tour_type: 'walk', revision: 3 }, + changes, + }); + expect(proposal.stations_after.map((s: { name: string; change: string }) => [s.name, s.change])).toEqual([ + ['Gate', 'kept'], + ['Cathedral', 'kept'], + ['Market', 'kept'], + ['Bakery', 'added'], + ['Beer garden', 'replaced'], + ]); + const asked = (points: Array<[number, number]>) => points.map(([lat, lng]) => ({ lat, lng })); + const saved: Array<[number, number]> = [ + [48.1, 11.5], + [48.104, 11.5], + [48.108, 11.5], + [48.112, 11.5], + ]; + expect(route).toHaveBeenCalledWith(f.user.id, f.trip.id, 0, asked(saved), 'walking', []); + expect(route).toHaveBeenCalledWith( + f.user.id, + f.trip.id, + 0, + asked([...saved.slice(0, 3), [48.109, 11.501], [48.113, 11.502]]), + 'walking', + [], + ); + expect(proposal.effects.walking).toEqual({ + planned_by: 'router_on_foot', + before: { planned: true, metres: 1500, minutes: 20 }, + after: { planned: true, metres: 2000, minutes: 27 }, + change: { metres: 500, minutes: 7 }, + stored: { distance_km: 1.6, walking_minutes: 22 }, + }); + expect(proposal.effects.stays).toMatchObject({ change_minutes_known: 15, complete: false }); + expect(proposal.warnings).toEqual([{ change: 2, key: 'stop-park', name: 'Park', why: 'must_station' }]); + expect(proposal.for_later.map((stop: { name: string }) => stop.name)).toEqual(['Bakery', 'Beer garden']); + expect(proposal.waypoints_after.map((p: { key?: string }) => p.key ?? null)).toEqual([ + 'stop-gate', + 'stop-cathedral', + 'stop-market', + null, + null, + ]); + expect(await untouched(f.walk.id)).toEqual(before); + }); + + it('TCHG-MCP-002: what was done, a protected station and a place of another trip are refused with every reason, and nothing is written', async () => { + const f = await fixture(); + const before = await untouched(f.walk.id); + const changes: TourChange[] = [ + { op: 'remove', key: 'stop-cathedral' }, + { op: 'move', key: 'stop-gate', after_key: 'stop-park' }, + { op: 'add', station: { lat: 48.1, lng: 11.5, linked_place_id: f.foreign.id }, after_key: 'stop-gate' }, + ]; + const err = await refusal(prepare(f.trip.id, f.walk.id, changes, f.user.id)); + expect([err.getStatus(), err.code]).toEqual([422, TOUR_CHANGE_REFUSED]); + expect(err.publicMessage.split('\n')).toEqual([ + 'Nothing was prepared and nothing changed.', + expect.stringMatching(/^Change 1 \(remove stop-cathedral\): this station is protected/), + expect.stringMatching(new RegExp(`^Change 2 \\(move stop-gate\\): .*day ids ${f.day1.id} visited\\.$`)), + expect.stringMatching(/^Change 3 \(add station\): the new station names a place that is not a place of/), + expect.stringMatching(/^Change 3 \(add stop-gate\): this would put a station before one/), + ]); + expect((err.details?.refused as Array<{ reason: string }>).map((r) => r.reason)).toEqual([ + 'protected', + 'done', + 'place_not_linkable', + 'before_done', + ]); + expect(route).not.toHaveBeenCalled(); + expect(await untouched(f.walk.id)).toEqual(before); + }); + + it('TCHG-MCP-003: a hike is refused as a type without changes, an outsider learns nothing and a place that is no tour is not found', async () => { + const f = await fixture(); + const changes: TourChange[] = [{ op: 'remove', key: 'pt-start' }]; + const hike = await refusal(prepare(f.trip.id, f.ridge.id, changes, f.user.id)); + expect(hike.publicMessage).toContain('The proposal: only a city walk takes prepared changes so far'); + expect(read(await prepare(f.trip.id, f.walk.id, changes, f.outsider.id))).toEqual({ + error: 'Trip not found or access denied.', + }); + expect(read(await prepare(f.trip.id, f.bakery.id, changes, f.user.id))).toEqual({ error: 'Tour not found.' }); + const failure = new Error('database gone'); + const prepare = vi.spyOn(t.get(TourChangePreviewService), 'prepare').mockRejectedValueOnce(failure); + try { + await expect(prepare(f.trip.id, f.walk.id, changes, f.user.id)).rejects.toBe(failure); + } finally { + prepare.mockRestore(); + } + }); + + it('TCHG-MCP-004: without a way from the router the walking effects stay unknown with why, and can_save follows place_edit', async () => { + const f = await fixture(); + route.mockReset().mockRejectedValue(new Error('Routing provider returned 503')); + const guard = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValueOnce(false); + try { + const changes: TourChange[] = [{ op: 'remove', key: 'stop-park' }]; + const proposal = read(await prepare(f.trip.id, f.walk.id, changes, f.user.id)); + expect(guard).toHaveBeenCalledWith('place_edit', f.trip.id, f.user.id); + expect(proposal.can_save).toBe(false); + expect(proposal.effects.walking).toMatchObject({ + before: { planned: false, why: 'router_unavailable' }, + after: { planned: false, why: 'router_unavailable' }, + change: null, + }); + expect(proposal.removed).toEqual([{ key: 'stop-park', name: 'Park', was_position: 4, by_change: 1 }]); + expect(proposal.data_gaps.map((gap: { about: string; why: string }) => [gap.about, gap.why])).toEqual([ + ['walking', 'router_unavailable'], + ['walking', 'router_unavailable'], + ['arrival_times', 'no_start_time'], + ]); + } finally { + guard.mockRestore(); + } + }); + + it('TCHG-MCP-005: the way on foot needs two points, and a router failure of any kind reads as router_unavailable', async () => { + const footWays = t.get(CityWalkFootWayService); + expect(await footWays.plan(1, 2, [{ lat: 48, lng: 11 }])).toEqual({ + kind: 'unrouted', + why: 'nothing_to_route', + position: null, + }); + expect(route).not.toHaveBeenCalled(); + route.mockRejectedValueOnce('socket hang up'); + const points = [ + { lat: 48, lng: 11 }, + { lat: 48.01, lng: 11 }, + ]; + expect(await footWays.plan(1, 2, points)).toEqual({ kind: 'unrouted', why: 'router_unavailable', position: null }); + }); + + it('TCHG-MCP-006: prepare_tour_change reads only, on the Tours addon, and says how a proposal is bound and saved', async () => { + const entry = getEntry(TourChangeMcp as unknown as ClassRef, 'prepareTourChange'); + if (!entry || entry.kind !== 'tool') throw new Error('prepareTourChange is no MCP tool'); + const { options } = entry; + expect([options.name, options.annotations?.readOnlyHint, options.access]).toEqual([ + 'prepare_tour_change', + true, + { group: 'trips', mode: 'read' }, + ]); + const terms = ['revision', 'spontaneous stop', 'protected', 'visited or skipped', 'data_gaps', 'create_place']; + for (const term of terms) expect(options.description).toContain(term); + const isAddonEnabled = vi.fn(async (id: string) => id === 'tours'); + expect(await options.when?.(ctx(1), { addons: { isAddonEnabled } })).toBe(true); + expect(isAddonEnabled).toHaveBeenCalledWith('tours'); + }); +}); diff --git a/shared/src/index.ts b/shared/src/index.ts index f0d72d517..4196222fb 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -64,6 +64,7 @@ export * from './tours/tour-trail-grade.schema'; export * from './tours/tour-walk.schema'; export * from './tours/tour-walk'; export * from './tours/tour-walk-briefing.schema'; +export * from './tours/tour-change.schema'; export * from './tours/walk-hours'; export * from './tours/tours.metrics'; export * from './tours/tour-gpx-import.schema'; diff --git a/shared/src/tours/tour-change.schema.spec.ts b/shared/src/tours/tour-change.schema.spec.ts new file mode 100644 index 000000000..15be176f2 --- /dev/null +++ b/shared/src/tours/tour-change.schema.spec.ts @@ -0,0 +1,36 @@ +import { TOUR_CHANGE_MAX, TOUR_CHANGE_OPS, tourChangeRequestSchema, tourChangeSchema } from './tour-change.schema'; + +import { describe, expect, it } from 'vitest'; + +const cafe = { lat: 48.1, lng: 11.5, name: 'Cafe', stay_minutes: 20 }; + +describe('a change to a saved tour prepared for review (MCP-T02)', () => { + it('takes an add, a remove, a replace and a move, each naming its stations by key', () => { + expect(tourChangeSchema.options.map((option) => option.shape.op.value)).toEqual([...TOUR_CHANGE_OPS]); + const changes = [ + { op: 'add', station: cafe, after_key: 'stop-gate' }, + { op: 'remove', key: 'stop-park' }, + { op: 'replace', key: 'stop-museum', station: { ...cafe, opening_hours: 'Mo-Su 08:00-18:00' } }, + { op: 'move', key: 'stop-market', after_key: 'stop-gate' }, + ]; + expect(tourChangeRequestSchema.parse({ changes })).toEqual({ changes }); + }); + + it('refuses a change it does not know, a key that is no key, a field a change does not carry and too many changes', () => { + const refused = [ + { changes: [] }, + { changes: [{ op: 'rename', key: 'stop-gate' }] }, + { changes: [{ op: 'remove', key: 'x' }] }, + { changes: [{ op: 'remove', key: 'stop-gate', after_key: 'stop-park' }] }, + { changes: [{ op: 'add', station: cafe }] }, + { changes: [{ op: 'add', station: { ...cafe, key: 'stop-new1' }, after_key: 'stop-gate' }] }, + { changes: [{ op: 'add', station: { ...cafe, lat: 91 }, after_key: 'stop-gate' }] }, + { changes: [{ op: 'move', key: 'stop-gate' }] }, + { changes: [{ op: 'remove', key: 'stop-gate' }], save: true }, + { changes: Array.from({ length: TOUR_CHANGE_MAX + 1 }, () => ({ op: 'remove', key: 'stop-gate' })) }, + ]; + for (const body of refused) { + expect(tourChangeRequestSchema.safeParse(body).success, JSON.stringify(body)).toBe(false); + } + }); +}); diff --git a/shared/src/tours/tour-change.schema.ts b/shared/src/tours/tour-change.schema.ts new file mode 100644 index 000000000..7d9a855c6 --- /dev/null +++ b/shared/src/tours/tour-change.schema.ts @@ -0,0 +1,48 @@ +import { cityWalkStationSchema } from './tour-walk-briefing.schema'; +import { stationKeySchema } from './tours.schema'; + +import { z } from 'zod'; + +/** + * MCP-T02: a change to a saved tour an assistant prepares for the traveller to + * review. Preparing it reads only: the answer shows the plan as it would be + * after the change, set against the saved plan, with the effects worked out + * and what could not be. Every change names the stations it touches by their + * keys, the same across saves, so it cannot drift onto another station. A + * spontaneous stop is a change like any other: an `add` after the station the + * traveller is at. + */ + +/** The most changes one proposal carries: enough to rework a walk, few enough to review at once. */ +export const TOUR_CHANGE_MAX = 10; + +/** The operations a proposal can hold; which of them a tour type takes is the server's rule. */ +export const TOUR_CHANGE_OPS = ['add', 'remove', 'replace', 'move'] as const; +export type TourChangeOp = (typeof TOUR_CHANGE_OPS)[number]; + +const key = stationKeySchema.describe('The key of a station of the saved tour, as get_tour_plan gives it'); +const afterKey = stationKeySchema.describe( + 'The key of the saved station it comes after; stops added after the same station keep the order they are given in', +); +const station = cityWalkStationSchema.describe( + 'The new station: its position, name, stay in minutes (0 passed through, null not known), importance, protected, opening hours as OpenStreetMap writes them, and the place of this trip it stands for', +); + +export const tourChangeSchema = z.discriminatedUnion('op', [ + z.object({ op: z.literal('add'), station, after_key: afterKey }).strict(), + z.object({ op: z.literal('remove'), key }).strict(), + z.object({ op: z.literal('replace'), key, station }).strict(), + z.object({ op: z.literal('move'), key, after_key: afterKey }).strict(), +]); +export type TourChange = z.infer; + +export const tourChangeRequestSchema = z + .object({ + changes: z + .array(tourChangeSchema) + .min(1) + .max(TOUR_CHANGE_MAX) + .describe('The changes in the order they apply, each to the plan the ones before it left'), + }) + .strict(); +export type TourChangeRequest = z.infer; diff --git a/wiki/MCP-Addon-Tools.md b/wiki/MCP-Addon-Tools.md index e99b2f51f..4f6034326 100644 --- a/wiki/MCP-Addon-Tools.md +++ b/wiki/MCP-Addon-Tools.md @@ -233,7 +233,7 @@ Each tool asks for the scope of what it writes, so the scopes differ per tool. T ### Tours _(Tours addon required)_ -The saved tours of a trip, as the Tours list and the tour detail show them, how far a city walk got on a day, paddle legs planned on the water, and a city walk prepared from a briefing. `take_over_tour` and `create_city_walk` write; every other tool here only reads. Tours someone is still drawing in the planner are not saved yet and do not show here. +The saved tours of a trip, as the Tours list and the tour detail show them, how far a city walk got on a day, paddle legs planned on the water, a city walk prepared from a briefing, and a change to a saved city walk prepared for review. `take_over_tour` and `create_city_walk` write; every other tool here only reads. Tours someone is still drawing in the planner are not saved yet and do not show here. | Tool | Description | Scope | |---|---|---| @@ -248,6 +248,7 @@ The saved tours of a trip, as the Tours list and the tour detail show them, how | `preview_google_maps_walk` | Reads the stops of a Google Maps walking route shared as a link (a `maps.app.goo.gl` short link or a `google.com/maps/dir` link), in order, for a city walk: each stop's name and position, or no position when the link gives none (nothing is looked up or guessed), and the long link that was read. Only a route Google Maps marks as on foot is read; a car, bike or transit route, or a link that does not say, is refused. A short link is followed only to Google Maps itself. Nothing is saved, and the line drawn in Google Maps is not taken over: TREK plans the way on foot between the stops again. Needs `place_edit` on the trip | `trips:read` | | `propose_city_walk` | Proposes a city walk from a briefing without saving anything: start (and end), the time frame on a day, the themes (`culture`, `parks`, `food`, `mixed`), the stations the traveller wished for, the places of the trip it may use and fixed appointments. Places for the themes come from the same search as `search_tour_pois`, up to 8, each with its source, theme and category; nothing is made up. Answers the stations in order with the walking distance and time from the one before, the arrival and leave times, the stay where the traveller gave it (unknown otherwise, which makes later arrivals the earliest possible), and the opening hours checked against the arrival on that day. The order is chosen on estimates; the walk in that order is then planned on foot by the router TREK uses for road trips (the traveller's own routing server where they set one), whose legs give the distances and times. Where it gives no way, because the router cannot be reached or a station lies more than 300 m off every way, the times are estimates over the straight distance with an allowance for streets at 4.5 km/h, and the answer says so and why. Walking and stays are kept apart, a complete total only when every stay is known, with the minutes the frame leaves for the stays not known. Lists free time, the wishes and appointments that cannot be kept as asked, what was left out and why, and `stations_for_create` for `create_city_walk` | `trips:read` | | `create_city_walk` | Creates a city walk from stations the traveller confirmed (for instance `stations_for_create` of `propose_city_walk`), through the same creation the planner's save uses: a key for every station, its name, stay, importance, protection, opening hours and the place of the trip it stands for. The way on foot is planned by the same router as for the proposal, and the walk is saved with it, its distance and its walking time. Where the router gives no way, the walk is saved with its stations only (`route_pending`), says why, and has no line, distance or walking time until someone opens it in the planner, where TREK plans the way on foot and the walk can be saved with it. Needs `place_edit` on the trip | `trips:write` | +| `prepare_tour_change` | Prepares a change to a saved city walk 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 was. The changes apply in order and name the saved stations by their keys: `add` (a new station after a station; a spontaneous stop on the way is an add after the station the traveller is at), `remove`, `replace` and `move`. A protected station, or one 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; such a change is refused, and with it the whole proposal, naming every change and why. Another type of tour, or a walk that is a recorded track without stations of its own, is refused as well: so far only a city walk takes prepared changes. The answer names 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), the stations after the change with what changed each and where it stood before, what was removed, the way on foot before and after planned by the same router TREK uses for city walks and its change in metres and minutes (the distance and walking time stored with the walk given apart), the stays as far as known before and after, every leg after the change with the new ones marked, `data_gaps` for what could not be worked out (no way from the router, stays not known, no arrival times), a warning for a station of importance must removed or replaced, each new station as `create_place` takes it to keep it as a place of the trip instead, and whether the traveller may change the trip's places at all (`can_save`) | `trips:read` | | `plan_paddle_route` | Plans the legs of a paddle tour on the water network TREK builds from the paddle regions an admin added: each leg (`from`, `to`) along rivers and canals and across lakes, carried round weirs, dams and waterfalls, through or round locks (`lock_policy`), with `boat` and `lake_style` (`direct` or `shore`). Answers per leg its length, how far its ends were moved onto the water and its stretches (water, lake, whitewater, boat pass, portage with its source, lock, gap); a leg that cannot be planned says why (`not_on_water`, `no_region`, `cross_region`, `no_water_path`, `busy`, `timeout`). Nothing is saved; a planning aid, never a safety or legal clearance | `trips:read` | ### Road trip _(Road trip addon required)_