feat(tours): keep whole tours in collections and take them into trips

A saved tour can now be kept in a collection, apart from any trip, and
later made into a tour of another trip. The bookmark button in a tour's
footer and in the planner's head (waiting for the save while there are
unsaved changes) opens a dialog with every list of the user; a list they
may only read stays in it, dimmed with a lock and a tooltip. The list
keeps an independent copy: the line, the type, every measure and setting,
the waypoints in order with their roles, the origin, and the trip and tour
it was saved from as they were called then. Its days, its links to places
of the trip and its obstacle decisions stay in the trip, and later changes
to the tour do not reach the copy.

A collection shows its kept tours as cards above its places: the grade
tile with the source badge, measures and the waypoint count as badges,
the trip it came from, and who kept it. The owner or an admin of the list
can remove one after a question; tours made from it stay. "Add to a trip"
shows the kept tour on a map with its facts and numbered waypoints, lists
the user's trips (the ones they may not add tours to dimmed), and asks
outright whether the waypoints come along. "Line only" keeps the line as
saved and adds no waypoints; a tour kept without a line can only bring
them. The new tour has an id of its own, no days and no new places, and
names the trip and tour it was saved from; the dialog then offers to open
that trip. Neither the collection nor the original tour changes.

On the server the kept tours are a table of their own in the tours domain
(collection_tours, migration 046100), each row written whole once. Every
copy, the in-trip "save as new tour", the take-over from another trip and
both directions here, now goes through one copy model (tour-copy.helpers)
instead of a second one. Reading and removing follow the collection's
roles, keeping one also needs access to the source trip, and taking one
over needs place_edit on the target trip; the kept tour is read again
inside the write, so one removed meanwhile leaves no half-made tour. The
MCP tools list_collection_tours, get_collection_tour,
save_tour_to_collection, take_over_collection_tour and
delete_collection_tour run over the same service and checks. All 27
locales carry the new strings, and the wiki describes the flow.
This commit is contained in:
Maurice
2026-10-20 13:15:42 +02:00
parent 3659297af1
commit 3fe34061fd
85 changed files with 6144 additions and 181 deletions
@@ -0,0 +1,101 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { CollectionToursRepository } from '../repositories/CollectionTours.repository';
import { DbTimestampType } from '../types';
import { Collections } from './Collections.entity';
import { TourTypes } from './TourTypes.entity';
import { Users } from './Users.entity';
export class CollectionTours {
[EntityRepositoryType]?: CollectionToursRepository;
id!: number & Opt;
collection!: Ref<Collections>;
collection_id!: number;
saved_by?: number | null;
name!: string;
description?: string | null;
website?: string | null;
route_geometry?: string | null;
waypoints!: string;
tour_type!: string;
distance?: number | null;
elevation_gain?: number | null;
elevation_loss?: number | null;
duration?: number | null;
planned_duration_minutes?: number | null;
break_additional_minutes?: number | null;
difficulty?: string | null;
wanderer_ref?: string | null;
match_confidence?: number | null;
max_hiking_difficulty?: number | null;
bike_profile?: string | null;
winter_activity?: string | null;
run_profile?: string | null;
run_pace_seconds_per_km?: number | null;
ski_discipline?: string | null;
ski_technique?: string | null;
boat_type?: string | null;
water_context?: string | null;
paddle_speed_kmh?: number | null;
portage_speed_kmh?: number | null;
paddle_lake_style?: string | null;
track_marks?: string | null;
hiking_preferences?: string | null;
origin!: string;
origin_file_name?: string | null;
track_started_at?: string | null;
track_ended_at?: string | null;
source_trip_title!: string;
source_tour_name!: string;
created_at!: string & Opt;
savedByRef?: Ref<Users> | null;
tourTypeRef!: Ref<TourTypes>;
}
export const CollectionToursSchema = defineEntity({
class: CollectionTours,
repository: () => CollectionToursRepository,
properties: {
id: p.integer().primary(),
collection: () => p.manyToOne(Collections).ref().deleteRule('cascade').hidden().index('idx_collection_tours_collection'),
collection_id: p.integer().persist(false).index('idx_collection_tours_collection'),
saved_by: p.integer().nullable().persist(false).index('idx_collection_tours_saved_by'),
name: p.text(),
description: p.text().nullable(),
website: p.text().nullable(),
route_geometry: p.text().nullable(),
waypoints: p.text(),
tour_type: p.text().persist(false).index('idx_collection_tours_tour_type'),
distance: p.double().nullable(),
elevation_gain: p.double().nullable(),
elevation_loss: p.double().nullable(),
duration: p.double().nullable(),
planned_duration_minutes: p.integer().nullable(),
break_additional_minutes: p.integer().nullable(),
difficulty: p.text().nullable(),
wanderer_ref: p.text().nullable(),
match_confidence: p.double().nullable(),
max_hiking_difficulty: p.integer().nullable(),
bike_profile: p.text().nullable(),
winter_activity: p.text().nullable(),
run_profile: p.text().nullable(),
run_pace_seconds_per_km: p.integer().nullable(),
ski_discipline: p.text().nullable(),
ski_technique: p.text().nullable(),
boat_type: p.text().nullable(),
water_context: p.text().nullable(),
paddle_speed_kmh: p.double().nullable(),
portage_speed_kmh: p.double().nullable(),
paddle_lake_style: p.text().nullable(),
track_marks: p.text().nullable(),
hiking_preferences: p.text().nullable(),
origin: p.text(),
origin_file_name: p.text().nullable(),
track_started_at: p.type(DbTimestampType).nullable(),
track_ended_at: p.type(DbTimestampType).nullable(),
source_trip_title: p.text(),
source_tour_name: p.text(),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
savedByRef: () => p.manyToOne(Users).ref().joinColumn('saved_by').nullable().hidden().index('idx_collection_tours_saved_by'),
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_collection_tours_tour_type'),
},
});
@@ -4,6 +4,7 @@ import { DbTimestampType } from '../types';
import { CollectionLabels } from './CollectionLabels.entity';
import { CollectionMembers } from './CollectionMembers.entity';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { CollectionTours } from './CollectionTours.entity';
import { Users } from './Users.entity';
export class Collections {
@@ -23,6 +24,7 @@ export class Collections {
collection_labels_collection = new Collection<CollectionLabels>(this);
collection_members_collection = new Collection<CollectionMembers>(this);
collection_places_collection = new Collection<CollectionPlaces>(this);
collection_tours_collection = new Collection<CollectionTours>(this);
}
export const CollectionsSchema = defineEntity({
@@ -44,5 +46,6 @@ export const CollectionsSchema = defineEntity({
collection_labels_collection: () => p.oneToMany(CollectionLabels).mappedBy('collection').hidden(),
collection_members_collection: () => p.oneToMany(CollectionMembers).mappedBy('collection').hidden(),
collection_places_collection: () => p.oneToMany(CollectionPlaces).mappedBy('collection').hidden(),
collection_tours_collection: () => p.oneToMany(CollectionTours).mappedBy('collection').hidden(),
},
});
@@ -1,5 +1,6 @@
import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, defineEntity, p } from '@mikro-orm/core';
import { TourTypesRepository } from '../repositories/TourTypes.repository';
import { CollectionTours } from './CollectionTours.entity';
import { Tours } from './Tours.entity';
export class TourTypes {
@@ -13,6 +14,7 @@ export class TourTypes {
is_sport: number & Opt = 1;
enabled: number & Opt = 1;
sort_order: number & Opt = 0;
collection_tours_collection = new Collection<CollectionTours>(this);
tours_collection = new Collection<Tours>(this);
}
@@ -28,6 +30,7 @@ export const TourTypesSchema = defineEntity({
is_sport: p.integer().default(1),
enabled: p.integer().default(1),
sort_order: p.integer().default(0),
collection_tours_collection: () => p.oneToMany(CollectionTours).mappedBy('tourTypeRef').hidden(),
tours_collection: () => p.oneToMany(Tours).mappedBy('tourTypeRef').hidden(),
},
});
+3
View File
@@ -18,6 +18,7 @@ import { CollabPolls } from './CollabPolls.entity';
import { CollectionMembers } from './CollectionMembers.entity';
import { CollectionPlaceRatings } from './CollectionPlaceRatings.entity';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { CollectionTours } from './CollectionTours.entity';
import { Collections } from './Collections.entity';
import { DawarichConnections } from './DawarichConnections.entity';
import { DawarichVisitSuggestions } from './DawarichVisitSuggestions.entity';
@@ -142,6 +143,7 @@ export class Users {
collection_place_ratings_collection = new Collection<CollectionPlaceRatings>(this);
collection_places_collection = new Collection<CollectionPlaces>(this);
collection_places_collection1 = new Collection<CollectionPlaces>(this);
collection_tours_collection = new Collection<CollectionTours>(this);
collections_collection = new Collection<Collections>(this);
dawarich_connections: Ref<DawarichConnections> | null = null;
dawarich_visit_suggestions_collection = new Collection<DawarichVisitSuggestions>(this);
@@ -289,6 +291,7 @@ export const UsersSchema = defineEntity({
collection_place_ratings_collection: () => p.oneToMany(CollectionPlaceRatings).mappedBy('user').hidden(),
collection_places_collection: () => p.oneToMany(CollectionPlaces).mappedBy('owner').hidden(),
collection_places_collection1: () => p.oneToMany(CollectionPlaces).mappedBy('savedByRef').hidden(),
collection_tours_collection: () => p.oneToMany(CollectionTours).mappedBy('savedByRef').hidden(),
collections_collection: () => p.oneToMany(Collections).mappedBy('owner').hidden(),
dawarich_connections: () => p.oneToOne(DawarichConnections).ref().mappedBy('user').hidden(),
dawarich_visit_suggestions_collection: () => p.oneToMany(DawarichVisitSuggestions).mappedBy('user').hidden(),
+2
View File
@@ -20,6 +20,7 @@ import { CollectionLabelsSchema } from './CollectionLabels.entity';
import { CollectionMembersSchema } from './CollectionMembers.entity';
import { CollectionPlaceRatingsSchema } from './CollectionPlaceRatings.entity';
import { CollectionPlacesSchema } from './CollectionPlaces.entity';
import { CollectionToursSchema } from './CollectionTours.entity';
import { CollectionsSchema } from './Collections.entity';
import { DawarichConnectionsSchema } from './DawarichConnections.entity';
import { DawarichVisitSuggestionsSchema } from './DawarichVisitSuggestions.entity';
@@ -168,6 +169,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
CollectionMembersSchema,
CollectionPlaceRatingsSchema,
CollectionPlacesSchema,
CollectionToursSchema,
CollectionsSchema,
DawarichConnectionsSchema,
DawarichVisitSuggestionsSchema,
+11
View File
@@ -267,3 +267,14 @@ export const TOUR_CHANGE_STEP_BEFORE: JsonColumn<TourChangeStepBefore | null> =
.nullable(),
fallback: () => null,
};
/**
* LIB-03: the control points of a tour kept in a collection, in route order,
* as they were when it was saved. A broken row reads as none and is logged;
* the line is kept in a column of its own and stays as it was.
*/
export const COLLECTION_TOUR_WAYPOINTS: JsonColumn<TourWaypoint[]> = {
column: 'collection_tours.waypoints',
schema: z.array(tourWaypointSchema),
fallback: () => [],
};
@@ -0,0 +1,45 @@
// 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 CollectionToursTable {
id: InsertOptional<number>;
collection_id: number;
saved_by: InsertOptional<number | null>;
name: string;
description: InsertOptional<string | null>;
website: InsertOptional<string | null>;
route_geometry: InsertOptional<string | null>;
waypoints: string;
tour_type: string;
distance: InsertOptional<number | null>;
elevation_gain: InsertOptional<number | null>;
elevation_loss: InsertOptional<number | null>;
duration: InsertOptional<number | null>;
planned_duration_minutes: InsertOptional<number | null>;
break_additional_minutes: InsertOptional<number | null>;
difficulty: InsertOptional<string | null>;
wanderer_ref: InsertOptional<string | null>;
match_confidence: InsertOptional<number | null>;
max_hiking_difficulty: InsertOptional<number | null>;
bike_profile: InsertOptional<string | null>;
winter_activity: InsertOptional<string | null>;
run_profile: InsertOptional<string | null>;
run_pace_seconds_per_km: InsertOptional<number | null>;
ski_discipline: InsertOptional<string | null>;
ski_technique: InsertOptional<string | null>;
boat_type: InsertOptional<string | null>;
water_context: InsertOptional<string | null>;
paddle_speed_kmh: InsertOptional<number | null>;
portage_speed_kmh: InsertOptional<number | null>;
paddle_lake_style: InsertOptional<string | null>;
track_marks: InsertOptional<string | null>;
hiking_preferences: InsertOptional<string | null>;
origin: string;
origin_file_name: InsertOptional<string | null>;
track_started_at: InsertOptional<string | null>;
track_ended_at: InsertOptional<string | null>;
source_trip_title: string;
source_tour_name: string;
created_at: InsertOptional<string>;
}
+2
View File
@@ -23,6 +23,7 @@ import type { CollectionPlaceLabelsTable } from './CollectionPlaceLabels.table';
import type { CollectionPlaceRatingsTable } from './CollectionPlaceRatings.table';
import type { CollectionPlaceTagsTable } from './CollectionPlaceTags.table';
import type { CollectionPlacesTable } from './CollectionPlaces.table';
import type { CollectionToursTable } from './CollectionTours.table';
import type { CollectionsTable } from './Collections.table';
import type { DawarichConnectionsTable } from './DawarichConnections.table';
import type { DawarichVisitSuggestionsTable } from './DawarichVisitSuggestions.table';
@@ -177,6 +178,7 @@ export interface DB {
collection_place_ratings: CollectionPlaceRatingsTable;
collection_place_tags: CollectionPlaceTagsTable;
collection_places: CollectionPlacesTable;
collection_tours: CollectionToursTable;
collections: CollectionsTable;
dawarich_connections: DawarichConnectionsTable;
dawarich_visit_suggestions: DawarichVisitSuggestionsTable;
@@ -0,0 +1,64 @@
import { Migration } from '@mikro-orm/migrations';
/**
* LIB-03: a collection keeps whole tours beside its places. Each row is an
* independent snapshot of a tour as it was saved: the line, the type, every
* measure and setting of the `tours` facet, and its control points as one
* JSON array in route order. Nothing points back at the tour it came from;
* the trip's title and the tour's name are kept as text, as written then,
* because the trip may be deleted, renamed or out of a member's reach later.
* `saved_by` names who kept it and turns unknown when that account goes. The
* rows go with their collection.
*/
export class Migration20200101046100_a_collection_keeps_whole_tours extends Migration {
override name = 'Migration20200101046100_a_collection_keeps_whole_tours';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS collection_tours (
id INTEGER PRIMARY KEY,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
saved_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
name TEXT NOT NULL,
description TEXT,
website TEXT,
route_geometry TEXT,
waypoints TEXT NOT NULL,
tour_type TEXT NOT NULL REFERENCES tour_types(key),
distance REAL,
elevation_gain REAL,
elevation_loss REAL,
duration REAL,
planned_duration_minutes INTEGER,
break_additional_minutes INTEGER,
difficulty TEXT,
wanderer_ref TEXT,
match_confidence REAL,
max_hiking_difficulty INTEGER,
bike_profile TEXT,
winter_activity TEXT,
run_profile TEXT,
run_pace_seconds_per_km INTEGER,
ski_discipline TEXT,
ski_technique TEXT,
boat_type TEXT,
water_context TEXT,
paddle_speed_kmh REAL,
portage_speed_kmh REAL,
paddle_lake_style TEXT,
track_marks TEXT,
hiking_preferences TEXT,
origin TEXT NOT NULL,
origin_file_name TEXT,
track_started_at DATETIME,
track_ended_at DATETIME,
source_trip_title TEXT NOT NULL,
source_tour_name TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_collection_tours_collection ON collection_tours(collection_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_collection_tours_saved_by ON collection_tours(saved_by)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_collection_tours_tour_type ON collection_tours(tour_type)');
}
}
@@ -0,0 +1,148 @@
import { decodeJson } from '../../utils/json-column';
import type { CollectionTours } from '../entities/CollectionTours.entity';
import { COLLECTION_TOUR_WAYPOINTS } from '../json-columns';
import type { DB } from '../kysely/db';
import type { TourWaypointRow } from './TourWaypoints.repository';
import { TrekRepository } from './_shared/trek-repository';
/**
* LIB-03: a tour kept in a collection, every column as stored but its control
* points, which come decoded in route order, and the name of who saved it
* (null once that account is gone).
*/
export interface CollectionTourRow {
id: number;
collection_id: number;
saved_by: number | null;
saved_by_name: string | null;
name: string;
description: string | null;
website: string | null;
route_geometry: string | null;
waypoints: TourWaypointRow[];
tour_type: string;
distance: number | null;
elevation_gain: number | null;
elevation_loss: number | null;
duration: number | null;
planned_duration_minutes: number | null;
break_additional_minutes: number | null;
difficulty: string | null;
wanderer_ref: string | null;
match_confidence: number | null;
max_hiking_difficulty: number | null;
bike_profile: string | null;
winter_activity: string | null;
run_profile: string | null;
run_pace_seconds_per_km: number | null;
ski_discipline: string | null;
ski_technique: string | null;
boat_type: string | null;
water_context: string | null;
paddle_speed_kmh: number | null;
portage_speed_kmh: number | null;
paddle_lake_style: string | null;
track_marks: string | null;
hiking_preferences: string | null;
origin: string;
origin_file_name: string | null;
track_started_at: string | null;
track_ended_at: string | null;
source_trip_title: string;
source_tour_name: string;
created_at: string;
}
/**
* What saving a tour into a collection writes: the whole snapshot, written
* once and never changed, its points already encoded for their column
* (`COLLECTION_TOUR_WAYPOINTS`) by the service that built them.
*/
export type CollectionTourInsert = Omit<CollectionTourRow, 'id' | 'saved_by_name' | 'created_at' | 'waypoints'> & {
waypoints: string;
};
/** A trip a kept tour could be taken into, with its owner for the permission check. */
interface CollectionTourTargetRow {
id: number;
user_id: number;
title: string;
start_date: string | null;
end_date: string | null;
}
type CollectionToursKyselyDB = Pick<DB, 'collection_tours' | 'users' | 'trips'>;
/**
* `collection_tours` (LIB-03): whole tours kept in a collection, apart from
* any trip. A row is written whole when a tour is saved and only ever read or
* deleted afterwards; it goes with its collection.
*/
export class CollectionToursRepository extends TrekRepository<CollectionTours> {
private db() {
return this.kysely<CollectionToursKyselyDB>();
}
/** The shared SELECT of {@link listForCollection} and {@link findInCollection}. */
private rowQuery() {
return this.db()
.selectFrom('collection_tours as ct')
.leftJoin('users as u', 'u.id', 'ct.saved_by')
.selectAll('ct')
.select('u.username as saved_by_name');
}
/** CT1: the tours kept in one collection, the newest first; the id breaks ties inside one second. */
async listForCollection(collection_id: number): Promise<CollectionTourRow[]> {
const rows = await this.rowQuery()
.where('ct.collection_id', '=', collection_id)
.orderBy('ct.created_at', 'desc')
.orderBy('ct.id', 'desc')
.execute();
return rows.map(readRow);
}
/** CT2: one kept tour, undefined unless it is in that collection. */
async findInCollection(collection_id: number, id: number): Promise<CollectionTourRow | undefined> {
const row = await this.rowQuery()
.where('ct.collection_id', '=', collection_id)
.where('ct.id', '=', id)
.executeTakeFirst();
return row ? readRow(row) : undefined;
}
/** CT3: keeps a snapshot in a collection and answers its id. */
async insertSnapshot(row: CollectionTourInsert): Promise<number> {
const inserted = await this.db()
.insertInto('collection_tours')
.values(row)
.returning('id')
.executeTakeFirstOrThrow();
return inserted.id;
}
/** CT4: removes a kept tour from its collection; false when it was not there. */
async deleteInCollection(collection_id: number, id: number): Promise<boolean> {
const result = await this.db()
.deleteFrom('collection_tours')
.where('collection_id', '=', collection_id)
.where('id', '=', id)
.executeTakeFirst();
return Number(result.numDeletedRows) > 0;
}
/** CT5: the given trips with their owner, title and dates, in no particular order; the caller orders them. */
async targetTrips(trip_ids: readonly number[]): Promise<CollectionTourTargetRow[]> {
if (trip_ids.length === 0) return [];
return await this.db()
.selectFrom('trips as t')
.select(['t.id', 't.user_id', 't.title', 't.start_date', 't.end_date'])
.where('t.id', 'in', [...trip_ids])
.execute();
}
}
/** A stored row as callers read it: its points decoded, a broken list read as none and logged. */
function readRow(row: Omit<CollectionTourRow, 'waypoints'> & { waypoints: string }): CollectionTourRow {
return { ...row, waypoints: decodeJson(COLLECTION_TOUR_WAYPOINTS, row.waypoints, `collection tour ${row.id}`) };
}