mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 15:17:30 +00:00
feat(tours): save_tour_change saves a confirmed change to a city walk whole or not at all
An assistant can now save the change prepare_tour_change prepared, once the traveller said yes to it exactly as shown. Until now a proposal could only be looked at; the traveller had to redo it by hand in the planner. - The save names the proposal: the same changes, the revision it was prepared on, the proposal_id the preparation answered and confirmed true. Anything else, a change altered on the way or no yes, is refused and nothing is saved. - Place editing on the trip and the tour are checked again before anything is written. A tour changed since the proposal was prepared is a conflict on the tour's one revision (no second one), telling the assistant to prepare the change anew instead of writing over newer edits. The changes are laid on the saved tour once more inside the write, so a station visited or skipped meanwhile, or a place of the trip gone, refuses the save with every reason. - The change goes through the write the planner's save uses, in one transaction: line, stations, keys, measures and visits together or not at all, and the trip is told only after the commit. Stations kept keep their keys and visits. Where the router gives no way on foot the walk keeps its stations only and waits for the planner, as a created one does. - Every save is kept as a step of the tour (tour_change_steps): the proposal, 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 the step can be followed and taken back later. Nothing of the conversation is kept. - A new walk has no revision to name and stays with create_city_walk; both tool descriptions and the wiki say which is which.
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { TourChangeStepsRepository } from '../repositories/TourChangeSteps.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { Tours } from './Tours.entity';
|
||||
|
||||
export class TourChangeSteps {
|
||||
[EntityRepositoryType]?: TourChangeStepsRepository;
|
||||
id!: number & Opt;
|
||||
place!: Ref<Tours>;
|
||||
place_id!: number;
|
||||
proposal_id!: string;
|
||||
base_revision!: number;
|
||||
revision!: number;
|
||||
changes!: string;
|
||||
before_state!: string;
|
||||
saved_by?: number | null;
|
||||
saved_at!: string & Opt;
|
||||
}
|
||||
|
||||
export const TourChangeStepsSchema = defineEntity({
|
||||
class: TourChangeSteps,
|
||||
repository: () => TourChangeStepsRepository,
|
||||
uniques: [{ properties: ['place', 'revision'] }],
|
||||
checks: [
|
||||
{ name: 'tour_change_steps_base_revision_check', expression: 'base_revision >= 1' },
|
||||
{ name: 'tour_change_steps_revision_check', expression: 'revision = base_revision + 1' },
|
||||
],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
place: () => p.manyToOne(Tours).ref().name('place_id').deleteRule('cascade').hidden(),
|
||||
place_id: p.integer().persist(false),
|
||||
proposal_id: p.text(),
|
||||
base_revision: p.integer(),
|
||||
revision: p.integer(),
|
||||
changes: p.text(),
|
||||
before_state: p.text(),
|
||||
saved_by: p.integer().nullable(),
|
||||
saved_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { ToursRepository } from '../repositories/Tours.repository';
|
||||
import { Places } from './Places.entity';
|
||||
import { TourChangeSteps } from './TourChangeSteps.entity';
|
||||
import { TourObstacleReviews } from './TourObstacleReviews.entity';
|
||||
import { TourSources } from './TourSources.entity';
|
||||
import { TourTypes } from './TourTypes.entity';
|
||||
@@ -45,6 +46,7 @@ export class Tours {
|
||||
ski_discipline?: TToursSkiDiscipline | null;
|
||||
ski_technique?: TToursSkiTechnique | null;
|
||||
tourTypeRef!: Ref<TourTypes>;
|
||||
tour_change_steps_collection = new Collection<TourChangeSteps>(this);
|
||||
tour_obstacle_reviews_collection = new Collection<TourObstacleReviews>(this);
|
||||
tour_sources: Ref<TourSources> | null = null;
|
||||
tour_waypoints_collection = new Collection<TourWaypoints>(this);
|
||||
@@ -175,6 +177,7 @@ export const ToursSchema = defineEntity({
|
||||
ski_discipline: p.enum(() => ToursSkiDiscipline).nullable(),
|
||||
ski_technique: p.enum(() => ToursSkiTechnique).nullable(),
|
||||
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
|
||||
tour_change_steps_collection: () => p.oneToMany(TourChangeSteps).mappedBy('place').hidden(),
|
||||
tour_obstacle_reviews_collection: () => p.oneToMany(TourObstacleReviews).mappedBy('place').hidden(),
|
||||
tour_sources: () => p.oneToOne(TourSources).ref().mappedBy('place').hidden(),
|
||||
tour_waypoints_collection: () => p.oneToMany(TourWaypoints).mappedBy('place').hidden(),
|
||||
|
||||
@@ -107,6 +107,7 @@ import { ShareTokensSchema } from './ShareTokens.entity';
|
||||
import { TagsSchema } from './Tags.entity';
|
||||
import { TodoCategoryAssigneesSchema } from './TodoCategoryAssignees.entity';
|
||||
import { TodoItemsSchema } from './TodoItems.entity';
|
||||
import { TourChangeStepsSchema } from './TourChangeSteps.entity';
|
||||
import { TourObstacleReviewsSchema } from './TourObstacleReviews.entity';
|
||||
import { TourSourcesSchema } from './TourSources.entity';
|
||||
import { TourStationVisitsSchema } from './TourStationVisits.entity';
|
||||
@@ -252,6 +253,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
|
||||
TagsSchema,
|
||||
TodoCategoryAssigneesSchema,
|
||||
TodoItemsSchema,
|
||||
TourChangeStepsSchema,
|
||||
TourObstacleReviewsSchema,
|
||||
TourSourcesSchema,
|
||||
TourStationVisitsSchema,
|
||||
|
||||
@@ -8,16 +8,21 @@ import {
|
||||
paddleLockSchema,
|
||||
paddleRegionBoundarySchema,
|
||||
paddleRegionGraphStatsSchema,
|
||||
tourChangeSchema,
|
||||
tourFixedLegSchema,
|
||||
tourWaypointSchema,
|
||||
trackMarksSchema,
|
||||
type Ferrata,
|
||||
type GeometryPoint,
|
||||
type HikingPreferences,
|
||||
type ObstacleSnapshot,
|
||||
type PaddleGeometry,
|
||||
type PaddleLock,
|
||||
type PaddleRegionBoundary,
|
||||
type PaddleRegionGraphStats,
|
||||
type TourChange,
|
||||
type TourFixedLeg,
|
||||
type TourWaypoint,
|
||||
type TrackMarks,
|
||||
} from '@trek/shared';
|
||||
|
||||
@@ -218,3 +223,47 @@ export const TOUR_OBSTACLE_SNAPSHOT: JsonColumn<ObstacleSnapshot | null> = {
|
||||
schema: obstacleSnapshotSchema.nullable(),
|
||||
fallback: () => null,
|
||||
};
|
||||
|
||||
/**
|
||||
* MCP-T03: the changes a saved step confirmed, as they were prepared. A broken
|
||||
* row reads as none, so a step never claims changes it cannot show.
|
||||
*/
|
||||
export const TOUR_CHANGE_STEP_CHANGES: JsonColumn<TourChange[]> = {
|
||||
column: 'tour_change_steps.changes',
|
||||
schema: z.array(tourChangeSchema),
|
||||
fallback: () => [],
|
||||
};
|
||||
|
||||
/** A point of a saved line: latitude, longitude and the height where it has one. */
|
||||
const savedLinePoint = z.union([z.tuple([z.number(), z.number()]), z.tuple([z.number(), z.number(), z.number()])]);
|
||||
|
||||
/** A tour as it was before a saved step (MCP-T03), as its JSON column holds it. */
|
||||
export interface TourChangeStepBefore {
|
||||
route_geometry: GeometryPoint[] | null;
|
||||
waypoints: TourWaypoint[];
|
||||
distance: number | null;
|
||||
duration: number | null;
|
||||
elevation_gain: number | null;
|
||||
elevation_loss: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP-T03: a tour as it was before a saved step changed it: its line (null
|
||||
* while it had none), its points with their keys, and the measures the save
|
||||
* replaced, null where they were not known. A broken row reads as no earlier
|
||||
* state, so nothing is ever restored from a guess.
|
||||
*/
|
||||
export const TOUR_CHANGE_STEP_BEFORE: JsonColumn<TourChangeStepBefore | null> = {
|
||||
column: 'tour_change_steps.before_state',
|
||||
schema: z
|
||||
.object({
|
||||
route_geometry: z.array(savedLinePoint).nullable(),
|
||||
waypoints: z.array(tourWaypointSchema),
|
||||
distance: z.number().nullable(),
|
||||
duration: z.number().nullable(),
|
||||
elevation_gain: z.number().nullable(),
|
||||
elevation_loss: z.number().nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
fallback: () => null,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface TourChangeStepsTable {
|
||||
id: InsertOptional<number>;
|
||||
place_id: number;
|
||||
proposal_id: string;
|
||||
base_revision: number;
|
||||
revision: number;
|
||||
changes: string;
|
||||
before_state: string;
|
||||
saved_by: InsertOptional<number | null>;
|
||||
saved_at: InsertOptional<string>;
|
||||
}
|
||||
@@ -113,6 +113,7 @@ import type { ShareTokensTable } from './ShareTokens.table';
|
||||
import type { TagsTable } from './Tags.table';
|
||||
import type { TodoCategoryAssigneesTable } from './TodoCategoryAssignees.table';
|
||||
import type { TodoItemsTable } from './TodoItems.table';
|
||||
import type { TourChangeStepsTable } from './TourChangeSteps.table';
|
||||
import type { TourObstacleReviewsTable } from './TourObstacleReviews.table';
|
||||
import type { TourSourcesTable } from './TourSources.table';
|
||||
import type { TourStationVisitsTable } from './TourStationVisits.table';
|
||||
@@ -264,6 +265,7 @@ export interface DB {
|
||||
tags: TagsTable;
|
||||
todo_category_assignees: TodoCategoryAssigneesTable;
|
||||
todo_items: TodoItemsTable;
|
||||
tour_change_steps: TourChangeStepsTable;
|
||||
tour_obstacle_reviews: TourObstacleReviewsTable;
|
||||
tour_sources: TourSourcesTable;
|
||||
tour_station_visits: TourStationVisitsTable;
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* MCP-T03: a change to a saved tour the traveller confirmed through an
|
||||
* assistant is kept as one step of the tour, so it can be followed and taken
|
||||
* back later (MCP-T04). A step names the proposal it saved (`proposal_id`),
|
||||
* the revision the tour was at when it was prepared (`base_revision`) and the
|
||||
* one the save raised it to (`revision`, always the next), the changes as
|
||||
* confirmed (JSON) and the tour as it was before them (`before_state`, JSON:
|
||||
* its line, its points and the measures the save replaced). Nothing of the
|
||||
* conversation is kept, only the plan. `saved_by` names who confirmed it,
|
||||
* kept as a plain id: a step outlives its author, who then reads as unknown.
|
||||
* One step per revision of a tour, and the steps go with their tour.
|
||||
*/
|
||||
export class Migration20200101045700_a_tour_records_the_changes_saved_from_a_proposal extends Migration {
|
||||
override name = 'Migration20200101045700_a_tour_records_the_changes_saved_from_a_proposal';
|
||||
|
||||
override up(): void {
|
||||
this.addSql(`
|
||||
CREATE TABLE IF NOT EXISTS tour_change_steps (
|
||||
id INTEGER PRIMARY KEY,
|
||||
place_id INTEGER NOT NULL REFERENCES tours(place_id) ON DELETE CASCADE,
|
||||
proposal_id TEXT NOT NULL,
|
||||
base_revision INTEGER NOT NULL CHECK (base_revision >= 1),
|
||||
revision INTEGER NOT NULL CHECK (revision = base_revision + 1),
|
||||
changes TEXT NOT NULL,
|
||||
before_state TEXT NOT NULL,
|
||||
saved_by INTEGER,
|
||||
saved_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (place_id, revision)
|
||||
)
|
||||
`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { TourChangeSteps } from '../entities/TourChangeSteps.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type StepsDB = Pick<DB, 'tour_change_steps'>;
|
||||
|
||||
/** What a save of a confirmed change records; `changes` and `before_state` are their JSON text. */
|
||||
export interface TourChangeStepWrite {
|
||||
place_id: number;
|
||||
proposal_id: string;
|
||||
base_revision: number;
|
||||
revision: number;
|
||||
changes: string;
|
||||
before_state: string;
|
||||
saved_by: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `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,
|
||||
* each with the tour as it was before, so a step can be followed and taken
|
||||
* back (MCP-T04). A step goes with its tour.
|
||||
*/
|
||||
export class TourChangeStepsRepository extends TrekRepository<TourChangeSteps> {
|
||||
private db() {
|
||||
return this.kysely<StepsDB>();
|
||||
}
|
||||
|
||||
/** Records one saved step and answers its id; the caller holds the transaction of the save. */
|
||||
async record(step: TourChangeStepWrite): Promise<number> {
|
||||
const inserted = await this.db()
|
||||
.insertInto('tour_change_steps')
|
||||
.values(step)
|
||||
.returning('id')
|
||||
.executeTakeFirstOrThrow();
|
||||
return inserted.id;
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ export class CityWalkMcp {
|
||||
@Tool({
|
||||
name: 'create_city_walk',
|
||||
description:
|
||||
'Create a city walk in a trip from stations the traveller confirmed (for instance stations_for_create of propose_city_walk), the way the planner saves a new walk: a new tour of type walk with its stations in their order, each with its name, stay_minutes (0 for a point passed through, null when not known), importance (optional, must, or null for normal), protected (a station any later proposal has to keep where it is), opening_hours as OpenStreetMap writes them and the place of the trip it stands for (linked_place_id; a place that is not of this trip leaves the station unlinked, a tour is refused). The way between the stations is planned on foot by the router the proposal uses, and the walk is saved with it, its distance and its walking time (foot_way planned true). Where the router gives no way (foot_way planned false, with why and position as in the estimate of the proposal), the walk is saved with its stations only (route_pending true, distance and walking time null), and TREK plans the way on foot when someone opens it in the planner and saves it; no straight line is stored as a route. Put it on a day with assign_place_to_day and give it a start time with update_assignment_time. Needs place editing permission on the trip. Create it only after the traveller said yes.',
|
||||
'Create a city walk in a trip from stations the traveller confirmed (for instance stations_for_create of propose_city_walk), the way the planner saves a new walk: a new tour of type walk with its stations in their order, each with its name, stay_minutes (0 for a point passed through, null when not known), importance (optional, must, or null for normal), protected (a station any later proposal has to keep where it is), opening_hours as OpenStreetMap writes them and the place of the trip it stands for (linked_place_id; a place that is not of this trip leaves the station unlinked, a tour is refused). The way between the stations is planned on foot by the router the proposal uses, and the walk is saved with it, its distance and its walking time (foot_way planned true). Where the router gives no way (foot_way planned false, with why and position as in the estimate of the proposal), the walk is saved with its stations only (route_pending true, distance and walking time null), and TREK plans the way on foot when someone opens it in the planner and saves it; no straight line is stored as a route. Put it on a day with assign_place_to_day and give it a start time with update_assignment_time. Needs place editing permission on the trip. Create it only after the traveller said yes. A change to a walk already saved is prepared with prepare_tour_change and saved with save_tour_change instead.',
|
||||
inputSchema: {
|
||||
tripId: idSchema.describe('The trip to create the walk in'),
|
||||
name: create.name,
|
||||
|
||||
@@ -160,7 +160,7 @@ function warningsOf(gone: readonly DraftPoint[]) {
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
export function asWaypoint(draft: DraftPoint): TourWaypoint {
|
||||
const { ref: _ref, origin: _origin, change: _change, after: _after, replaces: _replaces, ...point } = draft;
|
||||
return point;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 { proposalIdOf, staleProposal } from './tour-change-proposal';
|
||||
import { ToursService } from './tours.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
@@ -39,7 +40,8 @@ function doneByKey(visits: ReadonlyArray<StationDone & { station_key: string }>)
|
||||
* 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.
|
||||
* refused once the tour has moved on, and carries the id a save of it has to
|
||||
* name (MCP-T03).
|
||||
*/
|
||||
@Injectable()
|
||||
export class TourChangePreviewService {
|
||||
@@ -50,8 +52,19 @@ export class TourChangePreviewService {
|
||||
@InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,
|
||||
) {}
|
||||
|
||||
async prepare(tripId: number, placeId: number, userId: number, { changes }: TourChangeRequest) {
|
||||
/**
|
||||
* The changes laid onto the tour as it is saved now, with the visits of all
|
||||
* its days and the places the new stations name, or the refusal naming
|
||||
* every change the rules of the tour do not allow. A save lays them again
|
||||
* on the tour it is about to write, so it is held to the same rules, and
|
||||
* names the revision they were prepared on: a tour that moved past it is a
|
||||
* conflict before any rule is asked.
|
||||
*/
|
||||
async lay(tripId: number, placeId: number, changes: readonly TourChange[], preparedOn?: number) {
|
||||
const { tour, waypoints } = await this.tours.getTour(String(tripId), String(placeId));
|
||||
if (preparedOn !== undefined && tour.revision !== preparedOn) {
|
||||
throw staleProposal(preparedOn, tour.revision ?? null);
|
||||
}
|
||||
const [visits, linkable] = await Promise.all([
|
||||
this.visitsRepo.listForPlace(tripId, placeId),
|
||||
this.waypointsRepo.linkablePlaceIds(tripId, linkedIds(changes)),
|
||||
@@ -72,13 +85,20 @@ export class TourChangePreviewService {
|
||||
details: { refused: outcome.refused },
|
||||
});
|
||||
}
|
||||
return { tour, waypoints, outcome };
|
||||
}
|
||||
|
||||
async prepare(tripId: number, placeId: number, userId: number, { changes }: TourChangeRequest) {
|
||||
const { tour, waypoints, outcome } = await this.lay(tripId, placeId, changes);
|
||||
const [wayBefore, wayAfter] = await Promise.all([
|
||||
this.footWays.plan(userId, tripId, waypoints),
|
||||
this.footWays.plan(userId, tripId, outcome.points),
|
||||
]);
|
||||
const revision = tour.revision ?? null;
|
||||
return {
|
||||
prepared_only: true,
|
||||
base: { place_id: tour.place_id, name: tour.name, tour_type: tour.tour_type, revision: tour.revision ?? null },
|
||||
proposal_id: proposalIdOf({ tripId, placeId, revision, changes }),
|
||||
base: { place_id: tour.place_id, name: tour.name, tour_type: tour.tour_type, revision },
|
||||
changes,
|
||||
...describeChange({
|
||||
saved: waypoints,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { DomainError } from '../common/domain-error';
|
||||
import { tourRevisionConflict } from './tour-revision';
|
||||
import type { TourChange } from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
/** What a proposal is: these changes, to this tour of this trip, at this revision. */
|
||||
export interface ProposalBasis {
|
||||
tripId: number;
|
||||
placeId: number;
|
||||
/** Null only for a tour read before revisions were counted, which no save can name. */
|
||||
revision: number | null;
|
||||
changes: readonly TourChange[];
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP-T03: the id of a prepared proposal, the same for the same tour,
|
||||
* revision and changes and different for any other. A preparation answers
|
||||
* it, and a save has to name it, so what is saved is the very proposal the
|
||||
* traveller was shown and nothing an assistant changed on the way. It binds a
|
||||
* save to its review, it is no secret: the revision guards against a tour
|
||||
* that moved on.
|
||||
*/
|
||||
export function proposalIdOf({ tripId, placeId, revision, changes }: ProposalBasis): string {
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify([tripId, placeId, revision, changes]))
|
||||
.digest('hex')
|
||||
.slice(0, 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* The conflict of a save whose proposal was prepared on a revision the tour
|
||||
* has moved past: nothing is saved, and the assistant is told to read the
|
||||
* tour again and prepare the change anew rather than retry the old one.
|
||||
*/
|
||||
export function staleProposal(prepared: number, current: number | null): DomainError {
|
||||
return tourRevisionConflict(
|
||||
current,
|
||||
`The tour was changed after this proposal was prepared (revision ${prepared} then, ${current ?? 'unknown'} now). Nothing was saved: read it again with get_tour_plan and prepare the change anew.`,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { TourChangeSteps } from '../../db/entities/TourChangeSteps.entity';
|
||||
import { TOUR_CHANGE_STEP_BEFORE, TOUR_CHANGE_STEP_CHANGES } from '../../db/json-columns';
|
||||
import type { TourChangeStepsRepository } from '../../db/repositories/TourChangeSteps.repository';
|
||||
import { encodeJson } from '../../utils/json-column';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import type { FootWay } from './city-walk-briefing.helpers';
|
||||
import { CityWalkFootWayService } from './city-walk-foot-way.service';
|
||||
import type { DraftPoint } from './tour-change-apply';
|
||||
import { asWaypoint } from './tour-change-effects';
|
||||
import { TourChangePreviewService } from './tour-change-preview.service';
|
||||
import { proposalIdOf } from './tour-change-proposal';
|
||||
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';
|
||||
|
||||
/** 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';
|
||||
|
||||
/** What a save writes: the tour as read, the points after the changes and the way on foot through them. */
|
||||
interface ChangedTour {
|
||||
tour: TourListItem;
|
||||
points: readonly DraftPoint[];
|
||||
way: FootWay;
|
||||
preparedOn: number;
|
||||
}
|
||||
|
||||
/** The step a save recorded: its id and the revision it raised the tour to. */
|
||||
interface SavedStep {
|
||||
id: number;
|
||||
revision: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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),
|
||||
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. */
|
||||
function savedAnswer(detail: TourDetailResponse, step: SavedStep, { way, preparedOn }: ChangedTour) {
|
||||
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,
|
||||
},
|
||||
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,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP-T03: a prepared change the traveller confirmed, saved whole or not at
|
||||
* all through the write the planner's save uses. The save names the revision
|
||||
* the proposal was prepared on (P2C-03, the one revision a tour has) and the
|
||||
* proposal's id, so only the very proposal shown is saved, and never over a
|
||||
* tour that has moved on. The changes are laid again on the tour as it is, by
|
||||
* the same rules: first to plan the way on foot, then once more inside the
|
||||
* write, so a station visited or a place gone in between refuses the save
|
||||
* instead of being written over, and a failure leaves the tour as it was.
|
||||
*
|
||||
* 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
|
||||
* kept. A new city walk has no revision to name: it is created through
|
||||
* create_city_walk (CW-11), never saved as a change.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TourChangeSaveService {
|
||||
constructor(
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly tours: ToursService,
|
||||
private readonly preview: TourChangePreviewService,
|
||||
private readonly footWays: CityWalkFootWayService,
|
||||
@InjectRepository(TourChangeSteps) private readonly stepsRepo: TourChangeStepsRepository,
|
||||
) {}
|
||||
|
||||
async save(tripId: number, placeId: number, userId: number, request: TourChangeSaveRequest) {
|
||||
const { changes, expected_revision: preparedOn, proposal_id: proposalId } = request;
|
||||
if (proposalId !== proposalIdOf({ tripId, placeId, revision: preparedOn, changes })) {
|
||||
throw new DomainError(
|
||||
422,
|
||||
'These changes are not the proposal that was prepared. Nothing was saved: save the changes and the revision exactly as prepare_tour_change answered them, or prepare the change again.',
|
||||
{ code: TOUR_CHANGE_NOT_PREPARED },
|
||||
);
|
||||
}
|
||||
const laid = await this.preview.lay(tripId, placeId, changes, preparedOn);
|
||||
const way = await this.footWays.plan(userId, tripId, laid.outcome.points);
|
||||
const changed: ChangedTour = { tour: laid.tour, points: laid.outcome.points, way, preparedOn };
|
||||
const write = await this.tours.routeWrite(writeOf(changed));
|
||||
const saved = await this.uow.transactional(async () => {
|
||||
// Laid once more on the tour as it is now: a tour moved on, a station done or a place gone refuses here.
|
||||
const now = await this.preview.lay(tripId, placeId, changes, preparedOn);
|
||||
const before = await this.beforeState(tripId, placeId, now);
|
||||
const { revision, visitsDropped } = await this.tours.replaceRoute(tripId, placeId, write);
|
||||
const id = await this.stepsRepo.record({
|
||||
place_id: placeId,
|
||||
proposal_id: proposalId,
|
||||
base_revision: preparedOn,
|
||||
revision,
|
||||
changes: encodeJson(TOUR_CHANGE_STEP_CHANGES, changes),
|
||||
before_state: before,
|
||||
saved_by: userId,
|
||||
});
|
||||
return { step: { id, revision }, visitsDropped };
|
||||
});
|
||||
const detail = await this.tours.announceRouteUpdate(String(tripId), placeId, saved.visitsDropped);
|
||||
return savedAnswer(detail, saved.step, changed);
|
||||
}
|
||||
|
||||
/** The tour as it is before the change, as the step keeps it: its line, its points and its measures. */
|
||||
private async beforeState(
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
{ tour, waypoints }: { tour: TourListItem; waypoints: TourWaypoint[] },
|
||||
): Promise<string> {
|
||||
const line = await this.tours.savedLine(tripId, placeId);
|
||||
return encodeJson(TOUR_CHANGE_STEP_BEFORE, {
|
||||
route_geometry: line.length > 0 ? line : null,
|
||||
waypoints,
|
||||
distance: tour.distance,
|
||||
duration: tour.duration,
|
||||
elevation_gain: tour.elevation_gain,
|
||||
elevation_loss: tour.elevation_loss,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,30 @@
|
||||
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 { 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 { TourChangePreviewService } from './tour-change-preview.service';
|
||||
import { TourChangeSaveService } from './tour-change-save.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { idSchema, tourChangeRequestSchema, type TourChangeRequest } from '@trek/shared';
|
||||
import {
|
||||
idSchema,
|
||||
tourChangeRequestSchema,
|
||||
tourChangeSaveRequestSchema,
|
||||
type TourChangeRequest,
|
||||
type TourChangeSaveRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
const save = tourChangeSaveRequestSchema.shape;
|
||||
|
||||
/**
|
||||
* MCP-T02: a change to a saved tour prepared for the traveller to review,
|
||||
@@ -18,21 +35,26 @@ import { idSchema, tourChangeRequestSchema, type TourChangeRequest } from '@trek
|
||||
* 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.
|
||||
*
|
||||
* MCP-T03: the proposal the traveller confirmed is saved with 'place_edit'
|
||||
* on the trip, as the planner's save over REST asks, whole or not at all and
|
||||
* never over a tour that moved on since it was prepared.
|
||||
*/
|
||||
@McpController()
|
||||
export class TourChangeMcp {
|
||||
constructor(
|
||||
private readonly preview: TourChangePreviewService,
|
||||
private readonly saver: TourChangeSaveService,
|
||||
private readonly access: TripAccessService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of the tool here.
|
||||
// Read by the addon gate of every 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 (the closing leg of a loop included); such a change is refused, and so is the whole proposal, with every reason in the error. The answer: prepared_only (always true), base (the tour and the revision it was prepared on: a save has to name it, and a tour changed since is refused rather than overwritten, so prepare again), stations_after (each with its key, null for a new one, change kept, added, replaced or moved, by_change, was_position and what it replaces), removed, effects (walking: the whole way on foot before and after planned by TREK's router and the change in metres and minutes, the distance and walking time stored with the walk apart; stays: known minutes and unknown stays before and after; legs: each leg after, new ones marked), data_gaps (what could not be worked out and why: no way from the router, stays not known, no arrival times, shaping points dropped because the leg they steered changed), warnings (a must station removed or replaced), for_later (each new station not yet a place of the trip as create_place takes it, to keep it as a place instead; a station with linked_place_id already is one and is left out) and waypoints_after. Show every change and its effects to the traveller and save nothing without their yes. can_save says whether they may change the trip's places.",
|
||||
"Prepare a change to a saved tour for the traveller to review, without saving anything: no tour, station, visit or day plan changes, and turning it down keeps the plan as it is. Read the tour with get_tour_plan first. A city walk (tour_type walk) takes changes so far; every other type, and a walk that is a recorded track without stations of its own, is refused with the reason. changes apply in order, each naming saved stations by their key: add (a new station after after_key; a spontaneous stop is an add after the station the traveller is at), remove, replace (a new station in the place of key) and move (key to after after_key). Stops put after the same station keep the order given. A station protected, or visited or skipped on any day of the walk, is never removed, replaced or moved, nothing is put before the last station already done, and a leg drawn by hand stays as drawn (the closing leg of a loop included); such a change is refused, and so is the whole proposal, with every reason in the error. The answer: prepared_only (always true), base (the tour and the revision it was prepared on: a save has to name it, and a tour changed since is refused rather than overwritten, so prepare again), stations_after (each with its key, null for a new one, change kept, added, replaced or moved, by_change, was_position and what it replaces), removed, effects (walking: the whole way on foot before and after planned by TREK's router and the change in metres and minutes, the distance and walking time stored with the walk apart; stays: known minutes and unknown stays before and after; legs: each leg after, new ones marked), data_gaps (what could not be worked out and why: no way from the router, stays not known, no arrival times, shaping points dropped because the leg they steered changed), warnings (a must station removed or replaced), for_later (each new station not yet a place of the trip as create_place takes it, to keep it as a place instead; a station with linked_place_id already is one and is left out) and waypoints_after. proposal_id names this very proposal for save_tour_change. Show every change and its effects to the traveller and save nothing without their yes. can_save says whether they may change the trip's places.",
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
|
||||
@@ -56,4 +78,34 @@ export class TourChangeMcp {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@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.",
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
|
||||
changes: save.changes,
|
||||
expected_revision: save.expected_revision,
|
||||
proposal_id: save.proposal_id,
|
||||
confirmed: save.confirmed,
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async saveTourChange(
|
||||
{ tripId, placeId, ...request }: { tripId: number; placeId: number } & TourChangeSaveRequest,
|
||||
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.saver.save(tripId, placeId, ctx.userId, request));
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NotFoundException) return errorResult('Tour not found.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,19 @@ export async function advanceTourRevision(
|
||||
if (next !== null) return next;
|
||||
const current = await toursRepo.revisionOf(placeId);
|
||||
if (current === undefined) throw new NotFoundException('Tour not found');
|
||||
throw new DomainError(409, 'This tour was changed in the meantime', {
|
||||
throw tourRevisionConflict(current);
|
||||
}
|
||||
|
||||
/**
|
||||
* The 409 of a write based on a revision the tour has moved past, naming the
|
||||
* revision it is at now. A caller with its own words for it (a confirmed
|
||||
* change saved over MCP, MCP-T03) passes them; the code and details stay.
|
||||
*/
|
||||
export function tourRevisionConflict(
|
||||
current: number | null,
|
||||
message = 'This tour was changed in the meantime',
|
||||
): DomainError {
|
||||
return new DomainError(409, message, {
|
||||
code: TOUR_REVISION_CONFLICT,
|
||||
details: { code: TOUR_REVISION_CONFLICT, revision: current },
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { TourChangeSteps } from '../../db/entities/TourChangeSteps.entity';
|
||||
import { TourObstacleReviews } from '../../db/entities/TourObstacleReviews.entity';
|
||||
import { TourSources } from '../../db/entities/TourSources.entity';
|
||||
import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
|
||||
@@ -20,6 +21,7 @@ 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 { TourChangeSaveService } from './tour-change-save.service';
|
||||
import { TourChangeMcp } from './tour-change.mcp';
|
||||
import { TourGpxExportService } from './tour-gpx-export.service';
|
||||
import { TourHorseRoutesController } from './tour-horse-routes.controller';
|
||||
@@ -63,7 +65,9 @@ import { Module } from '@nestjs/common';
|
||||
* tours' own repositories, is planned on foot by RoadtripModule's router and
|
||||
* is created through ToursService (CW-11). A change to a saved city walk an
|
||||
* assistant prepares for review is laid onto its saved points and planned on
|
||||
* foot by the same router, and saves nothing (MCP-T02).
|
||||
* foot by the same router, and saves nothing (MCP-T02); once the traveller
|
||||
* confirmed it, it is saved through the tour's own write, which records the
|
||||
* step for a later undo (MCP-T03).
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -92,6 +96,7 @@ import { Module } from '@nestjs/common';
|
||||
TourSources,
|
||||
TourObstacleReviews,
|
||||
TourStationVisits,
|
||||
TourChangeSteps,
|
||||
Places,
|
||||
]),
|
||||
],
|
||||
@@ -126,6 +131,7 @@ import { Module } from '@nestjs/common';
|
||||
CityWalkFootWayService,
|
||||
CityWalkBriefingService,
|
||||
TourChangePreviewService,
|
||||
TourChangeSaveService,
|
||||
ToursMcp,
|
||||
TourLibraryMcp,
|
||||
TourWalkImportMcp,
|
||||
|
||||
@@ -95,6 +95,13 @@ export type TourCreateCommand = Omit<TourCreateRequest, 'route_geometry'> & {
|
||||
route_geometry: GeometryPoint[] | null;
|
||||
};
|
||||
|
||||
/** A route write checked and ready for its transaction: the write, where the tour starts and its fields. */
|
||||
export interface TourRouteWrite {
|
||||
input: TourCreateCommand;
|
||||
start: GeometryPoint;
|
||||
fields: TourUpdate;
|
||||
}
|
||||
|
||||
/** The way on foot the server's router planned for a city walk (CW-11): its line, and how long it walks in seconds. */
|
||||
interface CityWalkFootRoute {
|
||||
line: Array<[number, number]>;
|
||||
@@ -705,44 +712,75 @@ export class ToursService {
|
||||
const tid = toRowId(tripId);
|
||||
const pid = toRowId(placeId);
|
||||
if (tid === null || pid === null) throw new NotFoundException('Tour not found');
|
||||
const write = await this.routeWrite(input);
|
||||
const { visitsDropped } = await this.uow.transactional(() => this.replaceRoute(tid, pid, write));
|
||||
return await this.announceRouteUpdate(tripId, pid, visitsDropped, socketId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A route write checked before its transaction opens: its type switched on,
|
||||
* its texts and times valid, where it starts and the tour fields it writes.
|
||||
* A city walk saved from a confirmed change (MCP-T03) may come without a
|
||||
* line, as a created one may (CW-11): it is then at its first point, and the
|
||||
* planner plans the way when it is opened.
|
||||
*/
|
||||
async routeWrite(input: TourCreateCommand): Promise<TourRouteWrite> {
|
||||
await this.assertTourTypeEnabled(input.tour_type);
|
||||
this.validateInformationalMetadata(input);
|
||||
this.validatePlannedTimes(input);
|
||||
const start = input.route_geometry[0];
|
||||
const fields = this.routeFields(input);
|
||||
const start = input.route_geometry ? input.route_geometry[0] : firstPointOf(input.waypoints);
|
||||
if (!start) throw badRequest('A tour needs at least two points');
|
||||
return { input, start, fields: this.routeFields(input) };
|
||||
}
|
||||
|
||||
const visitsDropped = await this.uow.transactional(async () => {
|
||||
// The trip predicate is the cross-trip boundary. It runs inside the write
|
||||
// so an id from another accessible trip cannot be moved into the current
|
||||
// one, and a place deleted meanwhile answers 404 instead of failing a
|
||||
// waypoint insert on its foreign key.
|
||||
if (!(await this.toursRepo.findInTrip(tid, pid))) throw new NotFoundException('Tour not found');
|
||||
// P2C-03: refused here, before anything is written, while the draft's tour has moved on.
|
||||
await advanceTourRevision(this.toursRepo, pid, input.expected_revision);
|
||||
// An import planned over for the first time keeps the track it was recorded with.
|
||||
await this.toursRepo.keepRecordedTrack(pid);
|
||||
const placeUpdated = await this.placesRepo.updateTourRoute(pid, tid, {
|
||||
name: input.name,
|
||||
lat: start[0],
|
||||
lng: start[1],
|
||||
route_geometry: JSON.stringify(input.route_geometry),
|
||||
...(input.description !== undefined ? { description: input.description } : {}),
|
||||
...(input.website !== undefined ? { website: input.website } : {}),
|
||||
});
|
||||
if (!placeUpdated) throw new NotFoundException('Tour not found');
|
||||
if (!(await this.toursRepo.updateInTrip(tid, pid, fields))) throw new NotFoundException('Tour not found');
|
||||
await this.waypointsRepo.deleteForPlace(pid);
|
||||
const waypoints = keyedWaypoints(await this.linkedWaypoints(tid, input.waypoints));
|
||||
await this.waypointsRepo.insertForPlace(pid, waypoints);
|
||||
// CW-03: a station that is gone takes its visits with it; a tour that is no city walk keeps none.
|
||||
const stations = input.tour_type === 'walk' ? walkStationsOf(waypoints).map((point) => point.key) : [];
|
||||
return await this.visitsRepo.dropStationsNotIn(pid, stations);
|
||||
/**
|
||||
* A saved tour's route, points and visits written inside the caller's transaction, so what else a
|
||||
* caller records of the change (MCP-T03) commits or rolls back with it. Answers the revision it
|
||||
* raised the tour to and the day assignments whose visits went with a station that is gone.
|
||||
*/
|
||||
async replaceRoute(
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
{ input, start, fields }: TourRouteWrite,
|
||||
): Promise<{ revision: number; visitsDropped: number[] }> {
|
||||
// The trip predicate is the cross-trip boundary. It runs inside the write
|
||||
// so an id from another accessible trip cannot be moved into the current
|
||||
// one, and a place deleted meanwhile answers 404 instead of failing a
|
||||
// waypoint insert on its foreign key.
|
||||
if (!(await this.toursRepo.findInTrip(tripId, placeId))) throw new NotFoundException('Tour not found');
|
||||
// P2C-03: refused here, before anything is written, while the draft's tour has moved on.
|
||||
const revision = await advanceTourRevision(this.toursRepo, placeId, input.expected_revision);
|
||||
// An import planned over for the first time keeps the track it was recorded with.
|
||||
await this.toursRepo.keepRecordedTrack(placeId);
|
||||
const placeUpdated = await this.placesRepo.updateTourRoute(placeId, tripId, {
|
||||
name: input.name,
|
||||
lat: start[0],
|
||||
lng: start[1],
|
||||
route_geometry: input.route_geometry ? JSON.stringify(input.route_geometry) : null,
|
||||
...(input.description !== undefined ? { description: input.description } : {}),
|
||||
...(input.website !== undefined ? { website: input.website } : {}),
|
||||
});
|
||||
if (!placeUpdated) throw new NotFoundException('Tour not found');
|
||||
if (!(await this.toursRepo.updateInTrip(tripId, placeId, fields))) throw new NotFoundException('Tour not found');
|
||||
await this.waypointsRepo.deleteForPlace(placeId);
|
||||
const waypoints = keyedWaypoints(await this.linkedWaypoints(tripId, input.waypoints));
|
||||
await this.waypointsRepo.insertForPlace(placeId, waypoints);
|
||||
// CW-03: a station that is gone takes its visits with it; a tour that is no city walk keeps none.
|
||||
const stations = input.tour_type === 'walk' ? walkStationsOf(waypoints).map((point) => point.key) : [];
|
||||
return { revision, visitsDropped: await this.visitsRepo.dropStationsNotIn(placeId, stations) };
|
||||
}
|
||||
|
||||
const result = await this.getTour(tripId, placeId);
|
||||
const place = await this.placesRepo.findWithTagsAndRatings(pid);
|
||||
/** After a route write committed: the tour read back, and the trip told of it and of the visits it took along. */
|
||||
async announceRouteUpdate(
|
||||
tripId: string,
|
||||
placeId: number,
|
||||
visitsDropped: readonly number[],
|
||||
socketId?: string,
|
||||
): Promise<TourDetailResponse> {
|
||||
const result = await this.getTour(tripId, String(placeId));
|
||||
const place = await this.placesRepo.findWithTagsAndRatings(placeId);
|
||||
if (!place) throw new Error('Updated tour could not be loaded');
|
||||
this.broadcastToursChanged(tripId, [pid], socketId);
|
||||
this.broadcastToursChanged(tripId, [placeId], socketId);
|
||||
try {
|
||||
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
|
||||
} catch {
|
||||
|
||||
Reference in New Issue
Block a user