diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index ec375a812..540547485 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -208,7 +208,7 @@ "desktop": [ "src/components/Planner/DayDetailPanel.tsx", "src/components/Planner/DayPlanSidebar.tsx", - "src/components/Planner/PlaceInspector.tsx", + "src/components/Planner/PlaceLinkedBookingCard.tsx", "src/components/Planner/ReservationModal.tsx", "src/components/Planner/ReservationsPanel.tsx", "src/components/Planner/TransportModal.tsx", diff --git a/client/src/components/Collections/usePlaceEdit.ts b/client/src/components/Collections/usePlaceEdit.ts index 6e5ca2045..6422a9947 100644 --- a/client/src/components/Collections/usePlaceEdit.ts +++ b/client/src/components/Collections/usePlaceEdit.ts @@ -100,7 +100,7 @@ export function usePlaceEdit({ const [draft, setDraft] = useState(null); const [saving, setSaving] = useState(false); - const target = targets[0] ?? null; + const target: EditTarget | null = targets[0] ?? null; const start = () => { if (!target) return; diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index bca35b502..e1793a66c 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -8,11 +8,11 @@ "src/nest/atlas/atlas.service.ts": 1166, "src/nest/auth/auth.service.ts": 1115, "src/nest/budget/budget.service.ts": 1607, - "src/nest/collections/collections.service.ts": 1396, + "src/nest/collections/collections.service.ts": 1386, "src/nest/doc-sync/doc-sync.service.ts": 1060, "src/nest/doc-sync/providers/synology-drive.client.ts": 1160, "src/nest/journey/journey-domain.service.ts": 1659, - "src/nest/places/places.service.ts": 1546, + "src/nest/places/places.service.ts": 1517, "src/nest/plugins/plugin-runtime.service.ts": 1458, "src/nest/plugins/runtime/plugin-sdk.ts": 1093, "src/nest/reservations/reservations.service.ts": 1163, diff --git a/server/src/db/repositories/PlacesLibrary.repository.ts b/server/src/db/repositories/PlacesLibrary.repository.ts index 371e5eb94..f17f309c8 100644 --- a/server/src/db/repositories/PlacesLibrary.repository.ts +++ b/server/src/db/repositories/PlacesLibrary.repository.ts @@ -1,6 +1,5 @@ import { castIntegerKysely, 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'; @@ -122,22 +121,6 @@ interface LibraryTagMatch { reach: LibraryArms; } -/** A tag of a trip on one of its places (`place_tags`). */ -export interface LibraryTripTagRow { - place_id: number; - id: number; - name: string; - color: string | null; -} - -/** A tag a trip or a list owns, with the trip or list it belongs to. */ -export interface LibraryOwnedTagRow { - owner_id: number; - id: number; - name: string; - color: string | null; -} - /** Where an entry stands in the list's order: its sort value and its key. */ export interface LibraryPosition { value: string; @@ -235,55 +218,6 @@ export interface LibraryIdentityRow { category_icon: string | 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; - /** Who voted, as the list's votes name them, and their stored picture. */ - username?: string; - avatar?: string | null; - /** When the vote was last changed (cast, when never changed since), and its row, to tell which of a person's votes came last. */ - changed_at?: string | null; - id?: number; -} - -/** One of a person's votes: on a trip place (from_list 0) or a saved place. */ -export interface LibraryOwnVoteRow { - from_list: number; - use_id: number; - rating: number; - /** When the person last changed the vote, or cast it when they never changed it. */ - changed_at: string | null; - id: 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 @@ -782,43 +716,6 @@ export class PlacesLibraryRepository { return row ? Number(row.anchor_key) : null; } - /** The tags on the trip places (PLC-21), by name. */ - async tripPlaceTags(placeIds: number[]): Promise { - const rows = await this.db() - .selectFrom('place_tags as pt') - .innerJoin('tags as tg', 'tg.id', 'pt.tag_id') - .select(['pt.place_id', 'tg.id', 'tg.name', 'tg.color']) - .where('pt.place_id', 'in', idsOrNone(placeIds)) - .orderBy('tg.name') - .orderBy('tg.id') - .execute(); - // A legacy row can hold a number as its name, so it is read as text. - return rows.map((row) => ({ ...row, name: String(row.name) })); - } - - /** Every tag the trips own (PLC-21), by name. */ - async tripTags(tripIds: number[]): Promise { - const rows = await this.db() - .selectFrom('tags as tg') - .select(['tg.trip_id as owner_id', 'tg.id', 'tg.name', 'tg.color']) - .where('tg.trip_id', 'in', idsOrNone(tripIds)) - .orderBy('tg.name') - .orderBy('tg.id') - .execute(); - return rows.map((row) => ({ ...row, owner_id: Number(row.owner_id), name: String(row.name) })); - } - - /** Every label of the lists (PLC-21: a list's tags), in each list's label order. */ - async listLabels(collectionIds: number[]): Promise { - return await this.db() - .selectFrom('collection_labels as lb') - .select(['lb.collection_id as owner_id', 'lb.id', 'lb.name', 'lb.color']) - .where('lb.collection_id', 'in', idsOrNone(collectionIds)) - .orderBy('lb.sort_order') - .orderBy('lb.id') - .execute(); - } - /** The trip places with their trip and category, for the entries of a page. */ async tripPlaces(placeIds: number[], tripIds: number[]): Promise { return await this.db() @@ -917,187 +814,6 @@ export class PlacesLibraryRepository { .where('up.id', 'in', idsOrNone(ids)) .execute(); } - - /** - * 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 { - 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 { - return await this.db() - .selectFrom('places') - .select(['id', 'notes']) - .where('id', 'in', idsOrNone(placeIds)) - .execute(); - } - - async savedPlaceNotes(collectionPlaceIds: number[]): Promise { - 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 { - 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(); - } - - /** The votes on the saved places, each with who cast it (their name and stored picture). */ - async savedPlaceRatings(collectionPlaceIds: number[]): Promise { - return await this.db() - .selectFrom('collection_place_ratings as cr') - .innerJoin('users as vu', 'vu.id', 'cr.user_id') - .select([ - 'cr.collection_place_id as target_id', - 'cr.user_id', - 'cr.rating', - (eb) => eb.fn.coalesce('cr.updated_at', 'cr.created_at').as('changed_at'), - 'cr.id', - 'vu.username', - 'vu.avatar', - ]) - .where('cr.collection_place_id', 'in', idsOrNone(collectionPlaceIds)) - .execute(); - } - - /** The votes on the trip places, each with who cast it (their name and stored picture). */ - async tripPlaceRatings(placeIds: number[]): Promise { - return await this.db() - .selectFrom('place_ratings as pr') - .innerJoin('users as vu', 'vu.id', 'pr.user_id') - .select([ - 'pr.place_id as target_id', - 'pr.user_id', - 'pr.rating', - (eb) => eb.fn.coalesce('pr.updated_at', 'pr.created_at').as('changed_at'), - 'pr.id', - 'vu.username', - 'vu.avatar', - ]) - .where('pr.place_id', 'in', idsOrNone(placeIds)) - .execute(); - } - - /** Every vote of the user, on trip places and on saved places, in row order. */ - async votesOfUser(userId: number): Promise { - const db = this.db(); - const trips = await db - .selectFrom('place_ratings') - .select([ - 'place_id as use_id', - 'rating', - (eb) => eb.fn.coalesce('updated_at', 'created_at').as('changed_at'), - 'id', - ]) - .where('user_id', '=', userId) - .orderBy('id') - .execute(); - const saved = await db - .selectFrom('collection_place_ratings') - .select([ - 'collection_place_id as use_id', - 'rating', - (eb) => eb.fn.coalesce('updated_at', 'created_at').as('changed_at'), - 'id', - ]) - .where('user_id', '=', userId) - .orderBy('id') - .execute(); - return [...trips.map((row) => ({ ...row, from_list: 0 })), ...saved.map((row) => ({ ...row, from_list: 1 }))]; - } - - /** Up to `limit` of the people with a vote anywhere, by id, after the id `after`. */ - async voterIds(after: number, limit: number): Promise { - const db = this.db(); - const trips = await db - .selectFrom('place_ratings') - .select('user_id') - .distinct() - .where('user_id', '>', after) - .orderBy('user_id') - .limit(limit) - .execute(); - const saved = await db - .selectFrom('collection_place_ratings') - .select('user_id') - .distinct() - .where('user_id', '>', after) - .orderBy('user_id') - .limit(limit) - .execute(); - const ids = new Set([...trips, ...saved].map((row) => Number(row.user_id))); - return [...ids].sort((a, b) => a - b).slice(0, limit); - } - - /** The days each place is planned on, in day order, with the time set there. */ - async plannedDays(placeIds: number[]): Promise { - 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) }; - } } /** A use as the union reads it, its numbers as numbers whatever the engine hands back. */ diff --git a/server/src/db/repositories/PlacesLibraryDetails.repository.ts b/server/src/db/repositories/PlacesLibraryDetails.repository.ts new file mode 100644 index 000000000..807ba3fbf --- /dev/null +++ b/server/src/db/repositories/PlacesLibraryDetails.repository.ts @@ -0,0 +1,323 @@ +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 type { Kysely } from 'kysely'; + +type LibraryDetailsDB = Pick< + DB, + | 'places' + | 'tours' + | 'day_accommodations' + | 'reservations' + | 'collection_places' + | 'collections' + | 'collection_members' + | 'collection_place_labels' + | 'collection_labels' + | 'collection_place_ratings' + | 'place_ratings' + | 'day_assignments' + | 'days' + | 'tags' + | 'place_tags' + | 'users' +>; + +/** No row has the id 0: an empty set of ids reads as this one, so a statement keeps its shape and matches nothing. */ +const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]); + +/** A tag of a trip on one of its places (`place_tags`). */ +export interface LibraryTripTagRow { + place_id: number; + id: number; + name: string; + color: string | null; +} +/** A tag a trip or a list owns, with the trip or list it belongs to. */ +export interface LibraryOwnedTagRow { + owner_id: number; + id: number; + name: string; + color: string | 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; + /** Who voted, as the list's votes name them, and their stored picture. */ + username?: string; + avatar?: string | null; + /** When the vote was last changed (cast, when never changed since), and its row, to tell which of a person's votes came last. */ + changed_at?: string | null; + id?: number; +} +/** One of a person's votes: on a trip place (from_list 0) or a saved place. */ +export interface LibraryOwnVoteRow { + from_list: number; + use_id: number; + rating: number; + /** When the person last changed the vote, or cast it when they never changed it. */ + changed_at: string | null; + id: 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; +} + +/** + * What one entry of All places keeps beside its facts, read for the uses the + * caller already found (PlacesLibraryRepository): the tags of its trips and + * lists, the notes, the votes, the planned days and the bookings, and the + * reader's role on its lists. Not bound to an entity, provided by the + * places-library module over the context-resolving EntityManager like + * PlacesLibraryRepository. Read only; the ids every method takes are the + * caller's own access-checked ones. + */ +export class PlacesLibraryDetailsRepository { + constructor(private readonly em: EntityManager) {} + + /** The request's EntityManager, which throws outside a request context like every repository. */ + private db(): Kysely { + return (this.em.getContext() as SqlEntityManager).getKysely(); + } + + /** The tags on the trip places (PLC-21), by name. */ + async tripPlaceTags(placeIds: number[]): Promise { + const rows = await this.db() + .selectFrom('place_tags as pt') + .innerJoin('tags as tg', 'tg.id', 'pt.tag_id') + .select(['pt.place_id', 'tg.id', 'tg.name', 'tg.color']) + .where('pt.place_id', 'in', idsOrNone(placeIds)) + .orderBy('tg.name') + .orderBy('tg.id') + .execute(); + // A legacy row can hold a number as its name, so it is read as text. + return rows.map((row) => ({ ...row, name: String(row.name) })); + } + + /** Every tag the trips own (PLC-21), by name. */ + async tripTags(tripIds: number[]): Promise { + const rows = await this.db() + .selectFrom('tags as tg') + .select(['tg.trip_id as owner_id', 'tg.id', 'tg.name', 'tg.color']) + .where('tg.trip_id', 'in', idsOrNone(tripIds)) + .orderBy('tg.name') + .orderBy('tg.id') + .execute(); + return rows.map((row) => ({ ...row, owner_id: Number(row.owner_id), name: String(row.name) })); + } + + /** Every label of the lists (PLC-21: a list's tags), in each list's label order. */ + async listLabels(collectionIds: number[]): Promise { + return await this.db() + .selectFrom('collection_labels as lb') + .select(['lb.collection_id as owner_id', 'lb.id', 'lb.name', 'lb.color']) + .where('lb.collection_id', 'in', idsOrNone(collectionIds)) + .orderBy('lb.sort_order') + .orderBy('lb.id') + .execute(); + } + + /** + * 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 { + 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 { + return await this.db() + .selectFrom('places') + .select(['id', 'notes']) + .where('id', 'in', idsOrNone(placeIds)) + .execute(); + } + + async savedPlaceNotes(collectionPlaceIds: number[]): Promise { + 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 { + 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(); + } + + /** The votes on the saved places, each with who cast it (their name and stored picture). */ + async savedPlaceRatings(collectionPlaceIds: number[]): Promise { + return await this.db() + .selectFrom('collection_place_ratings as cr') + .innerJoin('users as vu', 'vu.id', 'cr.user_id') + .select([ + 'cr.collection_place_id as target_id', + 'cr.user_id', + 'cr.rating', + (eb) => eb.fn.coalesce('cr.updated_at', 'cr.created_at').as('changed_at'), + 'cr.id', + 'vu.username', + 'vu.avatar', + ]) + .where('cr.collection_place_id', 'in', idsOrNone(collectionPlaceIds)) + .execute(); + } + + /** The votes on the trip places, each with who cast it (their name and stored picture). */ + async tripPlaceRatings(placeIds: number[]): Promise { + return await this.db() + .selectFrom('place_ratings as pr') + .innerJoin('users as vu', 'vu.id', 'pr.user_id') + .select([ + 'pr.place_id as target_id', + 'pr.user_id', + 'pr.rating', + (eb) => eb.fn.coalesce('pr.updated_at', 'pr.created_at').as('changed_at'), + 'pr.id', + 'vu.username', + 'vu.avatar', + ]) + .where('pr.place_id', 'in', idsOrNone(placeIds)) + .execute(); + } + + /** Every vote of the user, on trip places and on saved places, in row order. */ + async votesOfUser(userId: number): Promise { + const db = this.db(); + const trips = await db + .selectFrom('place_ratings') + .select([ + 'place_id as use_id', + 'rating', + (eb) => eb.fn.coalesce('updated_at', 'created_at').as('changed_at'), + 'id', + ]) + .where('user_id', '=', userId) + .orderBy('id') + .execute(); + const saved = await db + .selectFrom('collection_place_ratings') + .select([ + 'collection_place_id as use_id', + 'rating', + (eb) => eb.fn.coalesce('updated_at', 'created_at').as('changed_at'), + 'id', + ]) + .where('user_id', '=', userId) + .orderBy('id') + .execute(); + return [...trips.map((row) => ({ ...row, from_list: 0 })), ...saved.map((row) => ({ ...row, from_list: 1 }))]; + } + + /** Up to `limit` of the people with a vote anywhere, by id, after the id `after`. */ + async voterIds(after: number, limit: number): Promise { + const db = this.db(); + const trips = await db + .selectFrom('place_ratings') + .select('user_id') + .distinct() + .where('user_id', '>', after) + .orderBy('user_id') + .limit(limit) + .execute(); + const saved = await db + .selectFrom('collection_place_ratings') + .select('user_id') + .distinct() + .where('user_id', '>', after) + .orderBy('user_id') + .limit(limit) + .execute(); + const ids = new Set([...trips, ...saved].map((row) => Number(row.user_id))); + return [...ids].sort((a, b) => a - b).slice(0, limit); + } + + /** The days each place is planned on, in day order, with the time set there. */ + async plannedDays(placeIds: number[]): Promise { + 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) }; + } +} diff --git a/server/src/nest/places-library/library-tags.helpers.ts b/server/src/nest/places-library/library-tags.helpers.ts index 39d2e4140..bbc871c5c 100644 --- a/server/src/nest/places-library/library-tags.helpers.ts +++ b/server/src/nest/places-library/library-tags.helpers.ts @@ -1,4 +1,4 @@ -import type { LibraryOwnedTagRow, LibraryTripTagRow } from '../../db/repositories/PlacesLibrary.repository'; +import type { LibraryOwnedTagRow, LibraryTripTagRow } from '../../db/repositories/PlacesLibraryDetails.repository'; import type { EntryRows } from './places-library.helpers'; import type { PlacesLibraryEntryTag, PlacesLibraryTag } from '@trek/shared'; diff --git a/server/src/nest/places-library/place-votes.helpers.ts b/server/src/nest/places-library/place-votes.helpers.ts index acc280775..ab20e7039 100644 --- a/server/src/nest/places-library/place-votes.helpers.ts +++ b/server/src/nest/places-library/place-votes.helpers.ts @@ -1,4 +1,5 @@ -import type { LibraryOwnVoteRow, LibraryUseRow } from '../../db/repositories/PlacesLibrary.repository'; +import type { LibraryUseRow } from '../../db/repositories/PlacesLibrary.repository'; +import type { LibraryOwnVoteRow } from '../../db/repositories/PlacesLibraryDetails.repository'; import { castAfter, type EntryRows } from './places-library.helpers'; /** The copies of a place a vote lands on: trip places with their trip, and saved places. */ diff --git a/server/src/nest/places-library/place-votes.service.ts b/server/src/nest/places-library/place-votes.service.ts index b23adcf2a..63052b00a 100644 --- a/server/src/nest/places-library/place-votes.service.ts +++ b/server/src/nest/places-library/place-votes.service.ts @@ -1,6 +1,6 @@ import { ADDON_IDS } from '../../addons'; import type { PlaceWithTagsRow } from '../../db/repositories/Places.repository'; -import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository'; +import { PlacesLibraryDetailsRepository } from '../../db/repositories/PlacesLibraryDetails.repository'; import { AddonsService } from '../addons/addons.service'; import { logError } from '../audit/audit-log.logger'; import { CollectionsService } from '../collections/collections.service'; @@ -64,7 +64,7 @@ export class PlaceVotesService implements OnModuleInit { private readonly collections: CollectionsService, private readonly places: PlacesService, private readonly uow: UnitOfWork, - private readonly repo: PlacesLibraryRepository, + private readonly details: PlacesLibraryDetailsRepository, private readonly addons: AddonsService, private readonly membership: TripMembershipService, ) {} @@ -180,7 +180,7 @@ export class PlaceVotesService implements OnModuleInit { /** Up to `limit` people with a vote anywhere, by id, after `after`: the pages of carryOver's pass. */ async voters(after: number, limit: number): Promise { - return this.repo.voterIds(after, limit); + return this.details.voterIds(after, limit); } /** @@ -231,7 +231,7 @@ export class PlaceVotesService implements OnModuleInit { return this.uow.transactional(async () => { const reach = await this.library.reach(userId); const uses = await this.library.usesOf(reach, null); - const carried = votesToCarry(uses, await this.repo.votesOfUser(userId)); + const carried = votesToCarry(uses, await this.details.votesOfUser(userId)); if (carried.length === 0) return []; const anchorOf = new Map(uses.map((use) => [`${use.from_list}:${use.use_id}`, use.anchor_key])); const anchors = new Set(carried.map((vote) => anchorOf.get(`${vote.fromList}:${vote.useId}`) ?? 0)); diff --git a/server/src/nest/places-library/places-library.helpers.ts b/server/src/nest/places-library/places-library.helpers.ts index 5f8ac0882..1f99adf67 100644 --- a/server/src/nest/places-library/places-library.helpers.ts +++ b/server/src/nest/places-library/places-library.helpers.ts @@ -7,11 +7,11 @@ import { type LibraryCollectionPlaceRow, type LibraryIdentityRow, type LibraryPosition, - type LibraryRatingRow, type LibrarySort, type LibraryTripPlaceRow, type LibraryUseRow, } from '../../db/repositories/PlacesLibrary.repository'; +import type { LibraryRatingRow } from '../../db/repositories/PlacesLibraryDetails.repository'; import { avatarUrl } from '../common/avatarUrl'; import { collectionStatusSchema, diff --git a/server/src/nest/places-library/places-library.module.ts b/server/src/nest/places-library/places-library.module.ts index c3c9eaedf..e755c328a 100644 --- a/server/src/nest/places-library/places-library.module.ts +++ b/server/src/nest/places-library/places-library.module.ts @@ -4,6 +4,7 @@ import { UserPlaceMerges } from '../../db/entities/UserPlaceMerges.entity'; import { UserPlaces } from '../../db/entities/UserPlaces.entity'; import { PlaceVisitContextRepository } from '../../db/repositories/PlaceVisitContext.repository'; import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository'; +import { PlacesLibraryDetailsRepository } from '../../db/repositories/PlacesLibraryDetails.repository'; import { AddonsModule } from '../addons/addons.module'; import { CollectionsModule } from '../collections/collections.module'; import { McpSharedModule } from '../mcp-shared/mcp-shared.module'; @@ -51,6 +52,11 @@ import { Module } from '@nestjs/common'; useFactory: (em: EntityManager) => new PlacesLibraryRepository(em), inject: [EntityManager], }, + { + provide: PlacesLibraryDetailsRepository, + useFactory: (em: EntityManager) => new PlacesLibraryDetailsRepository(em), + inject: [EntityManager], + }, { provide: PlaceVisitContextRepository, useFactory: (em: EntityManager) => new PlaceVisitContextRepository(em), @@ -66,6 +72,12 @@ import { Module } from '@nestjs/common'; PlaceIdentitiesPruneJob, ], // The visits and media (PlaceVisitsModule) and the votes (PlaceVotesModule) of All places, same domain, read through these. - exports: [PlacesLibraryService, PlaceVisitsReaderService, PlaceVisitContextRepository, PlacesLibraryRepository], + exports: [ + PlacesLibraryService, + PlaceVisitsReaderService, + PlaceVisitContextRepository, + PlacesLibraryRepository, + PlacesLibraryDetailsRepository, + ], }) export class PlacesLibraryModule {} diff --git a/server/src/nest/places-library/places-library.service.ts b/server/src/nest/places-library/places-library.service.ts index 39006f7e5..f7e8f9a8c 100644 --- a/server/src/nest/places-library/places-library.service.ts +++ b/server/src/nest/places-library/places-library.service.ts @@ -7,6 +7,7 @@ import { type LibraryTripPlaceRow, type LibraryUseRow, } from '../../db/repositories/PlacesLibrary.repository'; +import { PlacesLibraryDetailsRepository } from '../../db/repositories/PlacesLibraryDetails.repository'; import { CollectionsService } from '../collections/collections.service'; import { badRequest, notFound } from '../common/domain-error'; import { PermissionsService } from '../permissions/permissions.service'; @@ -101,6 +102,7 @@ function armsOfReach(reach: LibraryReach): LibraryArms { export class PlacesLibraryService { constructor( private readonly repo: PlacesLibraryRepository, + private readonly kept: PlacesLibraryDetailsRepository, // what each entry keeps beside its facts private readonly collections: CollectionsService, private readonly membership: TripMembershipService, private readonly permissions: PermissionsService, @@ -256,11 +258,11 @@ export class PlacesLibraryService { const placeIds = rows.flatMap((row) => row.trips.map((trip) => trip.id)); const savedIds = rows.flatMap((row) => row.saved.map((saved) => saved.id)); const onTrips = groupBy( - await readInChunks(placeIds, (chunk) => this.repo.tripPlaceRatings(chunk)), + await readInChunks(placeIds, (chunk) => this.kept.tripPlaceRatings(chunk)), (vote) => vote.target_id, ); const onLists = groupBy( - await readInChunks(savedIds, (chunk) => this.repo.savedPlaceRatings(chunk)), + await readInChunks(savedIds, (chunk) => this.kept.savedPlaceRatings(chunk)), (vote) => vote.target_id, ); return rows.map((row) => @@ -278,8 +280,8 @@ export class PlacesLibraryService { private async tagsOf(rows: readonly EntryRows[]): Promise { const placeIds = rows.flatMap((row) => row.trips.map((trip) => trip.id)); const savedIds = rows.flatMap((row) => row.saved.map((saved) => saved.id)); - const tripTags = await readInChunks(placeIds, (chunk) => this.repo.tripPlaceTags(chunk)); - const labels = await readInChunks(savedIds, (chunk) => this.repo.savedPlaceLabels(chunk)); + const tripTags = await readInChunks(placeIds, (chunk) => this.kept.tripPlaceTags(chunk)); + const labels = await readInChunks(savedIds, (chunk) => this.kept.savedPlaceLabels(chunk)); return entryTagsOf(rows, tripTags, labels); } @@ -301,7 +303,7 @@ export class PlacesLibraryService { saved: readonly LibraryCollectionPlaceRow[], ): Promise { const listIds = [...new Set(saved.map((row) => row.collection_id))]; - const roles = listIds.length > 0 ? await this.repo.collectionRoles(user.id, listIds) : []; + const roles = listIds.length > 0 ? await this.kept.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) @@ -325,12 +327,12 @@ export class PlacesLibraryService { const details: PlacesLibraryDetail[] = []; if (rows.trips.length > 0) { const placeIds = rows.trips.map((row) => row.id); - const notes = new Map((await this.repo.tripPlaceNotes(placeIds)).map((row) => [row.id, row.notes])); - const ratings = groupBy(await this.repo.tripPlaceRatings(placeIds), (row) => row.target_id); - const days = groupBy(await this.repo.plannedDays(placeIds), (row) => row.place_id); - const booked = await this.repo.bookedPlaces(placeIds); - const tags = groupBy(await this.repo.tripPlaceTags(placeIds), (row) => row.place_id); - const tripTags = tagsByOwner(await this.repo.tripTags([...new Set(rows.trips.map((row) => row.trip_id))])); + const notes = new Map((await this.kept.tripPlaceNotes(placeIds)).map((row) => [row.id, row.notes])); + const ratings = groupBy(await this.kept.tripPlaceRatings(placeIds), (row) => row.target_id); + const days = groupBy(await this.kept.plannedDays(placeIds), (row) => row.place_id); + const booked = await this.kept.bookedPlaces(placeIds); + const tags = groupBy(await this.kept.tripPlaceTags(placeIds), (row) => row.place_id); + const tripTags = tagsByOwner(await this.kept.tripTags([...new Set(rows.trips.map((row) => row.trip_id))])); for (const row of rows.trips) { const assigned = (tags.get(row.id) ?? []).map(tagOf); details.push({ @@ -357,11 +359,11 @@ export class PlacesLibraryService { } 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); + const notes = new Map((await this.kept.savedPlaceNotes(savedIds)).map((row) => [row.id, row.notes])); + const labels = groupBy(await this.kept.savedPlaceLabels(savedIds), (row) => row.collection_place_id); + const ratings = groupBy(await this.kept.savedPlaceRatings(savedIds), (row) => row.target_id); const listTags = tagsByOwner( - await this.repo.listLabels([...new Set(rows.saved.map((row) => row.collection_id))]), + await this.kept.listLabels([...new Set(rows.saved.map((row) => row.collection_id))]), ); for (const row of rows.saved) { const assigned = (labels.get(row.id) ?? []).map(tagOf); diff --git a/server/tests/e2e/place-votes.e2e.test.ts b/server/tests/e2e/place-votes.e2e.test.ts index 524485085..829dda061 100644 --- a/server/tests/e2e/place-votes.e2e.test.ts +++ b/server/tests/e2e/place-votes.e2e.test.ts @@ -43,7 +43,7 @@ const LIBRARY_RATING = `${COLLECTIONS}/library/places/rating`; const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); /** A voter as the entry rating names them. */ -const voter = (user: { id: number; username: string }, rating: number) => ({ +const voter = (user: { id: number; username?: string | null }, rating: number) => ({ user_id: user.id, username: user.username, avatar_url: null, diff --git a/server/tests/e2e/places-library-rating.e2e.test.ts b/server/tests/e2e/places-library-rating.e2e.test.ts new file mode 100644 index 000000000..660cd7010 --- /dev/null +++ b/server/tests/e2e/places-library-rating.e2e.test.ts @@ -0,0 +1,161 @@ +/** + * The rating filter and the rating order of All places, end to end on the + * whole app (buildApp, the real guards and a migrated temp database; in the + * Postgres lane on Postgres too): `min_rating` keeps the entries whose + * average vote (every person once, over the copies the reader reaches) + * reaches it and leaves out the unrated ones, the tab counts follow it, the + * order `rating` puts the best rated first and the unrated last, page by + * page through its cursor, and list_all_places answers the same. + */ +import { buildApp } from '../../src/bootstrap'; +import { CollectionPlaceRatings } from '../../src/db/entities/CollectionPlaceRatings.entity'; +import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity'; +import type { McpContext } from '../../src/nest-mcp'; +import { withRequestContext } from '../../src/nest/database/request-context'; +import { PlacesLibraryMcp } from '../../src/nest/places-library/places-library.mcp'; +import { makeCollection, makeCollectionPlace } from '../helpers/factories/collections'; +import { makePlace } from '../helpers/factories/places'; +import { insertRow } from '../helpers/factories/rows'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { addTripMember, makeTrip } from '../helpers/factories/trips'; +import { makeUser } from '../helpers/factories/users'; +import { resetRateLimits } from '../helpers/test-db'; +import { sessionCookie } from './harness'; +import { MikroORM } from '@mikro-orm/core'; +import type { INestApplication } from '@nestjs/common'; + +import type { Server } from 'http'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +let app: INestApplication; +let server: Server; +let orm: MikroORM; + +const LIBRARY = '/api/addons/collections/library/places'; +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); + +interface Page { + entries: { key: string; name: string; rating?: { average: number | null } }[]; + total: number; + counts: { all: number; trip: number; list: number }; + next_cursor: string | null; +} + +/** + * `me` has the trip Alps (with `friend` on it) holding Alpha (me 5, friend 3: + * 4 on average), Beta (me 5) and Gamma (no vote), and the list Food holding + * Delta (me 2). Each place stands alone, far from the others. + */ +async function seed() { + const { user: me } = await makeUser(orm); + const { user: friend } = await makeUser(orm); + const alps = await makeTrip(orm, me.id, { title: 'Alps' }); + await addTripMember(orm, alps.id, friend.id); + const alpha = await makePlace(orm, alps.id, { name: 'Alpha', lat: 10, lng: 10 }); + const beta = await makePlace(orm, alps.id, { name: 'Beta', lat: 20, lng: 20 }); + await makePlace(orm, alps.id, { name: 'Gamma', lat: 30, lng: 30 }); + const food = await makeCollection(orm, me.id, { name: 'Food' }); + const delta = await makeCollectionPlace(orm, food.id, me.id, { name: 'Delta', lat: 40, lng: 40 }); + await insertRow(orm, PlaceRatings, { place: alpha.id, user: me.id, rating: 5 }); + await insertRow(orm, PlaceRatings, { place: alpha.id, user: friend.id, rating: 3 }); + await insertRow(orm, PlaceRatings, { place: beta.id, user: me.id, rating: 5 }); + await insertRow(orm, CollectionPlaceRatings, { collectionPlace: delta.id, user: me.id, rating: 2 }); + return { me, friend, alps, food }; +} + +async function page(userId: number, query: Record): Promise { + const res = await request(server).get(LIBRARY).query(query).set(as(userId)); + expect(res.status).toBe(200); + return res.body as Page; +} + +const names = (p: Page) => p.entries.map((entry) => entry.name); + +beforeAll(async () => { + app = await buildApp(); + server = app.getHttpServer() as Server; + orm = app.get(MikroORM); + await setAddonEnabled(orm, 'collections', true); +}, 60_000); + +beforeEach(async () => { + await resetRateLimits(app); +}); + +afterAll(async () => { + await app?.close(); +}); + +describe('the rating filter of All places', () => { + it('keeps the entries whose average reaches the floor, and the counts follow it', async () => { + const s = await seed(); + const four = await page(s.me.id, { min_rating: 4 }); + expect(names(four).sort()).toEqual(['Alpha', 'Beta']); + expect(four.total).toBe(2); + expect(four.counts).toEqual({ all: 2, trip: 2, list: 0 }); + + const two = await page(s.me.id, { min_rating: '2' }); + expect(names(two).sort()).toEqual(['Alpha', 'Beta', 'Delta']); + expect(two.counts).toEqual({ all: 3, trip: 2, list: 1 }); + // Without the filter the unrated place is there too. + expect((await page(s.me.id, {})).counts.all).toBe(4); + }); + + it('narrows a kind as well, and refuses a floor outside 1 to 5', async () => { + const s = await seed(); + expect(names(await page(s.me.id, { min_rating: 2, kind: 'list' }))).toEqual(['Delta']); + for (const bad of ['0', '6', '4.5', 'x']) { + const res = await request(server).get(LIBRARY).query({ min_rating: bad }).set(as(s.me.id)); + expect(res.status).toBe(400); + } + }); + + it('averages over the votes the reader can see: the friend reaches the trip only', async () => { + const s = await seed(); + const theirs = await page(s.friend.id, { min_rating: 3 }); + expect(names(theirs).sort()).toEqual(['Alpha', 'Beta']); + expect(theirs.entries.find((entry) => entry.name === 'Alpha')?.rating?.average).toBe(4); + }); +}); + +describe('the rating order of All places', () => { + it('puts the best rated first, a tie by name, and the unrated last', async () => { + const s = await seed(); + expect(names(await page(s.me.id, { sort: 'rating' }))).toEqual(['Beta', 'Alpha', 'Delta', 'Gamma']); + }); + + it('pages through its cursor without a gap or a double', async () => { + const s = await seed(); + const seen: string[] = []; + let cursor: string | null = null; + for (let i = 0; i < 5; i++) { + const query: Record = { sort: 'rating', limit: 1 }; + if (cursor) query.cursor = cursor; + const p = await page(s.me.id, query); + seen.push(...names(p)); + cursor = p.next_cursor; + if (!cursor) break; + } + expect(seen).toEqual(['Beta', 'Alpha', 'Delta', 'Gamma']); + // A cursor of the name order is no cursor of the rating order. + const byName = await page(s.me.id, { limit: 1 }); + const res = await request(server) + .get(LIBRARY) + .query({ sort: 'rating', cursor: byName.next_cursor ?? '' }) + .set(as(s.me.id)); + expect(res.status).toBe(400); + }); + + it('combines with the floor, and list_all_places answers the same', async () => { + const s = await seed(); + expect(names(await page(s.me.id, { sort: 'rating', min_rating: 3 }))).toEqual(['Beta', 'Alpha']); + const tools = app.get(PlacesLibraryMcp); + const ctx: McpContext = { userId: s.me.id, scopes: null, isStaticToken: false }; + const answer = await withRequestContext(orm, () => + tools.listAllPlaces({ sort: 'rating', min_rating: 3 } as never, ctx), + ); + const text = (answer as unknown as { content: { text: string }[] }).content[0]?.text ?? ''; + expect((JSON.parse(text) as Page).entries.map((entry) => entry.name)).toEqual(['Beta', 'Alpha']); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-votes.helpers.test.ts b/server/tests/unit/nest/places-library/place-votes.helpers.test.ts index fa21c0865..2fee62585 100644 --- a/server/tests/unit/nest/places-library/place-votes.helpers.test.ts +++ b/server/tests/unit/nest/places-library/place-votes.helpers.test.ts @@ -1,9 +1,9 @@ import type { LibraryCollectionPlaceRow, - LibraryOwnVoteRow, LibraryTripPlaceRow, LibraryUseRow, } from '../../../../src/db/repositories/PlacesLibrary.repository'; +import type { LibraryOwnVoteRow } from '../../../../src/db/repositories/PlacesLibraryDetails.repository'; import { votesToCarry, voteTargetsOf } from '../../../../src/nest/places-library/place-votes.helpers'; import { castAfter, unifiedRatingOf, type EntryRows } from '../../../../src/nest/places-library/places-library.helpers'; diff --git a/server/tests/unit/nest/places-library/place-votes.service.test.ts b/server/tests/unit/nest/places-library/place-votes.service.test.ts index d3f742e53..dee16559b 100644 --- a/server/tests/unit/nest/places-library/place-votes.service.test.ts +++ b/server/tests/unit/nest/places-library/place-votes.service.test.ts @@ -7,7 +7,7 @@ * the vote by entry key and the carry-over's inserts. The SQL behind it and * the whole path run in tests/e2e/place-votes.e2e.test.ts. */ -import { PlacesLibraryRepository } from '../../../../src/db/repositories/PlacesLibrary.repository'; +import { PlacesLibraryDetailsRepository } from '../../../../src/db/repositories/PlacesLibraryDetails.repository'; import { AddonsService } from '../../../../src/nest/addons/addons.service'; import { CollectionsService } from '../../../../src/nest/collections/collections.service'; import { notFound } from '../../../../src/nest/common/domain-error'; @@ -62,7 +62,7 @@ async function build(copies: Copies, options: { addonOn?: boolean; uses?: unknow { provide: CollectionsService, useValue: collections }, { provide: PlacesService, useValue: places }, { provide: UnitOfWork, useValue: uow }, - { provide: PlacesLibraryRepository, useValue: repo }, + { provide: PlacesLibraryDetailsRepository, useValue: repo }, { provide: AddonsService, useValue: addons }, { provide: TripMembershipService, useValue: membership }, ], diff --git a/server/tests/unit/nest/places/places.mcp.origins.test.ts b/server/tests/unit/nest/places/places.mcp.origins.test.ts index f4a1c2560..36470ae7a 100644 --- a/server/tests/unit/nest/places/places.mcp.origins.test.ts +++ b/server/tests/unit/nest/places/places.mcp.origins.test.ts @@ -14,7 +14,7 @@ const BEFORE = { website: null, phone: null, email: null, opening_hours: null, d const places = { create: vi.fn(async (_trip: string, input: Record) => ({ id: 21, ...input })), - update: vi.fn(async (_trip: string, id: string) => ({ id: Number(id), name: 'Updated' })), + update: vi.fn(async (_trip: string, id: string, ..._rest: unknown[]) => ({ id: Number(id), name: 'Updated' })), setImageFromFile: vi.fn(async (_trip: string, id: string) => ({ id: Number(id) })), updateMany: vi.fn(async (_trip: string, ids: number[]) => ids.map((id) => ({ id }))), importGpx: vi.fn(async () => ({ places: [{ id: 31 }, { id: 32 }], count: 2, skipped: 0 })),