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,293 @@
/**
* Whole tours kept in a collection (LIB-03), through the real JwtAuthGuard,
* AddonGuard and TripAccessGuard against a migrated and seeded temp SQLite db,
* every answer checked against its response contract. The permission check is
* a container spy and the broadcasts go to a FakeRealtimeService.
*
* Fixtures: user 1 owns trips 5 and 6 and the collection, user 2 is a member
* of trip 5 whom the spy denies 'place_edit' and a viewer of the collection,
* user 3 has no access to either.
*/
import { CollectionTours } from '../../src/db/entities/CollectionTours.entity';
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { TourWaypoints } from '../../src/db/entities/TourWaypoints.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { ToursModule } from '../../src/nest/tours/tours.module';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { addCollectionMember, makeCollection } from '../helpers/factories/collections';
import { countRows, deleteRows, findRow, insertRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { addTripMember } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
const { journeyHooks } = vi.hoisted(() => ({
journeyHooks: {
reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
onPlaceCreated: vi.fn().mockResolvedValue(undefined),
onPlaceUpdated: vi.fn().mockResolvedValue(undefined),
onPlaceDeleted: vi.fn().mockResolvedValue(undefined),
},
}));
const db = createSnapshotTestDb();
const realtime = new FakeRealtimeService();
let orm: TestOrm;
let checkPermission: MockInstance;
let collectionId: number;
const OWNER = 1;
const MEMBER = 2;
const OUTSIDER = 3;
const GEOMETRY = [
[47, 11, 600],
[47.01, 11.01, 700],
[47.02, 11.02, 650],
];
const tourBody = (overrides: Record<string, unknown> = {}) => ({
name: 'Ridge walk',
route_geometry: GEOMETRY,
waypoints: [
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1, name: 'Saddle' },
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
],
max_hiking_difficulty: 3,
duration_seconds: 3600,
...overrides,
});
describe('Collection tours e2e (real guards + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
RealtimeModule,
ToursModule,
],
})
.overrideProvider(RealtimeService)
.useValue(realtime)
.overrideProvider(JourneyDomainService)
.useValue(journeyHooks)
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalPipes(new ZodValidationPipe());
nest.useGlobalFilters(new TrekExceptionFilter());
await nest.init();
return nest;
}
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const createTour = async (tripId = 5, body: Record<string, unknown> = tourBody()) => {
const res = await request(server).post(`/api/trips/${tripId}/tours`).set(as(OWNER)).send(body);
expect(res.status).toBe(201);
return res.body.tour.place_id as number;
};
const keep = async (placeId: number, userId = OWNER, extra: Record<string, unknown> = {}) =>
request(server)
.post(`/api/addons/collections/${collectionId}/tours`)
.set(as(userId))
.send({ source_trip_id: 5, source_place_id: placeId, ...extra });
beforeAll(async () => {
orm = await createTestOrm(db);
// Pinned ids: the session cookies sign for exactly these users.
await makeUser(orm, { id: 1, username: 'owner', email: 'owner@example.test', role: 'user', password_version: 0 });
await makeUser(orm, { id: 2, username: 'member', email: 'member@example.test', role: 'user', password_version: 0 });
await makeUser(orm, {
id: 3,
username: 'outsider',
email: 'outsider@example.test',
role: 'user',
password_version: 0,
});
await insertRows(orm, Trips, [
{ id: 5, user: 1, title: 'Alps' },
{ id: 6, user: 1, title: 'Other' },
]);
await addTripMember(orm, 5, 2);
const list = await makeCollection(orm, OWNER, { name: 'Hikes' });
collectionId = list.id;
await addCollectionMember(orm, collectionId, MEMBER, { role: 'viewer' });
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(async () => {
checkPermission.mockImplementation(
async (action: string, _role: string, _owner: number, userId: number) =>
!(action === 'place_edit' && userId === MEMBER),
);
await setAddonEnabled(orm, 'tours', true);
await setAddonEnabled(orm, 'collections', true);
realtime.broadcastMock.mockClear();
realtime.broadcastToUserMock.mockClear();
await deleteRows(orm, CollectionTours);
await deleteRows(orm, DayAssignments);
await deleteRows(orm, Places);
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('keeps a tour, lists it for every member and shows what taking it over asks about', async () => {
const source = await createTour();
const kept = await keep(source, OWNER, { name: 'Ridge, kept' });
expect(kept.status).toBe(201);
expect(kept.body.tour).toMatchObject({
name: 'Ridge, kept',
tour_type: 'hike',
has_line: true,
waypoint_count: 3,
source: { tripTitle: 'Alps', tourName: 'Ridge walk' },
saved_by: 'owner',
});
expect(realtime.broadcastToUserMock).toHaveBeenCalledWith(
MEMBER,
{ type: 'collections:updated', collectionId },
undefined,
);
const listed = await request(server).get(`/api/addons/collections/${collectionId}/tours`).set(as(MEMBER));
expect(listed.status).toBe(200);
expect(listed.body.tours.map((tour: { id: number }) => tour.id)).toEqual([kept.body.tour.id]);
const detail = await request(server)
.get(`/api/addons/collections/${collectionId}/tours/${kept.body.tour.id}`)
.set(as(MEMBER));
expect(detail.status).toBe(200);
expect(detail.body.line).toEqual(GEOMETRY.map(([lat, lng]) => [lat, lng]));
expect(detail.body.points).toEqual([
{ role: 'start', name: null, shaping: false },
{ role: 'via', name: 'Saddle', shaping: false },
{ role: 'end', name: null, shaping: false },
]);
// The member sees the trip they belong to, without the right to add a tour to it.
expect(detail.body.trips).toEqual([{ id: 5, title: 'Alps', start_date: null, end_date: null, can_add: false }]);
});
it('takes a kept tour into a trip with its points, or with its line only, and changes neither source', async () => {
const source = await createTour();
const kept = (await keep(source)).body.tour as { id: number };
// A later change to the source does not reach the kept tour.
await request(server)
.put(`/api/trips/5/tours/${source}`)
.set(as(OWNER))
.send(tourBody({ name: 'Changed later' }));
const full = await request(server)
.post('/api/trips/6/tours/from-collection')
.set(as(OWNER))
.send({ collection_id: collectionId, collection_tour_id: kept.id, include_waypoints: true });
expect(full.status).toBe(201);
expect(full.body.tour).toMatchObject({ name: 'Ridge walk', planned: false, revision: 1 });
const roles = full.body.waypoints.map((point: { role: string; name?: string }) => [point.role, point.name ?? null]);
expect(roles).toEqual([
['start', null],
['via', 'Saddle'],
['end', null],
]);
expect(full.body.provenance.takenOverFrom).toEqual({ tripTitle: 'Alps', tourName: 'Ridge walk' });
expect(realtime.broadcastMock.mock.calls.every(([tripId]) => String(tripId) === '6')).toBe(true);
const bare = await request(server)
.post('/api/trips/6/tours/from-collection')
.set(as(OWNER))
.send({ collection_id: collectionId, collection_tour_id: kept.id, include_waypoints: false, name: 'Bare' });
expect(bare.status).toBe(201);
expect(bare.body.tour).toMatchObject({ name: 'Bare', has_waypoints: false });
expect(await countRows(orm, TourWaypoints, { place: bare.body.tour.place_id })).toBe(0);
expect((await findRow(orm, Places, { id: bare.body.tour.place_id }))?.route_geometry).toBe(
JSON.stringify(GEOMETRY),
);
expect(await countRows(orm, Places, { trip: 6 })).toBe(2);
expect(await countRows(orm, DayAssignments)).toBe(0);
expect(await countRows(orm, CollectionTours)).toBe(1);
expect((await findRow(orm, Places, { id: source }))?.name).toBe('Changed later');
});
it('refuses a viewer keeping, a stranger reading, a trip without place_edit and an unsaid choice about the points', async () => {
const source = await createTour();
expect((await keep(source, MEMBER)).status).toBe(403);
const kept = (await keep(source)).body.tour as { id: number };
const stranger = await request(server).get(`/api/addons/collections/${collectionId}/tours`).set(as(OUTSIDER));
expect(stranger.status).toBe(404);
expect(stranger.body).toEqual({ error: 'Collection not found' });
const body = { collection_id: collectionId, collection_tour_id: kept.id, include_waypoints: true };
const takeOver = (tripId: number, userId: number) =>
request(server).post(`/api/trips/${tripId}/tours/from-collection`).set(as(userId)).send(body);
expect((await takeOver(5, MEMBER)).status).toBe(403);
expect((await takeOver(6, OUTSIDER)).status).toBe(404);
const unsaid = await request(server)
.post('/api/trips/6/tours/from-collection')
.set(as(OWNER))
.send({ collection_id: collectionId, collection_tour_id: kept.id });
expect(unsaid.status).toBe(400);
const wrongList = await request(server)
.post('/api/trips/6/tours/from-collection')
.set(as(OWNER))
.send({ ...body, collection_id: collectionId + 1000 });
expect(wrongList.status).toBe(404);
expect(await countRows(orm, Places, { trip: 6 })).toBe(0);
});
it('removes a kept tour for the owner only, and answers malformed ids, sessions and addons as the guards do', async () => {
const source = await createTour();
const kept = (await keep(source)).body.tour as { id: number };
const path = `/api/addons/collections/${collectionId}/tours/${kept.id}`;
expect((await request(server).delete(path).set(as(MEMBER))).status).toBe(403);
const removed = await request(server).delete(path).set(as(OWNER));
expect(removed.status).toBe(200);
expect(removed.body).toEqual({ success: true });
expect((await request(server).delete(path).set(as(OWNER))).status).toBe(404);
expect((await request(server).get(`/api/addons/collections/abc/tours`).set(as(OWNER))).status).toBe(404);
const malformed = await request(server).get(`/api/addons/collections/${collectionId}/tours/x`).set(as(OWNER));
expect(malformed.status).toBe(404);
expect((await request(server).get(`/api/addons/collections/${collectionId}/tours`)).status).toBe(401);
await setAddonEnabled(orm, 'collections', false);
const noCollections = await request(server).get(`/api/addons/collections/${collectionId}/tours`).set(as(OWNER));
expect(noCollections.body).toEqual({ error: 'Collections addon is not enabled' });
await setAddonEnabled(orm, 'tours', false);
const noTours = await request(server).get(`/api/addons/collections/${collectionId}/tours`).set(as(OWNER));
expect(noTours.status).toBe(404);
expect(noTours.body).toEqual({ error: 'Tours addon is not enabled' });
});
});
+4 -3
View File
@@ -43,14 +43,15 @@ describe('ALL_ENTITIES', () => {
* + tour_station_visits, how far a city walk got on one of its days
* + tour_change_steps, the changes to a tour saved from a confirmed proposal
* + tour_activities, the recorded tracks assigned to a tour
* + tour_activity_exclusions, the tours a user left out of their own activity sums)
* + tour_activity_exclusions, the tours a user left out of their own activity sums
* + collection_tours, the whole tours a collection keeps)
* is registered, and no two share a class name (a silent duplicate would
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
* which de-duplicates by class name).
*/
it('ENT-003: exactly 146 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(146);
it('ENT-003: exactly 147 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(147);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
@@ -40,7 +40,9 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
// only ever written whole, by the save of a confirmed change).
// + tour_activities: id, place_id, track_place_id (an assignment always names its tour and its recording).
// + tour_activity_exclusions: id, user_id, place_id (an exclusion always names its user and its tour).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 510;
// + collection_tours: id, collection_id, name, waypoints, tour_type, origin, source_trip_title, source_tour_name
// (a kept tour is only ever written whole, from the tour it was saved from).
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 518;
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
@@ -76,6 +76,7 @@ const UNNUMBERED = [
'Migration20200101045910_a_tour_can_be_left_out_of_ones_activities',
'Migration20200101046000_a_tour_waypoint_can_end_a_stage',
'Migration20200101046010_a_day_can_hold_one_stage_of_a_tour',
'Migration20200101046100_a_collection_keeps_whole_tours',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,173 @@
/**
* `CollectionToursRepository` (LIB-03): the whole tours a collection keeps.
* A kept tour is written whole (CT3), listed newest first (CT1), read only
* within its collection (CT2) and removed only from it (CT4); the trips one
* could go into come with their owner (CT5).
*/
import { CollectionTours } from '../../../../src/db/entities/CollectionTours.entity';
import { Collections } from '../../../../src/db/entities/Collections.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type {
CollectionTourInsert,
CollectionToursRepository,
} from '../../../../src/db/repositories/CollectionTours.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makeCollection } from '../../../helpers/factories/collections';
import { deleteRows, findRow, updateRows } from '../../../helpers/factories/rows';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: CollectionToursRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(CollectionTours);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
const POINTS = [
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1, name: 'Hut', key: 'stop-hut-1' },
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
];
/** A kept hike with a line and three points, the middle one named, its points encoded as the service writes them. */
function snapshot(collectionId: number, savedBy: number | null, overrides: Partial<CollectionTourInsert> = {}) {
const row: CollectionTourInsert = {
collection_id: collectionId,
saved_by: savedBy,
name: 'Ridge',
description: 'Up high',
website: null,
route_geometry: '[[47,11,600],[47.01,11.01,650],[47.02,11.02,630]]',
waypoints: JSON.stringify(POINTS),
tour_type: 'hike',
distance: 4.2,
elevation_gain: 300,
elevation_loss: null,
duration: 90,
planned_duration_minutes: null,
break_additional_minutes: 20,
difficulty: null,
wanderer_ref: null,
match_confidence: 1,
max_hiking_difficulty: 3,
bike_profile: null,
boat_type: null,
water_context: null,
paddle_speed_kmh: null,
portage_speed_kmh: null,
paddle_lake_style: null,
track_marks: null,
hiking_preferences: null,
origin: 'trek',
origin_file_name: null,
source_trip_title: 'Alps',
source_tour_name: 'Ridge',
...overrides,
};
return row;
}
async function fixture() {
const { user } = await makeUser(t, { username: 'keeper' });
const mine = await makeCollection(t, user.id, { name: 'Hikes' });
const other = await makeCollection(t, user.id, { name: 'Other' });
return { user, mine, other };
}
describe('CollectionToursRepository', () => {
it('CT3/CT2: keeps a snapshot whole and reads it back with its points decoded and who saved it', async () => {
const { user, mine, other } = await fixture();
const id = await repo.insertSnapshot(snapshot(mine.id, user.id));
const row = await repo.findInCollection(mine.id, id);
expect(row).toMatchObject({
id,
collection_id: mine.id,
saved_by: user.id,
saved_by_name: 'keeper',
name: 'Ridge',
tour_type: 'hike',
distance: 4.2,
elevation_loss: null,
source_trip_title: 'Alps',
});
expect(row?.waypoints).toEqual(POINTS);
expect(typeof row?.created_at).toBe('string');
// Only within its own collection.
expect(await repo.findInCollection(other.id, id)).toBeUndefined();
});
it('CT1: lists a collection’s tours newest first, the id breaking ties, and nothing of another', async () => {
const { user, mine, other } = await fixture();
const first = await repo.insertSnapshot(snapshot(mine.id, user.id, { name: 'First' }));
const second = await repo.insertSnapshot(snapshot(mine.id, user.id, { name: 'Second' }));
const older = await repo.insertSnapshot(snapshot(mine.id, user.id, { name: 'Older' }));
await repo.insertSnapshot(snapshot(other.id, user.id, { name: 'Elsewhere' }));
await updateRows(t, CollectionTours, { id: older }, { created_at: '2020-01-01 00:00:00' });
await updateRows(t, CollectionTours, { id: { $in: [first, second] } }, { created_at: '2026-10-20 10:00:00' });
const rows = await repo.listForCollection(mine.id);
expect(rows.map((row) => row.name)).toEqual(['Second', 'First', 'Older']);
});
it('CT1/CT2: an account that is gone leaves the kept tour with nobody named', async () => {
const { mine } = await fixture();
const { user: gone } = await makeUser(t, { username: 'gone' });
const id = await repo.insertSnapshot(snapshot(mine.id, gone.id));
await deleteRows(t, Users, { id: gone.id });
expect(await repo.findInCollection(mine.id, id)).toMatchObject({ saved_by: null, saved_by_name: null });
});
it('CT2: a broken point list, or one of another shape, reads as no points, the line kept as it is', async () => {
const { user, mine } = await fixture();
const id = await repo.insertSnapshot(snapshot(mine.id, user.id));
await updateRows(t, CollectionTours, { id }, { waypoints: 'not json' });
const row = await repo.findInCollection(mine.id, id);
expect(row?.waypoints).toEqual([]);
expect(row?.route_geometry).toContain('47.01');
await updateRows(t, CollectionTours, { id }, { waypoints: JSON.stringify([{ lat: 147, lng: 11 }]) });
expect((await repo.listForCollection(mine.id))[0]?.waypoints).toEqual([]);
});
it('CT4: removes a kept tour only from its own collection', async () => {
const { user, mine, other } = await fixture();
const id = await repo.insertSnapshot(snapshot(mine.id, user.id));
expect(await repo.deleteInCollection(other.id, id)).toBe(false);
expect(await findRow(t, CollectionTours, { id })).not.toBeNull();
expect(await repo.deleteInCollection(mine.id, id)).toBe(true);
expect(await repo.findInCollection(mine.id, id)).toBeUndefined();
});
it('CT5: names the trips asked for with their owner and dates, and none for no ids', async () => {
const { user } = await fixture();
const alps = await makeTrip(t, user.id, { title: 'Alps', start_date: '2026-07-01', end_date: '2026-07-08' });
const coast = await makeTrip(t, user.id, { title: 'Coast', start_date: null, end_date: null });
await makeTrip(t, user.id, { title: 'Not asked' });
const rows = await repo.targetTrips([coast.id, alps.id]);
expect([...rows].sort((a, b) => a.id - b.id)).toEqual([
{ id: alps.id, user_id: user.id, title: 'Alps', start_date: '2026-07-01', end_date: '2026-07-08' },
{ id: coast.id, user_id: user.id, title: 'Coast', start_date: null, end_date: null },
]);
expect(await repo.targetTrips([])).toEqual([]);
});
it('goes with its collection', async () => {
const { user, mine } = await fixture();
const id = await repo.insertSnapshot(snapshot(mine.id, user.id));
await deleteRows(t, Collections, { id: mine.id });
expect(await findRow(t, CollectionTours, { id })).toBeNull();
});
});
@@ -0,0 +1,116 @@
/**
* CollectionToursController and CollectionTourTakeOverController (LIB-03):
* route metadata, the guards and the addon they run behind, the permission
* the take-over needs, and the delegation to CollectionToursService, a
* malformed id answering 404 before the service is asked.
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { DomainError } from '../../../src/nest/common/domain-error';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import {
CollectionTourTakeOverController,
CollectionToursController,
} from '../../../src/nest/tours/collection-tours.controller';
import type { CollectionToursService } from '../../../src/nest/tours/collection-tours.service';
import type { User } from '../../../src/types';
import { RequestMethod } from '@nestjs/common';
import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
import { describe, expect, it, vi } from 'vitest';
const user = { id: 2, role: 'user', email: 'u@example.test' } as User;
function fakeService() {
return {
list: vi.fn().mockResolvedValue({ tours: [] }),
detail: vi.fn().mockResolvedValue({ tour: {}, line: [], points: [], trips: [] }),
save: vi.fn().mockResolvedValue({ tour: { id: 4 } }),
remove: vi.fn().mockResolvedValue(undefined),
takeOver: vi.fn().mockResolvedValue({ tour: { place_id: 9 }, waypoints: [] }),
};
}
function route(controller: object, method: string) {
const handler = (controller as Record<string, unknown>)[method] as object;
return {
path: Reflect.getMetadata(PATH_METADATA, handler) as string,
verb: Reflect.getMetadata(METHOD_METADATA, handler) as RequestMethod,
permission: Reflect.getMetadata(TRIP_PERMISSION_KEY, handler) as string | undefined,
};
}
async function notFound(work: () => Promise<unknown>): Promise<string> {
try {
await work();
} catch (err) {
expect(err).toBeInstanceOf(DomainError);
expect((err as DomainError).getStatus()).toBe(404);
return (err as DomainError).publicMessage;
}
throw new Error('expected a 404');
}
describe('CollectionToursController', () => {
it('LIB3-CTRL-001: lives under the collection, behind the Tours addon and a session, without a trip guard', () => {
expect(Reflect.getMetadata(PATH_METADATA, CollectionToursController)).toBe(
'api/addons/collections/:collectionId/tours',
);
expect(Reflect.getMetadata(GUARDS_METADATA, CollectionToursController)).toEqual([AddonGuard, JwtAuthGuard]);
expect(Reflect.getMetadata(REQUIRE_ADDON, CollectionToursController)).toEqual({ addonId: 'tours', label: 'Tours' });
const proto = CollectionToursController.prototype;
expect(route(proto, 'list')).toMatchObject({ path: '/', verb: RequestMethod.GET });
expect(route(proto, 'save')).toMatchObject({ path: '/', verb: RequestMethod.POST });
expect(route(proto, 'detail')).toMatchObject({ path: ':tourId', verb: RequestMethod.GET });
expect(route(proto, 'remove')).toMatchObject({ path: ':tourId', verb: RequestMethod.DELETE });
});
it('LIB3-CTRL-002: hands the user, the ids and the socket on to the service', async () => {
const service = fakeService();
const controller = new CollectionToursController(service as unknown as CollectionToursService);
const body = { source_trip_id: 5, source_place_id: 7 };
await controller.list(user, '3');
await controller.save(user, '3', body, 'sock');
await controller.detail(user, '3', '4');
expect(await controller.remove(user, '3', '4', 'sock')).toEqual({ success: true });
expect(service.list).toHaveBeenCalledWith(2, 3);
expect(service.save).toHaveBeenCalledWith(2, 3, body, 'sock');
expect(service.detail).toHaveBeenCalledWith(user, 3, 4);
expect(service.remove).toHaveBeenCalledWith(2, 3, 4, 'sock');
});
it('LIB3-CTRL-003: a malformed id is a missing collection or tour, never a 500', async () => {
const service = fakeService();
const controller = new CollectionToursController(service as unknown as CollectionToursService);
expect(await notFound(() => controller.list(user, 'abc'))).toBe('Collection not found');
expect(await notFound(() => controller.detail(user, '3', '1e3'))).toBe('Tour not found');
expect(await notFound(() => controller.remove(user, '-1', '4'))).toBe('Collection not found');
expect(service.list).not.toHaveBeenCalled();
expect(service.detail).not.toHaveBeenCalled();
expect(service.remove).not.toHaveBeenCalled();
});
});
describe('CollectionTourTakeOverController', () => {
it('LIB3-CTRL-004: is trip-scoped, needs place_edit and hands the body on', async () => {
expect(Reflect.getMetadata(PATH_METADATA, CollectionTourTakeOverController)).toBe('api/trips/:tripId/tours');
expect(Reflect.getMetadata(GUARDS_METADATA, CollectionTourTakeOverController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
]);
expect(route(CollectionTourTakeOverController.prototype, 'takeOver')).toEqual({
path: 'from-collection',
verb: RequestMethod.POST,
permission: 'place_edit',
});
const service = fakeService();
const controller = new CollectionTourTakeOverController(service as unknown as CollectionToursService);
const body = { collection_id: 3, collection_tour_id: 4, include_waypoints: false };
expect(await controller.takeOver('6', user, body, 'sock')).toEqual({ tour: { place_id: 9 }, waypoints: [] });
expect(service.takeOver).toHaveBeenCalledWith('6', 2, body, 'sock');
});
});
@@ -0,0 +1,155 @@
/**
* The pure halves of LIB-03 and the copy model it shares with P2C-07 and
* LIB-02: where a copy starts, what a kept tour shows and what a tour made
* from it carries.
*/
import type { CollectionTourRow } from '../../../src/db/repositories/CollectionTours.repository';
import {
keptTourCopySource,
keptTourItem,
keptTourLine,
keptTourPoints,
keptTourSnapshot,
} from '../../../src/nest/tours/collection-tours.helpers';
import { copiedFacet, copyStart } from '../../../src/nest/tours/tour-copy.helpers';
import { describe, expect, it } from 'vitest';
const row: CollectionTourRow = {
id: 4,
collection_id: 9,
saved_by: 1,
saved_by_name: 'owner',
name: 'Ridge',
description: null,
website: 'https://example.test/ridge',
route_geometry: '[[47,11,600],[47.02,11.02,630]]',
waypoints: [
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1, name: 'Hut', shaping: true },
],
tour_type: 'bike',
distance: 12,
elevation_gain: null,
elevation_loss: null,
duration: null,
planned_duration_minutes: 120,
break_additional_minutes: null,
difficulty: null,
wanderer_ref: null,
match_confidence: 1,
max_hiking_difficulty: null,
bike_profile: 'gravel',
boat_type: null,
water_context: null,
paddle_speed_kmh: null,
portage_speed_kmh: null,
paddle_lake_style: null,
track_marks: null,
hiking_preferences: null,
origin: 'gpx',
origin_file_name: 'ridge.gpx',
source_trip_title: 'Alps',
source_tour_name: 'Ridge',
created_at: '2026-10-20 10:00:00',
};
describe('collection tour helpers (LIB-03)', () => {
it('LIB3-HLP-001: a copy starts at the line, a walk without one at its first station, nothing without either', () => {
expect(copyStart({ route_geometry: '[[47,11,600],[48,12]]', waypoints: [] })).toEqual([47, 11]);
expect(copyStart({ route_geometry: null, waypoints: [{ lat: 1, lng: 2, role: 'start', sequence: 0 }] })).toEqual([
1, 2,
]);
expect(copyStart({ route_geometry: null, waypoints: [] })).toBeUndefined();
expect(copyStart({ route_geometry: '[]', waypoints: [] })).toBeUndefined();
});
it('LIB3-HLP-002: lists a kept tour as it was saved, unknown measures staying unknown', () => {
expect(keptTourItem(row)).toMatchObject({
id: 4,
tour_type: 'bike',
distance: 12,
elevation_gain: null,
origin: 'gpx',
has_line: true,
waypoint_count: 3,
station_count: null,
source: { tripTitle: 'Alps', tourName: 'Ridge' },
saved_by: 'owner',
saved_at: '2026-10-20 10:00:00',
});
expect(keptTourItem({ ...row, route_geometry: null }).has_line).toBe(false);
});
it('LIB3-HLP-003: shows the points in route order and the line thinned for drawing', () => {
expect(keptTourPoints(row)).toEqual([
{ role: 'start', name: null, shaping: false },
{ role: 'via', name: 'Hut', shaping: true },
{ role: 'end', name: null, shaping: false },
]);
expect(keptTourLine(row)).toEqual([
[47, 11],
[47.02, 11.02],
]);
const long = JSON.stringify(Array.from({ length: 900 }, (_, i) => [47 + i / 1000, 11]));
expect(keptTourLine({ route_geometry: long })).toHaveLength(400);
expect(keptTourLine({ route_geometry: null })).toEqual([]);
});
it('LIB3-HLP-004: a tour made from it carries everything, its points only when asked for', () => {
const withPoints = keptTourCopySource(row, true);
expect(withPoints).toMatchObject({ place_id: null, name: 'Ridge', website: 'https://example.test/ridge' });
expect(withPoints.waypoints).toHaveLength(3);
expect(keptTourCopySource(row, false).waypoints).toEqual([]);
expect(keptTourCopySource(row, false).route_geometry).toBe(row.route_geometry);
expect(copiedFacet(withPoints, 77, { derivedFrom: null, sameTrip: false })).toMatchObject({
place_id: 77,
tour_type: 'bike',
bike_profile: 'gravel',
planned_duration_minutes: 120,
origin: 'gpx',
origin_file_name: 'ridge.gpx',
derived_from_place_id: null,
taken_over_from_trip_title: 'Alps',
taken_over_from_tour_name: 'Ridge',
});
expect(
copiedFacet(withPoints, 77, {
derivedFrom: null,
sameTrip: false,
takenOverFrom: { tripTitle: 'Coast', tourName: 'Cliffs' },
}),
).toMatchObject({ taken_over_from_trip_title: 'Coast', taken_over_from_tour_name: 'Cliffs' });
});
it('LIB3-HLP-005: keeping one leaves its links to the trip behind and names where it came from', () => {
const source = keptTourCopySource(
{
...row,
waypoints: [
{ lat: 47, lng: 11, role: 'start', sequence: 0, linked_place_id: 3 },
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 1 },
],
},
true,
);
const snapshot = keptTourSnapshot(source, { collectionId: 9, userId: 1, name: 'Kept', tripTitle: 'Coast' });
expect(snapshot).toMatchObject({
collection_id: 9,
saved_by: 1,
name: 'Kept',
bike_profile: 'gravel',
origin_file_name: 'ridge.gpx',
source_trip_title: 'Coast',
source_tour_name: 'Ridge',
});
const kept = JSON.parse(snapshot.waypoints) as Array<{ linked_place_id?: number | null }>;
expect(kept.map((point) => point.linked_place_id)).toEqual([null, null]);
});
it('LIB3-HLP-006: a point that is no control point refuses the whole snapshot', () => {
const broken = keptTourCopySource({ ...row, waypoints: [{ lat: 147, lng: 11, role: 'start', sequence: 0 }] }, true);
expect(() => keptTourSnapshot(broken, { collectionId: 9, userId: 1, name: 'Kept', tripTitle: 'Coast' })).toThrow();
});
});
@@ -0,0 +1,238 @@
/**
* CollectionToursMcp (LIB-03): the tours a collection keeps, over the same
* service and the same checks as REST. The suite takes its subject from the
* container over a snapshot test db; the addon gate is the registry's.
*/
import { CollectionTours } from '../../../src/db/entities/CollectionTours.entity';
import { Places } from '../../../src/db/entities/Places.entity';
import type { McpContext } from '../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
import { CollectionToursMcp } from '../../../src/nest/tours/collection-tours.mcp';
import { ToursModule } from '../../../src/nest/tours/tours.module';
import { ToursService } from '../../../src/nest/tours/tours.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addCollectionMember, makeCollection } from '../../helpers/factories/collections';
import { makePlace } from '../../helpers/factories/places';
import { countRows, findRow } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
import { addTourWaypoints, makeTour } from '../../helpers/factories/tours';
import { makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { NotFoundException } from '@nestjs/common';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let mcp: CollectionToursMcp;
beforeAll(async () => {
t = await createTestModule({ db, imports: [ToursModule] });
mcp = t.get(CollectionToursMcp);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
await setAddonEnabled(orm, 'collections', true);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
const text = result.content[0]?.text ?? '';
return result.isError ? { error: text } : JSON.parse(text);
}
async function fixture() {
const { user } = await makeUser(orm);
const { user: viewer } = await makeUser(orm);
const { user: outsider } = await makeUser(orm);
const alps = await makeTrip(orm, user.id, { title: 'Alps' });
const next = await makeTrip(orm, user.id, { title: 'Next' });
const ridge = await makePlace(orm, alps.id, {
name: 'Ridge',
route_geometry: JSON.stringify([
[47, 11, 600],
[47.01, 11.01, 650],
]),
});
await makeTour(orm, ridge.id, { distance: 3.5 });
await addTourWaypoints(orm, ridge.id, [
{ lat: 47, lng: 11 },
{ lat: 47.01, lng: 11.01 },
]);
const list = await makeCollection(orm, user.id, { name: 'Hikes' });
await addCollectionMember(orm, list.id, viewer.id, { role: 'viewer' });
return { user, viewer, outsider, alps, next, ridge, list };
}
describe('CollectionToursMcp', () => {
it('LIB3-MCP-001: keeps a tour, lists it and reads it with the trips it could go into', async () => {
const f = await fixture();
const saved = read(
await mcp.saveTourToCollection(
{ collection_id: f.list.id, source_trip_id: f.alps.id, source_place_id: f.ridge.id },
ctx(f.user.id),
),
);
expect(saved.tour).toMatchObject({
name: 'Ridge',
distance: 3.5,
source: { tripTitle: 'Alps', tourName: 'Ridge' },
});
const listed = read(await mcp.listCollectionTours({ collection_id: f.list.id }, ctx(f.viewer.id)));
expect(listed.tours.map((tour: { id: number }) => tour.id)).toEqual([saved.tour.id]);
const detail = read(
await mcp.getCollectionTour({ collection_id: f.list.id, collection_tour_id: saved.tour.id }, ctx(f.user.id)),
);
expect(detail.points).toEqual([
{ role: 'start', name: null, shaping: false },
{ role: 'end', name: null, shaping: false },
]);
expect(detail.trips.map((trip: { title: string }) => trip.title).sort()).toEqual(['Alps', 'Next']);
});
it('LIB3-MCP-002: an admin may add to every trip; the role is read for the check', async () => {
const f = await fixture();
const admin = vi.spyOn(t.get(McpToolGuardsService), 'isAdminUser').mockResolvedValue(true);
const saved = read(
await mcp.saveTourToCollection(
{ collection_id: f.list.id, source_trip_id: f.alps.id, source_place_id: f.ridge.id },
ctx(f.user.id),
),
);
const detail = read(
await mcp.getCollectionTour({ collection_id: f.list.id, collection_tour_id: saved.tour.id }, ctx(f.user.id)),
);
expect(admin).toHaveBeenCalledWith(f.user.id);
expect(detail.trips.every((trip: { can_add: boolean }) => trip.can_add)).toBe(true);
});
it('LIB3-MCP-003: takes a kept tour into a trip with or without its points', async () => {
const f = await fixture();
const { tour } = read(
await mcp.saveTourToCollection(
{ collection_id: f.list.id, source_trip_id: f.alps.id, source_place_id: f.ridge.id },
ctx(f.user.id),
),
);
const base = { tripId: f.next.id, collection_id: f.list.id, collection_tour_id: tour.id };
const withPoints = read(await mcp.takeOverCollectionTour({ ...base, include_waypoints: true }, ctx(f.user.id)));
expect(withPoints.waypoints).toHaveLength(2);
expect(withPoints.provenance.takenOverFrom).toEqual({ tripTitle: 'Alps', tourName: 'Ridge' });
const lineOnly = read(
await mcp.takeOverCollectionTour({ ...base, include_waypoints: false, name: 'Bare' }, ctx(f.user.id)),
);
expect(lineOnly.tour.name).toBe('Bare');
expect(lineOnly.tour.has_waypoints).toBe(false);
expect(await findRow(orm, Places, { id: lineOnly.tour.place_id })).toMatchObject({ trip_id: f.next.id });
});
it('LIB3-MCP-004: refuses a trip out of reach, a trip without place_edit and a list out of sight', async () => {
const f = await fixture();
const { tour } = read(
await mcp.saveTourToCollection(
{ collection_id: f.list.id, source_trip_id: f.alps.id, source_place_id: f.ridge.id },
ctx(f.user.id),
),
);
const body = { collection_id: f.list.id, collection_tour_id: tour.id, include_waypoints: true };
expect(read(await mcp.takeOverCollectionTour({ ...body, tripId: f.next.id }, ctx(f.outsider.id)))).toEqual({
error: 'Trip not found or access denied.',
});
const denied = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValue(false);
const refused = await mcp.takeOverCollectionTour({ ...body, tripId: f.next.id }, ctx(f.user.id));
expect(refused.isError).toBe(true);
expect(denied).toHaveBeenCalledWith('place_edit', f.next.id, f.user.id);
denied.mockRestore();
const own = await makeTrip(orm, f.outsider.id);
// A service refusal reaches the session through the registry's error mapper.
await expect(mcp.takeOverCollectionTour({ ...body, tripId: own.id }, ctx(f.outsider.id))).rejects.toThrow(
'Collection not found',
);
expect(await countRows(orm, Places, { trip: f.next.id })).toBe(0);
});
it('LIB3-MCP-005: a tour the copy model cannot make is not found', async () => {
const f = await fixture();
const { tour } = read(
await mcp.saveTourToCollection(
{ collection_id: f.list.id, source_trip_id: f.alps.id, source_place_id: f.ridge.id },
ctx(f.user.id),
),
);
vi.spyOn(t.get(ToursService), 'createFromKeptTour').mockRejectedValueOnce(new NotFoundException('Tour not found'));
expect(
read(
await mcp.takeOverCollectionTour(
{ tripId: f.next.id, collection_id: f.list.id, collection_tour_id: tour.id, include_waypoints: true },
ctx(f.user.id),
),
),
).toEqual({ error: 'Tour not found.' });
vi.spyOn(t.get(ToursService), 'createFromKeptTour').mockRejectedValueOnce(new Error('boom'));
await expect(
mcp.takeOverCollectionTour(
{ tripId: f.next.id, collection_id: f.list.id, collection_tour_id: tour.id, include_waypoints: true },
ctx(f.user.id),
),
).rejects.toThrow('boom');
});
it('LIB3-MCP-006: the owner removes a kept tour, a viewer may not', async () => {
const f = await fixture();
const { tour } = read(
await mcp.saveTourToCollection(
{ collection_id: f.list.id, source_trip_id: f.alps.id, source_place_id: f.ridge.id },
ctx(f.user.id),
),
);
await expect(
mcp.deleteCollectionTour({ collection_id: f.list.id, collection_tour_id: tour.id }, ctx(f.viewer.id)),
).rejects.toThrow('Only an admin can remove tours from this list');
expect(
read(await mcp.deleteCollectionTour({ collection_id: f.list.id, collection_tour_id: tour.id }, ctx(f.user.id))),
).toEqual({ success: true });
expect(await countRows(orm, CollectionTours)).toBe(0);
});
it('LIB3-MCP-007: the tools are there only while both addons are on, and only for the scopes they need', async () => {
const options = (name: string) => {
const entry = getEntry(CollectionToursMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
const gate = options('listCollectionTours').when;
expect(await gate?.(ctx(1), mcp)).toBe(true);
enabled.mockImplementation(async (id: string) => id !== 'collections');
expect(await gate?.(ctx(1), mcp)).toBe(false);
enabled.mockImplementation(async (id: string) => id !== 'tours');
expect(await gate?.(ctx(1), mcp)).toBe(false);
const allowed = (name: string, scopes: string[]) => {
const access = options(name).access;
return typeof access === 'function' ? access({ userId: 1, scopes } as McpContext) : access;
};
expect(allowed('getCollectionTour', ['collections:read', 'trips:read'])).toBe(true);
expect(allowed('getCollectionTour', ['collections:read'])).toBe(false);
expect(allowed('saveTourToCollection', ['collections:write', 'trips:read'])).toBe(true);
expect(allowed('saveTourToCollection', ['collections:read', 'trips:read'])).toBe(false);
expect(allowed('takeOverCollectionTour', ['trips:write', 'collections:read'])).toBe(true);
expect(allowed('takeOverCollectionTour', ['trips:write'])).toBe(false);
expect(allowed('deleteCollectionTour', [])).toEqual({ group: 'collections', mode: 'write' });
});
});
@@ -0,0 +1,402 @@
/**
* CollectionToursService (LIB-03): whole tours kept in a collection and taken
* into a trip again, over the container and a snapshot test db. A kept tour is
* an independent snapshot made through the tours' one copy model; the
* collection's roles decide who reads, keeps and removes one, and nothing is
* kept in step afterwards.
*/
import { CollectionTours } from '../../../src/db/entities/CollectionTours.entity';
import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';
import { Places } from '../../../src/db/entities/Places.entity';
import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
import { Tours } from '../../../src/db/entities/Tours.entity';
import type { CollectionToursRepository } from '../../../src/db/repositories/CollectionTours.repository';
import { DomainError } from '../../../src/nest/common/domain-error';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { CollectionToursService } from '../../../src/nest/tours/collection-tours.service';
import { ToursModule } from '../../../src/nest/tours/tours.module';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addCollectionMember, makeCollection } from '../../helpers/factories/collections';
import { makePlace } from '../../helpers/factories/places';
import { countRows, deleteRows, findRow, findRows, updateRows } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
import { addTourWaypoints, makeTour } from '../../helpers/factories/tours';
import { addTripMember, makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { getRepositoryToken } from '@mikro-orm/nestjs';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let service: CollectionToursService;
const LINE = [
[47, 11, 600],
[47.01, 11.01, 650],
[47.02, 11.02, 630],
];
beforeAll(async () => {
t = await createTestModule({ db, imports: [ToursModule] });
service = t.get(CollectionToursService);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
t.realtime.broadcastToUserMock.mockClear();
await setAddonEnabled(orm, 'collections', true);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
/** Status and text of a refusal. */
async function refusal(work: Promise<unknown>): Promise<{ status: number; error: string }> {
try {
await work;
} catch (err) {
if (err instanceof DomainError) return { status: err.getStatus(), error: err.publicMessage };
const http = err as { getStatus?: () => number; message: string };
return { status: http.getStatus?.() ?? 500, error: http.message };
}
throw new Error('expected a refusal');
}
/**
* The owner's trips Alps (with a hike of three points, one standing for a
* place of the trip) and Next, someone else's trip Away the owner is a member
* of, a collection with an editor and a viewer, and an outsider.
*/
async function fixture() {
const { user: owner } = await makeUser(orm, { username: 'owner' });
const { user: editor } = await makeUser(orm, { username: 'editor' });
const { user: viewer } = await makeUser(orm, { username: 'viewer' });
const { user: outsider } = await makeUser(orm, { username: 'outsider' });
const alps = await makeTrip(orm, owner.id, { title: 'Alps' });
const next = await makeTrip(orm, owner.id, { title: 'Next' });
const away = await makeTrip(orm, outsider.id, { title: 'Away' });
await addTripMember(orm, away.id, owner.id);
const hut = await makePlace(orm, alps.id, { name: 'Hut', lat: 47.01, lng: 11.01 });
const ridge = await makePlace(orm, alps.id, {
name: 'Ridge',
lat: 47,
lng: 11,
description: 'Up high',
route_geometry: JSON.stringify(LINE),
});
await makeTour(orm, ridge.id, { distance: 4.2, elevation_gain: 300, max_hiking_difficulty: 3, duration: 90 });
await addTourWaypoints(orm, ridge.id, [
{ lat: 47, lng: 11 },
{ lat: 47.01, lng: 11.01, name: 'Hut', linkedPlace: hut.id, shaping: 0 },
{ lat: 47.015, lng: 11.015, shaping: 1 },
{ lat: 47.02, lng: 11.02 },
]);
const list = await makeCollection(orm, owner.id, { name: 'Hikes' });
await addCollectionMember(orm, list.id, editor.id, { role: 'editor' });
await addCollectionMember(orm, list.id, viewer.id, { role: 'viewer' });
return { owner, editor, viewer, outsider, alps, next, away, hut, ridge, list };
}
async function keep(f: Awaited<ReturnType<typeof fixture>>, name?: string) {
const { tour } = await service.save(f.owner.id, f.list.id, {
source_trip_id: f.alps.id,
source_place_id: f.ridge.id,
...(name ? { name } : {}),
});
return tour;
}
describe('CollectionToursService', () => {
it('LIB3-SVC-001: keeps a whole independent snapshot, its points in order, their links to the trip left behind', async () => {
const f = await fixture();
const tour = await keep(f);
expect(tour).toMatchObject({
collection_id: f.list.id,
name: 'Ridge',
tour_type: 'hike',
distance: 4.2,
elevation_gain: 300,
elevation_loss: null,
max_hiking_difficulty: 3,
origin: 'trek',
has_line: true,
waypoint_count: 4,
source: { tripTitle: 'Alps', tourName: 'Ridge' },
saved_by: 'owner',
});
const stored = await findRow(orm, CollectionTours, { id: tour.id });
expect(stored?.route_geometry).toBe(JSON.stringify(LINE));
const points = JSON.parse(stored?.waypoints ?? '[]') as Array<Record<string, unknown>>;
expect(points.map((point) => [point.role, point.sequence])).toEqual([
['start', 0],
['via', 1],
['via', 2],
['end', 3],
]);
expect(points.every((point) => point.linked_place_id == null)).toBe(true);
// Every member of the collection hears of it, the one who kept it included.
expect(t.realtime.broadcastToUserMock.mock.calls.map(([userId]) => userId).sort()).toEqual(
[f.owner.id, f.editor.id, f.viewer.id].sort(),
);
// Later changes to the tour it came from do not reach it.
await updateRows(orm, Places, { id: f.ridge.id }, { name: 'Renamed', route_geometry: '[[1,1],[2,2]]' });
await deleteRows(orm, TourWaypoints, { place: f.ridge.id });
const [listed] = (await service.list(f.viewer.id, f.list.id)).tours;
expect(listed).toMatchObject({ name: 'Ridge', waypoint_count: 4, has_line: true });
// And the trip it came from is as it was, beyond what the test changed itself.
expect(await countRows(orm, Places, { trip: f.alps.id })).toBe(2);
});
it('LIB3-SVC-002: keeps it under another name, an editor may keep one too', async () => {
const f = await fixture();
const { tour } = await service.save(f.editor.id, f.list.id, {
source_trip_id: f.alps.id,
source_place_id: f.ridge.id,
name: 'Ridge, spring',
});
expect(tour).toMatchObject({ name: 'Ridge, spring', source: { tripTitle: 'Alps', tourName: 'Ridge' } });
});
it('LIB3-SVC-003: refuses a viewer, a stranger, a trip out of reach and a place of another trip, writing nothing', async () => {
const f = await fixture();
const body = { source_trip_id: f.alps.id, source_place_id: f.ridge.id };
expect(await refusal(service.save(f.viewer.id, f.list.id, body))).toEqual({
status: 403,
error: 'You have read-only access to this list',
});
expect(await refusal(service.save(f.outsider.id, f.list.id, body))).toEqual({
status: 404,
error: 'Collection not found',
});
const own = await makeCollection(orm, f.outsider.id);
expect(await refusal(service.save(f.outsider.id, own.id, body))).toEqual({ status: 404, error: 'Tour not found' });
expect(
await refusal(service.save(f.owner.id, f.list.id, { source_trip_id: f.next.id, source_place_id: f.ridge.id })),
).toEqual({ status: 404, error: 'Tour not found' });
expect(
await refusal(service.save(f.owner.id, f.list.id, { source_trip_id: f.alps.id, source_place_id: f.hut.id })),
).toEqual({ status: 404, error: 'Tour not found' });
expect(await countRows(orm, CollectionTours)).toBe(0);
});
it('LIB3-SVC-004: lists for every member, the newest first, and refuses whoever cannot see the list', async () => {
const f = await fixture();
const first = await keep(f, 'First');
const second = await keep(f, 'Second');
await updateRows(orm, CollectionTours, { id: first.id }, { created_at: '2020-01-01 00:00:00' });
expect((await service.list(f.viewer.id, f.list.id)).tours.map((tour) => tour.id)).toEqual([second.id, first.id]);
expect(await refusal(service.list(f.outsider.id, f.list.id))).toEqual({
status: 404,
error: 'Collection not found',
});
});
it('LIB3-SVC-005: the detail has the line, the points in order and every trip, each saying whether a tour may go there', async () => {
const f = await fixture();
const tour = await keep(f);
vi.spyOn(t.get(PermissionsService), 'checkPermission').mockImplementation(
async (_action: string, _role: string, tripOwner: number | null, userId: number) => tripOwner === userId,
);
const detail = await service.detail({ id: f.owner.id, role: 'user' }, f.list.id, tour.id);
expect(detail.line).toEqual(LINE.map(([lat, lng]) => [lat, lng]));
expect(detail.points).toEqual([
{ role: 'start', name: null, shaping: false },
{ role: 'via', name: 'Hut', shaping: false },
{ role: 'via', name: null, shaping: true },
{ role: 'end', name: null, shaping: false },
]);
expect(detail.trips.map((trip) => [trip.title, trip.can_add]).sort()).toEqual([
['Alps', true],
['Away', false],
['Next', true],
]);
expect(await refusal(service.detail({ id: f.owner.id, role: 'user' }, f.list.id, 999999))).toEqual({
status: 404,
error: 'Tour not found',
});
});
it('LIB3-SVC-006: takes a kept tour into a trip with its points, as a tour of its own with no days', async () => {
const f = await fixture();
const kept = await keep(f);
const result = await service.takeOver(String(f.next.id), f.editor.id, {
collection_id: f.list.id,
collection_tour_id: kept.id,
include_waypoints: true,
});
const copy = result.tour.place_id;
expect(copy).not.toBe(f.ridge.id);
expect(result.tour).toMatchObject({ name: 'Ridge', tour_type: 'hike', distance: 4.2, revision: 1, planned: false });
expect(result.provenance?.takenOverFrom).toEqual({ tripTitle: 'Alps', tourName: 'Ridge' });
expect(result.waypoints.map((point) => [point.role, point.sequence, point.shaping === true])).toEqual([
['start', 0, false],
['via', 1, false],
['via', 2, true],
['end', 3, false],
]);
expect(result.waypoints.every((point) => point.linked_place_id == null)).toBe(true);
expect(await findRow(orm, Places, { id: copy })).toMatchObject({
trip_id: f.next.id,
route_geometry: JSON.stringify(LINE),
});
expect(await countRows(orm, DayAssignments, { place: copy })).toBe(0);
// Only the tour itself is new in the trip, no places for its points.
expect(await countRows(orm, Places, { trip: f.next.id })).toBe(1);
// The kept tour and the tour it was saved from are as they were.
expect((await service.list(f.owner.id, f.list.id)).tours).toHaveLength(1);
expect(await countRows(orm, TourWaypoints, { place: f.ridge.id })).toBe(4);
});
it('LIB3-SVC-007: without its points the new tour keeps the kept line as it is and has no points at all', async () => {
const f = await fixture();
const kept = await keep(f);
const result = await service.takeOver(String(f.next.id), f.owner.id, {
collection_id: f.list.id,
collection_tour_id: kept.id,
include_waypoints: false,
name: 'Line only',
});
const copy = result.tour.place_id;
expect(result.tour.name).toBe('Line only');
expect(await countRows(orm, TourWaypoints, { place: copy })).toBe(0);
expect((await findRow(orm, Places, { id: copy }))?.route_geometry).toBe(JSON.stringify(LINE));
expect(await countRows(orm, Places, { trip: f.next.id })).toBe(1);
expect((await findRows(orm, Tours, { place: copy }))[0]).toMatchObject({ distance: 4.2, elevation_gain: 300 });
});
it('LIB3-SVC-008: a kept walk without a line cannot leave its points behind, and nothing is written', async () => {
const f = await fixture();
const walk = await makePlace(orm, f.alps.id, { name: 'Old town', lat: 48.1, lng: 11.5 });
await makeTour(orm, walk.id, { tourTypeRef: 'walk' });
await addTourWaypoints(orm, walk.id, [
{ lat: 48.1, lng: 11.5, station_key: 'stop-gate-1', name: 'Gate', stay_minutes: 20 },
{ lat: 48.11, lng: 11.51, station_key: 'stop-dome-1', name: 'Dome' },
]);
const { tour: kept } = await service.save(f.owner.id, f.list.id, {
source_trip_id: f.alps.id,
source_place_id: walk.id,
});
expect(kept).toMatchObject({
has_line: false,
station_count: 2,
station_stay_minutes: 20,
station_stays_unknown: 1,
});
const before = await countRows(orm, Places);
expect(
await refusal(
service.takeOver(String(f.next.id), f.owner.id, {
collection_id: f.list.id,
collection_tour_id: kept.id,
include_waypoints: false,
}),
),
).toEqual({ status: 409, error: 'This tour has no line yet, so its points have to come along' });
expect(await countRows(orm, Places)).toBe(before);
// With its points it comes over as a walk still waiting for its way.
const result = await service.takeOver(String(f.next.id), f.owner.id, {
collection_id: f.list.id,
collection_tour_id: kept.id,
include_waypoints: true,
});
expect(result.tour).toMatchObject({ tour_type: 'walk', route_pending: true });
expect(result.waypoints.map((point) => point.name)).toEqual(['Gate', 'Dome']);
});
it('LIB3-SVC-009: refuses a list out of sight, a tour of another list, and a tour removed while it is made', async () => {
const f = await fixture();
const kept = await keep(f);
const other = await makeCollection(orm, f.owner.id, { name: 'Other' });
const body = { collection_id: f.list.id, collection_tour_id: kept.id, include_waypoints: true };
expect(await refusal(service.takeOver(String(f.away.id), f.outsider.id, body))).toEqual({
status: 404,
error: 'Collection not found',
});
expect(
await refusal(service.takeOver(String(f.next.id), f.owner.id, { ...body, collection_id: other.id })),
).toEqual({ status: 404, error: 'Tour not found' });
// Gone between the check and the write: the write leaves no half-made tour behind.
const repo = t.moduleRef.get<CollectionToursRepository>(getRepositoryToken(CollectionTours), { strict: false });
const find = repo.findInCollection.bind(repo);
vi.spyOn(repo, 'findInCollection')
.mockImplementationOnce(find)
.mockResolvedValueOnce(undefined);
const before = await countRows(orm, Places);
expect(await refusal(service.takeOver(String(f.next.id), f.owner.id, body))).toEqual({
status: 404,
error: 'Tour not found',
});
expect(await countRows(orm, Places)).toBe(before);
});
it('LIB3-SVC-010: a tour type switched off since cannot be taken into a trip', async () => {
const f = await fixture();
const kept = await keep(f);
await updateRows(orm, CollectionTours, { id: kept.id }, { tourTypeRef: 'food' });
const before = await countRows(orm, Places);
const refused = await refusal(
service.takeOver(String(f.next.id), f.owner.id, {
collection_id: f.list.id,
collection_tour_id: kept.id,
include_waypoints: true,
}),
);
expect(refused.status).toBe(400);
expect(await countRows(orm, Places)).toBe(before);
});
it('LIB3-SVC-011: only the owner or an admin of the list removes a kept tour; tours made from it stay', async () => {
const f = await fixture();
const kept = await keep(f);
const made = await service.takeOver(String(f.next.id), f.owner.id, {
collection_id: f.list.id,
collection_tour_id: kept.id,
include_waypoints: true,
});
expect(await refusal(service.remove(f.editor.id, f.list.id, kept.id))).toEqual({
status: 403,
error: 'Only an admin can remove tours from this list',
});
t.realtime.broadcastToUserMock.mockClear();
await service.remove(f.owner.id, f.list.id, kept.id);
expect(t.realtime.broadcastToUserMock).toHaveBeenCalled();
expect(await countRows(orm, CollectionTours)).toBe(0);
expect(await findRow(orm, Places, { id: made.tour.place_id })).not.toBeNull();
expect(await refusal(service.remove(f.owner.id, f.list.id, kept.id))).toEqual({
status: 404,
error: 'Tour not found',
});
});
it('LIB3-SVC-012: with the Collections addon off there is nothing to read, keep or take', async () => {
const f = await fixture();
const kept = await keep(f);
await setAddonEnabled(orm, 'collections', false);
const off = { status: 404, error: 'Collections addon is not enabled' };
expect(await refusal(service.list(f.owner.id, f.list.id))).toEqual(off);
expect(
await refusal(service.save(f.owner.id, f.list.id, { source_trip_id: f.alps.id, source_place_id: f.ridge.id })),
).toEqual(off);
expect(await refusal(service.remove(f.owner.id, f.list.id, kept.id))).toEqual(off);
expect(
await refusal(
service.takeOver(String(f.next.id), f.owner.id, {
collection_id: f.list.id,
collection_tour_id: kept.id,
include_waypoints: true,
}),
),
).toEqual(off);
});
});