mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 17:03:15 +00:00
1c9ac0b159
The reads of what an entry of All places keeps beside its facts (tags, notes, votes, planned days, bookings, list roles) move from PlacesLibraryRepository into PlacesLibraryDetailsRepository, so neither file passes the size limit. New end to end tests cover the rating filter, the tab counts under it, the rating order and its cursor, and list_all_places with both. The test types follow the vote shapes, the edit target says it may be null, the bookings pair names the booking card that now holds the booking model, and the size baselines drop to the measured lengths.
828 lines
30 KiB
TypeScript
828 lines
30 KiB
TypeScript
import { castIntegerKysely, containsIgnoringCaseKysely } from '../dialect/kysely-functions';
|
|
import type { DB } from '../kysely/db';
|
|
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'
|
|
| 'user_places'
|
|
| 'user_place_links'
|
|
| 'tags'
|
|
| 'place_tags'
|
|
| 'users'
|
|
>;
|
|
|
|
/**
|
|
* 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]);
|
|
|
|
/** What reading an entry's uses matches: everything. */
|
|
const NO_MATCH: LibraryMatch = { search: null, categoryId: null, status: null, tags: null, rating: null };
|
|
|
|
/**
|
|
* An entry's average vote as one integer that orders like it: the sum of the
|
|
* votes times this, divided by how many, truncated. Integers, so the order and
|
|
* a cursor read the same on both engines; ties a millionth of a star apart
|
|
* fall back to the key.
|
|
*/
|
|
export const RATING_SCORE_SCALE = 1_000_000;
|
|
|
|
/** The sort value of an entry nobody voted on: below every average, so it comes last. */
|
|
export const UNRATED_SCORE = -1;
|
|
|
|
/**
|
|
* 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');
|
|
|
|
/**
|
|
* How one number names an entry: `id * 4 + kind`, the id being the user's own
|
|
* place (D5), else the trip place, else the saved place the entry stands for.
|
|
* Being one number, it orders, pages and counts like a column.
|
|
*/
|
|
export const ANCHOR_TRIP = 1;
|
|
export const ANCHOR_LIST = 2;
|
|
export const ANCHOR_OWN = 3;
|
|
export const ANCHOR_SPAN = 4;
|
|
|
|
/**
|
|
* 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. `userId`
|
|
* names whose own places group the entries.
|
|
*/
|
|
export interface LibraryArms {
|
|
userId: number;
|
|
/** 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;
|
|
/** PLC-21: only entries carrying a tag of one of these names, a list's label or a trip's tag. */
|
|
tags: LibraryTagMatch | null;
|
|
/** The votes of the entries: only those whose average reaches `min` stars, and what the rating sort reads. */
|
|
rating: LibraryRatingMatch | null;
|
|
}
|
|
|
|
/**
|
|
* How the votes of an entry are read for the rating filter and sort: over
|
|
* every copy of it the user reaches (`reach`, every trip and list they can
|
|
* open), each person once with the vote they changed last, as the entry's
|
|
* rating counts them. `min` keeps the entries whose average is at least that
|
|
* many stars (an entry without votes has none); null keeps every entry.
|
|
*/
|
|
export interface LibraryRatingMatch {
|
|
min: number | null;
|
|
reach: LibraryArms;
|
|
}
|
|
|
|
/**
|
|
* The tag names an entry must carry one of (PLC-21), each as the engines fold
|
|
* a name (`lower(trim(name))`), so a name matches whatever its case. `reach`
|
|
* is every trip and list the user can open: a tag on any use of an entry
|
|
* counts, also on a use another filter of the page leaves out.
|
|
*/
|
|
interface LibraryTagMatch {
|
|
foldedNames: string[];
|
|
reach: LibraryArms;
|
|
}
|
|
|
|
/** 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' | 'rating';
|
|
|
|
/** One entry of a page, named by its anchor (see `ANCHOR_SPAN`). */
|
|
export interface LibraryAnchorRow {
|
|
anchor_key: number;
|
|
sort_name: string;
|
|
sort_time: string;
|
|
/** The rating sort's value (see `RATING_SCORE_SCALE`), `UNRATED_SCORE` without votes; 0 under the other sorts. */
|
|
sort_rating: number;
|
|
}
|
|
|
|
interface UnionRow extends LibraryAnchorRow {
|
|
/** 1 when the row came from a list of saved places. */
|
|
from_list: number;
|
|
/** The trip place or saved place of the row. */
|
|
use_id: number;
|
|
/** 1 when the user assigned this use to an own place of theirs. */
|
|
linked: number;
|
|
}
|
|
|
|
/** One use of an entry: a trip place (from_list 0) or a saved place, and whether the user linked it. */
|
|
export interface LibraryUseRow {
|
|
anchor_key: number;
|
|
from_list: number;
|
|
use_id: number;
|
|
linked: boolean;
|
|
}
|
|
|
|
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;
|
|
google_place_id: string | null;
|
|
google_ftid: string | null;
|
|
osm_id: 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;
|
|
/** The trip's cover picture, for the card that names it. */
|
|
trip_cover?: string | null;
|
|
}
|
|
|
|
export interface LibraryCollectionPlaceRow extends PlaceFactsRow {
|
|
id: number;
|
|
collection_id: number;
|
|
collection_name: string;
|
|
/** The list's own colour and symbol, as its rail row shows them. */
|
|
collection_color?: string | null;
|
|
collection_icon?: string | null;
|
|
status: string;
|
|
}
|
|
|
|
/** A user's own place (D5), with its category. */
|
|
export interface LibraryIdentityRow {
|
|
id: number;
|
|
name: string;
|
|
address: string | null;
|
|
lat: number | null;
|
|
lng: number | null;
|
|
google_place_id: string | null;
|
|
google_ftid: string | null;
|
|
osm_id: string | null;
|
|
updated_at: string | null;
|
|
category_id: number | null;
|
|
category_name: string | null;
|
|
category_color: string | null;
|
|
category_icon: 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.
|
|
*
|
|
* Above that, a use the user linked to an own place of theirs (D5,
|
|
* `user_place_links`) stands for that place's entry, and so does a saved place
|
|
* grouped with a linked trip place unless it is linked itself. Only uses the
|
|
* user reaches today come out, so an own place none of whose uses is open to
|
|
* them any more has no entry.
|
|
*/
|
|
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; one the user linked stands for their own place's entry. */
|
|
private tripArm(db: Kysely<LibraryDB>, arms: LibraryArms, match: LibraryMatch) {
|
|
const platform = this.em.getPlatform();
|
|
return db
|
|
.selectFrom('places as p')
|
|
.leftJoin('user_place_links as ul', (join) =>
|
|
join.onRef('ul.place_id', '=', 'p.id').on('ul.user_id', '=', arms.userId),
|
|
)
|
|
.leftJoin('user_places as up', 'up.id', 'ul.user_place_id')
|
|
.select((eb) => [
|
|
eb.fn
|
|
.coalesce(
|
|
eb(
|
|
eb('ul.user_place_id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
|
|
'+',
|
|
eb.lit(ANCHOR_OWN),
|
|
).$castTo<number>(),
|
|
eb(eb('p.id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(), '+', eb.lit(ANCHOR_TRIP)).$castTo<number>(),
|
|
)
|
|
.as('anchor_key'),
|
|
eb.fn<string>('lower', [eb.fn.coalesce('up.name', 'p.name')]).as('sort_name'),
|
|
eb
|
|
.case()
|
|
.when('up.id', 'is not', null)
|
|
.then(eb.fn.coalesce('up.updated_at', eb.val('')))
|
|
.else(eb.fn.coalesce('p.updated_at', eb.val('')))
|
|
.end()
|
|
.as('sort_time'),
|
|
eb.cast<number>(eb.lit(0), 'integer').as('from_list'),
|
|
'p.id as use_id',
|
|
eb.case().when('ul.id', 'is not', null).then(eb.lit(1)).else(eb.lit(0)).end().as('linked'),
|
|
])
|
|
.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 the user linked stands for their own
|
|
* place's entry; one grouped with a trip place stands for that place's entry,
|
|
* or for the own place that trip place is linked to.
|
|
*/
|
|
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')
|
|
.leftJoin('user_place_links as ulc', (join) =>
|
|
join.onRef('ulc.collection_place_id', '=', 'cp.id').on('ulc.user_id', '=', arms.userId),
|
|
)
|
|
.leftJoin('user_place_links as ulg', (join) =>
|
|
join.onRef('ulg.place_id', '=', 'gl.place_id').on('ulg.user_id', '=', arms.userId),
|
|
)
|
|
.leftJoin('user_places as up', (join) =>
|
|
join.on((eb) => eb('up.id', '=', eb.fn.coalesce('ulc.user_place_id', 'ulg.user_place_id'))),
|
|
)
|
|
.select((eb) => [
|
|
eb.fn
|
|
.coalesce(
|
|
eb(
|
|
eb('ulc.user_place_id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
|
|
'+',
|
|
eb.lit(ANCHOR_OWN),
|
|
).$castTo<number>(),
|
|
eb(
|
|
eb('ulg.user_place_id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
|
|
'+',
|
|
eb.lit(ANCHOR_OWN),
|
|
).$castTo<number>(),
|
|
eb(
|
|
eb('gl.place_id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
|
|
'+',
|
|
eb.lit(ANCHOR_TRIP),
|
|
).$castTo<number>(),
|
|
eb(eb('cp.id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(), '+', eb.lit(ANCHOR_LIST)).$castTo<number>(),
|
|
)
|
|
.as('anchor_key'),
|
|
eb.fn<string>('lower', [eb.fn.coalesce('up.name', 'g.name', 'cp.name')]).as('sort_name'),
|
|
eb
|
|
.case()
|
|
.when('up.id', 'is not', null)
|
|
.then(eb.fn.coalesce('up.updated_at', eb.val('')))
|
|
.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'),
|
|
'cp.id as use_id',
|
|
eb.case().when('ulc.id', 'is not', null).then(eb.lit(1)).else(eb.lit(0)).end().as('linked'),
|
|
])
|
|
.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');
|
|
}
|
|
|
|
/**
|
|
* The entries that carry a tag of one of the names (PLC-21): a trip tag on
|
|
* one of their trip places or a list label on one of their saved places.
|
|
*/
|
|
private taggedAnchors(db: Kysely<LibraryDB>, tags: LibraryTagMatch) {
|
|
const names = tags.foldedNames.length > 0 ? tags.foldedNames : [''];
|
|
return db
|
|
.selectFrom(this.entries(db, tags.reach, NO_MATCH))
|
|
.select('u.anchor_key')
|
|
.where((eb) =>
|
|
eb.or([
|
|
eb.and([
|
|
eb('u.from_list', '=', 0),
|
|
eb.exists(
|
|
eb
|
|
.selectFrom('place_tags as pt')
|
|
.innerJoin('tags as tg', 'tg.id', 'pt.tag_id')
|
|
.select('pt.tag_id')
|
|
.whereRef('pt.place_id', '=', 'u.use_id')
|
|
.where((inner) =>
|
|
inner(inner.fn<string>('lower', [inner.fn<string>('trim', ['tg.name'])]), 'in', names),
|
|
),
|
|
),
|
|
]),
|
|
eb.and([
|
|
eb('u.from_list', '=', 1),
|
|
eb.exists(
|
|
eb
|
|
.selectFrom('collection_place_labels as cpl')
|
|
.innerJoin('collection_labels as lb', 'lb.id', 'cpl.label_id')
|
|
.select('cpl.label_id')
|
|
.whereRef('cpl.collection_place_id', '=', 'u.use_id')
|
|
.where((inner) =>
|
|
inner(inner.fn<string>('lower', [inner.fn<string>('trim', ['lb.name'])]), 'in', names),
|
|
),
|
|
),
|
|
]),
|
|
]),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Every person's last vote on each entry, over the copies `reach` holds: the
|
|
* votes on its trip places and on its saved places, each person once with
|
|
* the vote they changed last (a later row breaks a tie, then a trip place
|
|
* before a saved place), the way `unifiedRatingOf` reads them.
|
|
*/
|
|
private lastVotes(db: Kysely<LibraryDB>, reach: LibraryArms) {
|
|
const onTrips = db
|
|
.selectFrom(this.entries(db, reach, NO_MATCH))
|
|
.innerJoin('place_ratings as pr', 'pr.place_id', 'u.use_id')
|
|
.where('u.from_list', '=', 0)
|
|
.select((eb) => [
|
|
'u.anchor_key',
|
|
'u.from_list',
|
|
'pr.user_id',
|
|
'pr.rating',
|
|
'pr.id',
|
|
eb.fn.coalesce('pr.updated_at', 'pr.created_at', eb.val('')).$castTo<string>().as('changed_at'),
|
|
]);
|
|
const onLists = db
|
|
.selectFrom(this.entries(db, reach, NO_MATCH))
|
|
.innerJoin('collection_place_ratings as cr', 'cr.collection_place_id', 'u.use_id')
|
|
.where('u.from_list', '=', 1)
|
|
.select((eb) => [
|
|
'u.anchor_key',
|
|
'u.from_list',
|
|
'cr.user_id',
|
|
'cr.rating',
|
|
'cr.id',
|
|
eb.fn.coalesce('cr.updated_at', 'cr.created_at', eb.val('')).$castTo<string>().as('changed_at'),
|
|
]);
|
|
return db.selectFrom(onTrips.unionAll(onLists).as('v')).select((eb) => [
|
|
'v.anchor_key',
|
|
'v.rating',
|
|
eb.fn
|
|
.agg<number>('row_number')
|
|
.over((ob) =>
|
|
ob
|
|
.partitionBy(['v.anchor_key', 'v.user_id'])
|
|
.orderBy('v.changed_at', 'desc')
|
|
.orderBy('v.id', 'desc')
|
|
.orderBy('v.from_list', 'asc'),
|
|
)
|
|
.as('nth'),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Each entry with votes on the copies `reach` holds: the sum of every
|
|
* person's last vote, how many people voted, and the score the rating sort
|
|
* orders by (see `RATING_SCORE_SCALE`).
|
|
*/
|
|
private entryScores(db: Kysely<LibraryDB>, reach: LibraryArms) {
|
|
const platform = this.em.getPlatform();
|
|
return db
|
|
.selectFrom(this.lastVotes(db, reach).as('lv'))
|
|
.where('lv.nth', '=', 1)
|
|
.groupBy('lv.anchor_key')
|
|
.select((eb) => {
|
|
const total = eb.fn.sum<number>('lv.rating');
|
|
const voters = eb.fn.countAll<number>();
|
|
const scaled = eb(eb(total, '*', eb.lit(RATING_SCORE_SCALE)), '/', voters);
|
|
return [
|
|
'lv.anchor_key',
|
|
total.as('total'),
|
|
voters.as('voters'),
|
|
castIntegerKysely(platform, eb, scaled).as('score'),
|
|
];
|
|
});
|
|
}
|
|
|
|
/**
|
|
* The union of the entries, narrowed to the ones carrying a tag when the
|
|
* match names tags, and to the ones whose average reaches the fewest stars
|
|
* when it names those.
|
|
*/
|
|
private matching(db: Kysely<LibraryDB>, arms: LibraryArms, match: LibraryMatch) {
|
|
const { tags, rating } = match;
|
|
let all = db.selectFrom(this.entries(db, arms, match));
|
|
if (tags !== null) all = all.where('u.anchor_key', 'in', this.taggedAnchors(db, tags));
|
|
if (rating !== null && rating.min !== null) {
|
|
const min = rating.min;
|
|
// The average reaches `min` exactly when the sum reaches `min` times the number of voters.
|
|
all = all.where(
|
|
'u.anchor_key',
|
|
'in',
|
|
db
|
|
.selectFrom(this.entryScores(db, rating.reach).as('rs'))
|
|
.select('rs.anchor_key')
|
|
.where((eb) => eb('rs.total', '>=', eb('rs.voters', '*', eb.val(min)))),
|
|
);
|
|
}
|
|
return all;
|
|
}
|
|
|
|
/** 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 this.matching(db, arms, match)
|
|
.select((eb) => [
|
|
eb.fn.count<number>('u.anchor_key').distinct().as('all'),
|
|
eb.fn
|
|
.count<number>(eb.case().when('u.from_list', '=', 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[]> {
|
|
if (sort === 'rating') return this.pageByRating(arms, match, after, limit);
|
|
const db = this.db();
|
|
const value = after?.value ?? '';
|
|
const key = after?.key ?? 0;
|
|
const rows = await this.matching(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,
|
|
sort_rating: 0,
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* Up to `limit` entries by their votes, the highest average first and the
|
|
* entries without votes last, after `after` when given. The votes are read
|
|
* over `match.rating.reach` (every copy the user reaches), else over `arms`.
|
|
*/
|
|
private async pageByRating(
|
|
arms: LibraryArms,
|
|
match: LibraryMatch,
|
|
after: LibraryPosition | null,
|
|
limit: number,
|
|
): Promise<LibraryAnchorRow[]> {
|
|
const db = this.db();
|
|
const value = after === null ? 0 : Number(after.value);
|
|
const key = after?.key ?? 0;
|
|
const rows = await this.matching(db, arms, match)
|
|
.leftJoin(this.entryScores(db, match.rating?.reach ?? arms).as('sc'), 'sc.anchor_key', 'u.anchor_key')
|
|
.select((eb) => [
|
|
'u.anchor_key',
|
|
'u.sort_name',
|
|
'u.sort_time',
|
|
eb.fn.coalesce('sc.score', eb.val(UNRATED_SCORE)).$castTo<number>().as('sort_rating'),
|
|
])
|
|
.distinct()
|
|
.$if(after !== null, (qb) =>
|
|
qb.where((eb) => {
|
|
const score = eb.fn.coalesce('sc.score', eb.val(UNRATED_SCORE));
|
|
return eb.or([eb(score, '<', value), eb.and([eb(score, '=', value), eb('u.anchor_key', '>', key)])]);
|
|
}),
|
|
)
|
|
.orderBy('sort_rating', 'desc')
|
|
.orderBy('u.anchor_key', 'asc')
|
|
.limit(limit)
|
|
.execute();
|
|
return rows.map((row) => ({
|
|
anchor_key: Number(row.anchor_key),
|
|
sort_name: row.sort_name,
|
|
sort_time: row.sort_time,
|
|
sort_rating: Number(row.sort_rating),
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* The uses of the entries `anchors` the user reaches (every use when
|
|
* `anchors` is null), with the entry each stands for: trip places first,
|
|
* then saved places, each in id order.
|
|
*/
|
|
async usesOf(arms: LibraryArms, anchors: number[] | null): Promise<LibraryUseRow[]> {
|
|
const db = this.db();
|
|
const rows = await db
|
|
.selectFrom(this.entries(db, arms, NO_MATCH))
|
|
.select(['u.anchor_key', 'u.from_list', 'u.use_id', 'u.linked'])
|
|
.$if(anchors !== null, (qb) => qb.where('u.anchor_key', 'in', idsOrNone(anchors ?? [])))
|
|
.orderBy('u.from_list')
|
|
.orderBy('u.use_id')
|
|
.execute();
|
|
return rows.map(useRowOf);
|
|
}
|
|
|
|
/** Which of the uses (from_list 0: a trip place, 1: a saved place) the user reaches, each with its entry. */
|
|
async reachedUses(arms: LibraryArms, uses: readonly { fromList: number; useId: number }[]): Promise<LibraryUseRow[]> {
|
|
if (uses.length === 0) return [];
|
|
const db = this.db();
|
|
const rows = await db
|
|
.selectFrom(this.entries(db, arms, NO_MATCH))
|
|
.select(['u.anchor_key', 'u.from_list', 'u.use_id', 'u.linked'])
|
|
.where((eb) =>
|
|
eb.or(uses.map((use) => eb.and([eb('u.from_list', '=', use.fromList), eb('u.use_id', '=', use.useId)]))),
|
|
)
|
|
.orderBy('u.from_list')
|
|
.orderBy('u.use_id')
|
|
.execute();
|
|
return rows.map(useRowOf);
|
|
}
|
|
|
|
/** The entry the use stands for (from_list 0: a trip place, 1: a saved place), when the user reaches it. */
|
|
async anchorOfUse(arms: LibraryArms, fromList: number, useId: number): Promise<number | null> {
|
|
const db = this.db();
|
|
const row = await db
|
|
.selectFrom(this.entries(db, arms, NO_MATCH))
|
|
.select('u.anchor_key')
|
|
.where('u.from_list', '=', fromList)
|
|
.where('u.use_id', '=', useId)
|
|
.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',
|
|
'p.google_place_id',
|
|
'p.google_ftid',
|
|
'p.osm_id',
|
|
'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',
|
|
't.cover_image as trip_cover',
|
|
])
|
|
.where('p.id', 'in', idsOrNone(placeIds))
|
|
.where('p.trip_id', 'in', idsOrNone(tripIds))
|
|
.orderBy('p.id')
|
|
.execute();
|
|
}
|
|
|
|
/** The saved places `ids` of `collectionIds`, each with its list, ordered by list name. */
|
|
async savedPlaces(collectionIds: number[], ids: number[]): Promise<LibraryCollectionPlaceRow[]> {
|
|
return await this.db()
|
|
.selectFrom('collection_places as cp')
|
|
.innerJoin('collections as col', 'col.id', 'cp.collection_id')
|
|
.leftJoin('categories as c', 'c.id', 'cp.category_id')
|
|
.select([
|
|
'cp.id',
|
|
'cp.collection_id',
|
|
'col.name as collection_name',
|
|
'col.color as collection_color',
|
|
'col.icon as collection_icon',
|
|
'cp.status',
|
|
'cp.name',
|
|
'cp.address',
|
|
'cp.lat',
|
|
'cp.lng',
|
|
'cp.image_url',
|
|
'cp.updated_at',
|
|
'cp.description',
|
|
'cp.website',
|
|
'cp.phone',
|
|
'cp.google_place_id',
|
|
'cp.google_ftid',
|
|
'cp.osm_id',
|
|
'c.id as category_id',
|
|
'c.name as category_name',
|
|
'c.color as category_color',
|
|
'c.icon as category_icon',
|
|
])
|
|
.where('cp.collection_id', 'in', idsOrNone(collectionIds))
|
|
.where('cp.id', 'in', idsOrNone(ids))
|
|
.orderBy('col.name')
|
|
.orderBy('cp.id')
|
|
.execute();
|
|
}
|
|
|
|
/** The user's own places `ids`, with their category. */
|
|
async identities(userId: number, ids: number[]): Promise<LibraryIdentityRow[]> {
|
|
return await this.db()
|
|
.selectFrom('user_places as up')
|
|
.leftJoin('categories as c', 'c.id', 'up.category_id')
|
|
.select([
|
|
'up.id',
|
|
'up.name',
|
|
'up.address',
|
|
'up.lat',
|
|
'up.lng',
|
|
'up.google_place_id',
|
|
'up.google_ftid',
|
|
'up.osm_id',
|
|
'up.updated_at',
|
|
'c.id as category_id',
|
|
'c.name as category_name',
|
|
'c.color as category_color',
|
|
'c.icon as category_icon',
|
|
])
|
|
.where('up.user_id', '=', userId)
|
|
.where('up.id', 'in', idsOrNone(ids))
|
|
.execute();
|
|
}
|
|
}
|
|
|
|
/** A use as the union reads it, its numbers as numbers whatever the engine hands back. */
|
|
function useRowOf(row: { anchor_key: unknown; from_list: unknown; use_id: unknown; linked: unknown }): LibraryUseRow {
|
|
return {
|
|
anchor_key: Number(row.anchor_key),
|
|
from_list: Number(row.from_list),
|
|
use_id: Number(row.use_id),
|
|
linked: Number(row.linked) === 1,
|
|
};
|
|
}
|