mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
refactor(server): trip-membership, place-shadow, place-enrichment, place-photos and query helpers through repositories
This commit is contained in:
@@ -157,12 +157,36 @@ export function nowMinusDays(platform: Platform, days: number): RawQueryFragment
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** `TRIM(<col>)`. Pairs with `lower()` for the `LOWER(TRIM(name))` shape (`places.service.ts:642`). */
|
||||
/**
|
||||
* `TRIM(<col>)`, standalone. **Does NOT compose with `lower()`** to build
|
||||
* `LOWER(TRIM(name))` (Task 0b review M3): `lower()`'s `ref` argument goes
|
||||
* through `column()`, whose regex rejects anything but a bare
|
||||
* `alias.column` reference — `TRIM(name)` fails it — and even if it didn't,
|
||||
* `coalesce()`'s own docstring in this file documents that a
|
||||
* `RawQueryFragment` cannot be nested inside another one (`raw()`'s
|
||||
* `[Symbol.toPrimitive]` only implements the `'string'` coercion hint, which
|
||||
* is the object-key position, not template-literal interpolation). Use
|
||||
* `lowerTrim()` below for the composed shape.
|
||||
*/
|
||||
export function trim(platform: Platform, ref: string): RawQueryFragment {
|
||||
if (platform instanceof SqlitePlatform) return raw(`TRIM(${column(ref)})`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `LOWER(TRIM(<col>))` as one fragment — the shape `places.service.ts:642`
|
||||
* (`lower(trim(name))`, PL26) actually needs; `lower()`/`trim()` above
|
||||
* cannot be composed to build it (see `trim()`'s docstring, Task 0b review
|
||||
* M3). Typed `RawQueryFragment & symbol`, the same brand `lower()` carries,
|
||||
* for use as a filter KEY: `{ [lowerTrim(platform, 'name')]: lowerParam(...) }`.
|
||||
* SQLite's `LOWER()` is ASCII-only (program rule 18) — unchanged by the
|
||||
* `TRIM()`.
|
||||
*/
|
||||
export function lowerTrim(platform: Platform, ref: string): RawQueryFragment & symbol {
|
||||
if (platform instanceof SqlitePlatform) return raw(`LOWER(TRIM(${column(ref)}))`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `COALESCE(<col>, <fallbackCol>)` — both sides column references, for the
|
||||
* `COALESCE(a, b)` SELECT-projection shape (`days.service.ts:93-94`,
|
||||
@@ -209,3 +233,36 @@ export function absDifference(platform: Platform, ref: string, value: number): R
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3c Task 1 — aggregate SELECT projections (`PlaceShadowPicksRepository
|
||||
// .totals`/`countBySource`/`countByLiveRank`, `place-shadow.service.ts:144,
|
||||
// 149, 157`). `alias` is a hand-written literal at every call site today
|
||||
// (never user input), validated the same way `column()` validates a column
|
||||
// reference, so a future caller cannot smuggle SQL through it either.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function alias(name: string): string {
|
||||
if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {
|
||||
throw new Error(`sql-functions: not an alias: ${name}`);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
/** `COUNT(*) as <alias>`, for a single-row totals read or a `GROUP BY` count column. */
|
||||
export function countAll(platform: Platform, aliasName: string): RawQueryFragment {
|
||||
if (platform instanceof SqlitePlatform) return raw(`COUNT(*) as ${alias(aliasName)}`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** `MIN(<col>) as <alias>`. */
|
||||
export function minOf(platform: Platform, ref: string, aliasName: string): RawQueryFragment {
|
||||
if (platform instanceof SqlitePlatform) return raw(`MIN(${column(ref)}) as ${alias(aliasName)}`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** `MAX(<col>) as <alias>`. */
|
||||
export function maxOf(platform: Platform, ref: string, aliasName: string): RawQueryFragment {
|
||||
if (platform instanceof SqlitePlatform) return raw(`MAX(${column(ref)}) as ${alias(aliasName)}`);
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,72 @@
|
||||
import type { GooglePlacePhotoMeta } from '../entities/GooglePlacePhotoMeta.entity';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class GooglePlacePhotoMetaRepository extends TrekRepository<GooglePlacePhotoMeta> {}
|
||||
export class GooglePlacePhotoMetaRepository extends TrekRepository<GooglePlacePhotoMeta> {
|
||||
/**
|
||||
* `SELECT attribution FROM google_place_photo_meta WHERE place_id = ? AND
|
||||
* error_at IS NULL` (`place-photo-cache.service.ts:76-79`, PP1). `place_id`
|
||||
* is a TEXT key — pseudo-ids like `coords:lat:lng` are legal values, not
|
||||
* only real Google place ids.
|
||||
*/
|
||||
async findLive(placeId: string): Promise<{ attribution: string | null } | null> {
|
||||
const row = await this.findOne({ place_id: placeId, error_at: null }, { fields: ['attribution'] });
|
||||
return row ? { attribution: row.attribution ?? null } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `DELETE FROM google_place_photo_meta WHERE place_id = ?` — ONE method for
|
||||
* the two call sites that share this exact statement: PP2
|
||||
* (`place-photo-cache.service.ts:87`, `get`'s self-healing delete after a
|
||||
* storage-object miss) and PP7 (`:219`, `deleteEntry`, after an explicit
|
||||
* storage delete).
|
||||
*/
|
||||
async deleteByPlaceId(placeId: string): Promise<void> {
|
||||
await this.nativeDelete({ place_id: placeId });
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT error_at FROM google_place_photo_meta WHERE place_id = ? AND
|
||||
* error_at IS NOT NULL` (`place-photo-cache.service.ts:103-106`, PP3). The
|
||||
* `Date.now() - row.error_at < MISSING_TTL` comparison stays the caller's
|
||||
* (D4's defaults rule).
|
||||
*/
|
||||
async findErrored(placeId: string): Promise<{ error_at: number } | null> {
|
||||
const row = await this.findOne({ place_id: placeId, error_at: { $ne: null } }, { fields: ['error_at'] });
|
||||
return row && row.error_at != null ? { error_at: row.error_at } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `INSERT OR REPLACE INTO google_place_photo_meta (place_id, attribution,
|
||||
* fetched_at, error_at) VALUES (?, NULL, ?, ?)` (`place-photo-cache.service.ts:131-134`,
|
||||
* PP4, `markError`'s `'no-photo'` branch) — `attribution` forced `NULL` on
|
||||
* every call, both timestamps ms-epoch INTEGERs (never `currentTimestamp`,
|
||||
* which renders SQL text). `em.upsert` with `onConflictFields: ['place_id']`
|
||||
* (the table's real PK, `Migration20200101014600_…`) and `onConflictAction:
|
||||
* 'merge'` — `INSERT OR REPLACE` semantics for this single-column key.
|
||||
*/
|
||||
async upsertError(placeId: string, at: number): Promise<void> {
|
||||
await this.upsert(
|
||||
{ place_id: placeId, attribution: null, fetched_at: at, error_at: at },
|
||||
{ onConflictFields: ['place_id'], onConflictAction: 'merge' },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `INSERT OR REPLACE INTO google_place_photo_meta (place_id, attribution,
|
||||
* fetched_at, error_at) VALUES (?, ?, ?, NULL)` (`place-photo-cache.service.ts:161-164`,
|
||||
* PP5, `put`) — `error_at` forced `NULL` on every call, PP4's mirror image
|
||||
* on the same PK. Same `em.upsert` shape as `upsertError` above.
|
||||
*/
|
||||
async upsertPhoto(placeId: string, attribution: string | null, at: number): Promise<void> {
|
||||
await this.upsert(
|
||||
{ place_id: placeId, attribution, fetched_at: at, error_at: null },
|
||||
{ onConflictFields: ['place_id'], onConflictAction: 'merge' },
|
||||
);
|
||||
}
|
||||
|
||||
/** `SELECT place_id FROM google_place_photo_meta` (`place-photo-cache.service.ts:239`, PP8) — the nightly/boot sweep's full-table scan. */
|
||||
async listPlaceIds(): Promise<string[]> {
|
||||
const rows = await this.find({}, { fields: ['place_id'] });
|
||||
return rows.map((r) => r.place_id).filter((id): id is string => id != null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,35 @@
|
||||
import type { PlaceDetailsCache } from '../entities/PlaceDetailsCache.entity';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class PlaceDetailsCacheRepository extends TrekRepository<PlaceDetailsCache> {}
|
||||
export class PlaceDetailsCacheRepository extends TrekRepository<PlaceDetailsCache> {
|
||||
/**
|
||||
* `SELECT payload_json, fetched_at FROM place_details_cache WHERE place_id = ?
|
||||
* AND lang = ? AND expanded = ?` (`place-enrichment.service.ts:810-815`,
|
||||
* PE2). The caller passes `lang ?? ''` (D4's defaults rule — the column is
|
||||
* `NOT NULL DEFAULT ''`, never NULL) and `expanded` bound to the
|
||||
* `CACHE_KIND` constant.
|
||||
*/
|
||||
async findEntry(placeId: string, lang: string, kind: number): Promise<{ payload_json: string; fetched_at: number } | null> {
|
||||
const row = await this.findOne(
|
||||
{ place_id: placeId, lang, expanded: kind },
|
||||
{ fields: ['payload_json', 'fetched_at'] },
|
||||
);
|
||||
return row ? { payload_json: row.payload_json, fetched_at: row.fetched_at } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `INSERT OR REPLACE INTO place_details_cache (place_id, lang, expanded,
|
||||
* payload_json, fetched_at) VALUES (?, ?, ?, ?, ?)`
|
||||
* (`place-enrichment.service.ts:847-854`, PE3). `em.upsert` with
|
||||
* `onConflictFields: ['place_id', 'lang', 'expanded']` — the table's real
|
||||
* composite PRIMARY KEY (`Migration20200101014700_…`,
|
||||
* `PRIMARY KEY (place_id, lang, expanded)`), not just `place_id`: naming
|
||||
* only the single column here would let `em.upsert` infer the wrong
|
||||
* conflict target and silently insert duplicate rows for two different
|
||||
* `lang`/`expanded` values on the same place. `fetched_at` is ms-epoch,
|
||||
* never `currentTimestamp`.
|
||||
*/
|
||||
async upsertEntry(row: { place_id: string; lang: string; expanded: number; payload_json: string; fetched_at: number }): Promise<void> {
|
||||
await this.upsert(row, { onConflictFields: ['place_id', 'lang', 'expanded'], onConflictAction: 'merge' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,43 @@
|
||||
import type { PlaceRatings } from '../entities/PlaceRatings.entity';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class PlaceRatingsRepository extends TrekRepository<PlaceRatings> {}
|
||||
/** One rated place, from `QueryHelpersService.loadRatingsByPlaceIds` (QH2). */
|
||||
export interface PlaceRatingForPlaceRow {
|
||||
place_id: number;
|
||||
user_id: number;
|
||||
username: string;
|
||||
avatar: string | null;
|
||||
rating: number;
|
||||
}
|
||||
|
||||
export class PlaceRatingsRepository extends TrekRepository<PlaceRatings> {
|
||||
/**
|
||||
* `SELECT pr.place_id, pr.user_id, u.username, u.avatar, pr.rating
|
||||
* FROM place_ratings pr JOIN users u ON pr.user_id = u.id
|
||||
* WHERE pr.place_id IN (${…}) ORDER BY pr.created_at`
|
||||
* (`query-helpers.service.ts:65-70`, QH2) — the batch loader behind
|
||||
* `PlacesService.list`'s ratings column. Empty `placeIds` short-circuits
|
||||
* before any query, matching the legacy service method (which never
|
||||
* built the `IN (...)` placeholder list for an empty array either).
|
||||
*/
|
||||
async listForPlaces(placeIds: number[]): Promise<PlaceRatingForPlaceRow[]> {
|
||||
if (placeIds.length === 0) return [];
|
||||
// `pr.place` selects the plain FK scalar as `place_id` (that relation is
|
||||
// never separately joined here). `pr.user` IS separately joined (to `u`,
|
||||
// for the username/avatar), and selecting a relation property that is
|
||||
// ALSO an active join's target makes MikroORM alias the column off the
|
||||
// JOINED entity's own primary key (`u__id`) instead of the FK scalar —
|
||||
// verified directly, not assumed — so the user id is pulled explicitly
|
||||
// off the join instead (`u.id as user_id`), the same "physical alias"
|
||||
// shape `Places.repository.ts`'s `'c.name as category_name'` uses.
|
||||
// Selecting the `persist(false)` scalar mirror directly (`pr.user_id`)
|
||||
// was tried and silently drops the column from the result — also
|
||||
// verified directly, not assumed.
|
||||
return this.qb('pr')
|
||||
.join('pr.user', 'u')
|
||||
.select(['pr.place', 'u.id as user_id', 'u.username', 'u.avatar', 'pr.rating'])
|
||||
.where({ 'pr.place': { $in: placeIds } })
|
||||
.orderBy({ 'pr.created_at': 'asc' })
|
||||
.execute<PlaceRatingForPlaceRow[]>('all', false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,127 @@
|
||||
import type { PlaceShadowPicks } from '../entities/PlaceShadowPicks.entity';
|
||||
import { countAll, maxOf, minOf, nowMinusDays } from '../dialect/sql-functions';
|
||||
import { toRow, type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
export class PlaceShadowPicksRepository extends TrekRepository<PlaceShadowPicks> {}
|
||||
/** A `place_shadow_picks` row as the API emits it. */
|
||||
export interface PlaceShadowPickRow {
|
||||
id: number;
|
||||
created_at: string;
|
||||
query: string;
|
||||
lang: string | null;
|
||||
bias_lat: number | null;
|
||||
bias_lng: number | null;
|
||||
source: string;
|
||||
live_rank: number;
|
||||
live_count: number;
|
||||
picked_name: string;
|
||||
picked_lat: number;
|
||||
picked_lng: number;
|
||||
picked_place_id: string | null;
|
||||
}
|
||||
|
||||
const _placeShadowPickRowKeys: AssertRowKeys<PlaceShadowPickRow, PlaceShadowPicks> = true;
|
||||
|
||||
/**
|
||||
* The column set of the legacy `record()` INSERT
|
||||
* (`place-shadow.service.ts:97-113`, PS2): `query`, `source`, `live_rank`,
|
||||
* `live_count`, `picked_name`, `picked_lat`, `picked_lng` required; the rest
|
||||
* nullable. The `round()` rounding, the `?? null` defaulting and the
|
||||
* `liveRank >= liveCount` drop all stay in `PlaceShadowService` (D4's
|
||||
* defaults rule) — this writes exactly the row it is given.
|
||||
*/
|
||||
export interface NewPlaceShadowPickRow {
|
||||
query: string;
|
||||
lang: string | null;
|
||||
bias_lat: number | null;
|
||||
bias_lng: number | null;
|
||||
source: string;
|
||||
live_rank: number;
|
||||
live_count: number;
|
||||
picked_name: string;
|
||||
picked_lat: number;
|
||||
picked_lng: number;
|
||||
picked_place_id: string | null;
|
||||
}
|
||||
|
||||
export class PlaceShadowPicksRepository extends TrekRepository<PlaceShadowPicks> {
|
||||
/** `INSERT INTO place_shadow_picks (query, lang, bias_lat, bias_lng, source, live_rank, live_count, picked_name, picked_lat, picked_lng, picked_place_id) VALUES (?×11)` (PS2). `this.insert`, no read-back — the caller (`record()`) only needs to know the write happened. */
|
||||
async insertPick(row: NewPlaceShadowPickRow): Promise<void> {
|
||||
await this.insert({ ...row });
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT * FROM place_shadow_picks WHERE id > ? ORDER BY id LIMIT ?`
|
||||
* (`place-shadow.service.ts:124-131`, PS3) — `size` is the PAGE size; this
|
||||
* fetches `size + 1` rows (the keyset-pagination probe row the caller uses
|
||||
* to compute `nextAfter`), matching the legacy statement's own `LIMIT
|
||||
* size + 1` exactly. Caller does the `after ?? 0` defaulting and the
|
||||
* `min(max(1, limit), EXPORT_PAGE_SIZE)` clamp (D4's defaults rule).
|
||||
*/
|
||||
async page(after: number, size: number): Promise<PlaceShadowPickRow[]> {
|
||||
const rows = await this.find({ id: { $gt: after } }, { orderBy: { id: 'asc' }, limit: size + 1 });
|
||||
return rows.map((r) => toRow(r) as PlaceShadowPickRow);
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT COUNT(*) AS total, MIN(created_at) AS oldest, MAX(created_at) AS newest
|
||||
* FROM place_shadow_picks` (`place-shadow.service.ts:143-145`, PS4) — one
|
||||
* row, always (SQLite's bare aggregate SELECT never returns zero rows),
|
||||
* so `total` defaults to `0`/`oldest`/`newest` to `null` only for
|
||||
* type-safety against an `undefined` row, not because the query itself
|
||||
* can come back empty.
|
||||
*/
|
||||
async totals(): Promise<{ total: number; oldest: string | null; newest: string | null }> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const row = await this.qb('p')
|
||||
.select([countAll(platform, 'total'), minOf(platform, 'p.created_at', 'oldest'), maxOf(platform, 'p.created_at', 'newest')])
|
||||
.execute<{ total: number; oldest: string | null; newest: string | null } | undefined>('get', false);
|
||||
return { total: row?.total ?? 0, oldest: row?.oldest ?? null, newest: row?.newest ?? null };
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT source, COUNT(*) AS count FROM place_shadow_picks GROUP BY source
|
||||
* ORDER BY count DESC` (PS5). The `ORDER BY` is applied in JS, not SQL:
|
||||
* MikroORM's QueryBuilder cannot order by an ad-hoc raw-fragment alias
|
||||
* (`countAll`'s `RawQueryFragment` return type carries no alias literal for
|
||||
* `ExtractRawAliases` to pick up, so `.orderBy({ count: 'desc' })` throws
|
||||
* "not existing property" at runtime, verified directly) — `Array.prototype
|
||||
* .sort` is stable (ES2019+), so this produces the identical final row
|
||||
* order the legacy `ORDER BY count DESC` did.
|
||||
*/
|
||||
async countBySource(): Promise<{ source: string; count: number }[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.qb('p')
|
||||
.select(['p.source', countAll(platform, 'count')])
|
||||
.groupBy('p.source')
|
||||
.execute<{ source: string; count: number }[]>('all', false);
|
||||
return [...rows].sort((a, b) => b.count - a.count);
|
||||
}
|
||||
|
||||
/** `SELECT live_rank, COUNT(*) AS count FROM place_shadow_picks GROUP BY live_rank` (PS6) — no ORDER BY, matching the legacy statement; the caller buckets the rows itself. */
|
||||
async countByLiveRank(): Promise<{ live_rank: number; count: number }[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
return this.qb('p')
|
||||
.select(['p.live_rank', countAll(platform, 'count')])
|
||||
.groupBy('p.live_rank')
|
||||
.execute<{ live_rank: number; count: number }[]>('all', false);
|
||||
}
|
||||
|
||||
/** `DELETE FROM place_shadow_picks` (PS7) — the admin wipe. Returns the affected-row count. */
|
||||
async deleteAll(): Promise<number> {
|
||||
return this.nativeDelete({});
|
||||
}
|
||||
|
||||
/**
|
||||
* `` DELETE FROM place_shadow_picks WHERE created_at < datetime('now', ?) ``
|
||||
* with `` `-${retentionDays} days` `` bound as a parameter
|
||||
* (`place-shadow.service.ts:190-193`, PS8) — `nowMinusDays` renders the
|
||||
* equivalent `datetime('now', '-N days')` fragment (it cannot bind the
|
||||
* modifier as a parameter the way the legacy statement did; see the
|
||||
* helper's own docstring). Returns the affected-row count.
|
||||
*/
|
||||
async purgeOlderThan(retentionDays: number): Promise<number> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
return this.nativeDelete({ created_at: { $lt: nowMinusDays(platform, retentionDays) } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Places } from '../entities/Places.entity';
|
||||
import type { Tags } from '../entities/Tags.entity';
|
||||
import { columnRef } from '../dialect/sql-functions';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
@@ -121,17 +122,37 @@ export class PlacesRepository extends TrekRepository<Places> {
|
||||
.where('p.id = ?', [place_id])
|
||||
.execute<TagRow[]>('all', false);
|
||||
|
||||
// Task 0b review B1 (HIGH, live regression): `.select(['pr.user', ...])`
|
||||
// makes MikroORM resolve `pr.user` through the ACTIVE `join('pr.user',
|
||||
// 'u')` and emit the joined entity's own PK under its join alias
|
||||
// (`u__id`), not the FK scalar (`user_id`) — `ratings[].user_id` never
|
||||
// existed at runtime, silently breaking the client's
|
||||
// `ratings.find(r => r.user_id === currentUserId)` own-rating lookup.
|
||||
// `columnRef(...).as('user_id')` routes the FK column through the
|
||||
// dialect layer and aliases it back explicitly; `'pr.user_id'` (the
|
||||
// `persist(false)` scalar mirror) was tried and silently drops the
|
||||
// column, `'pr.user as user_id'` was tried and is still `u__id` — both
|
||||
// verified directly, not assumed (same finding independently reproduced
|
||||
// in `PlaceRatingsRepository.listForPlaces`'s docstring, Plan 3c Task 1).
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const ratings = await this.qb('p')
|
||||
.join('p.place_ratings_collection', 'pr')
|
||||
.join('pr.user', 'u')
|
||||
.select(['pr.user', 'u.username', 'u.avatar', 'pr.rating'])
|
||||
.select([columnRef(platform, 'pr.user_id').as('user_id'), 'u.username', 'u.avatar', 'pr.rating'])
|
||||
.where('p.id = ?', [place_id])
|
||||
.orderBy({ 'pr.created_at': 'asc' })
|
||||
.execute<PlaceRatingRow[]>('all', false);
|
||||
|
||||
const { category_name, category_color, category_icon, ...placeRest } = place;
|
||||
// Task 0b review B2 (HIGH, live regression): the legacy `getPlaceWithTags`
|
||||
// returned `{ ...place, category: ... }` over the raw driver row of
|
||||
// `SELECT p.*, c.name as category_name, c.color as category_color, c.icon
|
||||
// as category_icon` — the three alias columns ride along on the wire
|
||||
// body (map popups, dashboard, shared-trip page all read them flat, per
|
||||
// the review's blast-radius list). Read them, don't strip them: spread
|
||||
// `place` whole, not `placeRest`.
|
||||
const { category_name, category_color, category_icon } = place;
|
||||
return {
|
||||
...placeRest,
|
||||
...place,
|
||||
category: place.category_id
|
||||
? { id: place.category_id, name: category_name!, color: category_color!, icon: category_icon! }
|
||||
: null,
|
||||
@@ -141,4 +162,23 @@ export class PlacesRepository extends TrekRepository<Places> {
|
||||
rating_count: ratings.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT 1 FROM places WHERE google_place_id = ? OR image_url = ? LIMIT 1`
|
||||
* — the `places`-owned half of `PlacePhotoCacheService.isReferenced`
|
||||
* (`place-photo-cache.service.ts:205-211`, PP6), split per the Plan 3c
|
||||
* Task 1 PP6 ruling (option 2): the legacy single `UNION ALL … LIMIT 1`
|
||||
* statement spans this table AND `collection_places` (Plan 3h's), so the
|
||||
* service evaluates this half first and only runs the `collection_places`
|
||||
* half when this one is `false` — reproducing the legacy `UNION ALL …
|
||||
* LIMIT 1`'s short-circuit by evaluation order rather than by SQL.
|
||||
*/
|
||||
async existsByGoogleIdOrImageUrl(googlePlaceId: string, imageUrl: string): Promise<boolean> {
|
||||
const row = await this.qb('p')
|
||||
.select(['p.id'])
|
||||
.where({ $or: [{ google_place_id: googlePlaceId }, { image_url: imageUrl }] })
|
||||
.limit(1)
|
||||
.execute<{ id: number } | undefined>('get', false);
|
||||
return !!row;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,22 @@ export interface TagRow {
|
||||
|
||||
const _tagRowKeys: AssertRowKeys<TagRow, Tags> = true;
|
||||
|
||||
/**
|
||||
* One tag attached to one place, from `QueryHelpersService.loadTagsByPlaceIds`
|
||||
* (QH1). `user_id` is present only on the non-compact projection — `listForPlaces`
|
||||
* selects a narrower column set when `compact` is set, so a compact row never
|
||||
* carries the key at all (matching the legacy's destructuring, which drops it
|
||||
* rather than nulling it).
|
||||
*/
|
||||
export interface TagForPlaceRow {
|
||||
place_id: number;
|
||||
id: number;
|
||||
user_id?: number;
|
||||
name: string;
|
||||
color: string | null;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
export class TagsRepository extends TrekRepository<Tags> {
|
||||
/**
|
||||
* `SELECT * FROM tags WHERE user_id = ? ORDER BY name ASC`, via the shared
|
||||
@@ -115,10 +131,36 @@ export class TagsRepository extends TrekRepository<Tags> {
|
||||
return this.nativeDelete({ id });
|
||||
}
|
||||
|
||||
// `loadForPlaces` (a batch `findByPlaceIds`-style tag loader) is reserved
|
||||
// here for Plan 3c, which moves QueryHelpersService's tag batch loader
|
||||
// (`query-helpers.service.ts:42`, `SELECT t.*, pt.place_id FROM tags t …`)
|
||||
// onto TagsRepository (spec D4). Not implemented in Plan 3a Task 3 — no
|
||||
// throwing stub, just this reservation, so `nest/places`'s later migration
|
||||
// doesn't duplicate the method name.
|
||||
/**
|
||||
* `SELECT t.*, pt.place_id FROM tags t JOIN place_tags pt ON t.id = pt.tag_id
|
||||
* WHERE pt.place_id IN (${…})` (`query-helpers.service.ts:41-45`, QH1) —
|
||||
* ONE method, TWO projections (Plan 3c Task 1 ruling): `compact` selects
|
||||
* `{id, name, color, created_at, place_id}`; the non-compact path selects
|
||||
* every `tags` column except the join key (`{id, user_id, name, color,
|
||||
* created_at, place_id}`), exactly the legacy's `t.*` minus `place_id`.
|
||||
*
|
||||
* Joined through `t.place_tags_inverse` (the inverse side of `Places.place_tags`,
|
||||
* a many-to-many over the `place_tags` pivot table): selecting the joined
|
||||
* place's own `id` as `place_id` is the same value the legacy's `pt.place_id`
|
||||
* read off the pivot row directly (the pivot's `place_id` column IS the
|
||||
* places row it points at), so this is not an approximation.
|
||||
*
|
||||
* Empty `placeIds` short-circuits before any query, matching the legacy
|
||||
* service method.
|
||||
*/
|
||||
async listForPlaces(placeIds: number[], options?: { compact?: boolean }): Promise<TagForPlaceRow[]> {
|
||||
if (placeIds.length === 0) return [];
|
||||
if (options?.compact) {
|
||||
return this.qb('t')
|
||||
.join('t.place_tags_inverse', 'p')
|
||||
.select(['t.id', 't.name', 't.color', 't.created_at', 'p.id as place_id'])
|
||||
.where({ 'p.id': { $in: placeIds } })
|
||||
.execute<TagForPlaceRow[]>('all', false);
|
||||
}
|
||||
return this.qb('t')
|
||||
.join('t.place_tags_inverse', 'p')
|
||||
.select(['t.id', 't.user', 't.name', 't.color', 't.created_at', 'p.id as place_id'])
|
||||
.where({ 'p.id': { $in: placeIds } })
|
||||
.execute<TagForPlaceRow[]>('all', false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,4 +42,45 @@ export class TripMembersRepository extends TrekRepository<TripMembers> {
|
||||
if (owner) ids.add(owner.user_id);
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT user_id FROM trip_members WHERE trip_id = ? ORDER BY added_at ASC`
|
||||
* (`trip-membership.service.ts:29-31`, TB2) — the owner is excluded by
|
||||
* construction (the table has no row for the owner), matching the legacy
|
||||
* statement exactly. Raw-bind (D4's T5 escape hatch), the same
|
||||
* `number | string` seam `TripsRepository.findAccessible` documents.
|
||||
*/
|
||||
async listUserIdsByTrip(trip_id: number | string): Promise<number[]> {
|
||||
const rows = await this.qb('m')
|
||||
.select(['m.user'])
|
||||
.where('m.trip_id = ?', [trip_id])
|
||||
.orderBy({ 'm.added_at': 'asc' })
|
||||
.execute<{ user_id: number }[]>('all', false);
|
||||
return rows.map((r) => r.user_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?`
|
||||
* (`trip-membership.service.ts:70`, TB5) — `joinTripAsMember`'s
|
||||
* already-a-member check, the second leg of the non-transactional
|
||||
* check-then-act sequence (§18.4: unchanged by this conversion). Both
|
||||
* callers (`TripMembershipService.joinTripAsMember`) always pass real
|
||||
* `number`s, so no raw-bind seam here.
|
||||
*/
|
||||
async exists(trip_id: number, user_id: number): Promise<boolean> {
|
||||
const row = await this.qb('m')
|
||||
.select(['m.id'])
|
||||
.where({ trip: trip_id, user: user_id })
|
||||
.execute<{ id: number } | undefined>('get', false);
|
||||
return !!row;
|
||||
}
|
||||
|
||||
/**
|
||||
* `INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)`
|
||||
* (`trip-membership.service.ts:72`, TB6) — the third leg of the same
|
||||
* non-transactional sequence as `exists` above; `invitedBy` may be `null`.
|
||||
*/
|
||||
async addMember(trip_id: number, user_id: number, invitedBy: number | null): Promise<void> {
|
||||
await this.insert({ trip: trip_id, user: user_id, invited_by: invitedBy });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,25 @@ export interface TripAccess {
|
||||
}
|
||||
|
||||
export class TripsRepository extends TrekRepository<Trips> {
|
||||
/**
|
||||
* The `LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
|
||||
* WHERE (t.user_id = ? OR m.user_id IS NOT NULL)` half `findAccessible`
|
||||
* and `listAccessibleIds` (Plan 3c Task 1, TB3) share — one join builder,
|
||||
* per the task brief's ruling that the two must derive from the same
|
||||
* source rather than hand-keeping two copies in sync (the cross-plan note
|
||||
* in the inventory: TB3 and `TripsService.list`'s id half are "the same
|
||||
* query with different projections"). No explicit return-type annotation,
|
||||
* for the same inference reason `TrekRepository.kysely()` gives (the
|
||||
* QueryBuilder's fluent generic parameters do not survive being spelled
|
||||
* out via a separate type alias) — every caller chains `.select()`/
|
||||
* `.where()`/`.orderBy()` straight off this method's return value.
|
||||
*/
|
||||
private accessibleTripsQuery(user_id: number) {
|
||||
return this.qb('t')
|
||||
.leftJoin('t.trip_members_collection', 'm', { 'm.user': user_id })
|
||||
.andWhere({ $or: [{ 't.user': user_id }, { 'm.user': { $ne: null } }] });
|
||||
}
|
||||
|
||||
/**
|
||||
* The trip if the user owns it or is a member of it, else undefined.
|
||||
*
|
||||
@@ -30,9 +49,8 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* affinity comparison of the unconverted string never matches one).
|
||||
*/
|
||||
async findAccessible(trip_id: number | string, user_id: number): Promise<TripAccess | undefined> {
|
||||
const row = await this.qb('t')
|
||||
const row = await this.accessibleTripsQuery(user_id)
|
||||
.select(['t.id', 't.user', 't.currency'])
|
||||
.leftJoin('t.trip_members_collection', 'm', { 'm.user': user_id })
|
||||
// Raw condition (D4's T5 escape hatch), not `.where({ 't.id': trip_id })`:
|
||||
// MikroORM's typed filter rejects a `string` against `t.id`'s branded
|
||||
// `number` type, and coercing to `Number(trip_id)` first would be
|
||||
@@ -40,8 +58,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
// `t.id`/`t.user_id` are the physical column names (not translated
|
||||
// through the entity's `trip`/`user` property aliasing the way a typed
|
||||
// filter object is), so the raw text names them directly.
|
||||
.where('t.id = ?', [trip_id])
|
||||
.andWhere({ $or: [{ 't.user': user_id }, { 'm.user': { $ne: null } }] })
|
||||
.andWhere('t.id = ?', [trip_id])
|
||||
// `mapResults: false` leaves the driver's row alone: the keys are the
|
||||
// column names, which is why the result type is spelled out here rather
|
||||
// than inferred from the entity's properties.
|
||||
@@ -69,4 +86,50 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
.execute<{ id: number } | undefined>('get', false);
|
||||
return !!row;
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT user_id FROM trips WHERE id = ?` (`trip-membership.service.ts:23`,
|
||||
* TB1) — `row ? row.user_id : null` stays the caller's decision to make
|
||||
* ("owner id for budget/MCP guards"); this returns exactly that shape.
|
||||
* Raw-bind (D4's T5 escape hatch), same `number | string` seam as
|
||||
* `findAccessible`/`isOwner` above.
|
||||
*/
|
||||
async getOwnerId(trip_id: number | string): Promise<number | null> {
|
||||
const row = await this.qb('t')
|
||||
.select(['t.user'])
|
||||
.where('t.id = ?', [trip_id])
|
||||
.execute<{ user_id: number } | undefined>('get', false);
|
||||
return row ? row.user_id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT id, user_id FROM trips WHERE id = ?` (`trip-membership.service.ts:66`,
|
||||
* TB4) — `joinTripAsMember`'s first check-then-act read (§18.4: the
|
||||
* sequence stays non-transactional, unchanged by this conversion). The
|
||||
* only caller (`TripMembershipService.joinTripAsMember(tripId: number, …)`)
|
||||
* always passes a real `number`, so this takes one too — no raw-bind seam
|
||||
* to preserve here, unlike `findAccessible`/`isOwner`/`getOwnerId`.
|
||||
*/
|
||||
async findIdAndOwner(trip_id: number): Promise<{ id: number; user_id: number } | undefined> {
|
||||
return this.qb('t')
|
||||
.select(['t.id', 't.user'])
|
||||
.where({ id: trip_id })
|
||||
.execute<{ id: number; user_id: number } | undefined>('get', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT t.id FROM trips t LEFT JOIN trip_members m ON m.trip_id = t.id
|
||||
* AND m.user_id = :userId WHERE (t.user_id = :userId OR m.user_id IS NOT NULL)
|
||||
* ORDER BY t.created_at DESC` (`trip-membership.service.ts:40-46`, TB3) —
|
||||
* the id half of `TripsService.list(userId, null)`, sharing `findAccessible`'s
|
||||
* join builder per the task brief's ruling (this class's `accessibleTripsQuery`
|
||||
* above).
|
||||
*/
|
||||
async listAccessibleIds(user_id: number): Promise<number[]> {
|
||||
const rows = await this.accessibleTripsQuery(user_id)
|
||||
.select(['t.id'])
|
||||
.orderBy({ 't.created_at': 'desc' })
|
||||
.execute<{ id: number }[]>('all', false);
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { PlacePhotosModule } from '../place-photos/place-photos.module';
|
||||
import { RateLimitModule } from '../common/rate-limit.module';
|
||||
import { PlaceEnrichmentController } from './place-enrichment.controller';
|
||||
import { PlaceEnrichmentService } from './place-enrichment.service';
|
||||
import { PlaceDetailsCache } from '../../db/entities/PlaceDetailsCache.entity';
|
||||
import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
|
||||
/**
|
||||
* Place enrichment (L4 leaf module). Registered in AppModule.
|
||||
@@ -13,9 +16,13 @@ import { PlaceEnrichmentService } from './place-enrichment.service';
|
||||
* matters here: the photo cache's stampede guard and the maps concurrency limit
|
||||
* only hold if this module queues behind the same ones everything else uses.
|
||||
* Nothing outside the container consumes it, so there is no bridge.
|
||||
*
|
||||
* MikroOrmModule.forFeature registers PlaceDetailsCacheRepository/
|
||||
* AppSettingsRepository for PlaceEnrichmentService's @InjectRepository
|
||||
* constructor (Plan 3c Task 1).
|
||||
*/
|
||||
@Module({
|
||||
imports: [MapsModule, PlacePhotosModule, RateLimitModule],
|
||||
imports: [MapsModule, PlacePhotosModule, RateLimitModule, MikroOrmModule.forFeature([PlaceDetailsCache, AppSettings])],
|
||||
controllers: [PlaceEnrichmentController],
|
||||
providers: [PlaceEnrichmentService],
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { placeWebsiteSchema } from '@trek/shared';
|
||||
import type {
|
||||
MapsPlaceEnrichmentRequest,
|
||||
@@ -11,7 +12,10 @@ import type {
|
||||
PlaceRating,
|
||||
} from '@trek/shared';
|
||||
import { safeFetchFollow } from '../../utils/ssrfGuard';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { PlaceDetailsCache } from '../../db/entities/PlaceDetailsCache.entity';
|
||||
import type { PlaceDetailsCacheRepository } from '../../db/repositories/PlaceDetailsCache.repository';
|
||||
import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
|
||||
import {
|
||||
MapsService,
|
||||
isGoogleMapsHost,
|
||||
@@ -307,7 +311,8 @@ export function collectRating(details: Record<string, unknown> | null): PlaceRat
|
||||
@Injectable()
|
||||
export class PlaceEnrichmentService {
|
||||
constructor(
|
||||
private readonly database: DatabaseService,
|
||||
@InjectRepository(PlaceDetailsCache) private readonly cache: PlaceDetailsCacheRepository,
|
||||
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
|
||||
private readonly maps: MapsService,
|
||||
private readonly photoCache: PlacePhotoCacheService,
|
||||
) {}
|
||||
@@ -319,8 +324,8 @@ export class PlaceEnrichmentService {
|
||||
* working, and there is nothing here that warrants a migration.
|
||||
*/
|
||||
async enrichDisabled(): Promise<boolean> {
|
||||
const row = this.database.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', 'places_enrich_enabled');
|
||||
return row?.value === 'false';
|
||||
const value = await this.appSettings.getValue('places_enrich_enabled');
|
||||
return value === 'false';
|
||||
}
|
||||
|
||||
async enrich(userId: number, req: MapsPlaceEnrichmentRequest): Promise<MapsPlaceEnrichmentResult> {
|
||||
@@ -807,12 +812,7 @@ export class PlaceEnrichmentService {
|
||||
|
||||
private async readCache(placeId: string, lang: string | undefined): Promise<CachedEnrichment | null> {
|
||||
try {
|
||||
const row = this.database.get<{ payload_json: string; fetched_at: number }>(
|
||||
'SELECT payload_json, fetched_at FROM place_details_cache WHERE place_id = ? AND lang = ? AND expanded = ?',
|
||||
placeId,
|
||||
lang ?? '',
|
||||
CACHE_KIND,
|
||||
);
|
||||
const row = await this.cache.findEntry(placeId, lang ?? '', CACHE_KIND);
|
||||
if (!row) return null;
|
||||
const parsed = JSON.parse(row.payload_json) as CachePayload;
|
||||
if (parsed.v !== CACHE_VERSION) return null;
|
||||
@@ -844,14 +844,13 @@ export class PlaceEnrichmentService {
|
||||
|
||||
private async writeCache(placeId: string, lang: string | undefined, value: CachedEnrichment): Promise<void> {
|
||||
try {
|
||||
this.database.run(
|
||||
'INSERT OR REPLACE INTO place_details_cache (place_id, lang, expanded, payload_json, fetched_at) VALUES (?, ?, ?, ?, ?)',
|
||||
placeId,
|
||||
lang ?? '',
|
||||
CACHE_KIND,
|
||||
JSON.stringify({ ...value, v: CACHE_VERSION } satisfies CachePayload),
|
||||
Date.now(),
|
||||
);
|
||||
await this.cache.upsertEntry({
|
||||
place_id: placeId,
|
||||
lang: lang ?? '',
|
||||
expanded: CACHE_KIND,
|
||||
payload_json: JSON.stringify({ ...value, v: CACHE_VERSION } satisfies CachePayload),
|
||||
fetched_at: Date.now(),
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to cache place enrichment:', err);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Jimp, JimpMime } from 'jimp';
|
||||
import crypto from 'node:crypto';
|
||||
import { Readable } from 'node:stream';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { GooglePlacePhotoMeta } from '../../db/entities/GooglePlacePhotoMeta.entity';
|
||||
import type { GooglePlacePhotoMetaRepository } from '../../db/repositories/GooglePlacePhotoMeta.repository';
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import type { PlacesRepository } from '../../db/repositories/Places.repository';
|
||||
|
||||
// How long a "no photo for this place" answer stays remembered. Nothing about it
|
||||
// changes until a photo appears upstream, so it is worth keeping: without it every
|
||||
@@ -46,6 +51,11 @@ interface CachedPhoto {
|
||||
* The registry's mode-aware prefix reproduces both TREK_PLACE_PHOTO_DIR
|
||||
* layouts (unset: uploads/photos/google; set: that dir, bare keys), so the
|
||||
* cache itself is mode-agnostic.
|
||||
*
|
||||
* `DatabaseService` stays injected (Plan 3c Task 1, PP6 ruling option 2)
|
||||
* purely for the `collection_places` half of `isReferenced` — that table is
|
||||
* Plan 3h's, so it stays a raw statement with a `// Plan 3h` comment until
|
||||
* then. Every other statement in this file is repository-backed.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlacePhotoCacheService {
|
||||
@@ -59,6 +69,8 @@ export class PlacePhotoCacheService {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly storage: StorageService,
|
||||
@InjectRepository(GooglePlacePhotoMeta) private readonly meta: GooglePlacePhotoMetaRepository,
|
||||
@InjectRepository(Places) private readonly places: PlacesRepository,
|
||||
) {}
|
||||
|
||||
private fileName(placeId: string): string {
|
||||
@@ -73,10 +85,7 @@ export class PlacePhotoCacheService {
|
||||
}
|
||||
|
||||
async get(placeId: string): Promise<CachedPhoto | null> {
|
||||
const row = this.db.get<{ attribution: string | null }>(
|
||||
'SELECT attribution FROM google_place_photo_meta WHERE place_id = ? AND error_at IS NULL',
|
||||
placeId,
|
||||
);
|
||||
const row = await this.meta.findLive(placeId);
|
||||
|
||||
if (!row) return null;
|
||||
|
||||
@@ -84,7 +93,7 @@ export class PlacePhotoCacheService {
|
||||
// First time this placeId is checked this session — verify the object exists.
|
||||
// (Guards against volume wipes or manual deletion between server restarts.)
|
||||
if (!(await this.storage.exists('photos-google', this.fileName(placeId)))) {
|
||||
this.db.run('DELETE FROM google_place_photo_meta WHERE place_id = ?', placeId);
|
||||
await this.meta.deleteByPlaceId(placeId);
|
||||
return null;
|
||||
}
|
||||
this.knownOnDisk.add(placeId);
|
||||
@@ -100,10 +109,7 @@ export class PlacePhotoCacheService {
|
||||
this.recentFailures.delete(placeId);
|
||||
}
|
||||
|
||||
const row = this.db.get<{ error_at: number }>(
|
||||
'SELECT error_at FROM google_place_photo_meta WHERE place_id = ? AND error_at IS NOT NULL',
|
||||
placeId,
|
||||
);
|
||||
const row = await this.meta.findErrored(placeId);
|
||||
|
||||
if (!row) return false;
|
||||
return Date.now() - row.error_at < MISSING_TTL;
|
||||
@@ -128,10 +134,7 @@ export class PlacePhotoCacheService {
|
||||
|
||||
this.recentFailures.delete(placeId);
|
||||
this.knownOnDisk.delete(placeId);
|
||||
this.db.run(
|
||||
'INSERT OR REPLACE INTO google_place_photo_meta (place_id, attribution, fetched_at, error_at) VALUES (?, NULL, ?, ?)',
|
||||
placeId, Date.now(), Date.now(),
|
||||
);
|
||||
await this.meta.upsertError(placeId, Date.now());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,10 +161,7 @@ export class PlacePhotoCacheService {
|
||||
this.knownOnDisk.add(placeId);
|
||||
this.recentFailures.delete(placeId);
|
||||
|
||||
this.db.run(
|
||||
'INSERT OR REPLACE INTO google_place_photo_meta (place_id, attribution, fetched_at, error_at) VALUES (?, ?, ?, NULL)',
|
||||
placeId, attribution, Date.now(),
|
||||
);
|
||||
await this.meta.upsertPhoto(placeId, attribution, Date.now());
|
||||
|
||||
return { photoUrl: this.proxyUrl(placeId), attribution };
|
||||
}
|
||||
@@ -200,14 +200,20 @@ export class PlacePhotoCacheService {
|
||||
* the google_place_id itself, so collection_places must count as a referencing
|
||||
* table — otherwise the nightly sweep + trip-place delete would evict a photo
|
||||
* still shown on a collection thumbnail (#1081 photo-cache pitfall).
|
||||
*
|
||||
* Plan 3c Task 1 PP6 ruling (option 2): the legacy single `UNION ALL … LIMIT 1`
|
||||
* statement spans `places` (this plan's) and `collection_places` (Plan 3h's),
|
||||
* so it is split into two existence checks, evaluated in the SAME order the
|
||||
* legacy `UNION ALL … LIMIT 1` would short-circuit in — the `collection_places`
|
||||
* half only runs when the `places` half comes back false.
|
||||
*/
|
||||
private async isReferenced(placeId: string): Promise<boolean> {
|
||||
const proxyUrl = this.proxyUrl(placeId);
|
||||
if (await this.places.existsByGoogleIdOrImageUrl(placeId, proxyUrl)) return true;
|
||||
// Plan 3h: collection_places is not yet repository-backed.
|
||||
const row = this.db.get(
|
||||
`SELECT 1 FROM places WHERE google_place_id = ? OR image_url = ?
|
||||
UNION ALL
|
||||
SELECT 1 FROM collection_places WHERE google_place_id = ? OR image_url = ?
|
||||
LIMIT 1`,
|
||||
placeId, this.proxyUrl(placeId), placeId, this.proxyUrl(placeId),
|
||||
`SELECT 1 FROM collection_places WHERE google_place_id = ? OR image_url = ? LIMIT 1`,
|
||||
placeId, proxyUrl,
|
||||
);
|
||||
return !!row;
|
||||
}
|
||||
@@ -216,7 +222,7 @@ export class PlacePhotoCacheService {
|
||||
await this.storage.delete('photos-google', this.fileName(placeId)).catch(() => {
|
||||
/* already gone */
|
||||
});
|
||||
this.db.run('DELETE FROM google_place_photo_meta WHERE place_id = ?', placeId);
|
||||
await this.meta.deleteByPlaceId(placeId);
|
||||
this.knownOnDisk.delete(placeId);
|
||||
}
|
||||
|
||||
@@ -236,9 +242,9 @@ export class PlacePhotoCacheService {
|
||||
async sweepOrphans(): Promise<number> {
|
||||
let removed = 0;
|
||||
|
||||
const rows = this.db.all<{ place_id: string }>('SELECT place_id FROM google_place_photo_meta');
|
||||
const placeIds = await this.meta.listPlaceIds();
|
||||
const keepFiles = new Set<string>();
|
||||
for (const { place_id } of rows) {
|
||||
for (const place_id of placeIds) {
|
||||
if (await this.isReferenced(place_id)) {
|
||||
keepFiles.add(this.fileName(place_id));
|
||||
} else {
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { PlacePhotoCacheService } from './place-photo-cache.service';
|
||||
import { PlacePhotoCacheJob } from './place-photo-cache.job';
|
||||
import { AppConfigModule } from '../app-config/app-config.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { GooglePlacePhotoMeta } from '../../db/entities/GooglePlacePhotoMeta.entity';
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
|
||||
/** The marker-photo cache. No controller of its own — maps serves the bytes,
|
||||
* places and share read through it, and PlacePhotoCacheJob sweeps it nightly.
|
||||
*
|
||||
* Deliberately NOT @Global (permissions precedent), and AppConfigModule is
|
||||
* imported explicitly because @Global only reaches modules that are in the
|
||||
* graph — which a single-domain e2e TestingModule is not. */
|
||||
* graph — which a single-domain e2e TestingModule is not.
|
||||
*
|
||||
* MikroOrmModule.forFeature registers GooglePlacePhotoMetaRepository/
|
||||
* PlacesRepository for PlacePhotoCacheService's @InjectRepository
|
||||
* constructor (Plan 3c Task 1). */
|
||||
@Module({
|
||||
imports: [AppConfigModule, SchedulingModule, StorageModule],
|
||||
imports: [AppConfigModule, SchedulingModule, StorageModule, MikroOrmModule.forFeature([GooglePlacePhotoMeta, Places])],
|
||||
providers: [PlacePhotoCacheService, PlacePhotoCacheJob],
|
||||
exports: [PlacePhotoCacheService],
|
||||
})
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { PlaceShadowController } from './place-shadow.controller';
|
||||
import { PlaceShadowRetentionJob } from './place-shadow.job';
|
||||
import { PlaceShadowService } from './place-shadow.service';
|
||||
import { PlaceShadowPicks } from '../../db/entities/PlaceShadowPicks.entity';
|
||||
import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
|
||||
/**
|
||||
* Place shadow log. Registered in AppModule; exports the service so the admin
|
||||
* surface can read the summary without going through HTTP.
|
||||
*
|
||||
* MikroOrmModule.forFeature registers PlaceShadowPicksRepository/
|
||||
* AppSettingsRepository for PlaceShadowService's @InjectRepository
|
||||
* constructor (Plan 3c Task 1).
|
||||
*/
|
||||
@Module({
|
||||
imports: [SchedulingModule],
|
||||
imports: [SchedulingModule, MikroOrmModule.forFeature([PlaceShadowPicks, AppSettings])],
|
||||
controllers: [PlaceShadowController],
|
||||
providers: [PlaceShadowService, PlaceShadowRetentionJob],
|
||||
exports: [PlaceShadowService],
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import type {
|
||||
PlaceShadowExportResult,
|
||||
PlaceShadowPickRequest,
|
||||
PlaceShadowRow,
|
||||
PlaceShadowSummaryResult,
|
||||
} from '@trek/shared';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { PlaceShadowPicks } from '../../db/entities/PlaceShadowPicks.entity';
|
||||
import type { PlaceShadowPicksRepository, PlaceShadowPickRow } from '../../db/repositories/PlaceShadowPicks.repository';
|
||||
import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
|
||||
|
||||
/** Rows older than this are removed nightly. */
|
||||
export const RETENTION_DAYS = 180;
|
||||
@@ -25,23 +29,7 @@ function round(value: number, decimals = COORD_DECIMALS): number {
|
||||
return Math.round(value * f) / f;
|
||||
}
|
||||
|
||||
interface DbRow {
|
||||
id: number;
|
||||
created_at: string;
|
||||
query: string;
|
||||
lang: string | null;
|
||||
bias_lat: number | null;
|
||||
bias_lng: number | null;
|
||||
source: string;
|
||||
live_rank: number;
|
||||
live_count: number;
|
||||
picked_name: string;
|
||||
picked_lat: number;
|
||||
picked_lng: number;
|
||||
picked_place_id: string | null;
|
||||
}
|
||||
|
||||
function toRow(r: DbRow): PlaceShadowRow {
|
||||
function toRow(r: PlaceShadowPickRow): PlaceShadowRow {
|
||||
return {
|
||||
id: r.id,
|
||||
createdAt: r.created_at,
|
||||
@@ -72,13 +60,14 @@ function toRow(r: DbRow): PlaceShadowRow {
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceShadowService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
constructor(
|
||||
@InjectRepository(PlaceShadowPicks) private readonly picks: PlaceShadowPicksRepository,
|
||||
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
|
||||
) {}
|
||||
|
||||
async enabled(): Promise<boolean> {
|
||||
const row = this.db.get<{ value: string }>(
|
||||
"SELECT value FROM app_settings WHERE key = 'place_shadow_enabled'",
|
||||
);
|
||||
return row?.value === 'true';
|
||||
const value = await this.appSettings.getValue('place_shadow_enabled');
|
||||
return value === 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -94,23 +83,19 @@ export class PlaceShadowService {
|
||||
// corpus exists to produce, so the row is dropped instead.
|
||||
if (pick.liveRank >= pick.liveCount) return false;
|
||||
|
||||
this.db.run(
|
||||
`INSERT INTO place_shadow_picks
|
||||
(query, lang, bias_lat, bias_lng, source, live_rank, live_count,
|
||||
picked_name, picked_lat, picked_lng, picked_place_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
pick.query,
|
||||
pick.lang ?? null,
|
||||
pick.biasLat === undefined ? null : round(pick.biasLat),
|
||||
pick.biasLng === undefined ? null : round(pick.biasLng),
|
||||
pick.source,
|
||||
pick.liveRank,
|
||||
pick.liveCount,
|
||||
pick.pickedName,
|
||||
round(pick.pickedLat),
|
||||
round(pick.pickedLng),
|
||||
pick.pickedPlaceId ?? null,
|
||||
);
|
||||
await this.picks.insertPick({
|
||||
query: pick.query,
|
||||
lang: pick.lang ?? null,
|
||||
bias_lat: pick.biasLat === undefined ? null : round(pick.biasLat),
|
||||
bias_lng: pick.biasLng === undefined ? null : round(pick.biasLng),
|
||||
source: pick.source,
|
||||
live_rank: pick.liveRank,
|
||||
live_count: pick.liveCount,
|
||||
picked_name: pick.pickedName,
|
||||
picked_lat: round(pick.pickedLat),
|
||||
picked_lng: round(pick.pickedLng),
|
||||
picked_place_id: pick.pickedPlaceId ?? null,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -121,14 +106,7 @@ export class PlaceShadowService {
|
||||
*/
|
||||
async export(after?: number, limit = EXPORT_PAGE_SIZE): Promise<PlaceShadowExportResult> {
|
||||
const size = Math.min(Math.max(1, limit), EXPORT_PAGE_SIZE);
|
||||
const rows = this.db.all<DbRow>(
|
||||
`SELECT * FROM place_shadow_picks
|
||||
WHERE id > ?
|
||||
ORDER BY id
|
||||
LIMIT ?`,
|
||||
after ?? 0,
|
||||
size + 1,
|
||||
);
|
||||
const rows = await this.picks.page(after ?? 0, size);
|
||||
const page = rows.slice(0, size);
|
||||
return {
|
||||
version: 1,
|
||||
@@ -140,22 +118,15 @@ export class PlaceShadowService {
|
||||
|
||||
async summary(): Promise<PlaceShadowSummaryResult> {
|
||||
const enabled = await this.enabled();
|
||||
const totals = this.db.get<{ total: number; oldest: string | null; newest: string | null }>(
|
||||
'SELECT COUNT(*) AS total, MIN(created_at) AS oldest, MAX(created_at) AS newest FROM place_shadow_picks',
|
||||
);
|
||||
const total = totals?.total ?? 0;
|
||||
const totals = await this.picks.totals();
|
||||
const total = totals.total;
|
||||
|
||||
const bySource = this.db.all<{ source: string; count: number }>(
|
||||
`SELECT source, COUNT(*) AS count FROM place_shadow_picks
|
||||
GROUP BY source ORDER BY count DESC`,
|
||||
);
|
||||
const bySource = await this.picks.countBySource();
|
||||
|
||||
// Buckets rather than a mean: the question is "did the user find it near
|
||||
// the top", and an average rank is dragged around by the rare query that
|
||||
// scrolled to result 40.
|
||||
const ranks = this.db.all<{ live_rank: number; count: number }>(
|
||||
'SELECT live_rank, COUNT(*) AS count FROM place_shadow_picks GROUP BY live_rank',
|
||||
);
|
||||
const ranks = await this.picks.countByLiveRank();
|
||||
const counted = (test: (rank: number) => boolean): number =>
|
||||
ranks.filter(r => test(r.live_rank)).reduce((sum, r) => sum + r.count, 0);
|
||||
|
||||
@@ -165,8 +136,8 @@ export class PlaceShadowService {
|
||||
return {
|
||||
enabled,
|
||||
total,
|
||||
oldest: totals?.oldest ?? null,
|
||||
newest: totals?.newest ?? null,
|
||||
oldest: totals.oldest,
|
||||
newest: totals.newest,
|
||||
retentionDays: RETENTION_DAYS,
|
||||
bySource,
|
||||
liveRankBuckets: [
|
||||
@@ -182,15 +153,11 @@ export class PlaceShadowService {
|
||||
|
||||
/** Admin wipe. Returns how many rows went. */
|
||||
async clear(): Promise<number> {
|
||||
return this.db.run('DELETE FROM place_shadow_picks').changes;
|
||||
return this.picks.deleteAll();
|
||||
}
|
||||
|
||||
/** Nightly retention. Returns how many rows went. */
|
||||
async purgeExpired(retentionDays = RETENTION_DAYS): Promise<number> {
|
||||
return this.db.run(
|
||||
`DELETE FROM place_shadow_picks
|
||||
WHERE created_at < datetime('now', ?)`,
|
||||
`-${retentionDays} days`,
|
||||
).changes;
|
||||
return this.picks.purgeOlderThan(retentionDays);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { QueryHelpersService } from './query-helpers.service';
|
||||
import { Tags } from '../../db/entities/Tags.entity';
|
||||
import { PlaceRatings } from '../../db/entities/PlaceRatings.entity';
|
||||
import { AssignmentParticipants } from '../../db/entities/AssignmentParticipants.entity';
|
||||
|
||||
/** Shared batch loaders for the list endpoints. No controller or MCP surface of
|
||||
* its own — assignments, days, places and share import it for the loaders.
|
||||
* Deliberately NOT @Global so e2e TestingModules resolve it transitively
|
||||
* through each consumer's explicit import, same as PermissionsModule. */
|
||||
* through each consumer's explicit import, same as PermissionsModule.
|
||||
*
|
||||
* MikroOrmModule.forFeature registers TagsRepository/PlaceRatingsRepository/
|
||||
* AssignmentParticipantsRepository for QueryHelpersService's
|
||||
* @InjectRepository constructor (Plan 3c Task 1). */
|
||||
@Module({
|
||||
imports: [MikroOrmModule.forFeature([Tags, PlaceRatings, AssignmentParticipants])],
|
||||
providers: [QueryHelpersService],
|
||||
exports: [QueryHelpersService],
|
||||
})
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Tags } from '../../db/entities/Tags.entity';
|
||||
import type { TagsRepository, TagForPlaceRow } from '../../db/repositories/Tags.repository';
|
||||
import { PlaceRatings } from '../../db/entities/PlaceRatings.entity';
|
||||
import type { PlaceRatingsRepository } from '../../db/repositories/PlaceRatings.repository';
|
||||
import { AssignmentParticipants } from '../../db/entities/AssignmentParticipants.entity';
|
||||
import type { AssignmentParticipantsRepository } from '../../db/repositories/AssignmentParticipants.repository';
|
||||
import type { Tag, Participant } from '../../types';
|
||||
|
||||
interface TagRow extends Tag {
|
||||
place_id: number;
|
||||
}
|
||||
|
||||
interface ParticipantRow {
|
||||
assignment_id: number;
|
||||
user_id: number;
|
||||
username: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
export interface PlaceRatingRow {
|
||||
user_id: number;
|
||||
username: string;
|
||||
@@ -22,8 +17,11 @@ export interface PlaceRatingRow {
|
||||
|
||||
/**
|
||||
* The batch loaders that keep the list endpoints off N+1 queries — one query per
|
||||
* collection instead of one per row. Moved 1:1 from services/queryHelpers.ts
|
||||
* (same SQL, same indexing) onto the injected connection.
|
||||
* collection instead of one per row. Plan 3c Task 1: onto `TagsRepository`
|
||||
* (QH1), `PlaceRatingsRepository` (QH2, a Plan 3c-owned table per the
|
||||
* inventory §14.6) and `AssignmentParticipantsRepository` (QH3) — this
|
||||
* service's own first repository test file, since it had none before
|
||||
* (inventory §15c).
|
||||
*
|
||||
* Only the loaders live here. The two pure reshaping functions that shipped in
|
||||
* the same legacy file touch no database and stayed free functions in
|
||||
@@ -31,29 +29,21 @@ export interface PlaceRatingRow {
|
||||
*/
|
||||
@Injectable()
|
||||
export class QueryHelpersService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
constructor(
|
||||
@InjectRepository(Tags) private readonly tags: TagsRepository,
|
||||
@InjectRepository(PlaceRatings) private readonly placeRatings: PlaceRatingsRepository,
|
||||
@InjectRepository(AssignmentParticipants) private readonly assignmentParticipants: AssignmentParticipantsRepository,
|
||||
) {}
|
||||
|
||||
/** Batch-load tags for multiple places in a single query, indexed by place ID. */
|
||||
async loadTagsByPlaceIds(placeIds: number[], { compact }: { compact?: boolean } = {}): Promise<Record<number, Partial<Tag>[]>> {
|
||||
const tagsByPlaceId: Record<number, Partial<Tag>[]> = {};
|
||||
if (placeIds.length > 0) {
|
||||
const placeholders = placeIds.map(() => '?').join(',');
|
||||
const allTags = this.db.all<TagRow>(`
|
||||
SELECT t.*, pt.place_id FROM tags t
|
||||
JOIN place_tags pt ON t.id = pt.tag_id
|
||||
WHERE pt.place_id IN (${placeholders})
|
||||
`, ...placeIds);
|
||||
|
||||
for (const tag of allTags) {
|
||||
const pid = tag.place_id;
|
||||
if (!tagsByPlaceId[pid]) tagsByPlaceId[pid] = [];
|
||||
if (compact) {
|
||||
tagsByPlaceId[pid].push({ id: tag.id, name: tag.name, color: tag.color, created_at: tag.created_at });
|
||||
} else {
|
||||
const { place_id, ...rest } = tag;
|
||||
tagsByPlaceId[pid].push(rest);
|
||||
}
|
||||
}
|
||||
const rows = await this.tags.listForPlaces(placeIds, { compact });
|
||||
for (const tag of rows as TagForPlaceRow[]) {
|
||||
const pid = tag.place_id;
|
||||
if (!tagsByPlaceId[pid]) tagsByPlaceId[pid] = [];
|
||||
const { place_id, ...rest } = tag;
|
||||
tagsByPlaceId[pid].push(rest);
|
||||
}
|
||||
return tagsByPlaceId;
|
||||
}
|
||||
@@ -61,17 +51,10 @@ export class QueryHelpersService {
|
||||
/** Batch-load collaborative ratings (#1435) for multiple places in one query, indexed by place ID. */
|
||||
async loadRatingsByPlaceIds(placeIds: number[]): Promise<Record<number, PlaceRatingRow[]>> {
|
||||
const ratingsByPlaceId: Record<number, PlaceRatingRow[]> = {};
|
||||
if (placeIds.length > 0) {
|
||||
const rows = this.db.all<PlaceRatingRow & { place_id: number }>(`
|
||||
SELECT pr.place_id, pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr
|
||||
JOIN users u ON pr.user_id = u.id
|
||||
WHERE pr.place_id IN (${placeIds.map(() => '?').join(',')})
|
||||
ORDER BY pr.created_at
|
||||
`, ...placeIds);
|
||||
for (const { place_id, ...rest } of rows) {
|
||||
if (!ratingsByPlaceId[place_id]) ratingsByPlaceId[place_id] = [];
|
||||
ratingsByPlaceId[place_id].push(rest);
|
||||
}
|
||||
const rows = await this.placeRatings.listForPlaces(placeIds);
|
||||
for (const { place_id, ...rest } of rows) {
|
||||
if (!ratingsByPlaceId[place_id]) ratingsByPlaceId[place_id] = [];
|
||||
ratingsByPlaceId[place_id].push(rest);
|
||||
}
|
||||
return ratingsByPlaceId;
|
||||
}
|
||||
@@ -79,15 +62,10 @@ export class QueryHelpersService {
|
||||
/** Batch-load participants for multiple day-assignments in a single query, indexed by assignment ID. */
|
||||
async loadParticipantsByAssignmentIds(assignmentIds: number[]): Promise<Record<number, Participant[]>> {
|
||||
const participantsByAssignment: Record<number, Participant[]> = {};
|
||||
if (assignmentIds.length > 0) {
|
||||
const allParticipants = this.db.all<ParticipantRow>(
|
||||
`SELECT ap.assignment_id, ap.user_id, u.username, u.avatar FROM assignment_participants ap JOIN users u ON ap.user_id = u.id WHERE ap.assignment_id IN (${assignmentIds.map(() => '?').join(',')})`,
|
||||
...assignmentIds,
|
||||
);
|
||||
for (const p of allParticipants) {
|
||||
if (!participantsByAssignment[p.assignment_id]) participantsByAssignment[p.assignment_id] = [];
|
||||
participantsByAssignment[p.assignment_id].push({ user_id: p.user_id, username: p.username, avatar: p.avatar });
|
||||
}
|
||||
const rows = await this.assignmentParticipants.listForAssignments(assignmentIds);
|
||||
for (const p of rows) {
|
||||
if (!participantsByAssignment[p.assignment_id]) participantsByAssignment[p.assignment_id] = [];
|
||||
participantsByAssignment[p.assignment_id].push({ user_id: p.user_id, username: p.username, avatar: p.avatar });
|
||||
}
|
||||
return participantsByAssignment;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { TripMembershipService } from './trip-membership.service';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import { TripMembers } from '../../db/entities/TripMembers.entity';
|
||||
|
||||
/** Trip membership joins. No controller of its own — the HTTP surface lives with
|
||||
* auth, oidc and trip-invite, which all import this for the join itself. Kept
|
||||
* separate so those three (plus the plugin host) share one implementation
|
||||
* without AuthModule and TripInviteModule importing each other. */
|
||||
* without AuthModule and TripInviteModule importing each other.
|
||||
*
|
||||
* MikroOrmModule.forFeature([Trips, TripMembers]) only — NO service import
|
||||
* (Plan 3c Task 1 ruling): five modules import THIS module, so a new service
|
||||
* import here would close a cycle. `EntityManager`/repository resolution
|
||||
* comes entirely from the ORM's own `@Global()` core module + this
|
||||
* `forFeature` registration, keeping this module a leaf. */
|
||||
@Module({
|
||||
imports: [MikroOrmModule.forFeature([Trips, TripMembers])],
|
||||
providers: [TripMembershipService],
|
||||
exports: [TripMembershipService],
|
||||
})
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import type { TripsRepository } from '../../db/repositories/Trips.repository';
|
||||
import { TripMembers } from '../../db/entities/TripMembers.entity';
|
||||
import type { TripMembersRepository } from '../../db/repositories/TripMembers.repository';
|
||||
|
||||
/**
|
||||
* Adding an existing user to a trip as a member, plus the leaf membership
|
||||
@@ -11,24 +15,26 @@ import { DatabaseService } from '../database/database.service';
|
||||
* this trip" / "which trips can this user see", but every service that owns
|
||||
* the hydrated answer (TripsService, TripMembersService, TripReadModelService)
|
||||
* lives in a module that imports the budget domain, so injecting one there
|
||||
* closes a real cycle. This module imports nothing, so it is the one place
|
||||
* those id-level reads can live — the fold that deleted trips.bridge.
|
||||
* closes a real cycle. This module imports nothing but `TripsRepository`/
|
||||
* `TripMembersRepository` (Plan 3c Task 1: `MikroOrmModule.forFeature`, no
|
||||
* service import — see `trip-membership.module.ts`), so it stays the one
|
||||
* place those id-level reads can live — the fold that deleted trips.bridge.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TripMembershipService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
constructor(
|
||||
@InjectRepository(Trips) private readonly trips: TripsRepository,
|
||||
@InjectRepository(TripMembers) private readonly tripMembers: TripMembersRepository,
|
||||
) {}
|
||||
|
||||
/** The trip owner's user id, or null when the trip does not exist. */
|
||||
async getOwnerId(tripId: string | number): Promise<number | null> {
|
||||
const row = this.db.get<{ user_id: number }>('SELECT user_id FROM trips WHERE id = ?', tripId);
|
||||
return row ? row.user_id : null;
|
||||
return this.trips.getOwnerId(tripId);
|
||||
}
|
||||
|
||||
/** Member user ids (owner excluded), in added_at order like listMembers. */
|
||||
async listMemberUserIds(tripId: string | number): Promise<number[]> {
|
||||
return this.db
|
||||
.all<{ user_id: number }>('SELECT user_id FROM trip_members WHERE trip_id = ? ORDER BY added_at ASC', tripId)
|
||||
.map((r) => r.user_id);
|
||||
return this.tripMembers.listUserIdsByTrip(tripId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,15 +42,7 @@ export class TripMembershipService {
|
||||
* half of TripsService.list(userId, null), same WHERE and ORDER BY.
|
||||
*/
|
||||
async listAccessibleTripIds(userId: number): Promise<number[]> {
|
||||
return this.db
|
||||
.prepare(`
|
||||
SELECT t.id FROM trips t
|
||||
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = :userId
|
||||
WHERE (t.user_id = :userId OR m.user_id IS NOT NULL)
|
||||
ORDER BY t.created_at DESC
|
||||
`)
|
||||
.all({ userId })
|
||||
.map((r) => (r as { id: number }).id);
|
||||
return this.trips.listAccessibleIds(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,19 +55,23 @@ export class TripMembershipService {
|
||||
* belongs to a real (non-guest) account.
|
||||
*
|
||||
* Returns whether a new membership row was actually created.
|
||||
*
|
||||
* Non-transactional check-then-act, unchanged (Plan 3c inventory §18.4,
|
||||
* program rule 11): two concurrent joins can both pass the "already a
|
||||
* member" check and both insert. Pinned by a concurrency test, not fixed.
|
||||
*/
|
||||
async joinTripAsMember(
|
||||
tripId: number,
|
||||
userId: number,
|
||||
invitedBy: number | null,
|
||||
): Promise<{ joined: boolean; tripId: number }> {
|
||||
const trip = this.db.get<{ id: number; user_id: number }>('SELECT id, user_id FROM trips WHERE id = ?', tripId);
|
||||
const trip = await this.trips.findIdAndOwner(tripId);
|
||||
if (!trip) return { joined: false, tripId };
|
||||
// The owner already has full access; never add them as a member.
|
||||
if (trip.user_id === userId) return { joined: false, tripId };
|
||||
const existing = this.db.get('SELECT id FROM trip_members WHERE trip_id = ? AND user_id = ?', tripId, userId);
|
||||
const existing = await this.tripMembers.exists(tripId, userId);
|
||||
if (existing) return { joined: false, tripId };
|
||||
this.db.run('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)', tripId, userId, invitedBy);
|
||||
await this.tripMembers.addMember(tripId, userId, invitedBy);
|
||||
return { joined: true, tripId };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user