Files
TREK/server/tests/e2e/place-copies.e2e.test.ts
T
Maurice 783c98f41e feat(places): one vote per person across copies, copies stay in step
A vote belongs to its person: cast or taken back on one copy of a place, it
lands on every copy of that place in the lists and trips the person may vote
on, in one transaction. A pass on the first start carries the existing votes
over, and whoever joins a list or a trip brings their latest vote onto its
copies of the places they voted on elsewhere, as inserts that never
overwrite.

An edit of the general facts of a place (name, description, address,
position, category, picture, website, phone) on a trip place or a saved
place is made on every other copy of it the editor may edit, with a history
entry per copy and an announcement per trip and list. Notes, tags, status
and votes stay with each copy, and a copy the editor may not edit is
skipped. REST and MCP take the same path; a token reaches only the kinds of
copies it holds write scope for.

The entry rating names its voters, the library list filters by a lowest
average vote and sorts by rating, and the tab counts honour the filter.
2026-11-29 23:36:43 +00:00

230 lines
10 KiB
TypeScript

/**
* The copies of a place stay in step, end to end on the whole app (buildApp,
* the real guards and a migrated temp database; in the Postgres lane on
* Postgres too): an edit of the general facts of a place on a trip place or a
* saved place is made on the editor's other copies of it they may edit, with
* a history entry per copy and an announcement per trip and list, while
* notes, status and the response stay each copy's own. A copy the editor may
* not edit is skipped, and an MCP token reaches only the kinds it may write.
*/
import { buildApp } from '../../src/bootstrap';
import { Categories } from '../../src/db/entities/Categories.entity';
import { CollectionPlaces } from '../../src/db/entities/CollectionPlaces.entity';
import { PlaceChangeLog } from '../../src/db/entities/PlaceChangeLog.entity';
import { Places } from '../../src/db/entities/Places.entity';
import type { McpContext } from '../../src/nest-mcp';
import { CollectionsMcp } from '../../src/nest/collections/collections.mcp';
import { withRequestContext } from '../../src/nest/database/request-context';
import { PlacesMcp } from '../../src/nest/places/places.mcp';
import { addCollectionMember, makeCollection, makeCollectionPlace } from '../helpers/factories/collections';
import { makePlace } from '../helpers/factories/places';
import { countRows, findRow, findRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime';
import { resetRateLimits } from '../helpers/test-db';
import { sessionCookie } from './harness';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
let app: INestApplication;
let server: Server;
let orm: MikroORM;
let realtime: RealtimeSpies;
const COLLECTIONS = '/api/addons/collections';
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
async function tripPlace(id: number) {
return findRow(orm, Places, { id });
}
async function savedPlace(id: number) {
return findRow(orm, CollectionPlaces, { id });
}
/**
* `me` owns the trip Alps with the place Café and the list Food with a saved
* copy of Café that came from it, so All places shows `me` the two as one
* place. `other` owns the list Theirs with a copy of the same Café, on which
* `me` is a viewer.
*/
async function seed() {
const { user: me } = await makeUser(orm);
const { user: other } = await makeUser(orm);
const alps = await makeTrip(orm, me.id, { title: 'Alps' });
const cafe = await makePlace(orm, alps.id, {
name: 'Café',
lat: 48.2,
lng: 16.3,
google_place_id: 'g-cafe',
notes: 'trip note',
});
const food = await makeCollection(orm, me.id, { name: 'Food' });
const saved = await makeCollectionPlace(orm, food.id, me.id, {
name: 'Café',
lat: 48.2,
lng: 16.3,
google_place_id: 'g-cafe',
source_trip_id: alps.id,
source_place_id: cafe.id,
notes: 'list note',
});
const theirs = await makeCollection(orm, other.id, { name: 'Theirs' });
await addCollectionMember(orm, theirs.id, me.id, { role: 'viewer' });
const foreign = await makeCollectionPlace(orm, theirs.id, other.id, {
name: 'Café',
lat: 48.2,
lng: 16.3,
google_place_id: 'g-cafe',
source_trip_id: alps.id,
source_place_id: cafe.id,
});
return { me, other, alps, cafe, food, saved, theirs, foreign };
}
beforeAll(async () => {
app = await buildApp();
server = app.getHttpServer() as Server;
orm = app.get(MikroORM);
await setAddonEnabled(orm, 'collections', true);
}, 60_000);
beforeEach(async () => {
await resetRateLimits(app);
realtime = spyOnRealtime(app);
});
afterAll(async () => {
await app?.close();
});
describe('an edit on one copy is made on the other copies the editor may edit', () => {
it('a trip place edit reaches the saved copy, with its own history entry and the list told', async () => {
const s = await seed();
const res = await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}`)
.set(as(s.me.id))
.set('X-Socket-Id', '7')
.send({ name: 'Café Central', address: 'Herrengasse 14', notes: 'new trip note' });
expect(res.status).toBe(200);
expect(res.body.place).toMatchObject({ id: s.cafe.id, name: 'Café Central', address: 'Herrengasse 14' });
const saved = await savedPlace(s.saved.id);
expect(saved).toMatchObject({ name: 'Café Central', address: 'Herrengasse 14', notes: 'list note' });
// A copy the editor may only view keeps what it had.
expect(await savedPlace(s.foreign.id)).toMatchObject({ name: 'Café', address: null });
const history = await findRows(orm, PlaceChangeLog, { collectionPlace: s.saved.id });
expect(history.map((row) => row.field).sort()).toEqual(['address', 'name']);
expect(history.every((row) => row.user_id === s.me.id)).toBe(true);
expect(realtime.broadcastToUser).toHaveBeenCalledWith(
s.me.id,
{ type: 'collections:updated', collectionId: s.food.id },
undefined,
);
});
it('a saved place edit reaches the trip place, whose room hears of it; status and notes stay apart', async () => {
const s = await seed();
const res = await request(server)
.patch(`${COLLECTIONS}/places/${s.saved.id}`)
.set(as(s.me.id))
.send({ description: 'Viennese coffee house', website: 'https://cafecentral.wien', notes: 'only here' });
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ id: s.saved.id, description: 'Viennese coffee house' });
expect(await tripPlace(s.cafe.id)).toMatchObject({
description: 'Viennese coffee house',
website: 'https://cafecentral.wien',
notes: 'trip note',
});
expect(await countRows(orm, PlaceChangeLog, { place: s.cafe.id })).toBe(2);
expect(realtime.broadcast).toHaveBeenCalledWith(
String(s.alps.id),
'place:updated',
{ place: expect.objectContaining({ id: s.cafe.id, description: 'Viennese coffee house' }) },
undefined,
);
});
it('a field the edit leaves alone is not carried, and an old difference is not filled in', async () => {
const s = await seed();
await request(server).patch(`${COLLECTIONS}/places/${s.saved.id}`).set(as(s.me.id)).send({ phone: '+43 1 533' });
expect((await tripPlace(s.cafe.id))?.phone).toBe('+43 1 533');
// The trip place differs in its notes from the start; renaming the saved copy leaves them.
await request(server).patch(`${COLLECTIONS}/places/${s.saved.id}`).set(as(s.me.id)).send({ name: 'Central' });
expect(await tripPlace(s.cafe.id)).toMatchObject({ name: 'Central', notes: 'trip note', phone: '+43 1 533' });
});
it('a bulk category change of trip places reaches their saved copies', async () => {
const s = await seed();
// Another category than the one the trip place starts with, so the edit changes it.
const category = (await findRows(orm, Categories, {})).find((row) => row.id !== s.cafe.category_id);
expect(category).toBeDefined();
const res = await request(server)
.post(`/api/trips/${s.alps.id}/places/bulk-update`)
.set(as(s.me.id))
.send({ ids: [s.cafe.id], category_id: category?.id });
expect(res.body).toEqual({ updated: [s.cafe.id], count: 1 });
expect((await savedPlace(s.saved.id))?.category_id).toBe(category?.id);
});
it('answers as before when no other copy exists, and keeps every refusal of the copy edited', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
const lone = await makePlace(orm, trip.id, { name: 'Lone' });
const res = await request(server)
.put(`/api/trips/${trip.id}/places/${lone.id}`)
.set(as(user.id))
.send({ name: 'Still lone' });
expect(res.status).toBe(200);
expect(res.body.place.name).toBe('Still lone');
const s = await seed();
const viewer = await request(server)
.patch(`${COLLECTIONS}/places/${s.foreign.id}`)
.set(as(s.me.id))
.send({ name: 'X' });
expect(viewer.status).toBe(403);
expect(viewer.body).toEqual({ error: 'You have read-only access to this list' });
expect((await tripPlace(s.cafe.id))?.name).toBe('Café');
});
});
describe('over MCP, a token reaches the copies of the kinds it may write', () => {
it('places:write alone leaves the saved copy, collections:write alone the trip place', async () => {
const s = await seed();
const places = app.get(PlacesMcp);
const collections = app.get(CollectionsMcp);
const placesOnly: McpContext = { userId: s.me.id, scopes: ['places:write'], isStaticToken: false };
await withRequestContext(orm, () =>
places.updatePlace({ tripId: s.alps.id, placeId: s.cafe.id, name: 'Trip name' }, placesOnly),
);
expect((await tripPlace(s.cafe.id))?.name).toBe('Trip name');
expect((await savedPlace(s.saved.id))?.name).toBe('Café');
const listsOnly: McpContext = { userId: s.me.id, scopes: ['collections:write'], isStaticToken: false };
await withRequestContext(orm, () =>
collections.updateCollectionPlace({ placeId: s.saved.id, address: 'Herrengasse 14' }, listsOnly),
);
expect((await savedPlace(s.saved.id))?.address).toBe('Herrengasse 14');
expect((await tripPlace(s.cafe.id))?.address).toBeNull();
});
it('a token with both scopes keeps every copy in step', async () => {
const s = await seed();
const places = app.get(PlacesMcp);
const both: McpContext = { userId: s.me.id, scopes: null, isStaticToken: false };
await withRequestContext(orm, () =>
places.bulkUpdatePlaces({ tripId: s.alps.id, placeIds: [s.cafe.id], description: 'From the assistant' }, both),
);
expect((await savedPlace(s.saved.id))?.description).toBe('From the assistant');
expect((await savedPlace(s.foreign.id))?.description).toBeNull();
});
});