Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(tours): undo_tour_change takes back a saved change to a tour once the traveller confirmed it

Maurice63a7a4d39759
diff --git a/server/src/db/entities/TourChangeSteps.entity.ts b/server/src/db/entities/TourChangeSteps.entity.ts
index 64cdf9a48..f8a619b0f 100644
--- a/server/src/db/entities/TourChangeSteps.entity.ts
+++ b/server/src/db/entities/TourChangeSteps.entity.ts
@@ -15,6 +15,9 @@ export class TourChangeSteps {
before_state!: string;
saved_by?: number | null;
saved_at!: string & Opt;
+ undone_revision?: number | null;
+ undone_by?: number | null;
+ undone_at?: string | null;
}
export const TourChangeStepsSchema = defineEntity({
@@ -24,6 +27,10 @@ export const TourChangeStepsSchema = defineEntity({
checks: [
{ name: 'tour_change_steps_base_revision_check', expression: 'base_revision >= 1' },
{ name: 'tour_change_steps_revision_check', expression: 'revision = base_revision + 1' },
+ {
+ name: 'tour_change_steps_undone_revision_check',
+ expression: 'undone_revision IS NULL OR undone_revision > revision',
+ },
],
properties: {
id: p.integer().primary(),
@@ -36,5 +43,8 @@ export const TourChangeStepsSchema = defineEntity({
before_state: p.text(),
saved_by: p.integer().nullable(),
saved_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
+ undone_revision: p.integer().nullable(),
+ undone_by: p.integer().nullable(),
+ undone_at: p.type(DbTimestampType).nullable(),
},
});
diff --git a/server/src/db/kysely/TourChangeSteps.table.ts b/server/src/db/kysely/TourChangeSteps.table.ts
index c9db7254d..ec5b3603d 100644
--- a/server/src/db/kysely/TourChangeSteps.table.ts
+++ b/server/src/db/kysely/TourChangeSteps.table.ts
@@ -12,4 +12,7 @@ export interface TourChangeStepsTable {
before_state: string;
saved_by: InsertOptional<number | null>;
saved_at: InsertOptional<string>;
+ undone_revision: InsertOptional<number | null>;
+ undone_by: InsertOptional<number | null>;
+ undone_at: InsertOptional<string | null>;
}
diff --git a/server/src/db/migrations/Migration20200101045710_a_saved_tour_change_can_be_taken_back.ts b/server/src/db/migrations/Migration20200101045710_a_saved_tour_change_can_be_taken_back.ts
new file mode 100644
index 000000000..81c989df4
--- /dev/null
+++ b/server/src/db/migrations/Migration20200101045710_a_saved_tour_change_can_be_taken_back.ts
@@ -0,0 +1,22 @@
+import { Migration } from '@mikro-orm/migrations';
+
+/**
+ * MCP-T04: a step of a tour saved from a confirmed proposal (MCP-T03) can be
+ * taken back once, which restores the tour as the step kept it before. The
+ * step then says so: `undone_revision` is the revision taking it back raised
+ * the tour to, always past the one the step saved, `undone_by` who confirmed
+ * it (a plain id, as `saved_by`) and `undone_at` when. All three stay NULL
+ * while the step stands. Taking a step back writes no second step and no
+ * second revision: the tour's one revision counts it like any other write.
+ */
+export class Migration20200101045710_a_saved_tour_change_can_be_taken_back extends Migration {
+ override name = 'Migration20200101045710_a_saved_tour_change_can_be_taken_back';
+
+ override up(): void {
+ this.addSql(
+ 'ALTER TABLE tour_change_steps ADD COLUMN undone_revision INTEGER CHECK (undone_revision IS NULL OR undone_revision > revision)',
+ );
+ this.addSql('ALTER TABLE tour_change_steps ADD COLUMN undone_by INTEGER');
+ this.addSql('ALTER TABLE tour_change_steps ADD COLUMN undone_at DATETIME');
+ }
+}
diff --git a/server/src/db/repositories/TourChangeSteps.repository.ts b/server/src/db/repositories/TourChangeSteps.repository.ts
index e40b9ca1c..697bb16d8 100644
--- a/server/src/db/repositories/TourChangeSteps.repository.ts
+++ b/server/src/db/repositories/TourChangeSteps.repository.ts
@@ -1,3 +1,4 @@
+import { currentTimestampKysely } from '../dialect/kysely-functions';
import type { TourChangeSteps } from '../entities/TourChangeSteps.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
@@ -15,6 +16,35 @@ export interface TourChangeStepWrite {
saved_by: number | null;
}
+/** A recorded step as it is read back, with whether and when it was taken back (MCP-T04). */
+export interface TourChangeStepRow {
+ id: number;
+ base_revision: number;
+ revision: number;
+ changes: string;
+ before_state: string;
+ saved_at: string;
+ undone_revision: number | null;
+ undone_at: string | null;
+}
+
+/** Taking a step back: the revision that raised the tour to and who confirmed it. */
+export interface TourChangeStepUndo {
+ undone_revision: number;
+ undone_by: number | null;
+}
+
+const STEP_COLUMNS = [
+ 'id',
+ 'base_revision',
+ 'revision',
+ 'changes',
+ 'before_state',
+ 'saved_at',
+ 'undone_revision',
+ 'undone_at',
+] as const;
+
/**
* `tour_change_steps` (MCP-T03): the changes to a tour saved from a proposal
* the traveller confirmed, one step per revision they raised the tour to,
@@ -35,4 +65,40 @@ export class TourChangeStepsRepository extends TrekRepository<TourChangeSteps> {
.executeTakeFirstOrThrow();
return inserted.id;
}
+
+ /** The steps of a tour, the latest first, at most `limit` of them. */
+ async listForPlace(place_id: number, limit: number): Promise<TourChangeStepRow[]> {
+ return await this.db()
+ .selectFrom('tour_change_steps')
+ .select(STEP_COLUMNS)
+ .where('place_id', '=', place_id)
+ .orderBy('revision', 'desc')
+ .limit(limit)
+ .execute();
+ }
+
+ /** One step of this tour; undefined for a step of another tour or none. */
+ async findForPlace(place_id: number, id: number): Promise<TourChangeStepRow | undefined> {
+ return await this.db()
+ .selectFrom('tour_change_steps')
+ .select(STEP_COLUMNS)
+ .where('place_id', '=', place_id)
+ .where('id', '=', id)
+ .executeTakeFirst();
+ }
+
+ /**
+ * Marks a step taken back, inside the caller's transaction. Only a step that
+ * still stands is marked, so it is taken back once: false when it was already.
+ */
+ async markUndone(id: number, { undone_revision, undone_by }: TourChangeStepUndo): Promise<boolean> {
+ const platform = this.getEntityManager().getPlatform();
+ const result = await this.db()
+ .updateTable('tour_change_steps')
+ .set({ undone_revision, undone_by, undone_at: currentTimestampKysely(platform) })
+ .where('id', '=', id)
+ .where('undone_revision', 'is', null)
+ .executeTakeFirst();
+ return Number(result.numUpdatedRows) === 1;
+ }
}
diff --git a/server/src/nest/tours/tour-change-preview.service.ts b/server/src/nest/tours/tour-change-preview.service.ts
index 699c1b120..ded47c45f 100644
--- a/server/src/nest/tours/tour-change-preview.service.ts
+++ b/server/src/nest/tours/tour-change-preview.service.ts
@@ -24,7 +24,7 @@ function linkedIds(changes: readonly TourChange[]): number[] {
}
/** The stations visited or skipped on any day of the walk, by key, each with the days. */
-function doneByKey(visits: ReadonlyArray<StationDone & { station_key: string }>): Map<string, StationDone[]> {
+export function doneByKey(visits: ReadonlyArray<StationDone & { station_key: string }>): Map<string, StationDone[]> {
const done = new Map<string, StationDone[]>();
for (const { station_key, day_id, status } of visits) {
done.set(station_key, [...(done.get(station_key) ?? []), { day_id, status }]);
diff --git a/server/src/nest/tours/tour-change-save.service.ts b/server/src/nest/tours/tour-change-save.service.ts
index 3d81b4b3f..d2a2178fe 100644
--- a/server/src/nest/tours/tour-change-save.service.ts
+++ b/server/src/nest/tours/tour-change-save.service.ts
@@ -10,17 +10,11 @@ import 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';
+import { tourWriteOf, writtenStations, writtenTour } from './tour-change-write';
import { ToursService, type TourCreateCommand } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
-import {
- plannableTourTypeSchema,
- walkStationsOf,
- type TourChangeSaveRequest,
- type TourDetailResponse,
- type TourListItem,
- type TourWaypoint,
-} from '@trek/shared';
+import type { 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';
@@ -40,31 +34,19 @@ interface SavedStep {
}
/**
- * The write of a confirmed change: the points after it, the way on foot the
- * router planned through them, and the tour's own name, type and options as
- * they are, so a change of stations changes nothing else. Without a way the
- * walk keeps its stations only, as a created one does (CW-11): no line, no
- * distance and no walking time until the planner plans the way.
+ * The write of a confirmed change: the points after it and the way on foot
+ * the router planned through them. Without a way the walk keeps its stations
+ * 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 {
const routed = way.kind === 'routed' ? way : null;
- return {
- name: tour.name,
- // Only a type that takes changes gets here, and each of them is one the planner draws.
- tour_type: plannableTourTypeSchema.parse(tour.tour_type),
+ return tourWriteOf(tour, {
route_geometry: routed?.line ?? null,
duration_seconds: routed?.seconds ?? null,
waypoints: points.map(asWaypoint),
- max_hiking_difficulty: tour.max_hiking_difficulty,
- hiking_preferences: tour.hiking_preferences,
- bike_profile: tour.bike_profile,
- boat_type: tour.boat_type,
- water_context: tour.water_context,
- paddle_speed_kmh: tour.paddle_speed_kmh,
- portage_speed_kmh: tour.portage_speed_kmh,
- paddle_lake_style: tour.paddle_lake_style,
expected_revision: preparedOn,
- };
+ });
}
/** The saved tour as the answer gives it, read back through the read the app uses. */
@@ -72,24 +54,12 @@ function savedAnswer(detail: TourDetailResponse, step: SavedStep, { way, prepare
return {
saved: true as const,
step: { id: step.id, base_revision: preparedOn, revision: step.revision },
- tour: {
- place_id: detail.tour.place_id,
- name: detail.tour.name,
- tour_type: detail.tour.tour_type,
- revision: step.revision,
- distance_km: detail.tour.distance,
- walking_minutes: detail.tour.duration,
- route_pending: detail.tour.route_pending === true,
- },
+ tour: writtenTour(detail, step.revision),
foot_way:
way.kind === 'routed'
? { planned: true as const }
: { planned: false as const, why: way.why, position: way.position },
- stations: walkStationsOf(detail.waypoints).map((station, index) => ({
- position: index + 1,
- key: station.key ?? null,
- name: station.name ?? null,
- })),
+ stations: writtenStations(detail),
};
}
@@ -105,7 +75,7 @@ function savedAnswer(detail: TourDetailResponse, step: SavedStep, { way, prepare
*
* The write records the step: the proposal, both revisions, the changes and
* the tour as it was before them (its line, its points, its measures), so it
- * can be followed and taken back (MCP-T04). Nothing of the conversation is
+ * can be followed and taken back (TourChangeUndoService, MCP-T04). Nothing of the conversation is
* kept. A new city walk has no revision to name: it is created through
* create_city_walk (CW-11), never saved as a change.
*/
diff --git a/server/src/nest/tours/tour-change-undo.mcp.ts b/server/src/nest/tours/tour-change-undo.mcp.ts
new file mode 100644
index 000000000..1aaa1f9c3
--- /dev/null
+++ b/server/src/nest/tours/tour-change-undo.mcp.ts
@@ -0,0 +1,116 @@
+import { ADDON_IDS } from '../../addons';
+import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
+import {
+ McpController,
+ Tool,
+ TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ TOOL_ANNOTATIONS_READONLY,
+ 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 { TourChangeUndoService } from './tour-change-undo.service';
+import { NotFoundException } from '@nestjs/common';
+import { idSchema, tourChangeUndoRequestSchema, type TourChangeUndoRequest } from '@trek/shared';
+
+const undo = tourChangeUndoRequestSchema.shape;
+const placeId = idSchema.describe('The place id of the tour, as list_tours gives it');
+
+/** A refusal for a tour this trip does not have, the same text every tool of the tours answers. */
+function tourNotFound(err: unknown) {
+ if (err instanceof NotFoundException) return errorResult('Tour not found.');
+ throw err;
+}
+
+/**
+ * MCP-T04: a step saved with save_tour_change (MCP-T03) taken back, the way a
+ * change is saved: listed, previewed without writing anything, then taken
+ * back once the traveller confirmed exactly that step. The preview and the
+ * listing read with trip access, as prepare_tour_change does; taking back
+ * writes with 'place_edit' on the trip, as save_tour_change and the planner's
+ * save over REST ask, and is checked again inside the write. None of it
+ * touches a draft in the planner: the planner's own undo stays in the browser.
+ */
+@McpController()
+export class TourChangeUndoMcp {
+ constructor(
+ private readonly undoer: TourChangeUndoService,
+ private readonly access: TripAccessService,
+ private readonly guards: McpToolGuardsService,
+ // Read by the addon gate of every tool here.
+ readonly addons: AddonsService,
+ ) {}
+
+ @Tool({
+ name: 'list_tour_change_steps',
+ description:
+ 'List the changes saved to a tour with save_tour_change, the latest first (at most listed_at_most): each step with its id, saved_at, base_revision (the revision it was prepared on), revision (the one it raised the tour to) and the changes as the traveller confirmed them. standing says whether it can be taken back: latest (it is the tour\'s latest change; prepare_tour_undo checks the rest), undone (taken back already, undone names the revision that raised the tour to and when), later_change (something was saved on top of it since, in the planner or by another step, so taking it back would lose that) or no_earlier_state (the record of the tour before it cannot be read). Edits saved in the planner are no steps and are not listed; a draft in the planner is never seen here. Reads only.',
+ inputSchema: { tripId: idSchema, placeId },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ when: addonGate(ADDON_IDS.TOURS),
+ access: { group: 'trips', mode: 'read' },
+ })
+ async listTourChangeSteps({ tripId, placeId }: { tripId: number; placeId: number }, ctx: McpContext) {
+ if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
+ try {
+ return ok(await this.undoer.steps(tripId, placeId));
+ } catch (err: unknown) {
+ return tourNotFound(err);
+ }
+ }
+
+ @Tool({
+ name: 'prepare_tour_undo',
+ description:
+ "Show what taking back a saved step of a tour (from list_tour_change_steps) would do, without changing anything. Only the tour's latest change can be taken back: a step something was saved on top of since is refused as a conflict, so no later edit is lost, and so is a step taken back already or one whose record of the tour before it cannot be read. Taking back is refused as well, with every reason, when it would remove a station visited or skipped since, or bring back a station whose place of the trip is gone. The answer: prepared_only (always true), step (its id, when it was saved, its revisions and the changes it made), now (the tour as it is: distance_km, walking_minutes and route_pending as stored, each station with done when it was visited or skipped on a day), restored (the tour exactly as it was before the step: its distance and walking time as stored then, route_pending, and each station kept or back, with where it stands now), removed (the stations taking back removes) and undo (step_id and expected_revision for undo_tour_change). Visits of stations that stay are kept, the days and the tour's name and notes are not touched. This is not the planner's undo: a draft in the planner is never seen here, and discarding one never changes a saved tour. Show it to the traveller and take nothing back without their yes. can_undo says whether they may change the trip's places.",
+ inputSchema: { tripId: idSchema, placeId, stepId: undo.step_id },
+ annotations: TOOL_ANNOTATIONS_READONLY,
+ when: addonGate(ADDON_IDS.TOURS),
+ access: { group: 'trips', mode: 'read' },
+ })
+ async prepareTourUndo(
+ { tripId, placeId, stepId }: { tripId: number; placeId: number; stepId: number },
+ ctx: McpContext,
+ ) {
+ if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
+ try {
+ const preview = await this.undoer.prepare(tripId, placeId, stepId);
+ const canUndo = await this.guards.hasTripPermission('place_edit', tripId, ctx.userId);
+ return ok({ ...preview, can_undo: canUndo });
+ } catch (err: unknown) {
+ return tourNotFound(err);
+ }
+ }
+
+ @Tool({
+ name: 'undo_tour_change',
+ description:
+ 'Take back a saved step of a tour that prepare_tour_undo showed and the traveller confirmed: the tour is restored exactly as it was before the step, its line, its stations with their keys, and the distance and walking time stored then, whole or not at all. Call it only after the traveller said yes to taking back exactly that step, with step_id and expected_revision as undo of the preview gave them and confirmed true. Everything is checked again before anything is written: a tour changed since the preview is refused as a conflict (prepare it again), and a step that is no longer the latest change, was taken back already, or would now remove a station visited or skipped meanwhile is refused with the reason; the tour then stays as it is. A step is taken back once, and taking back raises the tour\'s revision like any other save. The answer: undone, step (its id, its revision and undone_revision, the revision taking it back raised the tour to), the tour as now saved (revision, distance_km, walking_minutes, route_pending) and the stations in order with their keys. Read the result with get_tour_plan. It never touches a draft in the planner. Needs place editing permission on the trip.',
+ inputSchema: {
+ tripId: idSchema,
+ placeId,
+ step_id: undo.step_id,
+ expected_revision: undo.expected_revision,
+ confirmed: undo.confirmed,
+ },
+ annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
+ when: addonGate(ADDON_IDS.TOURS),
+ access: { group: 'trips', mode: 'write' },
+ })
+ async undoTourChange(
+ { tripId, placeId, ...request }: { tripId: number; placeId: number } & TourChangeUndoRequest,
+ ctx: McpContext,
+ ) {
+ if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
+ if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
+ try {
+ return ok(await this.undoer.undo(tripId, placeId, ctx.userId, request));
+ } catch (err: unknown) {
+ return tourNotFound(err);
+ }
+ }
+}
diff --git a/server/src/nest/tours/tour-change-undo.service.ts b/server/src/nest/tours/tour-change-undo.service.ts
new file mode 100644
index 000000000..069e5a3d1
--- /dev/null
+++ b/server/src/nest/tours/tour-change-undo.service.ts
@@ -0,0 +1,224 @@
+import { TourChangeSteps } from '../../db/entities/TourChangeSteps.entity';
+import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
+import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
+import { TOUR_CHANGE_STEP_BEFORE, TOUR_CHANGE_STEP_CHANGES, type TourChangeStepBefore } from '../../db/json-columns';
+import type { TourChangeStepRow, TourChangeStepsRepository } from '../../db/repositories/TourChangeSteps.repository';
+import type { TourStationVisitsRepository } from '../../db/repositories/TourStationVisits.repository';
+import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
+import { decodeJson } from '../../utils/json-column';
+import { DomainError } from '../common/domain-error';
+import { UnitOfWork } from '../database/unit-of-work';
+import { doneByKey } from './tour-change-preview.service';
+import { describeUndo, standingOf, undoRefusals, undoRefusalText, type StepStanding } from './tour-change-undo';
+import { tourWriteOf, writtenStations, writtenTour } from './tour-change-write';
+import { tourRevisionConflict } from './tour-revision';
+import { ToursService, type TourRouteWrite } from './tours.service';
+import { InjectRepository } from '@mikro-orm/nestjs';
+import { Injectable } from '@nestjs/common';
+import type { TourChangeUndoRequest, TourWaypoint } from '@trek/shared';
+
+/** A step this tour does not have. */
+export const TOUR_CHANGE_STEP_NOT_FOUND = 'tour_change_step_not_found';
+/** A step taken back already. */
+export const TOUR_CHANGE_STEP_UNDONE = 'tour_change_step_undone';
+/** A step whose record of the tour before it cannot be read. */
+export const TOUR_CHANGE_STEP_WITHOUT_EARLIER_STATE = 'tour_change_step_without_earlier_state';
+/** Taking a step back would lose what the travellers did since; its text names every reason. */
+export const TOUR_CHANGE_UNDO_REFUSED = 'tour_change_undo_refused';
+
+/** The most steps a listing gives, the latest first: only the latest one can be taken back. */
+export const TOUR_CHANGE_STEPS_LISTED = 20;
+
+/** The record of the tour before a step, as kept; null when it cannot be read. */
+function beforeOf(step: TourChangeStepRow): TourChangeStepBefore | null {
+ return decodeJson(TOUR_CHANGE_STEP_BEFORE, step.before_state, `tour_change_steps ${step.id}`);
+}
+
+/** A step as an answer names it: when it was saved, the revisions it went from and to, and its changes. */
+function stepAnswer(step: TourChangeStepRow) {
+ return {
+ id: step.id,
+ saved_at: step.saved_at,
+ base_revision: step.base_revision,
+ revision: step.revision,
+ changes: decodeJson(TOUR_CHANGE_STEP_CHANGES, step.changes, `tour_change_steps ${step.id}`),
+ };
+}
+
+/** Why a step that is not the tour's latest change cannot be taken back, as the refusal says it. */
+function standingRefusal(
+ standing: Exclude<StepStanding, 'latest'>,
+ step: TourChangeStepRow,
+ now: number | null,
+): DomainError {
+ if (standing === 'undone') {
+ return new DomainError(
+ 409,
+ `This step was taken back already, which raised the tour to revision ${step.undone_revision}. Nothing changed.`,
+ { code: TOUR_CHANGE_STEP_UNDONE },
+ );
+ }
+ if (standing === 'later_change') {
+ return tourRevisionConflict(
+ now,
+ `The tour was changed after this step was saved (revision ${step.revision} then, ${now ?? 'unknown'} now). Nothing changed: only the latest change of a tour can be taken back, so no later edit is lost. Read the tour with get_tour_plan and prepare a change instead.`,
+ );
+ }
+ return new DomainError(
+ 409,
+ 'This step keeps no readable record of the tour before it, so there is nothing to restore. Nothing changed.',
+ { code: TOUR_CHANGE_STEP_WITHOUT_EARLIER_STATE },
+ );
+}
+
+/**
+ * The write that restores the tour as the step kept it: its line and points
+ * with their keys, through the write the planner's save uses, and the
+ * measures stored then put back as they were rather than worked out anew.
+ */
+function restoringWrite(write: TourRouteWrite, before: TourChangeStepBefore): TourRouteWrite {
+ return {
+ ...write,
+ fields: {
+ ...write.fields,
+ distance: before.distance,
+ duration: before.duration,
+ elevation_gain: before.elevation_gain,
+ elevation_loss: before.elevation_loss,
+ },
+ };
+}
+
+/** The places of the trip the points of the tour before stand for. */
+function linkedIds(points: readonly TourWaypoint[]): number[] {
+ return points.flatMap((point) => (point.linked_place_id ? [point.linked_place_id] : []));
+}
+
+/**
+ * MCP-T04: a step saved from a confirmed proposal (MCP-T03) taken back, which
+ * restores the tour exactly as the step kept it before. Only the tour's latest
+ * change is taken back: the step's revision has to be the tour's, so anything
+ * saved on top of it since, in the planner or by another step, is a conflict
+ * on the tour's one revision (LIB-01) instead of being lost. Nothing the
+ * travellers did since is thrown away either: a station visited or skipped
+ * that would go, or a place of the trip gone that a station stood for,
+ * refuses it with every reason.
+ *
+ * The preview reads only. Taking back checks everything again inside the
+ * write, restores the line, the points with their keys and the measures in
+ * one transaction with the mark on the step, and tells the trip only after
+ * the commit; a failure leaves the tour as it is. A step is taken back once,
+ * and no second step or revision is kept for it: the tour's revision counts
+ * it like any other write. This is not the planner's undo: a draft in a
+ * browser is never seen here, and discarding one never changes a saved tour.
+ */
+@Injectable()
+export class TourChangeUndoService {
+ constructor(
+ private readonly uow: UnitOfWork,
+ private readonly tours: ToursService,
+ @InjectRepository(TourChangeSteps) private readonly stepsRepo: TourChangeStepsRepository,
+ @InjectRepository(TourStationVisits) private readonly visitsRepo: TourStationVisitsRepository,
+ @InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,
+ ) {}
+
+ /** The saved steps of a tour, the latest first, each with where it stands. */
+ async steps(tripId: number, placeId: number) {
+ const { tour } = await this.tours.getTour(String(tripId), String(placeId));
+ const rows = await this.stepsRepo.listForPlace(placeId, TOUR_CHANGE_STEPS_LISTED);
+ const revision = tour.revision ?? null;
+ return {
+ tour: { place_id: tour.place_id, name: tour.name, tour_type: tour.tour_type, revision },
+ steps: rows.map((step) => ({
+ ...stepAnswer(step),
+ standing: standingOf(step, beforeOf(step), revision).kind,
+ undone: step.undone_revision === null ? null : { revision: step.undone_revision, at: step.undone_at },
+ })),
+ listed_at_most: TOUR_CHANGE_STEPS_LISTED,
+ };
+ }
+
+ /** What taking the step back does, set against the tour now; writes nothing. */
+ async prepare(tripId: number, placeId: number, stepId: number) {
+ const { tour, step, basis } = await this.checked(tripId, placeId, stepId);
+ const measures = {
+ distance_km: tour.distance,
+ walking_minutes: tour.duration,
+ route_pending: tour.route_pending === true,
+ };
+ return {
+ prepared_only: true as const,
+ step: stepAnswer(step),
+ ...describeUndo(basis, measures),
+ undo: { step_id: step.id, expected_revision: step.revision },
+ };
+ }
+
+ /** The step taken back as the traveller confirmed it, whole or not at all. */
+ async undo(tripId: number, placeId: number, userId: number, { step_id, expected_revision }: TourChangeUndoRequest) {
+ const restored = await this.uow.transactional(async () => {
+ const { tour, step, basis } = await this.checked(tripId, placeId, step_id, expected_revision);
+ const { before } = basis;
+ const write = await this.tours.routeWrite(
+ tourWriteOf(tour, {
+ route_geometry: before.route_geometry,
+ duration_seconds: before.duration === null ? null : before.duration * 60,
+ waypoints: before.waypoints,
+ expected_revision,
+ }),
+ );
+ const written = await this.tours.replaceRoute(tripId, placeId, restoringWrite(write, before));
+ const marked = await this.stepsRepo.markUndone(step.id, { undone_revision: written.revision, undone_by: userId });
+ // Only a step taken back between the check and the mark gets here; the throw rolls the restore back.
+ if (!marked) {
+ throw new DomainError(409, 'This step was taken back meanwhile. Nothing changed.', {
+ code: TOUR_CHANGE_STEP_UNDONE,
+ });
+ }
+ return { step, ...written };
+ });
+ const detail = await this.tours.announceRouteUpdate(String(tripId), placeId, restored.visitsDropped);
+ return {
+ undone: true as const,
+ step: { id: restored.step.id, revision: restored.step.revision, undone_revision: restored.revision },
+ tour: writtenTour(detail, restored.revision),
+ stations: writtenStations(detail),
+ };
+ }
+
+ /**
+ * The tour, the step and what taking it back works on, once everything is
+ * checked: the step is this tour's latest change and keeps the tour before
+ * it, the tour is at the revision the preview was read at, and nothing done
+ * since would be lost. Anything else is a refusal, and nothing is written.
+ */
+ private async checked(tripId: number, placeId: number, stepId: number, expected?: number) {
+ const { tour, waypoints } = await this.tours.getTour(String(tripId), String(placeId));
+ const step = await this.stepsRepo.findForPlace(placeId, stepId);
+ if (!step) {
+ throw new DomainError(404, `This tour has no saved step ${stepId}. Nothing changed.`, {
+ code: TOUR_CHANGE_STEP_NOT_FOUND,
+ });
+ }
+ const now = tour.revision ?? null;
+ const standing = standingOf(step, beforeOf(step), now);
+ if (standing.kind !== 'latest') throw standingRefusal(standing.kind, step, now);
+ if (expected !== undefined && expected !== now) {
+ throw tourRevisionConflict(
+ now,
+ `The tour is at revision ${now} now, not ${expected} as the preview was read. Nothing changed: prepare taking the step back again with prepare_tour_undo.`,
+ );
+ }
+ const { before } = standing;
+ const [visits, linkable] = await Promise.all([
+ this.visitsRepo.listForPlace(tripId, placeId),
+ this.waypointsRepo.linkablePlaceIds(tripId, linkedIds(before.waypoints)),
+ ]);
+ const basis = { now: waypoints, before, done: doneByKey(visits), linkable };
+ const refused = undoRefusals(basis);
+ if (refused.length > 0) {
+ throw new DomainError(409, undoRefusalText(refused), { code: TOUR_CHANGE_UNDO_REFUSED, details: { refused } });
+ }
+ return { tour, step, basis };
+ }
+}
diff --git a/server/src/nest/tours/tour-change-undo.ts b/server/src/nest/tours/tour-change-undo.ts
new file mode 100644
index 000000000..942d0e93f
--- /dev/null
+++ b/server/src/nest/tours/tour-change-undo.ts
@@ -0,0 +1,160 @@
+/**
+ * MCP-T04: what taking back a saved step (MCP-T03) does and whether it may,
+ * worked out without writing anything. A step is taken back only while it is
+ * the tour's latest change: once anything else was saved on top of it, the
+ * tour it kept as before is no longer the one under the current plan, and
+ * restoring it would throw the later edits away unseen. Taking back restores
+ * the tour exactly as the step kept it, so it never removes a station that
+ * was visited or skipped since and never drops the link to a place of the
+ * trip: such a step is refused with every reason, and the tour stays as it is.
+ */
+import type { TourChangeStepBefore } from '../../db/json-columns';
+import type { StationDone } from './tour-change-apply';
+import { walkStationsOf, type TourWaypoint } from '@trek/shared';
+
+/** Where a step stands: still the tour's latest change, or why it cannot be taken back any more. */
+export type StepStanding = 'latest' | 'undone' | 'later_change' | 'no_earlier_state';
+
+/** The standing of a step, the latest one carrying the tour as it kept it before. */
+export type Standing =
+ | { kind: 'latest'; before: TourChangeStepBefore }
+ | { kind: Exclude<StepStanding, 'latest'> };
+
+/** What a recorded step says of itself for its standing. */
+interface StepFacts {
+ revision: number;
+ undone_revision: number | null;
+}
+
+/**
+ * The standing of a step on a tour at `tourRevision`. A step taken back says
+ * so first, since taking it back moved the tour on too; a broken record of the
+ * tour before reads as no earlier state, so nothing is restored from a guess.
+ */
+export function standingOf(
+ step: StepFacts,
+ before: TourChangeStepBefore | null,
+ tourRevision: number | null,
+): Standing {
+ if (step.undone_revision !== null) return { kind: 'undone' };
+ if (step.revision !== tourRevision) return { kind: 'later_change' };
+ if (before === null) return { kind: 'no_earlier_state' };
+ return { kind: 'latest', before };
+}
+
+/** Why the stations of a step refuse taking it back. */
+export type UndoRefusal =
+ | { why: 'station_done'; key: string; name: string | null; days: StationDone[] }
+ | { why: 'place_gone'; key: string | null; name: string | null; linked_place_id: number };
+
+/** The tour now and as the step kept it, with what the travellers did since and the places still there. */
+export interface UndoBasis {
+ now: readonly TourWaypoint[];
+ before: TourChangeStepBefore;
+ done: ReadonlyMap<string, StationDone[]>;
+ linkable: ReadonlySet<number>;
+}
+
+const keysOf = (points: readonly TourWaypoint[]) => new Set(points.flatMap((point) => (point.key ? [point.key] : [])));
+
+/** The stations of the tour now that taking the step back removes, with the stations they are. */
+function goingOf(now: readonly TourWaypoint[], before: readonly TourWaypoint[]) {
+ const kept = keysOf(before);
+ return walkStationsOf(now)
+ .map((station, index) => ({ station, position: index + 1 }))
+ .filter(({ station }) => !station.key || !kept.has(station.key));
+}
+
+/**
+ * Every reason taking the step back would lose something: a station it
+ * removes that was visited or skipped on a day since, and a station it
+ * brings back that stands for a place of the trip no longer there.
+ */
+export function undoRefusals({ now, before, done, linkable }: UndoBasis): UndoRefusal[] {
+ const stationsDone = goingOf(now, before.waypoints).flatMap(({ station }) => {
+ const days = station.key ? done.get(station.key) : undefined;
+ return station.key && days
+ ? [{ why: 'station_done' as const, key: station.key, name: station.name ?? null, days }]
+ : [];
+ });
+ const placesGone = before.waypoints.flatMap((point) =>
+ point.linked_place_id && !linkable.has(point.linked_place_id)
+ ? [
+ {
+ why: 'place_gone' as const,
+ key: point.key ?? null,
+ name: point.name ?? null,
+ linked_place_id: point.linked_place_id,
+ },
+ ]
+ : [],
+ );
+ return [...stationsDone, ...placesGone];
+}
+
+/** The refusal as the error text gives it, one reason a line. */
+export function undoRefusalText(refusals: readonly UndoRefusal[]): string {
+ const lines = refusals.map((refusal) =>
+ refusal.why === 'station_done'
+ ? `Station ${refusal.key} (${refusal.name ?? 'no name'}) would be removed, but it was visited or skipped since.`
+ : `Station ${refusal.key ?? 'without key'} (${refusal.name ?? 'no name'}) stands for place ${refusal.linked_place_id}, which is no longer a place of the trip.`,
+ );
+ return ['Taking this step back would lose what was done since. Nothing changed.', ...lines].join('\n');
+}
+
+/** The stations of the tour now, each with whether it was visited or skipped on any day. */
+function stationsNow(now: readonly TourWaypoint[], done: ReadonlyMap<string, StationDone[]>) {
+ return walkStationsOf(now).map((station, index) => ({
+ position: index + 1,
+ key: station.key ?? null,
+ name: station.name ?? null,
+ done: station.key ? done.has(station.key) : false,
+ }));
+}
+
+/** The stations as taking back restores them, each kept from now (and where it stands now) or coming back. */
+function stationsRestored(now: readonly TourWaypoint[], before: readonly TourWaypoint[]) {
+ const nowAt = new Map(
+ walkStationsOf(now).flatMap((station, index) => (station.key ? [[station.key, index + 1] as const] : [])),
+ );
+ return walkStationsOf(before).map((station, index) => {
+ const nowPosition = station.key ? (nowAt.get(station.key) ?? null) : null;
+ return {
+ position: index + 1,
+ key: station.key ?? null,
+ name: station.name ?? null,
+ change: nowPosition === null ? ('back' as const) : ('kept' as const),
+ now_position: nowPosition,
+ };
+ });
+}
+
+/** The measures of the tour now, as stored with it. */
+export interface MeasuresNow {
+ distance_km: number | null;
+ walking_minutes: number | null;
+ route_pending: boolean;
+}
+
+/**
+ * The tour now set against the tour as taking the step back restores it: the
+ * stations of each, the ones it removes and the ones it brings back, and the
+ * measures stored with each, never worked out anew.
+ */
+export function describeUndo(basis: UndoBasis, measures: MeasuresNow) {
+ const { now, before, done } = basis;
+ return {
+ now: { ...measures, stations: stationsNow(now, done) },
+ restored: {
+ distance_km: before.distance,
+ walking_minutes: before.duration,
+ route_pending: before.route_geometry === null,
+ stations: stationsRestored(now, before.waypoints),
+ },
+ removed: goingOf(now, before.waypoints).map(({ station, position }) => ({
+ key: station.key ?? null,
+ name: station.name ?? null,
+ position,
+ })),
+ };
+}
diff --git a/server/src/nest/tours/tour-change-write.ts b/server/src/nest/tours/tour-change-write.ts
new file mode 100644
index 000000000..26d1daa34
--- /dev/null
+++ b/server/src/nest/tours/tour-change-write.ts
@@ -0,0 +1,66 @@
+/**
+ * MCP-T03/T04: what a save of a confirmed change and the taking back of one
+ * have in common: the write of the tour's line and points through the write
+ * the planner's save uses, with the tour's own name, type and options kept as
+ * they are, and the tour as the answer of either gives it once written.
+ */
+import type { TourCreateCommand } from './tours.service';
+import {
+ plannableTourTypeSchema,
+ walkStationsOf,
+ type GeometryPoint,
+ type TourDetailResponse,
+ type TourListItem,
+ type TourWaypoint,
+} from '@trek/shared';
+
+/** The line and points a write puts on the tour, and the revision it is based on. */
+export interface TourLineWrite {
+ route_geometry: GeometryPoint[] | null;
+ duration_seconds: number | null;
+ waypoints: TourWaypoint[];
+ expected_revision: number;
+}
+
+/**
+ * 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.
+ */
+export function tourWriteOf(tour: TourListItem, line: TourLineWrite): TourCreateCommand {
+ return {
+ name: tour.name,
+ // Only a type that takes changes gets here, and each of them is one the planner draws.
+ tour_type: plannableTourTypeSchema.parse(tour.tour_type),
+ ...line,
+ max_hiking_difficulty: tour.max_hiking_difficulty,
+ hiking_preferences: tour.hiking_preferences,
+ bike_profile: tour.bike_profile,
+ boat_type: tour.boat_type,
+ water_context: tour.water_context,
+ paddle_speed_kmh: tour.paddle_speed_kmh,
+ portage_speed_kmh: tour.portage_speed_kmh,
+ paddle_lake_style: tour.paddle_lake_style,
+ };
+}
+
+/** The tour as now saved, read back through the read the app uses, at the revision the write raised it to. */
+export function writtenTour(detail: TourDetailResponse, revision: number) {
+ return {
+ place_id: detail.tour.place_id,
+ name: detail.tour.name,
+ tour_type: detail.tour.tour_type,
+ revision,
+ distance_km: detail.tour.distance,
+ walking_minutes: detail.tour.duration,
+ route_pending: detail.tour.route_pending === true,
+ };
+}
+
+/** The stations of the tour as now saved, in order, with their keys. */
+export function writtenStations(detail: TourDetailResponse) {
+ return walkStationsOf(detail.waypoints).map((station, index) => ({
+ position: index + 1,
+ key: station.key ?? null,
+ name: station.name ?? null,
+ }));
+}
diff --git a/server/src/nest/tours/tour-change.mcp.ts b/server/src/nest/tours/tour-change.mcp.ts
index 34f28b2b2..1b9791806 100644
--- a/server/src/nest/tours/tour-change.mcp.ts
+++ b/server/src/nest/tours/tour-change.mcp.ts
@@ -82,7 +82,7 @@ export class TourChangeMcp {
@Tool({
name: 'save_tour_change',
description:
- "Save a change to a saved tour that prepare_tour_change prepared and the traveller confirmed, whole or not at all. Call it only after the traveller said yes to the proposal exactly as it was shown to them, with confirmed true, the same changes, expected_revision set to base.revision and the proposal_id of that proposal; anything else is refused and nothing is saved. Before anything is written the trip permission and the tour are checked again: a tour changed since the proposal was prepared is refused as a conflict (prepare the change again from get_tour_plan, never retry the old one), and a change the rules no longer allow (a station visited or skipped meanwhile, a place of the trip gone) is refused with every reason. The save writes the stations, their keys and the way on foot as the planner's save does, planned by the same router as the proposal: where the router gives no way the walk keeps its stations only (route_pending true, distance and walking time null) until the planner plans it. Stations kept keep their keys and their visits. The answer: saved, step (its id, base_revision and the revision the save raised the tour to; the step keeps the changes and the tour as it was before, for taking it back later, and nothing of the conversation), the tour as now saved (revision, distance_km, walking_minutes, route_pending), foot_way (planned, or why not) and the stations in order with their keys. Read the result with get_tour_plan. A new walk has no revision yet: create it with create_city_walk instead. Needs place editing permission on the trip.",
+ "Save a change to a saved tour that prepare_tour_change prepared and the traveller confirmed, whole or not at all. Call it only after the traveller said yes to the proposal exactly as it was shown to them, with confirmed true, the same changes, expected_revision set to base.revision and the proposal_id of that proposal; anything else is refused and nothing is saved. Before anything is written the trip permission and the tour are checked again: a tour changed since the proposal was prepared is refused as a conflict (prepare the change again from get_tour_plan, never retry the old one), and a change the rules no longer allow (a station visited or skipped meanwhile, a place of the trip gone) is refused with every reason. The save writes the stations, their keys and the way on foot as the planner's save does, planned by the same router as the proposal: where the router gives no way the walk keeps its stations only (route_pending true, distance and walking time null) until the planner plans it. Stations kept keep their keys and their visits. The answer: saved, step (its id, base_revision and the revision the save raised the tour to; the step keeps the changes and the tour as it was before, so it can be taken back with prepare_tour_undo and undo_tour_change while it is the latest change, and nothing of the conversation), the tour as now saved (revision, distance_km, walking_minutes, route_pending), foot_way (planned, or why not) and the stations in order with their keys. Read the result with get_tour_plan. A new walk has no revision yet: create it with create_city_walk instead. Needs place editing permission on the trip.",
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
diff --git a/server/src/nest/tours/tours.module.ts b/server/src/nest/tours/tours.module.ts
index c4a8d6f23..6c4c504a0 100644
--- a/server/src/nest/tours/tours.module.ts
+++ b/server/src/nest/tours/tours.module.ts
@@ -22,6 +22,8 @@ import { CityWalkFootWayService } from './city-walk-foot-way.service';
import { CityWalkMcp } from './city-walk.mcp';
import { TourChangePreviewService } from './tour-change-preview.service';
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 { TourGpxExportService } from './tour-gpx-export.service';
import { TourHorseRoutesController } from './tour-horse-routes.controller';
@@ -132,11 +134,13 @@ import { Module } from '@nestjs/common';
CityWalkBriefingService,
TourChangePreviewService,
TourChangeSaveService,
+ TourChangeUndoService,
ToursMcp,
TourLibraryMcp,
TourWalkImportMcp,
CityWalkMcp,
TourChangeMcp,
+ TourChangeUndoMcp,
],
})
export class ToursModule {}
diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts
index ddf3bea1a..a4500493a 100644
--- a/server/tests/unit/db/legacy-baseline.test.ts
+++ b/server/tests/unit/db/legacy-baseline.test.ts
@@ -71,6 +71,7 @@ const UNNUMBERED = [
'Migration20200101045520_a_tour_can_be_a_ski_track',
'Migration20200101045600_a_tour_can_be_ridden_on_horseback',
'Migration20200101045700_a_tour_records_the_changes_saved_from_a_proposal',
+ 'Migration20200101045710_a_saved_tour_change_can_be_taken_back',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
diff --git a/server/tests/unit/db/repositories/TourChangeSteps.repository.test.ts b/server/tests/unit/db/repositories/TourChangeSteps.repository.test.ts
index eff7bedea..5c0b221e7 100644
--- a/server/tests/unit/db/repositories/TourChangeSteps.repository.test.ts
+++ b/server/tests/unit/db/repositories/TourChangeSteps.repository.test.ts
@@ -2,7 +2,8 @@
* `TourChangeStepsRepository` (MCP-T03): a step saved from a confirmed
* proposal recorded whole with its id answered, one step per revision of a
* tour, its revision the next after the one it was prepared on, and the steps
- * going with their tour.
+ * going with their tour. MCP-T04: the steps of a tour read back, the latest
+ * first and only the tour's own, and a step marked taken back once.
*/
import { TourChangeSteps } from '../../../../src/db/entities/TourChangeSteps.entity';
import { Tours } from '../../../../src/db/entities/Tours.entity';
@@ -93,4 +94,49 @@ describe('TourChangeStepsRepository', () => {
await deleteRows(t, Tours, { place: place.id });
expect(await countRows(t, TourChangeSteps, {})).toBe(0);
});
+
+ it('TCSTEP-004: lists the steps of a tour the latest first, at most as many as asked, and finds only its own', async () => {
+ const { place } = await walk();
+ const { place: other } = await walk();
+ const first = await steps.record(step(place.id));
+ const second = await steps.record(step(place.id, { base_revision: 4, revision: 5 }));
+ const elsewhere = await steps.record(step(other.id));
+
+ const listed = await steps.listForPlace(place.id, 20);
+ expect(listed.map((row) => [row.id, row.revision])).toEqual([
+ [second, 5],
+ [first, 4],
+ ]);
+ expect(listed[1]).toMatchObject({
+ base_revision: 3,
+ changes: '[{"op":"remove","key":"stop-park"}]',
+ before_state: '{"route_geometry":null,"waypoints":[]}',
+ saved_at: expect.any(String),
+ undone_revision: null,
+ undone_at: null,
+ });
+ expect((await steps.listForPlace(place.id, 1)).map((row) => row.id)).toEqual([second]);
+ expect((await steps.findForPlace(place.id, first))?.id).toBe(first);
+ expect(await steps.findForPlace(place.id, elsewhere)).toBeUndefined();
+ });
+
+ it('TCSTEP-005: marks a step taken back once, with the revision that raised the tour to, who and when', async () => {
+ const { user, place } = await walk();
+ const id = await steps.record(step(place.id));
+
+ expect(await steps.markUndone(id, { undone_revision: 5, undone_by: user.id })).toBe(true);
+ expect(await steps.markUndone(id, { undone_revision: 6, undone_by: null })).toBe(false);
+
+ const row = await findRow(t, TourChangeSteps, { id });
+ expect([row?.undone_revision, row?.undone_by]).toEqual([5, user.id]);
+ expect(row?.undone_at).toEqual(expect.any(String));
+ expect((await steps.findForPlace(place.id, id))?.undone_revision).toBe(5);
+ });
+
+ it('TCSTEP-006: taking a step back always raises the tour past the revision the step saved', async () => {
+ const { place } = await walk();
+ const id = await steps.record(step(place.id));
+ await expect(steps.markUndone(id, { undone_revision: 4, undone_by: null })).rejects.toThrow();
+ expect((await findRow(t, TourChangeSteps, { id }))?.undone_revision).toBeNull();
+ });
});
diff --git a/server/tests/unit/nest/tour-change-undo.mcp.test.ts b/server/tests/unit/nest/tour-change-undo.mcp.test.ts
new file mode 100644
index 000000000..f16732fcc
--- /dev/null
+++ b/server/tests/unit/nest/tour-change-undo.mcp.test.ts
@@ -0,0 +1,514 @@
+/**
+ * TourChangeUndoMcp (MCP-T04): a step saved with save_tour_change listed,
+ * previewed without writing, and taken back once the traveller confirmed it,
+ * which restores the tour exactly as the step kept it. Only the tour's latest
+ * change is taken back: anything saved on top of it since is a conflict on
+ * the tour's one revision, and a station done since that would go, or a
+ * place of the trip gone, refuses it; every refusal and failure leaves the
+ * tour as it is. The suite takes its subject from the container over a
+ * snapshot test db, saves the steps through the real save with a stub of the
+ * road trip's router and seeds through the ORM factories.
+ */
+import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';
+import { Places } from '../../../src/db/entities/Places.entity';
+import { TourChangeSteps } from '../../../src/db/entities/TourChangeSteps.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 { TourChangeStepsRepository } from '../../../src/db/repositories/TourChangeSteps.repository';
+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 { TourChangeUndoMcp } from '../../../src/nest/tours/tour-change-undo.mcp';
+import {
+ TOUR_CHANGE_STEP_NOT_FOUND,
+ TOUR_CHANGE_STEP_UNDONE,
+ TOUR_CHANGE_STEP_WITHOUT_EARLIER_STATE,
+ TOUR_CHANGE_STEPS_LISTED,
+ TOUR_CHANGE_UNDO_REFUSED,
+} from '../../../src/nest/tours/tour-change-undo.service';
+import { TourChangeMcp } from '../../../src/nest/tours/tour-change.mcp';
+import { ToursMcp } from '../../../src/nest/tours/tours.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, deleteRows, findRow, findRows, updateRows } 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 { TOUR_REVISION_CONFLICT, type TourChange, type TourChangeUndoRequest } 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: TourChangeUndoMcp;
+const orm = () => t.get(MikroORM);
+
+/** Every leg the router plans is 500 m and 400 s on foot, along the points asked. */
+async function routedOnFoot(
+ _userId: number,
+ _tripId: number,
+ _dayId: number,
+ points: Array<{ lat: number; lng: number }>,
+) {
+ return {
+ 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: [],
+ };
+}
+
+beforeAll(async () => {
+ t = await createTestModule({
+ db,
+ imports: [ToursModule],
+ overrides: [{ provide: RoadtripRouterService, useValue: { route } }],
+ });
+ mcp = t.get(TourChangeUndoMcp);
+});
+beforeEach(() => {
+ resetTestDb(db);
+ route.mockReset().mockImplementation(routedOnFoot);
+ t.realtime.broadcastMock.mockReset();
+});
+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);
+}
+
+/** The refusal a tool raised, which the registry answers with its text. */
+async function refusal(promise: Promise<unknown>): Promise<DomainError> {
+ const err = await catchDomainError(() => promise);
+ if (!(err instanceof DomainError)) throw new Error('no refusal');
+ return err;
+}
+
+const OLD_TOWN_LINE = '[[48.1,11.5],[48.112,11.5]]';
+
+/**
+ * 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 bakery of the trip. `line` false saves it with its
+ * stations only, its measures unknown.
+ */
+async function fixture({ line = true } = {}) {
+ const { user } = await makeUser(orm());
+ const { user: outsider } = await makeUser(orm());
+ const trip = 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', route_geometry: line ? OLD_TOWN_LINE : null });
+ const measures = line ? { distance: 1.6, duration: 22 } : { distance: null, duration: null };
+ await makeTour(orm(), walk.id, { tourTypeRef: 'walk', revision: 3, ...measures });
+ 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 bakery = await makePlace(orm(), trip.id, { name: 'Bakery', lat: 48.109, lng: 11.501 });
+ return { user, outsider, trip, walk, onDay1, bakery };
+}
+
+type Fixture = Awaited<ReturnType<typeof fixture>>;
+
+/** A stop at the bakery after the market and a beer garden in the place of the park. */
+const stopAndSwap = (bakeryId: number): TourChange[] => [
+ {
+ op: 'add',
+ station: { lat: 48.109, lng: 11.501, name: 'Bakery', stay_minutes: 15, linked_place_id: bakeryId },
+ after_key: 'stop-market',
+ },
+ { op: 'replace', key: 'stop-park', station: { lat: 48.113, lng: 11.502, name: 'Beer garden' } },
+];
+
+/** The changes prepared and saved as the traveller confirmed them; answers what the save answered. */
+async function saved(f: Fixture, changes: TourChange[]) {
+ const changeMcp = t.get(TourChangeMcp);
+ const tour = { tripId: f.trip.id, placeId: f.walk.id };
+ const proposal = read(await changeMcp.prepareTourChange({ ...tour, changes }, ctx(f.user.id)));
+ const request = {
+ changes,
+ expected_revision: proposal.base.revision,
+ proposal_id: proposal.proposal_id,
+ confirmed: true as const,
+ };
+ const answer = read(await changeMcp.saveTourChange({ ...tour, ...request }, ctx(f.user.id)));
+ t.realtime.broadcastMock.mockReset();
+ return answer;
+}
+
+const listed = async (f: Fixture, userId = f.user.id) =>
+ read(await mcp.listTourChangeSteps({ tripId: f.trip.id, placeId: f.walk.id }, ctx(userId)));
+const prepared = (f: Fixture, stepId: number, userId = f.user.id) =>
+ mcp.prepareTourUndo({ tripId: f.trip.id, placeId: f.walk.id, stepId }, ctx(userId));
+const undone = (f: Fixture, request: TourChangeUndoRequest, userId = f.user.id) =>
+ mcp.undoTourChange({ tripId: f.trip.id, placeId: f.walk.id, ...request }, ctx(userId));
+const confirmed = (step_id: number, expected_revision: number): TourChangeUndoRequest => ({
+ step_id,
+ expected_revision,
+ confirmed: true,
+});
+
+/** What a refused or failed undo must leave as it is. */
+const untouched = async (placeId: number) => [
+ await countRows(orm(), Places, {}),
+ await countRows(orm(), TourStationVisits, {}),
+ await countRows(orm(), DayAssignments, {}),
+ (await findRows(orm(), TourChangeSteps, {}, { id: 'asc' })).map((step) => step.undone_revision),
+ (await findRow(orm(), Tours, { place: placeId }))?.revision,
+ (await findRow(orm(), Places, { id: placeId }))?.route_geometry,
+ (await findRows(orm(), TourWaypoints, { place: placeId }, { sequence: 'asc' })).map((point) => point.station_key),
+];
+
+describe('TourChangeUndoMcp (MCP-T04)', () => {
+ it('TCHG-UNDO-001: the latest step is listed, previewed and taken back, restoring the tour exactly and read back the same', async () => {
+ const f = await fixture();
+ const save = await saved(f, stopAndSwap(f.bakery.id));
+ const [bakeryKey, beerKey] = [save.stations[3].key, save.stations[4].key];
+
+ const list = await listed(f);
+ expect(list).toMatchObject({
+ tour: { place_id: f.walk.id, name: 'Old town', tour_type: 'walk', revision: 4 },
+ listed_at_most: TOUR_CHANGE_STEPS_LISTED,
+ });
+ expect(list.steps).toEqual([
+ {
+ id: save.step.id,
+ saved_at: expect.any(String),
+ base_revision: 3,
+ revision: 4,
+ changes: stopAndSwap(f.bakery.id),
+ standing: 'latest',
+ undone: null,
+ },
+ ]);
+
+ route.mockClear();
+ const preview = read(await prepared(f, save.step.id));
+ expect(preview).toMatchObject({
+ prepared_only: true,
+ step: { id: save.step.id, base_revision: 3, revision: 4, changes: stopAndSwap(f.bakery.id) },
+ now: { walking_minutes: 27, route_pending: false },
+ restored: { distance_km: 1.6, walking_minutes: 22, route_pending: false },
+ undo: { step_id: save.step.id, expected_revision: 4 },
+ can_undo: true,
+ });
+ expect(preview.now.stations.map((s: { name: string; done: boolean }) => [s.name, s.done])).toEqual([
+ ['Gate', true],
+ ['Cathedral', false],
+ ['Market', true],
+ ['Bakery', false],
+ ['Beer garden', false],
+ ]);
+ expect(preview.restored.stations).toEqual([
+ { position: 1, key: 'stop-gate', name: 'Gate', change: 'kept', now_position: 1 },
+ { position: 2, key: 'stop-cathedral', name: 'Cathedral', change: 'kept', now_position: 2 },
+ { position: 3, key: 'stop-market', name: 'Market', change: 'kept', now_position: 3 },
+ { position: 4, key: 'stop-park', name: 'Park', change: 'back', now_position: null },
+ ]);
+ expect(preview.removed).toEqual([
+ { key: bakeryKey, name: 'Bakery', position: 4 },
+ { key: beerKey, name: 'Beer garden', position: 5 },
+ ]);
+ // The preview wrote nothing and planned no way: the tour is restored as stored.
+ expect((await findRow(orm(), Tours, { place: f.walk.id }))?.revision).toBe(4);
+ expect(t.realtime.broadcastMock).not.toHaveBeenCalled();
+
+ const answer = read(await undone(f, confirmed(preview.undo.step_id, preview.undo.expected_revision)));
+
+ expect(answer).toEqual({
+ undone: true,
+ step: { id: save.step.id, revision: 4, undone_revision: 5 },
+ tour: {
+ place_id: f.walk.id,
+ name: 'Old town',
+ tour_type: 'walk',
+ revision: 5,
+ distance_km: 1.6,
+ walking_minutes: 22,
+ route_pending: false,
+ },
+ stations: [
+ { position: 1, key: 'stop-gate', name: 'Gate' },
+ { position: 2, key: 'stop-cathedral', name: 'Cathedral' },
+ { position: 3, key: 'stop-market', name: 'Market' },
+ { position: 4, key: 'stop-park', name: 'Park' },
+ ],
+ });
+ expect(route).not.toHaveBeenCalled();
+
+ // Restored: the line, the start, the points with their keys and what they carried, the measures, the visits.
+ const place = await findRow(orm(), Places, { id: f.walk.id });
+ expect([place?.route_geometry, place?.lat, place?.lng]).toEqual([OLD_TOWN_LINE, 48.1, 11.5]);
+ const points = await findRows(orm(), TourWaypoints, { place: f.walk.id }, { sequence: 'asc' });
+ expect(points.map((point) => [point.station_key, point.role, point.protected, point.importance])).toEqual([
+ ['stop-gate', 'start', 0, null],
+ ['stop-cathedral', 'via', 1, null],
+ ['stop-market', 'via', 0, null],
+ ['stop-park', 'end', 0, 'must'],
+ ]);
+ const tour = await findRow(orm(), Tours, { place: f.walk.id });
+ expect([tour?.revision, tour?.distance, tour?.duration]).toEqual([5, 1.6, 22]);
+ expect(await countRows(orm(), TourStationVisits, {})).toBe(2);
+ const step = await findRow(orm(), TourChangeSteps, { id: save.step.id });
+ expect([step?.undone_revision, step?.undone_by]).toEqual([5, f.user.id]);
+ expect(step?.undone_at).toEqual(expect.any(String));
+
+ // Every client of the trip is told, after the commit.
+ const events = t.realtime.broadcastMock.mock.calls.map(([tripId, event]) => [tripId, event]);
+ expect(events).toEqual([
+ [String(f.trip.id), 'tours:changed'],
+ [String(f.trip.id), 'place:updated'],
+ ]);
+
+ // The tour read again says what taking back answered, and the step says it was taken back.
+ const plan = read(await t.get(ToursMcp).getTourPlan({ tripId: f.trip.id, placeId: f.walk.id }, ctx(f.user.id)));
+ expect(plan.tour).toMatchObject({ revision: 5, distance: 1.6, duration: 22 });
+ expect(plan.waypoints.map((point: { key: string }) => point.key)).toEqual(
+ answer.stations.map((s: { key: string }) => s.key),
+ );
+ expect((await listed(f)).steps[0]).toMatchObject({
+ standing: 'undone',
+ undone: { revision: 5, at: expect.any(String) },
+ });
+ });
+
+ it('TCHG-UNDO-002: a step something was saved on top of is a conflict, while the latest one still goes back alone', async () => {
+ const f = await fixture();
+ const first = await saved(f, stopAndSwap(f.bakery.id));
+ const second = await saved(f, [{ op: 'remove', key: first.stations[3].key }]);
+
+ expect((await listed(f)).steps.map((s: { id: number; standing: string }) => [s.id, s.standing])).toEqual([
+ [second.step.id, 'latest'],
+ [first.step.id, 'later_change'],
+ ]);
+ const before = await untouched(f.walk.id);
+ for (const attempt of [() => prepared(f, first.step.id), () => undone(f, confirmed(first.step.id, 5))]) {
+ const err = await refusal(attempt());
+ expect([err.getStatus(), err.code, err.details?.revision]).toEqual([409, TOUR_REVISION_CONFLICT, 5]);
+ expect(err.publicMessage).toContain('(revision 4 then, 5 now). Nothing changed: only the latest change');
+ }
+ expect(await untouched(f.walk.id)).toEqual(before);
+
+ // The latest step goes back to the walk the first one left; the first stays where it is.
+ const answer = read(await undone(f, confirmed(second.step.id, 5)));
+ expect(answer.stations.map((s: { name: string }) => s.name)).toEqual([
+ 'Gate',
+ 'Cathedral',
+ 'Market',
+ 'Bakery',
+ 'Beer garden',
+ ]);
+ expect((await listed(f)).steps.map((s: { standing: string }) => s.standing)).toEqual(['undone', 'later_change']);
+ });
+
+ it('TCHG-UNDO-003: a step is taken back once, and a preview read at another revision is a conflict', async () => {
+ const f = await fixture();
+ const save = await saved(f, stopAndSwap(f.bakery.id));
+
+ const stale = await refusal(undone(f, confirmed(save.step.id, 3)));
+ expect([stale.getStatus(), stale.code, stale.details?.revision]).toEqual([409, TOUR_REVISION_CONFLICT, 4]);
+ expect(stale.publicMessage).toBe(
+ 'The tour is at revision 4 now, not 3 as the preview was read. Nothing changed: prepare taking the step back again with prepare_tour_undo.',
+ );
+
+ read(await undone(f, confirmed(save.step.id, 4)));
+ const before = await untouched(f.walk.id);
+ const again = await refusal(undone(f, confirmed(save.step.id, 5)));
+ expect([again.getStatus(), again.code]).toEqual([409, TOUR_CHANGE_STEP_UNDONE]);
+ expect(again.publicMessage).toBe(
+ 'This step was taken back already, which raised the tour to revision 5. Nothing changed.',
+ );
+ expect(await untouched(f.walk.id)).toEqual(before);
+ });
+
+ it('TCHG-UNDO-004: a station visited since that taking back would remove refuses it with every reason', async () => {
+ const f = await fixture();
+ const save = await saved(f, stopAndSwap(f.bakery.id));
+ const bakeryKey = save.stations[3].key;
+ await markStationVisit(orm(), f.onDay1.id, bakeryKey, 'visited');
+ const before = await untouched(f.walk.id);
+
+ for (const attempt of [() => prepared(f, save.step.id), () => undone(f, confirmed(save.step.id, 4))]) {
+ const err = await refusal(attempt());
+ expect([err.getStatus(), err.code]).toEqual([409, TOUR_CHANGE_UNDO_REFUSED]);
+ expect(err.details?.refused).toEqual([
+ {
+ why: 'station_done',
+ key: bakeryKey,
+ name: 'Bakery',
+ days: [{ day_id: expect.any(Number), status: 'visited' }],
+ },
+ ]);
+ expect(err.publicMessage).toMatch(
+ /^Taking this step back would lose what was done since\. Nothing changed\.\nStation /,
+ );
+ }
+ expect(await untouched(f.walk.id)).toEqual(before);
+ expect(t.realtime.broadcastMock).not.toHaveBeenCalled();
+ });
+
+ it('TCHG-UNDO-005: a station whose place of the trip is gone refuses bringing it back', async () => {
+ const f = await fixture();
+ const first = await saved(f, stopAndSwap(f.bakery.id));
+ const second = await saved(f, [{ op: 'remove', key: first.stations[3].key }]);
+ await deleteRows(orm(), Places, { id: f.bakery.id });
+
+ const err = await refusal(prepared(f, second.step.id));
+ expect([err.getStatus(), err.code]).toEqual([409, TOUR_CHANGE_UNDO_REFUSED]);
+ expect(err.details?.refused).toEqual([
+ { why: 'place_gone', key: first.stations[3].key, name: 'Bakery', linked_place_id: f.bakery.id },
+ ]);
+ });
+
+ it('TCHG-UNDO-006: a step without a readable earlier tour, or one this tour does not have, is refused', async () => {
+ const f = await fixture();
+ const save = await saved(f, stopAndSwap(f.bakery.id));
+ const other = await makePlace(orm(), f.trip.id, { name: 'Harbour' });
+ await makeTour(orm(), other.id, { tourTypeRef: 'walk', revision: 1 });
+
+ const missing = await refusal(prepared(f, save.step.id + 100));
+ expect([missing.getStatus(), missing.code]).toEqual([404, TOUR_CHANGE_STEP_NOT_FOUND]);
+ const elsewhere = await refusal(
+ mcp.prepareTourUndo({ tripId: f.trip.id, placeId: other.id, stepId: save.step.id }, ctx(f.user.id)),
+ );
+ expect(elsewhere.code).toBe(TOUR_CHANGE_STEP_NOT_FOUND);
+
+ await updateRows(orm(), TourChangeSteps, { id: save.step.id }, { before_state: '{"waypoints":"broken"' });
+ expect((await listed(f)).steps[0].standing).toBe('no_earlier_state');
+ const before = await untouched(f.walk.id);
+ const broken = await refusal(undone(f, confirmed(save.step.id, 4)));
+ expect([broken.getStatus(), broken.code]).toEqual([409, TOUR_CHANGE_STEP_WITHOUT_EARLIER_STATE]);
+ expect(await untouched(f.walk.id)).toEqual(before);
+ });
+
+ it('TCHG-UNDO-007: a failure inside the write, or a step taken back meanwhile, rolls the whole restore back', async () => {
+ const f = await fixture();
+ const save = await saved(f, stopAndSwap(f.bakery.id));
+ const before = await untouched(f.walk.id);
+
+ const failure = new Error('disk full');
+ const mark = vi.spyOn(TourChangeStepsRepository.prototype, 'markUndone').mockRejectedValueOnce(failure);
+ try {
+ await expect(undone(f, confirmed(save.step.id, 4))).rejects.toBe(failure);
+ mark.mockResolvedValueOnce(false);
+ const meanwhile = await refusal(undone(f, confirmed(save.step.id, 4)));
+ expect([meanwhile.code, meanwhile.publicMessage]).toEqual([
+ TOUR_CHANGE_STEP_UNDONE,
+ 'This step was taken back meanwhile. Nothing changed.',
+ ]);
+ } finally {
+ mark.mockRestore();
+ }
+ expect(await untouched(f.walk.id)).toEqual(before);
+ expect(t.realtime.broadcastMock).not.toHaveBeenCalled();
+ });
+
+ it('TCHG-UNDO-008: a walk that waited for its way before the step waits for it again', async () => {
+ const f = await fixture({ line: false });
+ const save = await saved(f, [{ op: 'remove', key: 'stop-park' }]);
+ expect(save.tour.route_pending).toBe(false);
+
+ const preview = read(await prepared(f, save.step.id));
+ expect(preview.restored).toMatchObject({ distance_km: null, walking_minutes: null, route_pending: true });
+
+ const answer = read(await undone(f, confirmed(save.step.id, 4)));
+ expect(answer.tour).toMatchObject({ revision: 5, distance_km: null, walking_minutes: null, route_pending: true });
+ const place = await findRow(orm(), Places, { id: f.walk.id });
+ expect([place?.route_geometry, place?.lat, place?.lng]).toEqual([null, 48.1, 11.5]);
+ expect(answer.stations.map((s: { key: string }) => s.key)).toEqual([
+ 'stop-gate',
+ 'stop-cathedral',
+ 'stop-market',
+ 'stop-park',
+ ]);
+ });
+
+ it('TCHG-UNDO-009: only a traveller of the trip reads the steps, and only one with place editing takes one back', async () => {
+ const f = await fixture();
+ const save = await saved(f, stopAndSwap(f.bakery.id));
+ const before = await untouched(f.walk.id);
+ const noAccess = { error: 'Trip not found or access denied.' };
+
+ expect(await listed(f, f.outsider.id)).toEqual(noAccess);
+ expect(read(await prepared(f, save.step.id, f.outsider.id))).toEqual(noAccess);
+ expect(read(await undone(f, confirmed(save.step.id, 4), f.outsider.id))).toEqual(noAccess);
+
+ const guard = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValue(false);
+ try {
+ expect(read(await prepared(f, save.step.id)).can_undo).toBe(false);
+ expect(read(await undone(f, confirmed(save.step.id, 4)))).toEqual({
+ error: 'You do not have permission to perform this action on this trip.',
+ });
+ expect(guard).toHaveBeenCalledWith('place_edit', f.trip.id, f.user.id);
+ } finally {
+ guard.mockRestore();
+ }
+
+ const noTour = { error: 'Tour not found.' };
+ const bakery = { tripId: f.trip.id, placeId: f.bakery.id };
+ expect(read(await mcp.listTourChangeSteps(bakery, ctx(f.user.id)))).toEqual(noTour);
+ expect(read(await mcp.prepareTourUndo({ ...bakery, stepId: save.step.id }, ctx(f.user.id)))).toEqual(noTour);
+ const undoBakery = await mcp.undoTourChange({ ...bakery, ...confirmed(save.step.id, 4) }, ctx(f.user.id));
+ expect(read(undoBakery)).toEqual(noTour);
+ expect(await untouched(f.walk.id)).toEqual(before);
+ });
+
+ it('TCHG-UNDO-010: the listing and the preview read, taking back writes, all on the Tours addon and never without the yes', async () => {
+ const tools = [
+ ['listTourChangeSteps', 'list_tour_change_steps', true, 'read', ['tripId', 'placeId']],
+ ['prepareTourUndo', 'prepare_tour_undo', true, 'read', ['tripId', 'placeId', 'stepId']],
+ [
+ 'undoTourChange',
+ 'undo_tour_change',
+ false,
+ 'write',
+ ['tripId', 'placeId', 'step_id', 'expected_revision', 'confirmed'],
+ ],
+ ] as const;
+ for (const [method, name, readOnly, mode, fields] of tools) {
+ const entry = getEntry(TourChangeUndoMcp as unknown as ClassRef, method);
+ if (!entry || entry.kind !== 'tool') throw new Error(`${method} is no MCP tool`);
+ const { options } = entry;
+ expect([options.name, options.annotations?.readOnlyHint, options.access]).toEqual([
+ name,
+ readOnly,
+ { group: 'trips', mode },
+ ]);
+ expect(Object.keys(options.inputSchema as object)).toEqual([...fields]);
+ expect(options.description).toContain('planner');
+ const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
+ expect(await options.when?.(ctx(1), { addons: { isAddonEnabled } })).toBe(true);
+ expect(isAddonEnabled).toHaveBeenCalledWith('tours');
+ }
+ const entry = getEntry(TourChangeUndoMcp as unknown as ClassRef, 'undoTourChange');
+ if (!entry || entry.kind !== 'tool') throw new Error('undoTourChange is no MCP tool');
+ // The fields are zod schemas from @trek/shared, read here by what they answer.
+ const shape = entry.options.inputSchema as Record<string, { safeParse(value: unknown): { success: boolean } }>;
+ const yes = [true, false, undefined].map((value) => shape.confirmed?.safeParse(value).success);
+ expect(yes).toEqual([true, false, false]);
+ for (const term of ['prepare_tour_undo', 'expected_revision', 'conflict', 'get_tour_plan']) {
+ expect(entry.options.description).toContain(term);
+ }
+ });
+});
diff --git a/server/tests/unit/nest/tour-change-undo.test.ts b/server/tests/unit/nest/tour-change-undo.test.ts
new file mode 100644
index 000000000..00a619906
--- /dev/null
+++ b/server/tests/unit/nest/tour-change-undo.test.ts
@@ -0,0 +1,152 @@
+/**
+ * MCP-T04: what taking back a saved step does and whether it may, worked out
+ * without writing: the standing of a step, the reasons taking it back would
+ * lose something, and the tour now set against the tour it restores.
+ */
+import type { TourChangeStepBefore } from '../../../src/db/json-columns';
+import type { StationDone } from '../../../src/nest/tours/tour-change-apply';
+import {
+ describeUndo,
+ standingOf,
+ undoRefusals,
+ undoRefusalText,
+ type UndoBasis,
+} from '../../../src/nest/tours/tour-change-undo';
+import type { TourWaypoint } from '@trek/shared';
+
+import { describe, expect, it } from 'vitest';
+
+// TCHG-UNDO-PURE-001 to TCHG-UNDO-PURE-006
+
+const point = (key: string | undefined, sequence: number, extra: Partial<TourWaypoint> = {}): TourWaypoint => ({
+ lat: 48 + sequence * 0.01,
+ lng: 11,
+ role: 'via',
+ sequence,
+ ...(key ? { key, name: key.replace('stop-', '') } : {}),
+ ...extra,
+});
+
+/** The walk before the step: gate, museum (standing for place 7), park. */
+const before: TourChangeStepBefore = {
+ route_geometry: [
+ [48, 11],
+ [48.02, 11],
+ ],
+ waypoints: [
+ point('stop-gate', 0, { role: 'start' }),
+ point('stop-museum', 1, { linked_place_id: 7 }),
+ point('stop-park', 2, { role: 'end' }),
+ ],
+ distance: 1.2,
+ duration: 18,
+ elevation_gain: null,
+ elevation_loss: null,
+};
+
+/** The walk after the step: gate, a new cafe, park and a new end, the museum gone. */
+const now: TourWaypoint[] = [
+ point('stop-gate', 0, { role: 'start' }),
+ point('stop-cafe1', 1),
+ point('stop-park', 2),
+ point('stop-pier1', 3, { role: 'end' }),
+];
+
+const basis = (done: Array<[string, StationDone[]]> = [], linkable: number[] = [7]): UndoBasis => ({
+ now,
+ before,
+ done: new Map(done),
+ linkable: new Set(linkable),
+});
+
+describe('tour change undo, pure (MCP-T04)', () => {
+ it('TCHG-UNDO-PURE-001: a step stands as the latest change only on its own revision, untaken back and with a tour before it', () => {
+ const step = { revision: 4, undone_revision: null };
+ expect(standingOf(step, before, 4)).toEqual({ kind: 'latest', before });
+ expect(standingOf({ revision: 4, undone_revision: 5 }, before, 5)).toEqual({ kind: 'undone' });
+ expect(standingOf(step, before, 5)).toEqual({ kind: 'later_change' });
+ expect(standingOf(step, before, null)).toEqual({ kind: 'later_change' });
+ expect(standingOf(step, null, 4)).toEqual({ kind: 'no_earlier_state' });
+ });
+
+ it('TCHG-UNDO-PURE-002: nothing done since and every place still there refuses nothing', () => {
+ expect(undoRefusals(basis())).toEqual([]);
+ // A station that stays may well have been done: its visit stays with it.
+ expect(undoRefusals(basis([['stop-park', [{ day_id: 1, status: 'visited' }]]]))).toEqual([]);
+ });
+
+ it('TCHG-UNDO-PURE-003: a station done since that would go, and a place gone, refuse with every reason', () => {
+ const refused = undoRefusals(basis([['stop-cafe1', [{ day_id: 2, status: 'skipped' }]]], []));
+ expect(refused).toEqual([
+ { why: 'station_done', key: 'stop-cafe1', name: 'cafe1', days: [{ day_id: 2, status: 'skipped' }] },
+ { why: 'place_gone', key: 'stop-museum', name: 'museum', linked_place_id: 7 },
+ ]);
+ expect(undoRefusalText(refused)).toBe(
+ [
+ 'Taking this step back would lose what was done since. Nothing changed.',
+ 'Station stop-cafe1 (cafe1) would be removed, but it was visited or skipped since.',
+ 'Station stop-museum (museum) stands for place 7, which is no longer a place of the trip.',
+ ].join('\n'),
+ );
+ });
+
+ it('TCHG-UNDO-PURE-004: points without key or name are named as such and never matched by a missing key', () => {
+ const keyless: UndoBasis = {
+ now: [point('stop-gate', 0), point(undefined, 1)],
+ before: { ...before, waypoints: [point('stop-gate', 0), point(undefined, 1, { linked_place_id: 9 })] },
+ done: new Map(),
+ linkable: new Set(),
+ };
+ const refused = undoRefusals(keyless);
+ expect(refused).toEqual([{ why: 'place_gone', key: null, name: null, linked_place_id: 9 }]);
+ expect(undoRefusalText([...refused, { why: 'station_done', key: 'stop-x1', name: null, days: [] }])).toContain(
+ 'Station without key (no name) stands for place 9',
+ );
+ const described = describeUndo(keyless, { distance_km: null, walking_minutes: null, route_pending: true });
+ expect(described.now.stations[1]).toEqual({ position: 2, key: null, name: null, done: false });
+ expect(described.restored.stations[1]).toEqual({
+ position: 2,
+ key: null,
+ name: null,
+ change: 'back',
+ now_position: null,
+ });
+ expect(described.removed).toEqual([{ key: null, name: null, position: 2 }]);
+ });
+
+ it('TCHG-UNDO-PURE-005: the tour now is set against the tour restored, stations kept, back and removed', () => {
+ const gateVisited = basis([['stop-gate', [{ day_id: 1, status: 'visited' }]]]);
+ const described = describeUndo(gateVisited, { distance_km: 1.5, walking_minutes: 24, route_pending: false });
+ expect(described.now).toEqual({
+ distance_km: 1.5,
+ walking_minutes: 24,
+ route_pending: false,
+ stations: [
+ { position: 1, key: 'stop-gate', name: 'gate', done: true },
+ { position: 2, key: 'stop-cafe1', name: 'cafe1', done: false },
+ { position: 3, key: 'stop-park', name: 'park', done: false },
+ { position: 4, key: 'stop-pier1', name: 'pier1', done: false },
+ ],
+ });
+ expect(described.restored).toEqual({
+ distance_km: 1.2,
+ walking_minutes: 18,
+ route_pending: false,
+ stations: [
+ { position: 1, key: 'stop-gate', name: 'gate', change: 'kept', now_position: 1 },
+ { position: 2, key: 'stop-museum', name: 'museum', change: 'back', now_position: null },
+ { position: 3, key: 'stop-park', name: 'park', change: 'kept', now_position: 3 },
+ ],
+ });
+ expect(described.removed).toEqual([
+ { key: 'stop-cafe1', name: 'cafe1', position: 2 },
+ { key: 'stop-pier1', name: 'pier1', position: 4 },
+ ]);
+ });
+
+ it('TCHG-UNDO-PURE-006: a tour that had no line before restores as waiting for its way', () => {
+ const pending: UndoBasis = { ...basis(), before: { ...before, route_geometry: null, distance: null } };
+ const described = describeUndo(pending, { distance_km: 1.5, walking_minutes: 24, route_pending: false });
+ expect(described.restored).toMatchObject({ distance_km: null, walking_minutes: 18, route_pending: true });
+ });
+});
diff --git a/shared/src/tours/tour-change.schema.spec.ts b/shared/src/tours/tour-change.schema.spec.ts
index fd86a7fda..f1c2d4943 100644
--- a/shared/src/tours/tour-change.schema.spec.ts
+++ b/shared/src/tours/tour-change.schema.spec.ts
@@ -4,6 +4,7 @@ import {
tourChangeRequestSchema,
tourChangeSaveRequestSchema,
tourChangeSchema,
+ tourChangeUndoRequestSchema,
} from './tour-change.schema';
import { describe, expect, it } from 'vitest';
@@ -69,3 +70,26 @@ describe('a prepared change the traveller confirmed, sent to be saved (MCP-T03)'
}
});
});
+
+describe('a saved step the traveller confirmed to take back (MCP-T04)', () => {
+ const undo = { step_id: 7, expected_revision: 4, confirmed: true };
+
+ it('takes the step, the revision it was shown at and the yes', () => {
+ expect(tourChangeUndoRequestSchema.parse(undo)).toEqual(undo);
+ });
+
+ it('refuses an undo without the yes, without the revision, of no step, or with anything more', () => {
+ const refused = [
+ { ...undo, confirmed: false },
+ { ...undo, confirmed: undefined },
+ { ...undo, expected_revision: undefined },
+ { ...undo, expected_revision: 0 },
+ { ...undo, step_id: 0 },
+ { ...undo, step_id: 1.5 },
+ { ...undo, before_state: { waypoints: [] } },
+ ];
+ for (const body of refused) {
+ expect(tourChangeUndoRequestSchema.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
index 512fd6041..7820a48d1 100644
--- a/shared/src/tours/tour-change.schema.ts
+++ b/shared/src/tours/tour-change.schema.ts
@@ -1,3 +1,4 @@
+import { idSchema } from '../common/primitives.schema';
import { cityWalkStationSchema } from './tour-walk-briefing.schema';
import { stationKeySchema, tourRevisionSchema } from './tours.schema';
@@ -74,3 +75,22 @@ export const tourChangeSaveRequestSchema = tourChangeRequestSchema
})
.strict();
export type TourChangeSaveRequest = z.infer<typeof tourChangeSaveRequestSchema>;
+
+/**
+ * MCP-T04: a saved step the traveller confirmed to take back. It names the
+ * step, the revision of the tour the preview of it was read at and says yes
+ * in so many words. Taking back restores the tour exactly as the step kept it
+ * before, so there is nothing more to send: no changes, no state.
+ */
+export const tourChangeUndoRequestSchema = z
+ .object({
+ step_id: idSchema.describe('The id of the saved step, as list_tour_change_steps gives it'),
+ expected_revision: tourRevisionSchema.describe(
+ 'now.revision of the preview: the revision of the tour the step was shown to be taken back from',
+ ),
+ confirmed: z
+ .literal(true)
+ .describe('true only once the traveller said yes to taking back exactly this step as the preview showed it'),
+ })
+ .strict();
+export type TourChangeUndoRequest = z.infer<typeof tourChangeUndoRequestSchema>;
diff --git a/wiki/MCP-Addon-Tools.md b/wiki/MCP-Addon-Tools.md
index 011ea9624..ed3ff54d4 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, a city walk prepared from a briefing, and a change to a saved city walk prepared for review and saved once the traveller confirmed it. `take_over_tour`, `create_city_walk` and `save_tour_change` 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, a change to a saved city walk prepared for review and saved once the traveller confirmed it, and a saved change taken back the same way. `take_over_tour`, `create_city_walk`, `save_tour_change` and `undo_tour_change` 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 |
|---|---|---|
@@ -249,7 +249,10 @@ The saved tours of a trip, as the Tours list and the tour detail show them, how
| `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, the closing leg of a loop included; 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, shaping points dropped because the leg they steered changed), a warning for a station of importance must removed or replaced, each new station that is not yet a place of the trip as `create_place` takes it to keep it as a place instead (a station linked to a place of the trip is left out), whether the traveller may change the trip's places at all (`can_save`) and the `proposal_id` a save of it names | `trips:read` |
-| `save_tour_change` | Saves a change `prepare_tour_change` prepared, once the traveller said yes to it exactly as shown: the same changes, the `revision` it was prepared on, its `proposal_id` and `confirmed` set to true. Anything else is refused and nothing is saved. The trip permission and the tour are checked again before anything is written: a tour changed since the proposal was prepared is refused as a conflict rather than overwritten (prepare the change again), and a change the rules no longer allow, a station visited or skipped meanwhile or a place of the trip gone, is refused with every reason. The change is saved whole or not at all, through the same write the planner's save uses: the stations in their order, the stations kept keep their keys and their visits, and the way on foot is planned by the same router as the proposal; where it gives no way the walk keeps its stations only (`route_pending`) until someone opens it in the planner. Every save is kept as a step of the tour with the revision it was prepared on and the one it raised the tour to, the changes and the tour as it was before them, so it can be followed and taken back later; nothing of the conversation is kept. A new walk has no revision yet and is made with `create_city_walk`. Needs `place_edit` on the trip | `trips:write` |
+| `save_tour_change` | Saves a change `prepare_tour_change` prepared, once the traveller said yes to it exactly as shown: the same changes, the `revision` it was prepared on, its `proposal_id` and `confirmed` set to true. Anything else is refused and nothing is saved. The trip permission and the tour are checked again before anything is written: a tour changed since the proposal was prepared is refused as a conflict rather than overwritten (prepare the change again), and a change the rules no longer allow, a station visited or skipped meanwhile or a place of the trip gone, is refused with every reason. The change is saved whole or not at all, through the same write the planner's save uses: the stations in their order, the stations kept keep their keys and their visits, and the way on foot is planned by the same router as the proposal; where it gives no way the walk keeps its stations only (`route_pending`) until someone opens it in the planner. Every save is kept as a step of the tour with the revision it was prepared on and the one it raised the tour to, the changes and the tour as it was before them, so it can be followed and taken back with `undo_tour_change`; nothing of the conversation is kept. A new walk has no revision yet and is made with `create_city_walk`. Needs `place_edit` on the trip | `trips:write` |
+| `list_tour_change_steps` | Lists the changes saved to a tour with `save_tour_change`, the latest first: each step with when it was saved, the revision it was prepared on and the one it raised the tour to, and the changes as confirmed. `standing` says whether it can be taken back: `latest` (the tour's latest change), `undone` (taken back already, with when and the revision that raised the tour to), `later_change` (something was saved on top of it since, so taking it back would lose that) or `no_earlier_state` (its record of the tour before cannot be read). Edits saved in the planner are no steps, and a draft in the planner is never seen | `trips:read` |
+| `prepare_tour_undo` | Shows what taking back a saved step would do, without changing anything: the step and its changes, the tour now (distance and walking time as stored, each station with whether it was visited or skipped on a day) and the tour exactly as it was before the step (its stations, each kept or coming back with where it stands now, and the distance and walking time stored then), the stations taking back removes, and the `step_id` and `expected_revision` that `undo_tour_change` names. Only the tour's latest change can be taken back; a step something was saved on top of since is refused as a conflict, so no later edit is lost, and so is one that would remove a station visited or skipped since or bring back a station whose place of the trip is gone. Visits of stations that stay, the days and the tour's name and notes are not touched. Not the planner's undo: discarding a draft in the planner never changes a saved tour. Also says whether the traveller may change the trip's places (`can_undo`) | `trips:read` |
+| `undo_tour_change` | Takes back a saved step once the traveller said yes to the preview of exactly that step: `step_id` and `expected_revision` as `prepare_tour_undo` gave them, and `confirmed` set to true. Everything is checked again before anything is written, and a tour changed since the preview, a step no longer the latest change or taken back already, or a station visited or skipped meanwhile that would go, refuses it and leaves the tour as it is. Restores the tour whole or not at all, exactly as it was before the step: its line, its stations with their keys and the distance and walking time stored then. A step is taken back once, and taking it back raises the tour's revision like any other save. Needs `place_edit` on the trip | `trips:write` |
| `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)_