Files
TREK/server/src/db/repositories/PlacesLibrary.repository.ts
T
Maurice 0ecca2b46c 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.
2026-11-29 14:57:10 +01:00

595 lines
21 KiB
TypeScript

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) };
}
}