Files
TREK/server/tests/e2e/tours-planned.e2e.test.ts
T
Maurice ad86713fdc feat(tours): route choices for a hike, each checked against the router (MF-08)
A hike can ask the router for more than its difficulty limit: avoid steps,
avoid ferries, prefer footpaths, shorter over faster. They sit under the
limit in the planner's details as switches, each with what it really does,
and the info dot says they weigh the way and give way where there is no
other, and that none grades a path. Switching one plans the route again as
one step of the history, and the choice is kept in the draft.

Only preferences the public Valhalla was seen to honour are offered, with
the measured cases beside hikingCostingOptions: step_penalty took Würzburg
to the Festung from four flights to one, use_ferry 0 sent Kiel round the
Förde and Hamburg through the Elbe tunnel, walkway_factor moved Garmisch to
the Partnachklamm onto the paths, shortest cut the way to the Eckbauer.
use_hills and use_tracks showed no effect on foot and are left out, as are
marked, paved and rough ways, for which the router has no option.

tours.hiking_preferences (migration 045000) holds them as JSON, NULL for
none, so no tour saved before routes differently. Only a hike keeps them;
a paddle tour naming one is refused. A copy carries them, and list_tours
and get_tour_plan read them.

The trip copy's waypoint links now follow the copied places inside
TourWaypointsRepository.insertForPlace.
2026-10-19 11:31:31 +02:00

477 lines
20 KiB
TypeScript

/**
* Tours e2e for the planner's second round: the GPX export of one tour
* (PR1-06A), through the real JwtAuthGuard, AddonGuard and TripAccessGuard
* against a migrated and seeded temp SQLite db. The permission check is a
* container spy and the broadcast goes to a FakeRealtimeService, as in
* tours.e2e.test.ts.
*
* Fixtures: user 1 owns trips 5 and 6, user 2 is a member of trip 5 whom the
* permission spy denies 'place_edit', user 3 has no access to either trip.
*/
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { Tours } from '../../src/db/entities/Tours.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 { makePlace } from '../helpers/factories/places';
import { countRows, deleteRows, findRow, insertRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { makeTour } from '../helpers/factories/tours';
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 { describe, it, expect, beforeAll, afterAll, beforeEach, 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;
const OWNER = 1;
const VIEWER = 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.02, lng: 11.02, role: 'end', sequence: 1 },
],
max_hiking_difficulty: 3,
duration_seconds: 3600,
...overrides,
});
describe('Tours planned 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 createViaApi = async (tripId = 5, body: Record<string, unknown> = tourBody()) => {
const res = await request(server).post(`/api/trips/${tripId}/tours`).set('Cookie', sessionCookie(OWNER)).send(body);
expect(res.status).toBe(201);
return res.body.tour.place_id as number;
};
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: 'viewer', email: 'viewer@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);
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(async () => {
checkPermission.mockImplementation(
(action: string, _role: string, _owner: number, userId: number) =>
!(action === 'place_edit' && userId === VIEWER),
);
await setAddonEnabled(orm, 'tours', true);
realtime.broadcastMock.mockClear();
await deleteRows(orm, DayAssignments);
await deleteRows(orm, Places);
});
afterAll(async () => {
await app.close();
await orm.close();
});
describe('GET :placeId/export.gpx (PR1-06A)', () => {
const exportGpx = (userId: number, placeId: number, tripId = 5) =>
request(server)
.get(`/api/trips/${tripId}/tours/${placeId}/export.gpx`)
.set('Cookie', sessionCookie(userId))
.buffer(true)
.parse((res, done) => {
let text = '';
res.setEncoding('utf8');
res.on('data', (chunk: string) => (text += chunk));
res.on('end', () => done(null, text));
});
it('writes the whole saved line with its heights as one track, named after the tour', async () => {
const placeId = await createViaApi(5, tourBody({ name: 'Grat über Ü', description: 'Früh los.' }));
const res = await exportGpx(OWNER, placeId);
expect(res.status).toBe(200);
expect(res.headers['content-type']).toBe('application/gpx+xml; charset=utf-8');
expect(res.headers['content-disposition']).toContain("filename*=UTF-8''Grat-%C3%BCber-%C3%9C.gpx");
const gpx = res.body as string;
expect(gpx).toContain('<name>Grat über Ü</name>');
expect(gpx).toContain('<desc>Früh los.</desc>');
expect(gpx).toContain('<type>hiking</type>');
expect(gpx.match(/<trkpt /g)).toHaveLength(GEOMETRY.length);
expect(gpx).toContain('<trkpt lat="47.01" lon="11.01">');
expect(gpx).toContain('<ele>700</ele>');
});
it('writes no height a point lacks, and names a paddle tour by its boat', async () => {
const place = await makePlace(orm, 5, {
name: 'Canal',
route_geometry: JSON.stringify([
[48, 12],
[48.01, 12.01, 300],
]),
});
await makeTour(orm, place.id, {
tourTypeRef: 'kayak',
boat_type: 'canoe',
water_context: 'river',
origin: 'gpx',
});
const res = await exportGpx(OWNER, place.id);
expect(res.status).toBe(200);
const gpx = res.body as string;
expect(gpx).toContain('<type>canoeing</type>');
expect(gpx.match(/<ele>/g)).toHaveLength(1);
});
it('a member who may only read can export; the export changes nothing', async () => {
const placeId = await createViaApi();
const before = await findRow(orm, Tours, { place: placeId });
realtime.broadcastMock.mockClear();
const res = await exportGpx(VIEWER, placeId);
expect(res.status).toBe(200);
expect(await findRow(orm, Tours, { place: placeId })).toEqual(before);
expect(realtime.broadcastMock).not.toHaveBeenCalled();
});
it('422 for a tour without a line of two points, 404 for one of another trip or none', async () => {
const lonely = await makePlace(orm, 5, { name: 'Dot', route_geometry: JSON.stringify([[47, 11, 1]]) });
await makeTour(orm, lonely.id, { origin: 'gpx' });
const refused = await request(server)
.get(`/api/trips/5/tours/${lonely.id}/export.gpx`)
.set('Cookie', sessionCookie(OWNER));
expect(refused.status).toBe(422);
expect(refused.body).toEqual({ error: 'This tour has no route to export' });
const elsewhere = await createViaApi(6);
const wrongTrip = await request(server)
.get(`/api/trips/5/tours/${elsewhere}/export.gpx`)
.set('Cookie', sessionCookie(OWNER));
expect(wrongTrip.status).toBe(404);
expect(wrongTrip.body).toEqual({ error: 'Tour not found' });
const plain = await makePlace(orm, 5, { name: 'Cafe' });
expect(
(await request(server).get(`/api/trips/5/tours/${plain.id}/export.gpx`).set('Cookie', sessionCookie(OWNER)))
.status,
).toBe(404);
});
it('404 Trip not found for an outsider, 404 while the addon is off, 401 without a cookie', async () => {
const placeId = await createViaApi();
const outsider = await request(server)
.get(`/api/trips/5/tours/${placeId}/export.gpx`)
.set('Cookie', sessionCookie(OUTSIDER));
expect(outsider.status).toBe(404);
expect(outsider.body).toEqual({ error: 'Trip not found' });
expect((await request(server).get(`/api/trips/5/tours/${placeId}/export.gpx`)).status).toBe(401);
await setAddonEnabled(orm, 'tours', false);
const off = await request(server)
.get(`/api/trips/5/tours/${placeId}/export.gpx`)
.set('Cookie', sessionCookie(OWNER));
expect(off.status).toBe(404);
expect(off.body).toEqual({ error: 'Tours addon is not enabled' });
});
});
describe('revisions and conflicts (P2C-03)', () => {
const put = (placeId: number, body: Record<string, unknown>) =>
request(server).put(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER)).send(body);
it('a tour starts at 1, and every saved change raises it by one, in the list and the detail', async () => {
const placeId = await createViaApi();
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
expect(detail.body.tour.revision).toBe(1);
const saved = await put(placeId, tourBody({ name: 'Renamed', expected_revision: 1 }));
expect(saved.status).toBe(200);
expect(saved.body.tour).toMatchObject({ name: 'Renamed', revision: 2 });
const list = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(OWNER));
expect(list.body.tours[0].revision).toBe(2);
});
it('409 for a draft based on a revision the tour has left, and nothing of it is written', async () => {
const placeId = await createViaApi();
expect((await put(placeId, tourBody({ name: 'First', expected_revision: 1 }))).status).toBe(200);
realtime.broadcastMock.mockClear();
const stale = await put(
placeId,
tourBody({
name: 'Stale',
expected_revision: 1,
waypoints: [
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1 },
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
],
}),
);
expect(stale.status).toBe(409);
expect(stale.body).toEqual({
error: 'This tour was changed in the meantime',
code: 'tour_revision_conflict',
revision: 2,
});
const after = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
expect(after.body.tour).toMatchObject({ name: 'First', revision: 2 });
expect(after.body.waypoints).toHaveLength(2);
expect(realtime.broadcastMock).not.toHaveBeenCalled();
});
it('a write naming no revision writes as before, so an older client or a queued write still lands', async () => {
const placeId = await createViaApi();
expect((await put(placeId, tourBody({ name: 'One', expected_revision: 1 }))).status).toBe(200);
const blind = await put(placeId, tourBody({ name: 'Two' }));
expect(blind.status).toBe(200);
expect(blind.body.tour).toMatchObject({ name: 'Two', revision: 3 });
});
it('a copy starts at 1 of its own, and the original keeps its count', async () => {
const placeId = await createViaApi();
await put(placeId, tourBody({ expected_revision: 1 }));
const copy = await request(server)
.post(`/api/trips/5/tours/${placeId}/copy`)
.set('Cookie', sessionCookie(OWNER))
.send({ name: 'Copy' });
expect(copy.status).toBe(201);
expect(copy.body.tour.revision).toBe(1);
expect((await findRow(orm, Tours, { place: placeId }))?.revision).toBe(2);
});
it('the plan laid onto a recorded paddle track names its revision too', async () => {
const place = await makePlace(orm, 5, {
name: 'Canal',
route_geometry: JSON.stringify([
[48, 12],
[48.01, 12.01],
]),
});
await makeTour(orm, place.id, {
tourTypeRef: 'kayak',
boat_type: 'kayak',
water_context: 'river',
origin: 'gpx',
});
const plan = { paddle_speed_kmh: 5, portage_speed_kmh: null, track_marks: { portages: [], locks: [] } };
const putPlan = (body: Record<string, unknown>) =>
request(server)
.put(`/api/trips/5/tours/${place.id}/paddle-plan`)
.set('Cookie', sessionCookie(OWNER))
.send(body);
const first = await putPlan({ ...plan, expected_revision: 1 });
expect(first.status).toBe(200);
expect(first.body.tour.revision).toBe(2);
const stale = await putPlan({ ...plan, paddle_speed_kmh: 3, expected_revision: 1 });
expect(stale.status).toBe(409);
expect(stale.body).toMatchObject({ code: 'tour_revision_conflict', revision: 2 });
expect((await findRow(orm, Tours, { place: place.id }))?.paddle_speed_kmh).toBe(5);
});
it('rejects a revision below 1 at the boundary', async () => {
const placeId = await createViaApi();
expect((await put(placeId, tourBody({ expected_revision: 0 }))).status).toBe(400);
});
});
describe('trip places as waypoints (PR1-10)', () => {
const linked = (placeId: number | null) => [
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1, linked_place_id: placeId },
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
];
it('a waypoint stands for a place of the trip, read back with it, and the place stays as it was', async () => {
const hut = await makePlace(orm, 5, { name: 'Höllentalangerhütte', lat: 47.4, lng: 11.0 });
const placeId = await createViaApi(5, tourBody({ waypoints: linked(hut.id) }));
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
expect(detail.body.waypoints.map((point: { linked_place_id?: number }) => point.linked_place_id ?? null)).toEqual(
[null, hut.id, null],
);
// The waypoint keeps its own coordinates; the place keeps its own.
expect(detail.body.waypoints[1]).toMatchObject({ lat: 47.01, lng: 11.01 });
expect(await findRow(orm, Places, { id: hut.id })).toMatchObject({ name: 'Höllentalangerhütte', lat: 47.4 });
expect(await countRows(orm, DayAssignments, { place: hut.id })).toBe(0);
});
it('a place of another trip, or one that is gone, leaves the point unlinked; a tour cannot be stood for', async () => {
const foreign = await makePlace(orm, 6, { name: 'Elsewhere' });
const placeId = await createViaApi(5, tourBody({ waypoints: linked(foreign.id) }));
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
expect(detail.body.waypoints[1].linked_place_id).toBeUndefined();
const missing = await request(server)
.put(`/api/trips/5/tours/${placeId}`)
.set('Cookie', sessionCookie(OWNER))
.send(tourBody({ waypoints: linked(999_999) }));
expect(missing.status).toBe(200);
expect(missing.body.waypoints[1].linked_place_id).toBeUndefined();
const otherTour = await createViaApi();
const refused = await request(server)
.put(`/api/trips/5/tours/${placeId}`)
.set('Cookie', sessionCookie(OWNER))
.send(tourBody({ waypoints: linked(otherTour) }));
expect(refused.status).toBe(400);
expect(refused.body).toEqual({ error: 'A waypoint cannot stand for a tour', code: 'waypoint_links_a_tour' });
});
it('deleting the place keeps the waypoint and only drops the link; the GPX names the stops that stand for a place', async () => {
const hut = await makePlace(orm, 5, { name: 'Kreuzeckhaus' });
const lake = await makePlace(orm, 5, { name: 'Eibsee' });
const placeId = await createViaApi(
5,
tourBody({
waypoints: [
{ lat: 47, lng: 11, role: 'start', sequence: 0, linked_place_id: lake.id },
{ lat: 47.01, lng: 11.01, role: 'via', sequence: 1, linked_place_id: hut.id },
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 2 },
],
}),
);
const gpx = await request(server)
.get(`/api/trips/5/tours/${placeId}/export.gpx`)
.set('Cookie', sessionCookie(OWNER))
.buffer(true)
.parse((res, done) => {
let text = '';
res.setEncoding('utf8');
res.on('data', (chunk: string) => (text += chunk));
res.on('end', () => done(null, text));
});
expect((gpx.body as string).match(/<wpt /g)).toHaveLength(2);
expect(gpx.body).toContain('<name>Kreuzeckhaus</name>');
await deleteRows(orm, Places, { id: hut.id });
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
expect(detail.body.waypoints).toHaveLength(3);
expect(detail.body.waypoints[1].linked_place_id).toBeUndefined();
expect(detail.body.waypoints[0].linked_place_id).toBe(lake.id);
});
});
describe('hiking preferences (MF-08)', () => {
it('a hike keeps the preferences switched on, reads them back, and a copy carries them', async () => {
const placeId = await createViaApi(
5,
tourBody({ hiking_preferences: { avoid_steps: true, prefer_paths: true, shortest: false } }),
);
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
expect(detail.body.tour.hiking_preferences).toEqual({ avoid_steps: true, prefer_paths: true });
const copy = await request(server)
.post(`/api/trips/5/tours/${placeId}/copy`)
.set('Cookie', sessionCookie(OWNER))
.send({ name: 'Copy' });
expect(copy.body.tour.hiking_preferences).toEqual({ avoid_steps: true, prefer_paths: true });
// An edit that switches them all off keeps none; one without the field keeps none too.
const off = await request(server)
.put(`/api/trips/5/tours/${placeId}`)
.set('Cookie', sessionCookie(OWNER))
.send(tourBody({ hiking_preferences: { avoid_steps: false } }));
expect(off.body.tour.hiking_preferences).toBeNull();
expect((await findRow(orm, Tours, { place: placeId }))?.hiking_preferences).toBeNull();
});
it('a tour saved before keeps none, an unknown preference is refused, and a paddle tour has none', async () => {
const plain = await createViaApi();
const detail = await request(server).get(`/api/trips/5/tours/${plain}`).set('Cookie', sessionCookie(OWNER));
expect(detail.body.tour.hiking_preferences).toBeNull();
const unknown = await request(server)
.post('/api/trips/5/tours')
.set('Cookie', sessionCookie(OWNER))
.send(tourBody({ hiking_preferences: { avoid_hills: true } }));
expect(unknown.status).toBe(400);
const paddle = await request(server)
.post('/api/trips/5/tours')
.set('Cookie', sessionCookie(OWNER))
.send(
tourBody({
tour_type: 'kayak',
boat_type: 'kayak',
water_context: 'lake',
max_hiking_difficulty: null,
hiking_preferences: { avoid_steps: true },
}),
);
expect(paddle.status).toBe(400);
});
});
});