mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
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:
@@ -108,6 +108,7 @@ import { TagsModule } from './tags/tags.module';
|
||||
import { TodoModule } from './todo/todo.module';
|
||||
import { ToursModule } from './tours/tours.module';
|
||||
import { TransitModule } from './transit/transit.module';
|
||||
import { TripCollectionsModule } from './trip-collections/trip-collections.module';
|
||||
import { TripInviteModule } from './trip-invite/trip-invite.module';
|
||||
import { TripAccessService } from './trip-membership/trip-access.service';
|
||||
import { TripMembershipModule } from './trip-membership/trip-membership.module';
|
||||
@@ -204,6 +205,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
|
||||
TripJournalLinkModule,
|
||||
CollectionsModule,
|
||||
PlacesLibraryModule,
|
||||
TripCollectionsModule,
|
||||
ShareModule,
|
||||
TripInviteModule,
|
||||
TransitModule,
|
||||
|
||||
@@ -1112,13 +1112,15 @@ export class CollectionsService {
|
||||
|
||||
/** The trip's own tag of each name: the one it has, or one made now; `known` keeps the new ones for the next place. */
|
||||
private async tripTagIds(tripId: number, userId: number, tags: { name: string; color: string }[], known: Map<string, number>): Promise<number[]> {
|
||||
const ids: number[] = [];
|
||||
for (const { name, color } of tags) {
|
||||
const key = name.trim().toLowerCase();
|
||||
if (!known.has(key)) known.set(key, (await this.tags.createTag({ user_id: userId, trip_id: tripId, name: name.trim(), color })).id);
|
||||
ids.push(known.get(key)!);
|
||||
}
|
||||
return ids;
|
||||
const keyOf = (name: string) => name.trim().toLowerCase();
|
||||
const missing = [...new Map(tags.filter(t => !known.has(keyOf(t.name))).map(t => [keyOf(t.name), t])).entries()];
|
||||
const made = await Promise.all(missing.map(async ([key, { name, color }]) =>
|
||||
[key, (await this.tags.createTag({ user_id: userId, trip_id: tripId, name: name.trim(), color })).id] as const));
|
||||
for (const [key, id] of made) known.set(key, id);
|
||||
return tags.flatMap(({ name }): number[] => {
|
||||
const id = known.get(keyOf(name));
|
||||
return id === undefined ? [] : [id];
|
||||
});
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import {
|
||||
COORD_DEDUP_TOLERANCE,
|
||||
normalizePlaceName,
|
||||
type PLACES_LIBRARY_DUPLICATE_FIELDS,
|
||||
type PLACES_LIBRARY_DUPLICATE_REASONS,
|
||||
} from '@trek/shared';
|
||||
|
||||
type DuplicateReason = (typeof PLACES_LIBRARY_DUPLICATE_REASONS)[number];
|
||||
type DuplicateField = (typeof PLACES_LIBRARY_DUPLICATE_FIELDS)[number];
|
||||
|
||||
/** An entry as the duplicate search reads it: its key, its facts and every provider id one of its uses carries. */
|
||||
export interface DuplicateCandidate {
|
||||
key: string;
|
||||
name: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
address: string | null;
|
||||
category_id: number | null;
|
||||
google_place_id: string | null;
|
||||
google_ftid: string | null;
|
||||
osm_id: string | null;
|
||||
/** Every provider id of the entry's own place and of its uses, trimmed. */
|
||||
provider_ids: readonly string[];
|
||||
}
|
||||
|
||||
/** Two entries that look like one place; `a` has the smaller key. */
|
||||
interface DuplicatePair {
|
||||
a: DuplicateCandidate;
|
||||
b: DuplicateCandidate;
|
||||
reasons: DuplicateReason[];
|
||||
}
|
||||
|
||||
/**
|
||||
* More entries than this under one provider id or in one name cell are not a
|
||||
* duplicate but a pattern (a chain's shared id, a placeholder name); they are
|
||||
* left out rather than paired with each other.
|
||||
*/
|
||||
export const DUPLICATE_BUCKET_MAX = 20;
|
||||
|
||||
/** The pair's key, `a` before `b`: what a dismissal stores and the page order follows. */
|
||||
export function pairKey(a: string, b: string): string {
|
||||
return a < b ? `${a}|${b}` : `${b}|${a}`;
|
||||
}
|
||||
|
||||
function near(a: DuplicateCandidate, b: DuplicateCandidate): boolean {
|
||||
if (a.lat === null || a.lng === null || b.lat === null || b.lng === null) return false;
|
||||
return Math.abs(a.lat - b.lat) <= COORD_DEDUP_TOLERANCE && Math.abs(a.lng - b.lng) <= COORD_DEDUP_TOLERANCE;
|
||||
}
|
||||
|
||||
/** The grid cell of a position, one tolerance wide, so a neighbour is in this cell or one of the eight around it. */
|
||||
function cellOf(lat: number, lng: number): [number, number] {
|
||||
return [Math.floor(lat / COORD_DEDUP_TOLERANCE), Math.floor(lng / COORD_DEDUP_TOLERANCE)];
|
||||
}
|
||||
|
||||
/** A cell and the eight around it. */
|
||||
const NEIGHBOURS: ReadonlyArray<readonly [number, number]> = [-1, 0, 1].flatMap((dx) =>
|
||||
[-1, 0, 1].map((dy) => [dx, dy] as const),
|
||||
);
|
||||
|
||||
function addTo<K, V>(map: Map<K, V[]>, key: K, value: V): void {
|
||||
const list = map.get(key);
|
||||
if (list) list.push(value);
|
||||
else map.set(key, [value]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The likely duplicates among `entries`, without comparing every entry with
|
||||
* every other: entries are bucketed by provider id and by normalized name in a
|
||||
* grid one `COORD_DEDUP_TOLERANCE` wide, and only entries sharing a bucket (or
|
||||
* a neighbouring cell) are compared. Ordered by pair key.
|
||||
*/
|
||||
export function findDuplicates(entries: readonly DuplicateCandidate[]): DuplicatePair[] {
|
||||
const pairs = new Map<string, DuplicatePair>();
|
||||
const add = (x: DuplicateCandidate, y: DuplicateCandidate, reason: DuplicateReason) => {
|
||||
if (x.key === y.key) return;
|
||||
const key = pairKey(x.key, y.key);
|
||||
const [a, b] = x.key < y.key ? [x, y] : [y, x];
|
||||
const pair = pairs.get(key) ?? { a, b, reasons: [] };
|
||||
if (!pair.reasons.includes(reason)) pair.reasons.push(reason);
|
||||
pairs.set(key, pair);
|
||||
};
|
||||
|
||||
const byProvider = new Map<string, DuplicateCandidate[]>();
|
||||
for (const entry of entries) for (const id of new Set(entry.provider_ids)) addTo(byProvider, id, entry);
|
||||
for (const bucket of byProvider.values()) {
|
||||
if (bucket.length > DUPLICATE_BUCKET_MAX) continue;
|
||||
bucket.forEach((p, i) => {
|
||||
for (const q of bucket.slice(i + 1)) add(p, q, 'provider_id');
|
||||
});
|
||||
}
|
||||
|
||||
const byCell = new Map<string, DuplicateCandidate[]>();
|
||||
for (const entry of entries) {
|
||||
const name = normalizePlaceName(entry.name);
|
||||
if (name === null || entry.lat === null || entry.lng === null) continue;
|
||||
const [x, y] = cellOf(entry.lat, entry.lng);
|
||||
addTo(byCell, `${name}|${x}|${y}`, entry);
|
||||
}
|
||||
for (const [cellKey, bucket] of byCell) {
|
||||
if (bucket.length > DUPLICATE_BUCKET_MAX) continue;
|
||||
const [name, xs, ys] = cellKey.split('|') as [string, string, string];
|
||||
const x = Number(xs);
|
||||
const y = Number(ys);
|
||||
for (const [dx, dy] of NEIGHBOURS) {
|
||||
const other = byCell.get(`${name}|${x + dx}|${y + dy}`) ?? [];
|
||||
if (other.length > DUPLICATE_BUCKET_MAX) continue;
|
||||
for (const p of bucket) for (const q of other) if (near(p, q)) add(p, q, 'name_nearby');
|
||||
}
|
||||
}
|
||||
|
||||
return [...pairs.entries()].sort(([k1], [k2]) => (k1 < k2 ? -1 : k1 > k2 ? 1 : 0)).map(([, pair]) => pair);
|
||||
}
|
||||
|
||||
const sameText = (a: string | null, b: string | null) =>
|
||||
(a ?? '').trim().toLowerCase() === (b ?? '').trim().toLowerCase();
|
||||
|
||||
/** The facts the two sides of a pair differ in. */
|
||||
export function differingFields(a: DuplicateCandidate, b: DuplicateCandidate): DuplicateField[] {
|
||||
const fields: DuplicateField[] = [];
|
||||
if (normalizePlaceName(a.name) !== normalizePlaceName(b.name)) fields.push('name');
|
||||
const bothPlaced = a.lat !== null && a.lng !== null && b.lat !== null && b.lng !== null;
|
||||
const neitherPlaced = (a.lat === null || a.lng === null) && (b.lat === null || b.lng === null);
|
||||
if (!neitherPlaced && !(bothPlaced && near(a, b))) fields.push('position');
|
||||
if (!sameText(a.address, b.address)) fields.push('address');
|
||||
if (a.category_id !== b.category_id) fields.push('category');
|
||||
if (!sameText(a.google_place_id, b.google_place_id)) fields.push('google_place_id');
|
||||
if (!sameText(a.google_ftid, b.google_ftid)) fields.push('google_ftid');
|
||||
if (!sameText(a.osm_id, b.osm_id)) fields.push('osm_id');
|
||||
return fields;
|
||||
}
|
||||
|
||||
/** A page cursor: the pair key of the page's last pair, opaque to the client. */
|
||||
export function encodeDuplicatesCursor(key: string): string {
|
||||
return Buffer.from(key, 'utf8').toString('base64url');
|
||||
}
|
||||
|
||||
/** The pair key a cursor names, or null for one this route did not hand out. */
|
||||
export function decodeDuplicatesCursor(cursor: string): string | null {
|
||||
const key = Buffer.from(cursor, 'base64url').toString('utf8');
|
||||
return /^(own|trip|list):\d+\|(own|trip|list):\d+$/.test(key) ? key : null;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { badRequest } from '../common/domain-error';
|
||||
import {
|
||||
decodeDuplicatesCursor,
|
||||
differingFields,
|
||||
encodeDuplicatesCursor,
|
||||
findDuplicates,
|
||||
pairKey,
|
||||
type DuplicateCandidate,
|
||||
} from './place-duplicates.helpers';
|
||||
import { PlaceIdentitiesService } from './place-identities.service';
|
||||
import { categoryOf, entryKey, leadOf, originsOf, type EntryRows, type OriginAccess } from './places-library.helpers';
|
||||
import { PlacesLibraryService, type LibraryUser } from './places-library.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
externalIdsOf,
|
||||
PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT,
|
||||
type PlacesLibraryDuplicateSide,
|
||||
type PlacesLibraryDuplicatesQuery,
|
||||
type PlacesLibraryDuplicatesResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** The first of the entry's values for one provider id: its own place's, else its first use's that has one. */
|
||||
function providerId(rows: EntryRows, field: 'google_place_id' | 'google_ftid' | 'osm_id'): string | null {
|
||||
const own = rows.identity?.[field] ?? null;
|
||||
if (own) return own;
|
||||
return [...rows.trips, ...rows.saved].find((row) => row[field])?.[field] ?? null;
|
||||
}
|
||||
|
||||
/** An entry as the duplicate search compares it. */
|
||||
function candidateOf(rows: EntryRows): DuplicateCandidate {
|
||||
const lead = leadOf(rows);
|
||||
const ids = [rows.identity, ...rows.trips, ...rows.saved].flatMap((row) => (row ? externalIdsOf(row) : []));
|
||||
return {
|
||||
key: entryKey(rows.anchor),
|
||||
name: lead.name,
|
||||
lat: lead.lat,
|
||||
lng: lead.lng,
|
||||
address: lead.address,
|
||||
category_id: lead.category_id,
|
||||
google_place_id: providerId(rows, 'google_place_id'),
|
||||
google_ftid: providerId(rows, 'google_ftid'),
|
||||
osm_id: providerId(rows, 'osm_id'),
|
||||
provider_ids: [...new Set(ids)],
|
||||
};
|
||||
}
|
||||
|
||||
function sideOf(rows: EntryRows, candidate: DuplicateCandidate, access: OriginAccess): PlacesLibraryDuplicateSide {
|
||||
return {
|
||||
key: candidate.key,
|
||||
identity_id: rows.identity?.id ?? null,
|
||||
name: candidate.name,
|
||||
address: candidate.address,
|
||||
lat: candidate.lat,
|
||||
lng: candidate.lng,
|
||||
category: categoryOf(leadOf(rows)),
|
||||
google_place_id: candidate.google_place_id,
|
||||
google_ftid: candidate.google_ftid,
|
||||
osm_id: candidate.osm_id,
|
||||
origins: originsOf(rows, access),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* PLC-13: the likely duplicates among the user's own "All places", computed
|
||||
* on request over the entries they reach today and paged: two entries that
|
||||
* share a provider id, or carry the same name (trimmed, case ignored) within
|
||||
* `COORD_DEDUP_TOLERANCE`. Entries are bucketed first (`findDuplicates`), so
|
||||
* no entry is compared with every other. Pairs the user turned down stay out.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceDuplicatesService {
|
||||
constructor(
|
||||
private readonly library: PlacesLibraryService,
|
||||
private readonly identities: PlaceIdentitiesService,
|
||||
) {}
|
||||
|
||||
async list(user: LibraryUser, query: PlacesLibraryDuplicatesQuery): Promise<PlacesLibraryDuplicatesResponse> {
|
||||
const after = query.cursor === undefined ? null : decodeDuplicatesCursor(query.cursor);
|
||||
if (query.cursor !== undefined && after === null) {
|
||||
throw badRequest('Invalid cursor: pass the next_cursor of the page before');
|
||||
}
|
||||
const limit = query.limit ?? PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT;
|
||||
const reach = await this.library.reach(user.id);
|
||||
const uses = await this.library.usesOf(reach, null);
|
||||
const rows = await this.library.rows(reach, [...new Set(uses.map((use) => use.anchor_key))], uses);
|
||||
const rowsByKey = new Map(rows.map((row) => [entryKey(row.anchor), row]));
|
||||
const dismissed = await this.identities.dismissedPairs(user.id);
|
||||
const pairs = findDuplicates(rows.map(candidateOf)).filter((pair) => {
|
||||
const key = pairKey(pair.a.key, pair.b.key);
|
||||
return !dismissed.has(key) && (after === null || key > after);
|
||||
});
|
||||
const page = pairs.slice(0, limit);
|
||||
|
||||
const pageRows = [...new Set(page.flatMap((pair) => [pair.a.key, pair.b.key]))].flatMap((key): EntryRows[] => {
|
||||
const row = rowsByKey.get(key);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
const access = await this.library.access(
|
||||
user,
|
||||
pageRows.flatMap((row) => row.trips),
|
||||
pageRows.flatMap((row) => row.saved),
|
||||
);
|
||||
const whole = await this.identities.wholeIdentitiesOf(user.id, pageRows);
|
||||
const mergeable = new Map(pageRows.map((row, index) => [entryKey(row.anchor), whole[index] ?? false]));
|
||||
|
||||
const duplicates = page.flatMap((pair) => {
|
||||
const a = rowsByKey.get(pair.a.key);
|
||||
const b = rowsByKey.get(pair.b.key);
|
||||
if (!a || !b) return [];
|
||||
return [
|
||||
{
|
||||
a: sideOf(a, pair.a, access),
|
||||
b: sideOf(b, pair.b, access),
|
||||
reasons: pair.reasons,
|
||||
differing: differingFields(pair.a, pair.b),
|
||||
can_merge: (mergeable.get(pair.a.key) ?? false) && (mergeable.get(pair.b.key) ?? false),
|
||||
},
|
||||
];
|
||||
});
|
||||
const last = page[page.length - 1];
|
||||
return {
|
||||
duplicates,
|
||||
next_cursor: pairs.length > limit && last ? encodeDuplicatesCursor(pairKey(last.a.key, last.b.key)) : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { logError, logInfo } from '../audit/audit-log.logger';
|
||||
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
|
||||
import { PlaceIdentitiesService } from './place-identities.service';
|
||||
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Nightly removal of the own places (D5) nothing holds any more. A deleted
|
||||
* trip, place or list takes its links along, and the own place they made up
|
||||
* would otherwise keep the name, position and address it copied from them
|
||||
* until its owner next changes an own place.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceIdentitiesPruneJob implements OnApplicationBootstrap {
|
||||
constructor(
|
||||
private readonly identities: PlaceIdentitiesService,
|
||||
private readonly registrar: CronRegistrarService,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
if (!this.registrar.isEnabled()) return;
|
||||
this.registrar.register('place-identities-prune', '20 4 * * *', () => this.tick());
|
||||
}
|
||||
|
||||
async tick(): Promise<void> {
|
||||
try {
|
||||
const removed = await this.identities.pruneAll();
|
||||
if (removed > 0) logInfo(`Own places: removed ${removed} without a place left`);
|
||||
} catch (err: unknown) {
|
||||
logError(`Own places prune: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { PlaceDuplicatesService } from './place-duplicates.service';
|
||||
import { PlaceIdentitiesService } from './place-identities.service';
|
||||
import {
|
||||
PlacesLibraryDuplicatesQueryDto,
|
||||
PlacesLibraryLinkDto,
|
||||
PlacesLibraryMergeDto,
|
||||
PlacesLibraryPairDto,
|
||||
PlacesLibraryUnlinkDto,
|
||||
} from './places-library.dto';
|
||||
import { Body, Controller, Get, HttpCode, Param, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
placesLibraryDuplicatesResponseSchema,
|
||||
placesLibraryEntryResponseSchema,
|
||||
placesLibraryMergeResponseSchema,
|
||||
successResponseSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* D5/PLC-13 under /api/addons/collections/library: the user's own places in
|
||||
* "All places". Assigning uses to one, taking one out, the duplicate
|
||||
* suggestions, merging two entries and undoing it. Everything here is the
|
||||
* user's own and changes no trip place and no saved place, so nothing is
|
||||
* broadcast. Behind the Collections addon like the rest of the library.
|
||||
*/
|
||||
@Controller('api/addons/collections/library')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
|
||||
export class PlaceIdentitiesController {
|
||||
constructor(
|
||||
private readonly identities: PlaceIdentitiesService,
|
||||
private readonly duplicates: PlaceDuplicatesService,
|
||||
) {}
|
||||
|
||||
@Post('places/link')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(placesLibraryEntryResponseSchema)
|
||||
async link(@CurrentUser() user: User, @Body() body: PlacesLibraryLinkDto) {
|
||||
return this.identities.link({ id: user.id, role: user.role }, body);
|
||||
}
|
||||
|
||||
@Post('places/unlink')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(placesLibraryEntryResponseSchema)
|
||||
async unlink(@CurrentUser() user: User, @Body() body: PlacesLibraryUnlinkDto) {
|
||||
return this.identities.unlink({ id: user.id, role: user.role }, body);
|
||||
}
|
||||
|
||||
@Get('duplicates')
|
||||
@ResponseContract(placesLibraryDuplicatesResponseSchema)
|
||||
async listDuplicates(@CurrentUser() user: User, @Query() query: PlacesLibraryDuplicatesQueryDto) {
|
||||
return this.duplicates.list({ id: user.id, role: user.role }, query);
|
||||
}
|
||||
|
||||
@Post('duplicates/dismiss')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(successResponseSchema)
|
||||
async dismiss(@CurrentUser() user: User, @Body() body: PlacesLibraryPairDto) {
|
||||
return this.identities.dismiss(user.id, body.a, body.b);
|
||||
}
|
||||
|
||||
@Post('merges')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(placesLibraryMergeResponseSchema)
|
||||
async merge(@CurrentUser() user: User, @Body() body: PlacesLibraryMergeDto) {
|
||||
return this.identities.merge({ id: user.id, role: user.role }, body.leading, body.other);
|
||||
}
|
||||
|
||||
@Post('merges/:id/undo')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(successResponseSchema)
|
||||
async undoMerge(@CurrentUser() user: User, @Param('id', rowId('Merge not found')) id: number) {
|
||||
return this.identities.undoMerge({ id: user.id, role: user.role }, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { canRead, canReadTrips, canWrite } from '../../mcp/scopes';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { PlaceDuplicatesService } from './place-duplicates.service';
|
||||
import { PlaceIdentitiesService } from './place-identities.service';
|
||||
import type { LibraryUser } from './places-library.service';
|
||||
import {
|
||||
PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT,
|
||||
PLACES_LIBRARY_DUPLICATES_PAGE_MAX,
|
||||
placesLibraryDuplicatesQuerySchema,
|
||||
placesLibraryLinkRequestSchema,
|
||||
placesLibraryMergeRequestSchema,
|
||||
placesLibraryPairRequestSchema,
|
||||
placesLibraryUndoMergeRequestSchema,
|
||||
placesLibraryUnlinkRequestSchema,
|
||||
type PlacesLibraryDuplicatesQuery,
|
||||
type PlacesLibraryLinkRequest,
|
||||
type PlacesLibraryMergeRequest,
|
||||
type PlacesLibraryPairRequest,
|
||||
type PlacesLibraryUndoMergeRequest,
|
||||
type PlacesLibraryUse,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** The own places group trips and lists, so a token reads trips and lists. */
|
||||
const readsTripsAndLists = (ctx: McpContext) => canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
|
||||
/** Changing them writes only the user's own grouping, under the lists' write scope. */
|
||||
const writesOwnPlaces = (ctx: McpContext) => canWrite(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
|
||||
|
||||
const OWN_ONLY =
|
||||
'Only your own view of All places changes: no trip place and no saved place is renamed, moved or deleted, and no one else sees it.';
|
||||
|
||||
/**
|
||||
* D5/PLC-13 over the same services and checks as the REST routes under
|
||||
* /api/addons/collections/library: the user's own places, the duplicate
|
||||
* suggestions and merges.
|
||||
*/
|
||||
@McpController()
|
||||
export class PlaceIdentitiesMcp {
|
||||
constructor(
|
||||
private readonly identities: PlaceIdentitiesService,
|
||||
private readonly duplicates: PlaceDuplicatesService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
private async user(userId: number): Promise<LibraryUser> {
|
||||
return { id: userId, role: (await this.guards.isAdminUser(userId)) ? 'admin' : 'user' };
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'link_library_places',
|
||||
description: `Put trip places and saved places together as one place of your own in All places (list_all_places then shows them as one entry, key own:<id>). Name each by kind trip (place_id) or kind list (collection_place_id). With identity_id they join that own place; without it a new one is made, named and placed like the first one listed. A place that was part of another own place of yours moves. ${OWN_ONLY}`,
|
||||
inputSchema: placesLibraryLinkRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesOwnPlaces,
|
||||
})
|
||||
async linkLibraryPlaces(input: PlacesLibraryLinkRequest, ctx: McpContext) {
|
||||
return ok(await this.identities.link(await this.user(ctx.userId), input));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'unlink_library_place',
|
||||
description: `Take one trip place (kind trip) or saved place (kind list) out of the own place of yours it is part of; it is an entry of its own again. Answers the entry it belongs to now. ${OWN_ONLY}`,
|
||||
inputSchema: placesLibraryUnlinkRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesOwnPlaces,
|
||||
})
|
||||
async unlinkLibraryPlace(input: PlacesLibraryUse, ctx: McpContext) {
|
||||
return ok(await this.identities.unlink(await this.user(ctx.userId), input));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_library_duplicates',
|
||||
description: `Likely duplicates in All places, ${PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT} pairs at a time unless limit says otherwise (at most ${PLACES_LIBRARY_DUPLICATES_PAGE_MAX}): two entries that share a provider id (reason provider_id) or carry the same name a few metres apart (reason name_nearby). Each pair has both entries (key, name, position, address, category, provider ids, origins), the fields they differ in and can_merge (false while one side holds a place you can no longer open). Pairs you dismissed stay out. Go on with next_cursor.`,
|
||||
inputSchema: placesLibraryDuplicatesQuerySchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: readsTripsAndLists,
|
||||
})
|
||||
async listLibraryDuplicates(input: PlacesLibraryDuplicatesQuery, ctx: McpContext) {
|
||||
return ok(await this.duplicates.list(await this.user(ctx.userId), input));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'dismiss_library_duplicate',
|
||||
description:
|
||||
'Turn a duplicate suggestion of list_library_duplicates down by the keys of its two entries, so it is not suggested again. Changes nothing else.',
|
||||
inputSchema: placesLibraryPairRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesOwnPlaces,
|
||||
})
|
||||
async dismissLibraryDuplicate(input: PlacesLibraryPairRequest, ctx: McpContext) {
|
||||
return ok(await this.identities.dismiss(ctx.userId, input.a, input.b));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'merge_library_places',
|
||||
description: `Merge two entries of All places (by their keys) into one own place that keeps the name and position of leading; every trip place and saved place of both stays where it is and now shows under the merged entry. Refused while either side holds a place you can no longer open. Answers merge_id for undo_library_merge and the merged entry. ${OWN_ONLY}`,
|
||||
inputSchema: placesLibraryMergeRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesOwnPlaces,
|
||||
})
|
||||
async mergeLibraryPlaces(input: PlacesLibraryMergeRequest, ctx: McpContext) {
|
||||
return ok(await this.identities.merge(await this.user(ctx.userId), input.leading, input.other));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'undo_library_merge',
|
||||
description:
|
||||
'Take a merge of merge_library_places back by its merge_id: the places the merged entry brought along are an own place of their own again.',
|
||||
inputSchema: placesLibraryUndoMergeRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesOwnPlaces,
|
||||
})
|
||||
async undoLibraryMerge(input: PlacesLibraryUndoMergeRequest, ctx: McpContext) {
|
||||
return ok(await this.identities.undoMerge(await this.user(ctx.userId), input.merge_id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import { UserPlaceLinks } from '../../db/entities/UserPlaceLinks.entity';
|
||||
import { UserPlaceMergeDismissals } from '../../db/entities/UserPlaceMergeDismissals.entity';
|
||||
import { UserPlaceMerges } from '../../db/entities/UserPlaceMerges.entity';
|
||||
import { UserPlaces } from '../../db/entities/UserPlaces.entity';
|
||||
import { USER_PLACE_MERGE_MOVED_LINKS } from '../../db/json-columns';
|
||||
import type { LinkedUse, UserPlaceLinksRepository } from '../../db/repositories/UserPlaceLinks.repository';
|
||||
import type { UserPlaceMergeDismissalsRepository } from '../../db/repositories/UserPlaceMergeDismissals.repository';
|
||||
import type { UserPlaceMergesRepository } from '../../db/repositories/UserPlaceMerges.repository';
|
||||
import type { UserPlaceFacts, UserPlacesRepository } from '../../db/repositories/UserPlaces.repository';
|
||||
import { decodeJson, encodeJson } from '../../utils/json-column';
|
||||
import { badRequest, forbidden, notFound } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { pairKey } from './place-duplicates.helpers';
|
||||
import { anchorOfIdentity, anchorOfKey, firstUseOf, useKey, type EntryRows } from './places-library.helpers';
|
||||
import { PlacesLibraryService, placeNotFound, type LibraryReach, type LibraryUser } from './places-library.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type {
|
||||
PlacesLibraryEntryResponse,
|
||||
PlacesLibraryLinkRequest,
|
||||
PlacesLibraryMergeResponse,
|
||||
PlacesLibraryUse,
|
||||
SuccessResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
const notAssigned = () => notFound('This place is not part of one of your own places');
|
||||
const mergeNotFound = () => notFound('Merge not found');
|
||||
|
||||
/** The uses of an entry, as the links name them. */
|
||||
function usesOfRows(rows: EntryRows): LinkedUse[] {
|
||||
return [
|
||||
...rows.trips.map((row) => ({ kind: 'trip' as const, id: row.id })),
|
||||
...rows.saved.map((row) => ({ kind: 'list' as const, id: row.id })),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* D5/D6: the user's own places. Assigning uses to one, taking one out,
|
||||
* merging two entries and undoing a merge change only the user's own rows
|
||||
* (`user_places`, `user_place_links`, `user_place_merges`); no trip place and
|
||||
* no saved place is written, so nothing reaches anyone else and nothing needs
|
||||
* a realtime event. Every use named must be one the user reaches today
|
||||
* (the library's checks), else it is not found.
|
||||
*
|
||||
* An own place left without a link is removed in the same transaction as the
|
||||
* write that emptied it; one emptied by a deleted trip, place or list goes at
|
||||
* the user's next write here or with the nightly sweep
|
||||
* (`PlaceIdentitiesPruneJob`).
|
||||
*
|
||||
* Copies and restores make new rows, and a link names a row: a trip copy
|
||||
* (`TripsService` copy, `insertPlaceCopy`, also `copy_trip`) takes no link
|
||||
* along, so the copy's places start as entries of their own, and the planner's
|
||||
* undo of a deleted place (`placeRestorePayload` → `addPlace`) makes a new
|
||||
* place whose old link went with the deleted one (ON DELETE CASCADE). Neither
|
||||
* is linked again on its own; the user assigns it again. The lists a trip
|
||||
* draws on (`trip_collection_links`) are not copied with a trip either.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceIdentitiesService {
|
||||
constructor(
|
||||
private readonly library: PlacesLibraryService,
|
||||
@InjectRepository(UserPlaces) private readonly identities: UserPlacesRepository,
|
||||
@InjectRepository(UserPlaceLinks) private readonly links: UserPlaceLinksRepository,
|
||||
@InjectRepository(UserPlaceMerges) private readonly merges: UserPlaceMergesRepository,
|
||||
@InjectRepository(UserPlaceMergeDismissals) private readonly dismissals: UserPlaceMergeDismissalsRepository,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/** Puts the uses into one own place: `identity_id`'s, or a new one named after the first use. */
|
||||
async link(user: LibraryUser, request: PlacesLibraryLinkRequest): Promise<PlacesLibraryEntryResponse> {
|
||||
const uses = uniqueUses(request.uses);
|
||||
const reach = await this.library.reach(user.id);
|
||||
const reachable = new Set((await this.library.usesOf(reach, null)).map((use) => useKey(use.from_list, use.use_id)));
|
||||
if (uses.some((use) => !reachable.has(useKey(use.kind === 'trip' ? 0 : 1, use.id)))) throw placeNotFound();
|
||||
if (request.identity_id !== undefined) {
|
||||
const own = await this.identities.findOwn(user.id, request.identity_id);
|
||||
if (!own || own.merged_into_id !== null) throw placeNotFound();
|
||||
}
|
||||
const first = uses[0];
|
||||
if (!first) throw placeNotFound();
|
||||
const target =
|
||||
request.identity_id === undefined ? { facts: await this.factsOfUse(reach, first) } : { id: request.identity_id };
|
||||
const identityId = await this.uow.transactional(async () => {
|
||||
const id = 'id' in target ? target.id : await this.identities.create(user.id, target.facts);
|
||||
await this.attach(user.id, id, uses, 'user');
|
||||
await this.identities.touch(user.id, id);
|
||||
await this.prune(user.id);
|
||||
return id;
|
||||
});
|
||||
return { entry: await this.library.entry(user, anchorOfIdentity(identityId)) };
|
||||
}
|
||||
|
||||
/** Takes one use out of the own place it is in; it is an entry of its own (or of its source) again. */
|
||||
async unlink(user: LibraryUser, use: PlacesLibraryUse): Promise<PlacesLibraryEntryResponse> {
|
||||
const reach = await this.library.reach(user.id);
|
||||
if ((await this.library.anchorOfUse(reach, use.kind, use.id)) === null) throw placeNotFound();
|
||||
const link = await this.links.findForUse(user.id, use);
|
||||
if (!link) throw notAssigned();
|
||||
await this.uow.transactional(async () => {
|
||||
await this.links.deleteOwn(user.id, link.id);
|
||||
await this.identities.touch(user.id, link.user_place_id);
|
||||
await this.prune(user.id);
|
||||
});
|
||||
return { entry: await this.library.entry(user, await this.library.anchorOfUse(reach, use.kind, use.id)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges `otherKey`'s entry into `leadingKey`'s: both become own places (an
|
||||
* entry that was none becomes one with all its uses), the other's links move
|
||||
* to the leading one, and the other is marked merged into it. The merged
|
||||
* place keeps the leading entry's name and position; neither is written into
|
||||
* a trip or a list. Refused while either side holds a use the user cannot
|
||||
* open any more, since they could not see what they merge.
|
||||
*/
|
||||
async merge(user: LibraryUser, leadingKey: string, otherKey: string): Promise<PlacesLibraryMergeResponse> {
|
||||
const leading = anchorOfKey(leadingKey);
|
||||
const other = anchorOfKey(otherKey);
|
||||
if (leading === null || other === null) throw placeNotFound();
|
||||
if (leading === other) throw badRequest('Pick two different places to merge');
|
||||
const reach = await this.library.reach(user.id);
|
||||
const [lead, rest] = await this.library.rows(reach, [leading, other]);
|
||||
if (!lead || !rest) throw placeNotFound();
|
||||
if (!(await this.wholeIdentities(user.id, [lead, rest]))) {
|
||||
throw forbidden('One of these places holds a trip place or saved place you can no longer open');
|
||||
}
|
||||
const { mergeId, leadId } = await this.uow.transactional(async () => {
|
||||
const leadId = await this.materialize(user.id, lead);
|
||||
const restId = await this.materialize(user.id, rest);
|
||||
const moved = await this.links.idsOf(user.id, restId);
|
||||
await this.links.moveTo(user.id, moved, leadId);
|
||||
await this.identities.setMergedInto(user.id, restId, leadId);
|
||||
await this.identities.touch(user.id, leadId);
|
||||
const mergeId = await this.merges.create(
|
||||
user.id,
|
||||
leadId,
|
||||
restId,
|
||||
encodeJson(USER_PLACE_MERGE_MOVED_LINKS, moved),
|
||||
);
|
||||
return { mergeId, leadId };
|
||||
});
|
||||
return { merge_id: mergeId, entry: await this.library.entry(user, anchorOfIdentity(leadId)) };
|
||||
}
|
||||
|
||||
/** Takes a merge back: the moved links return to the merged place, which stands on its own again. */
|
||||
async undoMerge(user: LibraryUser, mergeId: number): Promise<SuccessResponse> {
|
||||
const merge = await this.merges.findOwn(user.id, mergeId);
|
||||
if (!merge) throw mergeNotFound();
|
||||
const moved = decodeJson(USER_PLACE_MERGE_MOVED_LINKS, merge.moved_link_ids, `user_place_merges ${merge.id}`);
|
||||
await this.uow.transactional(async () => {
|
||||
await this.links.moveTo(user.id, moved, merge.merged_id);
|
||||
await this.identities.setMergedInto(user.id, merge.merged_id, null);
|
||||
await this.identities.touch(user.id, merge.leading_id);
|
||||
await this.merges.deleteIds([merge.id]);
|
||||
await this.prune(user.id);
|
||||
});
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/** Turns a duplicate suggestion down, so it is not suggested again. */
|
||||
async dismiss(userId: number, a: string, b: string): Promise<SuccessResponse> {
|
||||
if (anchorOfKey(a) === null || anchorOfKey(b) === null) throw placeNotFound();
|
||||
if (a === b) throw badRequest('Pick two different places');
|
||||
const [keyA, keyB] = pairKey(a, b).split('|') as [string, string];
|
||||
await this.dismissals.dismiss(userId, { key_a: keyA, key_b: keyB });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/** The suggestions the user turned down, by pair key. */
|
||||
async dismissedPairs(userId: number): Promise<Set<string>> {
|
||||
return new Set((await this.dismissals.listForUser(userId)).map((row) => pairKey(row.key_a, row.key_b)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether every own place among `rows` holds only uses the user reaches
|
||||
* today, so merging moves nothing they cannot see. Answers per entry.
|
||||
*/
|
||||
async wholeIdentitiesOf(userId: number, rows: readonly EntryRows[]): Promise<boolean[]> {
|
||||
const ids = rows.flatMap((row) => (row.identity ? [row.identity.id] : []));
|
||||
const counts = new Map((await this.identities.linkCounts(userId, ids)).map((row) => [row.id, row.links]));
|
||||
return rows.map((row) => !row.identity || (counts.get(row.identity.id) ?? 0) <= row.linked.size);
|
||||
}
|
||||
|
||||
/** Removes every own place, of every user, nothing holds any more: the nightly sweep. */
|
||||
async pruneAll(): Promise<number> {
|
||||
return this.uow.transactional(async () => this.prune(null));
|
||||
}
|
||||
|
||||
private async wholeIdentities(userId: number, rows: readonly EntryRows[]): Promise<boolean> {
|
||||
return (await this.wholeIdentitiesOf(userId, rows)).every(Boolean);
|
||||
}
|
||||
|
||||
/** Moves the uses into the own place `id`, out of any other of the user's. Runs inside the caller's transaction. */
|
||||
private async attach(
|
||||
userId: number,
|
||||
id: number,
|
||||
uses: readonly LinkedUse[],
|
||||
linkedBy: 'user' | 'merge',
|
||||
): Promise<void> {
|
||||
await this.links.detach(userId, uses);
|
||||
await this.links.insert(userId, id, uses, linkedBy);
|
||||
}
|
||||
|
||||
/** The entry's own place, made from its first use when it has none yet. Runs inside the caller's transaction. */
|
||||
private async materialize(userId: number, rows: EntryRows): Promise<number> {
|
||||
if (rows.identity) return rows.identity.id;
|
||||
const first = firstUseOf(rows);
|
||||
const id = await this.identities.create(userId, {
|
||||
name: first.name,
|
||||
lat: first.lat,
|
||||
lng: first.lng,
|
||||
address: first.address,
|
||||
category_id: first.category_id,
|
||||
google_place_id: first.google_place_id,
|
||||
google_ftid: first.google_ftid,
|
||||
osm_id: first.osm_id,
|
||||
});
|
||||
await this.attach(userId, id, usesOfRows(rows), 'merge');
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The facts a new own place takes from the use it is named after. */
|
||||
private async factsOfUse(reach: LibraryReach, use: LinkedUse): Promise<UserPlaceFacts> {
|
||||
const anchor = await this.library.anchorOfUse(reach, use.kind, use.id);
|
||||
const rows = anchor === null ? [] : await this.library.rows(reach, [anchor]);
|
||||
const row =
|
||||
use.kind === 'trip'
|
||||
? rows[0]?.trips.find((trip) => trip.id === use.id)
|
||||
: rows[0]?.saved.find((saved) => saved.id === use.id);
|
||||
if (!row) throw placeNotFound();
|
||||
return {
|
||||
name: row.name,
|
||||
lat: row.lat,
|
||||
lng: row.lng,
|
||||
address: row.address,
|
||||
category_id: row.category_id,
|
||||
google_place_id: row.google_place_id,
|
||||
google_ftid: row.google_ftid,
|
||||
osm_id: row.osm_id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the merges none of whose moved links is left, then the own places of
|
||||
* the user (of everyone when null) that hold no link and no merge names.
|
||||
* Runs inside the caller's transaction.
|
||||
*/
|
||||
private async prune(userId: number | null): Promise<number> {
|
||||
const merges = await this.merges.list(userId);
|
||||
const moved = new Map(
|
||||
merges.map((merge) => [
|
||||
merge.id,
|
||||
decodeJson(USER_PLACE_MERGE_MOVED_LINKS, merge.moved_link_ids, `user_place_merges ${merge.id}`),
|
||||
]),
|
||||
);
|
||||
const alive = new Set(await this.links.existing([...new Set([...moved.values()].flat())]));
|
||||
const spent = merges.filter((merge) => !(moved.get(merge.id) ?? []).some((id) => alive.has(id)));
|
||||
await this.merges.deleteIds(spent.map((merge) => merge.id));
|
||||
return this.identities.pruneEmpty(userId);
|
||||
}
|
||||
}
|
||||
|
||||
/** The uses once each, in the order given. */
|
||||
function uniqueUses(uses: readonly PlacesLibraryUse[]): LinkedUse[] {
|
||||
const seen = new Set<string>();
|
||||
return uses.filter((use) => {
|
||||
const key = `${use.kind}:${use.id}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,18 @@
|
||||
import { placesLibraryQuerySchema } from '@trek/shared';
|
||||
import {
|
||||
placesLibraryDuplicatesQuerySchema,
|
||||
placesLibraryQuerySchema,
|
||||
placesLibraryLinkRequestSchema,
|
||||
placesLibraryMergeRequestSchema,
|
||||
placesLibraryPairRequestSchema,
|
||||
placesLibraryUnlinkRequestSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
export class PlacesLibraryQueryDto extends createZodDto(placesLibraryQuerySchema) {}
|
||||
|
||||
export class PlacesLibraryLinkDto extends createZodDto(placesLibraryLinkRequestSchema) {}
|
||||
export class PlacesLibraryUnlinkDto extends createZodDto(placesLibraryUnlinkRequestSchema) {}
|
||||
export class PlacesLibraryDuplicatesQueryDto extends createZodDto(placesLibraryDuplicatesQuerySchema) {}
|
||||
export class PlacesLibraryPairDto extends createZodDto(placesLibraryPairRequestSchema) {}
|
||||
export class PlacesLibraryMergeDto extends createZodDto(placesLibraryMergeRequestSchema) {}
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
import type {
|
||||
LibraryAnchorRow,
|
||||
LibraryCollectionPlaceRow,
|
||||
LibraryPosition,
|
||||
LibraryRatingRow,
|
||||
LibrarySort,
|
||||
LibraryTripPlaceRow,
|
||||
import {
|
||||
ANCHOR_LIST,
|
||||
ANCHOR_OWN,
|
||||
ANCHOR_SPAN,
|
||||
ANCHOR_TRIP,
|
||||
type LibraryAnchorRow,
|
||||
type LibraryCollectionPlaceRow,
|
||||
type LibraryIdentityRow,
|
||||
type LibraryPosition,
|
||||
type LibraryRatingRow,
|
||||
type LibrarySort,
|
||||
type LibraryTripPlaceRow,
|
||||
type LibraryUseRow,
|
||||
} from '../../db/repositories/PlacesLibrary.repository';
|
||||
import {
|
||||
collectionStatusSchema,
|
||||
PLACES_LIBRARY_KEY_PATTERN,
|
||||
PLACES_LIBRARY_SORTS,
|
||||
type PlacesLibraryCategory,
|
||||
type PlacesLibraryEntry,
|
||||
type PlacesLibraryInfo,
|
||||
type PlacesLibraryKind,
|
||||
type PlacesLibraryListOrigin,
|
||||
type PlacesLibraryRating,
|
||||
type PlacesLibraryTripOrigin,
|
||||
@@ -22,9 +30,41 @@ import { z } from 'zod';
|
||||
/** A cursor as it is encoded: the sort it belongs to, the last entry's sort value and its key. */
|
||||
const cursorSchema = z.tuple([z.enum(PLACES_LIBRARY_SORTS), z.string(), z.number().int()]);
|
||||
|
||||
/** The key an entry is known by: its trip place id when it has one, else its saved place id negated. */
|
||||
const PREFIX_OF_KIND: Record<number, string> = { [ANCHOR_TRIP]: 'trip', [ANCHOR_LIST]: 'list', [ANCHOR_OWN]: 'own' };
|
||||
const KIND_OF_PREFIX: Record<string, number> = { trip: ANCHOR_TRIP, list: ANCHOR_LIST, own: ANCHOR_OWN };
|
||||
|
||||
/** The key an entry is known by: own:<id>, trip:<place id> or list:<saved place id>. */
|
||||
export function entryKey(anchor: number): string {
|
||||
return anchor > 0 ? `trip:${anchor}` : `list:${-anchor}`;
|
||||
return `${PREFIX_OF_KIND[anchor % ANCHOR_SPAN] ?? 'list'}:${Math.floor(anchor / ANCHOR_SPAN)}`;
|
||||
}
|
||||
|
||||
/** The anchor an entry key names, or null for a key no entry can have. */
|
||||
export function anchorOfKey(key: string): number | null {
|
||||
if (!PLACES_LIBRARY_KEY_PATTERN.test(key)) return null;
|
||||
const [prefix = '', digits = ''] = key.split(':');
|
||||
const kind = KIND_OF_PREFIX[prefix];
|
||||
const anchor = Number(digits) * ANCHOR_SPAN + (kind ?? 0);
|
||||
return kind === undefined || !Number.isSafeInteger(anchor) ? null : anchor;
|
||||
}
|
||||
|
||||
/** The own place an anchor names, or null for an entry no one put together. */
|
||||
export function identityOfAnchor(anchor: number): number | null {
|
||||
return anchor % ANCHOR_SPAN === ANCHOR_OWN ? Math.floor(anchor / ANCHOR_SPAN) : null;
|
||||
}
|
||||
|
||||
/** The anchor of the user's own place `id`. */
|
||||
export function anchorOfIdentity(id: number): number {
|
||||
return id * ANCHOR_SPAN + ANCHOR_OWN;
|
||||
}
|
||||
|
||||
/** How a use is named: `trip:<place id>` or `list:<saved place id>`. */
|
||||
export function useKey(fromList: number, id: number): string {
|
||||
return `${fromList === 0 ? 'trip' : 'list'}:${id}`;
|
||||
}
|
||||
|
||||
/** The `from_list` of a use kind. */
|
||||
export function fromListOf(kind: PlacesLibraryKind): number {
|
||||
return kind === 'trip' ? 0 : 1;
|
||||
}
|
||||
|
||||
/** The position after which the next page starts, opaque to the client. */
|
||||
@@ -58,8 +98,9 @@ export function ratingOf(rows: readonly LibraryRatingRow[], userId: number): Pla
|
||||
}
|
||||
|
||||
type FactsRow = LibraryTripPlaceRow | LibraryCollectionPlaceRow;
|
||||
type LeadRow = FactsRow | LibraryIdentityRow;
|
||||
|
||||
function categoryOf(row: FactsRow): PlacesLibraryCategory | null {
|
||||
export function categoryOf(row: LeadRow): PlacesLibraryCategory | null {
|
||||
if (row.category_id === null || row.category_name === null) return null;
|
||||
return { id: row.category_id, name: row.category_name, color: row.category_color, icon: row.category_icon };
|
||||
}
|
||||
@@ -79,7 +120,7 @@ export function infoOf(row: FactsRow): PlacesLibraryInfo {
|
||||
};
|
||||
}
|
||||
|
||||
function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean): PlacesLibraryTripOrigin {
|
||||
function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean, linked: boolean): PlacesLibraryTripOrigin {
|
||||
return {
|
||||
kind: 'trip',
|
||||
trip_id: row.trip_id,
|
||||
@@ -89,10 +130,11 @@ function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean): PlacesLibrary
|
||||
place_id: row.id,
|
||||
can_edit: canEdit,
|
||||
read_only: !canEdit,
|
||||
linked,
|
||||
};
|
||||
}
|
||||
|
||||
function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean): PlacesLibraryListOrigin {
|
||||
function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean, linked: boolean): PlacesLibraryListOrigin {
|
||||
return {
|
||||
kind: 'list',
|
||||
collection_id: row.collection_id,
|
||||
@@ -100,6 +142,7 @@ function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean): PlacesL
|
||||
collection_place_id: row.id,
|
||||
status: collectionStatusSchema.parse(row.status),
|
||||
can_edit: canEdit,
|
||||
linked,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -109,52 +152,91 @@ export interface OriginAccess {
|
||||
canEditList: (row: LibraryCollectionPlaceRow) => boolean;
|
||||
}
|
||||
|
||||
/** One entry's rows: its trip place where it has one, and its saved places. */
|
||||
/** One entry's rows: the user's own place where it is one, its trip places and its saved places. */
|
||||
export interface EntryRows {
|
||||
anchor: number;
|
||||
trip: LibraryTripPlaceRow | null;
|
||||
identity: LibraryIdentityRow | null;
|
||||
trips: LibraryTripPlaceRow[];
|
||||
saved: LibraryCollectionPlaceRow[];
|
||||
/** The uses the user linked themselves, by `useKey`. */
|
||||
linked: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of each anchor, in the anchors' order. An anchor whose rows went
|
||||
* away between the reads (a place deleted in between) is left out.
|
||||
* away between the reads (a place deleted in between, an own place pruned) is
|
||||
* left out.
|
||||
*/
|
||||
export function rowsByAnchor(
|
||||
anchors: readonly number[],
|
||||
uses: readonly LibraryUseRow[],
|
||||
trips: readonly LibraryTripPlaceRow[],
|
||||
saved: readonly LibraryCollectionPlaceRow[],
|
||||
identities: readonly LibraryIdentityRow[],
|
||||
): EntryRows[] {
|
||||
const tripById = new Map(trips.map((row) => [row.id, row]));
|
||||
const savedById = new Map(saved.map((row) => [row.id, row]));
|
||||
const identityById = new Map(identities.map((row) => [row.id, row]));
|
||||
return anchors.flatMap((anchor) => {
|
||||
if (anchor > 0) {
|
||||
const trip = tripById.get(anchor);
|
||||
if (!trip) return [];
|
||||
return [{ anchor, trip, saved: saved.filter((row) => row.grouped_place_id === anchor) }];
|
||||
}
|
||||
const own = saved.filter((row) => row.id === -anchor && row.grouped_place_id === null);
|
||||
return own.length > 0 ? [{ anchor, trip: null, saved: own }] : [];
|
||||
const own = uses.filter((use) => use.anchor_key === anchor);
|
||||
const identityId = identityOfAnchor(anchor);
|
||||
const identity = identityId === null ? null : (identityById.get(identityId) ?? null);
|
||||
if (identityId !== null && identity === null) return [];
|
||||
const entry: EntryRows = {
|
||||
anchor,
|
||||
identity,
|
||||
trips: own.flatMap((use) => {
|
||||
const row = use.from_list === 0 ? tripById.get(use.use_id) : undefined;
|
||||
return row ? [row] : [];
|
||||
}),
|
||||
saved: own.flatMap((use) => {
|
||||
const row = use.from_list === 1 ? savedById.get(use.use_id) : undefined;
|
||||
return row ? [row] : [];
|
||||
}),
|
||||
linked: new Set(own.filter((use) => use.linked).map((use) => useKey(use.from_list, use.use_id))),
|
||||
};
|
||||
return entry.trips.length > 0 || entry.saved.length > 0 ? [entry] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** An entry of the list: the trip place's facts where there is one, the trip origin first. */
|
||||
export function entryOf(rows: EntryRows, access: OriginAccess): PlacesLibraryEntry {
|
||||
/** The facts an entry shows: its own place's, else its first trip place's, else its first saved place's. */
|
||||
export function leadOf(rows: EntryRows): LeadRow {
|
||||
const lead = rows.identity ?? rows.trips[0] ?? rows.saved[0];
|
||||
// rowsByAnchor never hands out an entry with neither a trip place nor a saved place.
|
||||
const lead: FactsRow = rows.trip ?? rows.saved[0];
|
||||
const origins = [
|
||||
...(rows.trip ? [tripOriginOf(rows.trip, access.canEditTrip(rows.trip))] : []),
|
||||
...rows.saved.map((row) => listOriginOf(row, access.canEditList(row))),
|
||||
if (!lead) throw new Error('An entry without a place');
|
||||
return lead;
|
||||
}
|
||||
|
||||
/** The facts of the use that stands first in an entry: its first trip place, else its first saved place. */
|
||||
export function firstUseOf(rows: EntryRows): FactsRow {
|
||||
const first = rows.trips[0] ?? rows.saved[0];
|
||||
if (!first) throw new Error('An entry without a place');
|
||||
return first;
|
||||
}
|
||||
|
||||
/** The origins of an entry: its trip places first, then its saved places. */
|
||||
export function originsOf(rows: EntryRows, access: OriginAccess): PlacesLibraryEntry['origins'] {
|
||||
return [
|
||||
...rows.trips.map((row) => tripOriginOf(row, access.canEditTrip(row), rows.linked.has(useKey(0, row.id)))),
|
||||
...rows.saved.map((row) => listOriginOf(row, access.canEditList(row), rows.linked.has(useKey(1, row.id)))),
|
||||
];
|
||||
}
|
||||
|
||||
/** An entry of the list: its own place's facts, else its trip place's where there is one. */
|
||||
export function entryOf(rows: EntryRows, access: OriginAccess): PlacesLibraryEntry {
|
||||
const lead = leadOf(rows);
|
||||
const facts: FactsRow[] = [...rows.trips, ...rows.saved];
|
||||
return {
|
||||
key: entryKey(rows.anchor),
|
||||
identity_id: rows.identity?.id ?? null,
|
||||
name: lead.name,
|
||||
address: lead.address,
|
||||
lat: lead.lat,
|
||||
lng: lead.lng,
|
||||
category: categoryOf(lead),
|
||||
image_url: lead.image_url ?? rows.saved.find((row) => row.image_url !== null)?.image_url ?? null,
|
||||
image_url: facts.find((row) => row.image_url !== null)?.image_url ?? null,
|
||||
updated_at: lead.updated_at,
|
||||
origins,
|
||||
origins: originsOf(rows, access),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +1,45 @@
|
||||
import { UserPlaceLinks } from '../../db/entities/UserPlaceLinks.entity';
|
||||
import { UserPlaceMergeDismissals } from '../../db/entities/UserPlaceMergeDismissals.entity';
|
||||
import { UserPlaceMerges } from '../../db/entities/UserPlaceMerges.entity';
|
||||
import { UserPlaces } from '../../db/entities/UserPlaces.entity';
|
||||
import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { CollectionsModule } from '../collections/collections.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { PlaceDuplicatesService } from './place-duplicates.service';
|
||||
import { PlaceIdentitiesPruneJob } from './place-identities-prune.job';
|
||||
import { PlaceIdentitiesController } from './place-identities.controller';
|
||||
import { PlaceIdentitiesMcp } from './place-identities.mcp';
|
||||
import { PlaceIdentitiesService } from './place-identities.service';
|
||||
import { PlacesLibraryController } from './places-library.controller';
|
||||
import { PlacesLibraryMcp } from './places-library.mcp';
|
||||
import { PlacesLibraryService } from './places-library.service';
|
||||
import { EntityManager } from '@mikro-orm/core';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* PLC-07/PLC-08 "All places" under the Collections addon: the saved places of
|
||||
* every list and the places of every trip the user can open, read only. The
|
||||
* repository reads across both, so it backs no entity and is built here over
|
||||
* the context-resolving EntityManager, the way MaintenanceModule builds its own.
|
||||
* every list and the places of every trip the user can open, read only, plus
|
||||
* (D5/PLC-13) the user's own places that group them, the duplicate
|
||||
* suggestions and merges. The library repository reads across trips and
|
||||
* lists, so it backs no entity and is built here over the context-resolving
|
||||
* EntityManager, the way MaintenanceModule builds its own.
|
||||
*/
|
||||
@Module({
|
||||
imports: [AddonsModule, CollectionsModule, TripMembershipModule, PermissionsModule, McpSharedModule],
|
||||
controllers: [PlacesLibraryController],
|
||||
imports: [
|
||||
AddonsModule,
|
||||
CollectionsModule,
|
||||
TripMembershipModule,
|
||||
PermissionsModule,
|
||||
McpSharedModule,
|
||||
SchedulingModule,
|
||||
MikroOrmModule.forFeature([UserPlaces, UserPlaceLinks, UserPlaceMerges, UserPlaceMergeDismissals]),
|
||||
],
|
||||
controllers: [PlacesLibraryController, PlaceIdentitiesController],
|
||||
providers: [
|
||||
{
|
||||
provide: PlacesLibraryRepository,
|
||||
@@ -27,6 +48,10 @@ import { Module } from '@nestjs/common';
|
||||
},
|
||||
PlacesLibraryService,
|
||||
PlacesLibraryMcp,
|
||||
PlaceIdentitiesService,
|
||||
PlaceDuplicatesService,
|
||||
PlaceIdentitiesMcp,
|
||||
PlaceIdentitiesPruneJob,
|
||||
],
|
||||
})
|
||||
export class PlacesLibraryModule {}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type LibraryMatch,
|
||||
type LibrarySort,
|
||||
type LibraryTripPlaceRow,
|
||||
type LibraryUseRow,
|
||||
} from '../../db/repositories/PlacesLibrary.repository';
|
||||
import { CollectionsService } from '../collections/collections.service';
|
||||
import { badRequest, notFound } from '../common/domain-error';
|
||||
@@ -15,7 +16,9 @@ import {
|
||||
encodeLibraryCursor,
|
||||
entryKey,
|
||||
entryOf,
|
||||
fromListOf,
|
||||
groupBy,
|
||||
identityOfAnchor,
|
||||
infoOf,
|
||||
ratingOf,
|
||||
rowsByAnchor,
|
||||
@@ -40,7 +43,8 @@ export interface LibraryUser {
|
||||
}
|
||||
|
||||
/** What the user reaches right now, read anew for every call. */
|
||||
interface Reach {
|
||||
export interface LibraryReach {
|
||||
userId: number;
|
||||
tripIds: number[];
|
||||
collectionIds: number[];
|
||||
}
|
||||
@@ -50,7 +54,17 @@ interface LibraryListOptions {
|
||||
maxChars?: number;
|
||||
}
|
||||
|
||||
const placeNotFound = () => notFound('Place not found');
|
||||
export const placeNotFound = () => notFound('Place not found');
|
||||
|
||||
/** Everything the user reaches, as the repository reads it. */
|
||||
function armsOfReach(reach: LibraryReach): LibraryArms {
|
||||
return {
|
||||
userId: reach.userId,
|
||||
tripIds: reach.tripIds,
|
||||
collectionIds: reach.collectionIds,
|
||||
reachableTripIds: reach.tripIds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* PLC-07/PLC-08 "All places": the saved places of every list the user can
|
||||
@@ -61,6 +75,10 @@ const placeNotFound = () => notFound('Place not found');
|
||||
* `TripMembershipService.listAccessibleTripIds`, the list roles for editing a
|
||||
* saved place and the trip's 'place_edit' for editing a trip place. A list or
|
||||
* trip out of reach is not found, never hinted at.
|
||||
*
|
||||
* Uses the user put together as one place of their own (D5) are one entry,
|
||||
* named and placed as that own place; only the uses the user reaches today
|
||||
* belong to it.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlacesLibraryService {
|
||||
@@ -89,8 +107,7 @@ export class PlacesLibraryService {
|
||||
status: query.status ?? null,
|
||||
};
|
||||
|
||||
const facets = { ...arms, tripIds: reach.tripIds, collectionIds: reach.collectionIds };
|
||||
const counts = await this.repo.countEntries(facets, { ...match, status: null });
|
||||
const counts = await this.repo.countEntries(armsOfReach(reach), { ...match, status: null });
|
||||
const narrowed =
|
||||
query.kind !== undefined ||
|
||||
query.collection_id !== undefined ||
|
||||
@@ -128,49 +145,71 @@ export class PlacesLibraryService {
|
||||
/** One entry, opened from the trip place or the saved place `id`, with what each origin keeps. */
|
||||
async detail(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise<PlacesLibraryDetailResponse> {
|
||||
const reach = await this.reach(user.id);
|
||||
const anchor =
|
||||
kind === 'trip'
|
||||
? await this.repo.findTripPlace(id, reach.tripIds)
|
||||
: await this.repo.findSavedPlaceKey(id, reach.collectionIds, reach.tripIds);
|
||||
const anchor = await this.repo.anchorOfUse(armsOfReach(reach), fromListOf(kind), id);
|
||||
if (anchor === null) throw placeNotFound();
|
||||
const rows = (await this.rows(reach, [anchor]))[0];
|
||||
if (!rows) throw placeNotFound();
|
||||
const entry = entryOf(rows, await this.access(user, rows.trip ? [rows.trip] : [], rows.saved));
|
||||
const entry = entryOf(rows, await this.access(user, rows.trips, rows.saved));
|
||||
return { entry, details: await this.details(user.id, rows) };
|
||||
}
|
||||
|
||||
private async reach(userId: number): Promise<Reach> {
|
||||
/** The trips and lists the user reaches right now. */
|
||||
async reach(userId: number): Promise<LibraryReach> {
|
||||
const tripIds = await this.membership.listAccessibleTripIds(userId);
|
||||
const collectionIds = await this.collections.accessibleCollectionIds(userId);
|
||||
return { tripIds, collectionIds };
|
||||
return { userId, tripIds, collectionIds };
|
||||
}
|
||||
|
||||
private async rows(reach: Reach, anchors: number[]): Promise<EntryRows[]> {
|
||||
const tripPlaceIds = anchors.filter((anchor) => anchor > 0);
|
||||
const savedIds = anchors.filter((anchor) => anchor < 0).map((anchor) => -anchor);
|
||||
/** The entry a use stands for, or null when the user does not reach it. */
|
||||
async anchorOfUse(reach: LibraryReach, kind: PlacesLibraryKind, id: number): Promise<number | null> {
|
||||
return this.repo.anchorOfUse(armsOfReach(reach), fromListOf(kind), id);
|
||||
}
|
||||
|
||||
/** The uses the user reaches, of the entries `anchors` or of all of them. */
|
||||
async usesOf(reach: LibraryReach, anchors: number[] | null): Promise<LibraryUseRow[]> {
|
||||
return this.repo.usesOf(armsOfReach(reach), anchors);
|
||||
}
|
||||
|
||||
/** The rows of the entries `anchors`, in their order, from the uses read for them (or read here). */
|
||||
async rows(reach: LibraryReach, anchors: number[], uses?: LibraryUseRow[]): Promise<EntryRows[]> {
|
||||
if (anchors.length === 0) return [];
|
||||
const own = uses ?? (await this.usesOf(reach, anchors));
|
||||
const tripPlaceIds = own.filter((use) => use.from_list === 0).map((use) => use.use_id);
|
||||
const savedIds = own.filter((use) => use.from_list === 1).map((use) => use.use_id);
|
||||
const identityIds = anchors.flatMap((anchor): number[] => {
|
||||
const id = identityOfAnchor(anchor);
|
||||
return id === null ? [] : [id];
|
||||
});
|
||||
const trips = tripPlaceIds.length > 0 ? await this.repo.tripPlaces(tripPlaceIds, reach.tripIds) : [];
|
||||
const saved =
|
||||
anchors.length > 0 ? await this.repo.savedPlaces(reach.collectionIds, reach.tripIds, savedIds, tripPlaceIds) : [];
|
||||
return rowsByAnchor(anchors, trips, saved);
|
||||
const saved = savedIds.length > 0 ? await this.repo.savedPlaces(reach.collectionIds, savedIds) : [];
|
||||
const identities = identityIds.length > 0 ? await this.repo.identities(reach.userId, identityIds) : [];
|
||||
return rowsByAnchor(anchors, own, trips, saved, identities);
|
||||
}
|
||||
|
||||
private async entries(user: LibraryUser, reach: Reach, anchors: number[]): Promise<PlacesLibraryEntry[]> {
|
||||
/** The entries `anchors` as the list shows them, in their order. */
|
||||
async entries(user: LibraryUser, reach: LibraryReach, anchors: number[]): Promise<PlacesLibraryEntry[]> {
|
||||
const rows = await this.rows(reach, anchors);
|
||||
const access = await this.access(
|
||||
user,
|
||||
rows.flatMap((row) => (row.trip ? [row.trip] : [])),
|
||||
rows.flatMap((row) => row.trips),
|
||||
rows.flatMap((row) => row.saved),
|
||||
);
|
||||
return rows.map((row) => entryOf(row, access));
|
||||
}
|
||||
|
||||
/** One entry, or null when it has no use the user reaches. */
|
||||
async entry(user: LibraryUser, anchor: number | null): Promise<PlacesLibraryEntry | null> {
|
||||
if (anchor === null) return null;
|
||||
return (await this.entries(user, await this.reach(user.id), [anchor]))[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the user may change each origin: a saved place with any list role
|
||||
* but viewer (assertCanEdit's rule), a trip place with 'place_edit', which
|
||||
* reads the same for every trip the user owns and for every one they are a
|
||||
* member of, so it is asked once for each.
|
||||
*/
|
||||
private async access(
|
||||
async access(
|
||||
user: LibraryUser,
|
||||
trips: readonly LibraryTripPlaceRow[],
|
||||
saved: readonly LibraryCollectionPlaceRow[],
|
||||
@@ -190,32 +229,34 @@ export class PlacesLibraryService {
|
||||
};
|
||||
}
|
||||
|
||||
/** What each origin keeps, in the entry's origin order: the trip place first, then the saved places. */
|
||||
/** What each origin keeps, in the entry's origin order: the trip places first, then the saved places. */
|
||||
private async details(userId: number, rows: EntryRows): Promise<PlacesLibraryDetail[]> {
|
||||
const details: PlacesLibraryDetail[] = [];
|
||||
if (rows.trip) {
|
||||
const placeIds = [rows.trip.id];
|
||||
const notes = await this.repo.tripPlaceNotes(placeIds);
|
||||
const ratings = await this.repo.tripPlaceRatings(placeIds);
|
||||
const days = await this.repo.plannedDays(placeIds);
|
||||
if (rows.trips.length > 0) {
|
||||
const placeIds = rows.trips.map((row) => row.id);
|
||||
const notes = new Map((await this.repo.tripPlaceNotes(placeIds)).map((row) => [row.id, row.notes]));
|
||||
const ratings = groupBy(await this.repo.tripPlaceRatings(placeIds), (row) => row.target_id);
|
||||
const days = groupBy(await this.repo.plannedDays(placeIds), (row) => row.place_id);
|
||||
const booked = await this.repo.bookedPlaces(placeIds);
|
||||
details.push({
|
||||
kind: 'trip',
|
||||
place_id: rows.trip.id,
|
||||
info: infoOf(rows.trip),
|
||||
notes: notes[0]?.notes ?? null,
|
||||
rating: ratingOf(ratings, userId),
|
||||
days: days.map((day) => ({
|
||||
day_id: day.day_id,
|
||||
day_number: day.day_number,
|
||||
date: day.date,
|
||||
title: day.title,
|
||||
time: day.time,
|
||||
end_time: day.end_time,
|
||||
})),
|
||||
has_accommodation: booked.stays.includes(rows.trip.id),
|
||||
has_reservation: booked.bookings.includes(rows.trip.id),
|
||||
});
|
||||
for (const row of rows.trips) {
|
||||
details.push({
|
||||
kind: 'trip',
|
||||
place_id: row.id,
|
||||
info: infoOf(row),
|
||||
notes: notes.get(row.id) ?? null,
|
||||
rating: ratingOf(ratings.get(row.id) ?? [], userId),
|
||||
days: (days.get(row.id) ?? []).map((day) => ({
|
||||
day_id: day.day_id,
|
||||
day_number: day.day_number,
|
||||
date: day.date,
|
||||
title: day.title,
|
||||
time: day.time,
|
||||
end_time: day.end_time,
|
||||
})),
|
||||
has_accommodation: booked.stays.includes(row.id),
|
||||
has_reservation: booked.bookings.includes(row.id),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (rows.saved.length > 0) {
|
||||
const savedIds = rows.saved.map((row) => row.id);
|
||||
@@ -242,13 +283,14 @@ export class PlacesLibraryService {
|
||||
* list, a status) leaves the trips out, a filter on a trip the lists; a list
|
||||
* or trip out of reach reads as none, so it answers like an empty one.
|
||||
*/
|
||||
function armsFor(reach: Reach, query: PlacesLibraryQuery): LibraryArms {
|
||||
function armsFor(reach: LibraryReach, query: PlacesLibraryQuery): LibraryArms {
|
||||
const listsOnly = query.kind === 'list' || query.collection_id !== undefined || query.status !== undefined;
|
||||
const tripsOnly = query.kind === 'trip' || query.trip_id !== undefined;
|
||||
if (listsOnly && tripsOnly) throw badRequest('Filter by a trip or by a list, not both');
|
||||
const only = (ids: number[], id: number | undefined) =>
|
||||
id === undefined ? ids : ids.filter((reachable) => reachable === id);
|
||||
return {
|
||||
userId: reach.userId,
|
||||
tripIds: listsOnly ? [] : only(reach.tripIds, query.trip_id),
|
||||
collectionIds: tripsOnly ? [] : only(reach.collectionIds, query.collection_id),
|
||||
reachableTripIds: reach.tripIds,
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { TripAccess } from '../../db/repositories/Trips.repository';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { Trip } from '../permissions/trip.decorator';
|
||||
import { TripCollectionLinkDto } from './trip-collections.dto';
|
||||
import { TripCollectionsService } from './trip-collections.service';
|
||||
import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
|
||||
import { tripCollectionLayerResponseSchema, tripCollectionLinksResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-15/PLC-16 at /api/trips/:tripId/collections: the lists of saved places
|
||||
* a trip draws on, and their saved places for the trip map. Every member reads
|
||||
* the lists open to them; linking and unlinking take 'place_edit'. Behind the
|
||||
* Collections addon: with it off the routes answer 404.
|
||||
*/
|
||||
@Controller('api/trips/:tripId/collections')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
|
||||
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
|
||||
export class TripCollectionsController {
|
||||
constructor(private readonly tripCollections: TripCollectionsService) {}
|
||||
|
||||
@Get()
|
||||
@ResponseContract(tripCollectionLinksResponseSchema)
|
||||
async list(@CurrentUser() user: User, @Trip() trip: TripAccess) {
|
||||
return this.tripCollections.list(trip.id, user);
|
||||
}
|
||||
|
||||
@Get('places')
|
||||
@ResponseContract(tripCollectionLayerResponseSchema)
|
||||
async layer(@CurrentUser() user: User, @Trip() trip: TripAccess) {
|
||||
return this.tripCollections.layer(trip.id, user);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
@RequirePermission('place_edit')
|
||||
@ResponseContract(tripCollectionLinksResponseSchema)
|
||||
async link(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Body() body: TripCollectionLinkDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.tripCollections.link(
|
||||
trip.id,
|
||||
body.collection_id,
|
||||
this.tripCollections.restWriter(trip.id, user, socketId),
|
||||
);
|
||||
}
|
||||
|
||||
@Delete(':collectionId')
|
||||
@HttpCode(200)
|
||||
@RequirePermission('place_edit')
|
||||
@ResponseContract(tripCollectionLinksResponseSchema)
|
||||
async unlink(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Param('collectionId', rowId('Collection not found')) collectionId: number,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.tripCollections.unlink(trip.id, collectionId, this.tripCollections.restWriter(trip.id, user, socketId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { tripCollectionLinkRequestSchema } from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
export class TripCollectionLinkDto extends createZodDto(tripCollectionLinkRequestSchema) {}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { canRead, canReadTrips, canWrite } from '../../mcp/scopes';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { TripCollectionsService } from './trip-collections.service';
|
||||
import { idSchema, tripCollectionLinkRequestSchema } from '@trek/shared';
|
||||
|
||||
/** Reading a trip's linked lists reads the trip and the lists. */
|
||||
const readsTripAndLists = (ctx: McpContext) => canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
|
||||
/** Linking changes the trip's places panel and needs the list to be readable. */
|
||||
const linksLists = (ctx: McpContext) => canWrite(ctx.scopes, 'places') && canRead(ctx.scopes, 'collections');
|
||||
|
||||
const tripInput = { tripId: idSchema };
|
||||
const linkInput = { tripId: idSchema, collection_id: tripCollectionLinkRequestSchema.shape.collection_id };
|
||||
|
||||
/**
|
||||
* PLC-15/PLC-16 over MCP: the same service, the same 'place_edit' and list
|
||||
* checks as `/api/trips/:tripId/collections`, behind the Collections addon.
|
||||
*/
|
||||
@McpController()
|
||||
export class TripCollectionsMcp {
|
||||
constructor(
|
||||
private readonly tripCollections: TripCollectionsService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'list_trip_collections',
|
||||
description:
|
||||
'The lists of saved places linked to a trip that you can open (lists linked by others that are closed to you are left out), with your role on each, how many places it holds, and whether you may link or unlink lists on this trip.',
|
||||
inputSchema: tripInput,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: readsTripAndLists,
|
||||
})
|
||||
async listTripCollections({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
const { role } = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
return ok(await this.tripCollections.list(tripId, { id: ctx.userId, role }));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'get_trip_collection_places',
|
||||
description:
|
||||
'The saved places with a position of every list linked to the trip that you can open, for the trip map: id, collection_id, name, lat, lng, category, status and in_trip (with trip_place_id) when the trip already has that place. Add one to the trip with copy_collection_places_to_trip.',
|
||||
inputSchema: tripInput,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: readsTripAndLists,
|
||||
})
|
||||
async getTripCollectionPlaces({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
const { role } = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
return ok(await this.tripCollections.layer(tripId, { id: ctx.userId, role }));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'link_collection_to_trip',
|
||||
description:
|
||||
'Link one of the lists of saved places you can open to a trip, so the trip can show its places. Gives no one access: members see the list only if it is open to them anyway. Needs the permission to edit the trip places.',
|
||||
inputSchema: linkInput,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: linksLists,
|
||||
})
|
||||
async linkCollectionToTrip({ tripId, collection_id }: { tripId: number; collection_id: number }, ctx: McpContext) {
|
||||
const writer = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
return ok(await this.tripCollections.link(tripId, collection_id, writer));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'unlink_collection_from_trip',
|
||||
description:
|
||||
'Unlink a list of saved places from a trip. The list and its places stay as they are. Needs the permission to edit the trip places and the list to be open to you.',
|
||||
inputSchema: linkInput,
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: linksLists,
|
||||
})
|
||||
async unlinkCollectionFromTrip(
|
||||
{ tripId, collection_id }: { tripId: number; collection_id: number },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
const writer = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
return ok(await this.tripCollections.unlink(tripId, collection_id, writer));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { TripCollectionLinks } from '../../db/entities/TripCollectionLinks.entity';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { CollectionsModule } from '../collections/collections.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { RealtimeModule } from '../realtime/realtime.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { TripCollectionsController } from './trip-collections.controller';
|
||||
import { TripCollectionsMcp } from './trip-collections.mcp';
|
||||
import { TripCollectionsService } from './trip-collections.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/** PLC-15/PLC-16: the lists of saved places a trip draws on, their routes and MCP tools. */
|
||||
@Module({
|
||||
imports: [
|
||||
AddonsModule,
|
||||
CollectionsModule,
|
||||
TripMembershipModule,
|
||||
PermissionsModule,
|
||||
RealtimeModule,
|
||||
McpSharedModule,
|
||||
MikroOrmModule.forFeature([TripCollectionLinks]),
|
||||
],
|
||||
controllers: [TripCollectionsController],
|
||||
providers: [TripCollectionsService, TripCollectionsMcp],
|
||||
})
|
||||
export class TripCollectionsModule {}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { TripCollectionLinks } from '../../db/entities/TripCollectionLinks.entity';
|
||||
import type { TripCollectionLinksRepository } from '../../db/repositories/TripCollectionLinks.repository';
|
||||
import type { User } from '../../types';
|
||||
import { CollectionsService } from '../collections/collections.service';
|
||||
import { notFound } from '../common/domain-error';
|
||||
import { requireTripWrite, restTripWriter, tripNotFound, type TripWriter } from '../common/trip-writer';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
collectionStatusSchema,
|
||||
TRIP_COLLECTION_ROLES,
|
||||
type TripCollectionLayerResponse,
|
||||
type TripCollectionLink,
|
||||
type TripCollectionLinksResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Who reads: their id and their account role, for the admin bypass of trip permissions. */
|
||||
interface TripCollectionsReader {
|
||||
id: number;
|
||||
role: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Linking a list to a trip or unlinking it changes the trip's places panel
|
||||
* for everyone on it, so it takes 'place_edit': the right to change the
|
||||
* trip's places, which copying a saved place into the trip already needs.
|
||||
* 'trip_edit' (the trip's own settings, owner-only by default) would keep
|
||||
* the members who plan the places from using their own lists.
|
||||
*/
|
||||
const LINK_PERMISSION = 'place_edit';
|
||||
|
||||
const collectionNotFound = () => notFound('Collection not found');
|
||||
|
||||
/**
|
||||
* PLC-15/PLC-16: the lists of saved places a trip draws on. A link gives no
|
||||
* one access: each member sees a linked list, its count included, only while
|
||||
* the list is open to them on their own (owner or accepted member), and
|
||||
* nothing of a list that is not. Linking and unlinking take 'place_edit' on
|
||||
* the trip and a list the caller can see; a list they cannot see is not
|
||||
* found. A trip or list deleted takes its links along (ON DELETE CASCADE).
|
||||
* Nothing here writes a trip place or a saved place.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TripCollectionsService {
|
||||
constructor(
|
||||
@InjectRepository(TripCollectionLinks) private readonly links: TripCollectionLinksRepository,
|
||||
private readonly collections: CollectionsService,
|
||||
private readonly trips: TripAccessService,
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
) {}
|
||||
|
||||
/** The REST caller of a link write: skips the sender's socket. */
|
||||
restWriter(tripId: number, user: User, socketId: string | undefined): TripWriter {
|
||||
return restTripWriter(this.realtime, tripId, user, socketId);
|
||||
}
|
||||
|
||||
private async requireTrip(tripId: number, userId: number) {
|
||||
const trip = await this.trips.findAccessible(tripId, userId);
|
||||
if (!trip) throw tripNotFound();
|
||||
return trip;
|
||||
}
|
||||
|
||||
/** The trip's linked lists the reader can open, with their role there, and whether they may change the links. */
|
||||
async list(tripId: number, reader: TripCollectionsReader): Promise<TripCollectionLinksResponse> {
|
||||
const trip = await this.requireTrip(tripId, reader.id);
|
||||
const canLink = await this.permissions.checkPermission(
|
||||
LINK_PERMISSION,
|
||||
reader.role,
|
||||
trip.user_id,
|
||||
reader.id,
|
||||
trip.user_id !== reader.id,
|
||||
);
|
||||
const visible = new Set(await this.collections.accessibleCollectionIds(reader.id));
|
||||
const rows = (await this.links.listForTrip(tripId)).filter((row) => visible.has(row.collection_id));
|
||||
const roles = await Promise.all(
|
||||
rows.map(async (row) =>
|
||||
row.owner_id === reader.id ? 'owner' : await this.collections.roleOf(reader.id, row.collection_id),
|
||||
),
|
||||
);
|
||||
const links = rows.flatMap((row, index): TripCollectionLink[] => {
|
||||
const role = TRIP_COLLECTION_ROLES.find((known) => known === roles[index]);
|
||||
if (!role) return [];
|
||||
return [
|
||||
{
|
||||
collection_id: row.collection_id,
|
||||
name: row.name,
|
||||
color: row.color,
|
||||
role,
|
||||
place_count: row.place_count,
|
||||
linked_by: row.linked_by,
|
||||
created_at: row.created_at,
|
||||
},
|
||||
];
|
||||
});
|
||||
return { links, can_link: canLink };
|
||||
}
|
||||
|
||||
/** Links a list the writer can open to the trip. Linking it again changes nothing and sends nothing. */
|
||||
async link(tripId: number, collectionId: number, writer: TripWriter): Promise<TripCollectionLinksResponse> {
|
||||
await this.gate(tripId, collectionId, writer);
|
||||
const before = (await this.links.listForTrip(tripId)).some((row) => row.collection_id === collectionId);
|
||||
if (!before) {
|
||||
await this.links.link(tripId, collectionId, writer.userId);
|
||||
writer.events.emit('tripCollections:changed', {});
|
||||
}
|
||||
return this.list(tripId, { id: writer.userId, role: writer.role });
|
||||
}
|
||||
|
||||
/** Unlinks a list the writer can open from the trip; the list itself stays as it is. */
|
||||
async unlink(tripId: number, collectionId: number, writer: TripWriter): Promise<TripCollectionLinksResponse> {
|
||||
await this.gate(tripId, collectionId, writer);
|
||||
if (!(await this.links.unlink(tripId, collectionId))) throw notFound('This list is not linked to the trip');
|
||||
writer.events.emit('tripCollections:changed', {});
|
||||
return this.list(tripId, { id: writer.userId, role: writer.role });
|
||||
}
|
||||
|
||||
/**
|
||||
* The saved places with a position of every linked list the reader can
|
||||
* open, for the trip map, each with whether the trip already has it.
|
||||
*/
|
||||
async layer(tripId: number, reader: TripCollectionsReader): Promise<TripCollectionLayerResponse> {
|
||||
await this.requireTrip(tripId, reader.id);
|
||||
const visible = new Set(await this.collections.accessibleCollectionIds(reader.id));
|
||||
const linked = (await this.links.listForTrip(tripId))
|
||||
.map((row) => row.collection_id)
|
||||
.filter((id) => visible.has(id));
|
||||
const rows = linked.length > 0 ? await this.links.layerPlaces(tripId, linked) : [];
|
||||
return {
|
||||
places: rows.map((row) => ({
|
||||
id: row.id,
|
||||
collection_id: row.collection_id,
|
||||
name: row.name,
|
||||
lat: row.lat,
|
||||
lng: row.lng,
|
||||
category:
|
||||
row.category_id === null || row.category_name === null
|
||||
? null
|
||||
: { id: row.category_id, name: row.category_name, color: row.category_color, icon: row.category_icon },
|
||||
status: collectionStatusSchema.parse(row.status),
|
||||
in_trip: row.trip_place_id !== null,
|
||||
trip_place_id: row.trip_place_id,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** The trip with 'place_edit' (404, 403) and a list the writer can see (404). */
|
||||
private async gate(tripId: number, collectionId: number, writer: TripWriter): Promise<void> {
|
||||
await requireTripWrite({ access: this.trips, permissions: this.permissions }, LINK_PERMISSION, tripId, writer);
|
||||
if ((await this.collections.roleOf(writer.userId, collectionId)) === null) throw collectionNotFound();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user