feat(tours): link the track a tour was actually done with, and show its own values (ACT-01)

A planned tour can now be given the track it was actually done with. In the
tour's detail, "Add actual track" opens a dialog that asks for the day the
tour was done on (or none) and a recording of the trip: an import nobody
planned over, or a new one through the existing GPX import, its preview
preset to the tour's type. What the choice measures is shown before anything
is written, and only "Link" writes. The linked track keeps its own name and
source; the detail shows its distance, heights, profile and, only where the
file carried time stamps, the time it took, marked as actual values next to
the untouched plan. A track can be changed or unlinked again.

Server: a tour_activities table points a tour's execution (a day assignment,
or none) at a recording of the same trip, and the tours GPX import keeps the
first and last time of a track whose every point carries one. The values are
read from the recording's own line on every read, so a changed recording
updates them while the plan's line, measures and revision stay as they were.
Every check runs inside the write: the recording must be an import of this
trip not planned over, documenting no other tour; the day must be one of this
tour; a refusal names its reason and changes nothing. PUT and DELETE
/api/trips/:tripId/tours/:placeId/activities answer the detail, which now
carries the actual tracks; the list names them per tour and per recording.
MCP: assign_tour_track and unassign_tour_track over the same service and
checks, get_tour_plan reads the values without the line.

A recording linked as a tour's actual track is no longer counted as a tour of
its own in the trip's tour summary, and the GPX preview imports a city walk
as one instead of as a hike.
This commit is contained in:
Maurice
2026-10-20 12:42:33 +02:00
parent f016972a4e
commit d0cc6fc2f4
101 changed files with 5031 additions and 50 deletions
@@ -7,6 +7,7 @@ import { FileLinks } from './FileLinks.entity';
import { Places } from './Places.entity';
import { Reservations } from './Reservations.entity';
import { RoadtripDayBoundaries } from './RoadtripDayBoundaries.entity';
import { TourActivities } from './TourActivities.entity';
import { TourStationVisits } from './TourStationVisits.entity';
export class DayAssignments {
@@ -34,6 +35,7 @@ export class DayAssignments {
reservations_collection = new Collection<Reservations>(this);
roadtrip_day_boundaries_collection = new Collection<RoadtripDayBoundaries>(this);
roadtrip_day_boundaries_collection1 = new Collection<RoadtripDayBoundaries>(this);
tour_activities_collection = new Collection<TourActivities>(this);
tour_station_visits_collection = new Collection<TourStationVisits>(this);
}
@@ -64,6 +66,7 @@ export const DayAssignmentsSchema = defineEntity({
reservations_collection: () => p.oneToMany(Reservations).mappedBy('assignment').hidden(),
roadtrip_day_boundaries_collection: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('fromAssignment').hidden(),
roadtrip_day_boundaries_collection1: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('toAssignment').hidden(),
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('assignment').hidden(),
tour_station_visits_collection: () => p.oneToMany(TourStationVisits).mappedBy('assignment').hidden(),
},
});
@@ -0,0 +1,45 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TourActivitiesRepository } from '../repositories/TourActivities.repository';
import { DbTimestampType } from '../types';
import { DayAssignments } from './DayAssignments.entity';
import { Tours } from './Tours.entity';
import { Users } from './Users.entity';
export class TourActivities {
[EntityRepositoryType]?: TourActivitiesRepository;
id!: number & Opt;
place!: Ref<Tours>;
place_id!: number;
trackPlace!: Ref<Tours>;
track_place_id!: number;
assignment?: Ref<DayAssignments> | null;
assignment_id?: number | null;
assigned_by?: number | null;
assigned_at!: string & Opt;
assignedByRef?: Ref<Users> | null;
}
export const TourActivitiesSchema = defineEntity({
class: TourActivities,
repository: () => TourActivitiesRepository,
uniques: [
{ properties: ['trackPlace'] },
{
name: 'idx_tour_activities_assignment',
where: 'assignment_id IS NOT NULL',
properties: ['assignment'],
},
],
properties: {
id: p.integer().primary(),
place: () => p.manyToOne(Tours).ref().name('place_id').deleteRule('cascade').hidden().index('idx_tour_activities_place'),
place_id: p.integer().persist(false).index('idx_tour_activities_place'),
trackPlace: () => p.manyToOne(Tours).ref().name('track_place_id').deleteRule('cascade').hidden(),
track_place_id: p.integer().persist(false),
assignment: () => p.manyToOne(DayAssignments).ref().nullable().hidden(),
assignment_id: p.integer().nullable().persist(false),
assigned_by: p.integer().nullable().persist(false).index('idx_tour_activities_assigned_by'),
assigned_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
assignedByRef: () => p.manyToOne(Users).ref().joinColumn('assigned_by').nullable().hidden().index('idx_tour_activities_assigned_by'),
},
});
+10
View File
@@ -1,6 +1,8 @@
import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { ToursRepository } from '../repositories/Tours.repository';
import { DbTimestampType } from '../types';
import { Places } from './Places.entity';
import { TourActivities } from './TourActivities.entity';
import { TourChangeSteps } from './TourChangeSteps.entity';
import { TourObstacleReviews } from './TourObstacleReviews.entity';
import { TourSources } from './TourSources.entity';
@@ -45,7 +47,11 @@ export class Tours {
run_pace_seconds_per_km?: number | null;
ski_discipline?: TToursSkiDiscipline | null;
ski_technique?: TToursSkiTechnique | null;
track_started_at?: string | null;
track_ended_at?: string | null;
tourTypeRef!: Ref<TourTypes>;
tour_activities_collection = new Collection<TourActivities>(this);
tour_activities_collection1 = new Collection<TourActivities>(this);
tour_change_steps_collection = new Collection<TourChangeSteps>(this);
tour_obstacle_reviews_collection = new Collection<TourObstacleReviews>(this);
tour_sources: Ref<TourSources> | null = null;
@@ -176,7 +182,11 @@ export const ToursSchema = defineEntity({
run_pace_seconds_per_km: p.integer().nullable(),
ski_discipline: p.enum(() => ToursSkiDiscipline).nullable(),
ski_technique: p.enum(() => ToursSkiTechnique).nullable(),
track_started_at: p.type(DbTimestampType).nullable(),
track_ended_at: p.type(DbTimestampType).nullable(),
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('place').hidden(),
tour_activities_collection1: () => p.oneToMany(TourActivities).mappedBy('trackPlace').hidden(),
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(),
+3
View File
@@ -51,6 +51,7 @@ import { ShareTokens } from './ShareTokens.entity';
import { Tags } from './Tags.entity';
import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity';
import { TodoItems } from './TodoItems.entity';
import { TourActivities } from './TourActivities.entity';
import { TourSources } from './TourSources.entity';
import { TrekPhotos } from './TrekPhotos.entity';
import { TripAlbumLinks } from './TripAlbumLinks.entity';
@@ -178,6 +179,7 @@ export class Users {
tags_collection = new Collection<Tags>(this);
todo_category_assignees_collection = new Collection<TodoCategoryAssignees>(this);
todo_items_collection = new Collection<TodoItems>(this);
tour_activities_collection = new Collection<TourActivities>(this);
tour_sources_collection = new Collection<TourSources>(this);
trek_photos_collection = new Collection<TrekPhotos>(this);
trip_album_links_collection = new Collection<TripAlbumLinks>(this);
@@ -323,6 +325,7 @@ export const UsersSchema = defineEntity({
tags_collection: () => p.oneToMany(Tags).mappedBy('user').hidden(),
todo_category_assignees_collection: () => p.oneToMany(TodoCategoryAssignees).mappedBy('user').hidden(),
todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('assignedUser').hidden(),
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('assignedByRef').hidden(),
tour_sources_collection: () => p.oneToMany(TourSources).mappedBy('importedByRef').hidden(),
trek_photos_collection: () => p.oneToMany(TrekPhotos).mappedBy('owner').hidden(),
trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('user').hidden(),
+2
View File
@@ -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 { TourActivitiesSchema } from './TourActivities.entity';
import { TourChangeStepsSchema } from './TourChangeSteps.entity';
import { TourObstacleReviewsSchema } from './TourObstacleReviews.entity';
import { TourSourcesSchema } from './TourSources.entity';
@@ -253,6 +254,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TagsSchema,
TodoCategoryAssigneesSchema,
TodoItemsSchema,
TourActivitiesSchema,
TourChangeStepsSchema,
TourObstacleReviewsSchema,
TourSourcesSchema,
@@ -0,0 +1,12 @@
// 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 TourActivitiesTable {
id: InsertOptional<number>;
place_id: number;
track_place_id: number;
assignment_id: InsertOptional<number | null>;
assigned_by: InsertOptional<number | null>;
assigned_at: InsertOptional<string>;
}
+2
View File
@@ -36,4 +36,6 @@ export interface ToursTable {
run_pace_seconds_per_km: InsertOptional<number | null>;
ski_discipline: InsertOptional<string | null>;
ski_technique: InsertOptional<string | null>;
track_started_at: InsertOptional<string | null>;
track_ended_at: InsertOptional<string | null>;
}
+2
View File
@@ -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 { TourActivitiesTable } from './TourActivities.table';
import type { TourChangeStepsTable } from './TourChangeSteps.table';
import type { TourObstacleReviewsTable } from './TourObstacleReviews.table';
import type { TourSourcesTable } from './TourSources.table';
@@ -265,6 +266,7 @@ export interface DB {
tags: TagsTable;
todo_category_assignees: TodoCategoryAssigneesTable;
todo_items: TodoItemsTable;
tour_activities: TourActivitiesTable;
tour_change_steps: TourChangeStepsTable;
tour_obstacle_reviews: TourObstacleReviewsTable;
tour_sources: TourSourcesTable;
@@ -0,0 +1,46 @@
import { Migration } from '@mikro-orm/migrations';
/**
* ACT-01: a tour can be given the track it was actually done with. The
* recording is a tour of the same trip that came in through the GPX import
* (or from wanderer); `tour_activities` only points at it, so it keeps its own
* name and provenance, and the planned tour keeps its line, measures and times
* untouched. `assignment_id` is the execution, the day assignment of the tour
* the recording belongs to; NULL for a tour done without a day. One recording
* documents one tour (`track_place_id UNIQUE`) and an execution has one
* recording (the partial unique index); an execution without a day is held to
* one by the service, which also refuses a tour as its own recording. Taking
* the tour off a day keeps the recording and only forgets the day; deleting
* either tour takes the assignment with it.
* `assigned_by` names who assigned it, kept as unknown when that account goes.
*
* Not to be confused with `tours.recorded_route_geometry`: that is the line an
* import was planned over from, this is what was walked.
*
* `track_started_at` and `track_ended_at` are the first and last time on the
* points of a track the GPX import read, NULL unless every point carried one;
* every tour imported before stays NULL, its times unknown.
*/
export class Migration20200101045900_a_tour_keeps_the_track_it_was_done_with extends Migration {
override name = 'Migration20200101045900_a_tour_keeps_the_track_it_was_done_with';
override up(): void {
this.addSql('ALTER TABLE tours ADD COLUMN track_started_at DATETIME');
this.addSql('ALTER TABLE tours ADD COLUMN track_ended_at DATETIME');
this.addSql(`
CREATE TABLE IF NOT EXISTS tour_activities (
id INTEGER PRIMARY KEY,
place_id INTEGER NOT NULL REFERENCES tours(place_id) ON DELETE CASCADE,
track_place_id INTEGER NOT NULL UNIQUE REFERENCES tours(place_id) ON DELETE CASCADE,
assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL,
assigned_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
assigned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_tour_activities_place ON tour_activities(place_id)');
this.addSql(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_tour_activities_assignment ON tour_activities(assignment_id) WHERE assignment_id IS NOT NULL',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_tour_activities_assigned_by ON tour_activities(assigned_by)');
}
}
@@ -0,0 +1,147 @@
import type { TourActivities } from '../entities/TourActivities.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type ActivitiesDB = Pick<DB, 'tour_activities' | 'tours' | 'places' | 'day_assignments'>;
/** One assignment of a recording to a tour, as the trip's tour list names it. */
export interface TourActivityRefRow {
id: number;
place_id: number;
track_place_id: number;
assignment_id: number | null;
}
/**
* One assignment with what the detail shows of its recording: the name and
* provenance it has in the trip, its line (the place's, or the line it kept
* when it was planned over since), and the times the import read off it.
*/
export interface TourActivityRow extends TourActivityRefRow {
day_id: number | null;
assigned_at: string;
track_name: string;
track_origin: string;
track_file_name: string | null;
track_created_at: string | null;
track_route_geometry: string | null;
track_recorded_route_geometry: string | null;
track_started_at: string | null;
track_ended_at: string | null;
}
/** What an assignment writes: the tour, its recording, the execution and who confirmed it. */
interface TourActivityInsert {
place_id: number;
track_place_id: number;
assignment_id: number | null;
assigned_by: number | null;
}
/**
* `tour_activities` (ACT-01): the recordings assigned to the tours of a trip.
* Every read here is scoped to one trip through both tours' places, so a row
* never reaches across trips even if an id does. Kysely throughout: the reads
* join the tours and places of both sides.
*/
export class TourActivitiesRepository extends TrekRepository<TourActivities> {
private db() {
return this.kysely<ActivitiesDB>();
}
/** The assignments of one tour of the trip, with their recordings, oldest first. */
async listForPlace(trip_id: number, place_id: number): Promise<TourActivityRow[]> {
return await this.db()
.selectFrom('tour_activities as a')
.innerJoin('places as p', 'p.id', 'a.place_id')
.innerJoin('places as tp', 'tp.id', 'a.track_place_id')
.innerJoin('tours as tt', 'tt.place_id', 'a.track_place_id')
.leftJoin('day_assignments as da', 'da.id', 'a.assignment_id')
.select([
'a.id as id',
'a.place_id as place_id',
'a.track_place_id as track_place_id',
'a.assignment_id as assignment_id',
'da.day_id as day_id',
'a.assigned_at as assigned_at',
'tp.name as track_name',
'tt.origin as track_origin',
'tt.origin_file_name as track_file_name',
'tt.created_at as track_created_at',
'tp.route_geometry as track_route_geometry',
'tt.recorded_route_geometry as track_recorded_route_geometry',
'tt.track_started_at as track_started_at',
'tt.track_ended_at as track_ended_at',
])
.where('a.place_id', '=', place_id)
.where('p.trip_id', '=', trip_id)
.where('tp.trip_id', '=', trip_id)
.orderBy('a.id', 'asc')
.execute();
}
/** Every assignment between tours of the trip, for its tour list. */
async listForTrip(trip_id: number): Promise<TourActivityRefRow[]> {
return await this.db()
.selectFrom('tour_activities as a')
.innerJoin('places as p', 'p.id', 'a.place_id')
.select(['a.id', 'a.place_id', 'a.track_place_id', 'a.assignment_id'])
.where('p.trip_id', '=', trip_id)
.orderBy('a.id', 'asc')
.execute();
}
/** The assignment a recording is part of, whichever tour it documents; undefined while it documents none. */
async findByTrack(track_place_id: number): Promise<TourActivityRefRow | undefined> {
return await this.db()
.selectFrom('tour_activities')
.select(['id', 'place_id', 'track_place_id', 'assignment_id'])
.where('track_place_id', '=', track_place_id)
.executeTakeFirst();
}
/** Whether a tour has any recording assigned to it. */
async hasActivities(place_id: number): Promise<boolean> {
const row = await this.db()
.selectFrom('tour_activities')
.select('id')
.where('place_id', '=', place_id)
.executeTakeFirst();
return !!row;
}
/**
* Clears the way for a new assignment of `track_place_id` to this execution
* of the tour: the recording the execution had, and the execution this
* recording had on the same tour. Inside the caller's transaction, before
* {@link insertActivity}.
*/
async clearFor(place_id: number, track_place_id: number, assignment_id: number | null): Promise<void> {
await this.db()
.deleteFrom('tour_activities')
.where('place_id', '=', place_id)
.where((eb) =>
eb.or([
assignment_id === null ? eb('assignment_id', 'is', null) : eb('assignment_id', '=', assignment_id),
eb('track_place_id', '=', track_place_id),
]),
)
.execute();
}
/** Writes one assignment and answers its id. */
async insertActivity(input: TourActivityInsert): Promise<number> {
const row = await this.db().insertInto('tour_activities').values(input).returning('id').executeTakeFirstOrThrow();
return row.id;
}
/** Removes one assignment of this tour; answers whether there was one. */
async removeFromPlace(place_id: number, id: number): Promise<boolean> {
const result = await this.db()
.deleteFrom('tour_activities')
.where('id', '=', id)
.where('place_id', '=', place_id)
.executeTakeFirst();
return Number(result.numDeletedRows ?? 0) > 0;
}
}
@@ -63,6 +63,9 @@ export interface TourListRow {
revision: number;
/** MF-08: a hike's routing preferences, still JSON text. */
hiking_preferences: string | null;
/** ACT-01: the first and last time on an imported track's points; NULL without times. */
track_started_at: string | null;
track_ended_at: string | null;
}
/** LIB-02: a tour of another trip as the take-over list reads it, with the trip it is in. */
@@ -119,6 +122,8 @@ export interface TourRow {
run_pace_seconds_per_km: number | null;
ski_discipline: string | null;
ski_technique: string | null;
track_started_at: string | null;
track_ended_at: string | null;
}
const _tourRowKeys: AssertRowKeys<TourRow, Tours> = true;
@@ -299,6 +304,8 @@ export class ToursRepository extends TrekRepository<Tours> {
't.track_marks as track_marks',
't.revision as revision',
't.hiking_preferences as hiking_preferences',
't.track_started_at as track_started_at',
't.track_ended_at as track_ended_at',
eb('t.recorded_route_geometry', 'is not', null).as('has_recorded_track'),
eb('p.route_geometry', 'is', null).as('route_missing'),
eb
@@ -637,6 +644,9 @@ export class ToursRepository extends TrekRepository<Tours> {
track_marks?: string | null;
taken_over_from_trip_title?: string | null;
taken_over_from_tour_name?: string | null;
/** ACT-01: the times the import read off the track's points, canonical DATETIME text. */
track_started_at?: string | null;
track_ended_at?: string | null;
},
): Promise<void> {
await this.insert({
@@ -670,6 +680,8 @@ export class ToursRepository extends TrekRepository<Tours> {
hiking_preferences: input.hiking_preferences ?? null,
taken_over_from_trip_title: input.taken_over_from_trip_title ?? null,
taken_over_from_tour_name: input.taken_over_from_tour_name ?? null,
track_started_at: input.track_started_at ?? null,
track_ended_at: input.track_ended_at ?? null,
});
}
@@ -13,6 +13,11 @@ export interface PreparedGpxPlace {
lng: number;
description: string | null;
routeGeometry?: string;
/**
* ACT-01: when a track was recorded, ISO 8601 in UTC: its first and last
* point's time, only when every point carries one. Never on a route.
*/
trackTimes?: { startedAt: string; endedAt: string };
}
export interface GpxImportOptions {
@@ -208,6 +208,29 @@ export function gpxFilename(tripTitle: string, fallback = 'trip'): string {
return `${[...base].slice(0, 60).join('') || fallback}.gpx`;
}
/** A time written with its zone (`Z` or an offset); one without is local to an unknown clock and reads as none. */
const ZONED_TIME = /(?:Z|[+-]\d{2}:?\d{2})$/i;
/**
* ACT-01: when a track was recorded, from the times on its points: the first
* and the last, only when every point carries one with its zone and they never
* run backwards, so a track drawn on a map or stitched from pieces never reads
* as recorded. Undefined otherwise.
*/
export function trackTimeSpan(times: readonly unknown[]): { startedAt: string; endedAt: string } | undefined {
let first: number | undefined;
let last = Number.NEGATIVE_INFINITY;
for (const raw of times) {
const text = typeof raw === 'string' ? raw.trim() : '';
const at = ZONED_TIME.test(text) ? Date.parse(text) : Number.NaN;
if (!Number.isFinite(at) || at < last) return undefined;
first ??= at;
last = at;
}
if (first === undefined || last <= first) return undefined;
return { startedAt: new Date(first).toISOString(), endedAt: new Date(last).toISOString() };
}
/**
* Parses a GPX file into the places an import would create, without writing
* anything. Waypoints become places, each route and each track becomes one
@@ -282,12 +305,14 @@ function prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): Prepar
if (importTracks) {
for (const trk of gpx.trk ?? []) {
const trackPoints: { lat: number; lng: number; ele: number | null }[] = [];
const times: unknown[] = [];
for (const seg of trk.trkseg ?? []) {
for (const pt of seg.trkpt ?? []) {
const lat = num(pt['@_lat']);
const lng = num(pt['@_lon']);
if (lat === null || lng === null) continue;
trackPoints.push({ lat, lng, ele: num(pt.ele) });
times.push(pt.time);
}
}
if (trackPoints.length === 0) continue;
@@ -300,6 +325,7 @@ function prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): Prepar
name: geoName(str(trk.name), 'GPX Track'),
description: str(trk.desc),
routeGeometry: JSON.stringify(routeGeometry),
...withTrackTimes(trackTimeSpan(times)),
});
}
}
@@ -307,6 +333,11 @@ function prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): Prepar
return waypoints;
}
/** The times as a row carries them: left out, not undefined, when the track has none. */
function withTrackTimes(span: ReturnType<typeof trackTimeSpan>): Pick<PreparedGpxPlace, 'trackTimes'> {
return span ? { trackTimes: span } : {};
}
/** The GPX source: a trip file in, a trip file out. */
@Injectable()
export class GpxProvider {
@@ -0,0 +1,5 @@
import { tourActivityAssignRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class TourActivityAssignDto extends createZodDto(tourActivityAssignRequestSchema) {}
@@ -0,0 +1,52 @@
import { ADDON_IDS } from '../../addons';
import type { User } from '../../types';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { TourActivityAssignDto } from './dto/tour-activity.dto';
import { TourActivitiesService } from './tour-activities.service';
import { Body, Controller, Delete, Headers, Param, ParseIntPipe, Put, UseGuards } from '@nestjs/common';
import { tourDetailResponseSchema } from '@trek/shared';
/**
* ACT-01: the recorded tracks of a tour. PUT
* /api/trips/:tripId/tours/:placeId/activities assigns a recording of the trip
* to one execution of the tour (a day it is on, or none); DELETE
* .../activities/:activityId takes it off again. Both answer the tour as its
* detail reads it and need 'place_edit', like every other change of a tour.
* Reading them is the tour's detail.
*/
@Controller('api/trips/:tripId/tours/:placeId/activities')
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class TourActivitiesController {
constructor(private readonly activities: TourActivitiesService) {}
@RequirePermission('place_edit')
@Put()
@ResponseContract(tourDetailResponseSchema)
async assign(
@Param('tripId') tripId: string,
@Param('placeId') placeId: string,
@Body() body: TourActivityAssignDto,
@CurrentUser() user: User,
@Headers('x-socket-id') socketId?: string,
) {
return await this.activities.assign(tripId, placeId, body, user.id, socketId);
}
@RequirePermission('place_edit')
@Delete(':activityId')
@ResponseContract(tourDetailResponseSchema)
async unassign(
@Param('tripId') tripId: string,
@Param('placeId') placeId: string,
@Param('activityId', ParseIntPipe) activityId: number,
@Headers('x-socket-id') socketId?: string,
) {
return await this.activities.unassign(tripId, placeId, activityId, socketId);
}
}
@@ -0,0 +1,99 @@
/**
* ACT-01: the pure half of a tour's recorded tracks. What a recording measures
* is read from its own line every time it is asked, so the answer follows the
* recording and never touches the plan; what an assignment row says about the
* two tours it joins is mapped here for the list and the detail.
*/
import type { TourActivityRefRow, TourActivityRow } from '../../db/repositories/TourActivities.repository';
import { dbNow, parseDbTimestamp, utcSuffix, type DbTimestamp } from '../../db/types';
import type { PreparedGpxPlace } from '../place-import/place-import.types';
import { computeTourMetrics, parseRouteGeometry } from './tours.helpers';
import type { TourActivity, TourListItem, TourOrigin } from '@trek/shared';
/** Minutes from the first to the last time of a track, pauses included; null unless both are there and in order. */
export function elapsedMinutes(startedAt: string | null, endedAt: string | null): number | null {
const start = parseDbTimestamp(startedAt);
const end = parseDbTimestamp(endedAt);
if (!start || !end || end.getTime() <= start.getTime()) return null;
return Math.round((end.getTime() - start.getTime()) / 60_000);
}
/**
* One assignment as the detail answers it. The recording's line is the one it
* kept when someone planned over it since, otherwise its place's own: either
* way the line it was recorded with, never a plan.
*/
export function toActivity(row: TourActivityRow): TourActivity {
const geometry = parseRouteGeometry(row.track_recorded_route_geometry ?? row.track_route_geometry);
const metrics = computeTourMetrics(geometry);
return {
id: row.id,
assignment_id: row.assignment_id,
day_id: row.day_id,
assigned_at: utcSuffix(row.assigned_at),
track: {
place_id: row.track_place_id,
name: row.track_name,
origin: row.track_origin as TourOrigin,
file_name: row.track_file_name,
imported_at: utcSuffix(row.track_created_at),
},
metrics: {
distance_km: geometry.length >= 2 ? metrics.distanceKm : null,
elevation_gain_m: metrics.elevationGainM,
elevation_loss_m: metrics.elevationLossM,
started_at: utcSuffix(row.track_started_at),
ended_at: utcSuffix(row.track_ended_at),
elapsed_minutes: elapsedMinutes(row.track_started_at, row.track_ended_at),
point_count: geometry.length,
},
geometry,
};
}
/** An assignment as an MCP tool answers it: everything but the recorded line, which runs to thousands of points. */
export function withoutLine({ geometry: _line, ...activity }: TourActivity): Omit<TourActivity, 'geometry'> {
return activity;
}
/** What the list says of a tour's assignments: the recordings it has, and the tour it documents itself. */
export function activityFacts(
placeId: number,
refs: readonly TourActivityRefRow[],
): Pick<TourListItem, 'activity_tracks' | 'activity_of'> {
return {
activity_tracks: refs
.filter((ref) => ref.place_id === placeId)
.map(({ id, track_place_id, assignment_id }) => ({ id, track_place_id, assignment_id })),
activity_of: refs.find((ref) => ref.track_place_id === placeId)?.place_id ?? null,
};
}
/** The times an import stores for a track, as the DATETIME columns hold them; NULL without. */
function storedTimes(row: PreparedGpxPlace | undefined): { started: DbTimestamp | null; ended: DbTimestamp | null } {
const times = row?.trackTimes;
return times
? { started: dbNow(new Date(times.startedAt)), ended: dbNow(new Date(times.endedAt)) }
: { started: null, ended: null };
}
/**
* The times of each imported place, found by the row it was made from: the
* same name and start, the first row not taken yet. The import skips a
* duplicate, so the places are not the rows one by one.
*/
export function trackTimesFor(
rows: readonly PreparedGpxPlace[],
places: ReadonlyArray<{ id: number; name: string; lat: number | null; lng: number | null }>,
): Map<number, { started: DbTimestamp | null; ended: DbTimestamp | null }> {
const taken = new Set<number>();
const byPlace = new Map<number, { started: DbTimestamp | null; ended: DbTimestamp | null }>();
for (const place of places) {
const index = rows.findIndex(
(row, at) => !taken.has(at) && row.name === place.name && row.lat === place.lat && row.lng === place.lng,
);
if (index >= 0) taken.add(index);
byPlace.set(place.id, storedTimes(rows[index]));
}
return byPlace;
}
@@ -0,0 +1,110 @@
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import {
McpController,
Tool,
TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_WRITE,
errorResult,
ok,
type McpContext,
} from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { withoutLine } from './tour-activities.helpers';
import { TourActivitiesService } from './tour-activities.service';
import { NotFoundException } from '@nestjs/common';
import {
idSchema,
tourActivityAssignRequestSchema,
type TourActivityAssignRequest,
type TourDetailResponse,
} from '@trek/shared';
const assign = tourActivityAssignRequestSchema.shape;
/** The tour after the change, its recordings without their lines. */
function answer(detail: TourDetailResponse) {
return { ...detail, activities: (detail.activities ?? []).map(withoutLine) };
}
/**
* ACT-01: assigning a recorded track to a tour and taking it off, over the
* same service and the same checks as REST: access to the trip, then
* 'place_edit' on it. What a tour's recordings measure is read with
* get_tour_plan.
*/
@McpController()
export class TourActivitiesMcp {
constructor(
private readonly activities: TourActivitiesService,
private readonly access: TripAccessService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
/** The checks every tool here runs first: the trip is the user's to see, and theirs to change tours in. */
private async refusal(tripId: number, userId: number) {
if (!(await this.access.findAccessible(tripId, userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, userId))) return permissionDenied();
return null;
}
@Tool({
name: 'assign_tour_track',
description:
'Assign a recorded track to a saved tour, as the way the tour was actually done, once the user has chosen the track and confirmed it. The track is another tour of the same trip that came in through the GPX import or from wanderer and was not planned over (list_tours: origin gpx or wanderer, has_waypoints false); it keeps its own name and source. assignment_id is the execution, one of the day assignments of the tour (find_tours_for_day and get_tour_plan show its days), or null for none; an execution that already has a track gets this one instead, and the track moves there if it was on another execution of the same tour. A track documents one tour only. The planned line, measures and times of the tour stay exactly as they are; what the recording measures (distance, ascent, descent, and the time from its first to its last point, only where the file carried times) is answered under activities and read again with get_tour_plan. Never assign a track the user did not pick.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the planned tour, as list_tours gives it'),
track_place_id: assign.track_place_id.describe('The place id of the recorded track, a tour of the same trip'),
assignment_id: assign.assignment_id.describe('The day assignment of the tour it was done on, or null'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async assignTourTrack(
{ tripId, placeId, ...body }: { tripId: number; placeId: number } & TourActivityAssignRequest,
ctx: McpContext,
) {
const refusal = await this.refusal(tripId, ctx.userId);
if (refusal) return refusal;
try {
return ok(answer(await this.activities.assign(String(tripId), String(placeId), body, ctx.userId)));
} catch (err: unknown) {
if (err instanceof NotFoundException) return errorResult('Tour or recorded track not found.');
throw err;
}
}
@Tool({
name: 'unassign_tour_track',
description:
'Take a recorded track off a saved tour again, by the id get_tour_plan lists it under activities. The track stays in the trip as the import it is, and nothing of the tour changes.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the planned tour, as list_tours gives it'),
activityId: idSchema.describe('The id of the assignment, from get_tour_plan activities'),
},
annotations: TOOL_ANNOTATIONS_DELETE,
when: addonGate(ADDON_IDS.TOURS),
access: { group: 'trips', mode: 'write' },
})
async unassignTourTrack(
{ tripId, placeId, activityId }: { tripId: number; placeId: number; activityId: number },
ctx: McpContext,
) {
const refusal = await this.refusal(tripId, ctx.userId);
if (refusal) return refusal;
try {
return ok(answer(await this.activities.unassign(String(tripId), String(placeId), activityId)));
} catch (err: unknown) {
if (err instanceof NotFoundException) return errorResult('Recorded track not found.');
throw err;
}
}
}
@@ -0,0 +1,121 @@
import { TourActivities } from '../../db/entities/TourActivities.entity';
import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
import { Tours } from '../../db/entities/Tours.entity';
import type { TourActivitiesRepository } from '../../db/repositories/TourActivities.repository';
import type { TourStationVisitsRepository } from '../../db/repositories/TourStationVisits.repository';
import type { ToursRepository } from '../../db/repositories/Tours.repository';
import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { ToursService } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, NotFoundException } from '@nestjs/common';
import type { TourActivityAssignRequest, TourActivityRefusal, TourDetailResponse } from '@trek/shared';
/** A refusal with its code in the body, so the app can say what went wrong in its own words. */
function refused(status: 400 | 409, code: TourActivityRefusal, message: string): DomainError {
return new DomainError(status, message, { code, details: { code } });
}
/**
* ACT-01: assigning a recorded track to a tour, and taking it off again. The
* recording is a tour of the same trip that still holds the line it was
* recorded with; the assignment points at it for one execution of the tour (a
* day it is on, or none) and changes nothing of either tour's plan, so it does
* not raise the tour's revision either: an open draft of the plan stays valid.
* Every check runs inside the write, so a recording assigned or a day removed
* meanwhile is refused rather than written over, and a refused write leaves
* everything as it was. Both surfaces (REST and MCP) call these two methods.
*/
@Injectable()
export class TourActivitiesService {
constructor(
private readonly uow: UnitOfWork,
private readonly tours: ToursService,
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
@InjectRepository(TourActivities) private readonly activitiesRepo: TourActivitiesRepository,
@InjectRepository(TourStationVisits) private readonly visitsRepo: TourStationVisitsRepository,
) {}
/**
* The recording becomes the track this execution of the tour was done with,
* in place of the one it had; a recording already on another execution of
* the same tour moves here. Answers the tour as the detail reads it.
*/
async assign(
tripId: string,
placeId: string,
input: TourActivityAssignRequest,
userId: number,
socketId?: string,
): Promise<TourDetailResponse> {
const { tid, pid } = this.ids(tripId, placeId);
const trackId = input.track_place_id;
await this.uow.transactional(async () => {
if (!(await this.toursRepo.findInTrip(tid, pid))) throw new NotFoundException('Tour not found');
await this.checkTrack(tid, pid, trackId);
await this.checkAssignment(tid, pid, input.assignment_id);
await this.activitiesRepo.clearFor(pid, trackId, input.assignment_id);
await this.activitiesRepo.insertActivity({
place_id: pid,
track_place_id: trackId,
assignment_id: input.assignment_id,
assigned_by: userId,
});
});
this.tours.broadcastToursChanged(tripId, [pid, trackId], socketId);
return await this.tours.getTour(tripId, placeId);
}
/** The recording is no longer this tour's; it stays in the trip as the import it is. */
async unassign(tripId: string, placeId: string, activityId: number, socketId?: string): Promise<TourDetailResponse> {
const { tid, pid } = this.ids(tripId, placeId);
const activity = (await this.activitiesRepo.listForPlace(tid, pid)).find((row) => row.id === activityId);
if (!activity || !(await this.activitiesRepo.removeFromPlace(pid, activityId))) {
throw new NotFoundException('Recorded track not found');
}
this.tours.broadcastToursChanged(tripId, [pid, activity.track_place_id], socketId);
return await this.tours.getTour(tripId, placeId);
}
private ids(tripId: string, placeId: string): { tid: number; pid: number } {
const tid = toRowId(tripId);
const pid = toRowId(placeId);
if (tid === null || pid === null) throw new NotFoundException('Tour not found');
return { tid, pid };
}
/**
* What may be assigned: a tour of this trip that came in as a recording and
* still is one, that is neither this tour nor one with recordings of its own,
* and that documents no other tour; and this tour must not be the recording
* of another. A tour of another trip reads as missing, as any id would.
*/
private async checkTrack(tripId: number, placeId: number, trackId: number): Promise<void> {
if (trackId === placeId) throw refused(400, 'activity_track_is_tour', 'A tour cannot be its own recorded track');
const track = await this.toursRepo.findInTrip(tripId, trackId);
if (!track) throw new NotFoundException('Recorded track not found');
if (track.origin === 'trek' || track.has_waypoints) {
throw refused(400, 'activity_track_not_recorded', 'Only an import that was not planned over can be assigned');
}
if (await this.activitiesRepo.hasActivities(trackId)) {
throw refused(400, 'activity_track_is_tour', 'A tour with recorded tracks of its own cannot be one');
}
const used = await this.activitiesRepo.findByTrack(trackId);
if (used && used.place_id !== placeId) {
throw refused(409, 'activity_track_in_use', 'This recorded track is assigned to another tour');
}
if (await this.activitiesRepo.findByTrack(placeId)) {
throw refused(400, 'activity_tour_is_track', 'A recorded track of another tour cannot have recorded tracks');
}
}
/** The execution, when one is named, is a day assignment of this very tour in this trip. */
private async checkAssignment(tripId: number, placeId: number, assignmentId: number | null): Promise<void> {
if (assignmentId === null) return;
const assignment = await this.visitsRepo.assignmentInTrip(assignmentId, tripId);
if (assignment?.place_id !== placeId) {
throw refused(400, 'activity_assignment_not_of_tour', 'The day is not one this tour is on');
}
}
}
+8 -4
View File
@@ -5,6 +5,7 @@ import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type M
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { withoutLine } from './tour-activities.helpers';
import { TourGpxExportService } from './tour-gpx-export.service';
import { derivedFields, planLegs, planLine, planPoints, planRun } from './tour-plan-read';
import { TourPoiSearchService } from './tour-poi-search.service';
@@ -41,8 +42,9 @@ interface PlanRead {
/**
* MCP-T01: the plan of one saved tour as an assistant reads it: the detail the
* app reads, its days, the legs between its control points, its saved line in
* brief, for a city walk the visits of the day asked for, and the fields that
* were worked out on reading rather than stored.
* brief, the recorded tracks assigned to it (ACT-01), for a city walk the
* visits of the day asked for, and the fields that were worked out on reading
* rather than stored.
*/
function planOf({ detail, days, line, names }: PlanRead, run: WalkProgress | null) {
const named = detail.waypoints.map((point) =>
@@ -57,6 +59,8 @@ function planOf({ detail, days, line, names }: PlanRead, run: WalkProgress | nul
...detail,
tour: withDays(detail.tour, days),
waypoints: planPoints(detail.tour.tour_type, named, run),
// ACT-01: the recorded tracks assigned to the tour, with their values and without their lines.
activities: (detail.activities ?? []).map(withoutLine),
legs: planLegs(detail.waypoints, { recorded }),
line: saved,
...(isWalk ? { run: run ? planRun(run) : null } : {}),
@@ -97,7 +101,7 @@ export class ToursMcp {
@Tool({
name: 'list_tours',
description:
'List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski tracks planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski track; a ride has no riding time worked out, so its duration is null), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the winter label of a hike (winter_activity: winter_hike or snowshoe, null for none; a label the travellers chose, while the route and its time are planned as for any hike, never a statement that a way can be walked in winter or anything about snow or avalanches), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the classification of a ski track (ski_discipline: alpine, snowboard, cross_country or touring for ski touring; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a ski track is imported from a GPX file and kept as recorded, never routed, its distance and heights come from the file, it has no ski time worked out, and nothing in it says anything about snow, avalanches or whether a run or trail is open), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), the revision (raised by every saved change of the tour), and the days of the trip each tour is on.',
'List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski tracks planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski track; a ride has no riding time worked out, so its duration is null), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the winter label of a hike (winter_activity: winter_hike or snowshoe, null for none; a label the travellers chose, while the route and its time are planned as for any hike, never a statement that a way can be walked in winter or anything about snow or avalanches), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the classification of a ski track (ski_discipline: alpine, snowboard, cross_country or touring for ski touring; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a ski track is imported from a GPX file and kept as recorded, never routed, its distance and heights come from the file, it has no ski time worked out, and nothing in it says anything about snow, avalanches or whether a run or trail is open), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), the revision (raised by every saved change of the tour), the recorded tracks assigned to a tour (activity_tracks) and, for a recorded track, the tour it documents (activity_of), when an imported track was recorded (track_started_at, track_ended_at; null when the file carried no times), and the days of the trip each tour is on.',
inputSchema: { tripId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.TOURS),
@@ -112,7 +116,7 @@ export class ToursMcp {
@Tool({
name: 'get_tour_plan',
description:
'Read one saved tour of a trip as the travellers saved it: its facts (tour: place_id, name, tour_type, distance, heights and walking time as stored, null when not known; the routing options as list_tours describes them; revision, raised by every saved change; the days it is on), its ordered control points (start, via and end, each with its sequence and its key, the same across saves; an import without its own shows the two ends of its track), where it came from (provenance) and its legs. Drafts in a browser are never visible: only saved tours exist here, and reading changes nothing, not the tour, its revision nor any visit. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. legs lists every step from one control point to the next (from_sequence, to_sequence, from_key, to_key) with its kind: routed (planned by the router), track (part of a recorded line, an import without control points of its own, which no router planned), ferrata (follows a via ferrata, name gives it), free (drawn by hand and checked by nothing), portage (a paddle tour carried over land) or horse_route (a ride only: a section of a signposted horse route from OpenStreetMap in the direction the rider chose; the fixed_leg of its control point says signposted, with or against the direction the route is signposted in, null where it is not signposted one way, and access, the metres of each horse=* value its ways carried when it was taken, unknown where untagged; being on a horse route is no permission to ride it); length_km is the length of the line a fixed leg keeps and null for a routed or track leg, whose length is not stored apart. line gives the saved line in brief: point_count, has_heights and a preview thinned to 200 points; null while the tour waits for its way to be planned. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app), opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known) and visit_status. Visits belong to one day of the walk: name that day with dayId (one of its days) to read the status of each station that day (planned, visited or skipped) and run (the day, its assignment and what is still open); without dayId visit_status and run are null. A station visited or skipped that day is done: do not ask about it again or move it to another day. dayId is for a city walk only. derived names the fields worked out on reading rather than stored with the tour: never present them as saved facts.',
'Read one saved tour of a trip as the travellers saved it: its facts (tour: place_id, name, tour_type, distance, heights and walking time as stored, null when not known; the routing options as list_tours describes them; revision, raised by every saved change; the days it is on), its ordered control points (start, via and end, each with its sequence and its key, the same across saves; an import without its own shows the two ends of its track), where it came from (provenance) and its legs. Drafts in a browser are never visible: only saved tours exist here, and reading changes nothing, not the tour, its revision nor any visit. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. legs lists every step from one control point to the next (from_sequence, to_sequence, from_key, to_key) with its kind: routed (planned by the router), track (part of a recorded line, an import without control points of its own, which no router planned), ferrata (follows a via ferrata, name gives it), free (drawn by hand and checked by nothing), portage (a paddle tour carried over land) or horse_route (a ride only: a section of a signposted horse route from OpenStreetMap in the direction the rider chose; the fixed_leg of its control point says signposted, with or against the direction the route is signposted in, null where it is not signposted one way, and access, the metres of each horse=* value its ways carried when it was taken, unknown where untagged; being on a horse route is no permission to ride it); length_km is the length of the line a fixed leg keeps and null for a routed or track leg, whose length is not stored apart. line gives the saved line in brief: point_count, has_heights and a preview thinned to 200 points; null while the tour waits for its way to be planned. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app), opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known) and visit_status. Visits belong to one day of the walk: name that day with dayId (one of its days) to read the status of each station that day (planned, visited or skipped) and run (the day, its assignment and what is still open); without dayId visit_status and run are null. A station visited or skipped that day is done: do not ask about it again or move it to another day. dayId is for a city walk only. The recorded tracks assigned to the tour (activities, ACT-01) each name their execution (assignment_id and day_id, null for none), the recording (track: its tour in the trip, origin, file name, when it came in) and what the recording measures (metrics: distance_km, elevation_gain_m and elevation_loss_m, null without heights; started_at, ended_at and elapsed_minutes from the first to the last time on its points, pauses included, null when the file carried no times, never estimated); these are the values of the recording, the planned values of the tour stay apart and unchanged. derived names the fields worked out on reading rather than stored with the tour: never present them as saved facts.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
+11 -1
View File
@@ -1,4 +1,5 @@
import { Places } from '../../db/entities/Places.entity';
import { TourActivities } from '../../db/entities/TourActivities.entity';
import { TourChangeSteps } from '../../db/entities/TourChangeSteps.entity';
import { TourObstacleReviews } from '../../db/entities/TourObstacleReviews.entity';
import { TourSources } from '../../db/entities/TourSources.entity';
@@ -20,6 +21,9 @@ 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 { TourActivitiesController } from './tour-activities.controller';
import { TourActivitiesMcp } from './tour-activities.mcp';
import { TourActivitiesService } from './tour-activities.service';
import { TourChangePreviewService } from './tour-change-preview.service';
import { TourChangeSaveService } from './tour-change-save.service';
import { TourChangeUndoMcp } from './tour-change-undo.mcp';
@@ -69,7 +73,9 @@ import { Module } from '@nestjs/common';
* assistant prepares for review is laid onto its saved points and planned on
* 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).
* step for a later undo (MCP-T03). The recorded tracks assigned to a tour
* (ACT-01) are read with its detail and written through
* TourActivitiesService, over the day assignments the visits repository reads.
*/
@Module({
imports: [
@@ -99,12 +105,14 @@ import { Module } from '@nestjs/common';
TourObstacleReviews,
TourStationVisits,
TourChangeSteps,
TourActivities,
Places,
]),
],
controllers: [
TourHorseRoutesController,
TourTakeOverController,
TourActivitiesController,
TourPoiSearchController,
TourSkiController,
TourTrailGradeController,
@@ -135,12 +143,14 @@ import { Module } from '@nestjs/common';
TourChangePreviewService,
TourChangeSaveService,
TourChangeUndoService,
TourActivitiesService,
ToursMcp,
TourLibraryMcp,
TourWalkImportMcp,
CityWalkMcp,
TourChangeMcp,
TourChangeUndoMcp,
TourActivitiesMcp,
],
})
export class ToursModule {}
+40 -4
View File
@@ -1,10 +1,12 @@
import { Places } from '../../db/entities/Places.entity';
import { TourActivities } from '../../db/entities/TourActivities.entity';
import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
import { TourTypes } from '../../db/entities/TourTypes.entity';
import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
import { Tours } from '../../db/entities/Tours.entity';
import { TOUR_HIKING_PREFERENCES, TOUR_TRACK_MARKS } from '../../db/json-columns';
import type { PlacesRepository } from '../../db/repositories/Places.repository';
import type { TourActivitiesRepository, TourActivityRefRow } from '../../db/repositories/TourActivities.repository';
import type { TourStationVisitsRepository } from '../../db/repositories/TourStationVisits.repository';
import type { TourTypesRepository } from '../../db/repositories/TourTypes.repository';
import type {
@@ -19,12 +21,14 @@ import type {
ToursRepository,
TourUpdate,
} from '../../db/repositories/Tours.repository';
import { utcSuffix } from '../../db/types';
import { decodeJson, encodeJson } from '../../utils/json-column';
import { badRequest, DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { PlaceImportService } from '../place-import/place-import.service';
import { PlacesService } from '../places/places.service';
import { activityFacts, toActivity, trackTimesFor } from './tour-activities.helpers';
import { TourPaddleCheckService } from './tour-paddle-check.service';
import { advanceTourRevision } from './tour-revision';
import { toVisit } from './tour-visits.service';
@@ -160,12 +164,20 @@ export class ToursService {
@InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,
@InjectRepository(TourStationVisits) private readonly visitsRepo: TourStationVisitsRepository,
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
@InjectRepository(TourActivities) private readonly activitiesRepo: TourActivitiesRepository,
private readonly placeImport: PlaceImportService,
private readonly paddleChecks: TourPaddleCheckService,
) {}
/** A tour as it is listed; a city walk with the stations its points make and their stays (CW-02, CW-03). */
private toItem(r: TourListRow, points: readonly TourWaypointRow[] = []): TourListItem {
/**
* A tour as it is listed; a city walk with the stations its points make and their stays (CW-02, CW-03),
* every tour with the recordings assigned to it and the tour it documents itself (ACT-01).
*/
private toItem(
r: TourListRow,
points: readonly TourWaypointRow[] = [],
activities: readonly TourActivityRefRow[] = [],
): TourListItem {
return {
place_id: r.place_id,
name: r.name,
@@ -204,6 +216,9 @@ export class ToursService {
hiking_preferences: decodeJson(TOUR_HIKING_PREFERENCES, r.hiking_preferences, 'tour'),
...walkStationFacts(r.tour_type, points),
route_pending: Boolean(r.route_missing) && Boolean(r.has_waypoints),
track_started_at: utcSuffix(r.track_started_at),
track_ended_at: utcSuffix(r.track_ended_at),
...activityFacts(r.place_id, activities),
};
}
@@ -287,9 +302,10 @@ export class ToursService {
if (tid === null) return [];
const rows = await this.toursRepo.listForTrip(tid);
const walkPoints = await this.walkPointsByPlace(rows);
const activities = await this.activitiesRepo.listForTrip(tid);
return await this.paddleChecks.forTrip(
tid,
rows.map((r) => this.toItem(r, walkPoints.get(r.place_id) ?? [])),
rows.map((r) => this.toItem(r, walkPoints.get(r.place_id) ?? [], activities)),
);
}
@@ -352,12 +368,21 @@ export class ToursService {
}
}
const checked = await this.paddleChecks.forTour(this.toItem(row, stored), stored, place?.route_geometry ?? null);
// ACT-01: the recordings assigned to this tour, and the assignment this tour is the recording of.
const activities = await this.activitiesRepo.listForPlace(tid, row.place_id);
const documents = await this.activitiesRepo.findByTrack(row.place_id);
const refs = documents ? [...activities, documents] : activities;
const checked = await this.paddleChecks.forTour(
this.toItem(row, stored, refs),
stored,
place?.route_geometry ?? null,
);
return {
tour: checked.item,
waypoints,
provenance: await this.provenanceOf(tid, row.place_id),
...(checked.obstacle_check ? { obstacle_check: checked.obstacle_check } : {}),
activities: activities.map(toActivity),
};
}
@@ -673,6 +698,9 @@ export class ToursService {
// A copy of a copy names where the first one came from.
taken_over_from_trip_title: how.takenOverFrom?.tripTitle ?? provenance.taken_over_from_trip_title,
taken_over_from_tour_name: how.takenOverFrom?.tourName ?? provenance.taken_over_from_tour_name,
// A copy of a recording was recorded when it was; the assignments stay with the tours they joined.
track_started_at: row.track_started_at,
track_ended_at: row.track_ended_at,
});
// A stop standing for a place of the source trip stands for nothing in another trip.
await this.waypointsRepo.insertForPlace(
@@ -890,7 +918,9 @@ export class ToursService {
const result = await this.uow.transactional(async () => {
// A nested transactional, so the places and their facets commit together.
const imported = await this.places.importPreparedGpx(tripId, rows);
const times = trackTimesFor(rows, imported.places);
for (const place of imported.places) {
const recorded = times.get(place.id);
const metrics = computeTourMetrics(parseRouteGeometry(place.route_geometry));
const matchConfidence = metrics.hasElevation ? 1 : 0.3;
await this.toursRepo.insertTour({
@@ -907,6 +937,8 @@ export class ToursService {
max_hiking_difficulty: null,
origin: 'gpx',
origin_file_name: gpxFileName(fileName),
track_started_at: recorded?.started ?? null,
track_ended_at: recorded?.ended ?? null,
});
tours.push(
this.toItem({
@@ -938,6 +970,8 @@ export class ToursService {
revision: 1,
hiking_preferences: null,
winter_activity: null,
track_started_at: recorded?.started ?? null,
track_ended_at: recorded?.ended ?? null,
}),
);
}
@@ -980,6 +1014,8 @@ export class ToursService {
distance_km: metrics.distanceKm,
elevation_gain_m: metrics.elevationGainM,
elevation_loss_m: metrics.elevationLossM,
started_at: row.trackTimes?.startedAt ?? null,
ended_at: row.trackTimes?.endedAt ?? null,
duplicate: duplicates[index] ?? false,
};
}),