feat(places): read every place of the trips and lists in one view

A read-only overview of every place a user can reach: the saved places of
their lists and the places of their trips, viewer trips included, with tours,
tracks and the stops of a drive left out. A saved place and a trip place are
one entry only when the saved place came from that trip place, the trip is
still open to the user, and both agree (a provider id, or the same name at the
same spot); anything else stays apart. Every entry names where it comes from
and whether it may be changed there.

- GET /api/addons/collections/library/places: paged by cursor, search,
  category, kind, list, trip and status filters, counts per kind.
- GET /api/addons/collections/library/places/{trip|list}/🆔 one entry with
  what each origin keeps on its own (notes after the existing rights, labels,
  ratings, a trip's planned days, whether a stay or booking uses it).
- MCP tools list_all_places and get_library_place.

Nothing is written and nothing migrates; the rights are the existing list and
trip checks, read on every call.
This commit is contained in:
Maurice
2026-11-29 14:57:10 +01:00
parent 82165855c7
commit 0ecca2b46c
27 changed files with 2616 additions and 2 deletions
+21
View File
@@ -299,3 +299,24 @@ export function currentTimestampKysely(platform: Platform): RawBuilder<string> {
if (isPostgres(platform)) return sql.raw<string>(pgTimestampText(PG_UTC_NOW));
return unsupported(platform);
}
/**
* Whether the text `<ref>` holds `needle`, case ignored: `instr(lower(<ref>),
* lower(CAST(? AS text))) > 0` on SQLite, `strpos(...)` on Postgres. A plain
* substring search, so `%`, `_` and `\` in the needle are characters and need
* no escaping, unlike a LIKE pattern. `lower()` folds ASCII letters only on
* SQLite, as its LIKE does, and every letter on Postgres. A NULL column holds
* nothing. The needle is cast to text, since `pg` sends parameters untyped and
* `lower` has overloads besides the one for text.
*/
export function containsIgnoringCaseKysely<DB, TB extends keyof DB>(
platform: Platform,
eb: ExpressionBuilder<DB, TB>,
ref: ReferenceExpression<DB, TB>,
needle: string,
): ExpressionWrapper<DB, TB, SqlBool> {
const position = isSqlite(platform) ? 'instr' : isPostgres(platform) ? 'strpos' : unsupported(platform);
const haystack = eb.fn<string>('lower', [ref]);
const wanted = eb.fn<string>('lower', [eb.cast<string>(eb.val(needle), 'text')]);
return eb(eb.fn<number>(position, [haystack, wanted]), '>', eb.lit(0));
}
@@ -0,0 +1,594 @@
import { containsIgnoringCaseKysely } from '../dialect/kysely-functions';
import type { DB } from '../kysely/db';
import { memberRoleOf } from './_shared/collection-role';
import type { EntityManager } from '@mikro-orm/core';
import type { SqlEntityManager } from '@mikro-orm/sql';
import { COORD_DEDUP_TOLERANCE } from '@trek/shared';
import { SERVICE_STOP_TYPES } from '@trek/shared/roadtrip';
import type { Expression, Kysely, SqlBool } from 'kysely';
type LibraryDB = Pick<
DB,
| 'places'
| 'trips'
| 'categories'
| 'tours'
| 'day_accommodations'
| 'reservations'
| 'collection_places'
| 'collections'
| 'collection_members'
| 'collection_place_labels'
| 'collection_labels'
| 'collection_place_ratings'
| 'place_ratings'
| 'day_assignments'
| 'days'
>;
/**
* Kysely cannot bind an empty IN list, and no row has the id 0, so an empty
* set of ids reads as this one: the statement keeps its shape and matches
* nothing.
*/
const NO_ROW = 0;
const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [NO_ROW]);
/**
* The road trip stops that belong to the drive rather than to the places of
* the trip. Lodging ('hotel') is a place like any other, as it is in Days.
*/
const DRIVE_STOP_TYPES = SERVICE_STOP_TYPES.filter((type) => type !== 'hotel');
/**
* What the list reads. A side turned off by a filter (only lists, one trip)
* comes with no ids for it; `reachableTripIds` stays every trip the user can
* open, because a saved place groups with a place of any of them.
*/
export interface LibraryArms {
/** The trips whose places are listed. */
tripIds: number[];
/** The lists whose saved places are listed. */
collectionIds: number[];
/** Every trip the user can open. */
reachableTripIds: number[];
}
/** What every entry of the list is matched by; null matches all. */
export interface LibraryMatch {
/** A part of the name or address, case ignored. */
search: string | null;
categoryId: number | null;
/** A list's status; only saved places have one. */
status: string | null;
}
/** Where an entry stands in the list's order: its sort value and its key. */
export interface LibraryPosition {
value: string;
key: number;
}
export type LibrarySort = 'name' | 'updated';
/**
* One entry of a page: `key` is the trip place id when the entry has one,
* else the saved place id negated, so one number names an entry.
*/
export interface LibraryAnchorRow {
anchor_key: number;
sort_name: string;
sort_time: string;
}
interface UnionRow extends LibraryAnchorRow {
/** 1 when the row came from a list of saved places. */
from_list: number;
}
interface LibraryCounts {
all: number;
trip: number;
list: number;
}
interface PlaceFactsRow {
name: string;
address: string | null;
lat: number | null;
lng: number | null;
image_url: string | null;
updated_at: string | null;
description: string | null;
website: string | null;
phone: string | null;
category_id: number | null;
category_name: string | null;
category_color: string | null;
category_icon: string | null;
}
export interface LibraryTripPlaceRow extends PlaceFactsRow {
id: number;
trip_id: number;
trip_title: string;
trip_start: string | null;
trip_end: string | null;
trip_owner_id: number;
}
export interface LibraryCollectionPlaceRow extends PlaceFactsRow {
id: number;
collection_id: number;
collection_name: string;
status: string;
/** The trip place this saved place is grouped with, if any. */
grouped_place_id: number | null;
}
interface LibraryCollectionRole {
id: number;
role: 'owner' | 'admin' | 'editor' | 'viewer';
}
interface LibraryNotesRow {
id: number;
notes: string | null;
}
interface LibraryLabelRow {
collection_place_id: number;
id: number;
name: string;
color: string | null;
}
export interface LibraryRatingRow {
target_id: number;
user_id: number;
rating: number;
}
interface LibraryDayRow {
place_id: number;
day_id: number;
day_number: number;
date: string | null;
title: string | null;
time: string | null;
end_time: string | null;
}
/**
* PLC-07/PLC-08 "All places": the saved places of the lists a user can open
* and the places of the trips they can open, read as one list. Not bound to an
* entity: it reads across the collections and the trips, the way
* `MaintenanceRepository` and `DemoRepository` stand outside the entity
* repositories, and the places-library module provides it over the
* context-resolving EntityManager. Read only; the ids every method takes are
* the caller's own access-checked lists, this class checks no access itself.
*
* A saved place and a trip place are one entry only when the saved place
* names that trip place as its source (`source_trip_id`/`source_place_id`),
* the trip is one the user can open, the place is a normal place of it, and
* the two agree: the same provider id, or the same name (trimmed, case
* ignored) within `COORD_DEDUP_TOLERANCE` and no provider id that differs.
* A name alone never groups anything.
*/
export class PlacesLibraryRepository {
constructor(private readonly em: EntityManager) {}
/** The request's EntityManager, which throws outside a request context like every repository. */
private db(): Kysely<LibraryDB> {
return (this.em.getContext() as SqlEntityManager).getKysely<LibraryDB>();
}
/**
* The ids of the trips' normal places: no tour, no track and no road trip
* stop of the drive (a stop a stay or a booking points at counts as a
* place, as in Days).
*/
private normalPlaceIds(db: Kysely<LibraryDB>, tripIds: readonly number[]) {
return db
.selectFrom('places as np')
.select('np.id')
.where('np.trip_id', 'in', idsOrNone(tripIds))
.where((eb) =>
eb.and([
eb.or([eb('np.route_geometry', 'is', null), eb('np.route_geometry', '=', '')]),
eb.not(eb.exists(eb.selectFrom('tours as nt').select('nt.place_id').whereRef('nt.place_id', '=', 'np.id'))),
eb.or([
eb('np.stop_type', 'is', null),
eb('np.stop_type', 'not in', [...DRIVE_STOP_TYPES]),
eb.exists(
eb.selectFrom('day_accommodations as nda').select('nda.id').whereRef('nda.place_id', '=', 'np.id'),
),
eb.exists(eb.selectFrom('reservations as nr').select('nr.id').whereRef('nr.place_id', '=', 'np.id')),
]),
]),
);
}
/** Each saved place that groups with a trip place, as the class docstring says, with that place's id. */
private groupLinks(db: Kysely<LibraryDB>, reachableTripIds: readonly number[]) {
return db
.selectFrom('collection_places as lc')
.innerJoin('places as lp', 'lp.id', 'lc.source_place_id')
.select(['lc.id as collection_place_id', 'lp.id as place_id'])
.whereRef('lp.trip_id', '=', 'lc.source_trip_id')
.where('lp.trip_id', 'in', idsOrNone(reachableTripIds))
.where('lp.id', 'in', this.normalPlaceIds(db, reachableTripIds))
.where((eb) => {
const providers = [
['lc.google_place_id', 'lp.google_place_id'],
['lc.google_ftid', 'lp.google_ftid'],
['lc.osm_id', 'lp.osm_id'],
] as const;
const given = (ref: (typeof providers)[number][number]) => eb.and([eb(ref, 'is not', null), eb(ref, '<>', '')]);
const same = providers.map(([saved, trip]) => eb.and([given(saved), eb(saved, '=', eb.ref(trip))]));
const differ = providers.map(([saved, trip]) =>
eb.and([given(saved), given(trip), eb(saved, '<>', eb.ref(trip))]),
);
const near = (saved: 'lc.lat' | 'lc.lng', trip: 'lp.lat' | 'lp.lng') =>
eb(eb.fn<number>('abs', [eb(saved, '-', eb.ref(trip))]), '<=', COORD_DEDUP_TOLERANCE);
const sameName = eb(
eb.fn<string>('lower', [eb.fn<string>('trim', ['lc.name'])]),
'=',
eb.fn<string>('lower', [eb.fn<string>('trim', ['lp.name'])]),
);
return eb.or([
...same,
eb.and([sameName, near('lc.lat', 'lp.lat'), near('lc.lng', 'lp.lng'), eb.not(eb.or(differ))]),
]);
});
}
/** The trip places of the list, one row each. */
private tripArm(db: Kysely<LibraryDB>, arms: LibraryArms, match: LibraryMatch) {
const platform = this.em.getPlatform();
return db
.selectFrom('places as p')
.select((eb) => [
'p.id as anchor_key',
eb.fn<string>('lower', ['p.name']).as('sort_name'),
eb.fn.coalesce('p.updated_at', eb.val('')).as('sort_time'),
eb.cast<number>(eb.lit(0), 'integer').as('from_list'),
])
.where((eb) => {
const conditions: Expression<SqlBool>[] = [
// A status belongs to a list, so a status filter leaves no trip place.
eb('p.trip_id', 'in', idsOrNone(match.status === null ? arms.tripIds : [])),
eb('p.id', 'in', this.normalPlaceIds(db, arms.tripIds)),
];
if (match.search !== null) {
conditions.push(
eb.or([
containsIgnoringCaseKysely(platform, eb, 'p.name', match.search),
containsIgnoringCaseKysely(platform, eb, 'p.address', match.search),
]),
);
}
if (match.categoryId !== null) conditions.push(eb('p.category_id', '=', match.categoryId));
return eb.and(conditions);
})
.$castTo<UnionRow>();
}
/** The saved places of the list; one grouped with a trip place stands for that place's entry. */
private listArm(db: Kysely<LibraryDB>, arms: LibraryArms, match: LibraryMatch) {
const platform = this.em.getPlatform();
return db
.selectFrom('collection_places as cp')
.leftJoin(this.groupLinks(db, arms.reachableTripIds).as('gl'), 'gl.collection_place_id', 'cp.id')
.leftJoin('places as g', 'g.id', 'gl.place_id')
.select((eb) => [
eb.fn.coalesce('gl.place_id', eb.neg('cp.id')).as('anchor_key'),
eb.fn<string>('lower', [eb.fn.coalesce('g.name', 'cp.name')]).as('sort_name'),
eb
.case()
.when('gl.place_id', 'is not', null)
.then(eb.fn.coalesce('g.updated_at', eb.val('')))
.else(eb.fn.coalesce('cp.updated_at', eb.val('')))
.end()
.as('sort_time'),
eb.cast<number>(eb.lit(1), 'integer').as('from_list'),
])
.where((eb) => {
const conditions: Expression<SqlBool>[] = [eb('cp.collection_id', 'in', idsOrNone(arms.collectionIds))];
if (match.search !== null) {
conditions.push(
eb.or([
containsIgnoringCaseKysely(platform, eb, 'cp.name', match.search),
containsIgnoringCaseKysely(platform, eb, 'cp.address', match.search),
]),
);
}
if (match.categoryId !== null) conditions.push(eb('cp.category_id', '=', match.categoryId));
if (match.status !== null) conditions.push(eb('cp.status', '=', match.status));
return eb.and(conditions);
})
.$castTo<UnionRow>();
}
private entries(db: Kysely<LibraryDB>, arms: LibraryArms, match: LibraryMatch) {
return this.tripArm(db, arms, match)
.unionAll(this.listArm(db, arms, match))
.as('u');
}
/** How many entries match: all of them, those with a trip place, those with a saved place. */
async countEntries(arms: LibraryArms, match: LibraryMatch): Promise<LibraryCounts> {
const db = this.db();
const row = await db
.selectFrom(this.entries(db, arms, match))
.select((eb) => [
eb.fn.count<number>('u.anchor_key').distinct().as('all'),
eb.fn
.count<number>(eb.case().when('u.anchor_key', '>', 0).then(eb.ref('u.anchor_key')).end())
.distinct()
.as('trip'),
eb.fn
.count<number>(eb.case().when('u.from_list', '=', 1).then(eb.ref('u.anchor_key')).end())
.distinct()
.as('list'),
])
.executeTakeFirstOrThrow();
return { all: Number(row.all), trip: Number(row.trip), list: Number(row.list) };
}
/** Up to `limit` entries in the list's order, after `after` when given. */
async pageEntries(
arms: LibraryArms,
match: LibraryMatch,
sort: LibrarySort,
after: LibraryPosition | null,
limit: number,
): Promise<LibraryAnchorRow[]> {
const db = this.db();
const value = after?.value ?? '';
const key = after?.key ?? 0;
const rows = await db
.selectFrom(this.entries(db, arms, match))
.select(['u.anchor_key', 'u.sort_name', 'u.sort_time'])
.distinct()
.$if(after !== null && sort === 'name', (qb) =>
qb.where((eb) =>
eb.or([eb('u.sort_name', '>', value), eb.and([eb('u.sort_name', '=', value), eb('u.anchor_key', '>', key)])]),
),
)
.$if(after !== null && sort === 'updated', (qb) =>
qb.where((eb) =>
eb.or([eb('u.sort_time', '<', value), eb.and([eb('u.sort_time', '=', value), eb('u.anchor_key', '<', key)])]),
),
)
.$if(sort === 'name', (qb) => qb.orderBy('u.sort_name', 'asc').orderBy('u.anchor_key', 'asc'))
.$if(sort === 'updated', (qb) => qb.orderBy('u.sort_time', 'desc').orderBy('u.anchor_key', 'desc'))
.limit(limit)
.execute();
return rows.map((row) => ({
anchor_key: Number(row.anchor_key),
sort_name: row.sort_name,
sort_time: row.sort_time,
}));
}
/** The trip place `placeId` when it is a normal place of one of `tripIds`. */
async findTripPlace(placeId: number, tripIds: number[]): Promise<number | null> {
const db = this.db();
const row = await db
.selectFrom('places as p')
.select('p.id')
.where('p.id', '=', placeId)
.where('p.id', 'in', this.normalPlaceIds(db, tripIds))
.executeTakeFirst();
return row ? row.id : null;
}
/** The entry key of the saved place `collectionPlaceId` when it is in one of `collectionIds`. */
async findSavedPlaceKey(
collectionPlaceId: number,
collectionIds: number[],
reachableTripIds: number[],
): Promise<number | null> {
const db = this.db();
const row = await db
.selectFrom('collection_places as cp')
.leftJoin(this.groupLinks(db, reachableTripIds).as('gl'), 'gl.collection_place_id', 'cp.id')
.select((eb) => eb.fn.coalesce('gl.place_id', eb.neg('cp.id')).as('anchor_key'))
.where('cp.id', '=', collectionPlaceId)
.where('cp.collection_id', 'in', idsOrNone(collectionIds))
.executeTakeFirst();
return row ? Number(row.anchor_key) : null;
}
/** The trip places with their trip and category, for the entries of a page. */
async tripPlaces(placeIds: number[], tripIds: number[]): Promise<LibraryTripPlaceRow[]> {
return await this.db()
.selectFrom('places as p')
.innerJoin('trips as t', 't.id', 'p.trip_id')
.leftJoin('categories as c', 'c.id', 'p.category_id')
.select([
'p.id',
'p.trip_id',
'p.name',
'p.address',
'p.lat',
'p.lng',
'p.image_url',
'p.updated_at',
'p.description',
'p.website',
'p.phone',
'c.id as category_id',
'c.name as category_name',
'c.color as category_color',
'c.icon as category_icon',
't.title as trip_title',
't.start_date as trip_start',
't.end_date as trip_end',
't.user_id as trip_owner_id',
])
.where('p.id', 'in', idsOrNone(placeIds))
.where('p.trip_id', 'in', idsOrNone(tripIds))
.execute();
}
/**
* The saved places of `collectionIds` that are named by `ids` or grouped
* with one of the trip places `groupedTo`, each with its list and the trip
* place it is grouped with, ordered by list name.
*/
async savedPlaces(
collectionIds: number[],
reachableTripIds: number[],
ids: number[],
groupedTo: number[],
): Promise<LibraryCollectionPlaceRow[]> {
const db = this.db();
const rows = await db
.selectFrom('collection_places as cp')
.innerJoin('collections as col', 'col.id', 'cp.collection_id')
.leftJoin(this.groupLinks(db, reachableTripIds).as('gl'), 'gl.collection_place_id', 'cp.id')
.leftJoin('categories as c', 'c.id', 'cp.category_id')
.select([
'cp.id',
'cp.collection_id',
'col.name as collection_name',
'cp.status',
'cp.name',
'cp.address',
'cp.lat',
'cp.lng',
'cp.image_url',
'cp.updated_at',
'cp.description',
'cp.website',
'cp.phone',
'c.id as category_id',
'c.name as category_name',
'c.color as category_color',
'c.icon as category_icon',
'gl.place_id as grouped_place_id',
])
.where('cp.collection_id', 'in', idsOrNone(collectionIds))
.where((eb) => eb.or([eb('cp.id', 'in', idsOrNone(ids)), eb('gl.place_id', 'in', idsOrNone(groupedTo))]))
.orderBy('col.name')
.orderBy('cp.id')
.execute();
return rows.map((row) => ({
...row,
grouped_place_id: row.grouped_place_id === null ? null : Number(row.grouped_place_id),
}));
}
/**
* The user's role on each of `collectionIds`: owner, or an accepted member
* row's role read the way `resolveCollectionRole` reads it. A list with
* neither reads as viewer, so it is never editable by mistake.
*/
async collectionRoles(userId: number, collectionIds: number[]): Promise<LibraryCollectionRole[]> {
const db = this.db();
const ids = idsOrNone(collectionIds);
const lists = await db.selectFrom('collections').select(['id', 'owner_id']).where('id', 'in', ids).execute();
const members = await db
.selectFrom('collection_members')
.select(['collection_id', 'role'])
.where('user_id', '=', userId)
.where('status', '=', 'accepted')
.where('collection_id', 'in', ids)
.execute();
const memberRole = new Map(members.map((row) => [row.collection_id, row.role]));
return lists.map((list) => {
if (list.owner_id === userId) return { id: list.id, role: 'owner' as const };
const stored = memberRole.get(list.id);
return { id: list.id, role: stored === undefined ? ('viewer' as const) : memberRoleOf(stored) };
});
}
async tripPlaceNotes(placeIds: number[]): Promise<LibraryNotesRow[]> {
return await this.db()
.selectFrom('places')
.select(['id', 'notes'])
.where('id', 'in', idsOrNone(placeIds))
.execute();
}
async savedPlaceNotes(collectionPlaceIds: number[]): Promise<LibraryNotesRow[]> {
return await this.db()
.selectFrom('collection_places')
.select(['id', 'notes'])
.where('id', 'in', idsOrNone(collectionPlaceIds))
.execute();
}
/** The labels of the saved places, in each list's label order. */
async savedPlaceLabels(collectionPlaceIds: number[]): Promise<LibraryLabelRow[]> {
return await this.db()
.selectFrom('collection_place_labels as cpl')
.innerJoin('collection_labels as l', 'l.id', 'cpl.label_id')
.select(['cpl.collection_place_id', 'l.id', 'l.name', 'l.color'])
.where('cpl.collection_place_id', 'in', idsOrNone(collectionPlaceIds))
.orderBy('l.sort_order')
.orderBy('l.id')
.execute();
}
async savedPlaceRatings(collectionPlaceIds: number[]): Promise<LibraryRatingRow[]> {
return await this.db()
.selectFrom('collection_place_ratings')
.select(['collection_place_id as target_id', 'user_id', 'rating'])
.where('collection_place_id', 'in', idsOrNone(collectionPlaceIds))
.execute();
}
async tripPlaceRatings(placeIds: number[]): Promise<LibraryRatingRow[]> {
return await this.db()
.selectFrom('place_ratings')
.select(['place_id as target_id', 'user_id', 'rating'])
.where('place_id', 'in', idsOrNone(placeIds))
.execute();
}
/** The days each place is planned on, in day order, with the time set there. */
async plannedDays(placeIds: number[]): Promise<LibraryDayRow[]> {
return await this.db()
.selectFrom('day_assignments as da')
.innerJoin('days as d', 'd.id', 'da.day_id')
.select([
'da.place_id',
'd.id as day_id',
'd.day_number',
'd.date',
'd.title',
'da.assignment_time as time',
'da.assignment_end_time as end_time',
])
.where('da.place_id', 'in', idsOrNone(placeIds))
.orderBy('d.day_number')
.orderBy('da.order_index')
.orderBy('da.id')
.execute();
}
/** Which of the places a stay points at, and which a booking points at. */
async bookedPlaces(placeIds: number[]): Promise<{ stays: number[]; bookings: number[] }> {
const db = this.db();
const ids = idsOrNone(placeIds);
const stays = await db
.selectFrom('day_accommodations')
.select('place_id')
.distinct()
.where('place_id', 'in', ids)
.execute();
const bookings = await db
.selectFrom('reservations')
.select('place_id')
.distinct()
.where('place_id', 'in', ids)
.execute();
const present = (rows: { place_id: number | null }[]) =>
rows.flatMap((row) => (row.place_id === null ? [] : [row.place_id]));
return { stays: present(stays), bookings: present(bookings) };
}
}
@@ -83,5 +83,14 @@ export async function resolveCollectionRole(
{ fields: ['role'] },
);
if (!member) return null;
return member.role === 'admin' || member.role === 'viewer' ? (member.role as 'admin' | 'viewer') : 'editor';
return memberRoleOf(member.role);
}
/**
* The role an accepted member row grants: `'admin'`/`'viewer'` as stored,
* anything else `'editor'` (the legacy `roleOf` fallback). Shared with the
* reads that resolve the roles of many lists at once.
*/
export function memberRoleOf(stored: string | null | undefined): 'admin' | 'editor' | 'viewer' {
return stored === 'admin' || stored === 'viewer' ? stored : 'editor';
}
+2
View File
@@ -80,6 +80,7 @@ import { PlaceContribModule } from './place-contrib/place-contrib.module';
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
import { PlaceImportModule } from './place-import/place-import.module';
import { PlaceShadowModule } from './place-shadow/place-shadow.module';
import { PlacesLibraryModule } from './places-library/places-library.module';
import { PlacesModule } from './places/places.module';
import { PlatformModule } from './platform/platform.module';
import { SpaFallbackFilter } from './platform/spa-fallback.filter';
@@ -202,6 +203,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
JourneyRecordingsModule,
TripJournalLinkModule,
CollectionsModule,
PlacesLibraryModule,
ShareModule,
TripInviteModule,
TransitModule,
@@ -0,0 +1,46 @@
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 { PlacesLibraryQueryDto } from './places-library.dto';
import { PlacesLibraryService } from './places-library.service';
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
import { placesLibraryDetailResponseSchema, placesLibraryPageResponseSchema } from '@trek/shared';
/**
* PLC-07/PLC-08 /api/addons/collections/library/places: "All places", the
* saved places of every list and the places of every trip the user can open,
* and one of them in detail, opened from a trip place or a saved place. Two
* segments deep, so the collections' own `GET /:id` never takes the list. The
* addon guard runs first, as on every collections route, so a disabled addon
* answers 404 before any sign-in check; the service bounds every answer by the
* user's lists and trips.
*/
@Controller('api/addons/collections/library/places')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
export class PlacesLibraryController {
constructor(private readonly library: PlacesLibraryService) {}
@Get()
@ResponseContract(placesLibraryPageResponseSchema)
async list(@CurrentUser() user: User, @Query() query: PlacesLibraryQueryDto) {
return await this.library.list({ id: user.id, role: user.role }, query);
}
@Get('trip/:id')
@ResponseContract(placesLibraryDetailResponseSchema)
async tripPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) {
return await this.library.detail({ id: user.id, role: user.role }, 'trip', id);
}
@Get('list/:id')
@ResponseContract(placesLibraryDetailResponseSchema)
async savedPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) {
return await this.library.detail({ id: user.id, role: user.role }, 'list', id);
}
}
@@ -0,0 +1,5 @@
import { placesLibraryQuerySchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class PlacesLibraryQueryDto extends createZodDto(placesLibraryQuerySchema) {}
@@ -0,0 +1,166 @@
import type {
LibraryAnchorRow,
LibraryCollectionPlaceRow,
LibraryPosition,
LibraryRatingRow,
LibrarySort,
LibraryTripPlaceRow,
} from '../../db/repositories/PlacesLibrary.repository';
import {
collectionStatusSchema,
PLACES_LIBRARY_SORTS,
type PlacesLibraryCategory,
type PlacesLibraryEntry,
type PlacesLibraryInfo,
type PlacesLibraryListOrigin,
type PlacesLibraryRating,
type PlacesLibraryTripOrigin,
} from '@trek/shared';
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. */
export function entryKey(anchor: number): string {
return anchor > 0 ? `trip:${anchor}` : `list:${-anchor}`;
}
/** The position after which the next page starts, opaque to the client. */
export function encodeLibraryCursor(sort: LibrarySort, anchor: LibraryAnchorRow): string {
const value = sort === 'name' ? anchor.sort_name : anchor.sort_time;
return Buffer.from(JSON.stringify([sort, value, anchor.anchor_key])).toString('base64url');
}
/** The position a cursor names, or null for one this sort did not hand out. */
export function decodeLibraryCursor(sort: LibrarySort, cursor: string): LibraryPosition | null {
let parsed: unknown;
try {
parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
} catch {
return null;
}
const result = cursorSchema.safeParse(parsed);
if (!result.success || result.data[0] !== sort) return null;
return { value: result.data[1], key: result.data[2] };
}
/** The votes of one place: their mean, how many there are, and the user's own. */
export function ratingOf(rows: readonly LibraryRatingRow[], userId: number): PlacesLibraryRating {
if (rows.length === 0) return { average: null, count: 0, mine: null };
const sum = rows.reduce((total, row) => total + row.rating, 0);
return {
average: sum / rows.length,
count: rows.length,
mine: rows.find((row) => row.user_id === userId)?.rating ?? null,
};
}
type FactsRow = LibraryTripPlaceRow | LibraryCollectionPlaceRow;
function categoryOf(row: FactsRow): 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 };
}
/** The general facts of a place as this row keeps them. */
export function infoOf(row: FactsRow): PlacesLibraryInfo {
return {
name: row.name,
address: row.address,
lat: row.lat,
lng: row.lng,
description: row.description,
website: row.website,
phone: row.phone,
image_url: row.image_url,
category: categoryOf(row),
};
}
function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean): PlacesLibraryTripOrigin {
return {
kind: 'trip',
trip_id: row.trip_id,
trip_title: row.trip_title,
trip_start: row.trip_start,
trip_end: row.trip_end,
place_id: row.id,
can_edit: canEdit,
read_only: !canEdit,
};
}
function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean): PlacesLibraryListOrigin {
return {
kind: 'list',
collection_id: row.collection_id,
collection_name: row.collection_name,
collection_place_id: row.id,
status: collectionStatusSchema.parse(row.status),
can_edit: canEdit,
};
}
/** What may be done with each origin, as the service resolved it. */
export interface OriginAccess {
canEditTrip: (row: LibraryTripPlaceRow) => boolean;
canEditList: (row: LibraryCollectionPlaceRow) => boolean;
}
/** One entry's rows: its trip place where it has one, and its saved places. */
export interface EntryRows {
anchor: number;
trip: LibraryTripPlaceRow | null;
saved: LibraryCollectionPlaceRow[];
}
/**
* 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.
*/
export function rowsByAnchor(
anchors: readonly number[],
trips: readonly LibraryTripPlaceRow[],
saved: readonly LibraryCollectionPlaceRow[],
): EntryRows[] {
const tripById = new Map(trips.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 }] : [];
});
}
/** 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 {
// 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))),
];
return {
key: entryKey(rows.anchor),
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,
updated_at: lead.updated_at,
origins,
};
}
/** Groups rows by one numeric field, keeping their order. */
export function groupBy<T>(rows: readonly T[], keyOf: (row: T) => number): Map<number, T[]> {
const groups = new Map<number, T[]>();
for (const row of rows) groups.set(keyOf(row), [...(groups.get(keyOf(row)) ?? []), row]);
return groups;
}
@@ -0,0 +1,68 @@
import { ADDON_IDS } from '../../addons';
import { canRead, canReadTrips } from '../../mcp/scopes';
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, okCompact, 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 { PlacesLibraryService, type LibraryUser } from './places-library.service';
import {
PLACES_LIBRARY_PAGE_DEFAULT,
PLACES_LIBRARY_PAGE_MAX,
placesLibraryDetailRequestSchema,
placesLibraryQuerySchema,
type PlacesLibraryDetailRequest,
type PlacesLibraryQuery,
} from '@trek/shared';
/**
* How long a page may run as JSON. The in-app assistant cuts a tool answer at
* 40,000 characters, so a page ends before that and next_cursor goes on after
* its last entry, as list_collection_places does.
*/
const PAGE_CHARS = 30_000;
/** The list reads trips and lists alike, so a token needs to read both. */
const readsTripsAndLists = (ctx: McpContext) => canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
/**
* PLC-07/PLC-08 "All places" over the same service and the same checks as
* REST: the lists and trips the user can open, read anew for every call.
*/
@McpController()
export class PlacesLibraryMcp {
constructor(
private readonly library: PlacesLibraryService,
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: 'list_all_places',
description: `Page through every place the user has: the saved places of every list they can open and the places of every trip they can open, by name (sort: name, the default) or last changed first (sort: updated), ${PLACES_LIBRARY_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${PLACES_LIBRARY_PAGE_MAX}). Tours, tracks and road trip stops of the drive are left out; lodging counts as a place. A saved place and a trip place are one entry only when the saved place came from that trip place and both agree (the same provider id, or the same name at the same spot); otherwise they are separate entries. Each entry has a key, name, address, lat, lng, category, image_url and its origins: kind trip (trip_id, trip_title, trip_start, trip_end, place_id, can_edit, read_only) or kind list (collection_id, collection_name, collection_place_id, status, can_edit). No notes; get_library_place reads one entry in full. Filter by q (name or address), category_id, kind, collection_id, trip_id or status (a list status); a list filter and a trip filter do not go together. Next to the page: total (what every filter matches), counts (all, trip, list for q and category_id alone) and next_cursor, passed back as cursor for the next page, null on the last. A page can end before limit, so always go on at next_cursor.`,
inputSchema: placesLibraryQuerySchema.shape,
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: readsTripsAndLists,
})
async listAllPlaces(input: PlacesLibraryQuery, ctx: McpContext) {
return okCompact(await this.library.list(await this.user(ctx.userId), input, { maxChars: PAGE_CHARS }));
}
@Tool({
name: 'get_library_place',
description:
'One entry of list_all_places in full, named by one of its origins: kind trip with a trip place_id, or kind list with a collection_place_id. Answers the entry with every origin, and for each origin what it keeps on its own, in the same order: info (name, address, lat, lng, description, website, phone, image_url and category as that origin stores them, so two origins may differ), notes, rating (average, count, mine), for a list its labels, for a trip the days the place is planned on (day number, date, title, time, end time) and whether a stay or a booking uses it. Changes nothing.',
inputSchema: placesLibraryDetailRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: readsTripsAndLists,
})
async getLibraryPlace(input: PlacesLibraryDetailRequest, ctx: McpContext) {
return ok(await this.library.detail(await this.user(ctx.userId), input.kind, input.id));
}
}
@@ -0,0 +1,32 @@
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 { TripMembershipModule } from '../trip-membership/trip-membership.module';
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 { 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.
*/
@Module({
imports: [AddonsModule, CollectionsModule, TripMembershipModule, PermissionsModule, McpSharedModule],
controllers: [PlacesLibraryController],
providers: [
{
provide: PlacesLibraryRepository,
useFactory: (em: EntityManager) => new PlacesLibraryRepository(em),
inject: [EntityManager],
},
PlacesLibraryService,
PlacesLibraryMcp,
],
})
export class PlacesLibraryModule {}
@@ -0,0 +1,269 @@
import {
PlacesLibraryRepository,
type LibraryArms,
type LibraryCollectionPlaceRow,
type LibraryMatch,
type LibrarySort,
type LibraryTripPlaceRow,
} from '../../db/repositories/PlacesLibrary.repository';
import { CollectionsService } from '../collections/collections.service';
import { badRequest, notFound } from '../common/domain-error';
import { PermissionsService } from '../permissions/permissions.service';
import { TripMembershipService } from '../trip-membership/trip-membership.service';
import {
decodeLibraryCursor,
encodeLibraryCursor,
entryKey,
entryOf,
groupBy,
infoOf,
ratingOf,
rowsByAnchor,
type EntryRows,
type OriginAccess,
} from './places-library.helpers';
import { Injectable } from '@nestjs/common';
import {
PLACES_LIBRARY_PAGE_DEFAULT,
type PlacesLibraryDetail,
type PlacesLibraryDetailResponse,
type PlacesLibraryEntry,
type PlacesLibraryKind,
type PlacesLibraryPageResponse,
type PlacesLibraryQuery,
} from '@trek/shared';
/** Who asks, as the permission check reads them. */
export interface LibraryUser {
id: number;
role: string;
}
/** What the user reaches right now, read anew for every call. */
interface Reach {
tripIds: number[];
collectionIds: number[];
}
interface LibraryListOptions {
/** End a page early once its entries run this long as JSON (the assistant cuts long tool answers). */
maxChars?: number;
}
const placeNotFound = () => notFound('Place not found');
/**
* PLC-07/PLC-08 "All places": the saved places of every list the user can
* open and the places of every trip they can open, read only and paged, and
* one entry in detail with what each of its origins keeps. Who sees what is
* the existing checks, asked anew for every call: the lists of
* `CollectionsService.accessibleCollectionIds`, the trips of
* `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.
*/
@Injectable()
export class PlacesLibraryService {
constructor(
private readonly repo: PlacesLibraryRepository,
private readonly collections: CollectionsService,
private readonly membership: TripMembershipService,
private readonly permissions: PermissionsService,
) {}
async list(
user: LibraryUser,
query: PlacesLibraryQuery,
options: LibraryListOptions = {},
): Promise<PlacesLibraryPageResponse> {
const sort: LibrarySort = query.sort ?? 'name';
const after = query.cursor === undefined ? null : decodeLibraryCursor(sort, query.cursor);
if (query.cursor !== undefined && after === null) {
throw badRequest('Invalid cursor: pass the next_cursor of the page before');
}
const reach = await this.reach(user.id);
const arms = armsFor(reach, query);
const match: LibraryMatch = {
search: query.q ? query.q : null,
categoryId: query.category_id ?? null,
status: query.status ?? null,
};
const facets = { ...arms, tripIds: reach.tripIds, collectionIds: reach.collectionIds };
const counts = await this.repo.countEntries(facets, { ...match, status: null });
const narrowed =
query.kind !== undefined ||
query.collection_id !== undefined ||
query.trip_id !== undefined ||
query.status !== undefined;
const total = narrowed ? (await this.repo.countEntries(arms, match)).all : counts.all;
const limit = query.limit ?? PLACES_LIBRARY_PAGE_DEFAULT;
// One entry more than the page holds says whether another page follows.
const anchors = await this.repo.pageEntries(arms, match, sort, after, limit + 1);
const candidates = anchors.slice(0, limit);
const entries = fitPage(
await this.entries(
user,
reach,
candidates.map((anchor) => anchor.anchor_key),
),
options.maxChars,
);
// The page goes on after its last entry; a place deleted between the reads leaves no gap in the order.
const lastKey = entries[entries.length - 1]?.key;
const last =
lastKey === undefined
? candidates[candidates.length - 1]
: candidates.find((anchor) => entryKey(anchor.anchor_key) === lastKey);
const more = anchors.length > limit || (last !== undefined && last !== candidates[candidates.length - 1]);
return {
entries,
total,
counts,
next_cursor: more && last ? encodeLibraryCursor(sort, last) : null,
};
}
/** 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);
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));
return { entry, details: await this.details(user.id, rows) };
}
private async reach(userId: number): Promise<Reach> {
const tripIds = await this.membership.listAccessibleTripIds(userId);
const collectionIds = await this.collections.accessibleCollectionIds(userId);
return { 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);
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);
}
private async entries(user: LibraryUser, reach: Reach, 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.saved),
);
return rows.map((row) => entryOf(row, access));
}
/**
* 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(
user: LibraryUser,
trips: readonly LibraryTripPlaceRow[],
saved: readonly LibraryCollectionPlaceRow[],
): Promise<OriginAccess> {
const listIds = [...new Set(saved.map((row) => row.collection_id))];
const roles = listIds.length > 0 ? await this.repo.collectionRoles(user.id, listIds) : [];
const editableLists = new Set(roles.filter((role) => role.role !== 'viewer').map((role) => role.id));
const asOwner = trips.some((row) => row.trip_owner_id === user.id)
? await this.permissions.checkPermission('place_edit', user.role, user.id, user.id, false)
: false;
const asMember = trips.some((row) => row.trip_owner_id !== user.id)
? await this.permissions.checkPermission('place_edit', user.role, null, user.id, true)
: false;
return {
canEditTrip: (row) => (row.trip_owner_id === user.id ? asOwner : asMember),
canEditList: (row) => editableLists.has(row.collection_id),
};
}
/** What each origin keeps, in the entry's origin order: the trip place 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);
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),
});
}
if (rows.saved.length > 0) {
const savedIds = rows.saved.map((row) => row.id);
const notes = new Map((await this.repo.savedPlaceNotes(savedIds)).map((row) => [row.id, row.notes]));
const labels = groupBy(await this.repo.savedPlaceLabels(savedIds), (row) => row.collection_place_id);
const ratings = groupBy(await this.repo.savedPlaceRatings(savedIds), (row) => row.target_id);
for (const row of rows.saved) {
details.push({
kind: 'list',
collection_place_id: row.id,
info: infoOf(row),
notes: notes.get(row.id) ?? null,
labels: (labels.get(row.id) ?? []).map(({ id, name, color }) => ({ id, name, color })),
rating: ratingOf(ratings.get(row.id) ?? [], userId),
});
}
}
return details;
}
}
/**
* Which trips and lists the page reads. A filter on a list (its kind, one
* 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 {
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 {
tripIds: listsOnly ? [] : only(reach.tripIds, query.trip_id),
collectionIds: tripsOnly ? [] : only(reach.collectionIds, query.collection_id),
reachableTripIds: reach.tripIds,
};
}
/** The entries in order until their JSON would pass `maxChars`; always at least one. */
function fitPage(entries: PlacesLibraryEntry[], maxChars: number | undefined): PlacesLibraryEntry[] {
if (maxChars === undefined) return entries;
const page: PlacesLibraryEntry[] = [];
let chars = 0;
for (const entry of entries) {
chars += JSON.stringify(entry).length + 1;
if (page.length > 0 && chars > maxChars) break;
page.push(entry);
}
return page;
}