Files
TREK/server/tests/e2e/place-history.e2e.test.ts
T
Maurice 382ba79584 feat(places): visits read from trips, change history, linked tours and bookings, personal tags
A visit is a place planned on a day of one of the reader's trips; nothing is kept
or confirmed by hand. A place keeps a log of changes to its details, links the
tours and bookings it is about, and carries tags private to the reader, which a
copy into a trip takes along only when picked. Contracts, routes, MCP tools and
migrations for both engines.
2026-11-29 21:16:50 +01:00

243 lines
11 KiB
TypeScript

/**
* PLC-14 end to end on the whole app (buildApp, the real guards, services,
* MCP registry and a migrated temp database): the history of a place's
* details is written by the routes and tools that change them, in their own
* transaction, and read over the origins of an entry of All places the
* reader reaches today. A change of a trip or list the reader cannot open
* leaves no trace, a cleared value takes its earlier changes along, a deleted
* place takes its history along, and the pages go on by their cursor.
*/
import { buildApp } from '../../src/bootstrap';
import { CollectionMembers } from '../../src/db/entities/CollectionMembers.entity';
import { PlaceChangeLog } from '../../src/db/entities/PlaceChangeLog.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
import { withRequestContext } from '../../src/nest/database/request-context';
import { addCollectionMember } from '../helpers/factories/collections';
import { countRows, deleteRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture';
import { resetRateLimits } from '../helpers/test-db';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import { Client } from '@modelcontextprotocol/sdk/client/index';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
import type { INestApplication } from '@nestjs/common';
import type { PlaceHistoryPageResponse } from '@trek/shared';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const LIBRARY = '/api/addons/collections/library/places';
let app: INestApplication;
let orm: MikroORM;
let f: LibraryFixture;
const http = () => request(app.getHttpServer());
async function history(userId: number, kind: 'trip' | 'list', id: number, query: Record<string, string> = {}) {
return http().get(`${LIBRARY}/${kind}/${id}/history`).query(query).set('Cookie', sessionCookie(userId));
}
async function changes(userId: number, kind: 'trip' | 'list', id: number): Promise<PlaceHistoryPageResponse> {
const res = await history(userId, kind, id);
expect(res.status).toBe(200);
return res.body as PlaceHistoryPageResponse;
}
const fieldsOf = (page: PlaceHistoryPageResponse) => page.entries.map((entry) => entry.field);
async function editTripPlace(userId: number, tripId: number, placeId: number, body: object) {
const res = await http()
.put(`/api/trips/${tripId}/places/${placeId}`)
.set('Cookie', sessionCookie(userId))
.send(body);
expect(res.status).toBe(200);
}
async function editSavedPlace(userId: number, savedId: number, body: object) {
const res = await http()
.patch(`/api/addons/collections/places/${savedId}`)
.set('Cookie', sessionCookie(userId))
.send(body);
expect(res.status).toBe(200);
}
/** One tool call through a real MCP session as `userId`: its JSON answer, or its error text. */
async function callTool(userId: number, name: string, args: Record<string, unknown>) {
const server = createLocalMcpServer('TREK place history e2e');
const around = (_info: unknown, call: () => unknown): unknown => withRequestContext(orm, call);
await withRequestContext(orm, () =>
app
.get(McpRegistryService)
.attach(server, { userId, scopes: null, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),
);
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'place-history-e2e', version: '1.0.0' });
await server.connect(serverTransport);
await client.connect(clientTransport);
try {
const result = await client.callTool({ name, arguments: args });
const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];
const text = content[0]?.text ?? '';
return result.isError === true
? { error: text, answer: null }
: { error: null, answer: JSON.parse(text) as unknown };
} finally {
await client.close();
await server.close();
}
}
beforeAll(async () => {
app = await buildApp();
orm = app.get(MikroORM);
await setAddonEnabled(orm, 'collections', true);
}, 60_000);
beforeEach(async () => {
await resetRateLimits(app);
f = await seedLibrary(orm);
});
afterAll(async () => {
await app?.close();
});
describe('the history of a place', () => {
it('PHIST-E2E-001: records each changed field of a trip place with who changed it, newest first', async () => {
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, {
name: 'Café Central Wien',
address: 'Herrengasse 14, 1010 Wien',
// Unchanged: no row for it.
description: 'A coffee house',
});
const page = await changes(f.me.id, 'trip', f.places.cafe.id);
expect(page.next_cursor).toBeNull();
expect(page.entries).toEqual([
expect.objectContaining({
field: 'address',
old_value: 'Herrengasse 14, Wien',
new_value: 'Herrengasse 14, 1010 Wien',
automatic: false,
editor: expect.objectContaining({ id: f.me.id }),
origin: { kind: 'trip', trip_id: f.alps.id, trip_title: 'Alps', place_id: f.places.cafe.id },
}),
expect.objectContaining({ field: 'name', old_value: 'Café Central', new_value: 'Café Central Wien' }),
]);
expect(page.entries[0]?.changed_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
});
it('PHIST-E2E-002: one entry reads the changes of all its origins, the list ones with their list', async () => {
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { phone: '+43 1 533' });
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'Try the strudel' });
const status = await http()
.post(`/api/addons/collections/places/${f.saved.savedCafe.id}/status`)
.set('Cookie', sessionCookie(f.me.id))
.send({ status: 'visited' });
expect(status.status).toBe(200);
const fromTrip = await changes(f.me.id, 'trip', f.places.cafe.id);
expect(fieldsOf(fromTrip)).toEqual(['status', 'notes', 'phone']);
expect(fromTrip.entries[0]).toEqual(
expect.objectContaining({
old_value: 'want',
new_value: 'visited',
origin: {
kind: 'list',
collection_id: f.lists.food.id,
collection_name: 'Food',
collection_place_id: f.saved.savedCafe.id,
},
}),
);
// Opened from the saved place, the same entry reads the same history.
expect(await changes(f.me.id, 'list', f.saved.savedCafe.id)).toEqual(fromTrip);
});
it('PHIST-E2E-003: shows only the changes of the origins the reader reaches, and none after access ends', async () => {
await addCollectionMember(orm, f.lists.food.id, f.friend.id, { role: 'viewer' });
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { notes: 'Window seat' });
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { description: 'Viennese coffee house' });
// The friend reaches the list but not the trip: the trip's change is not there, nor counted anywhere.
const friendPage = await changes(f.friend.id, 'list', f.saved.savedCafe.id);
expect(fieldsOf(friendPage)).toEqual(['description']);
expect(friendPage.next_cursor).toBeNull();
expect(JSON.stringify(friendPage)).not.toContain('Window seat');
expect((await history(f.friend.id, 'trip', f.places.cafe.id)).status).toBe(404);
// The stranger reaches neither; their own list's copy has a history of its own.
expect((await history(f.stranger.id, 'list', f.saved.savedCafe.id)).status).toBe(404);
await editSavedPlace(f.stranger.id, f.saved.secret.id, { notes: 'Secret note' });
expect(JSON.stringify(await changes(f.me.id, 'trip', f.places.cafe.id))).not.toContain('Secret note');
await deleteRows(orm, CollectionMembers, { collection: f.lists.food.id, user: f.friend.id });
expect((await history(f.friend.id, 'list', f.saved.savedCafe.id)).status).toBe(404);
});
it('PHIST-E2E-004: a cleared value takes the earlier changes of its field along, and is no change itself', async () => {
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'First' });
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'Second', address: 'Herrengasse 14' });
expect(fieldsOf(await changes(f.me.id, 'list', f.saved.savedCafe.id))).toEqual(['notes', 'address', 'notes']);
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: null });
const page = await changes(f.me.id, 'list', f.saved.savedCafe.id);
expect(fieldsOf(page)).toEqual(['address']);
expect(JSON.stringify(page)).not.toContain('First');
expect(JSON.stringify(page)).not.toContain('Try the cake');
// A trip place's text cleared to empty counts as cleared too.
await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { address: 'Museumstraße 15' });
await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { address: '' });
expect((await changes(f.me.id, 'trip', f.places.museum.id)).entries).toEqual([]);
});
it('PHIST-E2E-005: pages newest first by its cursor and refuses a cursor it never gave', async () => {
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://a.example' });
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://b.example' });
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://c.example' });
const first = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '2' });
expect(first.status).toBe(200);
const one = first.body as PlaceHistoryPageResponse;
expect(one.entries.map((entry) => entry.new_value)).toEqual(['https://c.example', 'https://b.example']);
expect(one.next_cursor).not.toBeNull();
const second = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '2', cursor: one.next_cursor ?? '' });
const two = second.body as PlaceHistoryPageResponse;
expect(two.entries.map((entry) => entry.new_value)).toEqual(['https://a.example']);
expect(two.next_cursor).toBeNull();
expect((await history(f.me.id, 'trip', f.places.cafe.id, { cursor: 'abc' })).status).toBe(400);
});
it('PHIST-E2E-006: a deleted place takes its history along', async () => {
await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { name: 'Landesmuseum' });
expect(await countRows(orm, PlaceChangeLog, { place: f.places.museum.id })).toBe(1);
await deleteRows(orm, Places, { id: f.places.museum.id });
expect(await countRows(orm, PlaceChangeLog, { place: f.places.museum.id })).toBe(0);
});
it('PHIST-E2E-007: the MCP tools write and read the same history with the same reach', async () => {
const updated = await callTool(f.me.id, 'update_place', {
tripId: f.alps.id,
placeId: f.places.cafe.id,
address: 'Herrengasse 14, 1010 Wien',
});
expect(updated.error).toBeNull();
const read = await callTool(f.me.id, 'get_library_place_history', { kind: 'trip', id: f.places.cafe.id });
expect(read.error).toBeNull();
const page = read.answer as PlaceHistoryPageResponse;
expect(page.entries).toEqual([
expect.objectContaining({ field: 'address', editor: expect.objectContaining({ id: f.me.id }) }),
]);
const refused = await callTool(f.friend.id, 'get_library_place_history', { kind: 'trip', id: f.places.cafe.id });
expect(refused.answer).toBeNull();
expect(refused.error).toMatch(/not found/i);
});
});