Tours: save a tour as a new, independent tour (P2C-07)

This commit is contained in:
Maurice
2026-10-15 22:18:41 +02:00
parent 356df90095
commit 485e360c64
38 changed files with 432 additions and 62 deletions
+2 -1
View File
@@ -1,5 +1,6 @@
import { tourCreateRequestSchema } from '@trek/shared';
import { tourCopyRequestSchema, tourCreateRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class TourCreateDto extends createZodDto(tourCreateRequestSchema) {}
export class TourCopyDto extends createZodDto(tourCopyRequestSchema) {}
+15 -2
View File
@@ -4,10 +4,10 @@ import { RequireAddon } from '../addons/require-addon.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { TourCreateDto } from './dto/tour-create.dto';
import { TourCopyDto, TourCreateDto } from './dto/tour-create.dto';
import { ToursService } from './tours.service';
import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, UseGuards } from '@nestjs/common';
import { tourDetailResponseSchema } from '@trek/shared';
import { tourCreateResponseSchema, tourDetailResponseSchema } from '@trek/shared';
/**
* /api/trips/:tripId/tours: the Tours facet, read and route edits.
@@ -53,6 +53,19 @@ export class ToursController {
return await this.tours.updateTour(tripId, placeId, body, socketId);
}
/** P2C-07: the tour saved again as a new, independent tour of the trip, without its days. */
@RequirePermission('place_edit')
@Post(':placeId/copy')
@ResponseContract(tourCreateResponseSchema)
async copy(
@Param('tripId') tripId: string,
@Param('placeId') placeId: string,
@Body() body: TourCopyDto,
@Headers('x-socket-id') socketId?: string,
) {
return await this.tours.copyTour(tripId, placeId, body.name, socketId);
}
/** Takes an import planned over in place back to its recorded track; the planning is dropped. */
@RequirePermission('place_edit')
@Post(':placeId/restore-recorded')
+61
View File
@@ -336,6 +336,67 @@ export class ToursService {
return result;
}
/**
* P2C-07 "save as new tour": an independent tour made from one of the trip,
* with its own id, its own copy of the line and the control points, the
* same measures and source, and none of the days. It points at the tour it
* came from (`derived_from_place_id`), so the detail can name it; nothing
* keeps the two in step afterwards.
*/
async copyTour(tripId: string, placeId: string, name: string, socketId?: string): Promise<TourCreateResponse> {
const tid = toRowId(tripId);
const pid = toRowId(placeId);
if (tid === null || pid === null) throw new NotFoundException('Tour not found');
const copyId = await this.uow.transactional(async () => {
const [source, provenance, place] = await Promise.all([
this.toursRepo.findInTrip(tid, pid),
this.toursRepo.findProvenance(tid, pid),
this.placesRepo.findInTrip(pid, tid),
]);
if (!source || !provenance || !place) throw new NotFoundException('Tour not found');
const start = parseRouteGeometry(place.route_geometry)[0];
const id = await this.placesRepo.insertTourPlace({
trip_id: tid,
name,
lat: start?.[0] ?? place.lat ?? 0,
lng: start?.[1] ?? place.lng ?? 0,
route_geometry: place.route_geometry,
description: place.description ?? null,
website: place.website ?? null,
});
await this.toursRepo.insertTour({
place_id: id,
tour_type: source.tour_type,
distance: source.distance,
elevation_gain: source.elevation_gain,
elevation_loss: source.elevation_loss,
duration: source.duration,
planned_duration_minutes: source.planned_duration_minutes,
break_additional_minutes: source.break_additional_minutes,
match_confidence: source.match_confidence,
max_hiking_difficulty: source.max_hiking_difficulty,
wanderer_ref: source.wanderer_ref,
difficulty: source.difficulty,
derived_from_place_id: pid,
origin: source.origin as TourOrigin,
origin_file_name: provenance.origin_file_name,
});
await this.waypointsRepo.insertForPlace(id, await this.waypointsRepo.listForPlace(pid));
return id;
});
const result = await this.getTour(tripId, String(copyId));
const created = await this.placesRepo.findWithTagsAndRatings(copyId);
this.broadcastToursChanged(tripId, [copyId], socketId);
try {
if (created) this.places.broadcast(tripId, 'place:created', { place: created }, socketId);
} catch {
this.logger.warn(`Committed Tour copy ${copyId}: place notification failed`);
}
return result;
}
/** Replace a saved tour's derived route and routing controls as one write. */
async updateTour(
tripId: string,
+60
View File
@@ -548,6 +548,66 @@ describe('Tours e2e (real guards + temp SQLite)', () => {
});
});
describe('save as new tour (P2C-07)', () => {
const copy = (
placeId: number,
body: Record<string, unknown> = { name: 'Ridge (copy)' },
userId = OWNER,
tripId = 5,
) =>
request(server)
.post(`/api/trips/${tripId}/tours/${placeId}/copy`)
.set('Cookie', sessionCookie(userId))
.send(body);
const detail = async (placeId: number) =>
(await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER))).body;
it('makes an independent tour with its own line and control points, no days, pointing at its source', async () => {
const source = await createViaApi();
await makeDayAssignment(orm, 3, source, { order_index: 0 });
const res = await copy(source);
expect(res.status).toBe(201);
const copyId = res.body.tour.place_id as number;
expect(copyId).not.toBe(source);
expect(res.body.tour).toMatchObject({
name: 'Ridge (copy)',
derived_from_place_id: source,
planned: false,
origin: 'trek',
});
expect(res.body.waypoints).toEqual((await detail(source)).waypoints);
expect(res.body.provenance).toMatchObject({ derivedFrom: { placeId: source } });
expect((await placeColumns(copyId, 'route_geometry')).route_geometry).toBe(
(await placeColumns(source, 'route_geometry')).route_geometry,
);
// Editing the copy leaves the original as it was.
await request(server)
.put(`/api/trips/5/tours/${copyId}`)
.set('Cookie', sessionCookie(OWNER))
.send(tourBody({ name: 'Shorter ridge' }));
expect((await detail(source)).tour).toMatchObject({ name: tourBody().name, planned: true });
});
it('a copied GPX import stays a GPX import with its file name', async () => {
const imported = await importGpx(OWNER, TRACK_GPX);
const source = imported.body.tours[0].place_id as number;
const res = await copy(source, { name: 'Track again' });
expect(res.status).toBe(201);
expect(res.body.tour).toMatchObject({ origin: 'gpx', has_waypoints: false });
expect(res.body.provenance).toMatchObject({ source: { kind: 'gpx', fileName: 'track.gpx' } });
});
it('refuses an empty name, a tour of another trip, a plain place, and someone who may not add places', async () => {
const source = await createViaApi();
expect((await copy(source, { name: ' ' })).status).toBe(400);
expect((await copy(source, { name: 'x' }, VIEWER)).status).toBe(403);
expect((await copy(await plainPlace(5, 'Cafe'))).status).toBe(404);
const foreign = await createViaApi(6);
expect((await copy(foreign)).status).toBe(404);
});
});
describe('planning over an import (PR1-05)', () => {
/** An imported GPX tour on trip 5: no waypoints, the recorded line as it came. */
const importedTour = async (tripId = 5) => {