feat(places): read every place of the trips and lists in one view

A read-only overview of every place a user can reach: the saved places of
their lists and the places of their trips, viewer trips included, with tours,
tracks and the stops of a drive left out. A saved place and a trip place are
one entry only when the saved place came from that trip place, the trip is
still open to the user, and both agree (a provider id, or the same name at the
same spot); anything else stays apart. Every entry names where it comes from
and whether it may be changed there.

- GET /api/addons/collections/library/places: paged by cursor, search,
  category, kind, list, trip and status filters, counts per kind.
- GET /api/addons/collections/library/places/{trip|list}/🆔 one entry with
  what each origin keeps on its own (notes after the existing rights, labels,
  ratings, a trip's planned days, whether a stay or booking uses it).
- MCP tools list_all_places and get_library_place.

Nothing is written and nothing migrates; the rights are the existing list and
trip checks, read on every call.
This commit is contained in:
Maurice
2026-11-29 14:57:10 +01:00
parent 82165855c7
commit 0ecca2b46c
27 changed files with 2616 additions and 2 deletions
+137
View File
@@ -0,0 +1,137 @@
/**
* "All places" (PLC-07/PLC-08) through the real AddonGuard and JwtAuthGuard
* against a migrated and seeded temp SQLite db, every answer checked against
* its response contract. The collections' own routes are mounted beside it,
* so the list is shown to reach its handler and not the collections' `GET /:id`.
*/
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { PlacesLibraryModule } from '../../src/nest/places-library/places-library.module';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { setAddonEnabled } from '../helpers/factories/settings';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { expectedKeysByName, seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture';
import { resetTestDb } from '../helpers/test-db';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } 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 db = createSnapshotTestDb();
const BASE = '/api/addons/collections/library/places';
let app: INestApplication;
let server: Server;
let orm: TestOrm;
let f: LibraryFixture;
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
RealtimeModule,
PlacesLibraryModule,
],
})
.overrideProvider(RealtimeService)
.useValue(new FakeRealtimeService())
.compile();
app = moduleRef.createNestApplication();
app.use(cookieParser());
app.useGlobalPipes(new ZodValidationPipe());
app.useGlobalFilters(new TrekExceptionFilter());
await app.init();
server = app.getHttpServer() as Server;
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
f = await seedLibrary(orm);
await setAddonEnabled(orm, 'collections', true);
});
afterAll(async () => {
await app.close();
await orm.close();
db.close();
});
describe('Places library e2e (real guards + temp SQLite)', () => {
it('answers 404 while Collections is off, before any sign-in check, and 401 without a session', async () => {
await setAddonEnabled(orm, 'collections', false);
expect((await request(server).get(BASE)).status).toBe(404);
expect((await request(server).get(`${BASE}/trip/${f.places.cafe.id}`)).status).toBe(404);
await setAddonEnabled(orm, 'collections', true);
expect((await request(server).get(BASE)).status).toBe(401);
});
it('lists every entry the user reaches, page by page', async () => {
const res = await request(server).get(BASE).set(as(f.me.id));
expect(res.status).toBe(200);
expect(res.body.entries.map((entry: { key: string }) => entry.key)).toEqual(expectedKeysByName(f));
expect(res.body.counts).toEqual({ all: 10, trip: 5, list: 7 });
const first = await request(server).get(BASE).query({ limit: '4' }).set(as(f.me.id));
expect(first.body.entries).toHaveLength(4);
const next = await request(server)
.get(BASE)
.query({ limit: '50', cursor: first.body.next_cursor })
.set(as(f.me.id));
expect(next.body.entries).toHaveLength(6);
expect(next.body.next_cursor).toBeNull();
});
it('reads the filters from the query string and refuses what it does not take', async () => {
const trips = await request(server)
.get(BASE)
.query({ kind: 'trip', trip_id: String(f.rome.id) })
.set(as(f.me.id));
expect(trips.status).toBe(200);
expect(trips.body.entries.map((entry: { key: string }) => entry.key)).toEqual([`trip:${f.places.forum.id}`]);
for (const query of [{ category_id: '0x5' }, { kind: 'tour' }, { limit: '1000' }, { notes: 'x' }]) {
expect((await request(server).get(BASE).query(query).set(as(f.me.id))).status).toBe(400);
}
const both = await request(server)
.get(BASE)
.query({ kind: 'list', trip_id: String(f.alps.id) })
.set(as(f.me.id));
expect(both.status).toBe(400);
expect(both.body).toEqual({ error: 'Filter by a trip or by a list, not both' });
});
it('opens one entry from a trip place or a saved place, and nothing out of reach', async () => {
const trip = await request(server).get(`${BASE}/trip/${f.places.cafe.id}`).set(as(f.me.id));
expect(trip.status).toBe(200);
expect(trip.body.entry.key).toBe(`trip:${f.places.cafe.id}`);
expect(trip.body.details.map((detail: { kind: string }) => detail.kind)).toEqual(['trip', 'list']);
const saved = await request(server).get(`${BASE}/list/${f.saved.pantheon.id}`).set(as(f.me.id));
expect(saved.status).toBe(200);
expect(saved.body.entry.origins[0]).toMatchObject({ kind: 'list', can_edit: false });
for (const path of [`trip/${f.places.hidden.id}`, `list/${f.saved.secret.id}`, 'trip/abc', 'list/0x5']) {
const res = await request(server).get(`${BASE}/${path}`).set(as(f.me.id));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Place not found' });
}
});
});
@@ -0,0 +1,171 @@
/**
* The lists and trips the "All places" suites read, seeded through the ORM
* factories. The user `me` owns the trip Alps and the list Food, is a member
* of `friend`'s trip Rome and a viewer of `friend`'s list Rome sights;
* `stranger` owns a trip and a list `me` cannot open.
*
* Alps holds the normal places Café Central, Museum, Hotel Sonne (lodging) and
* Camp Lake (a road trip campsite a stay points at), and the places "All
* places" leaves out: a tour, an imported track and a fuel stop. Food holds a
* copy of each kind the grouping rule tells apart.
*/
import { CollectionLabels } from '../../src/db/entities/CollectionLabels.entity';
import { CollectionPlaceRatings } from '../../src/db/entities/CollectionPlaceRatings.entity';
import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity';
import {
addCollectionMember,
labelCollectionPlace,
makeCollection,
makeCollectionPlace,
} from './factories/collections';
import type { FactoryOrm } from './factories/context';
import { makeDayAccommodation, makeDayAssignment } from './factories/itinerary';
import { makePlace } from './factories/places';
import { makeReservation } from './factories/reservations';
import { createRow, insertRows } from './factories/rows';
import { makeTour } from './factories/tours';
import { addTripMember, makeTrip, readTripDays } from './factories/trips';
import { makeUser } from './factories/users';
export async function seedLibrary(orm: FactoryOrm) {
const { user: me } = await makeUser(orm);
const { user: friend } = await makeUser(orm);
const { user: stranger } = await makeUser(orm);
const alps = await makeTrip(orm, me.id, { title: 'Alps', start_date: '2026-07-01', end_date: '2026-07-03' });
const rome = await makeTrip(orm, friend.id, { title: 'Rome' });
await addTripMember(orm, rome.id, me.id);
const elsewhere = await makeTrip(orm, stranger.id, { title: 'Elsewhere' });
const cafe = await makePlace(orm, alps.id, {
name: 'Café Central',
address: 'Herrengasse 14, Wien',
lat: 48.2104,
lng: 16.3655,
google_place_id: 'g-cafe',
notes: 'Book a table',
description: 'A coffee house',
});
const museum = await makePlace(orm, alps.id, {
name: 'Museum',
lat: 47.2681,
lng: 11.3933,
google_place_id: 'g-museum',
});
const hotel = await makePlace(orm, alps.id, { name: 'Hotel Sonne', stop_type: 'hotel' });
const camp = await makePlace(orm, alps.id, { name: 'Camp Lake', stop_type: 'campsite' });
const ridge = await makePlace(orm, alps.id, { name: 'Ridge walk' });
await makeTour(orm, ridge.id);
const track = await makePlace(orm, alps.id, { name: 'Imported track', route_geometry: '[[47,11],[47.1,11.1]]' });
const pump = await makePlace(orm, alps.id, { name: 'Fuel pump', stop_type: 'fuel' });
const days = await readTripDays(orm, alps.id);
const [day1, day2] = days;
if (!day1 || !day2) throw new Error('seedLibrary: Alps has no days');
await makeDayAccommodation(orm, alps.id, camp.id, day1.id, day2.id);
await makeDayAssignment(orm, day1.id, cafe.id, { assignment_time: '09:00' });
await makeReservation(orm, alps.id, { place: hotel.id, title: 'Hotel Sonne', type: 'hotel' });
await insertRows(orm, PlaceRatings, [
{ place: cafe.id, user: me.id, rating: 4 },
{ place: cafe.id, user: friend.id, rating: 2 },
]);
const forum = await makePlace(orm, rome.id, { name: 'Forum Romanum', lat: 41.8925, lng: 12.4853 });
const hidden = await makePlace(orm, elsewhere.id, { name: 'Hidden', lat: 1, lng: 1 });
const food = await makeCollection(orm, me.id, { name: 'Food' });
// The same place: it came from Café Central, same name once trimmed and lowered, a few metres off.
const savedCafe = await makeCollectionPlace(orm, food.id, me.id, {
name: ' café central ',
lat: 48.21042,
lng: 16.36551,
source_trip_id: alps.id,
source_place_id: cafe.id,
status: 'want',
notes: 'Try the cake',
});
// The same place by its provider id, whatever it is called and with no position.
const savedMuseum = await makeCollectionPlace(orm, food.id, me.id, {
name: 'Tiroler Landesmuseum',
lat: null,
lng: null,
google_place_id: 'g-museum',
source_trip_id: alps.id,
source_place_id: museum.id,
});
// Came from Café Central but renamed: a name of its own keeps it apart.
const lunch = await makeCollectionPlace(orm, food.id, me.id, {
name: 'Lunch spot',
lat: 48.2104,
lng: 16.3655,
source_trip_id: alps.id,
source_place_id: cafe.id,
});
// Same name and spot as Café Central, but another provider id: a different place.
const conflicting = await makeCollectionPlace(orm, food.id, me.id, {
name: 'Café Central',
lat: 48.2104,
lng: 16.3655,
google_place_id: 'g-other',
source_trip_id: alps.id,
source_place_id: cafe.id,
});
// Same name and spot as Museum, but no source: a name never groups on its own.
const namesake = await makeCollectionPlace(orm, food.id, me.id, { name: 'Museum', lat: 47.2681, lng: 11.3933 });
// Points at a place of a trip `me` cannot open.
const hiddenCopy = await makeCollectionPlace(orm, food.id, me.id, {
name: 'Hidden copy',
lat: 1,
lng: 1,
source_trip_id: elsewhere.id,
source_place_id: hidden.id,
});
const label = await createRow(orm, CollectionLabels, { collection: food.id, name: 'Must', color: '#ff0000' });
await labelCollectionPlace(orm, savedCafe.id, label.id);
await insertRows(orm, CollectionPlaceRatings, [{ collectionPlace: savedCafe.id, user: me.id, rating: 5 }]);
const sights = await makeCollection(orm, friend.id, { name: 'Rome sights' });
await addCollectionMember(orm, sights.id, me.id, { role: 'viewer' });
const pantheon = await makeCollectionPlace(orm, sights.id, friend.id, { name: 'Pantheon', status: 'visited' });
const secrets = await makeCollection(orm, stranger.id, { name: 'Secrets' });
const secret = await makeCollectionPlace(orm, secrets.id, stranger.id, {
name: 'Café Central',
lat: 48.2104,
lng: 16.3655,
source_trip_id: alps.id,
source_place_id: cafe.id,
});
return {
me,
friend,
stranger,
alps,
rome,
elsewhere,
day1,
places: { cafe, museum, hotel, camp, ridge, track, pump, forum, hidden },
lists: { food, sights, secrets },
saved: { savedCafe, savedMuseum, lunch, conflicting, namesake, hiddenCopy, pantheon, secret },
label,
};
}
export type LibraryFixture = Awaited<ReturnType<typeof seedLibrary>>;
/** The keys of `me`'s entries by name, ties by key (a saved place's negative key first). */
export function expectedKeysByName(f: LibraryFixture): string[] {
const { places, saved } = f;
return [
`list:${saved.conflicting.id}`,
`trip:${places.cafe.id}`,
`trip:${places.camp.id}`,
`trip:${places.forum.id}`,
`list:${saved.hiddenCopy.id}`,
`trip:${places.hotel.id}`,
`list:${saved.lunch.id}`,
`list:${saved.namesake.id}`,
`trip:${places.museum.id}`,
`list:${saved.pantheon.id}`,
];
}
@@ -1,6 +1,7 @@
import {
castIntegerKysely,
concatKysely,
containsIgnoringCaseKysely,
currentTimestampKysely,
integerTextEqualsKysely,
nowPlusSecondsKysely,
@@ -276,6 +277,28 @@ describe('kysely-functions (postgres)', () => {
expect(now.parameters).toEqual([]);
});
it('SQLFPG-026: containsIgnoringCaseKysely is strpos over both sides lowered, the needle cast to text', () => {
const compiled = db
.selectFrom('users')
.select((eb) => containsIgnoringCaseKysely(pg, eb, 'username', '50%').as('v'))
.compile();
expect(compiled.sql).toBe('select strpos(lower("username"), lower(cast($1 as text))) > 0 as "v" from "users"');
expect(compiled.parameters).toEqual(['50%']);
// The same statement spelled for SQLite, rendered by this compiler: only the function differs.
const onSqlite = db
.selectFrom('users')
.select((eb) => containsIgnoringCaseKysely(new SqlitePlatform(), eb, 'username', 'x').as('v'))
.compile();
expect(onSqlite.sql).toBe('select instr(lower("username"), lower(cast($1 as text))) > 0 as "v" from "users"');
class FakePlatform extends Platform {}
const eb = expressionBuilder<ProbeDB, 'users'>();
expect(() => containsIgnoringCaseKysely(new FakePlatform(), eb, 'username', 'x')).toThrow(
/no implementation for platform FakePlatform/,
);
});
it('SQLFPG-025: an unknown platform still fails closed in the Kysely twins', () => {
class FakePlatform extends Platform {}
const foreign = new FakePlatform();
@@ -0,0 +1,49 @@
/**
* PlacesLibraryController over a stub service: each route hands the signed-in
* user (id and role) and its input to the one service method, and answers
* with what it returns. Guards, the id pipe and the response contracts run in
* the e2e suite.
*/
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
import { PlacesLibraryController } from '../../../../src/nest/places-library/places-library.controller';
import type { PlacesLibraryService } from '../../../../src/nest/places-library/places-library.service';
import type { User } from '../../../../src/types';
import { placesLibraryDetailResponseSchema, placesLibraryPageResponseSchema } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
const user = { id: 7, role: 'admin', username: 'ann', email: 'ann@example.test' } as User;
function controller(service: Partial<PlacesLibraryService>) {
return new PlacesLibraryController(service as unknown as PlacesLibraryService);
}
describe('PlacesLibraryController', () => {
it('GET library/places hands the query to the list with the user and its role', async () => {
const page = { entries: [], total: 0, counts: { all: 0, trip: 0, list: 0 }, next_cursor: null };
const list = vi.fn().mockResolvedValue(page);
const query = { q: 'cafe', kind: 'list' as const, limit: 20 };
expect(await controller({ list }).list(user, query)).toBe(page);
expect(list).toHaveBeenCalledWith({ id: 7, role: 'admin' }, query);
});
it('GET library/places/trip/:id and list/:id open one entry by the origin they name', async () => {
const answer = { entry: { key: 'trip:3' }, details: [] };
const detail = vi.fn().mockResolvedValue(answer);
const c = controller({ detail });
expect(await c.tripPlace(user, 3)).toBe(answer);
expect(await c.savedPlace(user, 9)).toBe(answer);
expect(detail.mock.calls).toEqual([
[{ id: 7, role: 'admin' }, 'trip', 3],
[{ id: 7, role: 'admin' }, 'list', 9],
]);
});
it('declares the shared response contracts', () => {
const proto = PlacesLibraryController.prototype;
const contract = (handler: unknown) => Reflect.getMetadata(RESPONSE_CONTRACT_KEY, handler as object) as unknown;
expect(contract(proto.list)).toBe(placesLibraryPageResponseSchema);
expect(contract(proto.tripPlace)).toBe(placesLibraryDetailResponseSchema);
expect(contract(proto.savedPlace)).toBe(placesLibraryDetailResponseSchema);
});
});
@@ -0,0 +1,114 @@
/**
* The pure halves of "All places": entry keys, the cursor, votes and how an
* entry is put together from its rows.
*/
import type {
LibraryCollectionPlaceRow,
LibraryTripPlaceRow,
} from '../../../../src/db/repositories/PlacesLibrary.repository';
import {
decodeLibraryCursor,
encodeLibraryCursor,
entryKey,
entryOf,
groupBy,
ratingOf,
rowsByAnchor,
} from '../../../../src/nest/places-library/places-library.helpers';
import { describe, expect, it } from 'vitest';
const facts = {
address: null,
lat: 1,
lng: 2,
image_url: null,
updated_at: '2026-11-01 10:00:00',
description: null,
website: null,
phone: null,
category_id: 3,
category_name: 'Food',
category_color: '#f00',
category_icon: null,
};
const trip: LibraryTripPlaceRow = {
...facts,
id: 10,
trip_id: 5,
name: 'Café',
trip_title: 'Alps',
trip_start: null,
trip_end: null,
trip_owner_id: 1,
};
const saved = (id: number, grouped: number | null, extra: Partial<LibraryCollectionPlaceRow> = {}) =>
({
...facts,
id,
collection_id: 4,
collection_name: 'Food',
status: 'odd-status',
name: `Saved ${id}`,
grouped_place_id: grouped,
category_id: null,
category_name: null,
...extra,
}) satisfies LibraryCollectionPlaceRow;
const access = { canEditTrip: () => true, canEditList: () => false };
describe('places-library helpers', () => {
it('names an entry by its trip place, else by its saved place', () => {
expect(entryKey(10)).toBe('trip:10');
expect(entryKey(-4)).toBe('list:4');
});
it('hands out a cursor that only its own sort reads back', () => {
const cursor = encodeLibraryCursor('name', { anchor_key: -4, sort_name: 'café', sort_time: '2026' });
expect(decodeLibraryCursor('name', cursor)).toEqual({ value: 'café', key: -4 });
expect(decodeLibraryCursor('updated', cursor)).toBeNull();
const byTime = encodeLibraryCursor('updated', { anchor_key: 3, sort_name: 'x', sort_time: '2026-01-01' });
expect(decodeLibraryCursor('updated', byTime)).toEqual({ value: '2026-01-01', key: 3 });
expect(decodeLibraryCursor('name', '%%%')).toBeNull();
expect(decodeLibraryCursor('name', Buffer.from('{"a":1}').toString('base64url'))).toBeNull();
});
it('sums the votes and finds the user’s own', () => {
expect(ratingOf([], 1)).toEqual({ average: null, count: 0, mine: null });
const rows = [
{ target_id: 1, user_id: 1, rating: 5 },
{ target_id: 1, user_id: 2, rating: 2 },
];
expect(ratingOf(rows, 1)).toEqual({ average: 3.5, count: 2, mine: 5 });
expect(ratingOf(rows, 9)).toEqual({ average: 3.5, count: 2, mine: null });
});
it('puts an entry together from its rows, the trip place leading', () => {
const rows = rowsByAnchor([10, -7, -99, 42], [trip], [saved(6, 10, { image_url: '/u/6.jpg' }), saved(7, null)]);
expect(rows.map((row) => row.anchor)).toEqual([10, -7]);
const [first, second] = rows;
if (!first || !second) throw new Error('expected two entries');
const grouped = entryOf(first, access);
expect(grouped).toMatchObject({
key: 'trip:10',
name: 'Café',
category: { id: 3, name: 'Food', color: '#f00', icon: null },
image_url: '/u/6.jpg',
});
expect(grouped.origins).toEqual([
expect.objectContaining({ kind: 'trip', can_edit: true, read_only: false }),
expect.objectContaining({ kind: 'list', collection_place_id: 6, status: 'idea', can_edit: false }),
]);
const alone = entryOf(second, access);
expect(alone).toMatchObject({ key: 'list:7', name: 'Saved 7', category: null, image_url: null });
});
it('groups rows by a numeric field in order', () => {
const groups = groupBy([{ k: 1 }, { k: 2 }, { k: 1 }], (row) => row.k);
expect([...groups.entries()]).toEqual([
[1, [{ k: 1 }, { k: 1 }]],
[2, [{ k: 2 }]],
]);
});
});
@@ -0,0 +1,111 @@
/**
* PlacesLibraryMcp (PLC-07/PLC-08): list_all_places and get_library_place over
* the same service and checks as REST, with the addon gate and the scopes the
* tools need. The suite takes its subject from the container over a snapshot
* test db.
*/
import type { McpContext } from '../../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
import { AddonsService } from '../../../../src/nest/addons/addons.service';
import { McpToolGuardsService } from '../../../../src/nest/mcp-shared/mcp-tool-guards.service';
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
import { PlacesLibraryMcp } from '../../../../src/nest/places-library/places-library.mcp';
import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-library.module';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { expectedKeysByName, seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let mcp: PlacesLibraryMcp;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [PlacesLibraryModule] });
mcp = t.get(PlacesLibraryMcp);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
f = await seedLibrary(orm);
});
afterAll(async () => {
await orm.close();
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 options = (name: string) => {
const entry = getEntry(PlacesLibraryMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
describe('PlacesLibraryMcp', () => {
it('PLIB-MCP-001: list_all_places pages through the user’s places as REST lists them', async () => {
const page = read(await mcp.listAllPlaces({}, ctx(f.me.id)));
expect(page.entries.map((entry: { key: string }) => entry.key)).toEqual(expectedKeysByName(f));
expect(page.counts).toEqual({ all: 10, trip: 5, list: 7 });
expect(read(await mcp.listAllPlaces({ kind: 'trip', trip_id: f.rome.id }, ctx(f.me.id))).entries).toHaveLength(1);
});
it('PLIB-MCP-002: get_library_place reads one entry with what each origin keeps', async () => {
const answer = read(await mcp.getLibraryPlace({ kind: 'list', id: f.saved.savedCafe.id }, ctx(f.me.id)));
expect(answer.entry.key).toBe(`trip:${f.places.cafe.id}`);
expect(answer.details.map((detail: { kind: string; notes: string }) => [detail.kind, detail.notes])).toEqual([
['trip', 'Book a table'],
['list', 'Try the cake'],
]);
});
it('PLIB-MCP-003: refuses what REST refuses, as the service words it', async () => {
await expect(mcp.getLibraryPlace({ kind: 'trip', id: f.places.hidden.id }, ctx(f.me.id))).rejects.toThrow(
'Place not found',
);
await expect(mcp.listAllPlaces({ kind: 'list', trip_id: f.alps.id }, ctx(f.me.id))).rejects.toThrow(
'Filter by a trip or by a list, not both',
);
});
it('PLIB-MCP-004: an admin may edit every trip place; the role is read for the check', async () => {
const admin = vi.spyOn(t.get(McpToolGuardsService), 'isAdminUser').mockResolvedValue(true);
const check = vi.spyOn(t.get(PermissionsService), 'checkPermission');
await mcp.listAllPlaces({ trip_id: f.rome.id }, ctx(f.me.id));
expect(admin).toHaveBeenCalledWith(f.me.id);
expect(check).toHaveBeenCalledWith('place_edit', 'admin', null, f.me.id, true);
});
it('PLIB-MCP-005: the tools are there only with Collections on, and for tokens that read lists and trips', async () => {
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
const gate = options('listAllPlaces').when;
expect(await gate?.(ctx(1), mcp)).toBe(true);
enabled.mockResolvedValue(false);
expect(await gate?.(ctx(1), mcp)).toBe(false);
const allowed = (name: string, scopes: string[] | null) => {
const access = options(name).access;
return typeof access === 'function' ? access({ userId: 1, scopes } as McpContext) : access;
};
for (const name of ['listAllPlaces', 'getLibraryPlace']) {
expect(allowed(name, ['collections:read', 'trips:read'])).toBe(true);
expect(allowed(name, ['collections:read'])).toBe(false);
expect(allowed(name, ['trips:read'])).toBe(false);
expect(allowed(name, null)).toBe(true);
expect(options(name).annotations).toMatchObject({ readOnlyHint: true });
}
});
});
@@ -0,0 +1,282 @@
/**
* PlacesLibraryService (PLC-07/PLC-08) over the real repository on a migrated
* test db: which places "All places" lists and which it leaves out, when a
* saved place and a trip place are one entry, who may change what, the
* filters, counts and pages, and one entry in detail. Only the trip
* permission check is replaced, to deny 'place_edit' to trip members.
*/
import { Places } from '../../../../src/db/entities/Places.entity';
import { DomainError } from '../../../../src/nest/common/domain-error';
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-library.module';
import { PlacesLibraryService, type LibraryUser } from '../../../../src/nest/places-library/places-library.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { updateRows } from '../../../helpers/factories/rows';
import { expectedKeysByName, seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import type { PlacesLibraryEntry, PlacesLibraryPageResponse, PlacesLibraryQuery } from '@trek/shared';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let library: PlacesLibraryService;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [PlacesLibraryModule] });
library = t.get(PlacesLibraryService);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
// A trip's owner may edit its places, a member may not.
vi.spyOn(t.get(PermissionsService), 'checkPermission').mockImplementation(
async (_action, _role, tripOwner, userId) => tripOwner === userId,
);
f = await seedLibrary(orm);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const as = (id: number): LibraryUser => ({ id, role: 'user' });
const keys = (page: PlacesLibraryPageResponse) => page.entries.map((entry) => entry.key);
const entry = (page: PlacesLibraryPageResponse, key: string): PlacesLibraryEntry => {
const found = page.entries.find((candidate) => candidate.key === key);
if (!found) throw new Error(`no entry ${key}`);
return found;
};
async function refusal(promise: Promise<unknown>): Promise<{ status: number; message: string }> {
try {
await promise;
} catch (err) {
expect(err).toBeInstanceOf(DomainError);
const error = err as DomainError;
return { status: error.getStatus(), message: error.publicMessage };
}
throw new Error('expected a refusal');
}
describe('PlacesLibraryService.list', () => {
it('PLIB-001: lists the normal places of every trip and the saved places of every list, nothing else', async () => {
const page = await library.list(as(f.me.id), {});
expect(keys(page)).toEqual(expectedKeysByName(f));
const listed = new Set(keys(page));
for (const left of [f.places.ridge, f.places.track, f.places.pump, f.places.hidden]) {
expect(listed.has(`trip:${left.id}`)).toBe(false);
}
expect(listed.has(`list:${f.saved.secret.id}`)).toBe(false);
expect(page).toMatchObject({ total: 10, counts: { all: 10, trip: 5, list: 7 }, next_cursor: null });
});
it('PLIB-002: groups a saved place with the trip place it came from only when the two agree', async () => {
const page = await library.list(as(f.me.id), {});
const cafe = entry(page, `trip:${f.places.cafe.id}`);
expect(cafe).toMatchObject({
name: 'Café Central',
address: 'Herrengasse 14, Wien',
lat: 48.2104,
lng: 16.3655,
});
expect(cafe.origins).toEqual([
{
kind: 'trip',
trip_id: f.alps.id,
trip_title: 'Alps',
trip_start: '2026-07-01',
trip_end: '2026-07-03',
place_id: f.places.cafe.id,
can_edit: true,
read_only: false,
},
{
kind: 'list',
collection_id: f.lists.food.id,
collection_name: 'Food',
collection_place_id: f.saved.savedCafe.id,
status: 'want',
can_edit: true,
},
]);
// The provider id alone is enough, whatever the copy is called.
expect(entry(page, `trip:${f.places.museum.id}`).origins.map((origin) => origin.kind)).toEqual(['trip', 'list']);
// A renamed copy, one with another provider id, one without a source and one from a trip out of reach stay apart.
for (const apart of [f.saved.lunch, f.saved.conflicting, f.saved.namesake, f.saved.hiddenCopy]) {
expect(entry(page, `list:${apart.id}`).origins).toHaveLength(1);
}
});
it('PLIB-003: says what the user may change: a viewer of a list and a member without place_edit read only', async () => {
const page = await library.list(as(f.me.id), {});
expect(entry(page, `list:${f.saved.pantheon.id}`).origins).toEqual([
expect.objectContaining({ kind: 'list', collection_name: 'Rome sights', status: 'visited', can_edit: false }),
]);
expect(entry(page, `trip:${f.places.forum.id}`).origins).toEqual([
expect.objectContaining({ kind: 'trip', trip_title: 'Rome', can_edit: false, read_only: true }),
]);
});
it('PLIB-004: reads nothing of another user, and a stranger’s copy never groups with a trip out of reach', async () => {
const page = await library.list(as(f.stranger.id), {});
expect(keys(page).sort()).toEqual([`list:${f.saved.secret.id}`, `trip:${f.places.hidden.id}`].sort());
expect(entry(page, `list:${f.saved.secret.id}`).origins).toHaveLength(1);
});
it('PLIB-005: narrows by origin, list, trip, status, category and text, counting for the tabs apart', async () => {
const by = async (query: PlacesLibraryQuery) => keys(await library.list(as(f.me.id), query));
expect(await by({ kind: 'trip' })).toEqual([
`trip:${f.places.cafe.id}`,
`trip:${f.places.camp.id}`,
`trip:${f.places.forum.id}`,
`trip:${f.places.hotel.id}`,
`trip:${f.places.museum.id}`,
]);
// A grouped entry has a list origin, so it is one of the list's entries too.
expect(await by({ collection_id: f.lists.food.id })).toEqual([
`list:${f.saved.conflicting.id}`,
`trip:${f.places.cafe.id}`,
`list:${f.saved.hiddenCopy.id}`,
`list:${f.saved.lunch.id}`,
`list:${f.saved.namesake.id}`,
`trip:${f.places.museum.id}`,
]);
expect(await by({ trip_id: f.rome.id })).toEqual([`trip:${f.places.forum.id}`]);
expect(await by({ status: 'visited' })).toEqual([`list:${f.saved.pantheon.id}`]);
expect(await by({ q: 'HERRENGASSE' })).toEqual([`trip:${f.places.cafe.id}`]);
expect(await by({ q: '%' })).toEqual([]);
// A list or trip out of reach answers like an empty one.
expect(await by({ collection_id: f.lists.secrets.id })).toEqual([]);
expect(await by({ trip_id: f.elsewhere.id })).toEqual([]);
const narrowed = await library.list(as(f.me.id), { kind: 'trip', q: 'c' });
expect(narrowed.total).toBe(narrowed.entries.length);
expect(narrowed.counts.all).toBeGreaterThanOrEqual(narrowed.total);
});
it('PLIB-006: filters by category on either side', async () => {
await updateRows(orm, Places, { id: f.places.forum.id }, { category: null });
const all = await library.list(as(f.me.id), {});
const category = entry(all, `trip:${f.places.cafe.id}`).category;
expect(category).not.toBeNull();
const page = await library.list(as(f.me.id), { category_id: category?.id });
expect(keys(page)).not.toContain(`trip:${f.places.forum.id}`);
expect(keys(page)).toContain(`trip:${f.places.cafe.id}`);
});
it('PLIB-007: refuses a list filter together with a trip filter', async () => {
expect(await refusal(library.list(as(f.me.id), { kind: 'list', trip_id: f.alps.id }))).toEqual({
status: 400,
message: 'Filter by a trip or by a list, not both',
});
expect(await refusal(library.list(as(f.me.id), { status: 'want', kind: 'trip' }))).toMatchObject({ status: 400 });
});
it('PLIB-008: pages through every entry once, by name and by last change', async () => {
for (const sort of ['name', 'updated'] as const) {
const seen: string[] = [];
let cursor: string | undefined;
for (let round = 0; round < 10; round++) {
const page = await library.list(as(f.me.id), { sort, limit: 3, ...(cursor ? { cursor } : {}) });
seen.push(...keys(page));
if (!page.next_cursor) break;
cursor = page.next_cursor;
}
expect(seen).toHaveLength(10);
expect(new Set(seen)).toEqual(new Set(expectedKeysByName(f)));
}
});
it('PLIB-009: sorts by the last change, newest first', async () => {
await updateRows(orm, Places, { id: f.places.forum.id }, { updated_at: '2030-01-01 00:00:00' });
const page = await library.list(as(f.me.id), { sort: 'updated', limit: 1 });
expect(keys(page)).toEqual([`trip:${f.places.forum.id}`]);
expect(page.next_cursor).not.toBeNull();
});
it('PLIB-010: refuses a cursor it did not hand out, or one of the other sort', async () => {
const page = await library.list(as(f.me.id), { limit: 2 });
const invalid = { status: 400, message: 'Invalid cursor: pass the next_cursor of the page before' };
expect(await refusal(library.list(as(f.me.id), { cursor: 'nonsense' }))).toEqual(invalid);
expect(await refusal(library.list(as(f.me.id), { sort: 'updated', cursor: page.next_cursor ?? '' }))).toEqual(
invalid,
);
});
it('PLIB-011: ends a page early past maxChars, and the cursor goes on after its last entry', async () => {
const first = await library.list(as(f.me.id), {}, { maxChars: 10 });
expect(first.entries).toHaveLength(1);
const second = await library.list(as(f.me.id), { cursor: first.next_cursor ?? '' });
expect([...keys(first), ...keys(second)]).toEqual(expectedKeysByName(f));
});
});
describe('PlacesLibraryService.detail', () => {
it('PLIB-020: answers a trip place with what the trip and each list keep of it', async () => {
const answer = await library.detail(as(f.me.id), 'trip', f.places.cafe.id);
expect(answer.entry.key).toBe(`trip:${f.places.cafe.id}`);
expect(answer.details).toEqual([
expect.objectContaining({
kind: 'trip',
place_id: f.places.cafe.id,
info: expect.objectContaining({ name: 'Café Central', description: 'A coffee house' }),
notes: 'Book a table',
rating: { average: 3, count: 2, mine: 4 },
days: [{ day_id: f.day1.id, day_number: 1, date: '2026-07-01', title: null, time: '09:00', end_time: null }],
has_accommodation: false,
has_reservation: false,
}),
expect.objectContaining({
kind: 'list',
collection_place_id: f.saved.savedCafe.id,
info: expect.objectContaining({ name: ' café central ' }),
notes: 'Try the cake',
labels: [{ id: f.label.id, name: 'Must', color: '#ff0000' }],
rating: { average: 5, count: 1, mine: 5 },
}),
]);
});
it('PLIB-021: opens the same entry from the saved place it groups', async () => {
const answer = await library.detail(as(f.me.id), 'list', f.saved.savedCafe.id);
expect(answer.entry.key).toBe(`trip:${f.places.cafe.id}`);
expect(answer.details.map((detail) => detail.kind)).toEqual(['trip', 'list']);
});
it('PLIB-022: says whether a stay or a booking uses a trip place', async () => {
const camp = await library.detail(as(f.me.id), 'trip', f.places.camp.id);
expect(camp.details[0]).toMatchObject({ has_accommodation: true, has_reservation: false, days: [] });
const hotel = await library.detail(as(f.me.id), 'trip', f.places.hotel.id);
expect(hotel.details[0]).toMatchObject({ has_accommodation: false, has_reservation: true });
});
it('PLIB-023: a place of a trip or list out of reach, or one it leaves out, is not found', async () => {
const notFound = { status: 404, message: 'Place not found' };
expect(await refusal(library.detail(as(f.me.id), 'trip', f.places.hidden.id))).toEqual(notFound);
expect(await refusal(library.detail(as(f.me.id), 'trip', f.places.ridge.id))).toEqual(notFound);
expect(await refusal(library.detail(as(f.me.id), 'trip', f.places.pump.id))).toEqual(notFound);
expect(await refusal(library.detail(as(f.me.id), 'list', f.saved.secret.id))).toEqual(notFound);
expect(await refusal(library.detail(as(f.me.id), 'list', 999_999))).toEqual(notFound);
});
it('PLIB-024: a saved place apart from any trip place is an entry of its own', async () => {
const answer = await library.detail(as(f.me.id), 'list', f.saved.pantheon.id);
expect(answer.entry.key).toBe(`list:${f.saved.pantheon.id}`);
expect(answer.details).toEqual([
expect.objectContaining({
kind: 'list',
notes: null,
labels: [],
rating: { average: null, count: 0, mine: null },
}),
]);
});
});