mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
fix(tours): fit the merged tracks together after integration
Types, test expectations and helpers the seven tracks each changed on their own, brought in line with the integrated code. tours.service.ts and the tours repository grew past the size limit with every track and hand their row and write helpers to modules of their own.
This commit is contained in:
@@ -8,7 +8,6 @@
|
||||
* Fixtures: user 1 owns trip 5 (two dated days, one without a date), user 2 is
|
||||
* a member, user 3 has no access.
|
||||
*/
|
||||
import { db } from '../../src/db/database';
|
||||
import { AssignmentParticipants } from '../../src/db/entities/AssignmentParticipants.entity';
|
||||
import { Days } from '../../src/db/entities/Days.entity';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
@@ -20,6 +19,7 @@ import { JourneyDomainService } from '../../src/nest/journey/journey-domain.serv
|
||||
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 { makeDayAssignment } from '../helpers/factories/itinerary';
|
||||
import { countRows, deleteRows, insertRow, insertRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
@@ -36,10 +36,6 @@ import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
|
||||
return buildDbMock(createSnapshotTestDb());
|
||||
});
|
||||
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
@@ -48,6 +44,7 @@ vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const journeyHooks = {
|
||||
reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
|
||||
onPlaceCreated: vi.fn().mockResolvedValue(undefined),
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
* Fixtures: user 1 owns trip 5 (two days), user 2 is a member whom the
|
||||
* permission spy denies 'place_edit', user 3 has no access.
|
||||
*/
|
||||
import { db } from '../../src/db/database';
|
||||
import { Days } from '../../src/db/entities/Days.entity';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { TourActivities } from '../../src/db/entities/TourActivities.entity';
|
||||
@@ -20,6 +19,7 @@ import { PermissionsService } from '../../src/nest/permissions/permissions.servi
|
||||
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 { makeDayAssignment } from '../helpers/factories/itinerary';
|
||||
import { countRows, deleteRows, findRow, insertRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
@@ -36,10 +36,6 @@ import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
|
||||
|
||||
vi.mock('../../src/db/database', async () => {
|
||||
const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
|
||||
return buildDbMock(createSnapshotTestDb());
|
||||
});
|
||||
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
@@ -48,6 +44,7 @@ vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const journeyHooks = {
|
||||
reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
|
||||
onPlaceCreated: vi.fn().mockResolvedValue(undefined),
|
||||
|
||||
@@ -325,7 +325,12 @@ describe('Horse tours e2e (real guards + temp SQLite)', () => {
|
||||
.field('tour_type', 'horse')
|
||||
.attach('file', Buffer.from(GPX), { filename: 'ride.gpx', contentType: 'application/gpx+xml' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.tours[0]).toMatchObject({ tour_type: 'horse', origin: 'gpx', duration: null, bike_profile: null });
|
||||
expect(res.body.tours[0]).toMatchObject({
|
||||
tour_type: 'horse',
|
||||
origin: 'gpx',
|
||||
duration: null,
|
||||
bike_profile: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -172,7 +172,11 @@ describe('Runs e2e (real guards + temp SQLite)', () => {
|
||||
});
|
||||
const list = await request(server).get('/api/trips/5/tours').set('Cookie', sessionCookie(VIEWER));
|
||||
expect(list.status).toBe(200);
|
||||
expect(list.body.tours[0]).toMatchObject({ place_id: placeId, run_profile: 'running', run_pace_seconds_per_km: 360 });
|
||||
expect(list.body.tours[0]).toMatchObject({
|
||||
place_id: placeId,
|
||||
run_profile: 'running',
|
||||
run_pace_seconds_per_km: 360,
|
||||
});
|
||||
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
|
||||
expect(detail.body.tour).toMatchObject({ tour_type: 'run', run_profile: 'running', duration: 48 });
|
||||
expect(detail.body.waypoints).toHaveLength(2);
|
||||
|
||||
@@ -195,16 +195,17 @@ describe('Ski tracks e2e (real guards + temp SQLite)', () => {
|
||||
expect(opened.provenance).toMatchObject({ origin: 'gpx', source: { kind: 'gpx', fileName: 'hut.gpx' } });
|
||||
});
|
||||
|
||||
it('TOURS-SKI-E2E-002: a cross-country track keeps its technique, unknown included', async () => {
|
||||
for (const technique of ['classic', 'skating', 'unknown']) {
|
||||
it.each(['classic', 'skating', 'unknown'])(
|
||||
'TOURS-SKI-E2E-002: a cross-country track keeps its technique, unknown included: %s',
|
||||
async (technique) => {
|
||||
const placeId = await importSki({ ski_discipline: 'cross_country', ski_technique: technique });
|
||||
expect(await findRow(orm, Tours, { place: placeId })).toMatchObject({
|
||||
ski_discipline: 'cross_country',
|
||||
ski_technique: technique,
|
||||
});
|
||||
await deleteRows(orm, Places);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('TOURS-SKI-E2E-003: refuses a ski import without its discipline or with a technique it has not, and ski fields on a hike', async () => {
|
||||
const refused = await Promise.all(
|
||||
|
||||
@@ -388,7 +388,9 @@ export function createDayAssignment(
|
||||
};
|
||||
const orderIndex = overrides.order_index ?? (maxOrder.max !== null ? maxOrder.max + 1 : 0);
|
||||
const result = db
|
||||
.prepare('INSERT INTO day_assignments (day_id, place_id, order_index, notes, tour_stage_key) VALUES (?, ?, ?, ?, ?)')
|
||||
.prepare(
|
||||
'INSERT INTO day_assignments (day_id, place_id, order_index, notes, tour_stage_key) VALUES (?, ?, ?, ?, ?)',
|
||||
)
|
||||
.run(dayId, placeId, orderIndex, overrides.notes ?? null, overrides.tour_stage_key ?? null);
|
||||
return db.prepare('SELECT * FROM day_assignments WHERE id = ?').get(result.lastInsertRowid) as TestDayAssignment;
|
||||
}
|
||||
|
||||
@@ -448,14 +448,20 @@ describe('ToursRepository writes', () => {
|
||||
const place = createPlace(testDb, trip.id, { name: 'River loop' });
|
||||
const run = { ...METRICS, tour_type: 'run', max_hiking_difficulty: null };
|
||||
await repo.insertTour({ place_id: place.id, ...run, run_profile: 'running', run_pace_seconds_per_km: 360 });
|
||||
expect(await repo.findInTrip(trip.id, place.id)).toMatchObject({ run_profile: 'running', run_pace_seconds_per_km: 360 });
|
||||
expect(await repo.findInTrip(trip.id, place.id)).toMatchObject({
|
||||
run_profile: 'running',
|
||||
run_pace_seconds_per_km: 360,
|
||||
});
|
||||
|
||||
const faster = { ...HIKE_UPDATE, ...run, run_profile: 'running' as const, run_pace_seconds_per_km: 300 };
|
||||
expect(await repo.updateInTrip(trip.id, place.id, faster)).toBe(true);
|
||||
expect((await repo.listForTrip(trip.id))[0]).toMatchObject({ tour_type: 'run', run_pace_seconds_per_km: 300 });
|
||||
|
||||
expect(await repo.updateInTrip(trip.id, place.id, HIKE_UPDATE)).toBe(true);
|
||||
expect(await repo.findInTrip(trip.id, place.id)).toMatchObject({ run_profile: null, run_pace_seconds_per_km: null });
|
||||
expect(await repo.findInTrip(trip.id, place.id)).toMatchObject({
|
||||
run_profile: null,
|
||||
run_pace_seconds_per_km: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('TOURREPO-024: a ski track keeps its classification, is classified again only in its own trip, and a route edit takes it off (SKI-02)', async () => {
|
||||
@@ -682,8 +688,8 @@ describe('ToursRepository writes', () => {
|
||||
const plainCopy = createPlace(testDb, other.id);
|
||||
await repo.insertTour({ ...METRICS, place_id: plainCopy.id });
|
||||
|
||||
await repo.copyTourRelations(linked.id, linkedCopy.id);
|
||||
await repo.copyTourRelations(plain.id, plainCopy.id);
|
||||
await repo.copyPackingLink(linked.id, linkedCopy.id);
|
||||
await repo.copyPackingLink(plain.id, plainCopy.id);
|
||||
|
||||
const source = await findRow(t, TourPackingLinks, { place: linked.id });
|
||||
expect(await findRow(t, TourPackingLinks, { place: linkedCopy.id })).toMatchObject({
|
||||
|
||||
@@ -13,8 +13,8 @@ import { db as testDb } from '../../../src/db/database';
|
||||
import { DayAssignments } from '../../../src/db/entities/DayAssignments.entity';
|
||||
import { Days } from '../../../src/db/entities/Days.entity';
|
||||
import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import { RoadtripVias } from '../../../src/db/entities/RoadtripVias.entity';
|
||||
import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
|
||||
import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
@@ -416,7 +416,12 @@ describe('createAssignment with a stage of a multi-day tour (MDT-02)', () => {
|
||||
expect(await svc.createAssignment(day.id, ordinary.id)).toMatchObject({ tour_stage_key: null });
|
||||
});
|
||||
|
||||
it('ASG-SVC-053: refuses a stage the tour does not have: its last stop, a stop ending none, a plain place, a day tour', async () => {
|
||||
it.each([
|
||||
['its last stop', 'tour', 'stop-end'],
|
||||
['a stop ending none', 'tour', 'stop-unknown'],
|
||||
['a plain place', 'plain', 'stop-start'],
|
||||
['a day tour', 'dayTour', 'day-start'],
|
||||
] as const)('ASG-SVC-053: refuses a stage the tour does not have: %s', async (_label, which, key) => {
|
||||
const { trip, day, place } = fixture();
|
||||
await hutToHut(place.id);
|
||||
const plain = createPlace(testDb, trip.id, { name: 'Ordinary place' });
|
||||
@@ -426,18 +431,12 @@ describe('createAssignment with a stage of a multi-day tour (MDT-02)', () => {
|
||||
{ place: dayTour.id, lat: 47, lng: 11, role: 'start', sequence: 0, station_key: 'day-start' },
|
||||
{ place: dayTour.id, lat: 47.1, lng: 11, role: 'end', sequence: 1, station_key: 'day-end' },
|
||||
]);
|
||||
for (const [placeId, key] of [
|
||||
[place.id, 'stop-end'],
|
||||
[place.id, 'stop-unknown'],
|
||||
[plain.id, 'stop-start'],
|
||||
[dayTour.id, 'day-start'],
|
||||
] as const) {
|
||||
const refusal = await catchDomainError(() => svc.createAssignment(day.id, placeId, null, { tourStageKey: key }));
|
||||
expect(refusal instanceof DomainError && [refusal.getStatus(), refusal.publicMessage]).toEqual([
|
||||
400,
|
||||
'Tour has no such stage',
|
||||
]);
|
||||
}
|
||||
const placeId = { tour: place.id, plain: plain.id, dayTour: dayTour.id }[which];
|
||||
const refusal = await catchDomainError(() => svc.createAssignment(day.id, placeId, null, { tourStageKey: key }));
|
||||
expect(refusal instanceof DomainError && [refusal.getStatus(), refusal.publicMessage]).toEqual([
|
||||
400,
|
||||
'Tour has no such stage',
|
||||
]);
|
||||
expect(await countRows(await orm(), DayAssignments, {})).toBe(0);
|
||||
});
|
||||
|
||||
@@ -467,7 +466,7 @@ describe('createAssignment with a stage of a multi-day tour (MDT-02)', () => {
|
||||
await hutToHut(place.id);
|
||||
const secondDay = createDay(testDb, trip.id);
|
||||
const stage = await svc.createAssignment(day.id, place.id, null, { tourStageKey: 'stop-hut-two' });
|
||||
const { assignment } = await svc.moveAssignment(stage!.id, secondDay.id, 0);
|
||||
const { assignment } = await svc.moveAssignment(stage.id, secondDay.id, 0);
|
||||
expect(assignment).toMatchObject({ day_id: secondDay.id, tour_stage_key: 'stop-hut-two' });
|
||||
});
|
||||
|
||||
@@ -477,9 +476,7 @@ describe('createAssignment with a stage of a multi-day tour (MDT-02)', () => {
|
||||
const secondDay = createDay(testDb, trip.id);
|
||||
await svc.createAssignment(day.id, place.id, null, { tourStageKey: 'stop-start' });
|
||||
const second = await svc.createAssignment(secondDay.id, place.id, null, { tourStageKey: 'stop-hut-one' });
|
||||
expect(await svc.dropStaleTourStages(place.id, ['stop-start'])).toEqual([
|
||||
{ id: second!.id, day_id: secondDay.id },
|
||||
]);
|
||||
expect(await svc.dropStaleTourStages(place.id, ['stop-start'])).toEqual([{ id: second.id, day_id: secondDay.id }]);
|
||||
expect(await countRows(await orm(), DayAssignments, { place: place.id })).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -329,9 +329,7 @@ describe('CollectionToursService', () => {
|
||||
// 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);
|
||||
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,
|
||||
|
||||
@@ -9,8 +9,8 @@ import { TourActivities } from '../../../src/db/entities/TourActivities.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { TourActivitiesMcp } from '../../../src/nest/tours/tour-activities.mcp';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { ToursMcp } from '../../../src/nest/tours/tours.mcp';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
|
||||
@@ -48,23 +48,24 @@ function read(result: { content: Array<{ type: string; text: string }>; isError?
|
||||
return result.isError ? { error: text } : JSON.parse(text);
|
||||
}
|
||||
|
||||
/** A tour of the trip on a day of its own, with 500 m up and down; answers its place. */
|
||||
async function tourOnDay(tripId: number, name: string, type: 'hike' | 'kayak', distance: number, date: string) {
|
||||
const day = await makeDay(orm(), tripId, { date });
|
||||
const place = await makePlace(orm(), tripId, { name });
|
||||
await makeTour(orm(), place.id, { tourTypeRef: type, distance, elevation_gain: 500, elevation_loss: 500 });
|
||||
await makeDayAssignment(orm(), day.id, place.id);
|
||||
return place.id;
|
||||
}
|
||||
|
||||
/** A hike and a paddle tour done in July, a hike still ahead, and a trip somebody else owns. */
|
||||
async function fixture() {
|
||||
const { user } = await makeUser(orm());
|
||||
const { user: stranger } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id, { title: 'Alps' });
|
||||
const tours: Record<string, number> = {};
|
||||
for (const [name, type, distance, date] of [
|
||||
['Ridge', 'hike', 12, '2026-07-02'],
|
||||
['Lake', 'kayak', 9, '2026-07-04'],
|
||||
['Summit', 'hike', 15, '2026-07-20'],
|
||||
] as const) {
|
||||
const day = await makeDay(orm(), trip.id, { date });
|
||||
const place = await makePlace(orm(), trip.id, { name });
|
||||
await makeTour(orm(), place.id, { tourTypeRef: type, distance, elevation_gain: 500, elevation_loss: 500 });
|
||||
await makeDayAssignment(orm(), day.id, place.id);
|
||||
tours[name] = place.id;
|
||||
}
|
||||
tours.Ridge = await tourOnDay(trip.id, 'Ridge', 'hike', 12, '2026-07-02');
|
||||
tours.Lake = await tourOnDay(trip.id, 'Lake', 'kayak', 9, '2026-07-04');
|
||||
tours.Summit = await tourOnDay(trip.id, 'Summit', 'hike', 15, '2026-07-20');
|
||||
const closed = await makeTrip(orm(), stranger.id);
|
||||
const hidden = await makePlace(orm(), closed.id, { name: 'Hidden' });
|
||||
await makeTour(orm(), hidden.id);
|
||||
|
||||
@@ -288,8 +288,8 @@ describe('TourChangeMcp.saveTourChange (MCP-T03)', () => {
|
||||
{ ...request, expected_revision: 2 },
|
||||
{ ...request, proposal_id: 'f'.repeat(32) },
|
||||
];
|
||||
for (const body of altered) {
|
||||
const err = await refusal(saveAs(f.trip.id, f.walk.id, body, f.user.id));
|
||||
const refusals = await Promise.all(altered.map((body) => refusal(saveAs(f.trip.id, f.walk.id, body, f.user.id))));
|
||||
for (const err of refusals) {
|
||||
expect([err.getStatus(), err.code]).toEqual([422, TOUR_CHANGE_NOT_PREPARED]);
|
||||
expect(err.publicMessage).toMatch(/^These changes are not the proposal that was prepared\. Nothing was saved/);
|
||||
}
|
||||
|
||||
@@ -303,8 +303,9 @@ describe('TourChangeUndoMcp (MCP-T04)', () => {
|
||||
[first.step.id, 'later_change'],
|
||||
]);
|
||||
const before = await untouched(f.walk.id);
|
||||
for (const attempt of [() => prepared(f, first.step.id), () => undone(f, confirmed(first.step.id, 5))]) {
|
||||
const err = await refusal(attempt());
|
||||
const asPrepared = await refusal(prepared(f, first.step.id));
|
||||
const asUndone = await refusal(undone(f, confirmed(first.step.id, 5)));
|
||||
for (const err of [asPrepared, asUndone]) {
|
||||
expect([err.getStatus(), err.code, err.details?.revision]).toEqual([409, TOUR_REVISION_CONFLICT, 5]);
|
||||
expect(err.publicMessage).toContain('(revision 4 then, 5 now). Nothing changed: only the latest change');
|
||||
}
|
||||
@@ -349,8 +350,9 @@ describe('TourChangeUndoMcp (MCP-T04)', () => {
|
||||
await markStationVisit(orm(), f.onDay1.id, bakeryKey, 'visited');
|
||||
const before = await untouched(f.walk.id);
|
||||
|
||||
for (const attempt of [() => prepared(f, save.step.id), () => undone(f, confirmed(save.step.id, 4))]) {
|
||||
const err = await refusal(attempt());
|
||||
const asPrepared = await refusal(prepared(f, save.step.id));
|
||||
const asUndone = await refusal(undone(f, confirmed(save.step.id, 4)));
|
||||
for (const err of [asPrepared, asUndone]) {
|
||||
expect([err.getStatus(), err.code]).toEqual([409, TOUR_CHANGE_UNDO_REFUSED]);
|
||||
expect(err.details?.refused).toEqual([
|
||||
{
|
||||
@@ -486,7 +488,7 @@ describe('TourChangeUndoMcp (MCP-T04)', () => {
|
||||
['tripId', 'placeId', 'step_id', 'expected_revision', 'confirmed'],
|
||||
],
|
||||
] as const;
|
||||
for (const [method, name, readOnly, mode, fields] of tools) {
|
||||
const gates = tools.map(([method, name, readOnly, mode, fields]) => {
|
||||
const entry = getEntry(TourChangeUndoMcp as unknown as ClassRef, method);
|
||||
if (!entry || entry.kind !== 'tool') throw new Error(`${method} is no MCP tool`);
|
||||
const { options } = entry;
|
||||
@@ -498,9 +500,10 @@ describe('TourChangeUndoMcp (MCP-T04)', () => {
|
||||
expect(Object.keys(options.inputSchema as object)).toEqual([...fields]);
|
||||
expect(options.description).toContain('planner');
|
||||
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
|
||||
expect(await options.when?.(ctx(1), { addons: { isAddonEnabled } })).toBe(true);
|
||||
expect(isAddonEnabled).toHaveBeenCalledWith('tours');
|
||||
}
|
||||
return { isAddonEnabled, open: options.when?.(ctx(1), { addons: { isAddonEnabled } }) };
|
||||
});
|
||||
expect(await Promise.all(gates.map((gate) => gate.open))).toEqual([true, true, true]);
|
||||
for (const { isAddonEnabled } of gates) expect(isAddonEnabled).toHaveBeenCalledWith('tours');
|
||||
const entry = getEntry(TourChangeUndoMcp as unknown as ClassRef, 'undoTourChange');
|
||||
if (!entry || entry.kind !== 'tool') throw new Error('undoTourChange is no MCP tool');
|
||||
// The fields are zod schemas from @trek/shared, read here by what they answer.
|
||||
|
||||
@@ -51,14 +51,16 @@ beforeAll(async () => {
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
// Every leg the router plans is 500 m and 400 s on foot.
|
||||
route.mockReset().mockImplementation(
|
||||
async (_userId: number, _tripId: number, _dayId: number, points: Array<{ lat: number; lng: number }>) => ({
|
||||
leg: { line: points.map((point): [number, number] => [point.lat, point.lng]) },
|
||||
parts: points.slice(1).map(() => ({ distance: 500, duration: 400 })),
|
||||
snapped: points.map(() => ({ meters: 4 })),
|
||||
avoidMissed: [],
|
||||
}),
|
||||
);
|
||||
route
|
||||
.mockReset()
|
||||
.mockImplementation(
|
||||
async (_userId: number, _tripId: number, _dayId: number, points: Array<{ lat: number; lng: number }>) => ({
|
||||
leg: { line: points.map((point): [number, number] => [point.lat, point.lng]) },
|
||||
parts: points.slice(1).map(() => ({ distance: 500, duration: 400 })),
|
||||
snapped: points.map(() => ({ meters: 4 })),
|
||||
avoidMissed: [],
|
||||
}),
|
||||
);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
|
||||
@@ -4,10 +4,7 @@ import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator'
|
||||
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import { RESPONSE_CONTRACT_KEY } from '../../../src/nest/common/response-contract';
|
||||
import { TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
|
||||
import {
|
||||
parseHorseRoutesQuery,
|
||||
TourHorseRoutesController,
|
||||
} from '../../../src/nest/tours/tour-horse-routes.controller';
|
||||
import { parseHorseRoutesQuery, TourHorseRoutesController } from '../../../src/nest/tours/tour-horse-routes.controller';
|
||||
import type { TourHorseRoutesService } from '../../../src/nest/tours/tour-horse-routes.service';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
import { GUARDS_METADATA } from '@nestjs/common/constants';
|
||||
|
||||
@@ -92,7 +92,8 @@ describe('TourHorseRoutesService (HOR-01)', () => {
|
||||
it('HORSE-SVC-005: keeps a bounded number of answers, letting the one kept longest go', async () => {
|
||||
query.mockResolvedValue([]);
|
||||
const nth = (n: number) => ({ south: 40 + n * 0.1, west: 5, north: 40.05 + n * 0.1, east: 5.05 });
|
||||
for (let n = 0; n <= HORSE_ROUTES_KEPT_MAX; n += 1) await service.list(nth(n), NOW);
|
||||
// Asked all at once, the answers are kept in the order they were asked for.
|
||||
await Promise.all(Array.from({ length: HORSE_ROUTES_KEPT_MAX + 1 }, (_, n) => service.list(nth(n), NOW)));
|
||||
expect(query).toHaveBeenCalledTimes(HORSE_ROUTES_KEPT_MAX + 1);
|
||||
await service.list(nth(HORSE_ROUTES_KEPT_MAX), NOW);
|
||||
await service.list(nth(1), NOW);
|
||||
@@ -107,7 +108,12 @@ describe('TourHorseRoutesService (HOR-01)', () => {
|
||||
const wayCount = Math.ceil((HORSE_ROUTES_KEPT_POINTS_MAX / 2 + 1) / perWay);
|
||||
const ids = Array.from({ length: wayCount }, (_, w) => w + 1);
|
||||
const dense = [
|
||||
{ type: 'relation', id: 7, tags: { route: 'horse' }, members: ids.map((ref) => ({ type: 'way', ref, role: '' })) },
|
||||
{
|
||||
type: 'relation',
|
||||
id: 7,
|
||||
tags: { route: 'horse' },
|
||||
members: ids.map((ref) => ({ type: 'way', ref, role: '' })),
|
||||
},
|
||||
...ids.map((id) => ({
|
||||
type: 'way',
|
||||
id,
|
||||
|
||||
@@ -117,11 +117,14 @@ describe('TourPackingLinkService', () => {
|
||||
|
||||
it('TPL-SVC-003: a category the user cannot see an item of is refused, a private one of another member included', async () => {
|
||||
const f = await fixture();
|
||||
for (const category of ['Climbing', 'hiking gear', 'Secret']) {
|
||||
await expect(
|
||||
links.link(String(f.trip.id), String(f.hike.id), { category }, f.owner.id),
|
||||
).rejects.toMatchObject({ status: 400, publicMessage: 'Packing category not found' });
|
||||
}
|
||||
const refused = (category: string) =>
|
||||
expect(links.link(String(f.trip.id), String(f.hike.id), { category }, f.owner.id)).rejects.toMatchObject({
|
||||
status: 400,
|
||||
publicMessage: 'Packing category not found',
|
||||
});
|
||||
await refused('Climbing');
|
||||
await refused('hiking gear');
|
||||
await refused('Secret');
|
||||
// The member who keeps it may link it.
|
||||
const own = await links.link(String(f.trip.id), String(f.hike.id), { category: 'Secret' }, f.member.id);
|
||||
expect(own.packing_link?.category).toBe('Secret');
|
||||
@@ -163,18 +166,15 @@ describe('TourPackingLinkService', () => {
|
||||
|
||||
it('TPL-SVC-006: a tour of another trip, a plain place or a malformed id is not found', async () => {
|
||||
const f = await fixture();
|
||||
const attempts = [
|
||||
() => links.read(f.trip.id, f.otherTour.id),
|
||||
() => links.read(f.trip.id, f.cafe.id),
|
||||
() => links.read('abc', f.hike.id),
|
||||
() => links.read(f.trip.id, '1.5'),
|
||||
() => links.link(String(f.trip.id), String(f.otherTour.id), { category: null }, f.owner.id),
|
||||
() => links.unlink(String(f.trip.id), String(f.cafe.id)),
|
||||
() => links.view(f.other.id, f.hike.id, f.owner.id),
|
||||
];
|
||||
for (const attempt of attempts) {
|
||||
await expect(attempt()).rejects.toMatchObject({ status: 404, publicMessage: 'Tour not found' });
|
||||
}
|
||||
const notFound = (attempt: Promise<unknown>) =>
|
||||
expect(attempt).rejects.toMatchObject({ status: 404, publicMessage: 'Tour not found' });
|
||||
await notFound(links.read(f.trip.id, f.otherTour.id));
|
||||
await notFound(links.read(f.trip.id, f.cafe.id));
|
||||
await notFound(links.read('abc', f.hike.id));
|
||||
await notFound(links.read(f.trip.id, '1.5'));
|
||||
await notFound(links.link(String(f.trip.id), String(f.otherTour.id), { category: null }, f.owner.id));
|
||||
await notFound(links.unlink(String(f.trip.id), String(f.cafe.id)));
|
||||
await notFound(links.view(f.other.id, f.hike.id, f.owner.id));
|
||||
expect(await countRows(orm(), TourPackingLinks)).toBe(0);
|
||||
});
|
||||
|
||||
|
||||
@@ -115,9 +115,9 @@ describe('TourPackingMcp', () => {
|
||||
await expect(
|
||||
mcp.linkTourPacking({ tripId: f.trip.id, placeId: f.hike.id, category: 'Climbing' }, ctx(f.user.id)),
|
||||
).rejects.toThrow('Packing category not found');
|
||||
await expect(
|
||||
mcp.getTourPacking({ tripId: f.trip.id, placeId: 999_999 }, ctx(f.user.id)),
|
||||
).rejects.toThrow('Tour not found');
|
||||
await expect(mcp.getTourPacking({ tripId: f.trip.id, placeId: 999_999 }, ctx(f.user.id))).rejects.toThrow(
|
||||
'Tour not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('TPL-MCP-004: the tools are there only while Tours and Packing are on, and only for the scopes they need', async () => {
|
||||
@@ -127,15 +127,14 @@ describe('TourPackingMcp', () => {
|
||||
return entry.options;
|
||||
};
|
||||
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
|
||||
for (const name of ['getTourPacking', 'linkTourPacking', 'unlinkTourPacking']) {
|
||||
const gate = options(name).when;
|
||||
enabled.mockResolvedValue(true);
|
||||
expect(await gate?.(ctx(1), mcp)).toBe(true);
|
||||
enabled.mockImplementation(async (id: string) => id !== 'packing');
|
||||
expect(await gate?.(ctx(1), mcp)).toBe(false);
|
||||
enabled.mockImplementation(async (id: string) => id !== 'tours');
|
||||
expect(await gate?.(ctx(1), mcp)).toBe(false);
|
||||
}
|
||||
const gates = ['getTourPacking', 'linkTourPacking', 'unlinkTourPacking'].map((name) => options(name).when);
|
||||
const open = () => Promise.all(gates.map((gate) => gate?.(ctx(1), mcp)));
|
||||
enabled.mockResolvedValue(true);
|
||||
expect(await open()).toEqual([true, true, true]);
|
||||
enabled.mockImplementation(async (id: string) => id !== 'packing');
|
||||
expect(await open()).toEqual([false, false, false]);
|
||||
enabled.mockImplementation(async (id: string) => id !== 'tours');
|
||||
expect(await open()).toEqual([false, false, false]);
|
||||
|
||||
const allowed = (name: string, scopes: string[]) => {
|
||||
const access = options(name).access;
|
||||
|
||||
@@ -200,7 +200,9 @@ afterAll(() => {
|
||||
|
||||
describe('Tours GPX atomic persistence and postcommit publication', () => {
|
||||
async function expectEmpty() {
|
||||
for (const table of ['places', 'tours', 'tour_waypoints'] as const) expect(await count(table)).toBe(0);
|
||||
expect(await Promise.all((['places', 'tours', 'tour_waypoints'] as const).map((table) => count(table)))).toEqual([
|
||||
0, 0, 0,
|
||||
]);
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
}
|
||||
|
||||
@@ -451,7 +453,7 @@ describe('Tours KML import through the same persistence (IO-02)', () => {
|
||||
</Document></kml>`);
|
||||
|
||||
it('stores each line as a tour of its own, heights only where the file has them', async () => {
|
||||
const result = (await tours.importGpxAsTour(tripId, twoLines, 'alps.kml', 'socket'))!;
|
||||
const result = await tours.importGpxAsTour(tripId, twoLines, 'alps.kml', 'socket');
|
||||
|
||||
expect(result.tours.map((tour) => [tour.name, tour.origin, tour.elevation_gain])).toEqual([
|
||||
['Coast', 'gpx', null],
|
||||
@@ -466,7 +468,9 @@ describe('Tours KML import through the same persistence (IO-02)', () => {
|
||||
testDb.exec(`CREATE TRIGGER fail_place BEFORE INSERT ON places WHEN NEW.name = 'Ridge'
|
||||
BEGIN SELECT RAISE(ABORT, 'place failure'); END;`);
|
||||
await expect(tours.importGpxAsTour(tripId, twoLines, 'alps.kml')).rejects.toThrow('place failure');
|
||||
for (const table of ['places', 'tours', 'tour_waypoints'] as const) expect(await count(table)).toBe(0);
|
||||
expect(await Promise.all((['places', 'tours', 'tour_waypoints'] as const).map((table) => count(table)))).toEqual([
|
||||
0, 0, 0,
|
||||
]);
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -378,7 +378,9 @@ describe('ToursMcp', () => {
|
||||
const { tours } = read(await mcp.listTours({ tripId: trip.id }, ctx(user.id)));
|
||||
const listed = tours.find((tour: { place_id: number }) => tour.place_id === ridge.id);
|
||||
expect(listed.stage_stops.map((stop: { key: string }) => stop.key)).toEqual(['stop-start', 'stop-hut', 'stop-end']);
|
||||
expect(listed.days.map((day: { day_id: number; tour_stage_key: string | null }) => [day.day_id, day.tour_stage_key])).toEqual([
|
||||
expect(
|
||||
listed.days.map((day: { day_id: number; tour_stage_key: string | null }) => [day.day_id, day.tour_stage_key]),
|
||||
).toEqual([
|
||||
[day1.id, null],
|
||||
[day2.id, null],
|
||||
[day3.id, 'stop-hut'],
|
||||
@@ -586,7 +588,11 @@ describe('ToursMcp', () => {
|
||||
await orm.close();
|
||||
const { tours } = read(await mcp.listTours({ tripId: trip.id }, ctx(user.id)));
|
||||
const byId = new Map(tours.map((tour: { place_id: number }) => [tour.place_id, tour]));
|
||||
expect(byId.get(ridge.id)).toMatchObject({ tour_type: 'run', run_profile: 'running', run_pace_seconds_per_km: 360 });
|
||||
expect(byId.get(ridge.id)).toMatchObject({
|
||||
tour_type: 'run',
|
||||
run_profile: 'running',
|
||||
run_pace_seconds_per_km: 360,
|
||||
});
|
||||
expect(byId.get(gorge.id)).toMatchObject({ run_profile: null, run_pace_seconds_per_km: null });
|
||||
const entry = getEntry(ToursMcp as unknown as ClassRef, 'listTours');
|
||||
const description = entry?.kind === 'tool' ? (entry.options.description ?? '') : '';
|
||||
|
||||
@@ -685,7 +685,6 @@ describe('ToursService runs (RUN-01)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('ToursService multi-day tours (MDT-01)', () => {
|
||||
/** Hut to hut over three days: two stops between start and end each end a stage. */
|
||||
const hutToHut: TourCreateRequest = {
|
||||
|
||||
@@ -11,9 +11,9 @@ import { maybe_encrypt_api_key } from '../../../src/nest/common/crypto/apiKeyCry
|
||||
import { DomainError } from '../../../src/nest/common/domain-error';
|
||||
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
|
||||
import { contentHashOf } from '../../../src/nest/tours/tours.helpers';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { WATCH_BACKOFF_BASE_MS } from '../../../src/nest/tours/wanderer-watch.helpers';
|
||||
import { WandererWatchService } from '../../../src/nest/tours/wanderer-watch.service';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { WandererClient, WandererError } from '../../../src/nest/wanderer/wanderer.client';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
|
||||
Reference in New Issue
Block a user