Files
TREK/server/tests/unit/nest/collections.place-order.test.ts
T
Maurice f69a4c1a24 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.
2026-11-29 15:57:05 +01:00

245 lines
12 KiB
TypeScript

/**
* The order of a list's places (PLC-03) and the provenance a save keeps.
*
* reorderPlaces sets the order by hand for anyone who may edit the list; every
* way a place comes into a list puts it after the last one; and the source
* trip and place a save names are kept only when the caller can open that
* trip and the place is one of its own.
*
* Real in-memory SQLite over the container: the service comes out of
* CollectionsModule, the rows are seeded and read through the ORM factories.
*/
import { CollectionPlaces } from '../../../src/db/entities/CollectionPlaces.entity';
import { CollectionsModule } from '../../../src/nest/collections/collections.module';
import { CollectionsService } from '../../../src/nest/collections/collections.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addCollectionMember, makeCollectionPlace } from '../../helpers/factories/collections';
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';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let svc: CollectionsService;
const orm = () => t.get(MikroORM);
beforeAll(async () => {
t = await createTestModule({ db, imports: [CollectionsModule] });
svc = t.get(CollectionsService);
});
beforeEach(() => {
resetTestDb(db);
t.realtime.reset();
});
afterAll(async () => {
await t.close();
db.close();
});
/** The list's place names in the order the detail read answers them. */
async function namesInOrder(userId: number, collectionId: number): Promise<string[]> {
return (await svc.getCollection(userId, collectionId)).places.map((p) => p.name);
}
/** A place saved through the service, so it takes the position a save gives it. */
async function save(userId: number, collectionId: number, name: string) {
const { place } = await svc.savePlace(userId, { collection_id: collectionId, name });
if (!place) throw new Error(`expected ${name} to be saved`);
return place;
}
describe('reorderPlaces (PLC-03)', () => {
it('COLLECTIONS-ORDER-001: sets the order the request names, which every read then follows', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Lisbon' });
const a = await save(user.id, col.id, 'Alfama');
const b = await save(user.id, col.id, 'Belem');
const c = await save(user.id, col.id, 'Chiado');
await svc.reorderPlaces(user.id, col.id, [c.id, a.id, b.id], 'sock-1');
expect(await namesInOrder(user.id, col.id)).toEqual(['Chiado', 'Alfama', 'Belem']);
const rows = await findRows(orm(), CollectionPlaces, { collection: col.id }, { sort_order: 'asc' });
expect(rows.map((r) => [r.name, r.sort_order])).toEqual([
['Chiado', 0],
['Alfama', 1],
['Belem', 2],
]);
// The members' tabs reload the list, the asking one left out.
expect(t.realtime.broadcastToUserMock).toHaveBeenCalledWith(
user.id,
{ type: 'collections:updated', collectionId: col.id },
'sock-1',
);
});
it('COLLECTIONS-ORDER-002: places the request leaves out follow the named ones in the order they had', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Porto' });
const a = await save(user.id, col.id, 'A');
await save(user.id, col.id, 'B');
const c = await save(user.id, col.id, 'C');
await svc.reorderPlaces(user.id, col.id, [c.id, a.id]);
expect(await namesInOrder(user.id, col.id)).toEqual(['C', 'A', 'B']);
});
it('COLLECTIONS-ORDER-003: an id of another list, or one named twice, is refused and nothing moves', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Here' });
const other = await svc.createCollection(user.id, { name: 'There' });
const a = await save(user.id, col.id, 'A');
const b = await save(user.id, col.id, 'B');
const foreign = await save(user.id, other.id, 'Foreign');
t.realtime.reset();
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();
});
it('COLLECTIONS-ORDER-004: an editor may reorder, a viewer gets the read-only refusal, a stranger a 404', async () => {
const { user: owner } = await makeUser(orm());
const { user: editor } = await makeUser(orm());
const { user: viewer } = await makeUser(orm());
const { user: stranger } = await makeUser(orm());
const col = await svc.createCollection(owner.id, { name: 'Shared' });
await addCollectionMember(orm(), col.id, editor.id, { role: 'editor' });
await addCollectionMember(orm(), col.id, viewer.id, { role: 'viewer' });
const a = await save(owner.id, col.id, 'A');
const b = await save(owner.id, col.id, 'B');
await svc.reorderPlaces(editor.id, col.id, [b.id, a.id]);
expect(await namesInOrder(owner.id, col.id)).toEqual(['B', 'A']);
await expect(svc.reorderPlaces(viewer.id, col.id, [a.id, b.id])).rejects.toMatchObject({ status: 403 });
await expect(svc.reorderPlaces(stranger.id, col.id, [a.id, b.id])).rejects.toMatchObject({
status: 404,
message: 'Collection not found',
});
});
it('COLLECTIONS-ORDER-005: places that all still stand at 0 read oldest first, by id, until a reorder fixes them', async () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Old list' });
// Rows from before PLC-03 all carry the column default.
const first = await makeCollectionPlace(orm(), col.id, user.id, { name: 'First', sort_order: 0 });
await makeCollectionPlace(orm(), col.id, user.id, { name: 'Second', sort_order: 0 });
const third = await makeCollectionPlace(orm(), col.id, user.id, { name: 'Third', sort_order: 0 });
expect(await namesInOrder(user.id, col.id)).toEqual(['First', 'Second', 'Third']);
await svc.reorderPlaces(user.id, col.id, [third.id, first.id]);
expect(await namesInOrder(user.id, col.id)).toEqual(['Third', 'First', 'Second']);
});
});
describe('a new place goes after the last one (PLC-03)', () => {
it('COLLECTIONS-ORDER-006: a save, a save from a trip and a bulk save from a trip all append', async () => {
const { user } = await makeUser(orm());
await makeCategory(orm());
const trip = await makeTrip(orm(), user.id);
const tower = await makePlace(orm(), trip.id, { name: 'Tower', lat: 38.69, lng: -9.21 });
const tram = await makePlace(orm(), trip.id, { name: 'Tram', lat: 38.71, lng: -9.13 });
const view = await makePlace(orm(), trip.id, { name: 'View', lat: 38.72, lng: -9.14 });
const col = await svc.createCollection(user.id, { name: 'Lisbon' });
const a = await save(user.id, col.id, 'A');
const b = await save(user.id, col.id, 'B');
await svc.reorderPlaces(user.id, col.id, [b.id, a.id]);
await svc.saveFromTripPlace(user.id, col.id, trip.id, tower.id);
await svc.saveFromTripPlaces(user.id, col.id, trip.id, [tram.id, view.id]);
await save(user.id, col.id, 'Last');
expect(await namesInOrder(user.id, col.id)).toEqual(['B', 'A', 'Tower', 'Tram', 'View', 'Last']);
});
it('COLLECTIONS-ORDER-007: a place moved into another list joins the end of that list', async () => {
const { user } = await makeUser(orm());
const from = await svc.createCollection(user.id, { name: 'From' });
const to = await svc.createCollection(user.id, { name: 'To' });
await save(user.id, to.id, 'Already here');
await save(user.id, to.id, 'Also here');
const moving = await save(user.id, from.id, 'Moving');
await svc.updatePlace(user.id, moving.id, { collection_id: to.id });
expect(await namesInOrder(user.id, to.id)).toEqual(['Already here', 'Also here', 'Moving']);
expect((await findRow(orm(), CollectionPlaces, { id: moving.id }))?.sort_order).toBe(2);
});
it('COLLECTIONS-ORDER-008: an edit that names no coordinates keeps them, null clears them (PLC-04)', async () => {
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 });
});
});
describe('savePlace keeps only a provenance the caller can stand behind', () => {
it('COLLECTIONS-ORDER-009: a trip the caller can open, holding the place, is kept', async () => {
const { user } = await makeUser(orm());
await makeCategory(orm());
const trip = await makeTrip(orm(), user.id);
const place = await makePlace(orm(), trip.id, { name: 'Castle' });
const col = await svc.createCollection(user.id, { name: 'Mine' });
const { place: saved } = await svc.savePlace(user.id, {
collection_id: col.id,
name: 'Castle',
source_trip_id: trip.id,
source_place_id: place.id,
});
expect(saved).toMatchObject({ source_trip_id: trip.id, source_place_id: place.id });
});
it('COLLECTIONS-ORDER-010: a trip the caller cannot open, a place of another trip, or half a pair is stored as null', async () => {
const { user } = await makeUser(orm());
const { user: other } = await makeUser(orm());
await makeCategory(orm());
const mine = await makeTrip(orm(), user.id);
const theirs = await makeTrip(orm(), other.id);
const minePlace = await makePlace(orm(), mine.id, { name: 'Mine' });
const theirPlace = await makePlace(orm(), theirs.id, { name: 'Theirs' });
const col = await svc.createCollection(user.id, { name: 'Mine' });
const claims = [
{ source_trip_id: theirs.id, source_place_id: theirPlace.id }, // a trip they cannot open
{ source_trip_id: mine.id, source_place_id: theirPlace.id }, // a place that is not in that trip
{ source_trip_id: mine.id }, // half a pair
{ source_place_id: minePlace.id },
];
const rows = await oneByOne([...claims.entries()], async ([i, claim]) => {
const { place } = await svc.savePlace(user.id, { collection_id: col.id, name: `Claim ${i}`, ...claim });
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]),
);
});
});