mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
feat(tours): prepare_tour_change prepares a change to a saved city walk for review
An assistant can now prepare a change to a saved city walk and show the traveller what it would do before anything is saved. Preparing writes nothing: no tour, station, visit or day plan changes, and turning the proposal down keeps the plan as it was. - The changes apply in order and name the saved stations by their keys: add a station after another (a spontaneous stop is an add after the station the traveller is at), remove, replace and move. Stops put after the same station keep the order they were given in. - What the travellers did stays as it is: a station visited or skipped on any day of the walk is never removed, replaced or moved, nothing goes before the last station already done, a protected station keeps its place and a leg drawn by hand stays as drawn. A proposal breaking a rule is refused whole, naming every change and why. Other tour types, and a walk that is a recorded track, are refused too: so far only a city walk takes prepared changes, since the others plan their way with routing of their own the server cannot run. - The answer sets the walk after the change against the saved one: each station with what changed it and where it stood, what was removed, the way on foot before and after planned by the same router (the stored distance and walking time given apart, never mixed in), the stays as far as known, every leg with the new ones marked, the gaps that could not be worked out, a warning for a must station removed or replaced, and each new station as create_place takes it, to keep it for later as a place of the trip instead. - The proposal names the revision it was prepared on, so a save of it is refused once the tour has moved on, and says whether the traveller may change the trip's places at all. The way on foot of a new walk, its creation and a prepared change now come from one CityWalkFootWayService instead of a copy in the briefing service.
This commit is contained in:
@@ -71,6 +71,24 @@ export class TourStationVisitsRepository extends TrekRepository<TourStationVisit
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP-T02: every visit of one walk of this trip, on every day it is on, with
|
||||
* the day; a proposed change keeps each of these stations as it is. Ordered
|
||||
* by day and key; none of another trip.
|
||||
*/
|
||||
async listForPlace(trip_id: number, place_id: number): Promise<Array<{ day_id: number } & TourStationVisitRow>> {
|
||||
return await this.db()
|
||||
.selectFrom('tour_station_visits as v')
|
||||
.innerJoin('day_assignments as da', 'da.id', 'v.assignment_id')
|
||||
.innerJoin('days as d', 'd.id', 'da.day_id')
|
||||
.select(['da.day_id', 'v.assignment_id', 'v.station_key', 'v.status'])
|
||||
.where('da.place_id', '=', place_id)
|
||||
.where('d.trip_id', '=', trip_id)
|
||||
.orderBy('da.day_id', 'asc')
|
||||
.orderBy('v.station_key', 'asc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The visits of one day assignment. */
|
||||
async listForAssignment(assignment_id: number): Promise<TourStationVisitRow[]> {
|
||||
return await this.db()
|
||||
|
||||
@@ -4,21 +4,18 @@ import { Tours } from '../../db/entities/Tours.entity';
|
||||
import type { PlaceRow, PlacesRepository } from '../../db/repositories/Places.repository';
|
||||
import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
|
||||
import type { ToursRepository } from '../../db/repositories/Tours.repository';
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { notFound } from '../common/domain-error';
|
||||
import { RoadtripRouterService } from '../roadtrip/roadtrip-router.service';
|
||||
import {
|
||||
briefingCategories,
|
||||
describeWalk,
|
||||
footWayOf,
|
||||
frameOf,
|
||||
planWalk,
|
||||
themeCandidates,
|
||||
type FootWay,
|
||||
type LeftOut,
|
||||
type LeftOutReason,
|
||||
type WalkCandidate,
|
||||
} from './city-walk-briefing.helpers';
|
||||
import { CityWalkFootWayService } from './city-walk-foot-way.service';
|
||||
import { TourPoiSearchService } from './tour-poi-search.service';
|
||||
import { ToursService } from './tours.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
@@ -34,13 +31,6 @@ import {
|
||||
/** How far from the start, the wishes and the appointments the themes are searched when the briefing does not say. */
|
||||
const DEFAULT_CORRIDOR_M = 1000;
|
||||
|
||||
/**
|
||||
* The day the router is asked for. A way on foot does not depend on the day:
|
||||
* the router only keys its cache by one and hands it to a routing plugin,
|
||||
* which a walk on foot never asks.
|
||||
*/
|
||||
const ANY_DAY = 0;
|
||||
|
||||
/** The places of the trip a briefing names, and which of them a station may stand for (no tour). */
|
||||
interface NamedPlaces {
|
||||
rows: Map<number, PlaceRow>;
|
||||
@@ -105,7 +95,7 @@ function tripPlaceOf(
|
||||
export class CityWalkBriefingService {
|
||||
constructor(
|
||||
private readonly poiSearch: TourPoiSearchService,
|
||||
private readonly router: RoadtripRouterService,
|
||||
private readonly footWays: CityWalkFootWayService,
|
||||
private readonly tours: ToursService,
|
||||
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
|
||||
@InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,
|
||||
@@ -146,7 +136,7 @@ export class CityWalkBriefingService {
|
||||
themeLimit: theme.limit,
|
||||
});
|
||||
return {
|
||||
...describeWalk(plan.route, frame, await this.footWay(userId, tripId, plan.route)),
|
||||
...describeWalk(plan.route, frame, await this.footWays.plan(userId, tripId, plan.route)),
|
||||
left_out: [...leftOut, ...plan.leftOut],
|
||||
searched: theme.searched,
|
||||
};
|
||||
@@ -159,7 +149,7 @@ export class CityWalkBriefingService {
|
||||
* stations only and says why; no straight line is stored as a route.
|
||||
*/
|
||||
async create(tripId: number, userId: number, body: CityWalkCreateRequest) {
|
||||
const way = await this.footWay(userId, tripId, body.stations);
|
||||
const way = await this.footWays.plan(userId, tripId, body.stations);
|
||||
const created = await this.tours.createCityWalk(String(tripId), body, way.kind === 'routed' ? way : null);
|
||||
return {
|
||||
...created,
|
||||
@@ -167,22 +157,6 @@ export class CityWalkBriefingService {
|
||||
};
|
||||
}
|
||||
|
||||
/** The way on foot through the stations in their order, or why there is none. */
|
||||
private async footWay(
|
||||
userId: number,
|
||||
tripId: number,
|
||||
stations: ReadonlyArray<{ lat: number; lng: number }>,
|
||||
): Promise<FootWay> {
|
||||
if (stations.length < 2) return { kind: 'unrouted', why: 'nothing_to_route', position: null };
|
||||
const points = stations.map(({ lat, lng }) => ({ lat, lng }));
|
||||
try {
|
||||
return footWayOf(await this.router.route(userId, tripId, ANY_DAY, points, 'walking', []));
|
||||
} catch (err: unknown) {
|
||||
logWarn(`[CityWalk] no way on foot for trip ${tripId}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
return { kind: 'unrouted', why: 'router_unavailable', position: null };
|
||||
}
|
||||
}
|
||||
|
||||
/** The date of the day the walk is for, null without one; a day of another trip is not found. */
|
||||
private async dateOf(tripId: number, dayId: number | undefined): Promise<string | null> {
|
||||
if (dayId === undefined) return null;
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { RoadtripRouterService } from '../roadtrip/roadtrip-router.service';
|
||||
import { footWayOf, type FootWay } from './city-walk-briefing.helpers';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* The day the router is asked for. A way on foot does not depend on the day:
|
||||
* the router only keys its cache by one and hands it to a routing plugin,
|
||||
* which a walk on foot never asks.
|
||||
*/
|
||||
const ANY_DAY = 0;
|
||||
|
||||
/**
|
||||
* CW-11, MCP-T02: the way on foot through the points of a city walk, planned
|
||||
* by the router the road trip uses (the traveller's own routing server where
|
||||
* they set one). The proposal of a new walk, its creation and a prepared
|
||||
* change to a saved walk all ask here, so their distances and times come from
|
||||
* one source. Where the router gives no way, the answer says why instead of
|
||||
* guessing one.
|
||||
*/
|
||||
@Injectable()
|
||||
export class CityWalkFootWayService {
|
||||
constructor(private readonly router: RoadtripRouterService) {}
|
||||
|
||||
/** The way on foot through the points in their order, or why there is none. */
|
||||
async plan(userId: number, tripId: number, points: ReadonlyArray<{ lat: number; lng: number }>): Promise<FootWay> {
|
||||
if (points.length < 2) return { kind: 'unrouted', why: 'nothing_to_route', position: null };
|
||||
const asked = points.map(({ lat, lng }) => ({ lat, lng }));
|
||||
try {
|
||||
return footWayOf(await this.router.route(userId, tripId, ANY_DAY, asked, 'walking', []));
|
||||
} catch (err: unknown) {
|
||||
logWarn(`[CityWalk] no way on foot for trip ${tripId}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
return { kind: 'unrouted', why: 'router_unavailable', position: null };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* MCP-T02: a prepared change laid onto the saved points of a tour, by the
|
||||
* rules of its type, without writing anything. The changes apply one after
|
||||
* the other, each naming the stations it touches by their keys, and the
|
||||
* answer is either the points as they would be or every change refused and
|
||||
* why: a proposal is shown whole or not at all, never half applied.
|
||||
*
|
||||
* A city walk is the first type that takes changes. What its travellers have
|
||||
* already done stays as it is: a station visited or skipped on any of its days
|
||||
* is neither removed, replaced nor moved, nothing new goes before it, and a
|
||||
* protected station (CW-10) keeps its place. A leg drawn by hand is kept as
|
||||
* drawn, so neither of its ends changes and nothing is put into it.
|
||||
*/
|
||||
import {
|
||||
CITY_WALK_MAX_STATIONS,
|
||||
isClosedLoop,
|
||||
type CityWalkStation,
|
||||
type TourChange,
|
||||
type TourChangeOp,
|
||||
type TourWaypoint,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The types of tour a proposal can change, each with every change. A hike, a
|
||||
* bike or a paddle tour plans its way in the planner with routing of its own
|
||||
* that a proposal cannot run, so it takes none yet rather than a way guessed.
|
||||
*/
|
||||
const CHANGEABLE_TYPES: ReadonlySet<string> = new Set(['walk']);
|
||||
|
||||
/** How a point of the changed plan came to be: kept from the saved tour, or brought in by a change. */
|
||||
type DraftOrigin = 'saved' | 'added' | 'replacing' | 'moved';
|
||||
|
||||
/** A point of the plan as the changes leave it. */
|
||||
export type DraftPoint = TourWaypoint & {
|
||||
/**
|
||||
* Its key where it is a saved point that has one; `saved:<sequence>` for one
|
||||
* saved before keys existed and `new:<change>` for a station a change brings
|
||||
* in, neither of which a key can spell.
|
||||
*/
|
||||
ref: string;
|
||||
origin: DraftOrigin;
|
||||
/** The change (from 1) that brought it in or moved it; null for a point no change touched. */
|
||||
change: number | null;
|
||||
/** The saved station it was put after, so stops put after the same one keep the order they were given in. */
|
||||
after: string | null;
|
||||
/** The saved station a replacing one stands in for. */
|
||||
replaces: string | null;
|
||||
};
|
||||
|
||||
/** A day the travellers marked a station on, and how. */
|
||||
export interface StationDone {
|
||||
day_id: number;
|
||||
status: 'visited' | 'skipped';
|
||||
}
|
||||
|
||||
type RefusalReason =
|
||||
| 'type_not_supported'
|
||||
| 'recorded_track'
|
||||
| 'unknown_station'
|
||||
| 'already_changed'
|
||||
| 'anchor_is_station'
|
||||
| 'protected'
|
||||
| 'done'
|
||||
| 'before_done'
|
||||
| 'fixed_leg'
|
||||
| 'place_not_linkable'
|
||||
| 'too_few_stations'
|
||||
| 'too_many_stations';
|
||||
|
||||
/** Why a change, or the whole proposal (change null), cannot be prepared. */
|
||||
interface ChangeRefusal {
|
||||
change: number | null;
|
||||
op: TourChangeOp | null;
|
||||
key: string | null;
|
||||
reason: RefusalReason;
|
||||
/** For a station already done: the days it was visited or skipped on. */
|
||||
days?: StationDone[];
|
||||
}
|
||||
|
||||
/** What the changes are laid onto: the saved tour as read, and what its travellers already did. */
|
||||
export interface ChangeBasis {
|
||||
tourType: string;
|
||||
/** The tour stores no control points of its own: its points are the ends of a recorded track. */
|
||||
recorded: boolean;
|
||||
points: readonly TourWaypoint[];
|
||||
/** The stations visited or skipped on any day of the walk, by key. */
|
||||
done: ReadonlyMap<string, readonly StationDone[]>;
|
||||
/** The places of this trip a new station may stand for: no tour, none of another trip. */
|
||||
linkable: ReadonlySet<number>;
|
||||
}
|
||||
|
||||
type ChangeOutcome =
|
||||
| {
|
||||
kind: 'ready';
|
||||
points: DraftPoint[];
|
||||
/** The saved stations a remove took out, and those a replace stands in for. */
|
||||
removed: DraftPoint[];
|
||||
replaced: DraftPoint[];
|
||||
}
|
||||
| { kind: 'refused'; refused: ChangeRefusal[] };
|
||||
|
||||
/** A saved point as the changes start from it. */
|
||||
export function savedPoint(point: TourWaypoint): DraftPoint {
|
||||
const ref = point.key ?? `saved:${point.sequence}`;
|
||||
return { ...point, ref, origin: 'saved', change: null, after: null, replaces: null };
|
||||
}
|
||||
|
||||
function newStation(station: CityWalkStation, change: number): DraftPoint {
|
||||
return {
|
||||
...station,
|
||||
role: 'via',
|
||||
sequence: 0,
|
||||
ref: `new:${change}`,
|
||||
origin: 'added',
|
||||
change,
|
||||
after: null,
|
||||
replaces: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The work in progress: the points without the way back of a loop, and what the changes did so far. */
|
||||
class ChangeRun {
|
||||
readonly body: DraftPoint[];
|
||||
readonly removed: DraftPoint[] = [];
|
||||
readonly replaced: DraftPoint[] = [];
|
||||
readonly refused: ChangeRefusal[] = [];
|
||||
/** The saved stations a change removed or replaced, which no later change can name. */
|
||||
private readonly gone = new Set<string>();
|
||||
|
||||
constructor(
|
||||
private readonly basis: ChangeBasis,
|
||||
private readonly loop: boolean,
|
||||
) {
|
||||
const points = basis.points.map(savedPoint);
|
||||
this.body = loop ? points.slice(0, -1) : points;
|
||||
}
|
||||
|
||||
apply(change: TourChange, index: number): void {
|
||||
const number = index + 1;
|
||||
const refuse = (reason: RefusalReason, key: string | null, days?: StationDone[]) =>
|
||||
this.refused.push({ change: number, op: change.op, key, reason, ...(days ? { days } : {}) });
|
||||
const before = this.refused.length;
|
||||
if ('station' in change) this.checkLink(change.station, (reason) => refuse(reason, null));
|
||||
if (change.op === 'add') {
|
||||
const at = this.slotAfter(change.after_key, null, refuse);
|
||||
if (at !== null && this.refused.length === before) {
|
||||
this.body.splice(at, 0, { ...newStation(change.station, number), after: change.after_key });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const station = this.station(change.key, refuse);
|
||||
if (station === null) return;
|
||||
if (change.op === 'move') {
|
||||
const at = this.slotAfter(change.after_key, change.key, refuse);
|
||||
if (at === null || this.refused.length > before) return;
|
||||
const moved = this.body.splice(station, 1)[0] as DraftPoint;
|
||||
this.body.splice(at > station ? at - 1 : at, 0, {
|
||||
...moved,
|
||||
origin: 'moved',
|
||||
change: number,
|
||||
after: change.after_key,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (this.refused.length > before) return;
|
||||
this.gone.add(change.key);
|
||||
const replacing = change.op === 'replace' ? [this.replacing(change.station, number, change.key)] : [];
|
||||
const gone = this.body.splice(station, 1, ...replacing)[0] as DraftPoint;
|
||||
(change.op === 'remove' ? this.removed : this.replaced).push({ ...gone, change: number });
|
||||
}
|
||||
|
||||
private replacing(station: CityWalkStation, change: number, key: string): DraftPoint {
|
||||
return { ...newStation(station, change), origin: 'replacing', replaces: key };
|
||||
}
|
||||
|
||||
/** The index of the saved station a change touches, once its rules allow it; null when they do not. */
|
||||
private station(key: string, refuse: (reason: RefusalReason, key: string, days?: StationDone[]) => void) {
|
||||
const index = this.indexOfStation(key, refuse);
|
||||
if (index === null) return null;
|
||||
const point = this.body[index] as DraftPoint;
|
||||
const done = this.basis.done.get(key);
|
||||
if (point.protected === true) refuse('protected', key);
|
||||
if (done && done.length > 0) refuse('done', key, [...done]);
|
||||
if (point.fixed_leg || this.body[index - 1]?.fixed_leg) refuse('fixed_leg', key);
|
||||
return index;
|
||||
}
|
||||
|
||||
/** Where a saved station stands now, or why it cannot be named. */
|
||||
private indexOfStation(key: string, refuse: (reason: RefusalReason, key: string) => void): number | null {
|
||||
const index = this.body.findIndex((point) => point.ref === key && !point.shaping);
|
||||
if (index >= 0) return index;
|
||||
refuse(this.gone.has(key) ? 'already_changed' : 'unknown_station', key);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where something put after a saved station goes: right after it and after
|
||||
* the stops already put there, never into a hand-drawn leg and never before
|
||||
* a station the travellers already did.
|
||||
*/
|
||||
private slotAfter(
|
||||
anchor: string,
|
||||
moving: string | null,
|
||||
refuse: (reason: RefusalReason, key: string) => void,
|
||||
): number | null {
|
||||
if (anchor === moving) {
|
||||
refuse('anchor_is_station', anchor);
|
||||
return null;
|
||||
}
|
||||
const index = this.indexOfStation(anchor, refuse);
|
||||
if (index === null) return null;
|
||||
let at = index + 1;
|
||||
while (this.body[at]?.after === anchor && this.body[at]?.ref !== moving) at += 1;
|
||||
if (this.body[index]?.fixed_leg) refuse('fixed_leg', anchor);
|
||||
if (at <= this.lastDoneIndex()) refuse('before_done', anchor);
|
||||
return at;
|
||||
}
|
||||
|
||||
private lastDoneIndex(): number {
|
||||
let last = -1;
|
||||
this.body.forEach((point, index) => {
|
||||
if ((this.basis.done.get(point.ref)?.length ?? 0) > 0) last = index;
|
||||
});
|
||||
return last;
|
||||
}
|
||||
|
||||
private checkLink(station: { linked_place_id?: number | null }, refuse: (reason: RefusalReason) => void): void {
|
||||
const id = station.linked_place_id;
|
||||
if (id != null && !this.basis.linkable.has(id)) refuse('place_not_linkable');
|
||||
}
|
||||
|
||||
/** The changed points in order with their roles and sequence, the way back of a loop at its start again. */
|
||||
finished(): DraftPoint[] {
|
||||
const first = this.body[0];
|
||||
const last = this.basis.points[this.basis.points.length - 1];
|
||||
const back = this.loop && first && last ? [{ ...savedPoint(last), lat: first.lat, lng: first.lng }] : [];
|
||||
const points = [...this.body, ...back];
|
||||
const end = points.length - 1;
|
||||
return points.map((point, sequence): DraftPoint => ({
|
||||
...point,
|
||||
sequence,
|
||||
role: sequence === 0 ? 'start' : sequence === end ? 'end' : 'via',
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function stationCount(points: readonly DraftPoint[], loop: boolean): number {
|
||||
return (loop ? points.slice(0, -1) : points).filter((point) => !point.shaping).length;
|
||||
}
|
||||
|
||||
/** The changes laid onto the saved points, or every reason they cannot be. */
|
||||
export function applyChanges(basis: ChangeBasis, changes: readonly TourChange[]): ChangeOutcome {
|
||||
const whole = (reason: RefusalReason): ChangeOutcome => ({
|
||||
kind: 'refused',
|
||||
refused: [{ change: null, op: null, key: null, reason }],
|
||||
});
|
||||
if (!CHANGEABLE_TYPES.has(basis.tourType)) return whole('type_not_supported');
|
||||
if (basis.recorded) return whole('recorded_track');
|
||||
const loop = isClosedLoop(basis.points);
|
||||
const run = new ChangeRun(basis, loop);
|
||||
changes.forEach((change, index) => run.apply(change, index));
|
||||
if (run.refused.length > 0) return { kind: 'refused', refused: run.refused };
|
||||
const points = run.finished();
|
||||
const count = stationCount(points, loop);
|
||||
if (count < 2) return whole('too_few_stations');
|
||||
if (count > CITY_WALK_MAX_STATIONS && count > stationCount(basis.points.map(savedPoint), loop)) {
|
||||
return whole('too_many_stations');
|
||||
}
|
||||
return { kind: 'ready', points, removed: run.removed, replaced: run.replaced };
|
||||
}
|
||||
|
||||
const REFUSAL_TEXT: Record<RefusalReason, string> = {
|
||||
type_not_supported:
|
||||
'only a city walk takes prepared changes so far; this type plans its way with routing of its own in the planner',
|
||||
recorded_track:
|
||||
'this walk is a recorded track without stations of its own; open it in the planner to plan stations onto it',
|
||||
unknown_station: 'no station of the saved walk has this key (a shaping point or the way back of a loop is none)',
|
||||
already_changed: 'an earlier change of this proposal already removed or replaced this station',
|
||||
anchor_is_station: 'a station cannot be moved after itself',
|
||||
protected: 'this station is protected: it keeps its place, and only the travellers can change it in the app',
|
||||
done: 'the travellers already visited or skipped this station on a day of the walk; what was done stays as it is',
|
||||
before_done:
|
||||
'this would put a station before one the travellers already visited or skipped; add it after the last of those',
|
||||
fixed_leg: 'a leg drawn by hand in the planner starts or ends here and stays as drawn; change it in the planner',
|
||||
place_not_linkable: 'the new station names a place that is not a place of this trip, or is a tour',
|
||||
too_few_stations: 'a city walk keeps at least two stations',
|
||||
too_many_stations: `a city walk holds at most ${CITY_WALK_MAX_STATIONS} stations`,
|
||||
};
|
||||
|
||||
/** One refusal as a sentence the assistant can pass on. */
|
||||
function refusalLine(refusal: ChangeRefusal): string {
|
||||
const about =
|
||||
refusal.change === null ? 'The proposal' : `Change ${refusal.change} (${refusal.op} ${refusal.key ?? 'station'})`;
|
||||
const days = refusal.days ? `, day ids ${refusal.days.map((day) => `${day.day_id} ${day.status}`).join(', ')}` : '';
|
||||
return `${about}: ${REFUSAL_TEXT[refusal.reason]}${days}.`;
|
||||
}
|
||||
|
||||
/** Every refusal of a proposal, one per line, under a line saying nothing was prepared or saved. */
|
||||
export function refusalText(refused: readonly ChangeRefusal[]): string {
|
||||
return ['Nothing was prepared and nothing changed.', ...refused.map(refusalLine)].join('\n');
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/**
|
||||
* MCP-T02: what a prepared change does to a city walk, set against the saved
|
||||
* walk. The way on foot before and after is planned by the same router, so
|
||||
* the two are compared on one source; the distance and walking time stored
|
||||
* with the walk come from the planner and are given apart, never mixed in.
|
||||
* Stays are counted where they are known and an unknown one stays unknown.
|
||||
* Whatever cannot be worked out is named in `data_gaps` instead of guessed.
|
||||
*/
|
||||
import type { FootWay } from './city-walk-briefing.helpers';
|
||||
import { savedPoint, type DraftPoint } from './tour-change-apply';
|
||||
import { walkStationsOf, type TourWaypoint } from '@trek/shared';
|
||||
|
||||
/** Everything the description of a prepared change reads. */
|
||||
interface ChangeEffectsInput {
|
||||
saved: readonly TourWaypoint[];
|
||||
after: readonly DraftPoint[];
|
||||
removed: readonly DraftPoint[];
|
||||
replaced: readonly DraftPoint[];
|
||||
wayBefore: FootWay;
|
||||
wayAfter: FootWay;
|
||||
/** As stored with the walk when it was last saved: kilometres and minutes, null when not known. */
|
||||
stored: { distance_km: number | null; walking_minutes: number | null };
|
||||
}
|
||||
|
||||
type StationChange = 'kept' | 'added' | 'replaced' | 'moved';
|
||||
|
||||
const CHANGE_OF: Record<DraftPoint['origin'], StationChange> = {
|
||||
saved: 'kept',
|
||||
added: 'added',
|
||||
replacing: 'replaced',
|
||||
moved: 'moved',
|
||||
};
|
||||
|
||||
/** The key a point is saved under; null for a station a change brings in, which gets one when saved. */
|
||||
function keyOf(point: DraftPoint): string | null {
|
||||
return point.key ?? null;
|
||||
}
|
||||
|
||||
/** The names of the saved points by ref, for the station a replacing one stands in for. */
|
||||
type Names = ReadonlyMap<string, string | null>;
|
||||
|
||||
/** One station of the changed walk, with where it stood before and what changed it. */
|
||||
function stationAfter(point: DraftPoint, index: number, wasAt: ReadonlyMap<string, number>, names: Names) {
|
||||
return {
|
||||
position: index + 1,
|
||||
key: keyOf(point),
|
||||
name: point.name ?? null,
|
||||
change: CHANGE_OF[point.origin],
|
||||
by_change: point.change,
|
||||
was_position: wasAt.get(point.ref) ?? null,
|
||||
replaces: point.replaces ? { key: point.replaces, name: names.get(point.replaces) ?? null } : null,
|
||||
stay_minutes: point.stay_minutes ?? null,
|
||||
importance: point.importance ?? null,
|
||||
protected: point.protected === true,
|
||||
opening_hours: point.opening_hours ?? null,
|
||||
linked_place_id: point.linked_place_id ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The way on foot through all points, its whole length and walking time, or why there is none. */
|
||||
function wayTotal(way: FootWay) {
|
||||
if (way.kind === 'unrouted') return { planned: false as const, why: way.why, position: way.position };
|
||||
return {
|
||||
planned: true as const,
|
||||
metres: way.legs.reduce((sum, leg) => sum + leg.metres, 0),
|
||||
minutes: Math.round(way.seconds / 60),
|
||||
};
|
||||
}
|
||||
|
||||
function walkingOf(input: ChangeEffectsInput) {
|
||||
const before = wayTotal(input.wayBefore);
|
||||
const after = wayTotal(input.wayAfter);
|
||||
return {
|
||||
planned_by: 'router_on_foot' as const,
|
||||
before,
|
||||
after,
|
||||
change:
|
||||
before.planned && after.planned
|
||||
? { metres: after.metres - before.metres, minutes: after.minutes - before.minutes }
|
||||
: null,
|
||||
stored: input.stored,
|
||||
};
|
||||
}
|
||||
|
||||
/** The stays of the stations as far as entered, and how many are not known. */
|
||||
function staysOf(stations: readonly DraftPoint[]) {
|
||||
return {
|
||||
minutes_known: stations.reduce((sum, station) => sum + (station.stay_minutes ?? 0), 0),
|
||||
unknown: stations.filter((station) => station.stay_minutes == null).length,
|
||||
};
|
||||
}
|
||||
|
||||
function staysChange(before: readonly DraftPoint[], after: readonly DraftPoint[]) {
|
||||
const was = staysOf(before);
|
||||
const now = staysOf(after);
|
||||
return {
|
||||
before: was,
|
||||
after: now,
|
||||
change_minutes_known: now.minutes_known - was.minutes_known,
|
||||
complete: was.unknown === 0 && now.unknown === 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Every leg of the changed walk from one point to the next, the way on foot gives it, and whether it is new. */
|
||||
function legsOf(saved: readonly DraftPoint[], after: readonly DraftPoint[], way: FootWay) {
|
||||
const kept = new Set(saved.slice(1).map((to, index) => `${saved[index]?.ref}>${to.ref}`));
|
||||
return after.slice(1).map((to, index) => {
|
||||
const from = after[index] as DraftPoint;
|
||||
const leg = way.kind === 'routed' ? way.legs[index] : undefined;
|
||||
return {
|
||||
from: { key: keyOf(from), name: from.name ?? null },
|
||||
to: { key: keyOf(to), name: to.name ?? null },
|
||||
metres: leg?.metres ?? null,
|
||||
minutes: leg?.minutes ?? null,
|
||||
new: !kept.has(`${from.ref}>${to.ref}`),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** What could not be worked out, each with why, so nothing missing reads as nothing. */
|
||||
function gapsOf(input: ChangeEffectsInput, stationsAfter: readonly DraftPoint[]) {
|
||||
const unrouted = (side: 'before' | 'after', way: FootWay) =>
|
||||
way.kind === 'unrouted' ? [{ about: 'walking' as const, side, why: way.why, position: way.position }] : [];
|
||||
const unknownStays = stationsAfter.filter((station) => station.stay_minutes == null);
|
||||
return [
|
||||
...unrouted('before', input.wayBefore),
|
||||
...unrouted('after', input.wayAfter),
|
||||
...(input.saved.some((point) => point.fixed_leg)
|
||||
? [{ about: 'walking' as const, why: 'hand_drawn_leg_routed' as const }]
|
||||
: []),
|
||||
...(unknownStays.length > 0
|
||||
? [
|
||||
{
|
||||
about: 'stays' as const,
|
||||
why: 'stay_not_known' as const,
|
||||
stations: unknownStays.map((station) => ({ key: keyOf(station), name: station.name ?? null })),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{ about: 'arrival_times' as const, why: 'no_start_time' as const },
|
||||
];
|
||||
}
|
||||
|
||||
/** A station of importance must that the change removes or replaces, for the traveller to confirm on purpose. */
|
||||
function warningsOf(gone: readonly DraftPoint[]) {
|
||||
return gone
|
||||
.filter((point) => point.importance === 'must')
|
||||
.map((point) => ({ change: point.change, key: point.key ?? null, name: point.name ?? null, why: 'must_station' }));
|
||||
}
|
||||
|
||||
/** The points as a save takes them: a kept point with its key, a new one without, the server gives it one. */
|
||||
function asWaypoint(draft: DraftPoint): TourWaypoint {
|
||||
const { ref: _ref, origin: _origin, change: _change, after: _after, replaces: _replaces, ...point } = draft;
|
||||
return point;
|
||||
}
|
||||
|
||||
/** A new station as create_place takes it, to keep it as a place of the trip instead of putting it in the walk. */
|
||||
function forLater(point: DraftPoint) {
|
||||
return { change: point.change, name: point.name ?? null, lat: point.lat, lng: point.lng };
|
||||
}
|
||||
|
||||
/** The changed walk set against the saved one: its stations, what went, the effects and the gaps. */
|
||||
export function describeChange(input: ChangeEffectsInput) {
|
||||
const saved = input.saved.map(savedPoint);
|
||||
const stationsBefore = walkStationsOf(saved);
|
||||
const stationsAfter = walkStationsOf(input.after);
|
||||
const wasAt = new Map(stationsBefore.map((station, index) => [station.ref, index + 1]));
|
||||
const names: Names = new Map(saved.map((point) => [point.ref, point.name ?? null]));
|
||||
return {
|
||||
stations_after: stationsAfter.map((station, index) => stationAfter(station, index, wasAt, names)),
|
||||
removed: input.removed.map((point) => ({
|
||||
key: point.key ?? null,
|
||||
name: point.name ?? null,
|
||||
was_position: wasAt.get(point.ref) ?? null,
|
||||
by_change: point.change,
|
||||
})),
|
||||
effects: {
|
||||
walking: walkingOf(input),
|
||||
stays: staysChange(stationsBefore, stationsAfter),
|
||||
legs: legsOf(saved, input.after, input.wayAfter),
|
||||
},
|
||||
data_gaps: gapsOf(input, stationsAfter),
|
||||
warnings: warningsOf([...input.removed, ...input.replaced]),
|
||||
for_later: input.after.filter((point) => point.origin === 'added' || point.origin === 'replacing').map(forLater),
|
||||
waypoints_after: input.after.map(asWaypoint),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
|
||||
import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
|
||||
import type { TourStationVisitsRepository } from '../../db/repositories/TourStationVisits.repository';
|
||||
import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { CityWalkFootWayService } from './city-walk-foot-way.service';
|
||||
import { applyChanges, refusalText, type StationDone } from './tour-change-apply';
|
||||
import { describeChange } from './tour-change-effects';
|
||||
import { ToursService } from './tours.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { TourChange, TourChangeRequest } from '@trek/shared';
|
||||
|
||||
/** The refusal of a proposal the rules of its tour do not allow; its text names every change and why. */
|
||||
export const TOUR_CHANGE_REFUSED = 'tour_change_refused';
|
||||
|
||||
/** The places of the trip the new stations of a proposal name. */
|
||||
function linkedIds(changes: readonly TourChange[]): number[] {
|
||||
return changes.flatMap((change) => {
|
||||
const id = 'station' in change ? change.station.linked_place_id : null;
|
||||
return id ? [id] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The stations visited or skipped on any day of the walk, by key, each with the days. */
|
||||
function doneByKey(visits: ReadonlyArray<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 }]);
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP-T02: a change to a saved tour prepared for the traveller to review.
|
||||
* It reads the saved tour, the visits of all its days and the places the new
|
||||
* stations name, lays the changes onto the saved points by the rules of the
|
||||
* tour's type and works out the effects with the way on foot the router
|
||||
* plans before and after. It writes nothing: no tour, station, visit or day
|
||||
* plan changes, and turning the proposal down leaves the plan as it is. The
|
||||
* proposal names the revision it was prepared on, so a save of it can be
|
||||
* refused once the tour has moved on.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TourChangePreviewService {
|
||||
constructor(
|
||||
private readonly tours: ToursService,
|
||||
private readonly footWays: CityWalkFootWayService,
|
||||
@InjectRepository(TourStationVisits) private readonly visitsRepo: TourStationVisitsRepository,
|
||||
@InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,
|
||||
) {}
|
||||
|
||||
async prepare(tripId: number, placeId: number, userId: number, { changes }: TourChangeRequest) {
|
||||
const { tour, waypoints } = await this.tours.getTour(String(tripId), String(placeId));
|
||||
const [visits, linkable] = await Promise.all([
|
||||
this.visitsRepo.listForPlace(tripId, placeId),
|
||||
this.waypointsRepo.linkablePlaceIds(tripId, linkedIds(changes)),
|
||||
]);
|
||||
const outcome = applyChanges(
|
||||
{
|
||||
tourType: tour.tour_type,
|
||||
recorded: tour.has_waypoints !== true,
|
||||
points: waypoints,
|
||||
done: doneByKey(visits),
|
||||
linkable,
|
||||
},
|
||||
changes,
|
||||
);
|
||||
if (outcome.kind === 'refused') {
|
||||
throw new DomainError(422, refusalText(outcome.refused), {
|
||||
code: TOUR_CHANGE_REFUSED,
|
||||
details: { refused: outcome.refused },
|
||||
});
|
||||
}
|
||||
const [wayBefore, wayAfter] = await Promise.all([
|
||||
this.footWays.plan(userId, tripId, waypoints),
|
||||
this.footWays.plan(userId, tripId, outcome.points),
|
||||
]);
|
||||
return {
|
||||
prepared_only: true,
|
||||
base: { place_id: tour.place_id, name: tour.name, tour_type: tour.tour_type, revision: tour.revision ?? null },
|
||||
changes,
|
||||
...describeChange({
|
||||
saved: waypoints,
|
||||
after: outcome.points,
|
||||
removed: outcome.removed,
|
||||
replaced: outcome.replaced,
|
||||
wayBefore,
|
||||
wayAfter,
|
||||
stored: { distance_km: tour.distance, walking_minutes: tour.duration },
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { noAccess } from '../../mcp/tools/_shared';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { TourChangePreviewService } from './tour-change-preview.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { idSchema, tourChangeRequestSchema, type TourChangeRequest } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* MCP-T02: a change to a saved tour prepared for the traveller to review,
|
||||
* read only like propose_city_walk: nothing is saved while it is prepared,
|
||||
* and turning it down leaves the plan as it was. A change the rules of the
|
||||
* tour refuse is the service's DomainError, which the registry answers as an
|
||||
* error result naming every refused change and why. can_save tells the
|
||||
* assistant whether this traveller may save changes to the trip's places at
|
||||
* all, so a proposal is never offered as something they could apply when
|
||||
* they cannot.
|
||||
*/
|
||||
@McpController()
|
||||
export class TourChangeMcp {
|
||||
constructor(
|
||||
private readonly preview: TourChangePreviewService,
|
||||
private readonly access: TripAccessService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of the tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'prepare_tour_change',
|
||||
description:
|
||||
"Prepare a change to a saved tour for the traveller to review, without saving anything: no tour, station, visit or day plan changes, and turning it down keeps the plan as it is. Read the tour with get_tour_plan first. A city walk (tour_type walk) takes changes so far; every other type, and a walk that is a recorded track without stations of its own, is refused with the reason. changes apply in order, each naming saved stations by their key: add (a new station after after_key; a spontaneous stop is an add after the station the traveller is at), remove, replace (a new station in the place of key) and move (key to after after_key). Stops put after the same station keep the order given. A station protected, or visited or skipped on any day of the walk, is never removed, replaced or moved, nothing is put before the last station already done, and a leg drawn by hand stays as drawn; such a change is refused, and so is the whole proposal, with every reason in the error. The answer: prepared_only (always true), base (the tour and the revision it was prepared on: a save has to name it, and a tour changed since is refused rather than overwritten, so prepare again), stations_after (each with its key, null for a new one, change kept, added, replaced or moved, by_change, was_position and what it replaces), removed, effects (walking: the whole way on foot before and after planned by TREK's router and the change in metres and minutes, the distance and walking time stored with the walk apart; stays: known minutes and unknown stays before and after; legs: each leg after, new ones marked), data_gaps (what could not be worked out and why: no way from the router, stays not known, no arrival times), warnings (a must station removed or replaced), for_later (each new station as create_place takes it, to keep it as a place of the trip instead) and waypoints_after. Show every change and its effects to the traveller and save nothing without their yes. can_save says whether they may change the trip's places.",
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
|
||||
changes: tourChangeRequestSchema.shape.changes,
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
})
|
||||
async prepareTourChange(
|
||||
{ tripId, placeId, changes }: { tripId: number; placeId: number } & TourChangeRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
try {
|
||||
const proposal = await this.preview.prepare(tripId, placeId, ctx.userId, { changes });
|
||||
const canSave = await this.guards.hasTripPermission('place_edit', tripId, ctx.userId);
|
||||
return ok({ ...proposal, can_save: canSave });
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NotFoundException) return errorResult('Tour not found.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,10 @@ import { RoadtripModule } from '../roadtrip/roadtrip.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { WandererModule } from '../wanderer/wanderer.module';
|
||||
import { CityWalkBriefingService } from './city-walk-briefing.service';
|
||||
import { CityWalkFootWayService } from './city-walk-foot-way.service';
|
||||
import { CityWalkMcp } from './city-walk.mcp';
|
||||
import { TourChangePreviewService } from './tour-change-preview.service';
|
||||
import { TourChangeMcp } from './tour-change.mcp';
|
||||
import { TourGpxExportService } from './tour-gpx-export.service';
|
||||
import { TourHorseRoutesController } from './tour-horse-routes.controller';
|
||||
import { TourHorseRoutesService } from './tour-horse-routes.service';
|
||||
@@ -58,7 +61,9 @@ import { Module } from '@nestjs/common';
|
||||
* link followed by the narrow resolver there (CW-06). A city walk an assistant
|
||||
* prepares from a briefing reads the day and places of the trip through the
|
||||
* tours' own repositories, is planned on foot by RoadtripModule's router and
|
||||
* is created through ToursService (CW-11).
|
||||
* is created through ToursService (CW-11). A change to a saved city walk an
|
||||
* assistant prepares for review is laid onto its saved points and planned on
|
||||
* foot by the same router, and saves nothing (MCP-T02).
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -118,11 +123,14 @@ import { Module } from '@nestjs/common';
|
||||
TourTrailGradeService,
|
||||
TourVisitsService,
|
||||
TourWalkImportService,
|
||||
CityWalkFootWayService,
|
||||
CityWalkBriefingService,
|
||||
TourChangePreviewService,
|
||||
ToursMcp,
|
||||
TourLibraryMcp,
|
||||
TourWalkImportMcp,
|
||||
CityWalkMcp,
|
||||
TourChangeMcp,
|
||||
],
|
||||
})
|
||||
export class ToursModule {}
|
||||
|
||||
Reference in New Issue
Block a user