fix(tours): a tour import takes over a track imported before Tours

A GPX track imported in 4.x is a plain place: a line, no tours row. It never
showed under Tours, and importing the same file there was refused as a
duplicate by its name, so there was no way to turn it into a tour (#2810).

The tour import now takes over a track of the trip that has the same name
and is no tour yet: the place keeps its name and line and gets the tours
row, with the recorded times the file adds. The preview says so instead of
"Already in the trip". New and taken-over tracks commit in one transaction.
This commit is contained in:
Maurice
2026-10-26 12:17:15 +01:00
parent 1ecc449f3e
commit 39ebf0976c
39 changed files with 313 additions and 81 deletions
@@ -318,6 +318,21 @@ export class PlacesRepository extends TrekRepository<Places> {
return !!row;
}
/**
* The trip's tracks that are not tours: places with `route_geometry` and no
* `tours` row, oldest first. A GPX file imported before Tours existed (4.x)
* left its tracks like this, and the tour import takes one over by name
* instead of refusing it as a duplicate (#2810).
*/
async listTracksWithoutTour(trip_id: number | string): Promise<{ id: number; name: string; route_geometry: string }[]> {
return this.qb('p')
.leftJoin('p.tours', 't')
.select(['p.id', 'p.name', 'p.route_geometry'])
.where('p.trip_id = ? AND p.route_geometry IS NOT NULL AND t.place_id IS NULL', [trip_id])
.orderBy({ 'p.id': 'asc' })
.execute<{ id: number; name: string; route_geometry: string }[]>('all', false);
}
/** PL19/PL21 — `DELETE FROM places WHERE id = ?`, unscoped: every caller proved trip access first. */
async deleteById(id: number): Promise<void> {
await this.nativeDelete({ id });
+23 -1
View File
@@ -3,7 +3,7 @@ import path from 'node:path';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { resolveCountryCodeSync } from '../atlas/atlas-geo';
import { TRACK_COLORS, placeMatchStrategies, type PlaceMatchCandidate } from '@trek/shared';
import { TRACK_COLORS, normalizePlaceName, placeMatchStrategies, type PlaceMatchCandidate } from '@trek/shared';
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
import type { TripAccess } from '../../db/repositories/Trips.repository';
@@ -765,6 +765,28 @@ export class PlacesService {
});
}
/**
* The rows of a tour import that take over a track already in the trip,
* by row index: a place with a track and no tour yet, under the same name,
* one place per row. A GPX file imported before Tours existed (4.x) left
* its tracks as plain places, and the name alone made every tour import of
* the same file a duplicate with no tour to show for it (#2810).
*/
async tracksToAdopt(tripId: string, rows: PreparedGpxPlace[]): Promise<Map<number, { id: number; route_geometry: string }>> {
const byName = new Map<string, { id: number; route_geometry: string }[]>();
for (const track of await this.placesRepo.listTracksWithoutTour(tripId)) {
const key = normalizePlaceName(track.name);
if (key) byName.set(key, [...(byName.get(key) ?? []), track]);
}
const adopt = new Map<number, { id: number; route_geometry: string }>();
rows.forEach((row, index) => {
const key = normalizePlaceName(row.name);
const track = key ? byName.get(key)?.shift() : undefined;
if (track) adopt.set(index, track);
});
return adopt;
}
/**
* The id of the place on this trip that `candidate` already is, or null.
*
@@ -70,7 +70,10 @@ export function activityFacts(
}
/** 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 } {
export function recordedTimesOf(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)) }
@@ -93,7 +96,7 @@ export function trackTimesFor(
(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]));
byPlace.set(place.id, recordedTimesOf(rows[index]));
}
return byPlace;
}
+127 -75
View File
@@ -16,7 +16,7 @@ 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 { toActivity, trackTimesFor } from './tour-activities.helpers';
import { recordedTimesOf, toActivity, trackTimesFor } from './tour-activities.helpers';
import {
copiedFacet,
copyStart,
@@ -58,6 +58,30 @@ import {
wandererDifficultyToSac,
} from '@trek/shared';
/** `fn` over `items` one after the other, in order: the writes of one import share a transaction. */
async function inOrder<T, R>(items: readonly T[], fn: (item: T) => Promise<R>): Promise<R[]> {
return items.reduce<Promise<R[]>>(async (done, item) => [...(await done), await fn(item)], Promise.resolve([]));
}
/**
* What the type adds to each tour a file import makes: a bike tour and a run
* their profile, a paddle tour its boat and water, a ski track its discipline
* and technique (SKI-02). A run comes in without a pace and a ski track
* without a time: neither is worked out for them, so they stay unknown.
*/
function importedTypeFields(fields: TourGpxImportFields) {
return {
bike_profile: fields.bike_profile ?? null,
run_profile: fields.run_profile ?? null,
run_pace_seconds_per_km: null,
ski_discipline: fields.ski_discipline ?? null,
ski_technique: fields.ski_technique ?? null,
boat_type: fields.boat_type ?? null,
water_context: fields.water_context ?? null,
paddle_speed_kmh: null,
};
}
export interface ImportGpxAsTourResult {
tours: TourListItem[];
caution: boolean;
@@ -783,88 +807,38 @@ export class ToursService {
const { rows } = await readTourFile(this.placeImport, fileBuffer, fileName);
if (rows.length === 0) return null;
await this.assertTourTypeEnabled(fields.tour_type);
// What the type adds to each imported tour: a bike tour and a run their profile, a paddle tour its boat and water,
// a ski track its discipline and technique (SKI-02). A run comes in without a pace and a ski track without a
// time: neither is worked out for them, so they stay unknown.
const typeFields = {
bike_profile: fields.bike_profile ?? null,
run_profile: fields.run_profile ?? null,
run_pace_seconds_per_km: null,
ski_discipline: fields.ski_discipline ?? null,
ski_technique: fields.ski_technique ?? null,
boat_type: fields.boat_type ?? null,
water_context: fields.water_context ?? null,
paddle_speed_kmh: null,
};
const typeFields = importedTypeFields(fields);
const adopt = await this.places.tracksToAdopt(tripId, rows);
const fresh = rows.filter((_, index) => !adopt.has(index));
const tours: TourListItem[] = [];
const adopted: number[] = [];
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({
place_id: place.id,
tour_type: fields.tour_type,
...typeFields,
distance: metrics.distanceKm,
elevation_gain: metrics.elevationGainM,
elevation_loss: metrics.elevationLossM,
duration: null,
planned_duration_minutes: null,
break_additional_minutes: null,
match_confidence: matchConfidence,
max_hiking_difficulty: null,
origin: 'gpx',
origin_file_name: importFileName(fileName),
track_started_at: recorded?.started ?? null,
track_ended_at: recorded?.ended ?? null,
});
tours.push(
tourItemOf({
place_id: place.id,
name: place.name,
description: place.description ?? null,
website: place.website ?? null,
tour_type: fields.tour_type,
...typeFields,
distance: metrics.distanceKm,
elevation_gain: metrics.elevationGainM,
elevation_loss: metrics.elevationLossM,
duration: null,
planned_duration_minutes: null,
break_additional_minutes: null,
difficulty: null,
wanderer_ref: null,
match_confidence: matchConfidence,
max_hiking_difficulty: null,
derived_from_place_id: null,
origin: 'gpx',
portage_speed_kmh: null,
paddle_lake_style: null,
track_marks: null,
has_recorded_track: 0,
planned: 0,
has_waypoints: 0,
stage_ends: 0,
route_missing: 0,
revision: 1,
hiking_preferences: null,
track_started_at: recorded?.started ?? null,
track_ended_at: recorded?.ended ?? null,
}),
);
}
const imported =
fresh.length > 0 ? await this.places.importPreparedGpx(tripId, fresh) : { places: [], count: 0, skipped: 0 };
const times = trackTimesFor(fresh, imported.places);
tours.push(
...(await inOrder(imported.places, (place) =>
this.insertImportedTour(place, place.route_geometry ?? null, times.get(place.id), fields, typeFields, fileName),
)),
);
// A track from before Tours keeps its place and its line and becomes the
// tour; the file adds the recorded times 4.x never stored.
await inOrder([...adopt], async ([index, track]) => {
const place = await this.places.get(tripId, String(track.id));
if (!place) return;
const recorded = recordedTimesOf(rows[index]);
tours.push(await this.insertImportedTour(place, track.route_geometry, recorded, fields, typeFields, fileName));
adopted.push(place.id);
});
return imported;
});
if (result.places.length === 0) return { tours: [], caution: false, skipped: result.skipped };
if (tours.length === 0) return { tours: [], caution: false, skipped: result.skipped };
this.broadcastToursChanged(
tripId,
result.places.map((place) => place.id),
tours.map((tour) => tour.place_id),
socketId,
);
for (const place of result.places) {
@@ -874,9 +848,85 @@ export class ToursService {
this.logger.warn(`Committed GPX place ${place.id}: realtime notification failed`);
}
}
// The taken-over places now read as tours; the other clients get the row again.
await inOrder(adopted, async (id) => {
try {
const place = await this.places.get(tripId, String(id));
if (place) this.places.broadcast(tripId, 'place:updated', { place }, socketId);
} catch {
this.logger.warn(`Committed GPX tour on place ${id}: realtime notification failed`);
}
});
return { tours, caution: tours.some((t) => t.caution), skipped: result.skipped };
}
/**
* The `tours` row for one place of a GPX import, with its metrics read off
* `geometry` and the recorded times, and the list item the import answers
* with. A new place and a track taken over from before Tours (#2810) get the
* same row.
*/
private async insertImportedTour(
place: { id: number; name: string; description?: string | null; website?: string | null },
geometry: string | null,
recorded: ReturnType<typeof recordedTimesOf> | undefined,
fields: TourGpxImportFields,
typeFields: ReturnType<typeof importedTypeFields>,
fileName: string | undefined,
): Promise<TourListItem> {
const metrics = computeTourMetrics(parseRouteGeometry(geometry));
const matchConfidence = metrics.hasElevation ? 1 : 0.3;
await this.toursRepo.insertTour({
place_id: place.id,
tour_type: fields.tour_type,
...typeFields,
distance: metrics.distanceKm,
elevation_gain: metrics.elevationGainM,
elevation_loss: metrics.elevationLossM,
duration: null,
planned_duration_minutes: null,
break_additional_minutes: null,
match_confidence: matchConfidence,
max_hiking_difficulty: null,
origin: 'gpx',
origin_file_name: importFileName(fileName),
track_started_at: recorded?.started ?? null,
track_ended_at: recorded?.ended ?? null,
});
return tourItemOf({
place_id: place.id,
name: place.name,
description: place.description ?? null,
website: place.website ?? null,
tour_type: fields.tour_type,
...typeFields,
distance: metrics.distanceKm,
elevation_gain: metrics.elevationGainM,
elevation_loss: metrics.elevationLossM,
duration: null,
planned_duration_minutes: null,
break_additional_minutes: null,
difficulty: null,
wanderer_ref: null,
match_confidence: matchConfidence,
max_hiking_difficulty: null,
derived_from_place_id: null,
origin: 'gpx',
portage_speed_kmh: null,
paddle_lake_style: null,
track_marks: null,
has_recorded_track: 0,
planned: 0,
has_waypoints: 0,
stage_ends: 0,
route_missing: 0,
revision: 1,
hiking_preferences: null,
track_started_at: recorded?.started ?? null,
track_ended_at: recorded?.ended ?? null,
});
}
/**
* PAD-02: what a file would import, read with the import's own parser and
* duplicate rule and written nowhere. Null when the file holds no track or
@@ -887,6 +937,7 @@ export class ToursService {
const { rows, leftOut } = await readTourFile(this.placeImport, fileBuffer, fileName);
if (rows.length === 0) return null;
const duplicates = await this.places.gpxDuplicates(tripId, rows);
const adopt = await this.places.tracksToAdopt(tripId, rows);
return {
tracks: rows.map((row, index) => {
const geometry = parseRouteGeometry(row.routeGeometry);
@@ -900,7 +951,8 @@ export class ToursService {
elevation_loss_m: metrics.elevationLossM,
started_at: row.trackTimes?.startedAt ?? null,
ended_at: row.trackTimes?.endedAt ?? null,
duplicate: duplicates[index] ?? false,
duplicate: !adopt.has(index) && (duplicates[index] ?? false),
...(adopt.has(index) ? { adopts_track: true } : {}),
};
}),
...(leftOut ? { left_out: leftOut } : {}),