mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
Tours: provenance contract, source check, one assignment path and the map overview
- P2C-02: tours record their origin (planned, GPX with file name, wanderer) instead of reading it off their shape; the detail answers a provenance contract and a trip copy keeps a tour's import record - MF-03: a wanderer snapshot's source can be checked on purpose, read only, with a confirmed reimport as a new snapshot - PR1-18: every way of putting a tour on a day shares one set of rules - PR1-07/08: each person can hide tours from the trip map; the list shows each tour's line colour and the picked tour stands out on both maps
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { Collection, EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
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 { TourSources } from './TourSources.entity';
|
||||
@@ -25,11 +25,21 @@ export class Tours {
|
||||
derivedFromPlace?: Ref<Places> | null;
|
||||
derived_from_place_id?: number | null;
|
||||
recorded_route_geometry?: string | null;
|
||||
origin: TToursOrigin & Opt = ToursOrigin.TREK;
|
||||
origin_file_name?: string | null;
|
||||
tourTypeRef!: Ref<TourTypes>;
|
||||
tour_sources: Ref<TourSources> | null = null;
|
||||
tour_waypoints_collection = new Collection<TourWaypoints>(this);
|
||||
}
|
||||
|
||||
export const ToursOrigin = {
|
||||
TREK: 'trek',
|
||||
GPX: 'gpx',
|
||||
WANDERER: 'wanderer',
|
||||
} as const;
|
||||
|
||||
export type TToursOrigin = (typeof ToursOrigin)[keyof typeof ToursOrigin];
|
||||
|
||||
export const ToursSchema = defineEntity({
|
||||
class: Tours,
|
||||
repository: () => ToursRepository,
|
||||
@@ -58,6 +68,8 @@ export const ToursSchema = defineEntity({
|
||||
derivedFromPlace: () => p.manyToOne(Places).ref().nullable().hidden(),
|
||||
derived_from_place_id: p.integer().nullable().persist(false),
|
||||
recorded_route_geometry: p.text().nullable(),
|
||||
origin: p.enum(() => ToursOrigin).default('trek'),
|
||||
origin_file_name: p.text().nullable(),
|
||||
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
|
||||
tour_sources: () => p.oneToOne(TourSources).ref().mappedBy('place').hidden(),
|
||||
tour_waypoints_collection: () => p.oneToMany(TourWaypoints).mappedBy('place').hidden(),
|
||||
|
||||
@@ -18,4 +18,6 @@ export interface ToursTable {
|
||||
break_additional_minutes: InsertOptional<number | null>;
|
||||
derived_from_place_id: InsertOptional<number | null>;
|
||||
recorded_route_geometry: InsertOptional<string | null>;
|
||||
origin: InsertOptional<string>;
|
||||
origin_file_name: InsertOptional<string | null>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* Where a tour came from, recorded instead of read off its shape: planned in
|
||||
* TREK, imported from a GPX file (with the file's name) or copied in from
|
||||
* wanderer. Until now a list told a GPX import from a planned tour by whether it
|
||||
* had waypoints, which an import planned over in place no longer holds.
|
||||
*
|
||||
* The backfill is exact for every tour that can exist before this step: a
|
||||
* wanderer reference only comes from the wanderer import, and a tour without
|
||||
* stored waypoints, or one that keeps a recorded track, only from an import.
|
||||
* A GPX import's file name was never stored, so it stays unknown (NULL).
|
||||
*/
|
||||
export class Migration20200101043800_a_tour_records_where_it_came_from extends Migration {
|
||||
override name = 'Migration20200101043800_a_tour_records_where_it_came_from';
|
||||
|
||||
override up(): void {
|
||||
this.addSql(
|
||||
"ALTER TABLE tours ADD COLUMN origin TEXT NOT NULL DEFAULT 'trek' CHECK (origin IN ('trek', 'gpx', 'wanderer'))",
|
||||
);
|
||||
this.addSql('ALTER TABLE tours ADD COLUMN origin_file_name TEXT');
|
||||
this.addSql("UPDATE tours SET origin = 'wanderer' WHERE wanderer_ref IS NOT NULL");
|
||||
this.addSql(
|
||||
"UPDATE tours SET origin = 'gpx' WHERE origin = 'trek' AND (recorded_route_geometry IS NOT NULL OR NOT EXISTS (SELECT 1 FROM tour_waypoints w WHERE w.place_id = tours.place_id))",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Tours } from '../entities/Tours.entity';
|
||||
import { type Tours, type TToursOrigin, ToursOrigin } from '../entities/Tours.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import type { AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
@@ -26,6 +26,7 @@ export interface TourListRow {
|
||||
match_confidence: number | null;
|
||||
max_hiking_difficulty: number | null;
|
||||
derived_from_place_id: number | null;
|
||||
origin: string;
|
||||
has_recorded_track: number;
|
||||
planned: number;
|
||||
has_waypoints: number;
|
||||
@@ -48,6 +49,8 @@ export interface TourRow {
|
||||
max_hiking_difficulty: number | null;
|
||||
derived_from_place_id: number | null;
|
||||
recorded_route_geometry: string | null;
|
||||
origin: string;
|
||||
origin_file_name: string | null;
|
||||
}
|
||||
const _tourRowKeys: AssertRowKeys<TourRow, Tours> = true;
|
||||
|
||||
@@ -71,7 +74,32 @@ export type TourUpdate = Omit<TourInsert, 'place_id' | 'planned_duration_minutes
|
||||
break_additional_minutes?: number | null;
|
||||
};
|
||||
|
||||
type ToursKyselyDB = Pick<DB, 'tours' | 'places' | 'day_assignments' | 'tour_waypoints'>;
|
||||
type ToursKyselyDB = Pick<DB, 'tours' | 'places' | 'day_assignments' | 'tour_waypoints' | 'tour_sources'>;
|
||||
|
||||
/**
|
||||
* Where one tour came from, as the provenance contract reads it: the facet's
|
||||
* own record (origin, the GPX file name, when it was saved, the wanderer
|
||||
* reference), the import's snapshot row when there is one, and the name of the
|
||||
* import a planned tour came from while that import is still in the trip.
|
||||
*/
|
||||
export interface TourProvenanceRow {
|
||||
origin: string;
|
||||
origin_file_name: string | null;
|
||||
created_at: string | null;
|
||||
wanderer_ref: string | null;
|
||||
has_recorded_track: number;
|
||||
derived_from_place_id: number | null;
|
||||
derived_from_name: string | null;
|
||||
source_instance: string | null;
|
||||
source_external_id: string | null;
|
||||
source_external_url: string | null;
|
||||
source_external_updated: string | null;
|
||||
source_imported_at: string | null;
|
||||
source_content_hash: string | null;
|
||||
source_local_hash: string | null;
|
||||
route_geometry: string | null;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* `tours` — the facet that makes a place a tour (#2586). Keyed on the owning
|
||||
@@ -110,6 +138,7 @@ export class ToursRepository extends TrekRepository<Tours> {
|
||||
't.match_confidence as match_confidence',
|
||||
't.max_hiking_difficulty as max_hiking_difficulty',
|
||||
't.derived_from_place_id as derived_from_place_id',
|
||||
't.origin as origin',
|
||||
eb('t.recorded_route_geometry', 'is not', null).as('has_recorded_track'),
|
||||
eb
|
||||
.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.place_id', '=', 'p.id'))
|
||||
@@ -141,6 +170,79 @@ export class ToursRepository extends TrekRepository<Tours> {
|
||||
return row ? toListRow(row) : undefined;
|
||||
}
|
||||
|
||||
/** Where a tour of this trip came from; `undefined` unless the place is a tour of that trip. */
|
||||
async findProvenance(trip_id: number, place_id: number): Promise<TourProvenanceRow | undefined> {
|
||||
return await this.db()
|
||||
.selectFrom('tours as t')
|
||||
.innerJoin('places as p', 'p.id', 't.place_id')
|
||||
.leftJoin('tour_sources as s', 's.place_id', 't.place_id')
|
||||
.leftJoin('places as d', (join) =>
|
||||
join.onRef('d.id', '=', 't.derived_from_place_id').on('d.trip_id', '=', trip_id),
|
||||
)
|
||||
.select((eb) => [
|
||||
't.origin as origin',
|
||||
't.origin_file_name as origin_file_name',
|
||||
't.created_at as created_at',
|
||||
't.wanderer_ref as wanderer_ref',
|
||||
eb('t.recorded_route_geometry', 'is not', null).as('has_recorded_track'),
|
||||
't.derived_from_place_id as derived_from_place_id',
|
||||
'd.name as derived_from_name',
|
||||
's.instance as source_instance',
|
||||
's.external_id as source_external_id',
|
||||
's.external_url as source_external_url',
|
||||
's.external_updated as source_external_updated',
|
||||
's.imported_at as source_imported_at',
|
||||
's.content_hash as source_content_hash',
|
||||
's.local_hash as source_local_hash',
|
||||
'p.route_geometry as route_geometry',
|
||||
'p.name as name',
|
||||
])
|
||||
.where('p.trip_id', '=', trip_id)
|
||||
.where('p.id', '=', place_id)
|
||||
.executeTakeFirst()
|
||||
.then((row) => (row ? { ...row, has_recorded_track: Number(row.has_recorded_track) } : undefined));
|
||||
}
|
||||
|
||||
/**
|
||||
* A copied tour keeps the import record of the tour it was copied from, so a
|
||||
* trip copy still says where its imports came from and when. Nothing happens
|
||||
* for a tour without one.
|
||||
*/
|
||||
async copySource(source_place_id: number, place_id: number): Promise<void> {
|
||||
await this.db()
|
||||
.insertInto('tour_sources')
|
||||
.columns([
|
||||
'place_id',
|
||||
'provider',
|
||||
'instance',
|
||||
'external_id',
|
||||
'external_url',
|
||||
'external_updated',
|
||||
'content_hash',
|
||||
'local_hash',
|
||||
'imported_by',
|
||||
'imported_at',
|
||||
])
|
||||
.expression((eb) =>
|
||||
eb
|
||||
.selectFrom('tour_sources')
|
||||
.select((inner) => [
|
||||
inner.val(place_id).as('place_id'),
|
||||
'provider',
|
||||
'instance',
|
||||
'external_id',
|
||||
'external_url',
|
||||
'external_updated',
|
||||
'content_hash',
|
||||
'local_hash',
|
||||
'imported_by',
|
||||
'imported_at',
|
||||
])
|
||||
.where('place_id', '=', source_place_id),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** TO3 — `SELECT 1 FROM tours WHERE place_id = ?`: whether the place is a tour. */
|
||||
async existsForPlace(place_id: number): Promise<boolean> {
|
||||
const row = await this.db()
|
||||
@@ -193,15 +295,21 @@ export class ToursRepository extends TrekRepository<Tours> {
|
||||
/**
|
||||
* `wanderer_ref` and `difficulty` are set only by an import from a source that
|
||||
* carries them, `derived_from_place_id` only by a tour planned from an import.
|
||||
* `origin` says which way the tour came in (planned here unless an import
|
||||
* says otherwise), `origin_file_name` the GPX file it was read from.
|
||||
*/
|
||||
async insertTour(
|
||||
input: TourInsert & {
|
||||
wanderer_ref?: string | null;
|
||||
difficulty?: string | null;
|
||||
derived_from_place_id?: number | null;
|
||||
origin?: TToursOrigin;
|
||||
origin_file_name?: string | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
await this.insert({
|
||||
origin: input.origin ?? ToursOrigin.TREK,
|
||||
origin_file_name: input.origin_file_name ?? null,
|
||||
derivedFromPlace: input.derived_from_place_id ?? null,
|
||||
wanderer_ref: input.wanderer_ref ?? null,
|
||||
difficulty: input.difficulty ?? null,
|
||||
|
||||
@@ -10,7 +10,12 @@ import { WandererEnabledGuard } from '../wanderer/wanderer-enabled.guard';
|
||||
import { WandererImportDto, WandererSearchDto } from './dto/tours-wanderer.dto';
|
||||
import { ToursWandererService } from './tours-wanderer.service';
|
||||
import { Body, Controller, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
|
||||
import { wandererImportPreviewSchema, wandererImportResponseSchema, wandererSearchResponseSchema } from '@trek/shared';
|
||||
import {
|
||||
tourSourceCheckResponseSchema,
|
||||
wandererImportPreviewSchema,
|
||||
wandererImportResponseSchema,
|
||||
wandererSearchResponseSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* `/api/trips/:tripId/tours/wanderer`: the caller's wanderer trails, seen from
|
||||
@@ -40,6 +45,15 @@ export class ToursWandererController {
|
||||
return this.wanderer.preview(tripId, user.id, trailId);
|
||||
}
|
||||
|
||||
/** MF-03: whether the trail a wanderer snapshot came from changed since; reads, writes nothing. */
|
||||
@RequirePermission('place_edit')
|
||||
@Post('sources/:placeId/check')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(tourSourceCheckResponseSchema)
|
||||
checkSource(@Param('tripId') tripId: string, @Param('placeId') placeId: string, @CurrentUser() user: User) {
|
||||
return this.wanderer.checkSource(tripId, user.id, placeId);
|
||||
}
|
||||
|
||||
@RequirePermission('place_edit')
|
||||
@Post('import')
|
||||
@ResponseContract(wandererImportResponseSchema)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { TourSources } from '../../db/entities/TourSources.entity';
|
||||
import { Tours } from '../../db/entities/Tours.entity';
|
||||
import type { PlacesRepository } from '../../db/repositories/Places.repository';
|
||||
import type { TourSnapshotRow, TourSourcesRepository } from '../../db/repositories/TourSources.repository';
|
||||
import type { ToursRepository } from '../../db/repositories/Tours.repository';
|
||||
import type { TourProvenanceRow, ToursRepository } from '../../db/repositories/Tours.repository';
|
||||
import { thinLine } from '../../utils/polyline';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { toRowId } from '../common/row-id';
|
||||
@@ -11,7 +11,7 @@ import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { PlaceImportService } from '../place-import/place-import.service';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { WandererService } from '../wanderer/wanderer.service';
|
||||
import { computeTourMetrics, parseRouteGeometry, type GeometryPoint } from './tours.helpers';
|
||||
import { changedParts, computeTourMetrics, contentHashOf, localHashOf, parseRouteGeometry } from './tours.helpers';
|
||||
import { ToursService } from './tours.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
@@ -19,50 +19,27 @@ import type {
|
||||
WandererImportPreview,
|
||||
WandererImportRequest,
|
||||
WandererImportResponse,
|
||||
TourSourceCheckResponse,
|
||||
WandererSearchRequest,
|
||||
WandererSearchResponse,
|
||||
} from '@trek/shared';
|
||||
import { wandererDifficultyToSac } from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const PROVIDER = 'wanderer';
|
||||
/** The line the preview draws: the whole tour, thinned for the map. */
|
||||
const PREVIEW_LINE_POINTS = 800;
|
||||
|
||||
/** A short stable fingerprint of one part of a trail. */
|
||||
function fingerprint(value: unknown): string {
|
||||
return createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
/** Coordinates to five places (a metre) and heights to the metre, so a re-export with other float noise reads the same. */
|
||||
function normalizedRoute(points: readonly GeometryPoint[]): number[][] {
|
||||
return points.map(([lat, lng, ele]) =>
|
||||
ele == null ? [+lat.toFixed(5), +lng.toFixed(5)] : [+lat.toFixed(5), +lng.toFixed(5), Math.round(ele)],
|
||||
);
|
||||
}
|
||||
|
||||
/** What the source delivered, part by part: `name.description.route`. */
|
||||
function contentHashOf(name: string, description: string | null, route: readonly GeometryPoint[]): string {
|
||||
return [fingerprint(name.trim()), fingerprint((description ?? '').trim()), fingerprint(normalizedRoute(route))].join(
|
||||
'.',
|
||||
);
|
||||
}
|
||||
|
||||
/** The tour as saved here: `name.route`, to tell later whether it was edited. */
|
||||
function localHashOf(name: string, route: readonly GeometryPoint[]): string {
|
||||
return [fingerprint(name.trim()), fingerprint(normalizedRoute(route))].join('.');
|
||||
}
|
||||
|
||||
const CONTENT_PARTS = ['name', 'description', 'route'] as const;
|
||||
|
||||
function changedParts(before: string, now: string): Array<(typeof CONTENT_PARTS)[number]> {
|
||||
const a = before.split('.');
|
||||
const b = now.split('.');
|
||||
return CONTENT_PARTS.filter((_, i) => a[i] !== b[i]);
|
||||
}
|
||||
|
||||
/** The trip id the guard already resolved; a malformed one never got this far, and still answers 404. */
|
||||
/** The instance and trail a snapshot came from: its import record, else the reference the tour carries. */
|
||||
function sourceIdentity(row: TourProvenanceRow): { instance: string; externalId: string } {
|
||||
if (row.source_instance !== null && row.source_external_id !== null) {
|
||||
return { instance: row.source_instance, externalId: row.source_external_id };
|
||||
}
|
||||
const ref = row.wanderer_ref ?? '';
|
||||
const at = ref.lastIndexOf('#');
|
||||
return { instance: ref.slice(0, Math.max(at, 0)), externalId: ref.slice(at + 1) };
|
||||
}
|
||||
|
||||
function tripRowId(tripId: string): number {
|
||||
const tid = toRowId(tripId);
|
||||
if (tid === null) throw new DomainError(404, 'Trip not found');
|
||||
@@ -155,6 +132,58 @@ export class ToursWandererService {
|
||||
return await this.sources.listSnapshots(tid, PROVIDER, instance, [trailId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* MF-03: ask the source of one wanderer snapshot whether the trail changed
|
||||
* since it came in, on the caller's own connection. Reads only: the
|
||||
* snapshot stays as it is whatever the source says, and taking a change
|
||||
* over is the confirmed reimport, with the hash this answer carries.
|
||||
*/
|
||||
async checkSource(tripId: string, userId: number, placeId: string): Promise<TourSourceCheckResponse> {
|
||||
const tid = tripRowId(tripId);
|
||||
const pid = toRowId(placeId);
|
||||
const row = pid === null ? undefined : await this.toursRepo.findProvenance(tid, pid);
|
||||
if (!row) throw new DomainError(404, 'Tour not found');
|
||||
if (row.origin !== 'wanderer') {
|
||||
throw new DomainError(400, 'This tour has no wanderer source', {
|
||||
code: 'wanderer_no_source',
|
||||
details: { code: 'no_source' },
|
||||
});
|
||||
}
|
||||
const { instance, externalId } = sourceIdentity(row);
|
||||
const editedLocally =
|
||||
row.source_local_hash === null
|
||||
? null
|
||||
: localHashOf(row.name, parseRouteGeometry(row.route_geometry)) !== row.source_local_hash;
|
||||
const answer = (state: TourSourceCheckResponse['state']): TourSourceCheckResponse => ({
|
||||
state,
|
||||
changes: [],
|
||||
externalUpdated: null,
|
||||
importedUpdated: row.source_external_updated,
|
||||
editedLocally,
|
||||
reimport: null,
|
||||
});
|
||||
|
||||
const connected = await this.wanderer.getConnection(userId);
|
||||
if (!connected.connected) return answer('not_connected');
|
||||
if ((await this.wanderer.instanceOf(userId)) !== instance) return answer('other_instance');
|
||||
let fetched: Awaited<ReturnType<ToursWandererService['fetchTrail']>>;
|
||||
try {
|
||||
fetched = await this.fetchTrail(userId, externalId);
|
||||
} catch (err: unknown) {
|
||||
// Gone, or no longer the caller's to read: said as such, the snapshot is not touched.
|
||||
if (err instanceof DomainError && (err.getStatus() === 404 || err.getStatus() === 403))
|
||||
return answer('unavailable');
|
||||
throw err;
|
||||
}
|
||||
const reimport = { trailId: externalId, contentHash: fetched.contentHash };
|
||||
const externalUpdated = fetched.trail.updated ?? null;
|
||||
if (row.source_content_hash === null) return { ...answer('unknown'), externalUpdated, reimport };
|
||||
const changes = changedParts(row.source_content_hash, fetched.contentHash);
|
||||
return changes.length === 0
|
||||
? { ...answer('unchanged'), externalUpdated }
|
||||
: { ...answer('changed'), changes, externalUpdated, reimport };
|
||||
}
|
||||
|
||||
async preview(tripId: string, userId: number, trailId: string): Promise<WandererImportPreview> {
|
||||
const tid = tripRowId(tripId);
|
||||
const fetched = await this.fetchTrail(userId, trailId);
|
||||
@@ -242,6 +271,7 @@ export class ToursWandererService {
|
||||
max_hiking_difficulty: wandererDifficultyToSac(fetched.summary.difficulty),
|
||||
wanderer_ref: `${fetched.instance}#${trailId}`,
|
||||
difficulty: fetched.summary.difficulty,
|
||||
origin: 'wanderer',
|
||||
});
|
||||
await this.sources.insertSource({
|
||||
place_id: id,
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
*/
|
||||
import type { GeometryPoint } from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
// The metrics are shared with the client, which computes them for a tour saved offline.
|
||||
export { computeTourMetrics, type GeometryPoint, type TourMetrics } from '@trek/shared';
|
||||
|
||||
@@ -30,3 +32,35 @@ export function parseRouteGeometry(routeGeometry: string | null | undefined): Ge
|
||||
|
||||
/** Confidence threshold: below this, the tour imports with a caution flag. */
|
||||
export const LOW_CONFIDENCE_THRESHOLD = 0.5;
|
||||
|
||||
/** A short stable fingerprint of one part of a trail. */
|
||||
function fingerprint(value: unknown): string {
|
||||
return createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
/** Coordinates to five places (a metre) and heights to the metre, so a re-export with other float noise reads the same. */
|
||||
function normalizedRoute(points: readonly GeometryPoint[]): number[][] {
|
||||
return points.map(([lat, lng, ele]) =>
|
||||
ele == null ? [+lat.toFixed(5), +lng.toFixed(5)] : [+lat.toFixed(5), +lng.toFixed(5), Math.round(ele)],
|
||||
);
|
||||
}
|
||||
|
||||
/** What the source delivered, part by part: `name.description.route`. */
|
||||
export function contentHashOf(name: string, description: string | null, route: readonly GeometryPoint[]): string {
|
||||
return [fingerprint(name.trim()), fingerprint((description ?? '').trim()), fingerprint(normalizedRoute(route))].join(
|
||||
'.',
|
||||
);
|
||||
}
|
||||
|
||||
/** The tour as saved here: `name.route`, to tell later whether it was edited. */
|
||||
export function localHashOf(name: string, route: readonly GeometryPoint[]): string {
|
||||
return [fingerprint(name.trim()), fingerprint(normalizedRoute(route))].join('.');
|
||||
}
|
||||
|
||||
const CONTENT_PARTS = ['name', 'description', 'route'] as const;
|
||||
|
||||
export function changedParts(before: string, now: string): Array<(typeof CONTENT_PARTS)[number]> {
|
||||
const a = before.split('.');
|
||||
const b = now.split('.');
|
||||
return CONTENT_PARTS.filter((_, i) => a[i] !== b[i]);
|
||||
}
|
||||
|
||||
@@ -5,13 +5,24 @@ import { Tours } from '../../db/entities/Tours.entity';
|
||||
import type { PlacesRepository } from '../../db/repositories/Places.repository';
|
||||
import type { TourTypesRepository } from '../../db/repositories/TourTypes.repository';
|
||||
import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
|
||||
import type { TourListRow, ToursRepository, TourUpdate } from '../../db/repositories/Tours.repository';
|
||||
import type {
|
||||
TourListRow,
|
||||
TourProvenanceRow,
|
||||
ToursRepository,
|
||||
TourUpdate,
|
||||
} 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 { PlaceImportService } from '../place-import/place-import.service';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { computeTourMetrics, parseRouteGeometry, LOW_CONFIDENCE_THRESHOLD, type GeometryPoint } from './tours.helpers';
|
||||
import {
|
||||
computeTourMetrics,
|
||||
localHashOf,
|
||||
parseRouteGeometry,
|
||||
LOW_CONFIDENCE_THRESHOLD,
|
||||
type GeometryPoint,
|
||||
} from './tours.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { BadRequestException, Injectable, Logger, NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
@@ -22,6 +33,9 @@ import {
|
||||
type TourCreateResponse,
|
||||
type TourDetailResponse,
|
||||
type TourListItem,
|
||||
type TourOrigin,
|
||||
type TourProvenance,
|
||||
type TourProvenanceSource,
|
||||
type TourWaypoint,
|
||||
type WandererDifficulty,
|
||||
wandererDifficultyToSac,
|
||||
@@ -72,6 +86,7 @@ export class ToursService {
|
||||
match_confidence: r.match_confidence,
|
||||
max_hiking_difficulty: r.max_hiking_difficulty,
|
||||
derived_from_place_id: r.derived_from_place_id,
|
||||
origin: r.origin as TourOrigin,
|
||||
has_recorded_track: Boolean(r.has_recorded_track),
|
||||
planned: Boolean(r.planned),
|
||||
caution: r.match_confidence !== null && r.match_confidence < LOW_CONFIDENCE_THRESHOLD,
|
||||
@@ -168,7 +183,33 @@ export class ToursService {
|
||||
}
|
||||
}
|
||||
|
||||
return { tour: this.toItem(row), waypoints };
|
||||
return { tour: this.toItem(row), waypoints, provenance: await this.provenanceOf(tid!, row.place_id) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a tour came from (P2C-02): the origin it was saved with, what its
|
||||
* source carried, the import it was planned from, and whether it still
|
||||
* matches the import. Nothing here is guessed: a field the tour never
|
||||
* recorded stays null.
|
||||
*/
|
||||
private async provenanceOf(tripId: number, placeId: number): Promise<TourProvenance> {
|
||||
const row = await this.toursRepo.findProvenance(tripId, placeId);
|
||||
if (!row) throw new NotFoundException('Tour not found');
|
||||
const origin = row.origin as TourOrigin;
|
||||
return {
|
||||
origin,
|
||||
createdAt: row.created_at,
|
||||
source: provenanceSource(origin, row),
|
||||
derivedFrom:
|
||||
row.derived_from_place_id !== null && row.derived_from_name !== null
|
||||
? { placeId: row.derived_from_place_id, name: row.derived_from_name }
|
||||
: null,
|
||||
plannedOver: row.has_recorded_track === 1,
|
||||
editedLocally:
|
||||
origin === 'wanderer' && row.source_local_hash !== null
|
||||
? localHashOf(row.name, parseRouteGeometry(row.route_geometry)) !== row.source_local_hash
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Create the owning Place, Tours facet, and ordered control points as one write. */
|
||||
@@ -187,7 +228,7 @@ export class ToursService {
|
||||
// read in the write so it cannot go meanwhile.
|
||||
if (derivedFrom !== null) {
|
||||
const source = await this.toursRepo.findInTrip(tid, derivedFrom);
|
||||
if (!source || source.has_waypoints) {
|
||||
if (!source || source.origin === 'trek' || source.has_waypoints) {
|
||||
throw new DomainError(400, 'derived_from_place_id is not an imported tour of this trip');
|
||||
}
|
||||
}
|
||||
@@ -224,7 +265,7 @@ export class ToursService {
|
||||
} catch {
|
||||
this.logger.warn(`Committed Tour ${placeId}: place notification failed`);
|
||||
}
|
||||
return { tour: this.toItem(row), waypoints };
|
||||
return { tour: this.toItem(row), waypoints, provenance: await this.provenanceOf(tid, placeId) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -360,14 +401,14 @@ export class ToursService {
|
||||
async importGpxAsTour(
|
||||
tripId: string,
|
||||
fileBuffer: Buffer,
|
||||
defaultName?: string,
|
||||
fileName?: string,
|
||||
socketId?: string,
|
||||
): Promise<ImportGpxAsTourResult | null> {
|
||||
const rows = this.placeImport.readGpx(fileBuffer, {
|
||||
importWaypoints: false,
|
||||
importRoutes: true,
|
||||
importTracks: true,
|
||||
defaultName,
|
||||
defaultName: fileName,
|
||||
});
|
||||
if (rows.length === 0) return null;
|
||||
|
||||
@@ -389,6 +430,8 @@ export class ToursService {
|
||||
break_additional_minutes: null,
|
||||
match_confidence: matchConfidence,
|
||||
max_hiking_difficulty: null,
|
||||
origin: 'gpx',
|
||||
origin_file_name: gpxFileName(fileName),
|
||||
});
|
||||
tours.push(
|
||||
this.toItem({
|
||||
@@ -408,6 +451,7 @@ export class ToursService {
|
||||
match_confidence: matchConfidence,
|
||||
max_hiking_difficulty: null,
|
||||
derived_from_place_id: null,
|
||||
origin: 'gpx',
|
||||
has_recorded_track: 0,
|
||||
planned: 0,
|
||||
has_waypoints: 0,
|
||||
@@ -433,3 +477,32 @@ export class ToursService {
|
||||
return { tours, caution: tours.some((t) => t.caution), skipped: result.skipped };
|
||||
}
|
||||
}
|
||||
|
||||
/** The file name a GPX import keeps: the name as uploaded, without a path, cut to what the column shows. */
|
||||
function gpxFileName(name: string | undefined): string | null {
|
||||
const base = name?.split(/[\/]/).pop()?.trim();
|
||||
return base ? base.slice(0, 255) : null;
|
||||
}
|
||||
|
||||
/** What the source of a tour carried, read from the tour's own record and its import's snapshot row. */
|
||||
function provenanceSource(origin: TourOrigin, row: TourProvenanceRow): TourProvenanceSource {
|
||||
if (origin === 'gpx') return { kind: 'gpx', fileName: row.origin_file_name };
|
||||
if (origin === 'wanderer') {
|
||||
// The reference `instance#trail` is on the tour itself, so a snapshot whose row is missing still names its source.
|
||||
const [refInstance, refTrail] = splitWandererRef(row.wanderer_ref);
|
||||
return {
|
||||
kind: 'wanderer',
|
||||
instance: row.source_instance ?? refInstance,
|
||||
externalId: row.source_external_id ?? refTrail,
|
||||
externalUrl: row.source_external_url,
|
||||
externalUpdated: row.source_external_updated,
|
||||
importedAt: row.source_imported_at,
|
||||
};
|
||||
}
|
||||
return { kind: 'trek' };
|
||||
}
|
||||
|
||||
function splitWandererRef(ref: string | null): [string, string] {
|
||||
const at = ref?.lastIndexOf('#') ?? -1;
|
||||
return ref && at > 0 ? [ref.slice(0, at), ref.slice(at + 1)] : ['', ''];
|
||||
}
|
||||
|
||||
@@ -733,17 +733,16 @@ export class TripsService {
|
||||
if (newPlaceId) await this.tagsRepo.insertIgnore(newPlaceId, [t.tag_id]); // TP47
|
||||
}
|
||||
|
||||
// A Tour is a place plus its `tours` facet and the waypoints its route was
|
||||
// planned through. Without them the copy holds an ordinary place with a
|
||||
// line on it: no longer listed as a Tour, and its route can't be edited
|
||||
// because the points it was drawn from are gone. The facet row goes first,
|
||||
// since the waypoints reference it.
|
||||
// A Tour is a place plus its `tours` facet, its import record and the waypoints its route was planned
|
||||
// through; without them the copy is a plain place with a line, no Tour, its route not editable.
|
||||
// The facet row goes first, since the waypoints and the import record reference it.
|
||||
const oldTours = await this.toursRepo.listRowsForTrip(Number(sourceTripId));
|
||||
const copiedTours = new Set<number>();
|
||||
for (const { place_id, ...tour } of oldTours) {
|
||||
const newPlaceId = placeMap.get(place_id);
|
||||
if (!newPlaceId) continue;
|
||||
await this.toursRepo.insertCopy(newPlaceId, tour, placeMap);
|
||||
await this.toursRepo.copySource(place_id, newPlaceId);
|
||||
copiedTours.add(place_id);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user