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
+4
View File
@@ -122,6 +122,10 @@ export * from './geo/longitude';
export * from './collection/collection.schema';
export * from './collection/collection-file.schema';
export * from './places-library/places-library.schema';
// D5/PLC-13: the user's own places, duplicate suggestions and merges in All places.
export * from './places-library/place-identity.schema';
// PLC-15/PLC-16: the lists a trip draws on and their saved places on the trip map.
export * from './trip-collections/trip-collections.schema';
export * from './trip/trip.schema';
export * from './place/place-hours';
export * from './place/place-kind';
@@ -0,0 +1,92 @@
import {
PLACES_LIBRARY_DUPLICATES_PAGE_MAX,
PLACES_LIBRARY_LINK_MAX_USES,
placesLibraryDuplicatesQuerySchema,
placesLibraryDuplicatesResponseSchema,
placesLibraryLinkRequestSchema,
placesLibraryMergeRequestSchema,
placesLibraryPairRequestSchema,
placesLibraryUndoMergeRequestSchema,
placesLibraryUnlinkRequestSchema,
} from './place-identity.schema';
import { describe, expect, it } from 'vitest';
const side = {
key: 'trip:12',
identity_id: null,
name: 'Café',
address: null,
lat: 1,
lng: 2,
category: null,
google_place_id: 'g',
google_ftid: null,
osm_id: null,
origins: [
{
kind: 'trip',
trip_id: 5,
trip_title: 'Alps',
trip_start: null,
trip_end: null,
place_id: 12,
can_edit: true,
read_only: false,
linked: false,
},
],
};
describe('place identity contracts (D5/PLC-13)', () => {
it('takes uses by kind and id, at least one and not too many, nothing else', () => {
expect(placesLibraryLinkRequestSchema.parse({ uses: [{ kind: 'trip', id: 3 }], identity_id: 4 })).toEqual({
uses: [{ kind: 'trip', id: 3 }],
identity_id: 4,
});
const tooMany = Array.from({ length: PLACES_LIBRARY_LINK_MAX_USES + 1 }, (_, i) => ({ kind: 'list', id: i + 1 }));
for (const body of [
{ uses: [] },
{ uses: tooMany },
{ uses: [{ kind: 'tour', id: 1 }] },
{ uses: [{ kind: 'trip', id: '3' }] },
{ uses: [{ kind: 'trip', id: 1.5 }] },
{ uses: [{ kind: 'trip', id: 1 }], extra: 1 },
]) {
expect(placesLibraryLinkRequestSchema.safeParse(body).success).toBe(false);
}
expect(placesLibraryUnlinkRequestSchema.safeParse({ kind: 'list', id: 2 }).success).toBe(true);
expect(placesLibraryUnlinkRequestSchema.safeParse({ kind: 'list', id: 0 }).success).toBe(false);
});
it('takes entry keys only in the spelling list_all_places hands out', () => {
expect(placesLibraryMergeRequestSchema.safeParse({ leading: 'own:3', other: 'list:4' }).success).toBe(true);
expect(placesLibraryPairRequestSchema.safeParse({ a: 'trip:1', b: 'list:2' }).success).toBe(true);
for (const key of ['trip:0', 'trip:01', 'place:1', 'trip:1e3', 'trip:', ' trip:1']) {
expect(placesLibraryMergeRequestSchema.safeParse({ leading: key, other: 'list:4' }).success).toBe(false);
}
expect(placesLibraryUndoMergeRequestSchema.safeParse({ merge_id: 2 }).success).toBe(true);
expect(placesLibraryUndoMergeRequestSchema.safeParse({ merge_id: '2' }).success).toBe(false);
});
it('reads the duplicates page query and describes a page', () => {
expect(placesLibraryDuplicatesQuerySchema.parse({ limit: '5', cursor: 'abc' })).toEqual({
limit: 5,
cursor: 'abc',
});
expect(
placesLibraryDuplicatesQuerySchema.safeParse({ limit: String(PLACES_LIBRARY_DUPLICATES_PAGE_MAX + 1) }).success,
).toBe(false);
const page = {
duplicates: [
{ a: side, b: { ...side, key: 'list:3' }, reasons: ['name_nearby'], differing: [], can_merge: true },
],
next_cursor: null,
};
expect(placesLibraryDuplicatesResponseSchema.parse(page)).toEqual(page);
expect(
placesLibraryDuplicatesResponseSchema.safeParse({ ...page, duplicates: [{ ...page.duplicates[0], reasons: [] }] })
.success,
).toBe(false);
});
});
@@ -0,0 +1,165 @@
import { idSchema } from '../common/primitives.schema';
import {
PLACES_LIBRARY_KINDS,
placesLibraryCategorySchema,
placesLibraryEntrySchema,
placesLibraryKeySchema,
placesLibraryOriginSchema,
} from './places-library.schema';
import { z } from 'zod';
/**
* D5/PLC-13: the user's own places. A user may say that some of their trip
* places and saved places are one place (an identity of their own), take one
* back out, have TREK suggest likely duplicates, merge two entries and undo
* that. All of it groups only the user's own "All places": no trip place and
* no saved place is written, renamed, moved or deleted.
*/
/** One use of a place: a trip place (kind trip, its place id) or a saved place (kind list, its collection place id). */
export const placesLibraryUseSchema = z
.object({
kind: z.enum(PLACES_LIBRARY_KINDS).describe('trip for a trip place id, list for a saved place id'),
id: idSchema.describe('The place_id of a trip place or the collection_place_id of a saved place'),
})
.strict();
export type PlacesLibraryUse = z.infer<typeof placesLibraryUseSchema>;
export const PLACES_LIBRARY_LINK_MAX_USES = 50;
/**
* Put uses together as one place of the user's own. With `identity_id` they
* join that place; without it a new one is made from the first use's name,
* position, address, category and provider ids. A use that belonged to another
* of the user's places moves.
*/
export const placesLibraryLinkRequestSchema = z
.object({
uses: z
.array(placesLibraryUseSchema)
.min(1)
.max(PLACES_LIBRARY_LINK_MAX_USES)
.describe('The trip places and saved places to put together, the first one naming a new place'),
identity_id: idSchema.optional().describe('The own place they join; leave it out to make a new one'),
})
.strict();
export type PlacesLibraryLinkRequest = z.infer<typeof placesLibraryLinkRequestSchema>;
/** Take one use out of the user's own place again. */
export const placesLibraryUnlinkRequestSchema = placesLibraryUseSchema;
export type PlacesLibraryUnlinkRequest = PlacesLibraryUse;
/** The entry a use belongs to after the change, null when it is out of reach by now. */
export const placesLibraryEntryResponseSchema = z.object({
entry: placesLibraryEntrySchema.nullable(),
});
export type PlacesLibraryEntryResponse = z.infer<typeof placesLibraryEntryResponseSchema>;
export const PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT = 20;
export const PLACES_LIBRARY_DUPLICATES_PAGE_MAX = 50;
const duplicatesLimitSchema = z
.union([z.number().int(), z.string().regex(/^\d+$/)])
.transform(Number)
.pipe(z.number().int().min(1).max(PLACES_LIBRARY_DUPLICATES_PAGE_MAX));
export const placesLibraryDuplicatesQuerySchema = z
.object({
cursor: z
.string()
.max(200)
.optional()
.describe('Where to go on: the next_cursor of the page before. Leave it out for the first page.'),
limit: duplicatesLimitSchema
.optional()
.describe(
`How many pairs at most (default ${PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT}, at most ${PLACES_LIBRARY_DUPLICATES_PAGE_MAX})`,
),
})
.strict();
export type PlacesLibraryDuplicatesQuery = z.infer<typeof placesLibraryDuplicatesQuerySchema>;
export type PlacesLibraryDuplicatesQueryInput = z.input<typeof placesLibraryDuplicatesQuerySchema>;
/** Why two entries look like one place: a provider id they share, or the same name a few metres apart. */
export const PLACES_LIBRARY_DUPLICATE_REASONS = ['provider_id', 'name_nearby'] as const;
/** The facts the two sides of a suggestion can differ in. */
export const PLACES_LIBRARY_DUPLICATE_FIELDS = [
'name',
'position',
'address',
'category',
'google_place_id',
'google_ftid',
'osm_id',
] as const;
/** One side of a suggestion, as "All places" shows the entry, with the provider ids it is recognised by. */
export const placesLibraryDuplicateSideSchema = z.object({
key: z.string(),
identity_id: z.number().int().nullable(),
name: z.string(),
address: z.string().nullable(),
lat: z.number().nullable(),
lng: z.number().nullable(),
category: placesLibraryCategorySchema.nullable(),
google_place_id: z.string().nullable(),
google_ftid: z.string().nullable(),
osm_id: z.string().nullable(),
origins: z.array(placesLibraryOriginSchema).min(1),
});
export type PlacesLibraryDuplicateSide = z.infer<typeof placesLibraryDuplicateSideSchema>;
/**
* A likely duplicate: both entries, why they look alike, which facts differ,
* and whether they may be merged. `can_merge` is false while one side's own
* place still holds a use the user cannot open any more (a trip they left).
*/
export const placesLibraryDuplicateSchema = z.object({
a: placesLibraryDuplicateSideSchema,
b: placesLibraryDuplicateSideSchema,
reasons: z.array(z.enum(PLACES_LIBRARY_DUPLICATE_REASONS)).min(1),
differing: z.array(z.enum(PLACES_LIBRARY_DUPLICATE_FIELDS)),
can_merge: z.boolean(),
});
export type PlacesLibraryDuplicate = z.infer<typeof placesLibraryDuplicateSchema>;
export const placesLibraryDuplicatesResponseSchema = z.object({
duplicates: z.array(placesLibraryDuplicateSchema),
next_cursor: z.string().nullable(),
});
export type PlacesLibraryDuplicatesResponse = z.infer<typeof placesLibraryDuplicatesResponseSchema>;
/** A pair of entries by their keys, in either order. */
export const placesLibraryPairRequestSchema = z
.object({
a: placesLibraryKeySchema,
b: placesLibraryKeySchema,
})
.strict();
export type PlacesLibraryPairRequest = z.infer<typeof placesLibraryPairRequestSchema>;
/**
* Merge two entries into one place of the user's own. `leading` names the
* entry whose name and position the place keeps; nothing is written into a
* trip or a list.
*/
export const placesLibraryMergeRequestSchema = z
.object({
leading: placesLibraryKeySchema.describe('The entry whose name and position the merged place keeps'),
other: placesLibraryKeySchema.describe('The entry merged into it'),
})
.strict();
export type PlacesLibraryMergeRequest = z.infer<typeof placesLibraryMergeRequestSchema>;
export const placesLibraryMergeResponseSchema = z.object({
/** Pass it to the undo route to take the merge back. */
merge_id: z.number().int(),
entry: placesLibraryEntrySchema.nullable(),
});
export type PlacesLibraryMergeResponse = z.infer<typeof placesLibraryMergeResponseSchema>;
/** The merge an undo takes back, for MCP (REST names it in the path). */
export const placesLibraryUndoMergeRequestSchema = z.object({ merge_id: idSchema }).strict();
export type PlacesLibraryUndoMergeRequest = z.infer<typeof placesLibraryUndoMergeRequestSchema>;
@@ -85,6 +85,8 @@ export const placesLibraryListOriginSchema = z.object({
collection_place_id: z.number().int(),
status: z.enum(COLLECTION_STATUSES),
can_edit: z.boolean(),
/** True when the user assigned this saved place to the entry's own place (D5), so it can be taken out again. */
linked: z.boolean().optional(),
});
export type PlacesLibraryListOrigin = z.infer<typeof placesLibraryListOriginSchema>;
@@ -98,6 +100,8 @@ export const placesLibraryTripOriginSchema = z.object({
place_id: z.number().int(),
can_edit: z.boolean(),
read_only: z.boolean(),
/** True when the user assigned this trip place to the entry's own place (D5), so it can be taken out again. */
linked: z.boolean().optional(),
});
export type PlacesLibraryTripOrigin = z.infer<typeof placesLibraryTripOriginSchema>;
@@ -107,14 +111,24 @@ export const placesLibraryOriginSchema = z.discriminatedUnion('kind', [
]);
export type PlacesLibraryOrigin = z.infer<typeof placesLibraryOriginSchema>;
/** How an entry is named: its own place, else its trip place, else its saved place. */
export const PLACES_LIBRARY_KEY_PATTERN = /^(own|trip|list):[1-9]\d{0,15}$/;
export const placesLibraryKeySchema = z
.string()
.regex(PLACES_LIBRARY_KEY_PATTERN, 'Invalid key')
.describe('An entry key of list_all_places: own:<id>, trip:<place_id> or list:<collection_place_id>');
/**
* One place of "All places". `key` stays the same across pages and sorts:
* `trip:<place_id>` when the entry has a trip origin, else
* `list:<collection_place_id>`. Name, address, position, category and picture
* are the trip place's where there is one; the trip origin comes first.
* `own:<identity_id>` for uses the user put together as one place of their
* own (D5), else `trip:<place_id>` when the entry has a trip origin, else
* `list:<collection_place_id>`. Name, address, position and category are the
* own place's, else the trip place's where there is one; trip origins come first.
*/
export const placesLibraryEntrySchema = z.object({
key: z.string(),
/** The user's own place this entry is, or null for an entry no one put together. */
identity_id: z.number().int().nullable().optional(),
name: z.string(),
address: z.string().nullable(),
lat: z.number().nullable(),
+6 -3
View File
@@ -23,6 +23,7 @@ const FIXTURES: Record<TrekWsEventName, Record<string, unknown>> = {
'place:updated': { place: { id: 3, name: 'Louvre' } },
'place:deleted': { placeId: 3 },
'tripTags:changed': {},
'tripCollections:changed': {},
'tours:changed': { placeIds: [3] },
'tours:visits': { assignmentId: 9, visits: [{ assignment_id: 9, station_key: 'abcdef', status: 'visited' }] },
'assignment:created': { assignment: { id: 9, day_id: 2 } },
@@ -203,7 +204,7 @@ const DRIFT_VARIANTS: Partial<Record<TrekWsEventName, Record<string, unknown>[]>
};
describe('@trek/shared realtime event registry', () => {
it('WSEVT-REG-001: pins the authoritative inventory counts (82 trip + 43 user = 125)', () => {
it('WSEVT-REG-001: pins the authoritative inventory counts (83 trip + 43 user = 126)', () => {
// 67th to 69th trip event: the three collab:link:* a shared link emits.
// 70th and 71st: the road trip's vias and tracks, which used to be written silently.
// 74th: docsync:changed, so a sync run that moved documents refreshes the
@@ -227,9 +228,11 @@ describe('@trek/shared realtime event registry', () => {
// renames or deletes shows the same for everyone on it.
// 82nd trip event: tripAddons:changed, so a trip addon its owner switches on
// or off for the trip shows or hides for every member at once.
expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(82);
// 83rd trip event: tripCollections:changed, so the lists a trip draws on
// follow a link or unlink for every member, each with their own rights.
expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(83);
expect(TREK_WS_USER_EVENT_NAMES).toHaveLength(43);
expect(TREK_WS_EVENT_NAMES).toHaveLength(125);
expect(TREK_WS_EVENT_NAMES).toHaveLength(126);
});
it('WSEVT-REG-002: every name is domain:action shaped and outside the reserved plugin: namespace', () => {
+4
View File
@@ -298,6 +298,10 @@ export const TREK_WS_EVENTS = {
// instance setting: every trip addon as the trip now sees it.
'tripAddons:changed': { scope: 'trip', payload: z.object({ addons: tripAddonListSchema }) },
// A list was linked to the trip or unlinked. Content-free: who sees which list
// is per person, so every member asks again with their own rights.
'tripCollections:changed': { scope: 'trip', payload: empty },
// ── Notifications (user-scoped) ──────────────────────────────────────────
'notification:new': { scope: 'user', payload: z.object({ notification: entity }) },
'notification:updated': { scope: 'user', payload: z.object({ notification: entity }) },
@@ -0,0 +1,56 @@
import {
tripCollectionLayerResponseSchema,
tripCollectionLinkRequestSchema,
tripCollectionLinksResponseSchema,
} from './trip-collections.schema';
import { describe, expect, it } from 'vitest';
describe('trip collection contracts (PLC-15/PLC-16)', () => {
it('links one list by its id and nothing else', () => {
expect(tripCollectionLinkRequestSchema.parse({ collection_id: 3 })).toEqual({ collection_id: 3 });
for (const body of [
{},
{ collection_id: '3' },
{ collection_id: 0 },
{ collection_id: 1.5 },
{ collection_id: 1, x: 1 },
]) {
expect(tripCollectionLinkRequestSchema.safeParse(body).success).toBe(false);
}
});
it('describes the links and the map layer', () => {
const links = {
links: [
{
collection_id: 3,
name: 'Food',
color: null,
role: 'viewer',
place_count: 2,
linked_by: null,
created_at: null,
},
],
can_link: false,
};
expect(tripCollectionLinksResponseSchema.parse(links)).toEqual(links);
expect(
tripCollectionLinksResponseSchema.safeParse({ ...links, links: [{ ...links.links[0], role: 'guest' }] }).success,
).toBe(false);
const place = {
id: 1,
collection_id: 3,
name: 'Café',
lat: 1,
lng: 2,
category: null,
status: 'want',
in_trip: true,
trip_place_id: 9,
};
expect(tripCollectionLayerResponseSchema.parse({ places: [place] })).toEqual({ places: [place] });
expect(tripCollectionLayerResponseSchema.safeParse({ places: [{ ...place, lat: null }] }).success).toBe(false);
});
});
@@ -0,0 +1,64 @@
import { COLLECTION_STATUSES } from '../collection/collection.schema';
import { idSchema } from '../common/primitives.schema';
import { placesLibraryCategorySchema } from '../places-library/places-library.schema';
import { z } from 'zod';
/**
* PLC-15/PLC-16: the lists of saved places a trip draws on, at
* `/api/trips/:tripId/collections`. A link gives no one access: everyone on
* the trip sees a linked list only when the list is open to them anyway, and
* the others do not learn it is there.
*/
/** Link one list the caller can open to the trip. */
export const tripCollectionLinkRequestSchema = z
.object({ collection_id: idSchema.describe('A list of saved places you can open') })
.strict();
export type TripCollectionLinkRequest = z.infer<typeof tripCollectionLinkRequestSchema>;
/** The user's role on a list: its owner, or the role their membership gives. */
export const TRIP_COLLECTION_ROLES = ['owner', 'admin', 'editor', 'viewer'] as const;
/** A linked list as the caller sees it. */
export const tripCollectionLinkSchema = z.object({
collection_id: z.number().int(),
name: z.string(),
color: z.string().nullable(),
role: z.enum(TRIP_COLLECTION_ROLES),
place_count: z.number().int().nonnegative(),
linked_by: z.number().int().nullable(),
created_at: z.string().nullable(),
});
export type TripCollectionLink = z.infer<typeof tripCollectionLinkSchema>;
/** The trip's linked lists the caller can open, and whether they may link or unlink one. */
export const tripCollectionLinksResponseSchema = z.object({
links: z.array(tripCollectionLinkSchema),
can_link: z.boolean(),
});
export type TripCollectionLinksResponse = z.infer<typeof tripCollectionLinksResponseSchema>;
/**
* One saved place of a linked list on the trip's map, with a position. `in_trip`
* says whether the trip already has it (it came from a place of this trip, or
* shares a provider id, or has the same name a few metres away), with that
* place's id.
*/
export const tripCollectionLayerPlaceSchema = z.object({
id: z.number().int(),
collection_id: z.number().int(),
name: z.string(),
lat: z.number(),
lng: z.number(),
category: placesLibraryCategorySchema.nullable(),
status: z.enum(COLLECTION_STATUSES),
in_trip: z.boolean(),
trip_place_id: z.number().int().nullable(),
});
export type TripCollectionLayerPlace = z.infer<typeof tripCollectionLayerPlaceSchema>;
export const tripCollectionLayerResponseSchema = z.object({
places: z.array(tripCollectionLayerPlaceSchema),
});
export type TripCollectionLayerResponse = z.infer<typeof tripCollectionLayerResponseSchema>;