mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
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:
@@ -18,6 +18,7 @@
|
||||
import {
|
||||
castIntegerKysely,
|
||||
concatKysely,
|
||||
containsIgnoringCaseKysely,
|
||||
currentTimestampKysely,
|
||||
integerTextEqualsKysely,
|
||||
nowPlusSecondsKysely,
|
||||
@@ -350,6 +351,28 @@ export const HELPER_CASES: readonly HelperCase[] = [
|
||||
concatKysely(p, eb, { column: 'a' }, { value: 'T' }, { expression: substringKysely(p, eb, 'b', 3) }),
|
||||
expect: { equals: '2026-09-21T10:00' },
|
||||
},
|
||||
...(
|
||||
[
|
||||
['Café Central', 'CENTRAL', 'yes'],
|
||||
['50% off', '50%', 'yes'],
|
||||
['abc', 'a%', 'no'],
|
||||
['a_c', 'a_c', 'yes'],
|
||||
['abc', 'a_c', 'no'],
|
||||
] as const
|
||||
).map(
|
||||
([stored, needle, found]): HelperCase => ({
|
||||
name: `containsIgnoringCaseKysely finds ${JSON.stringify(needle)} in ${JSON.stringify(stored)}: ${found}`,
|
||||
row: { a: stored },
|
||||
kysely: (p, eb) => eb.case().when(containsIgnoringCaseKysely(p, eb, 'a', needle)).then('yes').else('no').end(),
|
||||
expect: { equals: found },
|
||||
}),
|
||||
),
|
||||
{
|
||||
name: 'containsIgnoringCaseKysely finds nothing in NULL',
|
||||
row: { a: null },
|
||||
kysely: (p, eb) => eb.case().when(containsIgnoringCaseKysely(p, eb, 'a', 'x')).then('yes').else('no').end(),
|
||||
expect: { equals: 'no' },
|
||||
},
|
||||
{
|
||||
name: 'castIntegerKysely',
|
||||
row: { a: '14.0' },
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* "All places" (PLC-07/PLC-08) through the real AddonGuard and JwtAuthGuard
|
||||
* against a migrated and seeded temp SQLite db, every answer checked against
|
||||
* its response contract. The collections' own routes are mounted beside it,
|
||||
* so the list is shown to reach its handler and not the collections' `GET /:id`.
|
||||
*/
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { PlacesLibraryModule } from '../../src/nest/places-library/places-library.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { expectedKeysByName, seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture';
|
||||
import { resetTestDb } from '../helpers/test-db';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const BASE = '/api/addons/collections/library/places';
|
||||
|
||||
let app: INestApplication;
|
||||
let server: Server;
|
||||
let orm: TestOrm;
|
||||
let f: LibraryFixture;
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
RealtimeModule,
|
||||
PlacesLibraryModule,
|
||||
],
|
||||
})
|
||||
.overrideProvider(RealtimeService)
|
||||
.useValue(new FakeRealtimeService())
|
||||
.compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.use(cookieParser());
|
||||
app.useGlobalPipes(new ZodValidationPipe());
|
||||
app.useGlobalFilters(new TrekExceptionFilter());
|
||||
await app.init();
|
||||
server = app.getHttpServer() as Server;
|
||||
orm = await createTestOrm(db);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(db);
|
||||
orm.clear();
|
||||
f = await seedLibrary(orm);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
describe('Places library e2e (real guards + temp SQLite)', () => {
|
||||
it('answers 404 while Collections is off, before any sign-in check, and 401 without a session', async () => {
|
||||
await setAddonEnabled(orm, 'collections', false);
|
||||
expect((await request(server).get(BASE)).status).toBe(404);
|
||||
expect((await request(server).get(`${BASE}/trip/${f.places.cafe.id}`)).status).toBe(404);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
expect((await request(server).get(BASE)).status).toBe(401);
|
||||
});
|
||||
|
||||
it('lists every entry the user reaches, page by page', async () => {
|
||||
const res = await request(server).get(BASE).set(as(f.me.id));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.entries.map((entry: { key: string }) => entry.key)).toEqual(expectedKeysByName(f));
|
||||
expect(res.body.counts).toEqual({ all: 10, trip: 5, list: 7 });
|
||||
|
||||
const first = await request(server).get(BASE).query({ limit: '4' }).set(as(f.me.id));
|
||||
expect(first.body.entries).toHaveLength(4);
|
||||
const next = await request(server)
|
||||
.get(BASE)
|
||||
.query({ limit: '50', cursor: first.body.next_cursor })
|
||||
.set(as(f.me.id));
|
||||
expect(next.body.entries).toHaveLength(6);
|
||||
expect(next.body.next_cursor).toBeNull();
|
||||
});
|
||||
|
||||
it('reads the filters from the query string and refuses what it does not take', async () => {
|
||||
const trips = await request(server)
|
||||
.get(BASE)
|
||||
.query({ kind: 'trip', trip_id: String(f.rome.id) })
|
||||
.set(as(f.me.id));
|
||||
expect(trips.status).toBe(200);
|
||||
expect(trips.body.entries.map((entry: { key: string }) => entry.key)).toEqual([`trip:${f.places.forum.id}`]);
|
||||
for (const query of [{ category_id: '0x5' }, { kind: 'tour' }, { limit: '1000' }, { notes: 'x' }]) {
|
||||
expect((await request(server).get(BASE).query(query).set(as(f.me.id))).status).toBe(400);
|
||||
}
|
||||
const both = await request(server)
|
||||
.get(BASE)
|
||||
.query({ kind: 'list', trip_id: String(f.alps.id) })
|
||||
.set(as(f.me.id));
|
||||
expect(both.status).toBe(400);
|
||||
expect(both.body).toEqual({ error: 'Filter by a trip or by a list, not both' });
|
||||
});
|
||||
|
||||
it('opens one entry from a trip place or a saved place, and nothing out of reach', async () => {
|
||||
const trip = await request(server).get(`${BASE}/trip/${f.places.cafe.id}`).set(as(f.me.id));
|
||||
expect(trip.status).toBe(200);
|
||||
expect(trip.body.entry.key).toBe(`trip:${f.places.cafe.id}`);
|
||||
expect(trip.body.details.map((detail: { kind: string }) => detail.kind)).toEqual(['trip', 'list']);
|
||||
|
||||
const saved = await request(server).get(`${BASE}/list/${f.saved.pantheon.id}`).set(as(f.me.id));
|
||||
expect(saved.status).toBe(200);
|
||||
expect(saved.body.entry.origins[0]).toMatchObject({ kind: 'list', can_edit: false });
|
||||
|
||||
for (const path of [`trip/${f.places.hidden.id}`, `list/${f.saved.secret.id}`, 'trip/abc', 'list/0x5']) {
|
||||
const res = await request(server).get(`${BASE}/${path}`).set(as(f.me.id));
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Place not found' });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* The lists and trips the "All places" suites read, seeded through the ORM
|
||||
* factories. The user `me` owns the trip Alps and the list Food, is a member
|
||||
* of `friend`'s trip Rome and a viewer of `friend`'s list Rome sights;
|
||||
* `stranger` owns a trip and a list `me` cannot open.
|
||||
*
|
||||
* Alps holds the normal places Café Central, Museum, Hotel Sonne (lodging) and
|
||||
* Camp Lake (a road trip campsite a stay points at), and the places "All
|
||||
* places" leaves out: a tour, an imported track and a fuel stop. Food holds a
|
||||
* copy of each kind the grouping rule tells apart.
|
||||
*/
|
||||
import { CollectionLabels } from '../../src/db/entities/CollectionLabels.entity';
|
||||
import { CollectionPlaceRatings } from '../../src/db/entities/CollectionPlaceRatings.entity';
|
||||
import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity';
|
||||
import {
|
||||
addCollectionMember,
|
||||
labelCollectionPlace,
|
||||
makeCollection,
|
||||
makeCollectionPlace,
|
||||
} from './factories/collections';
|
||||
import type { FactoryOrm } from './factories/context';
|
||||
import { makeDayAccommodation, makeDayAssignment } from './factories/itinerary';
|
||||
import { makePlace } from './factories/places';
|
||||
import { makeReservation } from './factories/reservations';
|
||||
import { createRow, insertRows } from './factories/rows';
|
||||
import { makeTour } from './factories/tours';
|
||||
import { addTripMember, makeTrip, readTripDays } from './factories/trips';
|
||||
import { makeUser } from './factories/users';
|
||||
|
||||
export async function seedLibrary(orm: FactoryOrm) {
|
||||
const { user: me } = await makeUser(orm);
|
||||
const { user: friend } = await makeUser(orm);
|
||||
const { user: stranger } = await makeUser(orm);
|
||||
|
||||
const alps = await makeTrip(orm, me.id, { title: 'Alps', start_date: '2026-07-01', end_date: '2026-07-03' });
|
||||
const rome = await makeTrip(orm, friend.id, { title: 'Rome' });
|
||||
await addTripMember(orm, rome.id, me.id);
|
||||
const elsewhere = await makeTrip(orm, stranger.id, { title: 'Elsewhere' });
|
||||
|
||||
const cafe = await makePlace(orm, alps.id, {
|
||||
name: 'Café Central',
|
||||
address: 'Herrengasse 14, Wien',
|
||||
lat: 48.2104,
|
||||
lng: 16.3655,
|
||||
google_place_id: 'g-cafe',
|
||||
notes: 'Book a table',
|
||||
description: 'A coffee house',
|
||||
});
|
||||
const museum = await makePlace(orm, alps.id, {
|
||||
name: 'Museum',
|
||||
lat: 47.2681,
|
||||
lng: 11.3933,
|
||||
google_place_id: 'g-museum',
|
||||
});
|
||||
const hotel = await makePlace(orm, alps.id, { name: 'Hotel Sonne', stop_type: 'hotel' });
|
||||
const camp = await makePlace(orm, alps.id, { name: 'Camp Lake', stop_type: 'campsite' });
|
||||
const ridge = await makePlace(orm, alps.id, { name: 'Ridge walk' });
|
||||
await makeTour(orm, ridge.id);
|
||||
const track = await makePlace(orm, alps.id, { name: 'Imported track', route_geometry: '[[47,11],[47.1,11.1]]' });
|
||||
const pump = await makePlace(orm, alps.id, { name: 'Fuel pump', stop_type: 'fuel' });
|
||||
const days = await readTripDays(orm, alps.id);
|
||||
const [day1, day2] = days;
|
||||
if (!day1 || !day2) throw new Error('seedLibrary: Alps has no days');
|
||||
await makeDayAccommodation(orm, alps.id, camp.id, day1.id, day2.id);
|
||||
await makeDayAssignment(orm, day1.id, cafe.id, { assignment_time: '09:00' });
|
||||
await makeReservation(orm, alps.id, { place: hotel.id, title: 'Hotel Sonne', type: 'hotel' });
|
||||
await insertRows(orm, PlaceRatings, [
|
||||
{ place: cafe.id, user: me.id, rating: 4 },
|
||||
{ place: cafe.id, user: friend.id, rating: 2 },
|
||||
]);
|
||||
|
||||
const forum = await makePlace(orm, rome.id, { name: 'Forum Romanum', lat: 41.8925, lng: 12.4853 });
|
||||
const hidden = await makePlace(orm, elsewhere.id, { name: 'Hidden', lat: 1, lng: 1 });
|
||||
|
||||
const food = await makeCollection(orm, me.id, { name: 'Food' });
|
||||
// The same place: it came from Café Central, same name once trimmed and lowered, a few metres off.
|
||||
const savedCafe = await makeCollectionPlace(orm, food.id, me.id, {
|
||||
name: ' café central ',
|
||||
lat: 48.21042,
|
||||
lng: 16.36551,
|
||||
source_trip_id: alps.id,
|
||||
source_place_id: cafe.id,
|
||||
status: 'want',
|
||||
notes: 'Try the cake',
|
||||
});
|
||||
// The same place by its provider id, whatever it is called and with no position.
|
||||
const savedMuseum = await makeCollectionPlace(orm, food.id, me.id, {
|
||||
name: 'Tiroler Landesmuseum',
|
||||
lat: null,
|
||||
lng: null,
|
||||
google_place_id: 'g-museum',
|
||||
source_trip_id: alps.id,
|
||||
source_place_id: museum.id,
|
||||
});
|
||||
// Came from Café Central but renamed: a name of its own keeps it apart.
|
||||
const lunch = await makeCollectionPlace(orm, food.id, me.id, {
|
||||
name: 'Lunch spot',
|
||||
lat: 48.2104,
|
||||
lng: 16.3655,
|
||||
source_trip_id: alps.id,
|
||||
source_place_id: cafe.id,
|
||||
});
|
||||
// Same name and spot as Café Central, but another provider id: a different place.
|
||||
const conflicting = await makeCollectionPlace(orm, food.id, me.id, {
|
||||
name: 'Café Central',
|
||||
lat: 48.2104,
|
||||
lng: 16.3655,
|
||||
google_place_id: 'g-other',
|
||||
source_trip_id: alps.id,
|
||||
source_place_id: cafe.id,
|
||||
});
|
||||
// Same name and spot as Museum, but no source: a name never groups on its own.
|
||||
const namesake = await makeCollectionPlace(orm, food.id, me.id, { name: 'Museum', lat: 47.2681, lng: 11.3933 });
|
||||
// Points at a place of a trip `me` cannot open.
|
||||
const hiddenCopy = await makeCollectionPlace(orm, food.id, me.id, {
|
||||
name: 'Hidden copy',
|
||||
lat: 1,
|
||||
lng: 1,
|
||||
source_trip_id: elsewhere.id,
|
||||
source_place_id: hidden.id,
|
||||
});
|
||||
const label = await createRow(orm, CollectionLabels, { collection: food.id, name: 'Must', color: '#ff0000' });
|
||||
await labelCollectionPlace(orm, savedCafe.id, label.id);
|
||||
await insertRows(orm, CollectionPlaceRatings, [{ collectionPlace: savedCafe.id, user: me.id, rating: 5 }]);
|
||||
|
||||
const sights = await makeCollection(orm, friend.id, { name: 'Rome sights' });
|
||||
await addCollectionMember(orm, sights.id, me.id, { role: 'viewer' });
|
||||
const pantheon = await makeCollectionPlace(orm, sights.id, friend.id, { name: 'Pantheon', status: 'visited' });
|
||||
|
||||
const secrets = await makeCollection(orm, stranger.id, { name: 'Secrets' });
|
||||
const secret = await makeCollectionPlace(orm, secrets.id, stranger.id, {
|
||||
name: 'Café Central',
|
||||
lat: 48.2104,
|
||||
lng: 16.3655,
|
||||
source_trip_id: alps.id,
|
||||
source_place_id: cafe.id,
|
||||
});
|
||||
|
||||
return {
|
||||
me,
|
||||
friend,
|
||||
stranger,
|
||||
alps,
|
||||
rome,
|
||||
elsewhere,
|
||||
day1,
|
||||
places: { cafe, museum, hotel, camp, ridge, track, pump, forum, hidden },
|
||||
lists: { food, sights, secrets },
|
||||
saved: { savedCafe, savedMuseum, lunch, conflicting, namesake, hiddenCopy, pantheon, secret },
|
||||
label,
|
||||
};
|
||||
}
|
||||
|
||||
export type LibraryFixture = Awaited<ReturnType<typeof seedLibrary>>;
|
||||
|
||||
/** The keys of `me`'s entries by name, ties by key (a saved place's negative key first). */
|
||||
export function expectedKeysByName(f: LibraryFixture): string[] {
|
||||
const { places, saved } = f;
|
||||
return [
|
||||
`list:${saved.conflicting.id}`,
|
||||
`trip:${places.cafe.id}`,
|
||||
`trip:${places.camp.id}`,
|
||||
`trip:${places.forum.id}`,
|
||||
`list:${saved.hiddenCopy.id}`,
|
||||
`trip:${places.hotel.id}`,
|
||||
`list:${saved.lunch.id}`,
|
||||
`list:${saved.namesake.id}`,
|
||||
`trip:${places.museum.id}`,
|
||||
`list:${saved.pantheon.id}`,
|
||||
];
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
castIntegerKysely,
|
||||
concatKysely,
|
||||
containsIgnoringCaseKysely,
|
||||
currentTimestampKysely,
|
||||
integerTextEqualsKysely,
|
||||
nowPlusSecondsKysely,
|
||||
@@ -276,6 +277,28 @@ describe('kysely-functions (postgres)', () => {
|
||||
expect(now.parameters).toEqual([]);
|
||||
});
|
||||
|
||||
it('SQLFPG-026: containsIgnoringCaseKysely is strpos over both sides lowered, the needle cast to text', () => {
|
||||
const compiled = db
|
||||
.selectFrom('users')
|
||||
.select((eb) => containsIgnoringCaseKysely(pg, eb, 'username', '50%').as('v'))
|
||||
.compile();
|
||||
expect(compiled.sql).toBe('select strpos(lower("username"), lower(cast($1 as text))) > 0 as "v" from "users"');
|
||||
expect(compiled.parameters).toEqual(['50%']);
|
||||
|
||||
// The same statement spelled for SQLite, rendered by this compiler: only the function differs.
|
||||
const onSqlite = db
|
||||
.selectFrom('users')
|
||||
.select((eb) => containsIgnoringCaseKysely(new SqlitePlatform(), eb, 'username', 'x').as('v'))
|
||||
.compile();
|
||||
expect(onSqlite.sql).toBe('select instr(lower("username"), lower(cast($1 as text))) > 0 as "v" from "users"');
|
||||
|
||||
class FakePlatform extends Platform {}
|
||||
const eb = expressionBuilder<ProbeDB, 'users'>();
|
||||
expect(() => containsIgnoringCaseKysely(new FakePlatform(), eb, 'username', 'x')).toThrow(
|
||||
/no implementation for platform FakePlatform/,
|
||||
);
|
||||
});
|
||||
|
||||
it('SQLFPG-025: an unknown platform still fails closed in the Kysely twins', () => {
|
||||
class FakePlatform extends Platform {}
|
||||
const foreign = new FakePlatform();
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* PlacesLibraryController over a stub service: each route hands the signed-in
|
||||
* user (id and role) and its input to the one service method, and answers
|
||||
* with what it returns. Guards, the id pipe and the response contracts run in
|
||||
* the e2e suite.
|
||||
*/
|
||||
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
|
||||
import { PlacesLibraryController } from '../../../../src/nest/places-library/places-library.controller';
|
||||
import type { PlacesLibraryService } from '../../../../src/nest/places-library/places-library.service';
|
||||
import type { User } from '../../../../src/types';
|
||||
import { placesLibraryDetailResponseSchema, placesLibraryPageResponseSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const user = { id: 7, role: 'admin', username: 'ann', email: 'ann@example.test' } as User;
|
||||
|
||||
function controller(service: Partial<PlacesLibraryService>) {
|
||||
return new PlacesLibraryController(service as unknown as PlacesLibraryService);
|
||||
}
|
||||
|
||||
describe('PlacesLibraryController', () => {
|
||||
it('GET library/places hands the query to the list with the user and its role', async () => {
|
||||
const page = { entries: [], total: 0, counts: { all: 0, trip: 0, list: 0 }, next_cursor: null };
|
||||
const list = vi.fn().mockResolvedValue(page);
|
||||
const query = { q: 'cafe', kind: 'list' as const, limit: 20 };
|
||||
expect(await controller({ list }).list(user, query)).toBe(page);
|
||||
expect(list).toHaveBeenCalledWith({ id: 7, role: 'admin' }, query);
|
||||
});
|
||||
|
||||
it('GET library/places/trip/:id and list/:id open one entry by the origin they name', async () => {
|
||||
const answer = { entry: { key: 'trip:3' }, details: [] };
|
||||
const detail = vi.fn().mockResolvedValue(answer);
|
||||
const c = controller({ detail });
|
||||
expect(await c.tripPlace(user, 3)).toBe(answer);
|
||||
expect(await c.savedPlace(user, 9)).toBe(answer);
|
||||
expect(detail.mock.calls).toEqual([
|
||||
[{ id: 7, role: 'admin' }, 'trip', 3],
|
||||
[{ id: 7, role: 'admin' }, 'list', 9],
|
||||
]);
|
||||
});
|
||||
|
||||
it('declares the shared response contracts', () => {
|
||||
const proto = PlacesLibraryController.prototype;
|
||||
const contract = (handler: unknown) => Reflect.getMetadata(RESPONSE_CONTRACT_KEY, handler as object) as unknown;
|
||||
expect(contract(proto.list)).toBe(placesLibraryPageResponseSchema);
|
||||
expect(contract(proto.tripPlace)).toBe(placesLibraryDetailResponseSchema);
|
||||
expect(contract(proto.savedPlace)).toBe(placesLibraryDetailResponseSchema);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* The pure halves of "All places": entry keys, the cursor, votes and how an
|
||||
* entry is put together from its rows.
|
||||
*/
|
||||
import type {
|
||||
LibraryCollectionPlaceRow,
|
||||
LibraryTripPlaceRow,
|
||||
} from '../../../../src/db/repositories/PlacesLibrary.repository';
|
||||
import {
|
||||
decodeLibraryCursor,
|
||||
encodeLibraryCursor,
|
||||
entryKey,
|
||||
entryOf,
|
||||
groupBy,
|
||||
ratingOf,
|
||||
rowsByAnchor,
|
||||
} from '../../../../src/nest/places-library/places-library.helpers';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const facts = {
|
||||
address: null,
|
||||
lat: 1,
|
||||
lng: 2,
|
||||
image_url: null,
|
||||
updated_at: '2026-11-01 10:00:00',
|
||||
description: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
category_id: 3,
|
||||
category_name: 'Food',
|
||||
category_color: '#f00',
|
||||
category_icon: null,
|
||||
};
|
||||
const trip: LibraryTripPlaceRow = {
|
||||
...facts,
|
||||
id: 10,
|
||||
trip_id: 5,
|
||||
name: 'Café',
|
||||
trip_title: 'Alps',
|
||||
trip_start: null,
|
||||
trip_end: null,
|
||||
trip_owner_id: 1,
|
||||
};
|
||||
const saved = (id: number, grouped: number | null, extra: Partial<LibraryCollectionPlaceRow> = {}) =>
|
||||
({
|
||||
...facts,
|
||||
id,
|
||||
collection_id: 4,
|
||||
collection_name: 'Food',
|
||||
status: 'odd-status',
|
||||
name: `Saved ${id}`,
|
||||
grouped_place_id: grouped,
|
||||
category_id: null,
|
||||
category_name: null,
|
||||
...extra,
|
||||
}) satisfies LibraryCollectionPlaceRow;
|
||||
|
||||
const access = { canEditTrip: () => true, canEditList: () => false };
|
||||
|
||||
describe('places-library helpers', () => {
|
||||
it('names an entry by its trip place, else by its saved place', () => {
|
||||
expect(entryKey(10)).toBe('trip:10');
|
||||
expect(entryKey(-4)).toBe('list:4');
|
||||
});
|
||||
|
||||
it('hands out a cursor that only its own sort reads back', () => {
|
||||
const cursor = encodeLibraryCursor('name', { anchor_key: -4, sort_name: 'café', sort_time: '2026' });
|
||||
expect(decodeLibraryCursor('name', cursor)).toEqual({ value: 'café', key: -4 });
|
||||
expect(decodeLibraryCursor('updated', cursor)).toBeNull();
|
||||
const byTime = encodeLibraryCursor('updated', { anchor_key: 3, sort_name: 'x', sort_time: '2026-01-01' });
|
||||
expect(decodeLibraryCursor('updated', byTime)).toEqual({ value: '2026-01-01', key: 3 });
|
||||
expect(decodeLibraryCursor('name', '%%%')).toBeNull();
|
||||
expect(decodeLibraryCursor('name', Buffer.from('{"a":1}').toString('base64url'))).toBeNull();
|
||||
});
|
||||
|
||||
it('sums the votes and finds the user’s own', () => {
|
||||
expect(ratingOf([], 1)).toEqual({ average: null, count: 0, mine: null });
|
||||
const rows = [
|
||||
{ target_id: 1, user_id: 1, rating: 5 },
|
||||
{ target_id: 1, user_id: 2, rating: 2 },
|
||||
];
|
||||
expect(ratingOf(rows, 1)).toEqual({ average: 3.5, count: 2, mine: 5 });
|
||||
expect(ratingOf(rows, 9)).toEqual({ average: 3.5, count: 2, mine: null });
|
||||
});
|
||||
|
||||
it('puts an entry together from its rows, the trip place leading', () => {
|
||||
const rows = rowsByAnchor([10, -7, -99, 42], [trip], [saved(6, 10, { image_url: '/u/6.jpg' }), saved(7, null)]);
|
||||
expect(rows.map((row) => row.anchor)).toEqual([10, -7]);
|
||||
const [first, second] = rows;
|
||||
if (!first || !second) throw new Error('expected two entries');
|
||||
const grouped = entryOf(first, access);
|
||||
expect(grouped).toMatchObject({
|
||||
key: 'trip:10',
|
||||
name: 'Café',
|
||||
category: { id: 3, name: 'Food', color: '#f00', icon: null },
|
||||
image_url: '/u/6.jpg',
|
||||
});
|
||||
expect(grouped.origins).toEqual([
|
||||
expect.objectContaining({ kind: 'trip', can_edit: true, read_only: false }),
|
||||
expect.objectContaining({ kind: 'list', collection_place_id: 6, status: 'idea', can_edit: false }),
|
||||
]);
|
||||
const alone = entryOf(second, access);
|
||||
expect(alone).toMatchObject({ key: 'list:7', name: 'Saved 7', category: null, image_url: null });
|
||||
});
|
||||
|
||||
it('groups rows by a numeric field in order', () => {
|
||||
const groups = groupBy([{ k: 1 }, { k: 2 }, { k: 1 }], (row) => row.k);
|
||||
expect([...groups.entries()]).toEqual([
|
||||
[1, [{ k: 1 }, { k: 1 }]],
|
||||
[2, [{ k: 2 }]],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* PlacesLibraryMcp (PLC-07/PLC-08): list_all_places and get_library_place over
|
||||
* the same service and checks as REST, with the addon gate and the scopes the
|
||||
* tools need. The suite takes its subject from the container over a snapshot
|
||||
* test db.
|
||||
*/
|
||||
import type { McpContext } from '../../../../src/nest-mcp';
|
||||
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
|
||||
import { AddonsService } from '../../../../src/nest/addons/addons.service';
|
||||
import { McpToolGuardsService } from '../../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
|
||||
import { PlacesLibraryMcp } from '../../../../src/nest/places-library/places-library.mcp';
|
||||
import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-library.module';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { expectedKeysByName, seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let orm: TestOrm;
|
||||
let mcp: PlacesLibraryMcp;
|
||||
let f: LibraryFixture;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [PlacesLibraryModule] });
|
||||
mcp = t.get(PlacesLibraryMcp);
|
||||
orm = await createTestOrm(db);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(db);
|
||||
orm.clear();
|
||||
vi.restoreAllMocks();
|
||||
f = await seedLibrary(orm);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await orm.close();
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const ctx = (userId: number) => ({ userId }) as McpContext;
|
||||
|
||||
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
|
||||
const text = result.content[0]?.text ?? '';
|
||||
return result.isError ? { error: text } : JSON.parse(text);
|
||||
}
|
||||
|
||||
const options = (name: string) => {
|
||||
const entry = getEntry(PlacesLibraryMcp as unknown as ClassRef, name);
|
||||
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
|
||||
return entry.options;
|
||||
};
|
||||
|
||||
describe('PlacesLibraryMcp', () => {
|
||||
it('PLIB-MCP-001: list_all_places pages through the user’s places as REST lists them', async () => {
|
||||
const page = read(await mcp.listAllPlaces({}, ctx(f.me.id)));
|
||||
expect(page.entries.map((entry: { key: string }) => entry.key)).toEqual(expectedKeysByName(f));
|
||||
expect(page.counts).toEqual({ all: 10, trip: 5, list: 7 });
|
||||
expect(read(await mcp.listAllPlaces({ kind: 'trip', trip_id: f.rome.id }, ctx(f.me.id))).entries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('PLIB-MCP-002: get_library_place reads one entry with what each origin keeps', async () => {
|
||||
const answer = read(await mcp.getLibraryPlace({ kind: 'list', id: f.saved.savedCafe.id }, ctx(f.me.id)));
|
||||
expect(answer.entry.key).toBe(`trip:${f.places.cafe.id}`);
|
||||
expect(answer.details.map((detail: { kind: string; notes: string }) => [detail.kind, detail.notes])).toEqual([
|
||||
['trip', 'Book a table'],
|
||||
['list', 'Try the cake'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('PLIB-MCP-003: refuses what REST refuses, as the service words it', async () => {
|
||||
await expect(mcp.getLibraryPlace({ kind: 'trip', id: f.places.hidden.id }, ctx(f.me.id))).rejects.toThrow(
|
||||
'Place not found',
|
||||
);
|
||||
await expect(mcp.listAllPlaces({ kind: 'list', trip_id: f.alps.id }, ctx(f.me.id))).rejects.toThrow(
|
||||
'Filter by a trip or by a list, not both',
|
||||
);
|
||||
});
|
||||
|
||||
it('PLIB-MCP-004: an admin may edit every trip place; the role is read for the check', async () => {
|
||||
const admin = vi.spyOn(t.get(McpToolGuardsService), 'isAdminUser').mockResolvedValue(true);
|
||||
const check = vi.spyOn(t.get(PermissionsService), 'checkPermission');
|
||||
await mcp.listAllPlaces({ trip_id: f.rome.id }, ctx(f.me.id));
|
||||
expect(admin).toHaveBeenCalledWith(f.me.id);
|
||||
expect(check).toHaveBeenCalledWith('place_edit', 'admin', null, f.me.id, true);
|
||||
});
|
||||
|
||||
it('PLIB-MCP-005: the tools are there only with Collections on, and for tokens that read lists and trips', async () => {
|
||||
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
|
||||
const gate = options('listAllPlaces').when;
|
||||
expect(await gate?.(ctx(1), mcp)).toBe(true);
|
||||
enabled.mockResolvedValue(false);
|
||||
expect(await gate?.(ctx(1), mcp)).toBe(false);
|
||||
|
||||
const allowed = (name: string, scopes: string[] | null) => {
|
||||
const access = options(name).access;
|
||||
return typeof access === 'function' ? access({ userId: 1, scopes } as McpContext) : access;
|
||||
};
|
||||
for (const name of ['listAllPlaces', 'getLibraryPlace']) {
|
||||
expect(allowed(name, ['collections:read', 'trips:read'])).toBe(true);
|
||||
expect(allowed(name, ['collections:read'])).toBe(false);
|
||||
expect(allowed(name, ['trips:read'])).toBe(false);
|
||||
expect(allowed(name, null)).toBe(true);
|
||||
expect(options(name).annotations).toMatchObject({ readOnlyHint: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* PlacesLibraryService (PLC-07/PLC-08) over the real repository on a migrated
|
||||
* test db: which places "All places" lists and which it leaves out, when a
|
||||
* saved place and a trip place are one entry, who may change what, the
|
||||
* filters, counts and pages, and one entry in detail. Only the trip
|
||||
* permission check is replaced, to deny 'place_edit' to trip members.
|
||||
*/
|
||||
import { Places } from '../../../../src/db/entities/Places.entity';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
|
||||
import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-library.module';
|
||||
import { PlacesLibraryService, type LibraryUser } from '../../../../src/nest/places-library/places-library.service';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { updateRows } from '../../../helpers/factories/rows';
|
||||
import { expectedKeysByName, seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
import type { PlacesLibraryEntry, PlacesLibraryPageResponse, PlacesLibraryQuery } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let orm: TestOrm;
|
||||
let library: PlacesLibraryService;
|
||||
let f: LibraryFixture;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [PlacesLibraryModule] });
|
||||
library = t.get(PlacesLibraryService);
|
||||
orm = await createTestOrm(db);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(db);
|
||||
orm.clear();
|
||||
vi.restoreAllMocks();
|
||||
// A trip's owner may edit its places, a member may not.
|
||||
vi.spyOn(t.get(PermissionsService), 'checkPermission').mockImplementation(
|
||||
async (_action, _role, tripOwner, userId) => tripOwner === userId,
|
||||
);
|
||||
f = await seedLibrary(orm);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await orm.close();
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const as = (id: number): LibraryUser => ({ id, role: 'user' });
|
||||
const keys = (page: PlacesLibraryPageResponse) => page.entries.map((entry) => entry.key);
|
||||
const entry = (page: PlacesLibraryPageResponse, key: string): PlacesLibraryEntry => {
|
||||
const found = page.entries.find((candidate) => candidate.key === key);
|
||||
if (!found) throw new Error(`no entry ${key}`);
|
||||
return found;
|
||||
};
|
||||
|
||||
async function refusal(promise: Promise<unknown>): Promise<{ status: number; message: string }> {
|
||||
try {
|
||||
await promise;
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(DomainError);
|
||||
const error = err as DomainError;
|
||||
return { status: error.getStatus(), message: error.publicMessage };
|
||||
}
|
||||
throw new Error('expected a refusal');
|
||||
}
|
||||
|
||||
describe('PlacesLibraryService.list', () => {
|
||||
it('PLIB-001: lists the normal places of every trip and the saved places of every list, nothing else', async () => {
|
||||
const page = await library.list(as(f.me.id), {});
|
||||
expect(keys(page)).toEqual(expectedKeysByName(f));
|
||||
const listed = new Set(keys(page));
|
||||
for (const left of [f.places.ridge, f.places.track, f.places.pump, f.places.hidden]) {
|
||||
expect(listed.has(`trip:${left.id}`)).toBe(false);
|
||||
}
|
||||
expect(listed.has(`list:${f.saved.secret.id}`)).toBe(false);
|
||||
expect(page).toMatchObject({ total: 10, counts: { all: 10, trip: 5, list: 7 }, next_cursor: null });
|
||||
});
|
||||
|
||||
it('PLIB-002: groups a saved place with the trip place it came from only when the two agree', async () => {
|
||||
const page = await library.list(as(f.me.id), {});
|
||||
const cafe = entry(page, `trip:${f.places.cafe.id}`);
|
||||
expect(cafe).toMatchObject({
|
||||
name: 'Café Central',
|
||||
address: 'Herrengasse 14, Wien',
|
||||
lat: 48.2104,
|
||||
lng: 16.3655,
|
||||
});
|
||||
expect(cafe.origins).toEqual([
|
||||
{
|
||||
kind: 'trip',
|
||||
trip_id: f.alps.id,
|
||||
trip_title: 'Alps',
|
||||
trip_start: '2026-07-01',
|
||||
trip_end: '2026-07-03',
|
||||
place_id: f.places.cafe.id,
|
||||
can_edit: true,
|
||||
read_only: false,
|
||||
},
|
||||
{
|
||||
kind: 'list',
|
||||
collection_id: f.lists.food.id,
|
||||
collection_name: 'Food',
|
||||
collection_place_id: f.saved.savedCafe.id,
|
||||
status: 'want',
|
||||
can_edit: true,
|
||||
},
|
||||
]);
|
||||
// The provider id alone is enough, whatever the copy is called.
|
||||
expect(entry(page, `trip:${f.places.museum.id}`).origins.map((origin) => origin.kind)).toEqual(['trip', 'list']);
|
||||
// A renamed copy, one with another provider id, one without a source and one from a trip out of reach stay apart.
|
||||
for (const apart of [f.saved.lunch, f.saved.conflicting, f.saved.namesake, f.saved.hiddenCopy]) {
|
||||
expect(entry(page, `list:${apart.id}`).origins).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('PLIB-003: says what the user may change: a viewer of a list and a member without place_edit read only', async () => {
|
||||
const page = await library.list(as(f.me.id), {});
|
||||
expect(entry(page, `list:${f.saved.pantheon.id}`).origins).toEqual([
|
||||
expect.objectContaining({ kind: 'list', collection_name: 'Rome sights', status: 'visited', can_edit: false }),
|
||||
]);
|
||||
expect(entry(page, `trip:${f.places.forum.id}`).origins).toEqual([
|
||||
expect.objectContaining({ kind: 'trip', trip_title: 'Rome', can_edit: false, read_only: true }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('PLIB-004: reads nothing of another user, and a stranger’s copy never groups with a trip out of reach', async () => {
|
||||
const page = await library.list(as(f.stranger.id), {});
|
||||
expect(keys(page).sort()).toEqual([`list:${f.saved.secret.id}`, `trip:${f.places.hidden.id}`].sort());
|
||||
expect(entry(page, `list:${f.saved.secret.id}`).origins).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('PLIB-005: narrows by origin, list, trip, status, category and text, counting for the tabs apart', async () => {
|
||||
const by = async (query: PlacesLibraryQuery) => keys(await library.list(as(f.me.id), query));
|
||||
expect(await by({ kind: 'trip' })).toEqual([
|
||||
`trip:${f.places.cafe.id}`,
|
||||
`trip:${f.places.camp.id}`,
|
||||
`trip:${f.places.forum.id}`,
|
||||
`trip:${f.places.hotel.id}`,
|
||||
`trip:${f.places.museum.id}`,
|
||||
]);
|
||||
// A grouped entry has a list origin, so it is one of the list's entries too.
|
||||
expect(await by({ collection_id: f.lists.food.id })).toEqual([
|
||||
`list:${f.saved.conflicting.id}`,
|
||||
`trip:${f.places.cafe.id}`,
|
||||
`list:${f.saved.hiddenCopy.id}`,
|
||||
`list:${f.saved.lunch.id}`,
|
||||
`list:${f.saved.namesake.id}`,
|
||||
`trip:${f.places.museum.id}`,
|
||||
]);
|
||||
expect(await by({ trip_id: f.rome.id })).toEqual([`trip:${f.places.forum.id}`]);
|
||||
expect(await by({ status: 'visited' })).toEqual([`list:${f.saved.pantheon.id}`]);
|
||||
expect(await by({ q: 'HERRENGASSE' })).toEqual([`trip:${f.places.cafe.id}`]);
|
||||
expect(await by({ q: '%' })).toEqual([]);
|
||||
// A list or trip out of reach answers like an empty one.
|
||||
expect(await by({ collection_id: f.lists.secrets.id })).toEqual([]);
|
||||
expect(await by({ trip_id: f.elsewhere.id })).toEqual([]);
|
||||
|
||||
const narrowed = await library.list(as(f.me.id), { kind: 'trip', q: 'c' });
|
||||
expect(narrowed.total).toBe(narrowed.entries.length);
|
||||
expect(narrowed.counts.all).toBeGreaterThanOrEqual(narrowed.total);
|
||||
});
|
||||
|
||||
it('PLIB-006: filters by category on either side', async () => {
|
||||
await updateRows(orm, Places, { id: f.places.forum.id }, { category: null });
|
||||
const all = await library.list(as(f.me.id), {});
|
||||
const category = entry(all, `trip:${f.places.cafe.id}`).category;
|
||||
expect(category).not.toBeNull();
|
||||
const page = await library.list(as(f.me.id), { category_id: category?.id });
|
||||
expect(keys(page)).not.toContain(`trip:${f.places.forum.id}`);
|
||||
expect(keys(page)).toContain(`trip:${f.places.cafe.id}`);
|
||||
});
|
||||
|
||||
it('PLIB-007: refuses a list filter together with a trip filter', async () => {
|
||||
expect(await refusal(library.list(as(f.me.id), { kind: 'list', trip_id: f.alps.id }))).toEqual({
|
||||
status: 400,
|
||||
message: 'Filter by a trip or by a list, not both',
|
||||
});
|
||||
expect(await refusal(library.list(as(f.me.id), { status: 'want', kind: 'trip' }))).toMatchObject({ status: 400 });
|
||||
});
|
||||
|
||||
it('PLIB-008: pages through every entry once, by name and by last change', async () => {
|
||||
for (const sort of ['name', 'updated'] as const) {
|
||||
const seen: string[] = [];
|
||||
let cursor: string | undefined;
|
||||
for (let round = 0; round < 10; round++) {
|
||||
const page = await library.list(as(f.me.id), { sort, limit: 3, ...(cursor ? { cursor } : {}) });
|
||||
seen.push(...keys(page));
|
||||
if (!page.next_cursor) break;
|
||||
cursor = page.next_cursor;
|
||||
}
|
||||
expect(seen).toHaveLength(10);
|
||||
expect(new Set(seen)).toEqual(new Set(expectedKeysByName(f)));
|
||||
}
|
||||
});
|
||||
|
||||
it('PLIB-009: sorts by the last change, newest first', async () => {
|
||||
await updateRows(orm, Places, { id: f.places.forum.id }, { updated_at: '2030-01-01 00:00:00' });
|
||||
const page = await library.list(as(f.me.id), { sort: 'updated', limit: 1 });
|
||||
expect(keys(page)).toEqual([`trip:${f.places.forum.id}`]);
|
||||
expect(page.next_cursor).not.toBeNull();
|
||||
});
|
||||
|
||||
it('PLIB-010: refuses a cursor it did not hand out, or one of the other sort', async () => {
|
||||
const page = await library.list(as(f.me.id), { limit: 2 });
|
||||
const invalid = { status: 400, message: 'Invalid cursor: pass the next_cursor of the page before' };
|
||||
expect(await refusal(library.list(as(f.me.id), { cursor: 'nonsense' }))).toEqual(invalid);
|
||||
expect(await refusal(library.list(as(f.me.id), { sort: 'updated', cursor: page.next_cursor ?? '' }))).toEqual(
|
||||
invalid,
|
||||
);
|
||||
});
|
||||
|
||||
it('PLIB-011: ends a page early past maxChars, and the cursor goes on after its last entry', async () => {
|
||||
const first = await library.list(as(f.me.id), {}, { maxChars: 10 });
|
||||
expect(first.entries).toHaveLength(1);
|
||||
const second = await library.list(as(f.me.id), { cursor: first.next_cursor ?? '' });
|
||||
expect([...keys(first), ...keys(second)]).toEqual(expectedKeysByName(f));
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlacesLibraryService.detail', () => {
|
||||
it('PLIB-020: answers a trip place with what the trip and each list keep of it', async () => {
|
||||
const answer = await library.detail(as(f.me.id), 'trip', f.places.cafe.id);
|
||||
expect(answer.entry.key).toBe(`trip:${f.places.cafe.id}`);
|
||||
expect(answer.details).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: 'trip',
|
||||
place_id: f.places.cafe.id,
|
||||
info: expect.objectContaining({ name: 'Café Central', description: 'A coffee house' }),
|
||||
notes: 'Book a table',
|
||||
rating: { average: 3, count: 2, mine: 4 },
|
||||
days: [{ day_id: f.day1.id, day_number: 1, date: '2026-07-01', title: null, time: '09:00', end_time: null }],
|
||||
has_accommodation: false,
|
||||
has_reservation: false,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: 'list',
|
||||
collection_place_id: f.saved.savedCafe.id,
|
||||
info: expect.objectContaining({ name: ' café central ' }),
|
||||
notes: 'Try the cake',
|
||||
labels: [{ id: f.label.id, name: 'Must', color: '#ff0000' }],
|
||||
rating: { average: 5, count: 1, mine: 5 },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it('PLIB-021: opens the same entry from the saved place it groups', async () => {
|
||||
const answer = await library.detail(as(f.me.id), 'list', f.saved.savedCafe.id);
|
||||
expect(answer.entry.key).toBe(`trip:${f.places.cafe.id}`);
|
||||
expect(answer.details.map((detail) => detail.kind)).toEqual(['trip', 'list']);
|
||||
});
|
||||
|
||||
it('PLIB-022: says whether a stay or a booking uses a trip place', async () => {
|
||||
const camp = await library.detail(as(f.me.id), 'trip', f.places.camp.id);
|
||||
expect(camp.details[0]).toMatchObject({ has_accommodation: true, has_reservation: false, days: [] });
|
||||
const hotel = await library.detail(as(f.me.id), 'trip', f.places.hotel.id);
|
||||
expect(hotel.details[0]).toMatchObject({ has_accommodation: false, has_reservation: true });
|
||||
});
|
||||
|
||||
it('PLIB-023: a place of a trip or list out of reach, or one it leaves out, is not found', async () => {
|
||||
const notFound = { status: 404, message: 'Place not found' };
|
||||
expect(await refusal(library.detail(as(f.me.id), 'trip', f.places.hidden.id))).toEqual(notFound);
|
||||
expect(await refusal(library.detail(as(f.me.id), 'trip', f.places.ridge.id))).toEqual(notFound);
|
||||
expect(await refusal(library.detail(as(f.me.id), 'trip', f.places.pump.id))).toEqual(notFound);
|
||||
expect(await refusal(library.detail(as(f.me.id), 'list', f.saved.secret.id))).toEqual(notFound);
|
||||
expect(await refusal(library.detail(as(f.me.id), 'list', 999_999))).toEqual(notFound);
|
||||
});
|
||||
|
||||
it('PLIB-024: a saved place apart from any trip place is an entry of its own', async () => {
|
||||
const answer = await library.detail(as(f.me.id), 'list', f.saved.pantheon.id);
|
||||
expect(answer.entry.key).toBe(`list:${f.saved.pantheon.id}`);
|
||||
expect(answer.details).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: 'list',
|
||||
notes: null,
|
||||
labels: [],
|
||||
rating: { average: null, count: 0, mine: null },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -183,6 +183,7 @@ export default defineConfig({
|
||||
// that it is off the 80 catch-all, where a new domain could shed twenty
|
||||
// points without anything noticing.
|
||||
'src/nest/place-shadow/**/*.ts': { statements: 90, branches: 80, functions: 90, lines: 95 },
|
||||
'src/nest/places-library/**/*.ts': { statements: 80, branches: 80, functions: 80, lines: 80 },
|
||||
'src/nest/places/**/*.ts': { statements: 91, branches: 82, functions: 96, lines: 94 },
|
||||
'src/nest/platform/**/*.ts': { statements: 99, branches: 99, functions: 99, lines: 99 },
|
||||
'src/nest/plugins/**/*.ts': { statements: 86, branches: 81, functions: 78, lines: 89 },
|
||||
|
||||
Reference in New Issue
Block a user