Files
TREK/server/tests/e2e/place-votes.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

472 lines
22 KiB
TypeScript

/**
* One vote per person on a place, end to end on the whole app (buildApp, the
* real guards and a migrated temp database; in the Postgres lane on Postgres
* too): a vote cast or taken back on one copy of a place lands on the person's
* other copies of it, a list never shows the vote of someone who is not on it,
* the entry of All places counts every person once, the vote by entry key, the
* carry-over of the votes cast before (and that it adds nothing when it runs
* again), the votes a copy into a trip or a list brings along, and the vote
* tools over MCP.
*/
import { buildApp } from '../../src/bootstrap';
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
import { CollectionPlaceRatings } from '../../src/db/entities/CollectionPlaceRatings.entity';
import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity';
import type { McpContext } from '../../src/nest-mcp';
import { withRequestContext } from '../../src/nest/database/request-context';
import { PlaceVotesCarryJob } from '../../src/nest/places-library/place-votes-carry.job';
import { PlaceVotesLibraryMcp, PlaceVotesMcp } from '../../src/nest/places-library/place-votes.mcp';
import { PlaceVotesService } from '../../src/nest/places-library/place-votes.service';
import { addCollectionMember, makeCollection, makeCollectionPlace } from '../helpers/factories/collections';
import { makePlace } from '../helpers/factories/places';
import { deleteRows, findRows, insertRow, updateRows } from '../helpers/factories/rows';
import { readAppSetting, setAddonEnabled } from '../helpers/factories/settings';
import { addTripMember, 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 LIBRARY_RATING = `${COLLECTIONS}/library/places/rating`;
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
/** A voter as the entry rating names them. */
const voter = (user: { id: number; username: string }, rating: number) => ({
user_id: user.id,
username: user.username,
avatar_url: null,
rating,
});
/** An entry rating with its voters in id order, so a comparison does not hang on the order they were read in. */
function sortedRating(rating: { votes?: { user_id: number }[] } | undefined) {
return rating && { ...rating, votes: [...(rating.votes ?? [])].sort((a, b) => a.user_id - b.user_id) };
}
/** The votes on a trip place and on a saved place, by person. */
async function tripVotes(placeId: number): Promise<Record<number, number>> {
const rows = await findRows(orm, PlaceRatings, { place: placeId });
return Object.fromEntries(rows.map((row) => [row.user_id, row.rating]));
}
async function listVotes(collectionPlaceId: number): Promise<Record<number, number>> {
const rows = await findRows(orm, CollectionPlaceRatings, { collectionPlace: collectionPlaceId });
return Object.fromEntries(rows.map((row) => [row.user_id, row.rating]));
}
/**
* `me` owns the trip Alps with the place Café (on it is `friend`) and the list
* Food with a saved copy of Café that came from the trip place (the same
* provider id), so All places shows `me` the two as one entry. `friend` is
* not on Food; `listmate` is on Food and not on Alps.
*/
async function seed() {
const { user: me } = await makeUser(orm);
const { user: friend } = await makeUser(orm);
const { user: listmate } = await makeUser(orm);
const alps = await makeTrip(orm, me.id, { title: 'Alps' });
await addTripMember(orm, alps.id, friend.id);
const cafe = await makePlace(orm, alps.id, { name: 'Café', lat: 48.2, lng: 16.3, google_place_id: 'g-cafe' });
const food = await makeCollection(orm, me.id, { name: 'Food' });
await addCollectionMember(orm, food.id, listmate.id, { role: 'viewer' });
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,
});
return { me, friend, listmate, alps, cafe, food, saved };
}
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('a vote on one copy lands on every copy of the person', () => {
it('a vote on the trip place is the vote on the saved copy, and each trip and list hears of it', async () => {
const s = await seed();
const res = await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`)
.set(as(s.me.id))
.set('X-Socket-Id', '7')
.send({ rating: 4 });
expect(res.status).toBe(200);
expect(res.body.place).toMatchObject({ id: s.cafe.id, rating_avg: 4, rating_count: 1 });
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 4 });
expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 4 });
// The trip place voted on skips the caller's socket; the list it reached does not.
expect(realtime.broadcast).toHaveBeenCalledWith(String(s.alps.id), 'place:updated', expect.anything(), '7');
expect(realtime.broadcastToUser).toHaveBeenCalledWith(
s.me.id,
{ type: 'collections:updated', collectionId: s.food.id },
undefined,
);
});
it('taking the vote back on the saved copy takes it off the trip place too', async () => {
const s = await seed();
await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 5 });
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 5 });
const res = await request(server).delete(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id));
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ id: s.saved.id, rating_avg: null, rating_count: 0 });
expect(await tripVotes(s.cafe.id)).toEqual({});
expect(await listVotes(s.saved.id)).toEqual({});
});
it('keeps every check of the copy voted on: an unknown place, a trip out of reach, a bad body', async () => {
const s = await seed();
const { user: stranger } = await makeUser(orm);
expect(
(await request(server).put(`/api/trips/${s.alps.id}/places/999999/rating`).set(as(s.me.id)).send({ rating: 3 }))
.body,
).toEqual({ error: 'Place not found' });
const outside = await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`)
.set(as(stranger.id))
.send({ rating: 3 });
expect(outside.status).toBe(404);
expect(outside.body).toEqual({ error: 'Trip not found' });
expect(
(await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(stranger.id)).send({ rating: 3 }))
.status,
).toBe(404);
expect(
(await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 9 }))
.status,
).toBe(400);
expect(await tripVotes(s.cafe.id)).toEqual({});
});
});
describe('a list or trip shows only its own members their votes', () => {
it("a trip member's vote never reaches a list they are not on; the entry counts each person once", async () => {
const s = await seed();
await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`)
.set(as(s.friend.id))
.send({ rating: 2 });
await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`)
.set(as(s.me.id))
.send({ rating: 4 });
expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 4 });
const list = await request(server).get(`${COLLECTIONS}/${s.food.id}`).set(as(s.listmate.id));
expect(list.status).toBe(200);
const place = (list.body.places as { id: number; ratings: { user_id: number }[] }[]).find(
(p) => p.id === s.saved.id,
);
expect(place?.ratings.map((vote) => vote.user_id)).toEqual([s.me.id]);
// me has a vote on both copies and counts once; friend's vote comes from the trip me is on.
const detail = await request(server).get(`${COLLECTIONS}/library/places/list/${s.saved.id}`).set(as(s.me.id));
expect(detail.status).toBe(200);
expect(sortedRating(detail.body.entry.rating)).toEqual({
average: 3,
count: 2,
mine: 4,
votes: [voter(s.me, 4), voter(s.friend, 2)].sort((a, b) => a.user_id - b.user_id),
});
// The list member sees the list's votes only.
const theirs = await request(server).get(`${COLLECTIONS}/library/places/list/${s.saved.id}`).set(as(s.listmate.id));
// Nor do they see friend among the voters.
expect(theirs.body.entry.rating).toEqual({ average: 4, count: 1, mine: null, votes: [voter(s.me, 4)] });
const page = await request(server).get(`${COLLECTIONS}/library/places`).query({ limit: 200 }).set(as(s.me.id));
const entry = (page.body.entries as { key: string; rating: { votes?: { user_id: number }[] } }[]).find(
(e) => e.key === `trip:${s.cafe.id}`,
);
expect(sortedRating(entry?.rating)).toEqual({
average: 3,
count: 2,
mine: 4,
votes: [voter(s.me, 4), voter(s.friend, 2)].sort((a, b) => a.user_id - b.user_id),
});
});
it("counts a person's differing votes on two copies once, with the one changed last", async () => {
const s = await seed();
// Cast on the trip in January and changed there in March; cast on the list in February.
await insertRow(orm, PlaceRatings, {
place: s.cafe.id,
user: s.me.id,
rating: 5,
created_at: '2026-01-01 10:00:00',
updated_at: '2026-03-01 10:00:00',
});
await insertRow(orm, CollectionPlaceRatings, {
collectionPlace: s.saved.id,
user: s.me.id,
rating: 1,
created_at: '2026-02-01 10:00:00',
});
const detail = await request(server).get(`${COLLECTIONS}/library/places/trip/${s.cafe.id}`).set(as(s.me.id));
expect(detail.body.entry.rating).toEqual({ average: 5, count: 1, mine: 5, votes: [voter(s.me, 5)] });
// Each copy keeps its own vote where it lives.
expect(detail.body.details.map((d: { rating: { mine: number } }) => d.rating.mine)).toEqual([5, 1]);
// Never changed, a vote reads as changed when it was cast: then the February list vote is the later one.
await deleteRows(orm, PlaceRatings, { place: s.cafe.id, user: s.me.id });
await insertRow(orm, PlaceRatings, {
place: s.cafe.id,
user: s.me.id,
rating: 5,
created_at: '2026-01-01 10:00:00',
});
const again = await request(server).get(`${COLLECTIONS}/library/places/trip/${s.cafe.id}`).set(as(s.me.id));
expect(again.body.entry.rating).toEqual({ average: 1, count: 1, mine: 1, votes: [voter(s.me, 1)] });
});
it('a vote records when it was changed, on every copy it lands on', async () => {
const s = await seed();
await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 2 });
await updateRows(
orm,
CollectionPlaceRatings,
{ collectionPlace: s.saved.id },
{ updated_at: '2026-01-01 00:00:00' },
);
await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 4 });
const [listVote] = await findRows(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id });
const [tripVote] = await findRows(orm, PlaceRatings, { place: s.cafe.id });
expect(listVote?.rating).toBe(4);
expect(listVote?.updated_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
expect(listVote?.updated_at).not.toBe('2026-01-01 00:00:00');
expect(tripVote?.rating).toBe(4);
expect(tripVote?.updated_at).not.toBeNull();
});
});
describe('the vote by entry key', () => {
it('sets and takes back the vote on every copy and answers the entry rating', async () => {
const s = await seed();
const put = await request(server)
.put(LIBRARY_RATING)
.set(as(s.me.id))
.send({ key: `trip:${s.cafe.id}`, rating: 5 });
expect(put.status).toBe(200);
expect(put.body).toEqual({
key: `trip:${s.cafe.id}`,
rating: { average: 5, count: 1, mine: 5, votes: [voter(s.me, 5)] },
});
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 5 });
expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 5 });
expect(realtime.broadcast).toHaveBeenCalledWith(String(s.alps.id), 'place:updated', expect.anything(), undefined);
const del = await request(server)
.delete(LIBRARY_RATING)
.query({ key: `trip:${s.cafe.id}` })
.set(as(s.me.id));
expect(del.status).toBe(200);
expect(del.body.rating).toEqual({ average: null, count: 0, mine: null, votes: [] });
expect(await tripVotes(s.cafe.id)).toEqual({});
expect(await listVotes(s.saved.id)).toEqual({});
});
it('a list member votes on the copies they reach only', async () => {
const s = await seed();
const res = await request(server)
.put(LIBRARY_RATING)
.set(as(s.listmate.id))
.send({ key: `list:${s.saved.id}`, rating: 3 });
expect(res.status).toBe(200);
expect(await listVotes(s.saved.id)).toEqual({ [s.listmate.id]: 3 });
expect(await tripVotes(s.cafe.id)).toEqual({});
});
it('answers 404 for a key out of reach, 400 for a malformed one, 401 without a session', async () => {
const s = await seed();
const { user: stranger } = await makeUser(orm);
const far = await request(server)
.put(LIBRARY_RATING)
.set(as(stranger.id))
.send({ key: `trip:${s.cafe.id}`, rating: 3 });
expect(far.status).toBe(404);
expect(far.body).toEqual({ error: 'Place not found' });
expect(
(await request(server).put(LIBRARY_RATING).set(as(s.me.id)).send({ key: 'trip:abc', rating: 3 })).status,
).toBe(400);
expect((await request(server).delete(LIBRARY_RATING).set(as(s.me.id))).status).toBe(400);
expect(
(
await request(server)
.put(LIBRARY_RATING)
.send({ key: `trip:${s.cafe.id}`, rating: 3 })
).status,
).toBe(401);
expect(await tripVotes(s.cafe.id)).toEqual({});
});
});
describe('the votes cast before are carried over', () => {
it('adds the last vote where a copy has none, leaves differing votes alone and adds nothing a second time', async () => {
const s = await seed();
// me voted on the saved copy only; friend on the trip place only and is not on the list.
await insertRow(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id, user: s.me.id, rating: 3 });
await insertRow(orm, PlaceRatings, { place: s.cafe.id, user: s.friend.id, rating: 4 });
const votes = app.get(PlaceVotesService);
expect(await withRequestContext(orm, () => votes.carryOver(s.me.id))).toBe(1);
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 3, [s.friend.id]: 4 });
// The carried copy keeps the time of the vote it came from, so it never reads as the newer one.
const [source] = await findRows(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id, user: s.me.id });
const [carried] = await findRows(orm, PlaceRatings, { place: s.cafe.id, user: s.me.id });
expect(carried?.updated_at ?? null).toBe(source?.updated_at ?? source?.created_at ?? null);
expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 3 });
expect(await withRequestContext(orm, () => votes.carryOver(s.me.id))).toBe(0);
expect(await withRequestContext(orm, () => votes.carryOver(s.friend.id))).toBe(0);
// Differing votes on the two copies stay as they are.
await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`)
.set(as(s.me.id))
.send({ rating: 3 });
await deleteRows(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id, user: s.me.id });
await insertRow(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id, user: s.me.id, rating: 2 });
expect(await withRequestContext(orm, () => votes.carryOver(s.me.id))).toBe(0);
expect(await tripVotes(s.cafe.id)).toMatchObject({ [s.me.id]: 3 });
expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 2 });
});
it('the boot pass carries every voter once, remembers it and then stays put', async () => {
const s = await seed();
await insertRow(orm, PlaceRatings, { place: s.cafe.id, user: s.me.id, rating: 5 });
await deleteRows(orm, AppSettings, { key: { $in: ['place_votes_carried_over', 'place_votes_carry_runs'] } });
const job = app.get(PlaceVotesCarryJob);
await job.run();
expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 5 });
expect(await readAppSetting(orm, 'place_votes_carried_over')).not.toBeNull();
expect(await readAppSetting(orm, 'place_votes_carry_runs')).toBe('1');
// Finished: a later start reads the mark and adds nothing, also where a copy lost its vote.
await deleteRows(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id });
await job.run();
expect(await listVotes(s.saved.id)).toEqual({});
});
});
describe('a copy brings the votes of the members of its target along', () => {
it('copying a saved place into a trip carries the votes of the trip members only', async () => {
const s = await seed();
await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 5 });
await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.listmate.id)).send({ rating: 2 });
const res = await request(server)
.post(`${COLLECTIONS}/copy-to-trip`)
.set(as(s.me.id))
.send({ trip_id: s.alps.id, place_ids: [s.saved.id], force: true });
expect(res.status).toBeLessThan(300);
const created = (res.body.created as { id: number }[])[0];
expect(created).toBeDefined();
expect(await tripVotes(created?.id ?? 0)).toEqual({ [s.me.id]: 5 });
});
it('saving a trip place into a list carries the votes of the list members only', async () => {
const s = await seed();
await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`)
.set(as(s.me.id))
.send({ rating: 4 });
await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`)
.set(as(s.friend.id))
.send({ rating: 1 });
const other = await makeCollection(orm, s.me.id, { name: 'Other' });
const res = await request(server)
.post(`${COLLECTIONS}/places/from-trip`)
.set(as(s.me.id))
.send({ collection_id: other.id, source_trip_id: s.alps.id, source_place_id: s.cafe.id, force: true });
expect(res.status).toBe(200);
const copies = await findRows(orm, CollectionPlaceRatings, { user: s.friend.id });
expect(copies).toEqual([]);
const mine = await findRows(orm, CollectionPlaceRatings, { user: s.me.id });
expect(mine.map((vote) => vote.rating).sort()).toEqual([4, 4]);
});
});
describe('the vote tools', () => {
it('rate_library_place, rate_place and rate_collection_place write through like the routes', async () => {
const s = await seed();
const tools = app.get(PlaceVotesMcp);
const libraryTools = app.get(PlaceVotesLibraryMcp);
const ctx: McpContext = { userId: s.me.id, scopes: null, isStaticToken: false };
const entry = await withRequestContext(orm, () =>
libraryTools.rateLibraryPlace({ key: `trip:${s.cafe.id}`, rating: 4 }, ctx),
);
const text = (entry as { content: { text: string }[] }).content[0]?.text ?? '';
expect(JSON.parse(text)).toMatchObject({ rating: { mine: 4 } });
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 4 });
await withRequestContext(orm, () => tools.ratePlace({ tripId: s.alps.id, placeId: s.cafe.id }, ctx));
expect(await listVotes(s.saved.id)).toEqual({});
expect(realtime.broadcast).toHaveBeenCalledWith(s.alps.id, 'place:updated', expect.anything());
await withRequestContext(orm, () => libraryTools.rateCollectionPlace({ placeId: s.saved.id, rating: 2 }, ctx));
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 2 });
const { user: stranger } = await makeUser(orm);
const refused = await withRequestContext(orm, () =>
tools.ratePlace({ tripId: s.alps.id, placeId: s.cafe.id, rating: 1 }, { ...ctx, userId: stranger.id }),
);
expect(refused).toMatchObject({ isError: true });
});
it('a token writes the copies of the kinds its scopes allow only', async () => {
const s = await seed();
const tools = app.get(PlaceVotesMcp);
const libraryTools = app.get(PlaceVotesLibraryMcp);
const placesOnly: McpContext = { userId: s.me.id, scopes: ['places:write'], isStaticToken: false };
await withRequestContext(orm, () =>
tools.ratePlace({ tripId: s.alps.id, placeId: s.cafe.id, rating: 5 }, placesOnly),
);
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 5 });
expect(await listVotes(s.saved.id)).toEqual({});
const listsOnly: McpContext = { userId: s.me.id, scopes: ['collections:write'], isStaticToken: false };
await withRequestContext(orm, () =>
libraryTools.rateCollectionPlace({ placeId: s.saved.id, rating: 2 }, listsOnly),
);
expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 2 });
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 5 });
});
});
describe('with the Collections addon off', () => {
it('a vote on a trip place stays off the saved copies', async () => {
const s = await seed();
await setAddonEnabled(orm, 'collections', false);
try {
const res = await request(server)
.put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`)
.set(as(s.me.id))
.send({ rating: 3 });
expect(res.status).toBe(200);
expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 3 });
expect(await listVotes(s.saved.id)).toEqual({});
} finally {
await setAddonEnabled(orm, 'collections', true);
}
});
});