mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
feat(tours): the assistant edits stations, reverses and closes tours, sets breaks, colour and copies, and writes ski and paddle plans
City walk changes take edit, reverse and close_loop; edits alone keep the saved way and never ask the router. update_tour turns a hike round or closes its loop with reshape. New MCP tools mirror the Tours tab's REST writes and reads: update_tour_details, set_tour_route_color, copy_tour, classify_ski_track, set_paddle_plan, decide_paddle_obstacles, restore_recorded_track, get_tour_trail_details and find_horse_routes, with change cards, undo where the answer keeps the values before, and broadcast parity cases.
This commit is contained in:
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* Tours e2e for the assistant's edits of a saved tour (P8, P9): a hike saved
|
||||
* over REST, its words and breaks, its colour and a copy changed over MCP and
|
||||
* read back over REST; a city walk's station edited through a confirmed
|
||||
* change without the router; the writes refused without 'place_edit'. Through
|
||||
* the real JwtAuthGuard, AddonGuard and TripAccessGuard against a migrated and
|
||||
* seeded temp SQLite db; the MCP tools run in a request context as the
|
||||
* transport runs them, and the broadcast goes to a FakeRealtimeService.
|
||||
*
|
||||
* Fixtures: user 1 owns trip 5, user 2 is a member of it whom the permission
|
||||
* spy denies 'place_edit'.
|
||||
*/
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { trekMcpAccessPolicy, trekMcpValidateAccess } from '../../src/mcp/nest-mcp-policy';
|
||||
import { createTestRegistry, type McpContext } from '../../src/nest-mcp';
|
||||
import { AssignmentsModule } from '../../src/nest/assignments/assignments.module';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { PlacesModule } from '../../src/nest/places/places.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||||
import { RoadtripRouterService } from '../../src/nest/roadtrip/roadtrip-router.service';
|
||||
import { proposalIdOf } from '../../src/nest/tours/tour-change-proposal';
|
||||
import { TourChangeMcp } from '../../src/nest/tours/tour-change.mcp';
|
||||
import { TourEditMcp } from '../../src/nest/tours/tour-edit.mcp';
|
||||
import { TourSportWritesMcp } from '../../src/nest/tours/tour-sport-writes.mcp';
|
||||
import { ToursModule } from '../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { deleteRows, 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 { MikroORM } from '@mikro-orm/core';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { TourChange } from '@trek/shared';
|
||||
|
||||
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;
|
||||
let routeOnFoot: MockInstance;
|
||||
|
||||
const OWNER = 1;
|
||||
const VIEWER = 2;
|
||||
|
||||
const LINE = [
|
||||
[47, 11, 600],
|
||||
[47.01, 11.01, 700],
|
||||
[47.02, 11.02, 650],
|
||||
];
|
||||
|
||||
const hikeBody = () => ({
|
||||
name: 'Ridge',
|
||||
route_geometry: LINE,
|
||||
waypoints: [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 1 },
|
||||
],
|
||||
max_hiking_difficulty: 2,
|
||||
duration_seconds: 3600,
|
||||
});
|
||||
|
||||
const walkBody = () => ({
|
||||
name: 'Old town',
|
||||
tour_type: 'walk',
|
||||
route_geometry: [
|
||||
[48.1, 11.5, 520],
|
||||
[48.108, 11.5, 525],
|
||||
],
|
||||
waypoints: [
|
||||
{ lat: 48.1, lng: 11.5, role: 'start', sequence: 0, key: 'walk-gate', name: 'Gate' },
|
||||
{ lat: 48.108, lng: 11.5, role: 'end', sequence: 1, key: 'walk-park', name: 'Park' },
|
||||
],
|
||||
duration_seconds: 900,
|
||||
});
|
||||
|
||||
type ToolResult = { content: Array<{ type: string; text: string }>; isError?: boolean };
|
||||
|
||||
describe('Tours e2e: the assistant edits a saved tour (P8, P9)', () => {
|
||||
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,
|
||||
PlacesModule,
|
||||
AssignmentsModule,
|
||||
],
|
||||
})
|
||||
.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;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
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 insertRows(orm, Trips, [{ id: 5, user: 1, title: 'Alps' }]);
|
||||
await addTripMember(orm, 5, 2);
|
||||
app = await build();
|
||||
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
|
||||
routeOnFoot = vi.spyOn(app.get(RoadtripRouterService), 'route');
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
checkPermission.mockImplementation(
|
||||
(action: string, _role: string, _owner: number, userId: number) =>
|
||||
!(action === 'place_edit' && userId === VIEWER),
|
||||
);
|
||||
routeOnFoot.mockReset().mockRejectedValue(new Error('no routing host in this test'));
|
||||
await setAddonEnabled(orm, 'tours', true);
|
||||
realtime.broadcastMock.mockClear();
|
||||
await deleteRows(orm, Places);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
const cookie = (userId = OWNER) => sessionCookie(userId);
|
||||
|
||||
/** A tool run as the transport runs it: in a request context of its own. */
|
||||
const run = (call: () => Promise<ToolResult>) =>
|
||||
withRequestContext(app.get(MikroORM), async () => {
|
||||
const result = await call();
|
||||
const text = result.content[0]?.text ?? '';
|
||||
return result.isError ? { error: text } : JSON.parse(text);
|
||||
});
|
||||
const as = (userId: number) => ({ userId }) as McpContext;
|
||||
|
||||
const saveTour = async (body: Record<string, unknown>) => {
|
||||
const res = await request(server).post('/api/trips/5/tours').set('Cookie', cookie()).send(body);
|
||||
expect(res.status).toBe(201);
|
||||
return res.body.tour.place_id as number;
|
||||
};
|
||||
const tourOf = async (placeId: number) => {
|
||||
const res = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', cookie());
|
||||
expect(res.status).toBe(200);
|
||||
return res.body;
|
||||
};
|
||||
|
||||
it('registers both controllers under the trip access policy', () => {
|
||||
expect(() =>
|
||||
createTestRegistry([app.get(TourEditMcp), app.get(TourSportWritesMcp)], {
|
||||
accessPolicy: trekMcpAccessPolicy,
|
||||
validateAccess: trekMcpValidateAccess,
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it('the words and breaks changed over MCP are what the planner reads, and its stale save is refused', async () => {
|
||||
const placeId = await saveTour(hikeBody());
|
||||
const changed = await run(() =>
|
||||
app.get(TourEditMcp).updateTourDetails(
|
||||
{
|
||||
tripId: 5,
|
||||
placeId,
|
||||
expected_revision: 1,
|
||||
website: 'https://ridge.example/',
|
||||
break_additional_minutes: 40,
|
||||
},
|
||||
as(OWNER),
|
||||
),
|
||||
);
|
||||
expect(changed.tour).toMatchObject({ revision: 2, website: 'https://ridge.example/' });
|
||||
const detail = await tourOf(placeId);
|
||||
expect(detail.tour).toMatchObject({ website: 'https://ridge.example/', break_additional_minutes: 40, revision: 2 });
|
||||
expect(detail.waypoints).toHaveLength(2);
|
||||
const stale = await request(server)
|
||||
.put(`/api/trips/5/tours/${placeId}`)
|
||||
.set('Cookie', cookie())
|
||||
.send({ ...hikeBody(), expected_revision: 1 });
|
||||
expect(stale.status).toBe(409);
|
||||
});
|
||||
|
||||
it('a colour set and a copy made over MCP show over REST', async () => {
|
||||
const placeId = await saveTour(hikeBody());
|
||||
await run(() => app.get(TourEditMcp).setTourRouteColor({ tripId: 5, placeId, route_color: '#e11d48' }, as(OWNER)));
|
||||
const place = await request(server).get(`/api/trips/5/places/${placeId}`).set('Cookie', cookie());
|
||||
expect(place.body.place.route_color).toBe('#e11d48');
|
||||
const copy = await run(() =>
|
||||
app.get(TourEditMcp).copyTour({ tripId: 5, placeId, name: 'Ridge (short)' }, as(OWNER)),
|
||||
);
|
||||
const list = await request(server).get('/api/trips/5/tours').set('Cookie', cookie());
|
||||
expect(list.body.tours.map((tour: { name: string }) => tour.name).sort()).toEqual(['Ridge', 'Ridge (short)']);
|
||||
expect(copy.tour.derived_from_place_id).toBe(placeId);
|
||||
});
|
||||
|
||||
it("a station's stay edited through a confirmed change keeps the walk's way without the router", async () => {
|
||||
const placeId = await saveTour(walkBody());
|
||||
const changes: TourChange[] = [{ op: 'edit', key: 'walk-park', stay_minutes: 30, importance: 'must' }];
|
||||
const saved = await run(() =>
|
||||
app.get(TourChangeMcp).saveTourChange(
|
||||
{
|
||||
tripId: 5,
|
||||
placeId,
|
||||
changes,
|
||||
expected_revision: 1,
|
||||
proposal_id: proposalIdOf({ tripId: 5, placeId, revision: 1, changes }),
|
||||
confirmed: true,
|
||||
},
|
||||
as(OWNER),
|
||||
),
|
||||
);
|
||||
expect(saved).toMatchObject({ saved: true, tour: { route_pending: false, walking_minutes: 15 } });
|
||||
expect(routeOnFoot).not.toHaveBeenCalled();
|
||||
const detail = await tourOf(placeId);
|
||||
expect(detail.waypoints[1]).toMatchObject({ key: 'walk-park', stay_minutes: 30, importance: 'must' });
|
||||
});
|
||||
|
||||
it('a member without place_edit changes nothing, over MCP as over REST', async () => {
|
||||
const placeId = await saveTour(hikeBody());
|
||||
const refused = await run(() =>
|
||||
app.get(TourEditMcp).updateTourDetails({ tripId: 5, placeId, expected_revision: 1, name: 'Mine' }, as(VIEWER)),
|
||||
);
|
||||
expect(refused).toHaveProperty('error');
|
||||
const ski = await run(() =>
|
||||
app.get(TourSportWritesMcp).classifySkiTrack({ tripId: 5, placeId, ski_discipline: 'snowshoe' }, as(VIEWER)),
|
||||
);
|
||||
expect(ski).toHaveProperty('error');
|
||||
const rest = await request(server)
|
||||
.put(`/api/trips/5/tours/${placeId}/ski`)
|
||||
.set('Cookie', cookie(VIEWER))
|
||||
.send({ ski_discipline: 'snowshoe' });
|
||||
expect(rest.status).toBe(403);
|
||||
expect((await tourOf(placeId)).tour).toMatchObject({ name: 'Ridge', revision: 1 });
|
||||
});
|
||||
});
|
||||
@@ -2,9 +2,10 @@ import { bookings } from './bookings.cases';
|
||||
import { collabTrip } from './collab-trip.cases';
|
||||
import { money } from './money.cases';
|
||||
import { plan } from './plan.cases';
|
||||
import { toursEdit } from './tours-edit.cases';
|
||||
import { toursRoadtrip } from './tours-roadtrip.cases';
|
||||
import type { CaseGroup } from './types';
|
||||
import { user } from './user.cases';
|
||||
|
||||
/** Every group, imported statically, so the registry test sees each row without running a case. */
|
||||
export const ALL_GROUPS: readonly CaseGroup[] = [plan, bookings, toursRoadtrip, money, collabTrip, user];
|
||||
export const ALL_GROUPS: readonly CaseGroup[] = [plan, bookings, toursRoadtrip, toursEdit, money, collabTrip, user];
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import { updateRows } from '../../helpers/factories/rows';
|
||||
import { addTourWaypoints } from '../../helpers/factories/tours';
|
||||
import type { CaseGroup, Scene } from './types';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
const ormOf = (app: INestApplication) => app.get(MikroORM);
|
||||
|
||||
/** A hike's line with its heights, as the planner saves one. */
|
||||
const LINE: [number, number, number][] = [
|
||||
[47, 11, 600],
|
||||
[47.01, 11.01, 700],
|
||||
[47.02, 11.02, 650],
|
||||
];
|
||||
|
||||
/** The planner's save of the scene's hike, for the edit route. */
|
||||
const hikeBody = (extra: Record<string, unknown>) => ({
|
||||
name: 'Ridge',
|
||||
route_geometry: LINE,
|
||||
waypoints: [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 1 },
|
||||
],
|
||||
max_hiking_difficulty: 2,
|
||||
duration_seconds: 3600,
|
||||
expected_revision: 1,
|
||||
...extra,
|
||||
});
|
||||
|
||||
/** The scene's hike with its line and its start and end, as the planner saves one. */
|
||||
async function planHike(s: Scene, app: INestApplication): Promise<void> {
|
||||
const orm = ormOf(app);
|
||||
await updateRows(orm, Places, { id: s.tourPlace.id }, { route_geometry: JSON.stringify(LINE) });
|
||||
await addTourWaypoints(orm, s.tourPlace.id, [
|
||||
{ lat: 47, lng: 11 },
|
||||
{ lat: 47.02, lng: 11.02 },
|
||||
]);
|
||||
}
|
||||
|
||||
/** The scene's tour as an imported ski track, classified alpine. */
|
||||
async function skiTrack(s: Scene, app: INestApplication): Promise<void> {
|
||||
const orm = ormOf(app);
|
||||
await updateRows(orm, Places, { id: s.tourPlace.id }, { route_geometry: JSON.stringify(LINE) });
|
||||
await updateRows(
|
||||
orm,
|
||||
Tours,
|
||||
{ place: s.tourPlace.id },
|
||||
{ tourTypeRef: 'ski', origin: 'gpx', ski_discipline: 'alpine' },
|
||||
);
|
||||
}
|
||||
|
||||
/** The scene's tour as a recorded paddle track; with `line` false it has no line yet. */
|
||||
function paddleTrack(line: boolean) {
|
||||
return async (s: Scene, app: INestApplication): Promise<void> => {
|
||||
const orm = ormOf(app);
|
||||
if (line) await updateRows(orm, Places, { id: s.tourPlace.id }, { route_geometry: JSON.stringify(LINE) });
|
||||
await updateRows(
|
||||
orm,
|
||||
Tours,
|
||||
{ place: s.tourPlace.id },
|
||||
{ tourTypeRef: 'kayak', origin: 'gpx', boat_type: 'kayak', water_context: 'river', max_hiking_difficulty: null },
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/** The scene's hike planned over an import: it still keeps the track it was recorded with. */
|
||||
async function plannedImport(s: Scene, app: INestApplication): Promise<void> {
|
||||
await planHike(s, app);
|
||||
await updateRows(ormOf(app), Tours, { place: s.tourPlace.id }, { recorded_route_geometry: JSON.stringify(LINE) });
|
||||
}
|
||||
|
||||
const tourPath = (s: Scene) => `/api/trips/${s.trip.id}/tours/${s.tourPlace.id}`;
|
||||
const MARKS = { portages: [{ from_m: 100, to_m: 300, extra_minutes: null }], locks: [] };
|
||||
const CLEAR = [{ key: 'node/12', op: 'clear', decision: null, note: null, basis: null }];
|
||||
|
||||
/**
|
||||
* P8 and P9: the edits of a saved tour besides its route (its words and
|
||||
* times, the colour of its line, a copy) and the writes a ski or paddle tour
|
||||
* has of its own, each with the REST route the Tours tab saves it through.
|
||||
*/
|
||||
export const toursEdit: CaseGroup = {
|
||||
name: 'tours-edit',
|
||||
prefix: 'BCP-TEDIT',
|
||||
cases: [
|
||||
{
|
||||
tool: 'update_tour_details',
|
||||
needs: ['tour'],
|
||||
setup: planHike,
|
||||
args: (s) => ({
|
||||
tripId: s.trip.id,
|
||||
placeId: s.tourPlace.id,
|
||||
expected_revision: 1,
|
||||
website: 'https://a.example/',
|
||||
}),
|
||||
// The planner saves the tour's words and times with its route.
|
||||
rest: { method: 'put', path: tourPath, body: () => hikeBody({ website: 'https://a.example/' }) },
|
||||
expect: ['tours:changed', 'place:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'set_tour_route_color',
|
||||
needs: ['tour'],
|
||||
args: (s) => ({ tripId: s.trip.id, placeId: s.tourPlace.id, route_color: '#e11d48' }),
|
||||
// The tour detail's colour picker writes the place.
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => `/api/trips/${s.trip.id}/places/${s.tourPlace.id}`,
|
||||
body: () => ({ route_color: '#e11d48' }),
|
||||
},
|
||||
expect: ['place:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'copy_tour',
|
||||
needs: ['tour'],
|
||||
setup: planHike,
|
||||
args: (s) => ({ tripId: s.trip.id, placeId: s.tourPlace.id, name: 'Ridge (short)' }),
|
||||
rest: { method: 'post', path: (s) => `${tourPath(s)}/copy`, body: () => ({ name: 'Ridge (short)' }) },
|
||||
expect: ['tours:changed', 'place:created'],
|
||||
},
|
||||
{
|
||||
tool: 'classify_ski_track',
|
||||
needs: ['tour'],
|
||||
setup: skiTrack,
|
||||
args: (s) => ({ tripId: s.trip.id, placeId: s.tourPlace.id, ski_discipline: 'snowshoe' }),
|
||||
rest: { method: 'put', path: (s) => `${tourPath(s)}/ski`, body: () => ({ ski_discipline: 'snowshoe' }) },
|
||||
expect: ['tours:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'set_paddle_plan',
|
||||
needs: ['tour'],
|
||||
setup: paddleTrack(true),
|
||||
args: (s) => ({
|
||||
tripId: s.trip.id,
|
||||
placeId: s.tourPlace.id,
|
||||
paddle_speed_kmh: 5,
|
||||
portage_speed_kmh: null,
|
||||
track_marks: MARKS,
|
||||
}),
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => `${tourPath(s)}/paddle-plan`,
|
||||
body: () => ({ paddle_speed_kmh: 5, portage_speed_kmh: null, track_marks: MARKS }),
|
||||
},
|
||||
expect: ['tours:changed'],
|
||||
},
|
||||
{
|
||||
// A track without a line has nothing to read against the obstacle data, so no data is asked for.
|
||||
tool: 'decide_paddle_obstacles',
|
||||
needs: ['tour'],
|
||||
setup: paddleTrack(false),
|
||||
args: (s) => ({ tripId: s.trip.id, placeId: s.tourPlace.id, ops: CLEAR }),
|
||||
rest: { method: 'put', path: (s) => `${tourPath(s)}/obstacle-reviews`, body: () => ({ ops: CLEAR }) },
|
||||
expect: ['tours:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'restore_recorded_track',
|
||||
needs: ['tour'],
|
||||
setup: plannedImport,
|
||||
args: (s) => ({ tripId: s.trip.id, placeId: s.tourPlace.id }),
|
||||
rest: { method: 'post', path: (s) => `${tourPath(s)}/restore-recorded` },
|
||||
expect: ['tours:changed', 'place:updated'],
|
||||
},
|
||||
],
|
||||
exempt: [],
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
import { runGroup } from './run-group';
|
||||
import { toursEdit } from './tours-edit.cases';
|
||||
|
||||
runGroup(toursEdit);
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* ASTCARD-TOUR-080 to ASTCARD-TOUR-088
|
||||
*
|
||||
* P8 and P9 in the chat: a saved tour's words and times, the colour of its
|
||||
* line, a copy, a hike turned round or taken back to its start, and the
|
||||
* writes a ski or paddle tour has of its own. Each card names the tour; where
|
||||
* the answer keeps what was there before, the way back writes it again while
|
||||
* the tour is still at the revision the change raised it to.
|
||||
*/
|
||||
import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';
|
||||
import { unchangedSinceApplied } from '../../../../../../src/nest/assistant/assistant-undo.helpers';
|
||||
import type { PreviewContext } from '../../../../../../src/nest/assistant/cards/card-types';
|
||||
import { readKey } from '../../../../../../src/nest/assistant/cards/card-values';
|
||||
import { ASSISTANT_UNDO_MAP, ASSISTANT_WRITE_TOOLS } from '../../../../../../src/nest/assistant/cards/registry';
|
||||
import { replans, reshapedPoints } from '../../../../../../src/nest/assistant/cards/tour/tour-change.cards';
|
||||
import { describeToolCall } from '../../../../../../src/nest/assistant/tool-call-preview.helpers';
|
||||
import { assistantChangePreviewSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
|
||||
vi.mock('../../../../../../src/nest/audit/audit-log.logger', () => logMock);
|
||||
|
||||
const card = buildTripCard(
|
||||
1,
|
||||
7,
|
||||
{ trip: { title: 'Alps' }, days: [] },
|
||||
{ places: [{ id: 61, name: 'Ridge walk', lat: 47, lng: 11, description: 'Up and down' }] },
|
||||
null,
|
||||
);
|
||||
const ctx: PreviewContext = { card, categories: new Map(), locale: 'en-GB', today: '2026-06-01', airport: () => null };
|
||||
|
||||
/** A snapshot holding the plan of the tour at a revision. */
|
||||
function atRevision(revision: number) {
|
||||
return {
|
||||
summary: { days: [] },
|
||||
places: { places: [] },
|
||||
reads: new Map([[readKey('get_tour_plan', { placeId: 61 }), { tour: { place_id: 61, revision } }]]),
|
||||
};
|
||||
}
|
||||
|
||||
describe('the edits of a saved tour in the chat', () => {
|
||||
it('ASTCARD-TOUR-080: new words and times name the tour and each field, and go back to the values before', () => {
|
||||
const args = { placeId: 61, expected_revision: 3, name: 'High ridge', break_additional_minutes: 90, website: null };
|
||||
const preview = describeToolCall('update_tour_details', 'tc-1', args, ctx, null);
|
||||
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
|
||||
expect(preview).toMatchObject({ subject: 'Ridge walk', verbKey: 'updateTour', placeIds: [61] });
|
||||
expect(preview.rows.map((row) => row.labelKey)).toEqual(['name', 'website', 'breaks']);
|
||||
expect(preview.rows.find((row) => row.labelKey === 'breaks')?.after).toBe('1:30 h');
|
||||
const result = {
|
||||
tour: { place_id: 61, revision: 4 },
|
||||
previous: { revision: 3, name: 'Ridge walk', website: 'https://a.example/', break_additional_minutes: null },
|
||||
};
|
||||
const undo = ASSISTANT_UNDO_MAP.update_tour_details;
|
||||
expect(undo.args(args, result, null)).toEqual({
|
||||
placeId: 61,
|
||||
expected_revision: 4,
|
||||
name: 'Ridge walk',
|
||||
website: 'https://a.example/',
|
||||
break_additional_minutes: null,
|
||||
});
|
||||
expect(undo.args(args, { tour: {}, previous: {} }, null)).toBeNull();
|
||||
const call = { args, preview: null };
|
||||
expect(unchangedSinceApplied('update_tour_details', result, atRevision(4), call)).toBe(true);
|
||||
expect(unchangedSinceApplied('update_tour_details', result, atRevision(5), call)).toBe(false);
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-081: a new colour goes back to the colour before while the place still has the new one', () => {
|
||||
const args = { placeId: 61, route_color: '#e11d48' };
|
||||
expect(describeToolCall('set_tour_route_color', 'tc-2', args, ctx, null)).toMatchObject({
|
||||
verbKey: 'setRouteColor',
|
||||
rows: [expect.objectContaining({ labelKey: 'color', after: '#e11d48' })],
|
||||
});
|
||||
const result = { place_id: 61, route_color: '#e11d48', previous_route_color: null };
|
||||
expect(ASSISTANT_UNDO_MAP.set_tour_route_color.args(args, result, null)).toEqual({
|
||||
placeId: 61,
|
||||
route_color: null,
|
||||
});
|
||||
const places = (color: string | null) => ({
|
||||
summary: { days: [] },
|
||||
places: { places: [{ id: 61, route_color: color }] },
|
||||
reads: new Map(),
|
||||
});
|
||||
expect(unchangedSinceApplied('set_tour_route_color', result, places('#e11d48'))).toBe(true);
|
||||
expect(unchangedSinceApplied('set_tour_route_color', result, places('#000000'))).toBe(false);
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-082: a copy names its new name and the tour it is made from, and goes back by deleting it', () => {
|
||||
const preview = describeToolCall('copy_tour', 'tc-3', { placeId: 61, name: 'Ridge (short)' }, ctx, null);
|
||||
expect(preview).toMatchObject({ subject: 'Ridge (short)', verbKey: 'copyTour', placeIds: [61] });
|
||||
expect(preview.rows).toEqual([expect.objectContaining({ labelKey: 'route', after: 'Ridge walk' })]);
|
||||
expect(ASSISTANT_UNDO_MAP.copy_tour.tool).toBe('delete_place');
|
||||
expect(ASSISTANT_UNDO_MAP.copy_tour.args({}, { tour: { place_id: 90 } }, null)).toEqual({ placeId: 90 });
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-083: a hike turned round or closed to a loop says so, and is planned anew through the turned points', () => {
|
||||
const reverse = describeToolCall(
|
||||
'update_tour',
|
||||
'tc-4',
|
||||
{ placeId: 61, expected_revision: 1, reshape: 'reverse' },
|
||||
ctx,
|
||||
null,
|
||||
);
|
||||
expect(reverse.verbKey).toBe('reverseTour');
|
||||
const loop = describeToolCall(
|
||||
'update_tour',
|
||||
'tc-5',
|
||||
{ placeId: 61, expected_revision: 1, reshape: 'close_loop' },
|
||||
ctx,
|
||||
null,
|
||||
);
|
||||
expect(loop.verbKey).toBe('closeLoop');
|
||||
const saved = { tour: { max_hiking_difficulty: 2 }, line: { point_count: 2 } };
|
||||
expect(replans({ reshape: 'reverse' }, saved)).toBe(true);
|
||||
expect(replans({ name: 'X' }, saved)).toBe(false);
|
||||
const points = [
|
||||
{ lat: 47, lng: 11 },
|
||||
{ lat: 47.1, lng: 11 },
|
||||
];
|
||||
expect(reshapedPoints('reverse', points)).toEqual([...points].reverse());
|
||||
expect(reshapedPoints('close_loop', points)).toEqual([...points, { lat: 47, lng: 11 }]);
|
||||
expect(reshapedPoints(undefined, points)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the writes of a ski or paddle tour in the chat', () => {
|
||||
it('ASTCARD-TOUR-084: a ski classification names the discipline and goes back to the one before', () => {
|
||||
const args = { placeId: 61, ski_discipline: 'cross_country', ski_technique: 'classic' };
|
||||
expect(describeToolCall('classify_ski_track', 'tc-6', args, ctx, null)).toMatchObject({
|
||||
verbKey: 'classifySki',
|
||||
rows: [expect.objectContaining({ labelKey: 'type', after: 'cross_country (classic)' })],
|
||||
});
|
||||
const result = { tour: { revision: 2 }, previous: { ski_discipline: 'alpine', ski_technique: null } };
|
||||
expect(ASSISTANT_UNDO_MAP.classify_ski_track.args(args, result, null)).toEqual({
|
||||
placeId: 61,
|
||||
ski_discipline: 'alpine',
|
||||
ski_technique: null,
|
||||
expected_revision: 2,
|
||||
});
|
||||
expect(unchangedSinceApplied('classify_ski_track', result, atRevision(2), { args, preview: null })).toBe(true);
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-085: a paddle plan goes back to the plan before', () => {
|
||||
const args = {
|
||||
placeId: 61,
|
||||
paddle_speed_kmh: 5,
|
||||
portage_speed_kmh: null,
|
||||
track_marks: { portages: [], locks: [] },
|
||||
};
|
||||
expect(describeToolCall('set_paddle_plan', 'tc-7', args, ctx, null)).toMatchObject({ verbKey: 'setPaddlePlan' });
|
||||
const previous = { paddle_speed_kmh: null, portage_speed_kmh: 2, track_marks: { portages: [], locks: [] } };
|
||||
expect(ASSISTANT_UNDO_MAP.set_paddle_plan.args(args, { tour: { revision: 7 }, previous }, null)).toEqual({
|
||||
placeId: 61,
|
||||
...previous,
|
||||
expected_revision: 7,
|
||||
});
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-086: decisions about obstacles and a track restored have a card and no way back', () => {
|
||||
for (const [tool, verbKey] of [
|
||||
['decide_paddle_obstacles', 'decideObstacles'],
|
||||
['restore_recorded_track', 'restoreTrack'],
|
||||
] as const) {
|
||||
expect(describeToolCall(tool, 'tc-8', { placeId: 61 }, ctx, null)).toMatchObject({
|
||||
subject: 'Ridge walk',
|
||||
verbKey,
|
||||
});
|
||||
expect(ASSISTANT_UNDO_MAP[tool]).toBeUndefined();
|
||||
expect(ASSISTANT_WRITE_TOOLS[tool]).toMatchObject({ entity: 'tour' });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* update_tour with reshape (P8, PR1-01 and PR1-02 for a saved hike): the saved
|
||||
* points turned round or taken back to their start, then planned anew as new
|
||||
* points are. The way is planned by a stub of HikeRoutingService; the write
|
||||
* is the real one over a snapshot test db.
|
||||
*/
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { HikePlanMcp } from '../../../src/nest/tours/hike-plan.mcp';
|
||||
import { HikeRoutingService, type PlannedHike } from '../../../src/nest/tours/hike-routing.service';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
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 { MikroORM } from '@mikro-orm/core';
|
||||
import type { GeometryPoint, HikePlanRequest } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// HIKE-RESHAPE-001 to HIKE-RESHAPE-004
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const plan = vi.fn<HikeRoutingService['plan']>();
|
||||
let t: TestModule;
|
||||
let mcp: HikePlanMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
/** The stub's plan: a straight way through the points asked for, with heights. */
|
||||
function routed(request: HikePlanRequest): PlannedHike {
|
||||
const line: GeometryPoint[] = request.waypoints.map(({ lat, lng }, index) => [lat, lng, 800 + index * 50]);
|
||||
return {
|
||||
plan: {
|
||||
kind: 'routed',
|
||||
max_hiking_difficulty: request.max_hiking_difficulty ?? 2,
|
||||
hiking_preferences: request.hiking_preferences ?? null,
|
||||
distance_m: 2000,
|
||||
ascent_m: 100,
|
||||
descent_m: 0,
|
||||
duration_minutes: 40,
|
||||
duration_basis: 'din33466',
|
||||
has_heights: true,
|
||||
line,
|
||||
profile: [],
|
||||
grades: null,
|
||||
},
|
||||
line,
|
||||
snapped: line.map(() => 0),
|
||||
legs: line.slice(1).map(() => 1000),
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [ToursModule],
|
||||
overrides: [{ provide: HikeRoutingService, useValue: { plan } }],
|
||||
});
|
||||
mcp = t.get(HikePlanMcp);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
plan.mockReset().mockImplementation(async (_userId, _tripId, request) => routed(request));
|
||||
});
|
||||
afterAll(async () => {
|
||||
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);
|
||||
}
|
||||
|
||||
const POINTS = [
|
||||
{ lat: 47.5, lng: 11.1, station_key: 'stop-carpark', name: 'Car park' },
|
||||
{ lat: 47.51, lng: 11.1, station_key: 'stop-hut0001', name: 'Hut' },
|
||||
{ lat: 47.52, lng: 11.1, station_key: 'stop-summit1', name: 'Summit' },
|
||||
];
|
||||
|
||||
async function hike(points = POINTS, type: 'hike' | 'walk' = 'hike') {
|
||||
const { user } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
const place = await makePlace(orm(), trip.id, {
|
||||
name: 'Herzogstand',
|
||||
route_geometry: JSON.stringify(points.map(({ lat, lng }) => [lat, lng, 800])),
|
||||
});
|
||||
await makeTour(orm(), place.id, { tourTypeRef: type, max_hiking_difficulty: type === 'hike' ? 2 : null });
|
||||
await addTourWaypoints(orm(), place.id, points);
|
||||
return { user, trip, place };
|
||||
}
|
||||
|
||||
describe('update_tour with reshape', () => {
|
||||
it('HIKE-RESHAPE-001: reverse plans the saved points the other way round, each keeping its name and key', async () => {
|
||||
const { user, trip, place } = await hike();
|
||||
const changed = read(
|
||||
await mcp.updateTour(
|
||||
{ tripId: trip.id, placeId: place.id, expected_revision: 1, reshape: 'reverse' },
|
||||
ctx(user.id),
|
||||
),
|
||||
);
|
||||
expect(plan.mock.calls[0]?.[2].waypoints.map(({ lat }) => lat)).toEqual([47.52, 47.51, 47.5]);
|
||||
expect(changed).toMatchObject({ replanned: true, tour: { revision: 2 } });
|
||||
expect(changed.waypoints.map((point: { name: string; key: string }) => [point.name, point.key])).toEqual([
|
||||
['Summit', 'stop-summit1'],
|
||||
['Hut', 'stop-hut0001'],
|
||||
['Car park', 'stop-carpark'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('HIKE-RESHAPE-002: close_loop adds the way back to the start, and a second one is refused', async () => {
|
||||
const { user, trip, place } = await hike();
|
||||
const closed = read(
|
||||
await mcp.updateTour(
|
||||
{ tripId: trip.id, placeId: place.id, expected_revision: 1, reshape: 'close_loop' },
|
||||
ctx(user.id),
|
||||
),
|
||||
);
|
||||
expect(closed.waypoints).toHaveLength(4);
|
||||
expect(closed.waypoints[3]).toMatchObject({ lat: 47.5, lng: 11.1, role: 'end' });
|
||||
await expect(
|
||||
mcp.updateTour({ tripId: trip.id, placeId: place.id, expected_revision: 2, reshape: 'close_loop' }, ctx(user.id)),
|
||||
).rejects.toThrow('This hike already ends where it starts.');
|
||||
});
|
||||
|
||||
it('HIKE-RESHAPE-003: a hike split into stages is not turned round, and nothing is planned', async () => {
|
||||
const staged = [POINTS[0], { ...POINTS[1], stage_end: 1 }, POINTS[2]] as typeof POINTS;
|
||||
const { user, trip, place } = await hike(staged);
|
||||
await expect(
|
||||
mcp.updateTour({ tripId: trip.id, placeId: place.id, expected_revision: 1, reshape: 'reverse' }, ctx(user.id)),
|
||||
).rejects.toThrow('split into stages over several days');
|
||||
expect(plan).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('HIKE-RESHAPE-004: any other type keeps being refused here', async () => {
|
||||
const { user, trip, place } = await hike(POINTS, 'walk');
|
||||
await expect(
|
||||
mcp.updateTour({ tripId: trip.id, placeId: place.id, expected_revision: 1, reshape: 'reverse' }, ctx(user.id)),
|
||||
).rejects.toThrow('Only a hike is changed here');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
import {
|
||||
applyChanges,
|
||||
editsOnly,
|
||||
refusalText,
|
||||
reversedPoints,
|
||||
savedPoint,
|
||||
turnedLeg,
|
||||
type ChangeBasis,
|
||||
type DraftPoint,
|
||||
} from '../../../src/nest/tours/tour-change-apply';
|
||||
import type { TourChange, TourWaypoint } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// TCHG-EDIT-001 to TCHG-EDIT-012: P8, a city walk's stations edited, the walk reversed and closed to a loop.
|
||||
|
||||
const point = (key: string, sequence: number, extra: Partial<TourWaypoint> = {}): TourWaypoint => ({
|
||||
lat: 48 + sequence * 0.01,
|
||||
lng: 11,
|
||||
role: 'via',
|
||||
sequence,
|
||||
key,
|
||||
name: key.replace('stop-', ''),
|
||||
...extra,
|
||||
});
|
||||
|
||||
/** A walk from the gate past the museum to the park. */
|
||||
const walk = (): TourWaypoint[] => [
|
||||
point('stop-gate', 0, { role: 'start', stay_minutes: 5 }),
|
||||
point('stop-museum', 1, { stay_minutes: 45, importance: 'must' }),
|
||||
point('stop-park', 2, { role: 'end' }),
|
||||
];
|
||||
|
||||
/** The same walk as a loop: the way back stands on the gate again. */
|
||||
const loop = (): TourWaypoint[] => [
|
||||
...walk().slice(0, 2),
|
||||
point('stop-park', 2),
|
||||
{ lat: 48, lng: 11, role: 'end', sequence: 3, key: 'back-0001' },
|
||||
];
|
||||
|
||||
const basis = (over: Partial<ChangeBasis> = {}): ChangeBasis => ({
|
||||
tourType: 'walk',
|
||||
recorded: false,
|
||||
points: walk(),
|
||||
done: new Map(),
|
||||
linkable: new Set(),
|
||||
...over,
|
||||
});
|
||||
|
||||
function ready(outcome: ReturnType<typeof applyChanges>) {
|
||||
if (outcome.kind !== 'ready') throw new Error(`refused: ${JSON.stringify(outcome.refused)}`);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
function refused(outcome: ReturnType<typeof applyChanges>) {
|
||||
if (outcome.kind !== 'refused') throw new Error('was laid');
|
||||
return outcome.refused;
|
||||
}
|
||||
|
||||
const refs = (points: readonly DraftPoint[]) => points.map((p) => p.ref);
|
||||
|
||||
describe('edits of a station (P8)', () => {
|
||||
it('TCHG-EDIT-001: an edit writes only the fields it names, null clears one, and the station stays where it is', () => {
|
||||
const changes: TourChange[] = [
|
||||
{ op: 'edit', key: 'stop-museum', name: 'Art museum', stay_minutes: null, importance: null, protected: true },
|
||||
{ op: 'edit', key: 'stop-park', opening_hours: 'Mo-Su 06:00-22:00' },
|
||||
];
|
||||
const { points } = ready(applyChanges(basis(), changes));
|
||||
expect(refs(points)).toEqual(['stop-gate', 'stop-museum', 'stop-park']);
|
||||
expect(points[1]).toMatchObject({
|
||||
name: 'Art museum',
|
||||
stay_minutes: null,
|
||||
importance: null,
|
||||
protected: true,
|
||||
origin: 'edited',
|
||||
change: 1,
|
||||
});
|
||||
expect(points[2]).toMatchObject({ name: 'park', opening_hours: 'Mo-Su 06:00-22:00', origin: 'edited', change: 2 });
|
||||
expect(points[0]).toMatchObject({ stay_minutes: 5, origin: 'saved' });
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-002: a protected or already visited station takes an edit; an unknown key is refused', () => {
|
||||
const points = walk().map((one) => (one.key === 'stop-museum' ? { ...one, protected: true } : one));
|
||||
const done = new Map([['stop-museum', [{ day_id: 3, status: 'visited' as const }]]]);
|
||||
const edited = ready(applyChanges(basis({ points, done }), [{ op: 'edit', key: 'stop-museum', stay_minutes: 60 }]));
|
||||
expect(edited.points[1]?.stay_minutes).toBe(60);
|
||||
const unknown = refused(applyChanges(basis(), [{ op: 'edit', key: 'stop-nowhere', name: 'X' }]));
|
||||
expect(unknown).toEqual([{ change: 1, op: 'edit', key: 'stop-nowhere', reason: 'unknown_station' }]);
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-003: editsOnly tells a proposal of edits from one that moves stations', () => {
|
||||
expect(editsOnly([{ op: 'edit', key: 'stop-park', name: 'P' }])).toBe(true);
|
||||
expect(editsOnly([{ op: 'edit', key: 'stop-park', name: 'P' }, { op: 'reverse' }])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a walk turned round (PR1-02)', () => {
|
||||
it('TCHG-EDIT-004: the last station starts it, every station is marked moved but one that keeps its place', () => {
|
||||
const { points } = ready(applyChanges(basis(), [{ op: 'reverse' }]));
|
||||
expect(refs(points)).toEqual(['stop-park', 'stop-museum', 'stop-gate']);
|
||||
expect(points.map((p) => [p.role, p.sequence])).toEqual([
|
||||
['start', 0],
|
||||
['via', 1],
|
||||
['end', 2],
|
||||
]);
|
||||
expect(points.map((p) => p.origin)).toEqual(['moved', 'saved', 'moved']);
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-005: a loop stays a loop from the same start, which keeps its key and stay', () => {
|
||||
const { points } = ready(applyChanges(basis({ points: loop() }), [{ op: 'reverse' }]));
|
||||
expect(points.map((p) => p.key)).toEqual(['stop-gate', 'stop-park', 'stop-museum', 'back-0001']);
|
||||
expect(points[0]).toMatchObject({ lat: 48, lng: 11, stay_minutes: 5, role: 'start' });
|
||||
expect(points[3]).toMatchObject({ lat: 48, lng: 11, role: 'end' });
|
||||
expect(points[3]?.name).toBeUndefined();
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-006: a walk under way or with a protected station is not turned round', () => {
|
||||
const done = new Map([['stop-gate', [{ day_id: 2, status: 'skipped' as const }]]]);
|
||||
expect(refused(applyChanges(basis({ done }), [{ op: 'reverse' }]))).toEqual([
|
||||
{ change: 1, op: 'reverse', key: null, reason: 'walk_under_way' },
|
||||
]);
|
||||
const points = walk().map((one) => (one.key === 'stop-museum' ? { ...one, protected: true } : one));
|
||||
expect(refused(applyChanges(basis({ points }), [{ op: 'reverse' }]))).toEqual([
|
||||
{ change: 1, op: 'reverse', key: 'stop-museum', reason: 'protected' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-007: a reverse goes with edits only, and only once', () => {
|
||||
const withMove = refused(
|
||||
applyChanges(basis(), [{ op: 'reverse' }, { op: 'move', key: 'stop-gate', after_key: 'stop-museum' }]),
|
||||
);
|
||||
expect(withMove).toEqual([{ change: null, op: null, key: null, reason: 'reshape_not_alone' }]);
|
||||
expect(refused(applyChanges(basis(), [{ op: 'reverse' }, { op: 'close_loop' }]))[0]?.reason).toBe(
|
||||
'reshape_not_alone',
|
||||
);
|
||||
const withEdit = ready(applyChanges(basis(), [{ op: 'reverse' }, { op: 'edit', key: 'stop-park', name: 'Park' }]));
|
||||
expect(withEdit.points[0]).toMatchObject({ key: 'stop-park', name: 'Park' });
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-008: a leg drawn by hand stays on its stretch, its line turned; a crossing by boat keeps its points', () => {
|
||||
const free = { kind: 'free' as const, geometry: [[48, 11] as [number, number], [48.01, 11] as [number, number]] };
|
||||
const ferry = {
|
||||
kind: 'ferry' as const,
|
||||
geometry: [
|
||||
[48.01, 11],
|
||||
[48.012, 11],
|
||||
[48.016, 11],
|
||||
[48.02, 11],
|
||||
] as Array<[number, number]>,
|
||||
crossings: [[1, 2]] as Array<[number, number]>,
|
||||
minutes: 10,
|
||||
walk_minutes: 4,
|
||||
};
|
||||
const points = [
|
||||
point('stop-gate', 0, { role: 'start', fixed_leg: free }),
|
||||
point('stop-museum', 1, { fixed_leg: ferry }),
|
||||
point('stop-park', 2, { role: 'end' }),
|
||||
];
|
||||
const turned = reversedPoints(points.map(savedPoint));
|
||||
expect(turned.map((p) => p.fixed_leg?.kind ?? null)).toEqual(['ferry', 'free', null]);
|
||||
expect(turned[0]?.fixed_leg).toMatchObject({ geometry: [...ferry.geometry].reverse(), crossings: [[1, 2]] });
|
||||
expect(turned[1]?.fixed_leg?.geometry).toEqual([...free.geometry].reverse());
|
||||
expect(turnedLeg({ ...ferry, crossings: [[0, 1]] })).toMatchObject({ crossings: [[2, 3]] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('a walk taken back to its start (PR1-01)', () => {
|
||||
it('TCHG-EDIT-009: a way back on the start is added, no station of its own and nothing to keep as a place', () => {
|
||||
const { points } = ready(applyChanges(basis(), [{ op: 'close_loop' }]));
|
||||
expect(points).toHaveLength(4);
|
||||
expect(points[3]).toMatchObject({ lat: 48, lng: 11, role: 'end', origin: 'loop', ref: 'new:1' });
|
||||
expect(points[3]?.key).toBeUndefined();
|
||||
expect(points[2]).toMatchObject({ key: 'stop-park', role: 'via' });
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-010: a walk that already ends at its start is refused, with the reason in words', () => {
|
||||
const outcome = refused(applyChanges(basis({ points: loop() }), [{ op: 'close_loop' }]));
|
||||
expect(outcome).toEqual([{ change: 1, op: 'close_loop', key: null, reason: 'already_loop' }]);
|
||||
expect(refusalText(outcome, 'prepared')).toBe(
|
||||
'Nothing was prepared and nothing changed.\nChange 1 (close_loop): this walk already ends where it starts.',
|
||||
);
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-011: the refusal names a reverse without a station and an edit with its key', () => {
|
||||
const text = refusalText(
|
||||
[
|
||||
{ change: 1, op: 'reverse', key: null, reason: 'walk_under_way' },
|
||||
{ change: 2, op: 'edit', key: 'stop-x', reason: 'unknown_station' },
|
||||
],
|
||||
'saved',
|
||||
);
|
||||
expect(text).toContain('Change 1 (reverse): the travellers already visited or skipped stations');
|
||||
expect(text).toContain('Change 2 (edit stop-x): no station');
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-012: a hike still takes no prepared change at all', () => {
|
||||
expect(refused(applyChanges(basis({ tourType: 'hike' }), [{ op: 'close_loop' }]))[0]?.reason).toBe(
|
||||
'type_not_supported',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* prepare_tour_change and save_tour_change with the changes P8 brings: a
|
||||
* station edited (its name, stay, importance, protection, opening hours), the
|
||||
* walk turned round and closed to a loop. Edits alone keep the walk's saved
|
||||
* way and walking time and never ask the router; a reverse or a loop plans
|
||||
* the way on foot anew. The road trip's router is a stub; the suite takes its
|
||||
* subject from the container over a snapshot test db.
|
||||
*/
|
||||
import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { TourChangeSteps } from '../../../src/db/entities/TourChangeSteps.entity';
|
||||
import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { RoadtripRouterService } from '../../../src/nest/roadtrip/roadtrip-router.service';
|
||||
import { proposalIdOf } from '../../../src/nest/tours/tour-change-proposal';
|
||||
import { TourChangeMcp } from '../../../src/nest/tours/tour-change.mcp';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { countRows, findRow, findRows } from '../../helpers/factories/rows';
|
||||
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 { MikroORM } from '@mikro-orm/core';
|
||||
import type { TourChange } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// TCHG-EDIT-MCP-001 to TCHG-EDIT-MCP-004
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const route = vi.fn();
|
||||
let t: TestModule;
|
||||
let mcp: TourChangeMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
/** Every leg is 500 m and 400 s on foot, along the points asked. */
|
||||
async function routedOnFoot(_u: number, _t: number, _d: number, points: Array<{ lat: number; lng: number }>) {
|
||||
return {
|
||||
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: [],
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [ToursModule],
|
||||
overrides: [{ provide: RoadtripRouterService, useValue: { route } }],
|
||||
});
|
||||
mcp = t.get(TourChangeMcp);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
route.mockReset().mockImplementation(routedOnFoot);
|
||||
});
|
||||
afterAll(async () => {
|
||||
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);
|
||||
}
|
||||
|
||||
/** The walk's saved line, with heights the router on foot never gives. */
|
||||
const LINE = [
|
||||
[48.1, 11.5, 520],
|
||||
[48.104, 11.5, 522],
|
||||
[48.108, 11.5, 525],
|
||||
];
|
||||
|
||||
async function walk() {
|
||||
const { user } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
const place = await makePlace(orm(), trip.id, { name: 'Old town', route_geometry: JSON.stringify(LINE) });
|
||||
await makeTour(orm(), place.id, { tourTypeRef: 'walk', duration: 25 });
|
||||
await addTourWaypoints(orm(), place.id, [
|
||||
{ lat: 48.1, lng: 11.5, station_key: 'walk-gate', name: 'Gate' },
|
||||
{ lat: 48.104, lng: 11.5, station_key: 'walk-market', name: 'Market', stay_minutes: 20 },
|
||||
{ lat: 48.108, lng: 11.5, station_key: 'walk-park', name: 'Park' },
|
||||
]);
|
||||
return { user, trip, place };
|
||||
}
|
||||
|
||||
async function saved(f: Awaited<ReturnType<typeof walk>>, changes: TourChange[]) {
|
||||
const args = { tripId: f.trip.id, placeId: f.place.id };
|
||||
return read(
|
||||
await mcp.saveTourChange(
|
||||
{
|
||||
...args,
|
||||
changes,
|
||||
expected_revision: 1,
|
||||
proposal_id: proposalIdOf({ ...args, revision: 1, changes }),
|
||||
confirmed: true,
|
||||
},
|
||||
ctx(f.user.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
describe('P8 changes of a saved city walk', () => {
|
||||
it('TCHG-EDIT-MCP-001: an edit is prepared with the router asked once, the station marked edited', async () => {
|
||||
const f = await walk();
|
||||
const changes: TourChange[] = [{ op: 'edit', key: 'walk-market', stay_minutes: 45, importance: 'must' }];
|
||||
const proposal = read(
|
||||
await mcp.prepareTourChange({ tripId: f.trip.id, placeId: f.place.id, changes }, ctx(f.user.id)),
|
||||
);
|
||||
expect(route).toHaveBeenCalledTimes(1);
|
||||
expect(proposal.stations_after[1]).toMatchObject({
|
||||
key: 'walk-market',
|
||||
change: 'edited',
|
||||
stay_minutes: 45,
|
||||
importance: 'must',
|
||||
});
|
||||
expect(proposal.effects.stays.change_minutes_known).toBe(25);
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-MCP-002: edits alone keep the saved line with its heights and the walking time, and record a step', async () => {
|
||||
const f = await walk();
|
||||
route.mockClear();
|
||||
const answer = await saved(f, [{ op: 'edit', key: 'walk-gate', name: 'Old gate', protected: true }]);
|
||||
expect(route).not.toHaveBeenCalled();
|
||||
expect(answer).toMatchObject({ saved: true, tour: { revision: 2, walking_minutes: 25, route_pending: false } });
|
||||
const place = await findRow(orm(), Places, { id: f.place.id });
|
||||
expect(JSON.parse(String(place?.route_geometry))).toEqual(LINE);
|
||||
const gate = await findRow(orm(), TourWaypoints, { place: f.place.id, station_key: 'walk-gate' });
|
||||
expect(gate?.name).toBe('Old gate');
|
||||
expect(Boolean(gate?.protected)).toBe(true);
|
||||
expect(await countRows(orm(), TourChangeSteps)).toBe(1);
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-MCP-003: a reverse plans the walk anew from its last station, keeping every key', async () => {
|
||||
const f = await walk();
|
||||
route.mockClear();
|
||||
const answer = await saved(f, [{ op: 'reverse' }]);
|
||||
expect(route).toHaveBeenCalledTimes(1);
|
||||
expect(answer.stations.map((station: { key: string }) => station.key)).toEqual([
|
||||
'walk-park',
|
||||
'walk-market',
|
||||
'walk-gate',
|
||||
]);
|
||||
});
|
||||
|
||||
it('TCHG-EDIT-MCP-004: a close_loop adds the way back, which no station counts', async () => {
|
||||
const f = await walk();
|
||||
const answer = await saved(f, [{ op: 'close_loop' }]);
|
||||
expect(answer.stations).toHaveLength(3);
|
||||
const points = await findRows(orm(), TourWaypoints, { place: f.place.id });
|
||||
expect(points).toHaveLength(4);
|
||||
expect(points.find((point) => point.sequence === 3)).toMatchObject({ lat: 48.1, lng: 11.5, role: 'end' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* TourEditMcp (P8): a saved tour's words and planned times, the colour of its
|
||||
* line and a copy of it, over MCP with the services and checks of their REST
|
||||
* routes (trip access, then 'place_edit'). The suite takes its subject from
|
||||
* the container over a snapshot test db.
|
||||
*/
|
||||
import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { TourEditMcp } from '../../../src/nest/tours/tour-edit.mcp';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { countRows, findRow } from '../../helpers/factories/rows';
|
||||
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 { MikroORM } from '@mikro-orm/core';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let mcp: TourEditMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [ToursModule] });
|
||||
mcp = t.get(TourEditMcp);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
t.realtime.broadcastMock.mockReset();
|
||||
});
|
||||
afterAll(async () => {
|
||||
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);
|
||||
}
|
||||
|
||||
const LINE = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.01, 11, 700],
|
||||
]);
|
||||
|
||||
async function fixture(duration = 120) {
|
||||
const { user } = await makeUser(orm());
|
||||
const { user: outsider } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
const hike = await makePlace(orm(), trip.id, { name: 'Ridge', route_geometry: LINE, website: 'https://old.example' });
|
||||
await makeTour(orm(), hike.id, { duration });
|
||||
await addTourWaypoints(orm(), hike.id, [
|
||||
{ lat: 47, lng: 11, station_key: 'stop-start1', name: 'Car park' },
|
||||
{ lat: 47.01, lng: 11, station_key: 'stop-summit', name: 'Summit' },
|
||||
]);
|
||||
const plain = await makePlace(orm(), trip.id, { name: 'Bakery' });
|
||||
return { user, outsider, trip, hike, plain };
|
||||
}
|
||||
|
||||
const events = () => t.realtime.broadcastMock.mock.calls.map(([, event]) => event);
|
||||
|
||||
describe('update_tour_details', () => {
|
||||
it('TEDIT-MCP-001: changes the website and the breaks against the revision, answering the values before', async () => {
|
||||
const { user, trip, hike } = await fixture();
|
||||
const result = read(
|
||||
await mcp.updateTourDetails(
|
||||
{
|
||||
tripId: trip.id,
|
||||
placeId: hike.id,
|
||||
expected_revision: 1,
|
||||
website: 'https://new.example/ridge',
|
||||
break_additional_minutes: 30,
|
||||
},
|
||||
ctx(user.id),
|
||||
),
|
||||
);
|
||||
expect(result.tour).toMatchObject({
|
||||
place_id: hike.id,
|
||||
revision: 2,
|
||||
name: 'Ridge',
|
||||
website: 'https://new.example/ridge',
|
||||
break_additional_minutes: 30,
|
||||
});
|
||||
expect(result.previous).toMatchObject({
|
||||
revision: 1,
|
||||
website: 'https://old.example',
|
||||
break_additional_minutes: null,
|
||||
});
|
||||
expect(await findRow(orm(), Tours, { place: hike.id })).toMatchObject({
|
||||
break_additional_minutes: 30,
|
||||
revision: 2,
|
||||
});
|
||||
expect(events()).toEqual(expect.arrayContaining(['tours:changed', 'place:updated']));
|
||||
});
|
||||
|
||||
it('TEDIT-MCP-002: clears a description with null and keeps the route and its points', async () => {
|
||||
const { user, trip, hike } = await fixture();
|
||||
await mcp.updateTourDetails(
|
||||
{ tripId: trip.id, placeId: hike.id, expected_revision: 1, description: null, name: 'High ridge' },
|
||||
ctx(user.id),
|
||||
);
|
||||
const place = await findRow(orm(), Places, { id: hike.id });
|
||||
expect(place).toMatchObject({ name: 'High ridge', description: null, route_geometry: LINE });
|
||||
});
|
||||
|
||||
it('TEDIT-MCP-003: refuses a tour changed since, breaks past the day and a change of nothing', async () => {
|
||||
const { user, trip, hike } = await fixture(1400);
|
||||
await expect(
|
||||
mcp.updateTourDetails({ tripId: trip.id, placeId: hike.id, expected_revision: 5, name: 'X' }, ctx(user.id)),
|
||||
).rejects.toThrow('This tour was changed in the meantime');
|
||||
await expect(
|
||||
mcp.updateTourDetails(
|
||||
{ tripId: trip.id, placeId: hike.id, expected_revision: 1, break_additional_minutes: 60 },
|
||||
ctx(user.id),
|
||||
),
|
||||
).rejects.toThrow('walking time plus breaks must be 1440 minutes or less');
|
||||
// With a planned total the breaks are the travellers' own.
|
||||
const planned = read(
|
||||
await mcp.updateTourDetails(
|
||||
{
|
||||
tripId: trip.id,
|
||||
placeId: hike.id,
|
||||
expected_revision: 1,
|
||||
break_additional_minutes: 60,
|
||||
planned_duration_minutes: 1440,
|
||||
},
|
||||
ctx(user.id),
|
||||
),
|
||||
);
|
||||
expect(planned.tour.break_additional_minutes).toBe(60);
|
||||
expect(
|
||||
read(await mcp.updateTourDetails({ tripId: trip.id, placeId: hike.id, expected_revision: 2 }, ctx(user.id))),
|
||||
).toEqual({ error: 'give at least one field to change' });
|
||||
});
|
||||
|
||||
it('TEDIT-MCP-004: a place that is no tour is not found', async () => {
|
||||
const { user, trip, plain } = await fixture();
|
||||
expect(
|
||||
read(
|
||||
await mcp.updateTourDetails(
|
||||
{ tripId: trip.id, placeId: plain.id, expected_revision: 1, name: 'X' },
|
||||
ctx(user.id),
|
||||
),
|
||||
),
|
||||
).toEqual({ error: 'Tour not found.' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('set_tour_route_color', () => {
|
||||
it('TEDIT-MCP-005: draws the line in another colour and back, without raising the revision', async () => {
|
||||
const { user, trip, hike } = await fixture();
|
||||
const set = read(
|
||||
await mcp.setTourRouteColor({ tripId: trip.id, placeId: hike.id, route_color: '#e11d48' }, ctx(user.id)),
|
||||
);
|
||||
expect(set).toEqual({ place_id: hike.id, route_color: '#e11d48', previous_route_color: null });
|
||||
const back = read(
|
||||
await mcp.setTourRouteColor({ tripId: trip.id, placeId: hike.id, route_color: null }, ctx(user.id)),
|
||||
);
|
||||
expect(back.previous_route_color).toBe('#e11d48');
|
||||
expect((await findRow(orm(), Places, { id: hike.id }))?.route_color).toBeNull();
|
||||
expect((await findRow(orm(), Tours, { place: hike.id }))?.revision).toBe(1);
|
||||
expect(events()).toEqual(['place:updated', 'place:updated']);
|
||||
});
|
||||
|
||||
it('TEDIT-MCP-006: a place that is no tour is not found and keeps its colour', async () => {
|
||||
const { user, trip, plain } = await fixture();
|
||||
expect(
|
||||
read(await mcp.setTourRouteColor({ tripId: trip.id, placeId: plain.id, route_color: '#000000' }, ctx(user.id))),
|
||||
).toEqual({ error: 'Tour not found.' });
|
||||
expect((await findRow(orm(), Places, { id: plain.id }))?.route_color).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('copy_tour', () => {
|
||||
it('TEDIT-MCP-007: saves the tour again as a new one of the trip under its own name', async () => {
|
||||
const { user, trip, hike } = await fixture();
|
||||
const before = await countRows(orm(), Tours);
|
||||
const copy = read(await mcp.copyTour({ tripId: trip.id, placeId: hike.id, name: 'Ridge (short)' }, ctx(user.id)));
|
||||
expect(copy.tour).toMatchObject({ name: 'Ridge (short)', tour_type: 'hike', derived_from_place_id: hike.id });
|
||||
expect(copy.tour.place_id).not.toBe(hike.id);
|
||||
expect(copy.waypoints).toHaveLength(2);
|
||||
expect(await countRows(orm(), Tours)).toBe(before + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the checks of the REST routes', () => {
|
||||
it('TEDIT-MCP-008: refuses a trip the user cannot open, and without place_edit writes nothing', async () => {
|
||||
const { user, outsider, trip, hike } = await fixture();
|
||||
const name = { tripId: trip.id, placeId: hike.id, name: 'X' };
|
||||
expect(read(await mcp.copyTour(name, ctx(outsider.id)))).toEqual({ error: 'Trip not found or access denied.' });
|
||||
const denied = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValue(false);
|
||||
const results = [
|
||||
await mcp.updateTourDetails({ ...name, expected_revision: 1 }, ctx(user.id)),
|
||||
await mcp.setTourRouteColor({ tripId: trip.id, placeId: hike.id, route_color: '#ffffff' }, ctx(user.id)),
|
||||
await mcp.copyTour(name, ctx(user.id)),
|
||||
];
|
||||
expect(results.every((result) => result.isError === true)).toBe(true);
|
||||
expect(denied).toHaveBeenCalledWith('place_edit', trip.id, user.id);
|
||||
expect(await findRow(orm(), Places, { id: hike.id })).toMatchObject({ name: 'Ridge', route_color: null });
|
||||
expect(await countRows(orm(), Tours)).toBe(1);
|
||||
denied.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,321 @@
|
||||
/**
|
||||
* TourSportWritesMcp (P9): the writes a ski or paddle tour has of its own, an
|
||||
* import taken back to its recording, and the reads beside them (the trail
|
||||
* details along a saved tour, the horse routes in a map view), over MCP with
|
||||
* the services and checks of their REST routes. The router, the trail grades
|
||||
* and the horse routes stand in for the network. The suite takes its subject
|
||||
* from the container over a snapshot test db.
|
||||
*/
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { RoadtripRouterService } from '../../../src/nest/roadtrip/roadtrip-router.service';
|
||||
import { TourHorseRoutesService } from '../../../src/nest/tours/tour-horse-routes.service';
|
||||
import { TourObstacleReviewsService } from '../../../src/nest/tours/tour-obstacle-reviews.service';
|
||||
import { TourSportWritesMcp } from '../../../src/nest/tours/tour-sport-writes.mcp';
|
||||
import { TourTrailGradeService } from '../../../src/nest/tours/tour-trail-grade.service';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { findRow, updateRows } from '../../helpers/factories/rows';
|
||||
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 { MikroORM } from '@mikro-orm/core';
|
||||
import { HORSE_ROUTES_ATTRIBUTION } from '@trek/shared';
|
||||
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let mcp: TourSportWritesMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [ToursModule] });
|
||||
mcp = t.get(TourSportWritesMcp);
|
||||
});
|
||||
beforeEach(() => resetTestDb(db));
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterAll(async () => {
|
||||
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);
|
||||
}
|
||||
|
||||
/** About 1.1 km north, with heights. */
|
||||
const LINE = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.01, 11, 700],
|
||||
]);
|
||||
|
||||
async function fixture() {
|
||||
const { user } = await makeUser(orm());
|
||||
const { user: outsider } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
const ski = await makePlace(orm(), trip.id, { name: 'Morning run', route_geometry: LINE });
|
||||
await makeTour(orm(), ski.id, { tourTypeRef: 'ski', origin: 'gpx', ski_discipline: 'alpine' });
|
||||
const paddle = await makePlace(orm(), trip.id, { name: 'River day', route_geometry: LINE });
|
||||
await makeTour(orm(), paddle.id, { tourTypeRef: 'kayak', origin: 'gpx', boat_type: 'kayak', water_context: 'river' });
|
||||
const hike = await makePlace(orm(), trip.id, { name: 'Ridge', route_geometry: LINE });
|
||||
await makeTour(orm(), hike.id);
|
||||
await addTourWaypoints(orm(), hike.id, [
|
||||
{ lat: 47, lng: 11 },
|
||||
{ lat: 47.01, lng: 11 },
|
||||
]);
|
||||
return { user, outsider, trip, ski, paddle, hike };
|
||||
}
|
||||
|
||||
describe('classify_ski_track', () => {
|
||||
it('TSPORT-MCP-001: classifies a ski track again and answers the classification before', async () => {
|
||||
const { user, trip, ski } = await fixture();
|
||||
const result = read(
|
||||
await mcp.classifySkiTrack(
|
||||
{ tripId: trip.id, placeId: ski.id, ski_discipline: 'cross_country', ski_technique: 'skating' },
|
||||
ctx(user.id),
|
||||
),
|
||||
);
|
||||
expect(result.tour).toMatchObject({ ski_discipline: 'cross_country', ski_technique: 'skating', revision: 2 });
|
||||
expect(result.previous).toEqual({ revision: 1, ski_discipline: 'alpine', ski_technique: null });
|
||||
});
|
||||
|
||||
it('TSPORT-MCP-002: refuses what the REST contract refuses, and a tour that is no ski track', async () => {
|
||||
const { user, trip, ski, hike } = await fixture();
|
||||
const technique = await mcp.classifySkiTrack(
|
||||
{ tripId: trip.id, placeId: ski.id, ski_discipline: 'alpine', ski_technique: 'classic' },
|
||||
ctx(user.id),
|
||||
);
|
||||
expect(technique.isError).toBe(true);
|
||||
await expect(
|
||||
mcp.classifySkiTrack({ tripId: trip.id, placeId: hike.id, ski_discipline: 'alpine' }, ctx(user.id)),
|
||||
).rejects.toThrow('Only a ski track has a ski classification');
|
||||
expect((await findRow(orm(), Tours, { place: ski.id }))?.ski_discipline).toBe('alpine');
|
||||
});
|
||||
});
|
||||
|
||||
describe('set_paddle_plan', () => {
|
||||
const marks = { portages: [{ from_m: 100, to_m: 300, extra_minutes: null }], locks: [] };
|
||||
|
||||
it('TSPORT-MCP-003: lays a portage onto a recorded paddle track and answers the plan before', async () => {
|
||||
const { user, trip, paddle } = await fixture();
|
||||
const result = read(
|
||||
await mcp.setPaddlePlan(
|
||||
{ tripId: trip.id, placeId: paddle.id, paddle_speed_kmh: 5, portage_speed_kmh: null, track_marks: marks },
|
||||
ctx(user.id),
|
||||
),
|
||||
);
|
||||
expect(result.tour).toMatchObject({ paddle_speed_kmh: 5, track_marks: marks, revision: 2 });
|
||||
expect(result.previous).toEqual({
|
||||
revision: 1,
|
||||
paddle_speed_kmh: null,
|
||||
portage_speed_kmh: null,
|
||||
track_marks: { portages: [], locks: [] },
|
||||
});
|
||||
});
|
||||
|
||||
it('TSPORT-MCP-004: a planned tour, a mark past the track and a mark the contract refuses are refused', async () => {
|
||||
const { user, trip, paddle, hike } = await fixture();
|
||||
await expect(
|
||||
mcp.setPaddlePlan(
|
||||
{ tripId: trip.id, placeId: hike.id, paddle_speed_kmh: null, portage_speed_kmh: null, track_marks: marks },
|
||||
ctx(user.id),
|
||||
),
|
||||
).rejects.toThrow('Only a paddle tour has a paddle plan');
|
||||
const far = { portages: [{ from_m: 100, to_m: 90_000, extra_minutes: null }], locks: [] };
|
||||
await expect(
|
||||
mcp.setPaddlePlan(
|
||||
{ tripId: trip.id, placeId: paddle.id, paddle_speed_kmh: null, portage_speed_kmh: null, track_marks: far },
|
||||
ctx(user.id),
|
||||
),
|
||||
).rejects.toThrow('A mark lies beyond the end of the track');
|
||||
const backwards = { portages: [{ from_m: 300, to_m: 100, extra_minutes: null }], locks: [] };
|
||||
const refused = await mcp.setPaddlePlan(
|
||||
{ tripId: trip.id, placeId: paddle.id, paddle_speed_kmh: null, portage_speed_kmh: null, track_marks: backwards },
|
||||
ctx(user.id),
|
||||
);
|
||||
expect(read(refused)).toEqual({ error: 'a portage ends after it begins' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('decide_paddle_obstacles', () => {
|
||||
const op = { key: 'node/12', op: 'note' as const, decision: null, note: 'carry left', basis: null };
|
||||
|
||||
it('TSPORT-MCP-005: saves through the checklist service as the user and answers the checklist', async () => {
|
||||
const { user, trip, paddle } = await fixture();
|
||||
const detail = await t.get(ToursService).getTour(String(trip.id), String(paddle.id));
|
||||
const check = { revision: 'r1', evaluated_at: '2026-10-23T08:00:00Z', entries: [], own: [] };
|
||||
const save = vi
|
||||
.spyOn(t.get(TourObstacleReviewsService), 'save')
|
||||
.mockResolvedValue({ ...detail, obstacle_check: check });
|
||||
const result = read(
|
||||
await mcp.decidePaddleObstacles({ tripId: trip.id, placeId: paddle.id, ops: [op] }, ctx(user.id)),
|
||||
);
|
||||
expect(save).toHaveBeenCalledWith(String(trip.id), String(paddle.id), { ops: [op] }, user.id);
|
||||
expect(result).toMatchObject({ tour: { place_id: paddle.id }, obstacle_check: check });
|
||||
});
|
||||
|
||||
it('TSPORT-MCP-006: one obstacle twice is refused before anything is saved', async () => {
|
||||
const { user, trip, paddle } = await fixture();
|
||||
const save = vi.spyOn(t.get(TourObstacleReviewsService), 'save');
|
||||
const result = await mcp.decidePaddleObstacles(
|
||||
{ tripId: trip.id, placeId: paddle.id, ops: [op, op] },
|
||||
ctx(user.id),
|
||||
);
|
||||
expect(read(result)).toEqual({ error: 'each obstacle at most once' });
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('restore_recorded_track', () => {
|
||||
it('TSPORT-MCP-007: takes a planned import back to its recording; one without a recording is refused', async () => {
|
||||
const { user, trip, hike, paddle } = await fixture();
|
||||
const recorded = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.005, 11.002, 650],
|
||||
[47.01, 11, 700],
|
||||
]);
|
||||
await updateRows(orm(), Tours, { place: hike.id }, { recorded_route_geometry: recorded });
|
||||
const result = read(await mcp.restoreRecordedTrack({ tripId: trip.id, placeId: hike.id }, ctx(user.id)));
|
||||
expect(result.tour).toMatchObject({ place_id: hike.id, has_waypoints: false });
|
||||
await expect(mcp.restoreRecordedTrack({ tripId: trip.id, placeId: paddle.id }, ctx(user.id))).rejects.toThrow(
|
||||
'This tour keeps no recorded track to go back to',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('get_tour_trail_details', () => {
|
||||
it('TSPORT-MCP-008: lays the grades of the ways under the saved line onto it', async () => {
|
||||
const { user, trip, hike } = await fixture();
|
||||
const ways = vi.spyOn(t.get(RoadtripRouterService), 'wayIds').mockResolvedValue([
|
||||
{ wayId: 1, metres: 600 },
|
||||
{ wayId: 2, metres: 400 },
|
||||
]);
|
||||
vi.spyOn(t.get(TourTrailGradeService), 'grades').mockResolvedValue({
|
||||
ways: [
|
||||
{
|
||||
id: 1,
|
||||
mtb_scale: '1',
|
||||
mtb_scale_uphill: null,
|
||||
mtb_scale_imba: null,
|
||||
sac_scale: 'mountain_hiking',
|
||||
sac_scale_unclear: null,
|
||||
surface: 'gravel',
|
||||
highway: 'track',
|
||||
},
|
||||
],
|
||||
unanswered: [2],
|
||||
});
|
||||
const result = read(await mcp.getTourTrailDetails({ tripId: trip.id, placeId: hike.id }, ctx(user.id)));
|
||||
expect(ways).toHaveBeenCalledWith(user.id, [
|
||||
[47, 11],
|
||||
[47.01, 11],
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
place_id: hike.id,
|
||||
tour_type: 'hike',
|
||||
sac: { highest: 2 },
|
||||
mtb: { highest: '1' },
|
||||
surface: [{ value: 'gravel', share: 0.6 }],
|
||||
highway: [{ value: 'track', share: 0.6 }],
|
||||
unknown_share: 0.4,
|
||||
ways_unanswered: 1,
|
||||
truncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('TSPORT-MCP-009: a router that does not answer is said so; reading needs only the trip', async () => {
|
||||
const { user, outsider, trip, hike } = await fixture();
|
||||
vi.spyOn(t.get(RoadtripRouterService), 'wayIds').mockRejectedValue(new Error('down'));
|
||||
await expect(mcp.getTourTrailDetails({ tripId: trip.id, placeId: hike.id }, ctx(user.id))).rejects.toThrow(
|
||||
'The ways under this tour cannot be read right now',
|
||||
);
|
||||
expect(read(await mcp.getTourTrailDetails({ tripId: trip.id, placeId: hike.id }, ctx(outsider.id)))).toEqual({
|
||||
error: 'Trip not found or access denied.',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('find_horse_routes', () => {
|
||||
it('TSPORT-MCP-010: answers each section without its line, its ends instead; a box too large is refused', async () => {
|
||||
const { user, trip } = await fixture();
|
||||
const list = vi.spyOn(t.get(TourHorseRoutesService), 'list').mockResolvedValue({
|
||||
routes: [
|
||||
{
|
||||
id: 'relation/5',
|
||||
name: 'Reitweg',
|
||||
ref: null,
|
||||
osmUrl: 'https://www.openstreetmap.org/relation/5',
|
||||
continues: false,
|
||||
sections: [
|
||||
{
|
||||
number: 1,
|
||||
geometry: [
|
||||
[47.5, 11.2],
|
||||
[47.51, 11.21],
|
||||
[47.52, 11.22],
|
||||
],
|
||||
length_m: 2600,
|
||||
access: [{ value: 'designated', length_m: 2600 }],
|
||||
signposted: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
truncated: false,
|
||||
source: 'openstreetmap',
|
||||
attribution: HORSE_ROUTES_ATTRIBUTION,
|
||||
});
|
||||
const result = read(await mcp.findHorseRoutes({ tripId: trip.id, bbox: '47.5,11.2,47.6,11.3' }, ctx(user.id)));
|
||||
expect(list).toHaveBeenCalledWith({ south: 47.5, west: 11.2, north: 47.6, east: 11.3 });
|
||||
expect(result.routes[0].sections[0]).toEqual({
|
||||
number: 1,
|
||||
length_m: 2600,
|
||||
access: [{ value: 'designated', length_m: 2600 }],
|
||||
signposted: null,
|
||||
from: [47.5, 11.2],
|
||||
to: [47.52, 11.22],
|
||||
});
|
||||
await expect(mcp.findHorseRoutes({ tripId: trip.id, bbox: '40,0,50,20' }, ctx(user.id))).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the checks of the REST routes', () => {
|
||||
it('TSPORT-MCP-011: without place_edit no write runs', async () => {
|
||||
const { user, trip, ski, paddle, hike } = await fixture();
|
||||
const denied = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValue(false);
|
||||
const results = [
|
||||
await mcp.classifySkiTrack({ tripId: trip.id, placeId: ski.id, ski_discipline: 'snowshoe' }, ctx(user.id)),
|
||||
await mcp.setPaddlePlan(
|
||||
{
|
||||
tripId: trip.id,
|
||||
placeId: paddle.id,
|
||||
paddle_speed_kmh: 5,
|
||||
portage_speed_kmh: null,
|
||||
track_marks: { portages: [], locks: [] },
|
||||
},
|
||||
ctx(user.id),
|
||||
),
|
||||
await mcp.decidePaddleObstacles(
|
||||
{
|
||||
tripId: trip.id,
|
||||
placeId: paddle.id,
|
||||
ops: [{ key: 'node/1', op: 'clear', decision: null, note: null, basis: null }],
|
||||
},
|
||||
ctx(user.id),
|
||||
),
|
||||
await mcp.restoreRecordedTrack({ tripId: trip.id, placeId: hike.id }, ctx(user.id)),
|
||||
];
|
||||
expect(results.every((result) => result.isError === true)).toBe(true);
|
||||
expect(denied).toHaveBeenCalledWith('place_edit', trip.id, user.id);
|
||||
expect((await findRow(orm(), Tours, { place: ski.id }))?.ski_discipline).toBe('alpine');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { reshapedHikePoints } from '../../../src/nest/tours/tour-reshape.helpers';
|
||||
import { trailDetailsOf } from '../../../src/nest/tours/tour-trail-details.helpers';
|
||||
import type { TourTrailGrade, TourWaypoint } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// TRAIL-DETAILS-001 to TRAIL-DETAILS-003, RESHAPE-HELPER-001 to RESHAPE-HELPER-003
|
||||
|
||||
const grade = (id: number, over: Partial<TourTrailGrade> = {}): TourTrailGrade => ({
|
||||
id,
|
||||
mtb_scale: null,
|
||||
mtb_scale_uphill: null,
|
||||
mtb_scale_imba: null,
|
||||
sac_scale: null,
|
||||
sac_scale_unclear: null,
|
||||
surface: null,
|
||||
highway: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('the trail details laid onto a saved line', () => {
|
||||
it('TRAIL-DETAILS-001: sums each value by the metres of its ways, scaled onto the saved length', () => {
|
||||
const ways = [
|
||||
{ wayId: 1, metres: 500 },
|
||||
{ wayId: 2, metres: 300 },
|
||||
{ wayId: null, metres: 200 },
|
||||
];
|
||||
const grades = new Map([
|
||||
[1, grade(1, { surface: 'asphalt', highway: 'residential' })],
|
||||
[2, grade(2, { surface: 'gravel', highway: 'track', sac_scale: 'hiking', mtb_scale: '2+' })],
|
||||
]);
|
||||
const details = trailDetailsOf(ways, grades, 2000);
|
||||
expect(details.length_m).toBe(2000);
|
||||
expect(details.surface).toEqual([
|
||||
{ value: 'asphalt', metres: 1000, share: 0.5 },
|
||||
{ value: 'gravel', metres: 600, share: 0.3 },
|
||||
]);
|
||||
expect(details.highway.map(({ value }) => value)).toEqual(['residential', 'track']);
|
||||
expect(details.sac).toMatchObject({ highest: 1, segments: [{ from_m: 1000, to_m: 1600, sac: 1 }] });
|
||||
expect(details.mtb).toEqual({ highest: '2+', values: [{ value: '2+', metres: 600, share: 0.3 }] });
|
||||
expect(details.unknown_share).toBe(0.2);
|
||||
});
|
||||
|
||||
it('TRAIL-DETAILS-002: the hardest mountain bike step wins, a plus above its plain step', () => {
|
||||
const ways = [1, 2, 3].map((wayId) => ({ wayId, metres: 100 }));
|
||||
const grades = new Map([
|
||||
[1, grade(1, { mtb_scale: '1' })],
|
||||
[2, grade(2, { mtb_scale: '2' })],
|
||||
[3, grade(3, { mtb_scale: '2+' })],
|
||||
]);
|
||||
expect(trailDetailsOf(ways, grades, 300).mtb.highest).toBe('2+');
|
||||
expect(trailDetailsOf(ways.slice(0, 2), grades, 200).mtb.highest).toBe('2');
|
||||
});
|
||||
|
||||
it('TRAIL-DETAILS-003: without ways the whole line is unknown, never easy', () => {
|
||||
const details = trailDetailsOf([], new Map(), 1000);
|
||||
expect(details).toMatchObject({ length_m: 0, surface: [], highway: [], unknown_share: 1, mtb: { highest: null } });
|
||||
expect(details.sac.highest).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
const saved = (): TourWaypoint[] => [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0, name: 'Car park', key: 'stop-carpark' },
|
||||
{ lat: 47.1, lng: 11, role: 'via', sequence: 1, poi_category: 'shelter', key: 'stop-hut0001' },
|
||||
{ lat: 47.2, lng: 11, role: 'end', sequence: 2, key: 'stop-summit1' },
|
||||
];
|
||||
|
||||
describe('a saved hike reshaped', () => {
|
||||
it('RESHAPE-HELPER-001: reverse turns the points round, each with its name and kind of place', () => {
|
||||
expect(reshapedHikePoints(saved(), 'reverse')).toEqual({
|
||||
points: [
|
||||
{ lat: 47.2, lng: 11 },
|
||||
{ lat: 47.1, lng: 11, poi_category: 'shelter' },
|
||||
{ lat: 47, lng: 11, name: 'Car park' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('RESHAPE-HELPER-002: close_loop adds the start again at the end, once', () => {
|
||||
const closed = reshapedHikePoints(saved(), 'close_loop');
|
||||
expect(closed).toMatchObject({ points: [{ name: 'Car park' }, {}, {}, { lat: 47, lng: 11 }] });
|
||||
const loop = [...saved(), { lat: 47, lng: 11, role: 'end' as const, sequence: 3 }];
|
||||
expect(reshapedHikePoints(loop, 'close_loop')).toEqual({ refused: 'This hike already ends where it starts.' });
|
||||
});
|
||||
|
||||
it('RESHAPE-HELPER-003: a recorded track and a hike in stages are refused with why', () => {
|
||||
expect(reshapedHikePoints([], 'reverse')).toMatchObject({ refused: expect.stringContaining('recorded track') });
|
||||
const staged = saved().map((point, index) => (index === 1 ? { ...point, stage_end: true } : point));
|
||||
expect(reshapedHikePoints(staged, 'reverse')).toMatchObject({ refused: expect.stringContaining('stages') });
|
||||
expect(reshapedHikePoints(staged, 'close_loop')).toMatchObject({
|
||||
points: expect.arrayContaining([expect.objectContaining({ stage_end: true })]),
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user