mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
feat(tours): bike tours in the contract and on the server (BIK-01 to BIK-06, RTE-01)
A tour can be a bike tour with a routing profile (touring, road, gravel, mtb), stored per tour by a new migration. The server grades the ways of a mountain bike route from OpenStreetMap (mtb:scale) through one shared Overpass client, offers CyclOSM behind its own admin switch, and exports a bike tour's GPX with the activity of its profile. A hike's route choices are now exactly the three the card names: steep climbs, steps and ferries.
This commit is contained in:
@@ -137,6 +137,7 @@ describe('GET /api/addons e2e (real auth guard + temp SQLite)', () => {
|
||||
// Tours is off in this database, so wanderer is not offered either.
|
||||
toursWanderer: false,
|
||||
toursHikingMap: false,
|
||||
toursCycleMap: false,
|
||||
addons: [
|
||||
{ id: 'packing', name: 'Packing', type: 'trip', icon: 'Backpack', enabled: true },
|
||||
{ id: 'journey', name: 'Journey', type: 'global', icon: 'Compass', enabled: true },
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* Tours e2e for bike tours (BIK-01 to BIK-05): a bike tour saved, read, copied,
|
||||
* imported and exported with its profile, 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 { MapsService } from '../../src/nest/maps/maps.service';
|
||||
import { OverpassElementsClient } from '../../src/nest/overpass/overpass-elements.client';
|
||||
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 mapsPois = vi.fn();
|
||||
// The trail grades (BIK-05) read OpenStreetMap through Overpass: no network in a test.
|
||||
const overpassQuery = vi.fn();
|
||||
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 bikeBody = (overrides: Record<string, unknown> = {}) => ({
|
||||
name: 'Lakeside ride',
|
||||
tour_type: 'bike',
|
||||
bike_profile: 'gravel',
|
||||
route_geometry: GEOMETRY,
|
||||
waypoints: [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 1 },
|
||||
],
|
||||
duration_seconds: 1800,
|
||||
...overrides,
|
||||
});
|
||||
const GPX = `<?xml version="1.0"?>
|
||||
<gpx version="1.1" creator="e2e"><trk><name>Gravel loop</name><trkseg>
|
||||
<trkpt lat="47" lon="11"><ele>600</ele></trkpt>
|
||||
<trkpt lat="47.01" lon="11.01"><ele>640</ele></trkpt>
|
||||
</trkseg></trk></gpx>`;
|
||||
|
||||
describe('Bike 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)
|
||||
.overrideProvider(MapsService)
|
||||
.useValue({ pois: mapsPois })
|
||||
.overrideProvider(OverpassElementsClient)
|
||||
.useValue({ query: overpassQuery })
|
||||
.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> = bikeBody()) => {
|
||||
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();
|
||||
});
|
||||
|
||||
const send = (method: 'post' | 'put', path: string, body: Record<string, unknown>, userId = OWNER) =>
|
||||
request(server)[method](`/api/trips/5/tours${path}`).set('Cookie', sessionCookie(userId)).send(body);
|
||||
|
||||
const gpxTypeOf = async (placeId: number) => {
|
||||
const res = 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));
|
||||
});
|
||||
return /<type>([^<]+)<\/type>/.exec(String(res.body))?.[1] ?? '';
|
||||
};
|
||||
|
||||
describe('a bike tour and its profile (BIK-01 to BIK-04)', () => {
|
||||
it('saves a bike tour with its profile, lists it so and broadcasts the change', async () => {
|
||||
const placeId = await createViaApi();
|
||||
const row = await findRow(orm, Tours, { place: placeId });
|
||||
expect(row).toMatchObject({ bike_profile: 'gravel', max_hiking_difficulty: null, boat_type: null });
|
||||
const list = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(VIEWER));
|
||||
expect(list.status).toBe(200);
|
||||
const tour = list.body.tours.find((item: { place_id: number }) => item.place_id === placeId);
|
||||
expect(tour).toMatchObject({ tour_type: 'bike', bike_profile: 'gravel', duration: 30 });
|
||||
expect(tour.elevation_gain).toBe(100);
|
||||
expect(realtime.broadcastMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a bike tour without a profile, with a hiking limit, or over a via ferrata', async () => {
|
||||
const ferrata = { kind: 'ferrata', ref: 'way/1', name: null, geometry: [GEOMETRY[0], GEOMETRY[2]] };
|
||||
const bodies = [
|
||||
bikeBody({ bike_profile: null }),
|
||||
bikeBody({ bike_profile: 'ebike' }),
|
||||
bikeBody({ max_hiking_difficulty: 3 }),
|
||||
bikeBody({
|
||||
waypoints: [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0, fixed_leg: ferrata },
|
||||
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 1 },
|
||||
],
|
||||
}),
|
||||
];
|
||||
const statuses = await bodies.reduce<Promise<number[]>>(
|
||||
async (done, body) => [...(await done), (await send('post', '', body)).status],
|
||||
Promise.resolve([]),
|
||||
);
|
||||
expect(statuses).toEqual([400, 400, 400, 400]);
|
||||
expect(await countRows(orm, Tours)).toBe(0);
|
||||
});
|
||||
|
||||
it('changes the profile with an edit, and a hike made of it keeps none', async () => {
|
||||
const placeId = await createViaApi();
|
||||
const road = await send('put', `/${placeId}`, bikeBody({ bike_profile: 'road', expected_revision: 1 }));
|
||||
expect(road.status).toBe(200);
|
||||
expect(road.body.tour).toMatchObject({ bike_profile: 'road', revision: 2 });
|
||||
const hike = await send(
|
||||
'put',
|
||||
`/${placeId}`,
|
||||
bikeBody({ tour_type: 'hike', bike_profile: undefined, max_hiking_difficulty: 2, expected_revision: 2 }),
|
||||
);
|
||||
expect(hike.status).toBe(200);
|
||||
expect(await findRow(orm, Tours, { place: placeId })).toMatchObject({
|
||||
tour_type: 'hike',
|
||||
bike_profile: null,
|
||||
max_hiking_difficulty: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('a member who may only read cannot save one', async () => {
|
||||
expect((await send('post', '', bikeBody(), VIEWER)).status).toBe(403);
|
||||
});
|
||||
|
||||
it('a copy keeps the profile', async () => {
|
||||
const placeId = await createViaApi(5, bikeBody({ bike_profile: 'mtb' }));
|
||||
const copy = await send('post', `/${placeId}/copy`, { name: 'Again' });
|
||||
expect(copy.status).toBe(201);
|
||||
expect(copy.body.tour).toMatchObject({ tour_type: 'bike', bike_profile: 'mtb' });
|
||||
});
|
||||
|
||||
it('exports a bike tour as the activity its profile names', async () => {
|
||||
const kinds: Record<string, string> = {
|
||||
touring: 'cycling',
|
||||
road: 'road_biking',
|
||||
gravel: 'gravel_cycling',
|
||||
mtb: 'mountain_biking',
|
||||
};
|
||||
const types = await Object.keys(kinds).reduce<Promise<string[]>>(
|
||||
async (done, profile) => [
|
||||
...(await done),
|
||||
await gpxTypeOf(await createViaApi(5, bikeBody({ bike_profile: profile }))),
|
||||
],
|
||||
Promise.resolve([]),
|
||||
);
|
||||
expect(types).toEqual(Object.values(kinds));
|
||||
});
|
||||
|
||||
it('imports a GPX file as a bike tour only with its profile', async () => {
|
||||
const importGpx = (fields: Record<string, string>) => {
|
||||
let req = request(server).post('/api/trips/5/tours/import/gpx').set('Cookie', sessionCookie(OWNER));
|
||||
for (const [key, value] of Object.entries(fields)) req = req.field(key, value);
|
||||
return req.attach('file', Buffer.from(GPX), { filename: 'loop.gpx', contentType: 'application/gpx+xml' });
|
||||
};
|
||||
expect((await importGpx({ tour_type: 'bike' })).status).toBe(400);
|
||||
const res = await importGpx({ tour_type: 'bike', bike_profile: 'road' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.tours[0]).toMatchObject({ tour_type: 'bike', bike_profile: 'road', origin: 'gpx' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST trail-grades (BIK-05)', () => {
|
||||
const ask = (body: unknown, userId?: number, tripId = 5) => {
|
||||
const req = request(server).post(`/api/trips/${tripId}/tours/trail-grades`);
|
||||
return (userId ? req.set('Cookie', sessionCookie(userId)) : req).send(body as object);
|
||||
};
|
||||
|
||||
it('answers the grades of the ways asked about to anyone who sees the trip', async () => {
|
||||
overpassQuery.mockResolvedValueOnce([
|
||||
{ type: 'way', id: 11, tags: { 'mtb:scale': '2', 'mtb:scale:uphill': '1' } },
|
||||
]);
|
||||
const res = await ask({ way_ids: [11, 12] }, VIEWER);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
ways: [{ id: 11, mtb_scale: '2', mtb_scale_uphill: '1', mtb_scale_imba: null }],
|
||||
unanswered: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses an outsider, a body it does not know, and no session', async () => {
|
||||
expect((await ask({ way_ids: [1] }, OUTSIDER)).status).toBe(404);
|
||||
const statuses = await [{ way_ids: [] }, { way_ids: [0] }, { way_ids: [1], extra: 1 }].reduce<Promise<number[]>>(
|
||||
async (done, body) => [...(await done), (await ask(body, OWNER)).status],
|
||||
Promise.resolve([]),
|
||||
);
|
||||
expect(statuses).toEqual([400, 400, 400]);
|
||||
expect((await ask({ way_ids: [1] })).status).toBe(401);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -435,15 +435,15 @@ describe('Tours planned e2e (real guards + temp SQLite)', () => {
|
||||
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 } }),
|
||||
tourBody({ hiking_preferences: { avoid_climbs: true, avoid_steps: true, avoid_ferries: 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 });
|
||||
expect(detail.body.tour.hiking_preferences).toEqual({ avoid_climbs: true, avoid_steps: 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 });
|
||||
expect(copy.body.tour.hiking_preferences).toEqual({ avoid_climbs: true, avoid_steps: true });
|
||||
|
||||
// An edit that switches them all off keeps none; one without the field keeps none too.
|
||||
const off = await request(server)
|
||||
|
||||
@@ -63,6 +63,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101044900_a_tour_waypoint_can_be_a_place_of_the_trip',
|
||||
'Migration20200101045000_a_hike_keeps_its_routing_preferences',
|
||||
'Migration20200101045100_a_tour_remembers_the_trip_it_was_taken_from',
|
||||
'Migration20200101045200_a_tour_can_be_ridden',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -101,6 +101,7 @@ describe('ToursRepository reads', () => {
|
||||
has_recorded_track: 0,
|
||||
revision: 1,
|
||||
hiking_preferences: null,
|
||||
bike_profile: null,
|
||||
},
|
||||
{
|
||||
place_id: older.id,
|
||||
@@ -131,6 +132,7 @@ describe('ToursRepository reads', () => {
|
||||
has_recorded_track: 0,
|
||||
revision: 1,
|
||||
hiking_preferences: null,
|
||||
bike_profile: null,
|
||||
},
|
||||
]);
|
||||
expect((await repo.listForTrip(trip.id)).map((r) => r.place_id)).not.toContain(plain.id);
|
||||
@@ -217,6 +219,7 @@ describe('ToursRepository writes', () => {
|
||||
has_recorded_track: 0,
|
||||
revision: 1,
|
||||
hiking_preferences: null,
|
||||
bike_profile: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -297,6 +300,7 @@ describe('ToursRepository writes', () => {
|
||||
track_marks: null,
|
||||
revision: 1,
|
||||
hiking_preferences: null,
|
||||
bike_profile: null,
|
||||
taken_over_from_trip_title: null,
|
||||
taken_over_from_tour_name: null,
|
||||
},
|
||||
|
||||
@@ -60,6 +60,12 @@ describe('global CSP: the other shipped raster presets (#2180)', () => {
|
||||
expect(await connectSrcSources()).toContain('https://tile.openmaps.fr');
|
||||
});
|
||||
|
||||
it('allows the CyclOSM shards the Tours planner offers as a cycling base map (BIK-06), and nothing wider', async () => {
|
||||
const sources = await connectSrcSources();
|
||||
for (const shard of ['a', 'b', 'c']) expect(sources).toContain(`https://${shard}.tile-cyclosm.openstreetmap.fr`);
|
||||
expect(sources).not.toContain('https://*.openstreetmap.fr');
|
||||
});
|
||||
|
||||
it('keeps the routing host, which is a different host and covers nothing here', async () => {
|
||||
// routing.openstreetmap.de was on the list all along and looks close enough
|
||||
// to hide the gap: a CSP source matches a host, not a suffix of one.
|
||||
|
||||
@@ -439,6 +439,22 @@ describe('AddonsService addon/feature flags', () => {
|
||||
expect((await svc.list()).toursHikingMap).toBe(false);
|
||||
});
|
||||
|
||||
it('CyclOSM under Tours is on until an admin switches it off, and offered only with Tours (BIK-06)', async () => {
|
||||
expect(await svc.getToursCycleMap()).toEqual({ enabled: true }); // absent row → ON
|
||||
expect((await svc.list()).toursCycleMap).toBe(false); // Tours is off
|
||||
await insertAddon({ id: 'tours', name: 'Tours', enabled: 1 });
|
||||
expect((await svc.list()).toursCycleMap).toBe(true);
|
||||
|
||||
expect(await svc.updateToursCycleMap(false)).toEqual({ enabled: false });
|
||||
expect(await storedAppSetting('tours_cycle_map_enabled')).toEqual({
|
||||
key: 'tours_cycle_map_enabled',
|
||||
value: 'false',
|
||||
});
|
||||
expect((await svc.list()).toursCycleMap).toBe(false);
|
||||
// The two maps are switched apart.
|
||||
expect((await svc.list()).toursHikingMap).toBe(true);
|
||||
});
|
||||
|
||||
it('getCollabFeatures is opt-out: absent rows default ON, only false disables', async () => {
|
||||
await setAppSetting('collab_chat_enabled', 'false');
|
||||
await setAppSetting('collab_polls_enabled', 'true');
|
||||
|
||||
@@ -48,6 +48,8 @@ const addonsStub = () =>
|
||||
updateToursWanderer: vi.fn((enabled: boolean) => ({ enabled })),
|
||||
getToursHikingMap: vi.fn(() => ({ enabled: true })),
|
||||
updateToursHikingMap: vi.fn((enabled: boolean) => ({ enabled })),
|
||||
getToursCycleMap: vi.fn(() => ({ enabled: true })),
|
||||
updateToursCycleMap: vi.fn((enabled: boolean) => ({ enabled })),
|
||||
getPlacesPhotos: vi.fn(() => ({ enabled: false })),
|
||||
updatePlacesPhotos: vi.fn((enabled: boolean) => ({ enabled })),
|
||||
getPlacesAutocomplete: vi.fn(() => ({ enabled: false })),
|
||||
@@ -495,6 +497,7 @@ describe('AdminController feature toggles', () => {
|
||||
[() => c.updateBagTracking(user, { enabled: true }, req), 'admin.bag_tracking', 'updateBagTracking'],
|
||||
[() => c.updateToursWanderer(user, { enabled: true }, req), 'admin.tours_wanderer', 'updateToursWanderer'],
|
||||
[() => c.updateToursHikingMap(user, { enabled: true }, req), 'admin.tours_hiking_map', 'updateToursHikingMap'],
|
||||
[() => c.updateToursCycleMap(user, { enabled: true }, req), 'admin.tours_cycle_map', 'updateToursCycleMap'],
|
||||
[() => c.updatePlacesPhotos(user, { enabled: true }, req), 'admin.places_photos', 'updatePlacesPhotos'],
|
||||
[
|
||||
() => c.updatePlacesAutocomplete(user, { enabled: true }, req),
|
||||
@@ -517,6 +520,7 @@ describe('AdminController feature toggles', () => {
|
||||
expect(await c.getBagTracking()).toEqual({ enabled: false });
|
||||
expect(await c.getToursWanderer()).toEqual({ enabled: false });
|
||||
expect(await c.getToursHikingMap()).toEqual({ enabled: true });
|
||||
expect(await c.getToursCycleMap()).toEqual({ enabled: true });
|
||||
expect(await c.getPlacesPhotos()).toEqual({ enabled: false });
|
||||
expect(await c.getPlacesAutocomplete()).toEqual({ enabled: false });
|
||||
expect(await c.getPlacesDetails()).toEqual({ enabled: false });
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
ferrataTileBlocks,
|
||||
ferrataTileKeysFor,
|
||||
ferrataTilesBbox,
|
||||
overpassFerrataAnswerSchema,
|
||||
parseFerrataGrade,
|
||||
snapFerrataBbox,
|
||||
splitFerratasByTile,
|
||||
@@ -211,18 +210,6 @@ describe('buildFerrataQuery', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('overpassFerrataAnswerSchema', () => {
|
||||
it('accepts an element list with or without a remark', () => {
|
||||
expect(overpassFerrataAnswerSchema.safeParse({ elements: [] }).success).toBe(true);
|
||||
expect(overpassFerrataAnswerSchema.safeParse({ elements: [], remark: 'runtime error' }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a body without elements', () => {
|
||||
expect(overpassFerrataAnswerSchema.safeParse({ error: 'x' }).success).toBe(false);
|
||||
expect(overpassFerrataAnswerSchema.safeParse(undefined).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toFerratas', () => {
|
||||
it('maps a way to the wire row', () => {
|
||||
const { ferratas, truncated } = toFerratas([way(42, { name: ' Pisciadù ', via_ferrata_scale: '3+' })]);
|
||||
|
||||
@@ -6,13 +6,13 @@
|
||||
import { FerrataTiles } from '../../../src/db/entities/FerrataTiles.entity';
|
||||
import { FerrataTilesRepository } from '../../../src/db/repositories/FerrataTiles.repository';
|
||||
import { DomainError } from '../../../src/nest/common/domain-error';
|
||||
import { FerratasOverpassClient } from '../../../src/nest/ferratas/ferratas-overpass.client';
|
||||
import { FerratasModule } from '../../../src/nest/ferratas/ferratas.module';
|
||||
import {
|
||||
FERRATA_TILE_STALE_MS,
|
||||
FERRATAS_UNAVAILABLE_MESSAGE,
|
||||
FerratasService,
|
||||
} from '../../../src/nest/ferratas/ferratas.service';
|
||||
import { OverpassElementsClient } from '../../../src/nest/overpass/overpass-elements.client';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { countRows, deleteRows, findRow, findRows, insertRows } from '../../helpers/factories/rows';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
@@ -73,7 +73,7 @@ async function boot(): Promise<void> {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [FerratasModule],
|
||||
overrides: [{ provide: FerratasOverpassClient, useValue: { query } }],
|
||||
overrides: [{ provide: OverpassElementsClient, useValue: { query } }],
|
||||
});
|
||||
service = t.get(FerratasService);
|
||||
}
|
||||
|
||||
+22
-10
@@ -1,20 +1,20 @@
|
||||
import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
|
||||
import { FerratasOverpassClient } from '../../../src/nest/ferratas/ferratas-overpass.client';
|
||||
import { parseOverpassEndpoints } from '../../../src/nest/maps/overpass.constants';
|
||||
import { OverpassElementsClient, overpassAnswerSchema } from '../../../src/nest/overpass/overpass-elements.client';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const integrations = { overpassUrl: undefined as string | undefined, overpassTimeoutMs: 5000 };
|
||||
let client: FerratasOverpassClient;
|
||||
let client: OverpassElementsClient;
|
||||
|
||||
beforeEach(async () => {
|
||||
integrations.overpassUrl = 'https://a.example/api/interpreter,https://b.example/api/interpreter';
|
||||
integrations.overpassTimeoutMs = 5000;
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [FerratasOverpassClient, { provide: RuntimeEnvService, useValue: { env: () => ({ integrations }) } }],
|
||||
providers: [OverpassElementsClient, { provide: RuntimeEnvService, useValue: { env: () => ({ integrations }) } }],
|
||||
}).compile();
|
||||
client = moduleRef.get(FerratasOverpassClient);
|
||||
client = moduleRef.get(OverpassElementsClient);
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
@@ -46,12 +46,12 @@ describe('parseOverpassEndpoints', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('FerratasOverpassClient.query', () => {
|
||||
describe('OverpassElementsClient.query', () => {
|
||||
it('POSTs the query with a user agent and a deadline, and answers the elements', async () => {
|
||||
const fetcher = vi.fn(async (_url: string, _init: RequestInit) => json({ elements: [{ type: 'way', id: 1 }] }));
|
||||
vi.stubGlobal('fetch', fetcher);
|
||||
integrations.overpassUrl = 'https://a.example/api/interpreter';
|
||||
const elements = await client.query('[out:json];way(1);out;');
|
||||
const elements = await client.query('[out:json];way(1);out;', 'Ferratas');
|
||||
expect(elements).toEqual([{ type: 'way', id: 1 }]);
|
||||
const [url, init] = fetcher.mock.calls[0] ?? [];
|
||||
expect(url).toBe('https://a.example/api/interpreter');
|
||||
@@ -71,7 +71,7 @@ describe('FerratasOverpassClient.query', () => {
|
||||
return json({ elements: [{ type: 'way', id: 2 }] });
|
||||
}),
|
||||
);
|
||||
expect(await client.query('q')).toEqual([{ type: 'way', id: 2 }]);
|
||||
expect(await client.query('q', 'Ferratas')).toEqual([{ type: 'way', id: 2 }]);
|
||||
expect(signals.every((s) => s.aborted)).toBe(true);
|
||||
});
|
||||
|
||||
@@ -80,7 +80,7 @@ describe('FerratasOverpassClient.query', () => {
|
||||
'fetch',
|
||||
vi.fn(async (url: string) => (url.startsWith('https://a.') ? json({}, 504) : json({ elements: 'nope' }))),
|
||||
);
|
||||
await expect(client.query('q')).rejects.toThrow('Could not reach any Overpass endpoint');
|
||||
await expect(client.query('q', 'Ferratas')).rejects.toThrow('Could not reach any Overpass endpoint');
|
||||
});
|
||||
|
||||
it('throws when a mirror cannot be reached at all', async () => {
|
||||
@@ -90,7 +90,7 @@ describe('FerratasOverpassClient.query', () => {
|
||||
throw new TypeError('fetch failed');
|
||||
}),
|
||||
);
|
||||
await expect(client.query('q')).rejects.toThrow('Could not reach any Overpass endpoint');
|
||||
await expect(client.query('q', 'Ferratas')).rejects.toThrow('Could not reach any Overpass endpoint');
|
||||
});
|
||||
|
||||
it('refuses an answer larger than the cap', async () => {
|
||||
@@ -101,6 +101,18 @@ describe('FerratasOverpassClient.query', () => {
|
||||
new Response('{"elements":[]}', { status: 200, headers: { 'content-length': String(9 * 1024 * 1024) } }),
|
||||
),
|
||||
);
|
||||
await expect(client.query('q')).rejects.toThrow('Could not reach any Overpass endpoint');
|
||||
await expect(client.query('q', 'Ferratas')).rejects.toThrow('Could not reach any Overpass endpoint');
|
||||
});
|
||||
});
|
||||
|
||||
describe('overpassAnswerSchema', () => {
|
||||
it('accepts an element list with or without a remark', () => {
|
||||
expect(overpassAnswerSchema.safeParse({ elements: [] }).success).toBe(true);
|
||||
expect(overpassAnswerSchema.safeParse({ elements: [], remark: 'runtime error' }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a body without elements', () => {
|
||||
expect(overpassAnswerSchema.safeParse({ error: 'x' }).success).toBe(false);
|
||||
expect(overpassAnswerSchema.safeParse(undefined).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { OverpassElementsClient } from '../../../src/nest/overpass/overpass-elements.client';
|
||||
import { TourTrailGradeService } from '../../../src/nest/tours/tour-trail-grade.service';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// TOUR-GRADE-001 to TOUR-GRADE-005
|
||||
|
||||
const query = vi.fn<(q: string, caller: string) => Promise<unknown[]>>();
|
||||
let service: TourTrailGradeService;
|
||||
|
||||
beforeEach(async () => {
|
||||
query.mockReset();
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [TourTrailGradeService, { provide: OverpassElementsClient, useValue: { query } }],
|
||||
}).compile();
|
||||
service = moduleRef.get(TourTrailGradeService);
|
||||
});
|
||||
|
||||
const way = (id: number, tags: Record<string, string>) => ({ type: 'way', id, tags });
|
||||
|
||||
describe('TourTrailGradeService (BIK-05)', () => {
|
||||
it('TOUR-GRADE-001: reads each scale to its steps and leaves a way without one out', async () => {
|
||||
query.mockResolvedValue([
|
||||
way(1, { 'mtb:scale': '2+', 'mtb:scale:uphill': '3' }),
|
||||
way(2, { 'mtb:scale': 'S1', 'mtb:scale:imba': '2' }),
|
||||
way(3, { highway: 'track' }),
|
||||
way(4, { 'mtb:scale': '9', 'mtb:scale:imba': 'hard' }),
|
||||
]);
|
||||
const answer = await service.grades({ way_ids: [1, 2, 3, 4, 5] });
|
||||
expect(answer).toEqual({
|
||||
ways: [
|
||||
{ id: 1, mtb_scale: '2+', mtb_scale_uphill: '3', mtb_scale_imba: null },
|
||||
{ id: 2, mtb_scale: '1', mtb_scale_uphill: null, mtb_scale_imba: '2' },
|
||||
],
|
||||
unanswered: [],
|
||||
});
|
||||
expect(query).toHaveBeenCalledWith('[out:json][timeout:25];way(id:1,2,3,4,5);out tags;', 'Tours');
|
||||
});
|
||||
|
||||
it('TOUR-GRADE-002: names the ways it could not ask about, never guesses them', async () => {
|
||||
query.mockRejectedValue(new Error('all mirrors down'));
|
||||
expect(await service.grades({ way_ids: [7, 8] })).toEqual({ ways: [], unanswered: [7, 8] });
|
||||
});
|
||||
|
||||
it('TOUR-GRADE-003: asks a long tour in parts, one after another, and keeps what one part answered', async () => {
|
||||
const ids = Array.from({ length: 900 }, (_, index) => index + 1);
|
||||
query
|
||||
.mockResolvedValueOnce([way(1, { 'mtb:scale': '0' })])
|
||||
.mockRejectedValueOnce(new Error('timeout'))
|
||||
.mockResolvedValueOnce([way(900, { 'mtb:scale': '5' })]);
|
||||
const answer = await service.grades({ way_ids: ids });
|
||||
expect(query).toHaveBeenCalledTimes(3);
|
||||
expect(answer.ways.map((grade) => grade.id)).toEqual([1, 900]);
|
||||
expect(answer.unanswered).toHaveLength(400);
|
||||
expect(answer.unanswered[0]).toBe(401);
|
||||
});
|
||||
|
||||
it('TOUR-GRADE-004: asks a way it already read only again a day later', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
query.mockResolvedValue([way(1, { 'mtb:scale': '3' })]);
|
||||
await service.grades({ way_ids: [1, 1] });
|
||||
await service.grades({ way_ids: [1] });
|
||||
expect(query).toHaveBeenCalledTimes(1);
|
||||
vi.advanceTimersByTime(24 * 60 * 60 * 1000 + 1);
|
||||
await service.grades({ way_ids: [1] });
|
||||
expect(query).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('TOUR-GRADE-005: skips what is no way in the answer', async () => {
|
||||
query.mockResolvedValue([{ type: 'node', id: 1, tags: { 'mtb:scale': '1' } }, { nonsense: true }]);
|
||||
expect(await service.grades({ way_ids: [1] })).toEqual({ ways: [], unanswered: [] });
|
||||
});
|
||||
});
|
||||
@@ -188,6 +188,7 @@ describe('ToursService planner contracts (mock-only; SQLite rollback semantics a
|
||||
portage_speed_kmh: null,
|
||||
paddle_lake_style: null,
|
||||
hiking_preferences: null,
|
||||
bike_profile: null,
|
||||
});
|
||||
expect((setup.toursRepo.insertTour.mock.calls[0][0] as { distance: number }).distance).toBeGreaterThan(0);
|
||||
expect(setup.waypointsRepo.insertForPlace).toHaveBeenCalledExactlyOnceWith(42, request.waypoints);
|
||||
@@ -305,6 +306,7 @@ describe('ToursService planner contracts (mock-only; SQLite rollback semantics a
|
||||
portage_speed_kmh: null,
|
||||
paddle_lake_style: null,
|
||||
hiking_preferences: null,
|
||||
bike_profile: null,
|
||||
});
|
||||
expect(setup.waypointsRepo.deleteForPlace).toHaveBeenCalledExactlyOnceWith(42);
|
||||
expect(setup.waypointsRepo.insertForPlace).toHaveBeenCalledExactlyOnceWith(42, update.waypoints);
|
||||
|
||||
@@ -250,7 +250,7 @@ describe('ToursService planner creation', () => {
|
||||
it('TOURS-SVC-010: a type the catalogue holds but has not enabled is a 400 without a write', async () => {
|
||||
// The contract only lets `hike` through today; this pins what happens the
|
||||
// day it lets more keys in before the planner offers them.
|
||||
const bike = { ...request, tour_type: 'bike' } as unknown as typeof request;
|
||||
const bike = { ...request, tour_type: 'run' } as unknown as typeof request;
|
||||
|
||||
await expect(service.createTour(tripId, bike)).rejects.toBeInstanceOf(BadRequestException);
|
||||
|
||||
@@ -262,7 +262,7 @@ describe('ToursService planner creation', () => {
|
||||
it('TOURS-SVC-011: an edit to a disabled type is a 400 and leaves the saved tour alone', async () => {
|
||||
const created = await service.createTour(tripId, request);
|
||||
broadcast.mockReset();
|
||||
const bike = { ...request, name: 'Renamed', tour_type: 'bike' } as unknown as typeof request;
|
||||
const bike = { ...request, name: 'Renamed', tour_type: 'run' } as unknown as typeof request;
|
||||
|
||||
await expect(service.updateTour(tripId, String(created.tour.place_id), bike)).rejects.toBeInstanceOf(
|
||||
BadRequestException,
|
||||
|
||||
Reference in New Issue
Block a user