mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
feat(tours): assistant takes found places into saved tours and route files from the chat
P6: insert_tour_stop and remove_tour_stop take a place into a saved hike or city walk as one stop and out again, each the other's undo, with change cards in the chat. The planner's insertion rule (poiInsertion) moved to shared so the planner and the server place a stop the same way. "+ Tour" on a found place holds it as a stop of the saved tour open in the planner. P7: GPX, KML and KMZ files attached in the chat are read into their tracks and each is held as a change that takes it in as a hike through import_tour_gpx, undoable per track; the GPX text stays on the held call.
This commit is contained in:
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* Trip assistant e2e for P6 and P7, the whole app (buildApp, every global
|
||||
* guard, the Zod pipe, the response contracts, the real MCP registry with
|
||||
* its addon gates) with an instance connection to a fake OpenAI-compatible
|
||||
* server on loopback, scripted per case.
|
||||
*
|
||||
* Covered: a GPX file attached in the chat is read into its tracks without a
|
||||
* model turn, each held as a change card that takes it in as a hike, the GPX
|
||||
* text kept off the thread; applying one imports exactly that track through
|
||||
* import_tour_gpx and undoing it deletes the tour again; a file without a
|
||||
* track ends with no_tracks_found. A stop the model takes into a saved hike
|
||||
* with insert_tour_stop is held with its card, saved through update_tour's
|
||||
* write when applied (the planner stubbed on the container, as in
|
||||
* assistant-tours.e2e), its receipt offering the way back.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { HikePlanService } from '../../src/nest/tours/hike-plan.service';
|
||||
import { makePlace } from '../helpers/factories/places';
|
||||
import { countRows, findRow } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { addTourWaypoints, makeTour } from '../helpers/factories/tours';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import type { AssistantMessagePart, UiStreamChunk } from '@trek/shared';
|
||||
|
||||
import { createServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// ASTE2E-TOURFILE-001 to ASTE2E-TOURFILE-004
|
||||
|
||||
// ── The fake provider ─────────────────────────────────────────────────────────
|
||||
|
||||
type Step = () => { chunks: object[] };
|
||||
|
||||
const provider = { requests: [] as object[], script: [] as Step[] };
|
||||
|
||||
const say =
|
||||
(text: string): Step =>
|
||||
() => ({
|
||||
chunks: [
|
||||
{ choices: [{ index: 0, delta: { content: text } }] },
|
||||
{ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
|
||||
{ choices: [], usage: { prompt_tokens: 12, completion_tokens: 4 } },
|
||||
],
|
||||
});
|
||||
|
||||
const callTool =
|
||||
(id: string, name: string, args: Record<string, unknown>): Step =>
|
||||
() => ({
|
||||
chunks: [
|
||||
{
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
tool_calls: [{ index: 0, id, type: 'function', function: { name, arguments: JSON.stringify(args) } }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] },
|
||||
],
|
||||
});
|
||||
|
||||
async function readBody(req: IncomingMessage): Promise<string> {
|
||||
let text = '';
|
||||
for await (const chunk of req) text += String(chunk);
|
||||
return text;
|
||||
}
|
||||
|
||||
async function answer(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
if (req.method === 'GET' && req.url?.startsWith('/api/tags')) {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ models: [{ name: 'fake-model', size: 1 }] }));
|
||||
return;
|
||||
}
|
||||
if (req.method !== 'POST' || req.url !== '/v1/chat/completions') {
|
||||
res.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
provider.requests.push(JSON.parse(await readBody(req)) as object);
|
||||
const reply = (provider.script.shift() ?? say('Nothing more.'))();
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream' });
|
||||
for (const chunk of reply.chunks) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
||||
res.end('data: [DONE]\n\n');
|
||||
}
|
||||
|
||||
// ── The app ──────────────────────────────────────────────────────────────────
|
||||
|
||||
let nestApp: INestApplication;
|
||||
let orm: MikroORM;
|
||||
let fake: HttpServer;
|
||||
|
||||
beforeAll(async () => {
|
||||
fake = createServer((req, res) => {
|
||||
answer(req, res).catch(() => res.destroy());
|
||||
});
|
||||
await new Promise<void>((resolve) => fake.listen(0, '127.0.0.1', resolve));
|
||||
nestApp = await buildApp();
|
||||
orm = nestApp.get(MikroORM);
|
||||
await setAddonEnabled(orm, 'ai_assistant', true);
|
||||
await setAddonEnabled(orm, 'tours', true);
|
||||
const admin = (await makeUser(orm, { role: 'admin' })).user.id;
|
||||
const { port } = fake.address() as AddressInfo;
|
||||
const res = await request(nestApp.getHttpServer())
|
||||
.put('/api/admin/ai/connection')
|
||||
.set('Cookie', sessionCookie(admin))
|
||||
.send({ kind: 'custom', baseUrl: `http://127.0.0.1:${port}/v1`, model: 'fake-model' });
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetRateLimits(nestApp);
|
||||
provider.requests = [];
|
||||
provider.script = [];
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await nestApp.close();
|
||||
await new Promise<void>((resolve) => fake.close(() => resolve()));
|
||||
});
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const CTX = { locale: 'en', timeZone: 'Europe/Berlin' };
|
||||
|
||||
interface Answer {
|
||||
status: number;
|
||||
chunks: UiStreamChunk[];
|
||||
json: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
function parseAnswer(status: number, type: string, text: string): Answer {
|
||||
if (!type.includes('text/event-stream')) {
|
||||
return { status, chunks: [], json: text ? (JSON.parse(text) as Record<string, unknown>) : null };
|
||||
}
|
||||
const events = text
|
||||
.split('\n\n')
|
||||
.filter((event) => event.startsWith('data: '))
|
||||
.map((event) => event.slice('data: '.length));
|
||||
expect(events.at(-1)).toBe('[DONE]');
|
||||
return { status, chunks: events.slice(0, -1).map((event) => JSON.parse(event) as UiStreamChunk), json: null };
|
||||
}
|
||||
|
||||
function asText(req: request.Test) {
|
||||
return req.buffer(true).parse((stream, done) => {
|
||||
let text = '';
|
||||
stream.setEncoding('utf8');
|
||||
stream.on('data', (chunk: string) => (text += chunk));
|
||||
stream.on('end', () => done(null, text));
|
||||
});
|
||||
}
|
||||
|
||||
async function post(path: string, userId: number, body: object): Promise<Answer> {
|
||||
const res = await asText(request(nestApp.getHttpServer()).post(path).set('Cookie', sessionCookie(userId)).send(body));
|
||||
return parseAnswer(res.status, String(res.headers['content-type']), res.body as string);
|
||||
}
|
||||
|
||||
async function upload(path: string, userId: number, fileName: string, text: string): Promise<Answer> {
|
||||
const req = request(nestApp.getHttpServer())
|
||||
.post(path)
|
||||
.set('Cookie', sessionCookie(userId))
|
||||
.field('locale', CTX.locale)
|
||||
.field('timeZone', CTX.timeZone)
|
||||
.attach('file', Buffer.from(text, 'utf8'), { filename: fileName, contentType: 'application/gpx+xml' });
|
||||
const res = await asText(req);
|
||||
return parseAnswer(res.status, String(res.headers['content-type']), res.body as string);
|
||||
}
|
||||
|
||||
const ofType = <T extends UiStreamChunk['type']>(chunks: UiStreamChunk[], type: T) =>
|
||||
chunks.filter((chunk): chunk is Extract<UiStreamChunk, { type: T }> => chunk.type === type);
|
||||
|
||||
async function traveller() {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id, { title: 'Bavaria' });
|
||||
return { userId: user.id, tripId: trip.id, base: `/api/trips/${trip.id}/assistant` };
|
||||
}
|
||||
|
||||
const WEEKEND = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
|
||||
<trk><name>Saturday</name><trkseg>
|
||||
<trkpt lat="47.5" lon="11.1"><ele>800</ele></trkpt>
|
||||
<trkpt lat="47.51" lon="11.1"><ele>1000</ele></trkpt>
|
||||
</trkseg></trk>
|
||||
<trk><name>Sunday</name><trkseg>
|
||||
<trkpt lat="47.6" lon="11.2"><ele>700</ele></trkpt>
|
||||
<trkpt lat="47.61" lon="11.2"><ele>900</ele></trkpt>
|
||||
</trkseg></trk>
|
||||
</gpx>`;
|
||||
|
||||
// ── Cases ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('a route file attached in the chat (P7)', () => {
|
||||
it('ASTE2E-TOURFILE-001: is read into its tracks without a model turn, each held as a hike, the GPX kept off the thread', async () => {
|
||||
const t = await traveller();
|
||||
const read = await upload(`${t.base}/attachments`, t.userId, 'weekend.gpx', WEEKEND);
|
||||
expect(read.status).toBe(200);
|
||||
expect(provider.requests).toHaveLength(0);
|
||||
const inputs = ofType(read.chunks, 'tool-input-available');
|
||||
expect(inputs.map((chunk) => chunk.toolName)).toEqual(['read_tour_file', 'import_tour_file', 'import_tour_file']);
|
||||
expect(JSON.stringify(read.chunks)).not.toContain('<trkpt');
|
||||
const changes = ofType(read.chunks, 'data-trek-change').map((chunk) => chunk.data);
|
||||
expect(changes.map((change) => [change.verbKey, change.subject, change.undoable])).toEqual([
|
||||
['importTour', 'Saturday', true],
|
||||
['importTour', 'Sunday', true],
|
||||
]);
|
||||
const threadId = ofType(read.chunks, 'data-trek-thread')[0]?.data.threadId;
|
||||
const shown = await request(nestApp.getHttpServer())
|
||||
.get(`${t.base}/threads/${threadId}`)
|
||||
.set('Cookie', sessionCookie(t.userId));
|
||||
expect(JSON.stringify(shown.body)).not.toContain('<trkpt');
|
||||
const parts = (shown.body.messages as Array<{ parts: AssistantMessagePart[] }>).flatMap((m) => m.parts);
|
||||
expect(parts).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: 'tool-call',
|
||||
toolName: 'import_tour_file',
|
||||
args: { via: 'import_tour_gpx', file_name: 'weekend.gpx', tour_type: 'hike', track_name: 'Saturday' },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('ASTE2E-TOURFILE-002: applying one track imports exactly that track as a hike, and its undo deletes it again', async () => {
|
||||
const t = await traveller();
|
||||
const read = await upload(`${t.base}/attachments`, t.userId, 'weekend.gpx', WEEKEND);
|
||||
const threadId = ofType(read.chunks, 'data-trek-thread')[0]?.data.threadId;
|
||||
const [saturday, sunday] = ofType(read.chunks, 'data-trek-change').map((chunk) => chunk.data.toolCallId);
|
||||
provider.script = [say('Saturday is in the trip now.')];
|
||||
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
|
||||
...CTX,
|
||||
decisions: [
|
||||
{ toolCallId: saturday, approved: true },
|
||||
{ toolCallId: sunday, approved: false },
|
||||
],
|
||||
});
|
||||
expect(decided.status).toBe(200);
|
||||
const [applied] = ofType(decided.chunks, 'data-trek-applied');
|
||||
expect(applied?.data).toMatchObject({ toolCallId: saturday, entity: 'tour' });
|
||||
const placeId = applied?.data.ids[0] ?? 0;
|
||||
expect((await findRow(orm, Places, { id: placeId }))?.name).toBe('Saturday');
|
||||
expect(await countRows(orm, Places, { trip: t.tripId })).toBe(1);
|
||||
|
||||
const undone = await request(nestApp.getHttpServer())
|
||||
.post(`${t.base}/tool-calls/${saturday}/undo`)
|
||||
.set('Cookie', sessionCookie(t.userId))
|
||||
.send({});
|
||||
expect(undone.status).toBe(200);
|
||||
expect(await findRow(orm, Places, { id: placeId })).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTE2E-TOURFILE-003: a route file without a track ends with no_tracks_found and holds nothing', async () => {
|
||||
const t = await traveller();
|
||||
const pins = '<gpx version="1.1"><wpt lat="47" lon="11"><name>Pin</name></wpt></gpx>';
|
||||
const read = await upload(`${t.base}/attachments`, t.userId, 'pins.gpx', pins);
|
||||
expect(ofType(read.chunks, 'error')[0]).toMatchObject({ errorText: 'no_tracks_found' });
|
||||
expect(ofType(read.chunks, 'data-trek-change')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a stop the model takes into a saved hike (P6)', () => {
|
||||
it('ASTE2E-TOURFILE-004: is held with its card, saved when applied, and its receipt offers the way back', async () => {
|
||||
const t = await traveller();
|
||||
const place = await makePlace(orm, t.tripId, { name: 'Herzogstand', category: null });
|
||||
await makeTour(orm, place.id, { revision: 3 });
|
||||
await addTourWaypoints(orm, place.id, [
|
||||
{ lat: 47.5, lng: 11.1, station_key: 'start1', name: 'Car park' },
|
||||
{ lat: 47.505, lng: 11.1, station_key: 'alm111', name: 'Alm' },
|
||||
{ lat: 47.51, lng: 11.1, station_key: 'summit', name: 'Summit' },
|
||||
]);
|
||||
const hikes = nestApp.get(HikePlanService);
|
||||
const saved = (revision: number, keys: string[]) =>
|
||||
({
|
||||
tour: { place_id: place.id, name: 'Herzogstand', tour_type: 'hike', revision, has_waypoints: true },
|
||||
waypoints: keys.map((key, index) => ({
|
||||
key,
|
||||
lat: key === 'spring' ? 47.507 : [47.5, 47.505, 47.51][Math.min(index, 2)],
|
||||
lng: 11.1,
|
||||
role: 'via',
|
||||
sequence: index,
|
||||
})),
|
||||
route: { planned: true },
|
||||
replanned: true,
|
||||
}) as unknown as Awaited<ReturnType<HikePlanService['update']>>;
|
||||
const update = vi.spyOn(hikes, 'update').mockResolvedValue(saved(4, ['start1', 'alm111', 'spring', 'summit']));
|
||||
|
||||
provider.script = [
|
||||
callTool('call_tours', 'use_addon_tools', { groups: ['tours'] }),
|
||||
callTool('call_stop', 'insert_tour_stop', {
|
||||
placeId: place.id,
|
||||
expected_revision: 3,
|
||||
stop: { lat: 47.507, lng: 11.1, name: 'Spring' },
|
||||
}),
|
||||
say('Shall I add the spring?'),
|
||||
];
|
||||
const turn = await post(`${t.base}/chat`, t.userId, { ...CTX, threadId: null, text: 'Add the spring to the hike' });
|
||||
const threadId = ofType(turn.chunks, 'data-trek-thread')[0]?.data.threadId;
|
||||
const [change] = ofType(turn.chunks, 'data-trek-change');
|
||||
expect(change?.data).toMatchObject({ verbKey: 'addTourStop', subject: 'Herzogstand', undoable: true });
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
|
||||
provider.script = [say('Added.')];
|
||||
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
|
||||
...CTX,
|
||||
decisions: [{ toolCallId: change?.data.toolCallId, approved: true }],
|
||||
});
|
||||
expect(update.mock.calls[0]?.[2]).toMatchObject({ placeId: place.id, expected_revision: 3 });
|
||||
expect(update.mock.calls[0]?.[2].waypoints?.map((point) => point.name)).toEqual([
|
||||
'Car park',
|
||||
'Alm',
|
||||
'Spring',
|
||||
'Summit',
|
||||
]);
|
||||
const [applied] = ofType(decided.chunks, 'data-trek-applied');
|
||||
expect(applied?.data).toMatchObject({ entity: 'tour', ids: [place.id] });
|
||||
expect(applied?.data.undoUntil).toEqual(expect.any(String));
|
||||
});
|
||||
});
|
||||
@@ -553,6 +553,32 @@ export const toursRoadtrip: CaseGroup = {
|
||||
stub: routerDown,
|
||||
expect: ['tours:changed', 'place:updated'],
|
||||
},
|
||||
{
|
||||
// P6: a found place taken into the walk as a station, saved as save_tour_change saves one change.
|
||||
tool: 'insert_tour_stop',
|
||||
needs: ['tour'],
|
||||
setup: planWalk,
|
||||
args: (s) => ({
|
||||
tripId: s.trip.id,
|
||||
placeId: s.tourPlace.id,
|
||||
expected_revision: 1,
|
||||
stop: { lat: 48.106, lng: 11.5, name: 'Fountain' },
|
||||
after_key: 'walk-market',
|
||||
}),
|
||||
// The planner takes a found place in as a point of its draft and saves the walk through the same route write.
|
||||
rest: { method: 'put', path: tourPath, body: () => walkBody(1) },
|
||||
stub: routerDown,
|
||||
expect: ['tours:changed', 'place:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'remove_tour_stop',
|
||||
needs: ['tour'],
|
||||
setup: planWalk,
|
||||
args: (s) => ({ tripId: s.trip.id, placeId: s.tourPlace.id, expected_revision: 1, key: 'walk-market' }),
|
||||
rest: { method: 'put', path: tourPath, body: () => walkBody(1) },
|
||||
stub: routerDown,
|
||||
expect: ['tours:changed', 'place:updated'],
|
||||
},
|
||||
{
|
||||
tool: 'undo_tour_change',
|
||||
needs: ['tour'],
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* P6, P7: the server's own tour steps as the model is told of them, a found
|
||||
* place taken into a tour, a route file read and a track of it taken in,
|
||||
* through the note the history replays in place of a call.
|
||||
*/
|
||||
import { serverStepsNote } from '../../../../src/nest/assistant/assistant-history';
|
||||
import {
|
||||
ADD_FOUND_PLACE_TOOL,
|
||||
ASSISTANT_SERVER_TOOLS,
|
||||
IMPORT_TOUR_FILE_TOOL,
|
||||
READ_TOUR_FILE_TOOL,
|
||||
} from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import type { AssistantMessagePart } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// AST-HISTORY-TOURS-001 to AST-HISTORY-TOURS-004
|
||||
|
||||
type Call = Extract<AssistantMessagePart, { type: 'tool-call' }>;
|
||||
|
||||
const call = (toolName: string, args: Record<string, unknown>, over: Partial<Call> = {}): Call => ({
|
||||
type: 'tool-call',
|
||||
toolCallId: 'c1',
|
||||
toolName,
|
||||
args,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('the tour steps the model is told of', () => {
|
||||
it('AST-HISTORY-TOURS-001: the route file steps are the server own, never replayed as calls', () => {
|
||||
expect(ASSISTANT_SERVER_TOOLS.has(READ_TOUR_FILE_TOOL)).toBe(true);
|
||||
expect(ASSISTANT_SERVER_TOOLS.has(IMPORT_TOUR_FILE_TOOL)).toBe(true);
|
||||
});
|
||||
|
||||
it('AST-HISTORY-TOURS-002: a found place taken into a tour, as it waits and once decided', () => {
|
||||
const args = { via: 'insert_tour_stop', placeId: 64, stop: { name: 'Spring' }, tourName: 'Herzogstand' };
|
||||
expect(serverStepsNote([call(ADD_FOUND_PLACE_TOOL, args, { approval: { id: 'c1' } })])).toBe(
|
||||
'The user picked "Spring" as a stop of the tour "Herzogstand" from the search results; it waits for them to add or discard it.',
|
||||
);
|
||||
expect(serverStepsNote([call(ADD_FOUND_PLACE_TOOL, args, { approval: { id: 'c1', approved: true } })])).toBe(
|
||||
'"Spring" as a stop of the tour "Herzogstand" was added.',
|
||||
);
|
||||
expect(serverStepsNote([call(ADD_FOUND_PLACE_TOOL, args, { approval: { id: 'c1', approved: false } })])).toBe(
|
||||
'The user discarded "Spring" as a stop of the tour "Herzogstand".',
|
||||
);
|
||||
});
|
||||
|
||||
it('AST-HISTORY-TOURS-003: a route file read, with its tracks, without any, or not at all', () => {
|
||||
const tracks = [{ name: 'Saturday', distance_km: 8.2, points: 120, has_heights: true }];
|
||||
expect(serverStepsNote([call(READ_TOUR_FILE_TOOL, { name: 'weekend.gpx' }, { result: { tracks } })])).toBe(
|
||||
`TREK read the attached route file "weekend.gpx" and found 1 track(s): ${JSON.stringify(tracks)}.`,
|
||||
);
|
||||
expect(serverStepsNote([call(READ_TOUR_FILE_TOOL, { name: 'pins.kml' }, { result: { tracks: [] } })])).toBe(
|
||||
'TREK read the attached route file "pins.kml" and found no track or route in it.',
|
||||
);
|
||||
expect(serverStepsNote([call(READ_TOUR_FILE_TOOL, { name: 'x.kmz' }, { isError: true })])).toBe(
|
||||
'TREK could not read the attached route file "x.kmz".',
|
||||
);
|
||||
});
|
||||
|
||||
it('AST-HISTORY-TOURS-004: a track taken in as a hike, or not', () => {
|
||||
const args = { via: 'import_tour_gpx', file_name: 'weekend.gpx', track_name: 'Saturday', tour_type: 'hike' };
|
||||
expect(serverStepsNote([call(IMPORT_TOUR_FILE_TOOL, args, { approval: { id: 'c1', approved: true } })])).toBe(
|
||||
'The track "Saturday" of "weekend.gpx" was taken in as a hike.',
|
||||
);
|
||||
expect(
|
||||
serverStepsNote([call(IMPORT_TOUR_FILE_TOOL, args, { approval: { id: 'c1', approved: true }, isError: true })]),
|
||||
).toBe('The track "Saturday" of "weekend.gpx" could not be taken in as a hike.');
|
||||
expect(
|
||||
serverStepsNote([call(IMPORT_TOUR_FILE_TOOL, args, { approval: { id: 'c1', resolution: 'cancelled' } })]),
|
||||
).toBe('The track "Saturday" of "weekend.gpx" was not taken in as a hike; the user moved on without deciding.');
|
||||
expect(serverStepsNote([call(IMPORT_TOUR_FILE_TOOL, args, { approval: { id: 'c1' } })])).toBe(
|
||||
'The track "Saturday" of "weekend.gpx" waits for the user to take it in as a hike or discard it.',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* P7: a route file attached in the trip chat, as the assistant proposes it:
|
||||
* refused where tours are off, one held import per track (the GPX text on the
|
||||
* held call only), the tracks the trip has or no import takes named in the
|
||||
* read step and not proposed, at most a step's worth.
|
||||
*/
|
||||
import { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import {
|
||||
foundPlaceArgs,
|
||||
IMPORT_TOUR_FILE_TOOL,
|
||||
MAX_WRITES_PER_STEP,
|
||||
READ_TOUR_FILE_TOOL,
|
||||
writeToolOf,
|
||||
} from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import { AssistantTourFileService } from '../../../../src/nest/assistant/assistant-tour-file.service';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { TourFileReadService, type TourFileTrack } from '../../../../src/nest/tours/tour-file-read.service';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// AST-TOUR-FILE-001 to AST-TOUR-FILE-005
|
||||
|
||||
const track = (name: string, over: Partial<TourFileTrack> = {}): TourFileTrack => ({
|
||||
name,
|
||||
gpx: `<gpx><trk><name>${name}</name></trk></gpx>`,
|
||||
point_count: 120,
|
||||
distance_km: 8.24,
|
||||
has_heights: true,
|
||||
duplicate: false,
|
||||
...over,
|
||||
});
|
||||
|
||||
function file(name: string): Express.Multer.File {
|
||||
return { originalname: name, buffer: Buffer.from('<gpx/>'), size: 6 } as Express.Multer.File;
|
||||
}
|
||||
|
||||
async function make(tracks: TourFileTrack[], opts: { tours?: boolean; whole?: boolean } = {}) {
|
||||
const read = vi.fn(async () => ({ tracks, whole: opts.whole === true }));
|
||||
const isAddonEnabled = vi.fn(async () => opts.tours !== false);
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
AssistantTourFileService,
|
||||
{ provide: TourFileReadService, useValue: { read } },
|
||||
{ provide: AddonsService, useValue: { isAddonEnabled } },
|
||||
],
|
||||
}).compile();
|
||||
return { service: moduleRef.get(AssistantTourFileService), read, isAddonEnabled };
|
||||
}
|
||||
|
||||
describe('AssistantTourFileService', () => {
|
||||
it('AST-TOUR-FILE-001: names its read step and the error of a file without a track', async () => {
|
||||
const { service } = await make([]);
|
||||
expect(service.readTool).toBe(READ_TOUR_FILE_TOOL);
|
||||
expect(service.emptyCode).toBe('no_tracks_found');
|
||||
});
|
||||
|
||||
it('AST-TOUR-FILE-002: refuses a route file where tours are off', async () => {
|
||||
const { service, isAddonEnabled } = await make([], { tours: false });
|
||||
await expect(service.ensureReadable(7, file('a.gpx'))).rejects.toBeInstanceOf(DomainError);
|
||||
expect(isAddonEnabled).toHaveBeenCalledWith('tours');
|
||||
await expect((await make([])).service.ensureReadable(7, file('a.gpx'))).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('AST-TOUR-FILE-003: proposes one hike per track, the GPX text kept on the held call only', async () => {
|
||||
const { service, read } = await make([track('Saturday'), track('Sunday')]);
|
||||
const { found, proposals } = await service.propose(7, 5, file('weekend.gpx'));
|
||||
expect(read).toHaveBeenCalledWith(5, expect.any(Buffer), 'weekend.gpx');
|
||||
expect(proposals).toHaveLength(2);
|
||||
expect(proposals[0]).toEqual({
|
||||
toolName: IMPORT_TOUR_FILE_TOOL,
|
||||
args: {
|
||||
via: 'import_tour_gpx',
|
||||
file_name: 'weekend.gpx',
|
||||
tour_type: 'hike',
|
||||
track_name: 'Saturday',
|
||||
gpx: '<gpx><trk><name>Saturday</name></trk></gpx>',
|
||||
},
|
||||
shownArgs: { via: 'import_tour_gpx', file_name: 'weekend.gpx', tour_type: 'hike', track_name: 'Saturday' },
|
||||
});
|
||||
expect(found).toEqual({
|
||||
tracks: [
|
||||
{ name: 'Saturday', distance_km: 8.2, points: 120, has_heights: true },
|
||||
{ name: 'Sunday', distance_km: 8.2, points: 120, has_heights: true },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('AST-TOUR-FILE-004: names a track the trip has or no import takes, and proposes neither', async () => {
|
||||
const { service } = await make([track('Known', { duplicate: true }), track('Huge', { gpx: null }), track('New')]);
|
||||
const { found, proposals } = await service.propose(7, 5, file('mixed.kml'));
|
||||
expect(proposals.map((proposal) => proposal.args.track_name)).toEqual(['New']);
|
||||
expect(found.tracks).toEqual([
|
||||
expect.objectContaining({ name: 'Known', skipped: 'already_in_trip' }),
|
||||
expect.objectContaining({ name: 'Huge', skipped: 'too_large' }),
|
||||
expect.objectContaining({ name: 'New' }),
|
||||
]);
|
||||
expect(found.proposed).toBe(1);
|
||||
});
|
||||
|
||||
it('AST-TOUR-FILE-005: holds at most a step of tracks, runs each through import_tour_gpx with what it takes', async () => {
|
||||
const many = Array.from({ length: MAX_WRITES_PER_STEP + 3 }, (_, index) => track(`Leg ${index}`));
|
||||
const { service } = await make(many, { whole: true });
|
||||
const { found, proposals } = await service.propose(7, 5, file('legs.gpx'));
|
||||
expect(proposals).toHaveLength(MAX_WRITES_PER_STEP);
|
||||
expect(found.whole_file).toBe(true);
|
||||
const args = proposals[0]?.args ?? {};
|
||||
expect(writeToolOf(IMPORT_TOUR_FILE_TOOL, args)).toBe('import_tour_gpx');
|
||||
expect(foundPlaceArgs(args)).toEqual({ gpx: args.gpx, file_name: 'legs.gpx', tour_type: 'hike' });
|
||||
expect(writeToolOf(IMPORT_TOUR_FILE_TOOL, { ...args, via: 'delete_place' })).toBe(IMPORT_TOUR_FILE_TOOL);
|
||||
});
|
||||
});
|
||||
@@ -40,7 +40,10 @@ function make() {
|
||||
undo: vi.fn(async () => undefined),
|
||||
stop: vi.fn(async () => undefined),
|
||||
};
|
||||
const foundPlaces = { add: vi.fn(async () => ({ message: { id: 'msg-3' } })) };
|
||||
const foundPlaces = {
|
||||
add: vi.fn(async () => ({ message: { id: 'msg-3' } })),
|
||||
insertIntoTour: vi.fn(async () => ({ message: { id: 'msg-4' } })),
|
||||
};
|
||||
const shares = { share: vi.fn(async () => ({ message: { id: 12, origin: 'assistant' } })) };
|
||||
const proposals = { take: vi.fn(async () => ({ message: { id: 'msg-4' } })) };
|
||||
const controller = new AssistantController(
|
||||
@@ -112,6 +115,11 @@ describe('AssistantController', () => {
|
||||
path: 'threads/:threadId/found-places',
|
||||
httpCode: 200,
|
||||
});
|
||||
expect(route('insertFoundPlace')).toEqual({
|
||||
method: RequestMethod.POST,
|
||||
path: 'threads/:threadId/found-places/tour',
|
||||
httpCode: 200,
|
||||
});
|
||||
expect(route('takeProposal')).toEqual({
|
||||
method: RequestMethod.POST,
|
||||
path: 'threads/:threadId/proposals',
|
||||
@@ -148,6 +156,9 @@ describe('AssistantController', () => {
|
||||
});
|
||||
expect(shares.share).toHaveBeenCalledWith(user, 5, 9, 'msg-3', 'Hi all', 'sock-1');
|
||||
expect(() => controller.addFoundPlace(user, '5', 'x', body)).toThrow(DomainError);
|
||||
const stop = { locale: 'en', timeZone: 'UTC', ref: 'call_1:0', tourId: 64 };
|
||||
expect(await controller.insertFoundPlace(user, '5', '9', stop)).toEqual({ message: { id: 'msg-4' } });
|
||||
expect(foundPlaces.insertIntoTour).toHaveBeenCalledWith(7, 5, 9, stop);
|
||||
});
|
||||
|
||||
it('ASTCTL-008: sharing asks for the trip chat right, "Plan this" and "+ Day" for editing places; nothing else asks', () => {
|
||||
@@ -155,6 +166,7 @@ describe('AssistantController', () => {
|
||||
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers.share)).toBe('collab_edit');
|
||||
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers.takeProposal)).toBe('place_edit');
|
||||
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers.addFoundPlace)).toBe('place_edit');
|
||||
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers.insertFoundPlace)).toBe('place_edit');
|
||||
for (const name of ['chat', 'decide', 'undo']) {
|
||||
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers[name]), name).toBeUndefined();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* ASTCARD-TOUR-080 to ASTCARD-TOUR-087
|
||||
*
|
||||
* P6 in the chat: a found place taken into a saved tour as a stop
|
||||
* (insert_tour_stop), by the model or with "+ Tour" on a found place, and a
|
||||
* stop taken out (remove_tour_stop). The card names the tour, the stop and
|
||||
* the two points it goes between; each change goes back by the other while
|
||||
* the tour is still at the revision the change left it at.
|
||||
*/
|
||||
import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';
|
||||
import { stopArgs } from '../../../../../../src/nest/assistant/assistant-found-places.service';
|
||||
import {
|
||||
ADD_FOUND_PLACE_TOOL,
|
||||
foundPlaceArgs,
|
||||
writeToolOf,
|
||||
} from '../../../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import { unchangedSinceApplied } from '../../../../../../src/nest/assistant/assistant-undo.helpers';
|
||||
import { loadFor } from '../../../../../../src/nest/assistant/cards/card-context';
|
||||
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 { defaultAfterKeyOf } from '../../../../../../src/nest/assistant/cards/tour/tour-stop.cards';
|
||||
import { describeToolCall } from '../../../../../../src/nest/assistant/tool-call-preview.helpers';
|
||||
import { DomainError } from '../../../../../../src/nest/common/domain-error';
|
||||
import { assistantChangePreviewSchema, type AssistantFoundPlace } 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: 64, name: 'Herzogstand', lat: 47.5, lng: 11.1 }] },
|
||||
null,
|
||||
);
|
||||
const ctx: PreviewContext = { card, categories: new Map(), locale: 'en-GB', today: '2026-06-01', airport: () => null };
|
||||
|
||||
/** get_tour_plan of the hike: three points and its line in brief. */
|
||||
const PLAN = {
|
||||
tour: { place_id: 64, name: 'Herzogstand', tour_type: 'hike', revision: 3 },
|
||||
waypoints: [
|
||||
{ key: 'start1', lat: 47.5, lng: 11.1, role: 'start', name: 'Car park' },
|
||||
{ key: 'alm111', lat: 47.505, lng: 11.1, role: 'via', name: 'Alm' },
|
||||
{ key: 'summit', lat: 47.51, lng: 11.1, role: 'end', name: 'Summit' },
|
||||
],
|
||||
line: {
|
||||
point_count: 3,
|
||||
has_heights: true,
|
||||
preview: [
|
||||
[47.5, 11.1, 800],
|
||||
[47.505, 11.1, 900],
|
||||
[47.51, 11.1, 1000],
|
||||
],
|
||||
},
|
||||
};
|
||||
const STOP = { lat: 47.507, lng: 11.1, name: 'Spring' };
|
||||
|
||||
function holding(value: unknown) {
|
||||
return {
|
||||
summary: { days: [] },
|
||||
places: { places: [] },
|
||||
reads: new Map([[readKey('get_tour_plan', { placeId: 64 }), value]]),
|
||||
};
|
||||
}
|
||||
|
||||
describe('a stop taken into a tour in the chat', () => {
|
||||
it('ASTCARD-TOUR-080: reads the tour, and its card names the tour, the stop and the two points it goes between', async () => {
|
||||
const read = vi.fn(async () => PLAN);
|
||||
const args = { placeId: 64, expected_revision: 3, stop: STOP };
|
||||
const loaded = await loadFor('insert_tour_stop', args, read);
|
||||
expect(read).toHaveBeenCalledWith('get_tour_plan', { placeId: 64 });
|
||||
const preview = describeToolCall('insert_tour_stop', 'tc-1', args, ctx, loaded);
|
||||
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
|
||||
expect(preview).toMatchObject({ subject: 'Herzogstand', verbKey: 'addTourStop', placeIds: [64], undoable: true });
|
||||
expect(preview.rows).toEqual([
|
||||
{ op: 'add', labelKey: 'name', before: null, after: 'Spring' },
|
||||
{ op: 'add', labelKey: 'position', before: null, after: 'Alm → Summit' },
|
||||
]);
|
||||
expect(ASSISTANT_WRITE_TOOLS.insert_tour_stop).toMatchObject({ verbKey: 'addTourStop', entity: 'tour' });
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-081: a point named keeps its place in the card; a new end has nothing after it', () => {
|
||||
const named = describeToolCall(
|
||||
'insert_tour_stop',
|
||||
'tc-1',
|
||||
{ placeId: 64, stop: STOP, after_key: 'start1' },
|
||||
ctx,
|
||||
PLAN,
|
||||
);
|
||||
expect(named.rows[1]?.after).toBe('Car park → Alm');
|
||||
const end = describeToolCall(
|
||||
'insert_tour_stop',
|
||||
'tc-1',
|
||||
{ placeId: 64, stop: STOP, after_key: 'summit' },
|
||||
ctx,
|
||||
PLAN,
|
||||
);
|
||||
expect(end.rows[1]?.after).toBe('Summit →');
|
||||
// Without the tour read, the card still names the tour from the trip.
|
||||
expect(describeToolCall('insert_tour_stop', 'tc-1', { placeId: 64, stop: STOP }, ctx, null).subject).toBe(
|
||||
'Herzogstand',
|
||||
);
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-082: goes back by taking the stop out, while the tour is at the revision it left', () => {
|
||||
const undo = ASSISTANT_UNDO_MAP.insert_tour_stop;
|
||||
const result = { tour: { place_id: 64, revision: 4 }, stop: { key: 'spring', name: 'Spring' } };
|
||||
expect(undo.tool).toBe('remove_tour_stop');
|
||||
expect(undo.args({}, result, null)).toEqual({ placeId: 64, key: 'spring', expected_revision: 4 });
|
||||
expect(undo.args({}, { ...result, stop: { key: null } }, null)).toBeNull();
|
||||
const call = { args: { placeId: 64 }, preview: null };
|
||||
const at = (revision: number) => holding({ tour: { revision } });
|
||||
expect(unchangedSinceApplied('insert_tour_stop', result, at(4), call)).toBe(true);
|
||||
expect(unchangedSinceApplied('insert_tour_stop', result, at(5), call)).toBe(false);
|
||||
expect(unchangedSinceApplied('insert_tour_stop', result, at(4))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a stop taken out in the chat', () => {
|
||||
it('ASTCARD-TOUR-083: names the tour and the stop, and goes back by putting it after the point it followed', () => {
|
||||
const preview = describeToolCall('remove_tour_stop', 'tc-2', { placeId: 64, key: 'alm111' }, ctx, PLAN);
|
||||
expect(preview).toMatchObject({ subject: 'Herzogstand', verbKey: 'removeTourStop', undoable: true });
|
||||
expect(preview.rows).toEqual([{ op: 'add', labelKey: 'name', before: null, after: 'Alm' }]);
|
||||
const undo = ASSISTANT_UNDO_MAP.remove_tour_stop;
|
||||
const result = {
|
||||
tour: { place_id: 64, revision: 5 },
|
||||
removed: { key: 'alm111', lat: 47.505, lng: 11.1, name: 'Alm', poi_category: 'shelter', after_key: 'start1' },
|
||||
};
|
||||
expect(undo.tool).toBe('insert_tour_stop');
|
||||
expect(undo.args({}, result, null)).toEqual({
|
||||
placeId: 64,
|
||||
expected_revision: 5,
|
||||
stop: { lat: 47.505, lng: 11.1, name: 'Alm', poi_category: 'shelter' },
|
||||
after_key: 'start1',
|
||||
});
|
||||
expect(undo.args({}, { tour: result.tour, removed: { key: 'x' } }, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('"+ Tour" on a found place', () => {
|
||||
const place: AssistantFoundPlace = {
|
||||
ref: 'tc-9:0',
|
||||
name: 'Spring',
|
||||
address: null,
|
||||
lat: 47.507,
|
||||
lng: 11.1,
|
||||
kind: null,
|
||||
rating: null,
|
||||
openNow: null,
|
||||
googlePlaceId: null,
|
||||
osmId: null,
|
||||
photoKey: null,
|
||||
inTripPlaceId: null,
|
||||
};
|
||||
|
||||
it('ASTCARD-TOUR-084: holds insert_tour_stop after the last point before the place, against the revision read', () => {
|
||||
const args = stopArgs(place, 64, PLAN);
|
||||
expect(args).toEqual({
|
||||
via: 'insert_tour_stop',
|
||||
placeId: 64,
|
||||
expected_revision: 3,
|
||||
stop: { lat: 47.507, lng: 11.1, name: 'Spring' },
|
||||
after_key: 'alm111',
|
||||
tourName: 'Herzogstand',
|
||||
});
|
||||
expect(writeToolOf(ADD_FOUND_PLACE_TOOL, args)).toBe('insert_tour_stop');
|
||||
expect(foundPlaceArgs(args)).toEqual({
|
||||
placeId: 64,
|
||||
expected_revision: 3,
|
||||
stop: { lat: 47.507, lng: 11.1, name: 'Spring' },
|
||||
after_key: 'alm111',
|
||||
});
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-085: refuses a tour of another trip, one not read and a type that takes no stop', () => {
|
||||
expect(() => stopArgs(place, 65, PLAN)).toThrow(DomainError);
|
||||
expect(() => stopArgs(place, 64, null)).toThrow(/Tour not found/);
|
||||
expect(() => stopArgs(place, 64, { ...PLAN, tour: { ...PLAN.tour, tour_type: 'bike' } })).toThrow(
|
||||
/hike or a city walk/,
|
||||
);
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-086: the card of a held "+ Tour" reads as the stop it adds', () => {
|
||||
const args = stopArgs(place, 64, PLAN);
|
||||
const preview = describeToolCall(ADD_FOUND_PLACE_TOOL, 'tc-3', args, ctx, PLAN);
|
||||
expect(preview).toMatchObject({ verbKey: 'addTourStop', subject: 'Herzogstand' });
|
||||
expect(preview.rows[1]?.after).toBe('Alm → Summit');
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-087: the point a place goes after skips a point the tour gave no key yet', () => {
|
||||
const unkeyed = { ...PLAN, waypoints: PLAN.waypoints.map((point) => ({ ...point, key: undefined })) };
|
||||
expect(defaultAfterKeyOf(PLAN, STOP)).toBe('alm111');
|
||||
expect(defaultAfterKeyOf(unkeyed, STOP)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* P7: a route file attached in the assistant's chat, read into one GPX text
|
||||
* per track (TourFileReadService over the Tours import's own reader, with the
|
||||
* real place import over a snapshot test db), and the cut itself
|
||||
* (tour-file-split.helpers): a GPX file keeps every point as it came, a KML
|
||||
* line is written as GPX.
|
||||
*/
|
||||
import { PlaceImportService } from '../../../src/nest/place-import/place-import.service';
|
||||
import { TourFileReadService } from '../../../src/nest/tours/tour-file-read.service';
|
||||
import { gpxOfLine, splitGpxTracks } from '../../../src/nest/tours/tour-file-split.helpers';
|
||||
import { TourFilesModule } from '../../../src/nest/tours/tour-files.module';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makeTrip } from '../../helpers/factories/trips';
|
||||
import { makeUser } from '../../helpers/factories/users';
|
||||
import { createTestModule, type TestModule } from '../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { TOUR_GPX_TEXT_MAX } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
// TOUR-FILE-READ-001 to TOUR-FILE-READ-008
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let files: TourFileReadService;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [TourFilesModule] });
|
||||
files = t.get(TourFileReadService);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const TWO_TRACKS = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
|
||||
<metadata><name>Weekend</name></metadata>
|
||||
<wpt lat="47.0" lon="11.0"><name>Loose pin</name></wpt>
|
||||
<trk><name>Saturday</name><trkseg>
|
||||
<trkpt lat="47.5" lon="11.1"><ele>800</ele><time>2026-10-17T08:00:00Z</time></trkpt>
|
||||
<trkpt lat="47.51" lon="11.1"><ele>1000</ele><time>2026-10-17T09:00:00Z</time></trkpt>
|
||||
</trkseg></trk>
|
||||
<rte><name>Sunday</name>
|
||||
<rtept lat="47.6" lon="11.2"></rtept>
|
||||
<rtept lat="47.61" lon="11.2"></rtept>
|
||||
</rte>
|
||||
</gpx>`;
|
||||
|
||||
const KML = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<kml xmlns="http://www.opengis.net/kml/2.2"><Document>
|
||||
<Placemark><name>Ridge & lake</name><LineString><coordinates>11.1,47.5,800 11.1,47.51,1000</coordinates></LineString></Placemark>
|
||||
<Placemark><name>Pin</name><Point><coordinates>11.0,47.0</coordinates></Point></Placemark>
|
||||
</Document></kml>`;
|
||||
|
||||
describe('cutting a GPX file into its tracks', () => {
|
||||
it('TOUR-FILE-READ-001: one text per track and route, each with the head and without the loose points', () => {
|
||||
const pieces = splitGpxTracks(TWO_TRACKS);
|
||||
expect(pieces).toHaveLength(2);
|
||||
expect(pieces[0]).toContain('<metadata><name>Weekend</name></metadata>');
|
||||
expect(pieces[0]).toContain('<time>2026-10-17T08:00:00Z</time>');
|
||||
expect(pieces[0]).not.toContain('Sunday');
|
||||
expect(pieces[0]).not.toContain('Loose pin');
|
||||
expect(pieces[1]).toContain('<rte><name>Sunday</name>');
|
||||
expect(pieces.every((piece) => piece.trimEnd().endsWith('</gpx>'))).toBe(true);
|
||||
});
|
||||
|
||||
it('TOUR-FILE-READ-002: a <trkseg> is no track of its own, and a file without any gives nothing', () => {
|
||||
expect(splitGpxTracks('<gpx><trkseg></trkseg></gpx>')).toEqual([]);
|
||||
expect(splitGpxTracks('<gpx><trk><name>Open</name>')).toEqual([]);
|
||||
});
|
||||
|
||||
it('TOUR-FILE-READ-003: a KML line is written as one GPX track, its name escaped', () => {
|
||||
const gpx = gpxOfLine('Ridge & lake', 'Up <and> down', [
|
||||
[47.5, 11.1, 800],
|
||||
[47.51, 11.1],
|
||||
]);
|
||||
expect(gpx).toContain('<name>Ridge & lake</name>');
|
||||
expect(gpx).toContain('<desc>Up <and> down</desc>');
|
||||
expect(gpx).toContain('<trkpt lat="47.5" lon="11.1"><ele>800</ele></trkpt>');
|
||||
expect(gpx).toContain('<trkpt lat="47.51" lon="11.1"></trkpt>');
|
||||
const rows = t.get(PlaceImportService).readGpx(Buffer.from(gpx, 'utf8'), { importTracks: true });
|
||||
expect(rows).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TourFileReadService', () => {
|
||||
async function tripId() {
|
||||
const { user } = await makeUser(t.get(MikroORM));
|
||||
return (await makeTrip(t.get(MikroORM), user.id)).id;
|
||||
}
|
||||
|
||||
it('TOUR-FILE-READ-004: a GPX file comes back track by track, each one reading back as itself', async () => {
|
||||
const read = await files.read(await tripId(), Buffer.from(TWO_TRACKS, 'utf8'), 'weekend.gpx');
|
||||
expect(read.whole).toBe(false);
|
||||
expect(read.tracks.map((track) => [track.name, track.point_count, track.duplicate])).toEqual([
|
||||
['Saturday', 2, false],
|
||||
['Sunday', 2, false],
|
||||
]);
|
||||
expect(read.tracks[0]?.has_heights).toBe(true);
|
||||
expect(read.tracks[0]?.distance_km).toBeGreaterThan(1);
|
||||
expect(read.tracks[0]?.gpx).toContain('2026-10-17T08:00:00Z');
|
||||
});
|
||||
|
||||
it('TOUR-FILE-READ-005: a KML file gives its lines as GPX and counts the pins it leaves out', async () => {
|
||||
const read = await files.read(await tripId(), Buffer.from(KML, 'utf8'), 'ridge.kml');
|
||||
expect(read.tracks).toHaveLength(1);
|
||||
expect(read.tracks[0]?.name).toBe('Ridge & lake');
|
||||
expect(read.tracks[0]?.gpx).toContain('<trkseg>');
|
||||
expect(read.left_out).toBeDefined();
|
||||
});
|
||||
|
||||
it('TOUR-FILE-READ-006: a GPX file whose tracks cannot be cut comes back whole, as one import', async () => {
|
||||
const prefixed = TWO_TRACKS.replace(/<(\/?)(trk|rte)\b/g, '<$1gpx:$2').replace(
|
||||
'xmlns="http://www.topografix.com/GPX/1/1"',
|
||||
'xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpx="http://www.topografix.com/GPX/1/1"',
|
||||
);
|
||||
const read = await files.read(await tripId(), Buffer.from(prefixed, 'utf8'), 'weekend.gpx');
|
||||
if (read.tracks.length === 0) return; // a reader that takes no prefixed tags finds nothing to cut
|
||||
expect(read.whole).toBe(true);
|
||||
expect(read.tracks).toHaveLength(1);
|
||||
expect(read.tracks[0]?.name).toBe('weekend.gpx');
|
||||
});
|
||||
|
||||
it('TOUR-FILE-READ-007: a file without a line gives no track', async () => {
|
||||
const empty = '<gpx version="1.1"><wpt lat="47" lon="11"><name>Pin</name></wpt></gpx>';
|
||||
expect(await files.read(await tripId(), Buffer.from(empty, 'utf8'), 'pins.gpx')).toEqual({
|
||||
tracks: [],
|
||||
whole: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('TOUR-FILE-READ-008: a track longer than one import takes is named but carries no text', async () => {
|
||||
const points = Array.from(
|
||||
{ length: 20_000 },
|
||||
(_, i) =>
|
||||
`<trkpt lat="${47 + i / 100_000}" lon="11.1"><ele>800.123456</ele><time>2026-10-17T08:00:00Z</time></trkpt>`,
|
||||
).join('');
|
||||
const big = `<gpx version="1.1"><trk><name>Long</name><trkseg>${points}</trkseg></trk></gpx>`;
|
||||
expect(big.length).toBeGreaterThan(TOUR_GPX_TEXT_MAX);
|
||||
const read = await files.read(await tripId(), Buffer.from(big, 'utf8'), 'long.gpx');
|
||||
expect(read.tracks[0]).toMatchObject({ name: 'Long', gpx: null });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* P6: the pure half of a stop taken into a saved tour or out of it: where it
|
||||
* goes, what update_tour is handed for a hike, which stops may be taken out,
|
||||
* and the key the save gave the new stop.
|
||||
*/
|
||||
import {
|
||||
afterPointOf,
|
||||
hikePointsWithStop,
|
||||
hikePointsWithout,
|
||||
keyBefore,
|
||||
keyNear,
|
||||
removalRefusal,
|
||||
stopPointsOf,
|
||||
} from '../../../src/nest/tours/tour-stops.helpers';
|
||||
import type { GeometryPoint, TourWaypoint } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// TOUR-STOPS-HELPERS-001 to TOUR-STOPS-HELPERS-008
|
||||
|
||||
const wp = (key: string, lat: number, role: TourWaypoint['role'], over: Partial<TourWaypoint> = {}): TourWaypoint => ({
|
||||
key,
|
||||
lat,
|
||||
lng: 11.0,
|
||||
role,
|
||||
sequence: 0,
|
||||
...over,
|
||||
});
|
||||
|
||||
const START = wp('start1', 47.0, 'start', { name: 'Parking' });
|
||||
const HUT = wp('hut111', 47.01, 'via', { name: 'Hut', poi_category: 'shelter', stage_end: true });
|
||||
const END = wp('summit', 47.02, 'end', { name: 'Summit' });
|
||||
const LINE: GeometryPoint[] = [
|
||||
[47.0, 11.0],
|
||||
[47.01, 11.0],
|
||||
[47.02, 11.0],
|
||||
];
|
||||
|
||||
describe('where a stop goes', () => {
|
||||
it('TOUR-STOPS-HELPERS-001: after the last point before it along the line, or after the point named', () => {
|
||||
const points = stopPointsOf([START, HUT, END]);
|
||||
const between = afterPointOf(points, LINE, { lat: 47.015, lng: 11.0 }, undefined);
|
||||
expect(typeof between === 'string' ? between : between.id).toBe('hut111');
|
||||
const named = afterPointOf(points, LINE, { lat: 47.015, lng: 11.0 }, 'start1');
|
||||
expect(typeof named === 'string' ? named : named.id).toBe('start1');
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-HELPERS-002: refuses a key the tour does not have, a shaping point and a leg drawn by hand', () => {
|
||||
const free = {
|
||||
...HUT,
|
||||
fixed_leg: {
|
||||
kind: 'free' as const,
|
||||
geometry: [[47.01, 11.0] as [number, number], [47.02, 11.0] as [number, number]],
|
||||
},
|
||||
};
|
||||
const shaping = wp('shape1', 47.005, 'via', { shaping: true });
|
||||
expect(afterPointOf(stopPointsOf([START, HUT, END]), LINE, START, 'nope00')).toMatch(
|
||||
/no point with the key nope00/,
|
||||
);
|
||||
expect(afterPointOf(stopPointsOf([START, shaping, END]), LINE, START, 'shape1')).toMatch(/only shapes the line/);
|
||||
expect(afterPointOf(stopPointsOf([START, free, END]), LINE, START, 'hut111')).toMatch(/drawn by hand/);
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-HELPERS-003: a loop takes nothing after its way back', () => {
|
||||
const back = wp('back11', 47.0, 'end');
|
||||
expect(afterPointOf(stopPointsOf([START, HUT, back]), LINE, HUT, 'back11')).toMatch(/way back of a loop/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a hike handed to update_tour', () => {
|
||||
it('TOUR-STOPS-HELPERS-004: keeps names, kinds and stage ends, the stop in its place', () => {
|
||||
const points = stopPointsOf([START, HUT, END]);
|
||||
const next = hikePointsWithStop(points, 'hut111', {
|
||||
lat: 47.015,
|
||||
lng: 11.0,
|
||||
name: 'Spring',
|
||||
poi_category: 'drinking_water',
|
||||
});
|
||||
expect(next).toEqual([
|
||||
{ lat: 47.0, lng: 11.0, name: 'Parking' },
|
||||
{ lat: 47.01, lng: 11.0, name: 'Hut', poi_category: 'shelter', stage_end: true },
|
||||
{ lat: 47.015, lng: 11.0, name: 'Spring', poi_category: 'drinking_water' },
|
||||
{ lat: 47.02, lng: 11.0, name: 'Summit' },
|
||||
]);
|
||||
expect(hikePointsWithStop(points, 'nope00', { lat: 47.015, lng: 11.0 })).toBeNull();
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-HELPERS-005: takes the stop out and leaves the rest as it was', () => {
|
||||
expect(hikePointsWithout(stopPointsOf([START, HUT, END]), 'hut111')).toEqual([
|
||||
{ lat: 47.0, lng: 11.0, name: 'Parking' },
|
||||
{ lat: 47.02, lng: 11.0, name: 'Summit' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('which stop may be taken out', () => {
|
||||
it('TOUR-STOPS-HELPERS-006: never the start, the way back of a loop, or a point of a tour of two', () => {
|
||||
const back = wp('back11', 47.0, 'end');
|
||||
expect(removalRefusal(stopPointsOf([START, HUT, END]), 'hut111')).toBeNull();
|
||||
expect(removalRefusal(stopPointsOf([START, HUT, END]), 'summit')).toBeNull();
|
||||
expect(removalRefusal(stopPointsOf([START, HUT, END]), 'start1')).toMatch(/start/);
|
||||
expect(removalRefusal(stopPointsOf([START, END]), 'summit')).toMatch(/at least its start and its end/);
|
||||
expect(removalRefusal(stopPointsOf([START, HUT, back]), 'back11')).toMatch(/way back of a loop/);
|
||||
expect(removalRefusal(stopPointsOf([START, HUT, END]), 'nope00')).toMatch(/no point with the key/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the keys around a stop', () => {
|
||||
it('TOUR-STOPS-HELPERS-007: the key the save gave the stop is the nearest keyed point within a few metres', () => {
|
||||
expect(keyNear([START, HUT, END], { lat: 47.01, lng: 11.0001 })).toBe('hut111');
|
||||
expect(keyNear([START, HUT, END], { lat: 47.03, lng: 11.0 })).toBeNull();
|
||||
expect(keyNear([{ ...HUT, key: undefined }], { lat: 47.01, lng: 11.0 })).toBeNull();
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-HELPERS-008: the point a stop followed, by its key; none before the start', () => {
|
||||
const points = stopPointsOf([START, HUT, END]);
|
||||
expect(keyBefore(points, 'hut111')).toBe('start1');
|
||||
expect(keyBefore(points, 'start1')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* P6: TourStopsMcp over a snapshot test db: a found place taken into a saved
|
||||
* hike as a stop with insert_tour_stop and taken out again with
|
||||
* remove_tour_stop, through the write update_tour saves with. The hike is
|
||||
* created through create_hike; its way is planned by a stub of
|
||||
* HikeRoutingService, as in the hike suite. The gates are the tours': trip
|
||||
* access, then place_edit, on the Tours addon.
|
||||
*/
|
||||
import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
|
||||
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { HikePlanMcp } from '../../../src/nest/tours/hike-plan.mcp';
|
||||
import { HikeRoutingService, type PlannedHike } from '../../../src/nest/tours/hike-routing.service';
|
||||
import { TourPoiSearchService } from '../../../src/nest/tours/tour-poi-search.service';
|
||||
import { TourStopsMcp } from '../../../src/nest/tours/tour-stops.mcp';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { WeatherService } from '../../../src/nest/weather/weather.service';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { countRows, findRow } from '../../helpers/factories/rows';
|
||||
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';
|
||||
|
||||
// TOUR-STOPS-MCP-001 to TOUR-STOPS-MCP-005
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const plan = vi.fn<HikeRoutingService['plan']>();
|
||||
let t: TestModule;
|
||||
let stops: TourStopsMcp;
|
||||
let hikes: HikePlanMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
const LINE: GeometryPoint[] = [
|
||||
[47.5, 11.1, 800],
|
||||
[47.505, 11.1, 900],
|
||||
[47.51, 11.1, 1000],
|
||||
];
|
||||
|
||||
/** The stub's plan: the way above under the limit asked for, whatever the points. */
|
||||
function routed(request: HikePlanRequest): PlannedHike {
|
||||
return {
|
||||
plan: {
|
||||
kind: 'routed',
|
||||
max_hiking_difficulty: request.max_hiking_difficulty ?? 2,
|
||||
hiking_preferences: request.hiking_preferences ?? null,
|
||||
distance_m: 1112,
|
||||
ascent_m: 200,
|
||||
descent_m: 0,
|
||||
duration_minutes: 52,
|
||||
duration_basis: 'din33466',
|
||||
has_heights: true,
|
||||
line: LINE,
|
||||
profile: [
|
||||
[0, 800],
|
||||
[1112, 1000],
|
||||
],
|
||||
grades: null,
|
||||
},
|
||||
line: LINE,
|
||||
snapped: request.waypoints.map(() => 5),
|
||||
legs: request.waypoints.slice(1).map(() => 300),
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [ToursModule],
|
||||
overrides: [
|
||||
{ provide: HikeRoutingService, useValue: { plan } },
|
||||
{ provide: TourPoiSearchService, useValue: { search: vi.fn() } },
|
||||
{ provide: WeatherService, useValue: { getDetailed: vi.fn() } },
|
||||
],
|
||||
});
|
||||
stops = t.get(TourStopsMcp);
|
||||
hikes = 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 WAYPOINTS = [
|
||||
{ lat: 47.5, lng: 11.1, name: 'Car park' },
|
||||
{ lat: 47.505, lng: 11.1, name: 'Alm' },
|
||||
{ lat: 47.51, lng: 11.1, name: 'Summit' },
|
||||
];
|
||||
const SPRING = { lat: 47.507, lng: 11.1, name: 'Spring', poi_category: 'drinking_water' as const };
|
||||
|
||||
async function fixture() {
|
||||
const { user } = await makeUser(orm());
|
||||
const { user: outsider } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
const hike = read(
|
||||
await hikes.createHike({ tripId: trip.id, name: 'Herzogstand', waypoints: WAYPOINTS }, ctx(user.id)),
|
||||
);
|
||||
return { user, outsider, trip, placeId: hike.tour.place_id as number };
|
||||
}
|
||||
|
||||
describe('TourStopsMcp', () => {
|
||||
it('TOUR-STOPS-MCP-001: both tools write on the Tours addon, in the trips group', async () => {
|
||||
const options = (method: string) => {
|
||||
const entry = getEntry(TourStopsMcp as unknown as ClassRef, method);
|
||||
if (!entry || entry.kind !== 'tool') throw new Error(`${method} is no MCP tool`);
|
||||
return entry.options;
|
||||
};
|
||||
const tools = ['insertTourStop', 'removeTourStop'].map(options);
|
||||
expect(tools.map((tool) => [tool.name, tool.annotations?.readOnlyHint, tool.access])).toEqual([
|
||||
['insert_tour_stop', false, { group: 'trips', mode: 'write' }],
|
||||
['remove_tour_stop', false, { group: 'trips', mode: 'write' }],
|
||||
]);
|
||||
expect(tools[0].description).toContain('after_key');
|
||||
const isAddonEnabled = vi.fn(async (id: string) => id === 'tours');
|
||||
const gated = await Promise.all(tools.map((tool) => tool.when?.(ctx(1), { addons: { isAddonEnabled } })));
|
||||
expect(gated).toEqual([true, true]);
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-MCP-002: takes a place in after the last point before it, plans the hike anew and raises its revision', async () => {
|
||||
const f = await fixture();
|
||||
plan.mockClear();
|
||||
const answer = read(
|
||||
await stops.insertTourStop(
|
||||
{ tripId: f.trip.id, placeId: f.placeId, expected_revision: 1, stop: SPRING },
|
||||
ctx(f.user.id),
|
||||
),
|
||||
);
|
||||
expect(plan).toHaveBeenCalledTimes(1);
|
||||
expect(plan.mock.calls[0]?.[2].waypoints.map((point) => point.lat)).toEqual([47.5, 47.505, 47.507, 47.51]);
|
||||
expect(answer.tour).toMatchObject({ place_id: f.placeId, tour_type: 'hike', revision: 2 });
|
||||
expect(answer.stop).toMatchObject({ name: 'Spring', after_name: 'Alm' });
|
||||
expect(typeof answer.stop.key).toBe('string');
|
||||
expect(await countRows(orm(), TourWaypoints, { place: f.placeId })).toBe(4);
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-MCP-003: takes the stop out again by its key, back to the points it had', async () => {
|
||||
const f = await fixture();
|
||||
const own = ctx(f.user.id);
|
||||
const inserted = read(
|
||||
await stops.insertTourStop({ tripId: f.trip.id, placeId: f.placeId, expected_revision: 1, stop: SPRING }, own),
|
||||
);
|
||||
const removed = read(
|
||||
await stops.removeTourStop(
|
||||
{ tripId: f.trip.id, placeId: f.placeId, expected_revision: 2, key: inserted.stop.key },
|
||||
own,
|
||||
),
|
||||
);
|
||||
expect(removed.tour.revision).toBe(3);
|
||||
expect(removed.removed).toMatchObject({ key: inserted.stop.key, name: 'Spring', lat: 47.507 });
|
||||
expect(await countRows(orm(), TourWaypoints, { place: f.placeId })).toBe(3);
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-MCP-004: a stale revision is refused and the hike stays as it was', async () => {
|
||||
const f = await fixture();
|
||||
await expect(
|
||||
stops.insertTourStop(
|
||||
{ tripId: f.trip.id, placeId: f.placeId, expected_revision: 4, stop: SPRING },
|
||||
ctx(f.user.id),
|
||||
),
|
||||
).rejects.toThrow('This tour was changed in the meantime');
|
||||
expect((await findRow(orm(), Tours, { place: f.placeId }))?.revision).toBe(1);
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-MCP-005: an outsider is refused, and a member without place_edit, as REST refuses them', async () => {
|
||||
const f = await fixture();
|
||||
const request = { tripId: f.trip.id, placeId: f.placeId, expected_revision: 1, stop: SPRING };
|
||||
expect(read(await stops.insertTourStop(request, ctx(f.outsider.id)))).toEqual({
|
||||
error: 'Trip not found or access denied.',
|
||||
});
|
||||
const denied = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValue(false);
|
||||
expect((await stops.insertTourStop(request, ctx(f.user.id))).isError).toBe(true);
|
||||
const removal = { tripId: f.trip.id, placeId: f.placeId, expected_revision: 1, key: 'abcdef' };
|
||||
expect((await stops.removeTourStop(removal, ctx(f.user.id))).isError).toBe(true);
|
||||
expect(denied).toHaveBeenCalledWith('place_edit', f.trip.id, f.user.id);
|
||||
denied.mockRestore();
|
||||
expect(await countRows(orm(), TourWaypoints, { place: f.placeId })).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* P6: TourStopsService takes a stop into a saved hike or city walk, and out
|
||||
* again, through the paths update_tour and save_tour_change save with. Those
|
||||
* are stubs here (their own suites run them against a db): this suite pins
|
||||
* what they are handed, the refusals before them and the answer.
|
||||
*/
|
||||
import { DomainError } from '../../../src/nest/common/domain-error';
|
||||
import { HikePlanService } from '../../../src/nest/tours/hike-plan.service';
|
||||
import { proposalIdOf } from '../../../src/nest/tours/tour-change-proposal';
|
||||
import { TourChangeSaveService } from '../../../src/nest/tours/tour-change-save.service';
|
||||
import { TourStopsService } from '../../../src/nest/tours/tour-stops.service';
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { TourDetailResponse, TourWaypoint } from '@trek/shared';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// TOUR-STOPS-SVC-001 to TOUR-STOPS-SVC-009
|
||||
|
||||
const wp = (key: string, lat: number, role: TourWaypoint['role'], name: string): TourWaypoint => ({
|
||||
key,
|
||||
lat,
|
||||
lng: 11.0,
|
||||
role,
|
||||
sequence: 0,
|
||||
name,
|
||||
});
|
||||
const START = wp('start1', 47.0, 'start', 'Parking');
|
||||
const HUT = wp('hut111', 47.01, 'via', 'Hut');
|
||||
const END = wp('summit', 47.02, 'end', 'Summit');
|
||||
const SPRING = wp('spring', 47.015, 'via', 'Spring');
|
||||
|
||||
function detail(tourType: string, waypoints: TourWaypoint[], revision = 3, extra: Record<string, unknown> = {}) {
|
||||
return {
|
||||
tour: {
|
||||
place_id: 64,
|
||||
name: 'Herzogstand',
|
||||
tour_type: tourType,
|
||||
revision,
|
||||
distance: 8.2,
|
||||
duration: 190,
|
||||
has_waypoints: true,
|
||||
...extra,
|
||||
},
|
||||
waypoints,
|
||||
} as unknown as TourDetailResponse;
|
||||
}
|
||||
|
||||
const getTour = vi.fn<(tripId: string, placeId: string) => Promise<TourDetailResponse>>();
|
||||
const savedLine = vi.fn(async () => [
|
||||
[47.0, 11.0],
|
||||
[47.01, 11.0],
|
||||
[47.02, 11.0],
|
||||
]);
|
||||
const update = vi.fn();
|
||||
const save = vi.fn();
|
||||
let service: TourStopsService;
|
||||
|
||||
beforeEach(async () => {
|
||||
getTour.mockReset();
|
||||
update.mockReset().mockResolvedValue({ ...detail('hike', [START, HUT, SPRING, END], 4), route: { planned: true } });
|
||||
save.mockReset().mockResolvedValue({ saved: true });
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
TourStopsService,
|
||||
{ provide: ToursService, useValue: { getTour, savedLine } },
|
||||
{ provide: HikePlanService, useValue: { update } },
|
||||
{ provide: TourChangeSaveService, useValue: { save } },
|
||||
],
|
||||
}).compile();
|
||||
service = moduleRef.get(TourStopsService);
|
||||
});
|
||||
|
||||
const stop = { lat: 47.015, lng: 11.0, name: 'Spring', poi_category: 'drinking_water' as const };
|
||||
|
||||
describe('a stop taken into a hike', () => {
|
||||
it('TOUR-STOPS-SVC-001: goes after the last point before it, and the hike is planned through the new points', async () => {
|
||||
getTour.mockResolvedValue(detail('hike', [START, HUT, END]));
|
||||
const answer = await service.insert(7, 5, { placeId: 64, expected_revision: 3, stop });
|
||||
expect(update).toHaveBeenCalledWith(7, 5, {
|
||||
placeId: 64,
|
||||
expected_revision: 3,
|
||||
waypoints: [
|
||||
{ lat: 47.0, lng: 11.0, name: 'Parking' },
|
||||
{ lat: 47.01, lng: 11.0, name: 'Hut' },
|
||||
{ lat: 47.015, lng: 11.0, name: 'Spring', poi_category: 'drinking_water' },
|
||||
{ lat: 47.02, lng: 11.0, name: 'Summit' },
|
||||
],
|
||||
});
|
||||
expect(answer.tour).toMatchObject({ place_id: 64, tour_type: 'hike', revision: 4 });
|
||||
expect(answer.stop).toMatchObject({ key: 'spring', after_key: 'hut111', after_name: 'Hut' });
|
||||
expect(answer.before).toEqual({ distance_km: 8.2, minutes: 190 });
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-SVC-002: is refused against a revision the hike moved past, before anything is planned', async () => {
|
||||
getTour.mockResolvedValue(detail('hike', [START, HUT, END], 5));
|
||||
await expect(service.insert(7, 5, { placeId: 64, expected_revision: 3, stop })).rejects.toThrow(
|
||||
/changed in the meantime/,
|
||||
);
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-SVC-003: refuses another tour type and a recorded track without points of its own', async () => {
|
||||
getTour.mockResolvedValue(detail('bike', [START, END]));
|
||||
await expect(service.insert(7, 5, { placeId: 64, expected_revision: 3, stop })).rejects.toThrow(
|
||||
/hike or a city walk/,
|
||||
);
|
||||
getTour.mockResolvedValue(detail('hike', [START, END], 3, { has_waypoints: false }));
|
||||
await expect(service.insert(7, 5, { placeId: 64, expected_revision: 3, stop })).rejects.toThrow(/recorded track/);
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-SVC-004: names the reason when the point named takes no stop', async () => {
|
||||
getTour.mockResolvedValue(detail('hike', [START, HUT, END]));
|
||||
const refused = service.insert(7, 5, { placeId: 64, expected_revision: 3, stop, after_key: 'nope00' });
|
||||
await expect(refused).rejects.toBeInstanceOf(DomainError);
|
||||
await expect(refused).rejects.toThrow(/no point with the key/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a stop taken into a city walk', () => {
|
||||
it('TOUR-STOPS-SVC-005: is saved as one add after the station, with the proposal id a save checks', async () => {
|
||||
getTour
|
||||
.mockResolvedValueOnce(detail('walk', [START, HUT, END]))
|
||||
.mockResolvedValueOnce(detail('walk', [START, HUT, SPRING, END], 4));
|
||||
const answer = await service.insert(7, 5, {
|
||||
placeId: 64,
|
||||
expected_revision: 3,
|
||||
stop: { lat: 47.015, lng: 11.0, name: 'Spring', opening_hours: 'Mo-Su 09:00-18:00' },
|
||||
after_key: 'hut111',
|
||||
});
|
||||
const changes = [
|
||||
{
|
||||
op: 'add',
|
||||
after_key: 'hut111',
|
||||
station: { lat: 47.015, lng: 11.0, name: 'Spring', opening_hours: 'Mo-Su 09:00-18:00' },
|
||||
},
|
||||
];
|
||||
expect(save).toHaveBeenCalledWith(5, 64, 7, {
|
||||
changes,
|
||||
expected_revision: 3,
|
||||
proposal_id: proposalIdOf({ tripId: 5, placeId: 64, revision: 3, changes: changes as never }),
|
||||
confirmed: true,
|
||||
});
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
expect(answer.tour).toMatchObject({ tour_type: 'walk', revision: 4 });
|
||||
expect(answer.stop.key).toBe('spring');
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-SVC-006: refuses a walk whose stations have no keys yet', async () => {
|
||||
getTour.mockResolvedValue(detail('walk', [START, { ...HUT, key: undefined }, END]));
|
||||
const refused = service.insert(7, 5, { placeId: 64, expected_revision: 3, stop });
|
||||
await expect(refused).rejects.toThrow(/no keys yet/);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a stop taken out', () => {
|
||||
it('TOUR-STOPS-SVC-007: plans a hike through the points left and names what it took out', async () => {
|
||||
getTour.mockResolvedValue(detail('hike', [START, HUT, SPRING, END], 4));
|
||||
update.mockResolvedValue({ ...detail('hike', [START, HUT, END], 5), route: { planned: true } });
|
||||
const answer = await service.remove(7, 5, { placeId: 64, expected_revision: 4, key: 'spring' });
|
||||
expect(update.mock.calls[0]?.[2]).toMatchObject({ placeId: 64, expected_revision: 4 });
|
||||
expect(update.mock.calls[0]?.[2].waypoints).toHaveLength(3);
|
||||
expect(answer.removed).toEqual({
|
||||
key: 'spring',
|
||||
lat: 47.015,
|
||||
lng: 11.0,
|
||||
name: 'Spring',
|
||||
poi_category: null,
|
||||
after_key: 'hut111',
|
||||
});
|
||||
expect(answer.tour.revision).toBe(5);
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-SVC-008: removes a station of a city walk through the save of one change', async () => {
|
||||
getTour
|
||||
.mockResolvedValueOnce(detail('walk', [START, HUT, SPRING, END], 4))
|
||||
.mockResolvedValueOnce(detail('walk', [START, HUT, END], 5));
|
||||
await service.remove(7, 5, { placeId: 64, expected_revision: 4, key: 'spring' });
|
||||
expect(save.mock.calls[0]?.[3]).toMatchObject({ changes: [{ op: 'remove', key: 'spring' }], expected_revision: 4 });
|
||||
});
|
||||
|
||||
it('TOUR-STOPS-SVC-009: keeps the start of the tour', async () => {
|
||||
getTour.mockResolvedValue(detail('hike', [START, HUT, END]));
|
||||
await expect(service.remove(7, 5, { placeId: 64, expected_revision: 3, key: 'start1' })).rejects.toThrow(/start/);
|
||||
expect(update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user