Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(tours): pair the tracks to take over in the tours domain, off the places list

Mauricefd818050bd7a
diff --git a/server/src/db/repositories/Places.repository.ts b/server/src/db/repositories/Places.repository.ts
index 33f59199a..2b9d8c2fb 100644
--- a/server/src/db/repositories/Places.repository.ts
+++ b/server/src/db/repositories/Places.repository.ts
@@ -318,21 +318,6 @@ 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): 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': trip_id, 'p.route_geometry': { $ne: null }, 't.place': null })
- .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 });
diff --git a/server/src/nest/places/places.service.ts b/server/src/nest/places/places.service.ts
index 30e9720a6..49414aecb 100644
--- a/server/src/nest/places/places.service.ts
+++ b/server/src/nest/places/places.service.ts
@@ -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, normalizePlaceName, placeMatchStrategies, type PlaceMatchCandidate } from '@trek/shared';
+import { TRACK_COLORS, 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,30 +765,6 @@ 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 adopt = new Map<number, { id: number; route_geometry: string }>();
- const tid = toRowId(tripId);
- if (tid === null) return adopt;
- const byName = new Map<string, { id: number; route_geometry: string }[]>();
- for (const track of await this.placesRepo.listTracksWithoutTour(tid)) {
- const key = normalizePlaceName(track.name);
- if (key) byName.set(key, [...(byName.get(key) ?? []), track]);
- }
- 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.
*
diff --git a/server/src/nest/tours/tour-track-adoption.ts b/server/src/nest/tours/tour-track-adoption.ts
new file mode 100644
index 000000000..9996fc7c7
--- /dev/null
+++ b/server/src/nest/tours/tour-track-adoption.ts
@@ -0,0 +1,42 @@
+import { normalizePlaceName } from '@trek/shared';
+
+/** A place of the trip as the places list reads it: enough to tell a track that is no tour yet. */
+export interface TripPlaceForAdoption {
+ id: number;
+ name: string;
+ route_geometry?: string | null;
+ tour_place_id?: number | null;
+}
+
+/** A track of the trip a file row takes over: its place and the line it already holds. */
+export interface AdoptedTrack {
+ id: number;
+ route_geometry: string;
+}
+
+/**
+ * The rows of a tour import that take over a track already in the trip, by
+ * row index: a place with a line and no tour yet, under the same name
+ * (trimmed, any case, the duplicate rule's own reading), one place per row
+ * and oldest first. 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).
+ */
+export function tracksToAdopt(
+ rows: ReadonlyArray<{ name: string }>,
+ places: ReadonlyArray<TripPlaceForAdoption>,
+): Map<number, AdoptedTrack> {
+ const byName = new Map<string, AdoptedTrack[]>();
+ for (const place of [...places].sort((a, b) => a.id - b.id)) {
+ const key = normalizePlaceName(place.name);
+ if (!key || !place.route_geometry || place.tour_place_id != null) continue;
+ byName.set(key, [...(byName.get(key) ?? []), { id: place.id, route_geometry: place.route_geometry }]);
+ }
+ const adopt = new Map<number, AdoptedTrack>();
+ 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;
+}
diff --git a/server/src/nest/tours/tours.service.ts b/server/src/nest/tours/tours.service.ts
index 30000e97a..ecc6b766f 100644
--- a/server/src/nest/tours/tours.service.ts
+++ b/server/src/nest/tours/tours.service.ts
@@ -29,6 +29,7 @@ import { readTourFile } from './tour-file-import.helpers';
import { provenanceSource, tourItemOf } from './tour-item.helpers';
import { TourPaddleCheckService } from './tour-paddle-check.service';
import { advanceTourRevision } from './tour-revision';
+import { tracksToAdopt } from './tour-track-adoption';
import { toVisit } from './tour-visits.service';
import { checkTourCommand, firstPointOf, importFileName, keyedWaypoints, tourRouteFields } from './tour-write.helpers';
import { computeTourMetrics, localHashOf, parseRouteGeometry, type GeometryPoint } from './tours.helpers';
@@ -809,7 +810,7 @@ export class ToursService {
await this.assertTourTypeEnabled(fields.tour_type);
const typeFields = importedTypeFields(fields);
- const adopt = await this.places.tracksToAdopt(tripId, rows);
+ const adopt = await this.adoptableTracks(tripId, rows);
const fresh = rows.filter((_, index) => !adopt.has(index));
const tours: TourListItem[] = [];
const adopted: number[] = [];
@@ -867,6 +868,11 @@ export class ToursService {
return { tours, caution: tours.some((t) => t.caution), skipped: result.skipped };
}
+ /** Which rows of a file take over a track of the trip from before Tours (#2810), read off the places list. */
+ private async adoptableTracks(tripId: string, rows: ReadonlyArray<{ name: string }>) {
+ return tracksToAdopt(rows, await this.places.list(tripId, {}));
+ }
+
/**
* 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
@@ -944,7 +950,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);
+ const adopt = await this.adoptableTracks(tripId, rows);
return {
tracks: rows.map((row, index) => {
const geometry = parseRouteGeometry(row.routeGeometry);
diff --git a/server/tests/unit/db/repositories/Places.repository.test.ts b/server/tests/unit/db/repositories/Places.repository.test.ts
index 50bc10502..1b307c3e9 100644
--- a/server/tests/unit/db/repositories/Places.repository.test.ts
+++ b/server/tests/unit/db/repositories/Places.repository.test.ts
@@ -1587,27 +1587,4 @@ describe('PlacesRepository.isTour / listForTrip tour_place_id', () => {
expect(byId.get(tour.id)).toBe(tour.id);
expect(byId.get(plain.id)).toBeNull();
});
-
- it("PLACEREPO-TOUR-005: listTracksWithoutTour lists the trip's tracks that are no tour yet, oldest first (#2810)", async () => {
- const { user } = createUser(testDb);
- const trip = createTrip(testDb, user.id);
- const other = createTrip(testDb, user.id);
- const line = '[[49,12,100],[49.01,12.01,150]]';
- const track = async (tripId: number, name: string) => {
- const place = createPlace(testDb, tripId, { name });
- await updateRows(t.orm, Places, { id: place.id }, { route_geometry: line });
- return place;
- };
- const first = await track(trip.id, 'Garmin hike');
- const second = await track(trip.id, 'Garmin hike');
- const toured = await track(trip.id, 'Ridge walk');
- createTour(testDb, toured.id);
- createPlace(testDb, trip.id, { name: 'Cafe' });
- await track(other.id, 'Garmin hike');
-
- expect(await places.listTracksWithoutTour(trip.id)).toEqual([
- { id: first.id, name: 'Garmin hike', route_geometry: line },
- { id: second.id, name: 'Garmin hike', route_geometry: line },
- ]);
- });
});
diff --git a/server/tests/unit/nest/places.service.test.ts b/server/tests/unit/nest/places.service.test.ts
index 633ba3e8b..c2a4a9f4e 100644
--- a/server/tests/unit/nest/places.service.test.ts
+++ b/server/tests/unit/nest/places.service.test.ts
@@ -1385,22 +1385,6 @@ describe('searchImage', () => {
// ── Import deduplication ──────────────────────────────────────────────────────
describe('importGpx deduplication', () => {
- it('PLACE-SVC-033b — tracksToAdopt pairs each named row with one track of that name that is no tour (#2810)', async () => {
- const { user } = createUser(testDb);
- const trip = createTrip(testDb, user.id);
- const line = '[[46.1,11.1,1200],[46.2,11.2,1300]]';
- const ids = ['Garmin Hike', 'garmin hike ', ' '].map((name) => createPlace(testDb, trip.id, { name }).id);
- await updateRows(orm, Places, { id: { $in: ids } }, { route_geometry: line });
- type Row = Parameters<PlacesService['tracksToAdopt']>[1][number];
- const row = (name: string) => ({ name, lat: 46.1, lng: 11.1, routeGeometry: line }) as unknown as Row;
-
- const adopt = await svc.tracksToAdopt(String(trip.id), [row('GARMIN HIKE'), row(''), row('Garmin hike'), row('garmin hike')]);
- expect([...adopt.entries()]).toEqual([
- [0, { id: ids[0], name: 'Garmin Hike', route_geometry: line }],
- [2, { id: ids[1], name: 'garmin hike ', route_geometry: line }],
- ]);
- });
-
it('PLACE-SVC-033 — skips waypoints already in trip by name', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
diff --git a/server/tests/unit/nest/tour-track-adoption.test.ts b/server/tests/unit/nest/tour-track-adoption.test.ts
new file mode 100644
index 000000000..40a3d291a
--- /dev/null
+++ b/server/tests/unit/nest/tour-track-adoption.test.ts
@@ -0,0 +1,47 @@
+/**
+ * tracksToAdopt (#2810): which rows of a tour import take over a track that a
+ * GPX import before Tours left as a plain place.
+ */
+import { tracksToAdopt } from '../../../src/nest/tours/tour-track-adoption';
+
+import { describe, expect, it } from 'vitest';
+
+const LINE = '[[46.1,11.1,1200],[46.2,11.2,1300]]';
+const track = (
+ id: number,
+ name: string,
+ extra: { route_geometry?: string | null; tour_place_id?: number | null } = {},
+) => ({
+ id,
+ name,
+ route_geometry: LINE,
+ tour_place_id: null,
+ ...extra,
+});
+const rows = (...names: string[]) => names.map((name) => ({ name }));
+
+describe('tracksToAdopt', () => {
+ it('TRACK-ADOPT-001: pairs a row with a track of the same name, trimmed and in any case', () => {
+ expect([...tracksToAdopt(rows('GARMIN HIKE'), [track(4, ' Garmin hike ')])]).toEqual([
+ [0, { id: 4, route_geometry: LINE }],
+ ]);
+ });
+
+ it('TRACK-ADOPT-002: gives each track to one row only, oldest first', () => {
+ const adopt = tracksToAdopt(rows('Hike', 'hike', 'HIKE'), [track(9, 'hike'), track(3, 'Hike')]);
+ expect([...adopt]).toEqual([
+ [0, { id: 3, route_geometry: LINE }],
+ [1, { id: 9, route_geometry: LINE }],
+ ]);
+ });
+
+ it('TRACK-ADOPT-003: leaves out a tour, a place without a line, an unnamed place and an unnamed row', () => {
+ const places = [
+ track(1, 'Ridge', { tour_place_id: 1 }),
+ track(2, 'Cafe', { route_geometry: null }),
+ track(3, ' '),
+ track(4, 'Lake'),
+ ];
+ expect([...tracksToAdopt(rows('Ridge', 'Cafe', '', 'Other'), places)]).toEqual([]);
+ });
+});