feat(places): own place identities, duplicate merging and lists linked to a trip

- A user can group the uses of one place (trip places and saved places) into a
  place identity of their own (user_places, user_place_links). It is personal:
  it groups their "All places" and is never written into a shared trip or list
  row. An identity without a use they can still reach is not shown, and one
  left without links is pruned on their next write and nightly.
- Possible duplicates are suggested server side (same provider id, or the same
  name at the same spot), each pair with what differs and whether the user may
  merge it. A merge joins two identities in one transaction and can be undone;
  a dismissed pair does not come back. No trip or list row is deleted or changed.
- A trip can link lists (trip_collection_links, needs place_edit and access to
  the list). A member sees a linked list only with their own access to it; the
  map layer lists its places and whether each is already in the trip.
  tripCollections:changed tells the members to read their view again.
- REST, MCP tools and client data layer for all of it; migrations on both
  engines, additive only.
- CI: the stage 1 to 2 places-library helper types, and the await-in-loop and
  non-null counts it had raised.
This commit is contained in:
Maurice
2026-11-29 15:57:05 +01:00
parent 01d327b502
commit f69a4c1a24
87 changed files with 4882 additions and 221 deletions
+5 -7
View File
@@ -25,6 +25,7 @@ import {
createDayAssignment,
} from '../helpers/factories';
import { countRows, findRow } from '../helpers/factories/rows';
import { oneByOne } from '../helpers/one-by-one';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
@@ -892,13 +893,10 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const col = (await request(server).post('/api/addons/collections').set(as(ownerId)).send({ name: 'Ordered' })).body;
const ids: number[] = [];
for (const name of ['One', 'Two', 'Three']) {
const saved = await request(server)
.post('/api/addons/collections/places')
.set(as(ownerId))
.send({ collection_id: col.id, name });
ids.push(saved.body.place.id);
}
const saves = await oneByOne(['One', 'Two', 'Three'], (name) =>
request(server).post('/api/addons/collections/places').set(as(ownerId)).send({ collection_id: col.id, name }),
);
ids.push(...saves.map((saved) => saved.body.place.id as number));
const reorder = (userId: number | null, orderedIds: number[]) => {
const req = request(server).put(`/api/addons/collections/${col.id}/places/reorder`);
return (userId === null ? req : req.set(as(userId))).send({ orderedIds });
+93 -5
View File
@@ -12,6 +12,7 @@ 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 { oneByOne } from '../helpers/one-by-one';
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';
@@ -107,9 +108,11 @@ describe('Places library e2e (real guards + temp SQLite)', () => {
.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 refused = await oneByOne(
[{ category_id: '0x5' }, { kind: 'tour' }, { limit: '1000' }, { notes: 'x' }],
(query) => request(server).get(BASE).query(query).set(as(f.me.id)),
);
expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400]);
const both = await request(server)
.get(BASE)
.query({ kind: 'list', trip_id: String(f.alps.id) })
@@ -128,10 +131,95 @@ describe('Places library e2e (real guards + temp SQLite)', () => {
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));
const missing = await oneByOne(
[`trip/${f.places.hidden.id}`, `list/${f.saved.secret.id}`, 'trip/abc', 'list/0x5'],
(path) => request(server).get(`${BASE}/${path}`).set(as(f.me.id)),
);
for (const res of missing) {
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Place not found' });
}
});
});
describe('Own places, duplicates and merges e2e (real guards + temp SQLite)', () => {
const LIBRARY = '/api/addons/collections/library';
it('answers 404 while Collections is off and 401 without a session', async () => {
await setAddonEnabled(orm, 'collections', false);
expect((await request(server).get(`${LIBRARY}/duplicates`)).status).toBe(404);
await setAddonEnabled(orm, 'collections', true);
expect((await request(server).post(`${LIBRARY}/places/link`).send({ uses: [] })).status).toBe(401);
});
it('links, unlinks, suggests, merges and undoes, each answer checked against its contract', async () => {
const link = await request(server)
.post(`${LIBRARY}/places/link`)
.set(as(f.me.id))
.send({
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
});
expect(link.status).toBe(200);
expect(link.body.entry.key).toBe(`own:${link.body.entry.identity_id}`);
const unlink = await request(server)
.post(`${LIBRARY}/places/unlink`)
.set(as(f.me.id))
.send({ kind: 'list', id: f.saved.pantheon.id });
expect(unlink.status).toBe(200);
expect(unlink.body.entry.key).toBe(`list:${f.saved.pantheon.id}`);
const duplicates = await request(server).get(`${LIBRARY}/duplicates`).query({ limit: '1' }).set(as(f.me.id));
expect(duplicates.status).toBe(200);
expect(duplicates.body.duplicates).toHaveLength(1);
expect(duplicates.body.next_cursor).not.toBeNull();
const [pair] = duplicates.body.duplicates;
const merge = await request(server)
.post(`${LIBRARY}/merges`)
.set(as(f.me.id))
.send({ leading: pair.a.key, other: pair.b.key });
expect(merge.status).toBe(200);
const undo = await request(server).post(`${LIBRARY}/merges/${merge.body.merge_id}/undo`).set(as(f.me.id));
expect(undo.status).toBe(200);
expect(undo.body).toEqual({ success: true });
const dismiss = await request(server)
.post(`${LIBRARY}/duplicates/dismiss`)
.set(as(f.me.id))
.send({ a: pair.a.key, b: pair.b.key });
expect(dismiss.body).toEqual({ success: true });
});
it('refuses what it does not take, and what the user cannot reach', async () => {
const bad = [
{ uses: [{ kind: 'trip', id: '0x5' }] },
{ uses: [] },
{ uses: [{ kind: 'tour', id: 1 }] },
{ uses: [{ kind: 'trip', id: 1 }], extra: true },
];
const refused = await oneByOne(bad, (body) =>
request(server).post(`${LIBRARY}/places/link`).set(as(f.me.id)).send(body),
);
expect(refused.map((res) => res.status)).toEqual(bad.map(() => 400));
const hidden = await request(server)
.post(`${LIBRARY}/places/link`)
.set(as(f.me.id))
.send({ uses: [{ kind: 'trip', id: f.places.hidden.id }] });
expect(hidden.status).toBe(404);
expect(hidden.body).toEqual({ error: 'Place not found' });
const merge = await request(server)
.post(`${LIBRARY}/merges`)
.set(as(f.me.id))
.send({ leading: 'trip:abc', other: 'list:1' });
expect(merge.status).toBe(400);
const undos = await oneByOne(['abc', '0x5', '999999'], (id) =>
request(server).post(`${LIBRARY}/merges/${id}/undo`).set(as(f.me.id)),
);
for (const undo of undos) {
expect(undo.status).toBe(404);
expect(undo.body).toEqual({ error: 'Merge not found' });
}
});
});
@@ -0,0 +1,141 @@
/**
* The lists a trip draws on (PLC-15/PLC-16) through the real AddonGuard,
* JwtAuthGuard and TripAccessGuard against a migrated and seeded temp SQLite
* db, every answer checked against its response contract.
*/
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { TripCollectionsModule } from '../../src/nest/trip-collections/trip-collections.module';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { setAddonEnabled } from '../helpers/factories/settings';
import { addTripMember } from '../helpers/factories/trips';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { oneByOne } from '../helpers/one-by-one';
import { 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 } from 'vitest';
const db = createSnapshotTestDb();
const realtime = new FakeRealtimeService();
let app: INestApplication;
let server: Server;
let orm: TestOrm;
let f: LibraryFixture;
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const base = (tripId: number) => `/api/trips/${tripId}/collections`;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
RealtimeModule,
TripCollectionsModule,
],
})
.overrideProvider(RealtimeService)
.useValue(realtime)
.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();
realtime.reset();
f = await seedLibrary(orm);
await setAddonEnabled(orm, 'collections', true);
});
afterAll(async () => {
await app.close();
await orm.close();
db.close();
});
describe('Trip collections e2e (real guards + temp SQLite)', () => {
it('answers 404 while Collections is off, 401 without a session and 404 for a trip out of reach', async () => {
await setAddonEnabled(orm, 'collections', false);
expect((await request(server).get(base(f.alps.id))).status).toBe(404);
await setAddonEnabled(orm, 'collections', true);
expect((await request(server).get(base(f.alps.id))).status).toBe(401);
const hidden = await request(server).get(base(f.elsewhere.id)).set(as(f.me.id));
expect(hidden.status).toBe(404);
expect(hidden.body).toEqual({ error: 'Trip not found' });
});
it('links a list, lists it, maps its places and unlinks it, skipping the sender socket', async () => {
const link = await request(server)
.post(base(f.alps.id))
.set(as(f.me.id))
.set('X-Socket-Id', '42')
.send({ collection_id: f.lists.food.id });
expect(link.status).toBe(200);
expect(link.body.links).toEqual([expect.objectContaining({ collection_id: f.lists.food.id, role: 'owner' })]);
expect(realtime.broadcastMock).toHaveBeenCalledWith(f.alps.id, 'tripCollections:changed', {}, '42');
const layer = await request(server)
.get(`${base(f.alps.id)}/places`)
.set(as(f.me.id));
expect(layer.status).toBe(200);
expect(layer.body.places.some((place: { in_trip: boolean }) => place.in_trip)).toBe(true);
const unlink = await request(server)
.delete(`${base(f.alps.id)}/${f.lists.food.id}`)
.set(as(f.me.id));
expect(unlink.status).toBe(200);
expect(unlink.body).toEqual({ links: [], can_link: true });
});
it('refuses a body it does not take, a list out of reach and a bad id', async () => {
const refused = await oneByOne(
[{}, { collection_id: '0x5' }, { collection_id: 1.5 }, { collection_id: 1, x: 1 }],
(body) => request(server).post(base(f.alps.id)).set(as(f.me.id)).send(body),
);
expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400]);
const secret = await request(server)
.post(base(f.alps.id))
.set(as(f.me.id))
.send({ collection_id: f.lists.secrets.id });
expect(secret.status).toBe(404);
expect(secret.body).toEqual({ error: 'Collection not found' });
const missing = await oneByOne(['abc', '0x5'], (id) =>
request(server)
.delete(`${base(f.alps.id)}/${id}`)
.set(as(f.me.id)),
);
for (const res of missing) {
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Collection not found' });
}
});
it('shows a member nothing of a list closed to them', async () => {
await request(server).post(base(f.alps.id)).set(as(f.me.id)).send({ collection_id: f.lists.food.id });
await addTripMember(orm, f.alps.id, f.friend.id);
const res = await request(server).get(base(f.alps.id)).set(as(f.friend.id));
expect(res.status).toBe(200);
expect(res.body.links).toEqual([]);
const layer = await request(server)
.get(`${base(f.alps.id)}/places`)
.set(as(f.friend.id));
expect(layer.body).toEqual({ places: [] });
});
});
@@ -0,0 +1,43 @@
import { TripCollectionLinks } from '../../../src/db/entities/TripCollectionLinks.entity';
import { UserPlaceLinks } from '../../../src/db/entities/UserPlaceLinks.entity';
import { UserPlaces } from '../../../src/db/entities/UserPlaces.entity';
import { nextSeq, type FactoryOrm } from './context';
import { createRow } from './rows';
import type { EntityData, EntityDTO } from '@mikro-orm/core';
export type UserPlaceRow = EntityDTO<UserPlaces>;
export type UserPlaceLinkRow = EntityDTO<UserPlaceLinks>;
/** An own place (D5) of `userId`. */
export function makeUserPlace(
orm: FactoryOrm,
userId: number,
overrides: EntityData<UserPlaces> = {},
): Promise<UserPlaceRow> {
return createRow(orm, UserPlaces, { user: userId, name: `Own place ${nextSeq('user-place')}` }, overrides);
}
/** Links one use (a trip place or a saved place) of `userId` to the own place. */
export function linkUserPlace(
orm: FactoryOrm,
userId: number,
userPlaceId: number,
use: { place?: number; collectionPlace?: number },
): Promise<UserPlaceLinkRow> {
return createRow(orm, UserPlaceLinks, {
userPlace: userPlaceId,
user: userId,
place: use.place ?? null,
collectionPlace: use.collectionPlace ?? null,
});
}
/** Links a list to a trip (PLC-15). */
export function linkTripCollection(
orm: FactoryOrm,
tripId: number,
collectionId: number,
linkedBy: number | null = null,
): Promise<EntityDTO<TripCollectionLinks>> {
return createRow(orm, TripCollectionLinks, { trip: tripId, collection: collectionId, linkedByRef: linkedBy });
}
+14 -3
View File
@@ -153,12 +153,15 @@ export async function seedLibrary(orm: FactoryOrm) {
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). */
/**
* The keys of `me`'s entries by name. Café Central's two entries tie on the
* name and then go by their anchor (`id * 4 + kind`, a trip place's kind 1,
* a saved place's 2), so their order follows the ids the seed got.
*/
export function expectedKeysByName(f: LibraryFixture): string[] {
const { places, saved } = f;
return [
`list:${saved.conflicting.id}`,
`trip:${places.cafe.id}`,
...cafeTie(f),
`trip:${places.camp.id}`,
`trip:${places.forum.id}`,
`list:${saved.hiddenCopy.id}`,
@@ -169,3 +172,11 @@ export function expectedKeysByName(f: LibraryFixture): string[] {
`list:${saved.pantheon.id}`,
];
}
/** The two entries named Café Central, in the order their anchors give. */
export function cafeTie(f: LibraryFixture): string[] {
const conflicting = f.saved.conflicting.id * 4 + 2;
const cafe = f.places.cafe.id * 4 + 1;
const pair = [`list:${f.saved.conflicting.id}`, `trip:${f.places.cafe.id}`];
return conflicting < cafe ? pair : [...pair].reverse();
}
@@ -7,6 +7,7 @@ import { StorageService } from '../../../src/nest/storage/storage.service';
import { makeDayAssignment } from '../../helpers/factories/itinerary';
import { makeTag } from '../../helpers/factories/places';
import { insertRow, updateRows } from '../../helpers/factories/rows';
import { linkTripCollection } from '../../helpers/factories/user-places';
import type { CaseGroup, Scene } from './types';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
@@ -380,6 +381,28 @@ export const plan: CaseGroup = {
},
expect: ['place:created'],
},
{
// PLC-15: content-free, so every member asks again with their own list rights.
tool: 'link_collection_to_trip',
needs: ['collection'],
args: (s) => ({ tripId: s.trip.id, collection_id: s.collection.id }),
rest: {
method: 'post',
path: (s) => `/api/trips/${s.trip.id}/collections`,
body: (s) => ({ collection_id: s.collection.id }),
},
expect: ['tripCollections:changed'],
},
{
tool: 'unlink_collection_from_trip',
needs: ['collection'],
setup: async (s, app) => {
await linkTripCollection(app.get(MikroORM), s.trip.id, s.collection.id, s.owner.id);
},
args: (s) => ({ tripId: s.trip.id, collection_id: s.collection.id }),
rest: { method: 'delete', path: (s) => `/api/trips/${s.trip.id}/collections/${s.collection.id}` },
expect: ['tripCollections:changed'],
},
{
tool: 'create_day_note',
args: (s) => ({ tripId: s.trip.id, dayId: s.days[0].id, text: 'Bring the museum pass' }),
@@ -15,10 +15,12 @@ import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.s
import { JourneyRecordedDaysService } from '../../../src/nest/journey/journey-recorded-days.service';
import { PhotoCaptureBackfillService } from '../../../src/nest/memories/photo-capture-backfill.service';
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { PlaceIdentitiesService } from '../../../src/nest/places-library/place-identities.service';
import { addCollectionMember } from '../../helpers/factories/collections';
import { inContext } from '../../helpers/factories/context';
import { addJourneyContributor, linkTripToJourney, makeJourneyEntry } from '../../helpers/factories/journeys';
import { createRow, insertRow, updateRows } from '../../helpers/factories/rows';
import { linkUserPlace, makeUserPlace } from '../../helpers/factories/user-places';
import { addVacayPlanMember } from '../../helpers/factories/vacay';
import { holidayCode } from './harness';
import type { CaseGroup, ParityCase, RestCall, Scene } from './types';
@@ -35,6 +37,25 @@ import { vi } from 'vitest';
* that asked, MCP none, so the tab the assistant runs in shows the change.
*/
const HOLIDAY_CATALOG = "the admin's school holiday catalog is global: no room, and the registry has no event for it";
const OWN_PLACES =
"changes only the caller's own grouping of All places (D5): no trip place or saved place is written and nobody else sees it, so there is nothing to send";
const placeKeys = (s: Scene) => ({ a: `trip:${s.place.id}`, b: `trip:${s.place2.id}` });
/** The owner's own place holding the scene's first place, for the unlink. */
async function ownPlace(s: Scene, app: INestApplication): Promise<void> {
const own = await makeUserPlace(ormOf(app), s.owner.id);
await linkUserPlace(ormOf(app), s.owner.id, own.id, { place: s.place.id });
}
/** The scene's two places merged by the owner, for the undo. */
async function mergedPlaces(s: Scene, app: INestApplication): Promise<void> {
const merged = await withRequestContext(ormOf(app), () =>
app
.get(PlaceIdentitiesService)
.merge({ id: s.owner.id, role: 'user' }, `trip:${s.place.id}`, `trip:${s.place2.id}`),
);
keep(s, 'merge', merged.merge_id);
}
const TOKEN_ONLY = 'manages a public link token: nothing on any screen follows it live, so there is nothing to send';
const onJourney = (s: Scene) => ({ journeyId: s.journey.id });
const WINTER = { name: 'Winter', startDate: '2027-02-01', endDate: '2027-02-12' };
@@ -1305,6 +1326,38 @@ export const user: CaseGroup = {
setup: recordStay,
args: (s) => ({ suggestionId: kept(s, 'stay') }),
},
{
tool: 'link_library_places',
reason: OWN_PLACES,
needs: ['place', 'place2'],
args: (s) => ({
uses: [
{ kind: 'trip', id: s.place.id },
{ kind: 'trip', id: s.place2.id },
],
}),
},
{
tool: 'unlink_library_place',
reason: OWN_PLACES,
needs: ['place'],
setup: ownPlace,
args: (s) => ({ kind: 'trip', id: s.place.id }),
},
{ tool: 'dismiss_library_duplicate', reason: OWN_PLACES, needs: ['place', 'place2'], args: placeKeys },
{
tool: 'merge_library_places',
reason: OWN_PLACES,
needs: ['place', 'place2'],
args: (s) => ({ leading: `trip:${s.place.id}`, other: `trip:${s.place2.id}` }),
},
{
tool: 'undo_library_merge',
reason: OWN_PLACES,
needs: ['place', 'place2'],
setup: mergedPlaces,
args: (s) => ({ merge_id: kept(s, 'merge') }),
},
{
tool: 'create_manual_school_holiday_country',
reason: HOLIDAY_CATALOG,
@@ -119,6 +119,8 @@ const UNNUMBERED = [
'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account',
'Migration20200101046510_a_session_knows_its_provider_session',
'Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to',
'Migration20200101046530_a_user_keeps_their_own_place_identities',
'Migration20200101046540_a_trip_links_its_collections',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -490,9 +490,9 @@ describe('CollectionsController', () => {
new RuntimeEnvService(),
storageStub,
);
for (const code of ['not-map', 'unreadable', 'too-many-places'] as const) {
expect(await rejected(refuse(code).readMap(upload))).toEqual({ status: 400, body: { error: 'refused', code } });
}
const codes = ['not-map', 'unreadable', 'too-many-places'] as const;
const answers = await Promise.all(codes.map((code) => rejected(refuse(code).readMap(upload))));
expect(answers).toEqual(codes.map((code) => ({ status: 400, body: { error: 'refused', code } })));
expect(await rejected(refuse('too-large').readMap(upload))).toEqual({
status: 413,
body: { error: 'refused', code: 'too-large' },
@@ -152,8 +152,9 @@ describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9)
await svc.copyToTrip(user.id, { trip_id: trip.id, place_ids: [spot.id] }, svc.tripEvents(trip.id, undefined));
const copy = await findRow(orm, Places, { trip: trip.id, name: 'Cafe' });
expect(copy?.notes).toBeNull();
expect(await tagsOf(copy!.id)).toEqual([]);
if (!copy) throw new Error('the copy is missing');
expect(copy.notes).toBeNull();
expect(await tagsOf(copy.id)).toEqual([]);
expect(tripTagEvents()).toEqual([]);
});
@@ -201,7 +202,8 @@ describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9)
const skyBar = await findRow(orm, Places, { trip: trip.id, name: 'Sky Bar' });
const garden = await findRow(orm, Places, { trip: trip.id, name: 'Garden' });
const sky = await tagsOf(skyBar!.id);
if (!skyBar || !garden) throw new Error('a copy is missing');
const sky = await tagsOf(skyBar.id);
expect(sky).toHaveLength(2);
expect(sky).toEqual(
expect.arrayContaining([
@@ -209,10 +211,10 @@ describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9)
['Brunch', trip.id, owner.id],
]),
);
expect(await tagsOf(garden!.id)).toEqual([['Brunch', trip.id, owner.id]]);
expect(await tagsOf(garden.id)).toEqual([['Brunch', trip.id, owner.id]]);
// One new trip tag for both places, the trip's own one reused, the personal tags left where they were.
expect(await countRows(orm, Tags, { trip: trip.id })).toBe(2);
expect((await findRows(orm, Tags, { place_tags_inverse: skyBar!.id })).map((tag) => tag.id)).toContain(existing.id);
expect((await findRows(orm, Tags, { place_tags_inverse: skyBar.id })).map((tag) => tag.id)).toContain(existing.id);
expect(tripTagEvents()).toEqual([[trip.id, 'tripTags:changed', {}, 'sock-1']]);
});
@@ -18,6 +18,7 @@ import { makeCategory, makePlace } from '../../helpers/factories/places';
import { findRow, findRows } from '../../helpers/factories/rows';
import { makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { oneByOne } from '../../helpers/one-by-one';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
@@ -100,15 +101,17 @@ describe('reorderPlaces (PLC-03)', () => {
const foreign = await save(user.id, other.id, 'Foreign');
t.realtime.reset();
for (const ids of [
[b.id, foreign.id],
[b.id, b.id, a.id],
]) {
await expect(svc.reorderPlaces(user.id, col.id, ids)).rejects.toMatchObject({
status: 400,
message: 'Every place of the order must be in this list, once',
});
}
await oneByOne(
[
[b.id, foreign.id],
[b.id, b.id, a.id],
],
(ids) =>
expect(svc.reorderPlaces(user.id, col.id, ids)).rejects.toMatchObject({
status: 400,
message: 'Every place of the order must be in this list, once',
}),
);
expect(await namesInOrder(user.id, col.id)).toEqual(['A', 'B']);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
@@ -185,13 +188,14 @@ describe('a new place goes after the last one (PLC-03)', () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Coords' });
const { place } = await svc.savePlace(user.id, { collection_id: col.id, name: 'Pin', lat: 38.7, lng: -9.1 });
if (!place) throw new Error('nothing saved');
await svc.updatePlace(user.id, place!.id, { address: 'Rua Augusta 1' });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: 38.7, lng: -9.1 });
await svc.updatePlace(user.id, place!.id, { lat: null, lng: null });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: null, lng: null });
await svc.updatePlace(user.id, place!.id, { lat: 38.71, lng: -9.14 });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: 38.71, lng: -9.14 });
await svc.updatePlace(user.id, place.id, { address: 'Rua Augusta 1' });
expect(await findRow(orm(), CollectionPlaces, { id: place.id })).toMatchObject({ lat: 38.7, lng: -9.1 });
await svc.updatePlace(user.id, place.id, { lat: null, lng: null });
expect(await findRow(orm(), CollectionPlaces, { id: place.id })).toMatchObject({ lat: null, lng: null });
await svc.updatePlace(user.id, place.id, { lat: 38.71, lng: -9.14 });
expect(await findRow(orm(), CollectionPlaces, { id: place.id })).toMatchObject({ lat: 38.71, lng: -9.14 });
});
});
@@ -229,10 +233,12 @@ describe('savePlace keeps only a provenance the caller can stand behind', () =>
{ source_trip_id: mine.id }, // half a pair
{ source_place_id: minePlace.id },
];
for (const [i, claim] of claims.entries()) {
const rows = await oneByOne([...claims.entries()], async ([i, claim]) => {
const { place } = await svc.savePlace(user.id, { collection_id: col.id, name: `Claim ${i}`, ...claim });
const row = await findRow(orm(), CollectionPlaces, { id: place!.id });
expect([row?.source_trip_id, row?.source_place_id], JSON.stringify(claim)).toEqual([null, null]);
}
return place ? await findRow(orm(), CollectionPlaces, { id: place.id }) : null;
});
rows.forEach((row, i) =>
expect([row?.source_trip_id, row?.source_place_id], JSON.stringify(claims[i])).toEqual([null, null]),
);
});
});
@@ -0,0 +1,93 @@
/**
* The pure half of the duplicate suggestions (PLC-13): which entries pair up,
* found by bucket and never by comparing every entry with every other, which
* facts differ, and the page cursor.
*/
import {
decodeDuplicatesCursor,
differingFields,
DUPLICATE_BUCKET_MAX,
encodeDuplicatesCursor,
findDuplicates,
pairKey,
type DuplicateCandidate,
} from '../../../../src/nest/places-library/place-duplicates.helpers';
import { COORD_DEDUP_TOLERANCE } from '@trek/shared';
import { describe, expect, it } from 'vitest';
const candidate = (key: string, extra: Partial<DuplicateCandidate> = {}): DuplicateCandidate => ({
key,
name: 'Café',
lat: 48.2,
lng: 16.3,
address: null,
category_id: null,
google_place_id: null,
google_ftid: null,
osm_id: null,
provider_ids: [],
...extra,
});
describe('place duplicates helpers', () => {
it('PDUP-001: pairs the same name within the tolerance, across a cell border too, and nothing farther', () => {
const edge = Math.floor(48.2 / COORD_DEDUP_TOLERANCE) * COORD_DEDUP_TOLERANCE;
const pairs = findDuplicates([
candidate('trip:1', { lat: edge - COORD_DEDUP_TOLERANCE / 4 }),
candidate('list:2', { name: ' CAFÉ ', lat: edge + COORD_DEDUP_TOLERANCE / 4 }),
candidate('list:3', { lat: 48.3 }),
candidate('list:4', { name: 'Bar' }),
candidate('list:5', { lat: null, lng: null }),
]);
expect(pairs.map((pair) => [pair.a.key, pair.b.key, pair.reasons])).toEqual([
['list:2', 'trip:1', ['name_nearby']],
]);
});
it('PDUP-002: pairs a shared provider id whatever the names and positions, once per pair with both reasons', () => {
const pairs = findDuplicates([
candidate('own:1', { provider_ids: ['g-1', 'node/2'] }),
candidate('trip:9', { name: 'Elsewhere', lat: 1, lng: 1, provider_ids: ['g-1'] }),
candidate('list:3', { provider_ids: ['g-1'] }),
]);
expect(pairs.map((pair) => pairKey(pair.a.key, pair.b.key))).toEqual([
'list:3|own:1',
'list:3|trip:9',
'own:1|trip:9',
]);
expect(pairs[0]?.reasons).toEqual(['provider_id', 'name_nearby']);
expect(pairs[1]?.reasons).toEqual(['provider_id']);
});
it('PDUP-003: leaves a bucket out that is too full to be a duplicate', () => {
const crowd = Array.from({ length: DUPLICATE_BUCKET_MAX + 1 }, (_, index) =>
candidate(`list:${index + 1}`, { provider_ids: ['chain'], lat: index, lng: index, name: `Shop ${index}` }),
);
expect(findDuplicates(crowd)).toEqual([]);
});
it('PDUP-004: names the facts two sides differ in', () => {
const a = candidate('trip:1', { address: 'Main 1', category_id: 2, google_place_id: 'g' });
expect(
differingFields(a, candidate('list:2', { address: ' main 1 ', category_id: 2, google_place_id: 'g' })),
).toEqual([]);
expect(differingFields(a, candidate('list:3', { name: 'Bar', lat: 50, osm_id: 'n' }))).toEqual([
'name',
'position',
'address',
'category',
'google_place_id',
'osm_id',
]);
expect(differingFields(candidate('a:1', { lat: null }), candidate('b:1', { lng: null }))).not.toContain('position');
expect(differingFields(candidate('a:1', { lat: null }), candidate('b:1'))).toContain('position');
});
it('PDUP-005: hands out a cursor it reads back, and refuses anything else', () => {
const cursor = encodeDuplicatesCursor('list:3|trip:9');
expect(decodeDuplicatesCursor(cursor)).toBe('list:3|trip:9');
expect(decodeDuplicatesCursor('nonsense')).toBeNull();
expect(decodeDuplicatesCursor(encodeDuplicatesCursor('list:3'))).toBeNull();
});
});
@@ -0,0 +1,69 @@
/**
* PlaceIdentitiesController over stub services: each route hands the user and
* its input to one service method and answers what it returns. Guards, pipes
* and the response contracts run in the e2e suite.
*/
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
import type { PlaceDuplicatesService } from '../../../../src/nest/places-library/place-duplicates.service';
import { PlaceIdentitiesController } from '../../../../src/nest/places-library/place-identities.controller';
import type { PlaceIdentitiesService } from '../../../../src/nest/places-library/place-identities.service';
import type { User } from '../../../../src/types';
import {
placesLibraryDuplicatesResponseSchema,
placesLibraryEntryResponseSchema,
placesLibraryMergeResponseSchema,
successResponseSchema,
} from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
const user = { id: 7, role: 'user', username: 'ann', email: 'ann@example.test' } as User;
const me = { id: 7, role: 'user' };
function controller(identities: Partial<PlaceIdentitiesService>, duplicates: Partial<PlaceDuplicatesService> = {}) {
return new PlaceIdentitiesController(
identities as unknown as PlaceIdentitiesService,
duplicates as unknown as PlaceDuplicatesService,
);
}
describe('PlaceIdentitiesController', () => {
it('PIDC-001: link and unlink hand the uses on with the user', async () => {
const answer = { entry: null };
const link = vi.fn().mockResolvedValue(answer);
const unlink = vi.fn().mockResolvedValue(answer);
const c = controller({ link, unlink });
const body = { uses: [{ kind: 'trip' as const, id: 3 }] };
expect(await c.link(user, body)).toBe(answer);
expect(await c.unlink(user, { kind: 'list', id: 4 })).toBe(answer);
expect(link).toHaveBeenCalledWith(me, body);
expect(unlink).toHaveBeenCalledWith(me, { kind: 'list', id: 4 });
});
it('PIDC-002: duplicates, dismiss, merge and undo reach their service methods', async () => {
const list = vi.fn().mockResolvedValue({ duplicates: [], next_cursor: null });
const dismiss = vi.fn().mockResolvedValue({ success: true });
const merge = vi.fn().mockResolvedValue({ merge_id: 2, entry: null });
const undoMerge = vi.fn().mockResolvedValue({ success: true });
const c = controller({ dismiss, merge, undoMerge }, { list });
await c.listDuplicates(user, { limit: 5 });
await c.dismiss(user, { a: 'trip:1', b: 'list:2' });
await c.merge(user, { leading: 'trip:1', other: 'list:2' });
await c.undoMerge(user, 2);
expect(list).toHaveBeenCalledWith(me, { limit: 5 });
expect(dismiss).toHaveBeenCalledWith(7, 'trip:1', 'list:2');
expect(merge).toHaveBeenCalledWith(me, 'trip:1', 'list:2');
expect(undoMerge).toHaveBeenCalledWith(me, 2);
});
it('PIDC-003: declares the shared response contracts', () => {
const proto = PlaceIdentitiesController.prototype;
const contract = (handler: unknown) => Reflect.getMetadata(RESPONSE_CONTRACT_KEY, handler as object) as unknown;
expect(contract(proto.link)).toBe(placesLibraryEntryResponseSchema);
expect(contract(proto.unlink)).toBe(placesLibraryEntryResponseSchema);
expect(contract(proto.listDuplicates)).toBe(placesLibraryDuplicatesResponseSchema);
expect(contract(proto.dismiss)).toBe(successResponseSchema);
expect(contract(proto.merge)).toBe(placesLibraryMergeResponseSchema);
expect(contract(proto.undoMerge)).toBe(successResponseSchema);
});
});
@@ -0,0 +1,138 @@
/**
* PlaceIdentitiesMcp (D5/PLC-13): the own-place, duplicate and merge tools
* over the same services as REST, with the addon gate and the scopes they
* need, and the nightly sweep. Taken from the container over a snapshot db.
*/
import { UserPlaces } from '../../../../src/db/entities/UserPlaces.entity';
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 { PlaceIdentitiesPruneJob } from '../../../../src/nest/places-library/place-identities-prune.job';
import { PlaceIdentitiesMcp } from '../../../../src/nest/places-library/place-identities.mcp';
import { PlaceIdentitiesService } from '../../../../src/nest/places-library/place-identities.service';
import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-library.module';
import { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { countRows } from '../../../helpers/factories/rows';
import { makeUserPlace } from '../../../helpers/factories/user-places';
import { 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';
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();
let t: TestModule;
let orm: TestOrm;
let mcp: PlaceIdentitiesMcp;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [PlacesLibraryModule] });
mcp = t.get(PlaceIdentitiesMcp);
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 }) {
return JSON.parse(result.content[0]?.text ?? '');
}
const options = (name: string) => {
const entry = getEntry(PlaceIdentitiesMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
describe('PlaceIdentitiesMcp', () => {
it('PID-MCP-001: links, unlinks, merges and undoes as REST does', async () => {
const linked = read(
await mcp.linkLibraryPlaces(
{
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
},
ctx(f.me.id),
),
);
expect(linked.entry.key).toBe(`own:${linked.entry.identity_id}`);
const out = read(await mcp.unlinkLibraryPlace({ kind: 'list', id: f.saved.pantheon.id }, ctx(f.me.id)));
expect(out.entry.key).toBe(`list:${f.saved.pantheon.id}`);
const page = read(await mcp.listLibraryDuplicates({}, ctx(f.me.id)));
expect(page.duplicates).toHaveLength(2);
const [pair] = page.duplicates;
const merged = read(await mcp.mergeLibraryPlaces({ leading: pair.a.key, other: pair.b.key }, ctx(f.me.id)));
expect(merged.merge_id).toBeGreaterThan(0);
expect(read(await mcp.undoLibraryMerge({ merge_id: merged.merge_id }, ctx(f.me.id)))).toEqual({ success: true });
expect(read(await mcp.dismissLibraryDuplicate({ a: pair.a.key, b: pair.b.key }, ctx(f.me.id)))).toEqual({
success: true,
});
await expect(
mcp.linkLibraryPlaces({ uses: [{ kind: 'trip', id: f.places.hidden.id }] }, ctx(f.me.id)),
).rejects.toThrow('Place not found');
});
it('PID-MCP-002: the tools are there only with Collections on, and for tokens that may', async () => {
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false);
expect(await options('mergeLibraryPlaces').when?.(ctx(1), mcp)).toBe(false);
enabled.mockResolvedValue(true);
expect(await options('mergeLibraryPlaces').when?.(ctx(1), mcp)).toBe(true);
const allowed = (name: string, scopes: string[]) => {
const access = options(name).access;
return typeof access === 'function' ? access({ userId: 1, scopes } as McpContext) : access;
};
for (const name of [
'linkLibraryPlaces',
'unlinkLibraryPlace',
'dismissLibraryDuplicate',
'mergeLibraryPlaces',
'undoLibraryMerge',
]) {
expect(allowed(name, ['collections:write', 'trips:read'])).toBe(true);
expect(allowed(name, ['collections:read', 'trips:read'])).toBe(false);
expect(options(name).annotations?.readOnlyHint).not.toBe(true);
}
expect(allowed('listLibraryDuplicates', ['collections:read', 'trips:read'])).toBe(true);
expect(allowed('listLibraryDuplicates', ['collections:read'])).toBe(false);
expect(options('listLibraryDuplicates').annotations).toMatchObject({ readOnlyHint: true });
});
it('PID-MCP-003: the nightly sweep removes own places nothing holds, and keeps going on a failure', async () => {
await makeUserPlace(orm, f.me.id);
const job = t.get(PlaceIdentitiesPruneJob);
await job.tick();
expect(await countRows(orm, UserPlaces, {})).toBe(0);
vi.spyOn(t.get(PlaceIdentitiesService), 'pruneAll').mockRejectedValue(new Error('boom'));
await expect(job.tick()).resolves.toBeUndefined();
const registrar = t.get(CronRegistrarService);
vi.spyOn(registrar, 'isEnabled').mockReturnValue(true);
const register = vi.spyOn(registrar, 'register').mockImplementation(() => undefined);
job.onApplicationBootstrap();
expect(register).toHaveBeenCalledWith('place-identities-prune', '20 4 * * *', expect.any(Function));
});
});
@@ -0,0 +1,283 @@
/**
* PlaceIdentitiesService and PlaceDuplicatesService (D5/D6, PLC-13) over the
* real repositories on a migrated test db: putting uses together as an own
* place, taking one out, what is left once a trip or list is out of reach,
* merging two entries and undoing it, the duplicate suggestions and turning
* one down. Only the trip permission check is replaced, as in the library
* suite. No trip place and no saved place may change along the way.
*/
import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity';
import { Places } from '../../../../src/db/entities/Places.entity';
import { TripMembers } from '../../../../src/db/entities/TripMembers.entity';
import { Trips } from '../../../../src/db/entities/Trips.entity';
import { UserPlaceLinks } from '../../../../src/db/entities/UserPlaceLinks.entity';
import { UserPlaceMerges } from '../../../../src/db/entities/UserPlaceMerges.entity';
import { UserPlaces } from '../../../../src/db/entities/UserPlaces.entity';
import { DomainError } from '../../../../src/nest/common/domain-error';
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
import { PlaceDuplicatesService } from '../../../../src/nest/places-library/place-duplicates.service';
import { PlaceIdentitiesService } from '../../../../src/nest/places-library/place-identities.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 { countRows, deleteRows, findRows, updateRows } from '../../../helpers/factories/rows';
import { linkUserPlace, makeUserPlace } from '../../../helpers/factories/user-places';
import { 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 identities: PlaceIdentitiesService;
let duplicates: PlaceDuplicatesService;
let library: PlacesLibraryService;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [PlacesLibraryModule] });
identities = t.get(PlaceIdentitiesService);
duplicates = t.get(PlaceDuplicatesService);
library = t.get(PlacesLibraryService);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
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 keysOf = async (userId: number) => (await library.list(as(userId), {})).entries.map((entry) => entry.key);
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');
}
/** The trip places and saved places as they are, to prove nothing of them changed. */
async function sharedRows() {
const places = await findRows(orm, Places, {}, { id: 'asc' });
const saved = await findRows(orm, CollectionPlaces, {}, { id: 'asc' });
return JSON.stringify([
places.map((p) => [p.id, p.name, p.lat, p.lng, p.updated_at]),
saved.map((s) => [s.id, s.name, s.lat, s.lng, s.updated_at]),
]);
}
describe('PlaceIdentitiesService.link and unlink', () => {
it('PID-001: puts a trip place and a saved place together as one own place named after the first', async () => {
const before = await sharedRows();
const { entry } = await identities.link(as(f.me.id), {
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
});
expect(entry).toMatchObject({ name: 'Forum Romanum', lat: 41.8925, lng: 12.4853 });
expect(entry?.key).toBe(`own:${entry?.identity_id}`);
expect(entry?.origins.map((origin) => [origin.kind, origin.linked])).toEqual([
['trip', true],
['list', true],
]);
const keys = await keysOf(f.me.id);
expect(keys).toContain(entry?.key);
expect(keys).not.toContain(`trip:${f.places.forum.id}`);
expect(keys).not.toContain(`list:${f.saved.pantheon.id}`);
expect(keys).toHaveLength(9);
expect(await sharedRows()).toBe(before);
// Only `me` sees it as one place; the friend's view stays as it was.
expect(await keysOf(f.friend.id)).toContain(`trip:${f.places.forum.id}`);
});
it('PID-002: refuses a use out of reach or an own place of someone else, and writes nothing', async () => {
const notFound = { status: 404, message: 'Place not found' };
expect(await refusal(identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.hidden.id }] }))).toEqual(
notFound,
);
expect(await refusal(identities.link(as(f.me.id), { uses: [{ kind: 'list', id: f.saved.secret.id }] }))).toEqual(
notFound,
);
const theirs = await makeUserPlace(orm, f.stranger.id);
expect(
await refusal(
identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.cafe.id }], identity_id: theirs.id }),
),
).toEqual(notFound);
expect(await countRows(orm, UserPlaceLinks, {})).toBe(0);
expect(await countRows(orm, UserPlaces, { user: f.me.id })).toBe(0);
});
it('PID-003: joins an existing own place, and one left empty by the move goes', async () => {
const first = await identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.forum.id }] });
const second = await identities.link(as(f.me.id), { uses: [{ kind: 'list', id: f.saved.pantheon.id }] });
const joined = await identities.link(as(f.me.id), {
uses: [{ kind: 'list', id: f.saved.pantheon.id }],
identity_id: first.entry?.identity_id ?? 0,
});
expect(joined.entry?.origins).toHaveLength(2);
expect(await countRows(orm, UserPlaces, { id: second.entry?.identity_id ?? 0 })).toBe(0);
});
it('PID-004: takes one use out again; the last one out removes the own place', async () => {
const { entry } = await identities.link(as(f.me.id), {
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
});
const out = await identities.unlink(as(f.me.id), { kind: 'list', id: f.saved.pantheon.id });
expect(out.entry?.key).toBe(`list:${f.saved.pantheon.id}`);
expect(await refusal(identities.unlink(as(f.me.id), { kind: 'list', id: f.saved.pantheon.id }))).toEqual({
status: 404,
message: 'This place is not part of one of your own places',
});
expect(await refusal(identities.unlink(as(f.me.id), { kind: 'trip', id: f.places.hidden.id }))).toMatchObject({
status: 404,
});
const last = await identities.unlink(as(f.me.id), { kind: 'trip', id: f.places.forum.id });
expect(last.entry?.key).toBe(`trip:${f.places.forum.id}`);
expect(await countRows(orm, UserPlaces, { id: entry?.identity_id ?? 0 })).toBe(0);
});
it('PID-005: an own place shows only the uses still in reach, none once all are gone, and the sweep removes it', async () => {
const { entry } = await identities.link(as(f.me.id), {
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
});
await deleteRows(orm, TripMembers, { trip: f.rome.id, user: f.me.id });
const page = await library.list(as(f.me.id), {});
const own = page.entries.find((candidate) => candidate.key === entry?.key);
expect(own?.origins.map((origin) => origin.kind)).toEqual(['list']);
const alone = await identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.cafe.id }] });
await deleteRows(orm, Trips, { id: f.alps.id });
expect(await keysOf(f.me.id)).not.toContain(alone.entry?.key);
expect(await identities.pruneAll()).toBe(1);
expect(await countRows(orm, UserPlaces, { id: alone.entry?.identity_id ?? 0 })).toBe(0);
expect(await countRows(orm, UserPlaces, { id: entry?.identity_id ?? 0 })).toBe(1);
});
});
describe('PlaceIdentitiesService.merge and undo', () => {
it('PID-010: merges two entries into one own place with the leading name, and undoes it', async () => {
const before = await sharedRows();
const cafeKey = `trip:${f.places.cafe.id}`;
const conflictingKey = `list:${f.saved.conflicting.id}`;
const merged = await identities.merge(as(f.me.id), cafeKey, conflictingKey);
expect(merged.entry).toMatchObject({ name: 'Café Central', address: 'Herrengasse 14, Wien' });
expect(
merged.entry?.origins.map((origin) => (origin.kind === 'trip' ? origin.place_id : origin.collection_place_id)),
).toEqual([f.places.cafe.id, f.saved.savedCafe.id, f.saved.conflicting.id]);
const keys = await keysOf(f.me.id);
expect(keys).not.toContain(cafeKey);
expect(keys).not.toContain(conflictingKey);
expect(keys).toHaveLength(9);
expect(await sharedRows()).toBe(before);
expect(await identities.undoMerge(as(f.me.id), merged.merge_id)).toEqual({ success: true });
expect(await keysOf(f.me.id)).toHaveLength(10);
expect(await countRows(orm, UserPlaceMerges, {})).toBe(0);
expect(await refusal(identities.undoMerge(as(f.me.id), merged.merge_id))).toEqual({
status: 404,
message: 'Merge not found',
});
expect(await sharedRows()).toBe(before);
});
it('PID-011: refuses one entry twice, a key no entry has and a merge of someone else', async () => {
const key = `trip:${f.places.cafe.id}`;
expect(await refusal(identities.merge(as(f.me.id), key, key))).toEqual({
status: 400,
message: 'Pick two different places to merge',
});
expect(await refusal(identities.merge(as(f.me.id), key, `trip:${f.places.hidden.id}`))).toEqual({
status: 404,
message: 'Place not found',
});
expect(await refusal(identities.merge(as(f.me.id), key, 'nonsense'))).toMatchObject({ status: 404 });
const merged = await identities.merge(as(f.me.id), key, `list:${f.saved.lunch.id}`);
expect(await refusal(identities.undoMerge(as(f.friend.id), merged.merge_id))).toMatchObject({ status: 404 });
});
it('PID-012: refuses while an own place still holds a use the user can no longer open', async () => {
const own = await makeUserPlace(orm, f.me.id, { name: 'Mixed' });
await linkUserPlace(orm, f.me.id, own.id, { collectionPlace: f.saved.namesake.id });
await linkUserPlace(orm, f.me.id, own.id, { place: f.places.hidden.id });
expect(await refusal(identities.merge(as(f.me.id), `own:${own.id}`, `trip:${f.places.museum.id}`))).toEqual({
status: 403,
message: 'One of these places holds a trip place or saved place you can no longer open',
});
});
});
describe('PlaceDuplicatesService', () => {
it('PID-020: suggests the same name a few metres apart, says what differs, and pages', async () => {
const page = await duplicates.list(as(f.me.id), {});
const pairs = page.duplicates.map((pair) => new Set([pair.a.key, pair.b.key]));
expect(pairs).toEqual(
expect.arrayContaining([
new Set([`trip:${f.places.cafe.id}`, `list:${f.saved.conflicting.id}`]),
new Set([`trip:${f.places.museum.id}`, `list:${f.saved.namesake.id}`]),
]),
);
expect(page.duplicates).toHaveLength(2);
const cafe = page.duplicates.find((pair) => [pair.a.key, pair.b.key].includes(`list:${f.saved.conflicting.id}`));
expect(cafe).toMatchObject({ reasons: ['name_nearby'], can_merge: true });
expect(cafe?.differing).toEqual(expect.arrayContaining(['address', 'google_place_id']));
expect(cafe?.differing).not.toContain('name');
const first = await duplicates.list(as(f.me.id), { limit: 1 });
expect(first.duplicates).toHaveLength(1);
const second = await duplicates.list(as(f.me.id), { cursor: first.next_cursor ?? '' });
expect(second.duplicates).toHaveLength(1);
expect(second.next_cursor).toBeNull();
expect(await refusal(duplicates.list(as(f.me.id), { cursor: 'nonsense' }))).toMatchObject({ status: 400 });
});
it('PID-021: a turned-down pair does not come back; a shared provider id is a reason of its own', async () => {
await identities.dismiss(f.me.id, `list:${f.saved.namesake.id}`, `trip:${f.places.museum.id}`);
await identities.dismiss(f.me.id, `trip:${f.places.museum.id}`, `list:${f.saved.namesake.id}`);
expect(await refusal(identities.dismiss(f.me.id, 'own:1', 'own:1'))).toMatchObject({ status: 400 });
const page = await duplicates.list(as(f.me.id), {});
expect(page.duplicates).toHaveLength(1);
await updateRows(orm, CollectionPlaces, { id: f.saved.lunch.id }, { osm_id: 'node/1' });
await updateRows(orm, Places, { id: f.places.forum.id }, { osm_id: 'node/1' });
const shared = await duplicates.list(as(f.me.id), {});
const byProvider = shared.duplicates.find((pair) => pair.reasons.includes('provider_id'));
expect(new Set([byProvider?.a.key, byProvider?.b.key])).toEqual(
new Set([`list:${f.saved.lunch.id}`, `trip:${f.places.forum.id}`]),
);
expect(byProvider?.differing).toEqual(expect.arrayContaining(['name', 'position']));
});
it('PID-022: cannot be merged while one side holds a use out of reach', async () => {
const own = await makeUserPlace(orm, f.me.id, { name: 'Museum', lat: 47.2681, lng: 11.3933 });
await linkUserPlace(orm, f.me.id, own.id, { collectionPlace: f.saved.namesake.id });
await linkUserPlace(orm, f.me.id, own.id, { place: f.places.hidden.id });
const page = await duplicates.list(as(f.me.id), {});
const museum = page.duplicates.find((pair) => [pair.a.key, pair.b.key].includes(`own:${own.id}`));
expect(museum?.can_merge).toBe(false);
});
});
@@ -4,14 +4,22 @@
*/
import type {
LibraryCollectionPlaceRow,
LibraryIdentityRow,
LibraryTripPlaceRow,
LibraryUseRow,
} from '../../../../src/db/repositories/PlacesLibrary.repository';
import {
anchorOfIdentity,
anchorOfKey,
decodeLibraryCursor,
encodeLibraryCursor,
entryKey,
entryOf,
firstUseOf,
fromListOf,
groupBy,
identityOfAnchor,
leadOf,
ratingOf,
rowsByAnchor,
} from '../../../../src/nest/places-library/places-library.helpers';
@@ -27,6 +35,9 @@ const facts = {
description: null,
website: null,
phone: null,
google_place_id: null,
google_ftid: null,
osm_id: null,
category_id: 3,
category_name: 'Food',
category_color: '#f00',
@@ -42,7 +53,7 @@ const trip: LibraryTripPlaceRow = {
trip_end: null,
trip_owner_id: 1,
};
const saved = (id: number, grouped: number | null, extra: Partial<LibraryCollectionPlaceRow> = {}) =>
const saved = (id: number, extra: Partial<LibraryCollectionPlaceRow> = {}) =>
({
...facts,
id,
@@ -50,7 +61,6 @@ const saved = (id: number, grouped: number | null, extra: Partial<LibraryCollect
collection_name: 'Food',
status: 'odd-status',
name: `Saved ${id}`,
grouped_place_id: grouped,
category_id: null,
category_name: null,
...extra,
@@ -59,9 +69,20 @@ const saved = (id: number, grouped: number | null, extra: Partial<LibraryCollect
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('names an entry by its own place, its trip place or its saved place, and reads the key back', () => {
expect(entryKey(10 * 4 + 1)).toBe('trip:10');
expect(entryKey(4 * 4 + 2)).toBe('list:4');
expect(entryKey(anchorOfIdentity(7))).toBe('own:7');
expect(anchorOfKey('trip:10')).toBe(41);
expect(anchorOfKey('list:4')).toBe(18);
expect(anchorOfKey('own:7')).toBe(31);
for (const bad of ['trip:0', 'trip:01', 'place:3', 'own:', 'own:1e3', 'list:99999999999999999']) {
expect(anchorOfKey(bad)).toBeNull();
}
expect(identityOfAnchor(31)).toBe(7);
expect(identityOfAnchor(41)).toBeNull();
expect(fromListOf('trip')).toBe(0);
expect(fromListOf('list')).toBe(1);
});
it('hands out a cursor that only its own sort reads back', () => {
@@ -85,25 +106,69 @@ describe('places-library helpers', () => {
});
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 uses: LibraryUseRow[] = [
{ anchor_key: 41, from_list: 0, use_id: 10, linked: false },
{ anchor_key: 41, from_list: 1, use_id: 6, linked: false },
{ anchor_key: 30, from_list: 1, use_id: 7, linked: false },
];
const rows = rowsByAnchor([41, 30, 398, 170], uses, [trip], [saved(6, { image_url: '/u/6.jpg' }), saved(7)], []);
expect(rows.map((row) => row.anchor)).toEqual([41, 30]);
const [first, second] = rows;
if (!first || !second) throw new Error('expected two entries');
const grouped = entryOf(first, access);
expect(grouped).toMatchObject({
key: 'trip:10',
identity_id: null,
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 }),
expect.objectContaining({ kind: 'trip', can_edit: true, read_only: false, linked: false }),
expect.objectContaining({ kind: 'list', collection_place_id: 6, status: 'idea', can_edit: false, linked: false }),
]);
const alone = entryOf(second, access);
expect(alone).toMatchObject({ key: 'list:7', name: 'Saved 7', category: null, image_url: null });
});
it('shows an own place under its own name, with every trip and list origin, and leaves a pruned one out', () => {
const own: LibraryIdentityRow = {
id: 5,
name: 'My café',
address: 'Somewhere 1',
lat: 9,
lng: 8,
google_place_id: null,
google_ftid: null,
osm_id: null,
updated_at: '2026-11-02 08:00:00',
category_id: null,
category_name: null,
category_color: null,
category_icon: null,
};
const other = { ...trip, id: 11, trip_id: 6, trip_title: 'Rome' };
const uses: LibraryUseRow[] = [
{ anchor_key: 23, from_list: 0, use_id: 10, linked: true },
{ anchor_key: 23, from_list: 0, use_id: 11, linked: true },
{ anchor_key: 23, from_list: 1, use_id: 6, linked: false },
{ anchor_key: 27, from_list: 1, use_id: 7, linked: true },
];
const rows = rowsByAnchor([23, 27], uses, [trip, other], [saved(6), saved(7)], [own]);
expect(rows).toHaveLength(1);
const [only] = rows;
if (!only) throw new Error('expected one entry');
expect(leadOf(only)).toBe(own);
expect(firstUseOf(only)).toBe(trip);
const shown = entryOf(only, access);
expect(shown).toMatchObject({ key: 'own:5', identity_id: 5, name: 'My café', lat: 9, category: null });
expect(shown.origins.map((origin) => [origin.kind, origin.linked])).toEqual([
['trip', true],
['trip', true],
['list', false],
]);
});
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([
@@ -12,7 +12,8 @@ import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-
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 { oneByOne } from '../../../helpers/one-by-one';
import { cafeTie, 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';
@@ -97,6 +98,7 @@ describe('PlacesLibraryService.list', () => {
place_id: f.places.cafe.id,
can_edit: true,
read_only: false,
linked: false,
},
{
kind: 'list',
@@ -105,6 +107,7 @@ describe('PlacesLibraryService.list', () => {
collection_place_id: f.saved.savedCafe.id,
status: 'want',
can_edit: true,
linked: false,
},
]);
// The provider id alone is enough, whatever the copy is called.
@@ -142,8 +145,7 @@ describe('PlacesLibraryService.list', () => {
]);
// 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}`,
...cafeTie(f),
`list:${f.saved.hiddenCopy.id}`,
`list:${f.saved.lunch.id}`,
`list:${f.saved.namesake.id}`,
@@ -181,17 +183,15 @@ describe('PlacesLibraryService.list', () => {
});
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)));
const pageThrough = async (sort: 'name' | 'updated', cursor?: string, round = 0): Promise<string[]> => {
const page = await library.list(as(f.me.id), { sort, limit: 3, ...(cursor ? { cursor } : {}) });
if (!page.next_cursor || round >= 10) return keys(page);
return [...keys(page), ...(await pageThrough(sort, page.next_cursor, round + 1))];
};
const seen = await oneByOne(['name', 'updated'] as const, (sort) => pageThrough(sort));
for (const keysSeen of seen) {
expect(keysSeen).toHaveLength(10);
expect(new Set(keysSeen)).toEqual(new Set(expectedKeysByName(f)));
}
});
@@ -0,0 +1,56 @@
/**
* TripCollectionsController over a stub service: each route hands the trip
* the guard resolved, the user and its input (and the X-Socket-Id on writes)
* to one service method. Guards, pipes and contracts run in the e2e suite.
*/
import type { TripAccess } from '../../../../src/db/repositories/Trips.repository';
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
import type { TripWriter } from '../../../../src/nest/common/trip-writer';
import { TRIP_PERMISSION_KEY } from '../../../../src/nest/permissions/trip-access.guard';
import { TripCollectionsController } from '../../../../src/nest/trip-collections/trip-collections.controller';
import type { TripCollectionsService } from '../../../../src/nest/trip-collections/trip-collections.service';
import type { User } from '../../../../src/types';
import { tripCollectionLayerResponseSchema, tripCollectionLinksResponseSchema } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
const user = { id: 7, role: 'user', username: 'ann', email: 'ann@example.test' } as User;
const trip = { id: 4, user_id: 7 } as TripAccess;
const answer = { links: [], can_link: true };
describe('TripCollectionsController', () => {
it('TCLC-001: reads the links and the map layer of the trip for the user', async () => {
const list = vi.fn().mockResolvedValue(answer);
const layer = vi.fn().mockResolvedValue({ places: [] });
const c = new TripCollectionsController({ list, layer } as unknown as TripCollectionsService);
expect(await c.list(user, trip)).toBe(answer);
expect(await c.layer(user, trip)).toEqual({ places: [] });
expect(list).toHaveBeenCalledWith(4, user);
expect(layer).toHaveBeenCalledWith(4, user);
});
it('TCLC-002: links and unlinks with a REST writer that carries the socket id', async () => {
const writer = { userId: 7 } as TripWriter;
const restWriter = vi.fn().mockReturnValue(writer);
const link = vi.fn().mockResolvedValue(answer);
const unlink = vi.fn().mockResolvedValue(answer);
const c = new TripCollectionsController({ restWriter, link, unlink } as unknown as TripCollectionsService);
await c.link(user, trip, { collection_id: 9 }, 'sock-2');
await c.unlink(user, trip, 9, 'sock-2');
expect(restWriter).toHaveBeenCalledWith(4, user, 'sock-2');
expect(link).toHaveBeenCalledWith(4, 9, writer);
expect(unlink).toHaveBeenCalledWith(4, 9, writer);
});
it('TCLC-003: the writes take place_edit, and every route declares its contract', () => {
const proto = TripCollectionsController.prototype;
const meta = (key: string, handler: unknown) => Reflect.getMetadata(key, handler as object) as unknown;
expect(meta(TRIP_PERMISSION_KEY, proto.link)).toBe('place_edit');
expect(meta(TRIP_PERMISSION_KEY, proto.unlink)).toBe('place_edit');
expect(meta(TRIP_PERMISSION_KEY, proto.list)).toBeUndefined();
expect(meta(RESPONSE_CONTRACT_KEY, proto.list)).toBe(tripCollectionLinksResponseSchema);
expect(meta(RESPONSE_CONTRACT_KEY, proto.link)).toBe(tripCollectionLinksResponseSchema);
expect(meta(RESPONSE_CONTRACT_KEY, proto.unlink)).toBe(tripCollectionLinksResponseSchema);
expect(meta(RESPONSE_CONTRACT_KEY, proto.layer)).toBe(tripCollectionLayerResponseSchema);
});
});
@@ -0,0 +1,89 @@
/**
* TripCollectionsMcp (PLC-15/PLC-16): the same service, permission and list
* checks as REST, the addon gate and the scopes. From the container over a
* snapshot db; broadcasts go to the FakeRealtimeService.
*/
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 { TripCollectionsMcp } from '../../../../src/nest/trip-collections/trip-collections.mcp';
import { TripCollectionsModule } from '../../../../src/nest/trip-collections/trip-collections.module';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { 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: TripCollectionsMcp;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [TripCollectionsModule] });
mcp = t.get(TripCollectionsMcp);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
t.realtime.reset();
f = await seedLibrary(orm);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
const read = (result: { content: Array<{ type: string; text: string }> }) => JSON.parse(result.content[0]?.text ?? '');
const options = (name: string) => {
const entry = getEntry(TripCollectionsMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
describe('TripCollectionsMcp', () => {
it('TCL-MCP-001: links, reads, maps and unlinks a list, with the event marked as MCP', async () => {
const input = { tripId: f.alps.id, collection_id: f.lists.food.id };
expect(read(await mcp.linkCollectionToTrip(input, ctx(f.me.id))).links).toHaveLength(1);
expect(t.realtime.broadcastMock).toHaveBeenCalledWith(f.alps.id, 'tripCollections:changed', { _source: 'mcp' });
expect(read(await mcp.listTripCollections({ tripId: f.alps.id }, ctx(f.me.id))).can_link).toBe(true);
expect(read(await mcp.getTripCollectionPlaces({ tripId: f.alps.id }, ctx(f.me.id))).places.length).toBeGreaterThan(
0,
);
expect(read(await mcp.unlinkCollectionFromTrip(input, ctx(f.me.id))).links).toEqual([]);
});
it('TCL-MCP-002: refuses a trip out of reach and a list the caller cannot see', async () => {
await expect(mcp.listTripCollections({ tripId: f.elsewhere.id }, ctx(f.me.id))).rejects.toThrow();
await expect(
mcp.linkCollectionToTrip({ tripId: f.alps.id, collection_id: f.lists.secrets.id }, ctx(f.me.id)),
).rejects.toThrow('Collection not found');
});
it('TCL-MCP-003: there only with Collections on, and for tokens that may', async () => {
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false);
expect(await options('linkCollectionToTrip').when?.(ctx(1), mcp)).toBe(false);
enabled.mockResolvedValue(true);
expect(await options('linkCollectionToTrip').when?.(ctx(1), mcp)).toBe(true);
const allowed = (name: string, scopes: string[]) => {
const access = options(name).access;
return typeof access === 'function' ? access({ userId: 1, scopes } as McpContext) : access;
};
for (const name of ['linkCollectionToTrip', 'unlinkCollectionFromTrip']) {
expect(allowed(name, ['places:write', 'collections:read'])).toBe(true);
expect(allowed(name, ['places:read', 'collections:read'])).toBe(false);
}
for (const name of ['listTripCollections', 'getTripCollectionPlaces']) {
expect(allowed(name, ['trips:read', 'collections:read'])).toBe(true);
expect(allowed(name, ['trips:read'])).toBe(false);
expect(options(name).annotations).toMatchObject({ readOnlyHint: true });
}
});
});
@@ -0,0 +1,138 @@
/**
* TripCollectionsService (PLC-15/PLC-16) over the real repository on a
* migrated test db: linking and unlinking a list, who sees a linked list
* (only someone the list is open to), the permission and the list check, the
* saved places for the trip map with whether the trip already has them, and
* what a deleted list leaves. Broadcasts go to a FakeRealtimeService.
*/
import { Collections } from '../../../../src/db/entities/Collections.entity';
import { TripCollectionLinks } from '../../../../src/db/entities/TripCollectionLinks.entity';
import { DomainError } from '../../../../src/nest/common/domain-error';
import { restTripWriter } from '../../../../src/nest/common/trip-writer';
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
import { TripCollectionsModule } from '../../../../src/nest/trip-collections/trip-collections.module';
import { TripCollectionsService } from '../../../../src/nest/trip-collections/trip-collections.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { addCollectionMember } from '../../../helpers/factories/collections';
import { countRows, deleteRows } from '../../../helpers/factories/rows';
import { addTripMember } from '../../../helpers/factories/trips';
import { 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 service: TripCollectionsService;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [TripCollectionsModule] });
service = t.get(TripCollectionsService);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
t.realtime.reset();
f = await seedLibrary(orm);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const reader = (id: number) => ({ id, role: 'user' });
const writer = (id: number) => restTripWriter(t.realtime, f.alps.id, reader(id), 'sock-1');
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('TripCollectionsService', () => {
it('TCL-001: links a list once, says so to the trip, and lists it with the role and count', async () => {
const broadcast = t.realtime.broadcastMock;
const answer = await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
expect(answer).toEqual({
links: [
expect.objectContaining({
collection_id: f.lists.food.id,
name: 'Food',
role: 'owner',
place_count: 6,
linked_by: f.me.id,
}),
],
can_link: true,
});
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
expect(broadcast).toHaveBeenCalledTimes(1);
expect(broadcast).toHaveBeenCalledWith(f.alps.id, 'tripCollections:changed', {}, 'sock-1');
expect(await countRows(orm, TripCollectionLinks, {})).toBe(1);
});
it('TCL-002: a member sees a linked list only while it is open to them', async () => {
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
expect(await refusal(service.list(f.alps.id, reader(f.friend.id)))).toMatchObject({ status: 404 });
await addTripMember(orm, f.alps.id, f.friend.id);
expect((await service.list(f.alps.id, reader(f.friend.id))).links).toEqual([]);
expect((await service.layer(f.alps.id, reader(f.friend.id))).places).toEqual([]);
await addCollectionMember(orm, f.lists.food.id, f.friend.id, { role: 'viewer', status: 'accepted' });
expect((await service.list(f.alps.id, reader(f.friend.id))).links).toEqual([
expect.objectContaining({ collection_id: f.lists.food.id, role: 'viewer' }),
]);
});
it('TCL-003: refuses a list the writer cannot see, and a writer without place_edit', async () => {
expect(await refusal(service.link(f.alps.id, f.lists.secrets.id, writer(f.me.id)))).toEqual({
status: 404,
message: 'Collection not found',
});
await addTripMember(orm, f.alps.id, f.friend.id);
vi.spyOn(t.get(PermissionsService), 'checkPermission').mockResolvedValue(false);
expect(await refusal(service.link(f.alps.id, f.lists.sights.id, writer(f.friend.id)))).toMatchObject({
status: 403,
});
expect((await service.list(f.alps.id, reader(f.friend.id))).can_link).toBe(false);
expect(await countRows(orm, TripCollectionLinks, {})).toBe(0);
});
it('TCL-004: hands the map the saved places with a position and says which the trip already has', async () => {
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
const { places } = await service.layer(f.alps.id, reader(f.me.id));
const byId = new Map(places.map((place) => [place.id, place]));
expect(byId.has(f.saved.savedMuseum.id)).toBe(false);
expect(byId.get(f.saved.savedCafe.id)).toMatchObject({ in_trip: true, trip_place_id: f.places.cafe.id });
expect(byId.get(f.saved.namesake.id)).toMatchObject({ in_trip: true, trip_place_id: f.places.museum.id });
// A name of its own, or another provider id, is another place, whatever source it names.
expect(byId.get(f.saved.lunch.id)).toMatchObject({ in_trip: false, trip_place_id: null });
expect(byId.get(f.saved.conflicting.id)).toMatchObject({ in_trip: false });
expect(byId.get(f.saved.hiddenCopy.id)).toMatchObject({ in_trip: false, collection_id: f.lists.food.id });
});
it('TCL-005: unlinks, refuses a list that is not linked, and a deleted list takes its link along', async () => {
const broadcast = t.realtime.broadcastMock;
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
expect((await service.unlink(f.alps.id, f.lists.food.id, writer(f.me.id))).links).toEqual([]);
expect(broadcast).toHaveBeenCalledTimes(2);
expect(await refusal(service.unlink(f.alps.id, f.lists.food.id, writer(f.me.id)))).toEqual({
status: 404,
message: 'This list is not linked to the trip',
});
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
await deleteRows(orm, Collections, { id: f.lists.food.id });
expect(await countRows(orm, TripCollectionLinks, {})).toBe(0);
});
});