Files
TREK/server/tests/unit/nest/collections.copy-to-trip.test.ts
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

270 lines
12 KiB
TypeScript

/**
* CollectionsService.copyToTrip, the trip side (G3): after the commit every copied
* place goes out to the trip room as `place:created`, shaped as the place routes
* send it, and runs the places domain's journey hook, so open planners show the
* copies without a reload. A skipped duplicate and a refused copy send nothing.
*
* And what a copy takes along (D9): a saved place's notes and tags stay in the
* list unless the request asks for them, and an asked-for tag arrives as a tag
* of the trip, never as somebody's personal tag.
*/
import { Places } from '../../../src/db/entities/Places.entity';
import { Tags } from '../../../src/db/entities/Tags.entity';
import { CollectionsModule } from '../../../src/nest/collections/collections.module';
import { CollectionsService } from '../../../src/nest/collections/collections.service';
import { PlacesService } from '../../../src/nest/places/places.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addCollectionMember } from '../../helpers/factories/collections';
import { makeCategory, makePlace, makeTag } from '../../helpers/factories/places';
import { countRows, findRow, findRows } from '../../helpers/factories/rows';
import { makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
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, type MockInstance } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let svc: CollectionsService;
let onCreated: MockInstance<PlacesService['onCreated']>;
beforeAll(async () => {
t = await createTestModule({ db, imports: [CollectionsModule] });
svc = t.get(CollectionsService);
onCreated = vi.spyOn(t.get(PlacesService), 'onCreated');
orm = await createTestOrm(db);
});
beforeEach(() => {
resetTestDb(db);
orm.clear();
t.realtime.reset();
onCreated.mockClear();
});
afterAll(async () => {
onCreated.mockRestore();
await orm.close();
await t.close();
db.close();
});
/** The place events of the trip room, as [room, payload, left-out socket]. */
const placeCreated = () =>
t.realtime.broadcastMock.mock.calls
.filter(([, event]) => event === 'place:created')
.map(([room, , payload, sid]) => [room, payload, sid]);
/** The place a save to a collection kept; a save that answered with a warning instead fails the case. */
async function saved(userId: number, body: Parameters<CollectionsService['savePlace']>[1]) {
const { place } = await svc.savePlace(userId, body);
if (!place) throw new Error(`expected ${body.name} to be saved`);
return place;
}
describe('CollectionsService.copyToTrip: the trip hears its new places', () => {
it('COLLECTIONS-SVC-215: each copied place goes out as place:created with its tags, then runs the journey hook; a skipped one sends nothing', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
const tag = await makeTag(orm, user.id, { name: 'rooftop' });
const col = await svc.createCollection(user.id, { name: 'Evenings' });
const bar = await saved(user.id, { collection_id: col.id, name: 'Sky Bar', tag_ids: [tag.id] });
await makePlace(orm, trip.id, { name: 'Pantheon' });
const dup = await saved(user.id, { collection_id: col.id, name: 'Pantheon' });
t.realtime.broadcastMock.mockClear();
const res = await svc.copyToTrip(
user.id,
{ trip_id: trip.id, place_ids: [bar.id, dup.id], tag_ids: [tag.id] },
svc.tripEvents(trip.id, 'sock-copy'),
);
const copy = await findRow(orm, Places, { trip: trip.id, name: 'Sky Bar' });
if (!copy) throw new Error('expected the copy in the trip');
// Each new trip place is named with the saved place it came from, for the assistant's "Show on map".
expect(res).toEqual({
copied: 1,
skipped: [{ id: dup.id, name: 'Pantheon' }],
created: [{ id: copy.id, source_id: bar.id }],
});
const sent = placeCreated();
expect(sent).toHaveLength(1);
// The trip room, the REST socket left out, the place as the place routes send it.
const [room, payload, sid] = sent[0];
expect([room, sid]).toEqual([trip.id, 'sock-copy']);
// The tag arrives as one of the trip's own, under the same name.
expect((payload as { place: { id: number; tags: { name: string }[] } }).place).toMatchObject({
id: copy.id,
tags: [expect.objectContaining({ name: 'rooftop' })],
});
expect(onCreated.mock.calls).toEqual([[String(trip.id), copy.id]]);
});
it('COLLECTIONS-SVC-216: a refused copy sends nothing and runs no hook', async () => {
const { user: owner } = await makeUser(orm);
const { user: stranger } = await makeUser(orm);
await makeCategory(orm);
const col = await svc.createCollection(owner.id, { name: 'Mine' });
const gem = await saved(owner.id, { collection_id: col.id, name: 'Hidden gem' });
const theirs = await makeTrip(orm, stranger.id);
t.realtime.broadcastMock.mockClear();
await expect(
svc.copyToTrip(owner.id, { trip_id: theirs.id, place_ids: [gem.id] }, svc.tripEvents(theirs.id, undefined)),
).rejects.toThrow();
expect(placeCreated()).toEqual([]);
expect(onCreated).not.toHaveBeenCalled();
});
it('COLLECTIONS-SVC-225: a plugin copy has no socket, so no tab of the trip is left out', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
const col = await svc.createCollection(user.id, { name: 'Plugin' });
const spot = await saved(user.id, { collection_id: col.id, name: 'Viewpoint' });
t.realtime.broadcastMock.mockClear();
await svc.copyToTrip(user.id, { trip_id: trip.id, place_ids: [spot.id] }, svc.tripEvents(trip.id, undefined));
expect(placeCreated().map(([room, , sid]) => [room, sid])).toEqual([[trip.id, undefined]]);
});
});
/** Every tag on the trip place, as [name, trip_id, user_id]. */
async function tagsOf(placeId: number) {
return (await findRows(orm, Tags, { place_tags_inverse: placeId })).map((t) => [t.name, t.trip_id, t.user_id]);
}
const tripTagEvents = () => t.realtime.broadcastMock.mock.calls.filter(([, event]) => event === 'tripTags:changed');
describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9)', () => {
it('COLLECTIONS-SVC-226: a body without the new fields copies the place with neither its notes nor its tags', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
const tag = await makeTag(orm, user.id, { name: 'private' });
const col = await svc.createCollection(user.id, { name: 'Mine' });
const spot = await saved(user.id, { collection_id: col.id, name: 'Cafe', notes: 'ask for Ana', tag_ids: [tag.id] });
t.realtime.broadcastMock.mockClear();
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' });
if (!copy) throw new Error('the copy is missing');
expect(copy.notes).toBeNull();
expect(await tagsOf(copy.id)).toEqual([]);
expect(tripTagEvents()).toEqual([]);
});
it('COLLECTIONS-SVC-227: include_notes: true brings the notes along', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
const col = await svc.createCollection(user.id, { name: 'Mine' });
const spot = await saved(user.id, { collection_id: col.id, name: 'Bakery', notes: 'open at 7' });
await svc.copyToTrip(
user.id,
{ trip_id: trip.id, place_ids: [spot.id], include_notes: true },
svc.tripEvents(trip.id, undefined),
);
expect((await findRow(orm, Places, { trip: trip.id, name: 'Bakery' }))?.notes).toBe('open at 7');
});
it('COLLECTIONS-SVC-228: asked-for tags become trip tags: one of the same name is reused, a new one made once, no personal tag is linked', async () => {
const { user: owner } = await makeUser(orm);
const { user: friend } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, owner.id);
const existing = await makeTag(orm, owner.id, { name: 'Rooftop', trip: trip.id });
const col = await svc.createCollection(owner.id, { name: 'Shared' });
await addCollectionMember(orm, col.id, friend.id);
// Both personal tags of the list's people: the friend's, and one the copy is not asked for.
const rooftop = await makeTag(orm, friend.id, { name: 'rooftop ' });
const brunch = await makeTag(orm, friend.id, { name: 'Brunch' });
const quiet = await makeTag(orm, owner.id, { name: 'quiet' });
const a = await saved(friend.id, {
collection_id: col.id,
name: 'Sky Bar',
tag_ids: [rooftop.id, brunch.id, quiet.id],
});
const b = await saved(friend.id, { collection_id: col.id, name: 'Garden', tag_ids: [brunch.id] });
t.realtime.broadcastMock.mockClear();
await svc.copyToTrip(
owner.id,
{ trip_id: trip.id, place_ids: [a.id, b.id], tag_ids: [rooftop.id, brunch.id, 999_999] },
svc.tripEvents(trip.id, 'sock-1'),
);
const skyBar = await findRow(orm, Places, { trip: trip.id, name: 'Sky Bar' });
const garden = await findRow(orm, Places, { trip: trip.id, name: 'Garden' });
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([
['Rooftop', trip.id, owner.id],
['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(tripTagEvents()).toEqual([[trip.id, 'tripTags:changed', {}, 'sock-1']]);
});
it('COLLECTIONS-SVC-229: a skipped duplicate makes no trip tag', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
await makePlace(orm, trip.id, { name: 'Pantheon' });
const tag = await makeTag(orm, user.id, { name: 'ancient' });
const col = await svc.createCollection(user.id, { name: 'Rome' });
const dup = await saved(user.id, { collection_id: col.id, name: 'Pantheon', tag_ids: [tag.id] });
t.realtime.broadcastMock.mockClear();
const res = await svc.copyToTrip(
user.id,
{ trip_id: trip.id, place_ids: [dup.id], tag_ids: [tag.id] },
svc.tripEvents(trip.id, undefined),
);
expect(res.copied).toBe(0);
expect(await countRows(orm, Tags, { trip: trip.id })).toBe(0);
expect(tripTagEvents()).toEqual([]);
});
it('COLLECTIONS-SVC-232: the list tags asked for (its labels) arrive as tags of the trip, a trip tag of the name reused', async () => {
const { user } = await makeUser(orm);
await makeCategory(orm);
const trip = await makeTrip(orm, user.id);
const existing = await makeTag(orm, user.id, { name: 'coffee', trip: trip.id });
const col = await svc.createCollection(user.id, { name: 'Lisbon' });
const coffee = await svc.createLabel(user.id, col.id, 'Coffee', '#111111');
const view = await svc.createLabel(user.id, col.id, 'View', '#222222');
const unasked = await svc.createLabel(user.id, col.id, 'Later');
const spot = await saved(user.id, { collection_id: col.id, name: 'Miradouro' });
await svc.updatePlace(user.id, spot.id, { label_ids: [coffee.id, view.id, unasked.id] });
t.realtime.broadcastMock.mockClear();
await svc.copyToTrip(
user.id,
{ trip_id: trip.id, place_ids: [spot.id], label_ids: [coffee.id, view.id] },
svc.tripEvents(trip.id, undefined),
);
const copy = await findRow(orm, Places, { trip: trip.id, name: 'Miradouro' });
if (!copy) throw new Error('the copy is missing');
const carried = await findRows(orm, Tags, { place_tags_inverse: copy.id });
expect(carried.map((tag) => tag.name).sort()).toEqual(['View', 'coffee']);
expect(carried.map((tag) => tag.id)).toContain(existing.id);
expect(carried.find((tag) => tag.name === 'View')).toMatchObject({ trip_id: trip.id, color: '#222222' });
expect(tripTagEvents()).toHaveLength(1);
});
});