refactor(collections): saved places, copy-to-trip, labels and invitations through repositories

This commit is contained in:
jubnl
2026-09-24 00:11:01 +02:00
parent 1d72c6909b
commit d79f4cc605
12 changed files with 1178 additions and 274 deletions
@@ -1,4 +1,5 @@
import type { CollectionLabels } from '../entities/CollectionLabels.entity';
import { lower, lowerParam } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
/** `collection_labels` — `loadLabelsByCollection`'s (CL7) shape. */
@@ -73,4 +74,71 @@ export class CollectionLabelsRepository extends TrekRepository<CollectionLabels>
const result = await this.kysely<CollectionLabelsInsertKyselyDB>().insertInto('collection_labels').values(row).executeTakeFirstOrThrow();
return Number(result.insertId);
}
// -------------------------------------------------------------------------
// Plan 3h Task 2 (part B) — CL71-77, additive.
// -------------------------------------------------------------------------
/**
* CL71 (`collectionIdOfLabel`) — `SELECT collection_id FROM
* collection_labels WHERE id=?`. Kysely, not `findOne({fields:
* ['collection_id']})` — `collection_id` is a `persist(false)` relation
* mirror, and the program-wide "a bare `persist(false)` mirror column
* selected via `fields:` is silently dropped" trap (3d/3e ledgers)
* applies here exactly as it does to a bare `.select([...])`.
*/
async collectionIdOf(labelId: number): Promise<number | undefined> {
const row = await this.db_().selectFrom('collection_labels').select('collection_id').where('id', '=', labelId).executeTakeFirst();
return row?.collection_id;
}
/** CL72 (`getLabelById`) — `SELECT id, collection_id, name, color, sort_order FROM collection_labels WHERE id=?`. Kysely, same `collection_id` mirror-column reason as {@link collectionIdOf}. */
async findById(labelId: number): Promise<CollectionLabelRow | undefined> {
return await this.db_()
.selectFrom('collection_labels')
.select(['id', 'collection_id', 'name', 'color', 'sort_order'])
.where('id', '=', labelId)
.executeTakeFirst();
}
/** CL73 (`createLabel`) — `SELECT COUNT(*) AS n FROM collection_labels WHERE collection_id=?`. */
async countByCollection(collectionId: number): Promise<number> {
return await this.count({ collection: collectionId });
}
/**
* CL74 (`createLabel`) — `SELECT 1 FROM collection_labels WHERE
* collection_id=? AND lower(name)=lower(?)`. Both sides folded by SQLite
* (`lower`/`lowerParam`'s pair, program rule 18) — the legacy statement
* lowers the bound value in SQL too, never in JS.
*/
async nameExists(collectionId: number, name: string): Promise<boolean> {
const platform = this.getEntityManager().getPlatform();
const row = await this.findOne(
{ collection: collectionId, [lower(platform, 'name')]: lowerParam(platform, name) },
{ fields: ['id'] },
);
return !!row;
}
/** CL75 (`updateLabel`) — same as {@link nameExists}, plus `AND id != ?` (excludes the label being renamed). */
async nameExistsExcluding(collectionId: number, name: string, excludeId: number): Promise<boolean> {
const platform = this.getEntityManager().getPlatform();
const row = await this.findOne(
{ collection: collectionId, [lower(platform, 'name')]: lowerParam(platform, name), id: { $ne: excludeId } },
{ fields: ['id'] },
);
return !!row;
}
/** CL76 (`updateLabel`) — the allow-listed dynamic `UPDATE collection_labels SET ... WHERE id=?`. No `updated_at` stamp — the table has no such column, and the legacy statement never wrote one. */
async updateFields(labelId: number, write: Partial<{ name: string; color: string; sort_order: number }>): Promise<void> {
if (Object.keys(write).length === 0) return;
await this.nativeUpdate({ id: labelId }, write);
}
/** CL77 (`deleteLabel`) — `DELETE FROM collection_labels WHERE id=?` (CASCADE clears place assignments). */
async deleteById(labelId: number): Promise<void> {
await this.nativeDelete({ id: labelId });
}
}
@@ -111,4 +111,87 @@ export class CollectionMembersRepository extends TrekRepository<CollectionMember
.where('cm.status', '=', 'pending')
.execute();
}
// -------------------------------------------------------------------------
// Plan 3h Task 2 (part B) — CL79-88, additive: the invite lifecycle
// (sendInvite/acceptInvite/declineInvite/cancelInvite/leaveCollection/
// removeMember/setMemberRole/availableUsers/findMembershipForUser).
// -------------------------------------------------------------------------
/** CL80 (`sendInvite`) — `SELECT id, status FROM collection_members WHERE collection_id=? AND user_id=?` (dup/pending guard). */
async findByCollectionAndUser(collectionId: number, userId: number): Promise<{ id: number; status: string } | undefined> {
const row = await this.findOne({ collection: collectionId, user: userId }, { fields: ['id', 'status'] });
return row ?? undefined;
}
/** CL81 (`sendInvite`) — `INSERT INTO collection_members (collection_id, user_id, status, role) VALUES (?, ?, 'pending', ?)`. */
async insertInvite(collectionId: number, userId: number, role: string): Promise<void> {
await this.insert({ collection: collectionId, user: userId, status: 'pending', role });
}
/** CL82 (`acceptInvite`) — `SELECT id FROM collection_members WHERE collection_id=? AND user_id=? AND status='pending'`. */
async findPendingInvite(collectionId: number, userId: number): Promise<number | undefined> {
const row = await this.findOne({ collection: collectionId, user: userId, status: 'pending' }, { fields: ['id'] });
return row?.id;
}
/** CL83 (`acceptInvite`) — `UPDATE collection_members SET status='accepted' WHERE id=?`. */
async accept(memberId: number): Promise<void> {
await this.nativeUpdate({ id: memberId }, { status: 'accepted' });
}
/** CL84 (`declineInvite`, dup text also `cancelInvite`) — `DELETE FROM collection_members WHERE collection_id=? AND user_id=? AND status='pending'`. */
async deletePending(collectionId: number, userId: number): Promise<void> {
await this.nativeDelete({ collection: collectionId, user: userId, status: 'pending' });
}
/** CL85 (`leaveCollection`, dup text also `removeMember`) — `DELETE FROM collection_members WHERE collection_id=? AND user_id=? AND status='accepted'`. Returns the affected row count (`removeMember`'s own 404-on-zero check). */
async deleteAccepted(collectionId: number, userId: number): Promise<number> {
return await this.nativeDelete({ collection: collectionId, user: userId, status: 'accepted' });
}
/** CL86 (`setMemberRole`) — `UPDATE collection_members SET role=? WHERE collection_id=? AND user_id=? AND status='accepted'`. Returns the affected row count (0 ⇒ 404). */
async setRole(collectionId: number, userId: number, role: string): Promise<number> {
return await this.nativeUpdate({ collection: collectionId, user: userId, status: 'accepted' }, { role });
}
/**
* CL87 (`availableUsers`) — `SELECT u.id, u.username FROM users u WHERE
* u.id != ? AND u.id NOT IN (SELECT user_id FROM collection_members WHERE
* collection_id = ?) AND u.is_guest = 0 ORDER BY u.username`. Kysely — a
* `NOT IN` subquery against a different repository's own table (`users`),
* the same cross-entity shape `pendingInvitesForUser` above already uses.
*/
async availableUsers(ownerId: number, collectionId: number): Promise<{ id: number; username: string }[]> {
return await this.kysely<CollectionAvailableUsersKyselyDB>()
.selectFrom('users as u')
.select(['u.id', 'u.username'])
.where('u.id', '!=', ownerId)
.where('u.is_guest', '=', 0)
.where((eb) =>
eb.not(
eb.exists(
eb
.selectFrom('collection_members as cm')
.select('cm.user_id')
.whereRef('cm.user_id', '=', 'u.id')
.where('cm.collection_id', '=', collectionId),
),
),
)
.orderBy('u.username')
.execute();
}
/** CL88 (`findMembershipForUser`) — `SELECT status FROM collection_members WHERE collection_id=? AND user_id=?` (no status filter — any row, pending or accepted). */
async statusFor(collectionId: number, userId: number): Promise<string | undefined> {
const row = await this.findOne({ collection: collectionId, user: userId }, { fields: ['status'] });
return row?.status;
}
}
/** {@link CollectionMembersRepository.availableUsers}'s narrow `users`/`collection_members` shape. */
interface CollectionAvailableUsersKyselyDB {
users: { id: number; username: string; is_guest: number };
collection_members: { collection_id: number; user_id: number };
}
@@ -1,4 +1,72 @@
import type { CollectionPlaceRatings } from '../entities/CollectionPlaceRatings.entity';
import { TrekRepository } from './_shared/trek-repository';
export class CollectionPlaceRatingsRepository extends TrekRepository<CollectionPlaceRatings> {}
/**
* `collection_place_ratings` (Plan 3h Task 2, part B — #1435's per-voter
* star ratings on a saved place). A real entity/composite-unique table
* (`uniques: [{ properties: ['collectionPlace', 'user'] }]`, Task 0's
* entity/repository population table), unlike the two pivot tables this
* plan's own `collection_place_tags`/`collection_place_labels` conversions
* route through `CollectionPlacesRepository`'s Kysely bridge — writes here
* go through the MikroORM entity API using the entity's own relation
* property names (`collectionPlace`/`user`), `PlaceRatingsRepository
* .upsertRating`'s exact precedent for the sibling `place_ratings` table.
*/
export class CollectionPlaceRatingsRepository extends TrekRepository<CollectionPlaceRatings> {
/**
* CL52 (`setRating`, `rating === null` branch) — `DELETE FROM
* collection_place_ratings WHERE collection_place_id=? AND user_id=?`.
*/
async deleteRating(collectionPlaceId: number, userId: number): Promise<void> {
await this.nativeDelete({ collectionPlace: collectionPlaceId, user: userId });
}
/**
* CL53 (`setRating`, `rating !== null` branch) — `INSERT INTO
* collection_place_ratings (collection_place_id, user_id, rating) VALUES
* (?, ?, ?) ON CONFLICT(collection_place_id, user_id) DO UPDATE SET
* rating = excluded.rating`. A STRAIGHTFORWARD blind-overwrite composite
* upsert (the brief's own framing, confirmed against
* `PlaceRatingsRepository.upsertRating`, the closer precedent than R4's
* additive-counter shape): `onConflictFields: ['collectionPlace', 'user']`
* on the entity's own declared composite unique (property names, not
* column names — `collection_place_id`/`user_id` are `persist(false)`
* mirrors of those two relations), `onConflictMergeFields: ['rating']`
* so a future column never silently joins the merge set (same reasoning
* `PlaceRatingsRepository.upsertRating`'s own docstring gives).
*/
async upsertRating(collectionPlaceId: number, userId: number, rating: number): Promise<void> {
await this.upsert(
{ collectionPlace: collectionPlaceId, user: userId, rating },
{ onConflictFields: ['collectionPlace', 'user'], onConflictAction: 'merge', onConflictMergeFields: ['rating'] },
);
}
/**
* CL41 (`copyTripRatings`, PREPARED/looped) — `INSERT OR IGNORE INTO
* collection_place_ratings (collection_place_id, user_id, rating) VALUES
* (?, ?, ?)`. Distinct from {@link upsertRating}'s `DO UPDATE` shape — a
* vote already carried over from a prior copy is left alone, not
* overwritten, `onConflictAction: 'ignore'` on the same composite unique.
*/
async insertIgnoreRating(collectionPlaceId: number, userId: number, rating: number): Promise<void> {
await this.upsert(
{ collectionPlace: collectionPlaceId, user: userId, rating },
{ onConflictFields: ['collectionPlace', 'user'], onConflictAction: 'ignore' },
);
}
/**
* CL68 (`copyToTrip`, loop, TX) — `SELECT user_id, rating FROM
* collection_place_ratings WHERE collection_place_id=?`. `user_id` is a
* `persist(false)` relation mirror — Kysely, the program-wide "bare
* mirror column silently dropped" trap (3d/3e ledgers).
*/
async listForPlace(collectionPlaceId: number): Promise<{ user_id: number; rating: number }[]> {
return await this.kysely<{ collection_place_ratings: { collection_place_id: number; user_id: number; rating: number } }>()
.selectFrom('collection_place_ratings')
.select(['user_id', 'rating'])
.where('collection_place_id', '=', collectionPlaceId)
.execute();
}
}
@@ -1,4 +1,453 @@
import type { CollectionPlaces } from '../entities/CollectionPlaces.entity';
import { currentTimestamp } from '../dialect/sql-functions';
import type { CollectionPlaceRow } from './Collections.repository';
import { TrekRepository } from './_shared/trek-repository';
export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces> {}
/**
* `collection_places` (Plan 3h Task 2, part B — saved places CRUD, dedup,
* copy-to-trip, library-wide membership lookup, label assignment). Task 1's
* own bridge methods for this table (CL10/11/16/17/22/23/25/26/27) stay on
* `CollectionsRepository` as its report flags — this repository is additive
* ONLY, every method here a NEW statement in Task 2's own CL37-69 range,
* never a re-derivation of what Task 1 already built.
*
* **Read/write split**: every READ here goes through `this.kysely()` rather
* than the MikroORM entity API, even for statements the entity COULD in
* principle express, because every read in this file's own range projects
* at least one `persist(false)` relation-mirror column (`collection_id`/
* `category_id`) or needs `abs()`/dynamic OR conditions Kysely expresses
* more directly — the TRAP list's "a `persist(false)` mirror column
* selected bare is silently dropped, with or without an active join"
* finding (3d/3e ledgers) applies to a `qb().select([...])`/`fields: [...]`
* read exactly as much as it does to `find`, so Kysely sidesteps the whole
* class of bug rather than being audited statement-by-statement for it.
* WRITES go through the MikroORM entity API (`insert`/`nativeUpdate`/
* `nativeDelete`) wherever the target table has an entity, using the
* entity's own relation property names (`collection`/`owner`/`category`)
* for FK columns — {@link PlaceRatingsRepository.upsertRating}'s
* `{ place: place_id, user: user_id }` precedent — since a write is never
* subject to the read-side narrowing trap. The two pivot tables this file
* also owns (`collection_place_tags`/`collection_place_labels`) have NO
* entity of their own (`Task 0's` entity/repository population table) and
* so go through Kysely unconditionally, both reads and writes.
*/
export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces> {
private db_() {
return this.kysely<CollectionPlacesKyselyDB>();
}
// ---------------------------------------------------------------------
// CL37/CL38 — attachTags (private helper, savePlace/updatePlace)
// ---------------------------------------------------------------------
/**
* CL38 (`attachTags`, PREPARED/looped in the legacy code) — `INSERT OR
* IGNORE INTO collection_place_tags (collection_place_id, tag_id) VALUES
* (?, ?)`, one call per eligible tag id. Batched into ONE Kysely insert
* with `onConflict(...).doNothing()` on the pivot's real composite
* `PRIMARY KEY (collection_place_id, tag_id)` — the exact shape
* `TagsRepository.insertIgnore` already established for `place_tags`
* (the sibling pivot in the 3c-owned `places` cluster). Empty `tagIds`
* short-circuits before any query.
*/
async attachTags(collectionPlaceId: number, tagIds: number[]): Promise<void> {
if (tagIds.length === 0) return;
await this.db_()
.insertInto('collection_place_tags')
.values(tagIds.map((tag_id) => ({ collection_place_id: collectionPlaceId, tag_id })))
.onConflict((oc) => oc.columns(['collection_place_id', 'tag_id']).doNothing())
.execute();
}
// ---------------------------------------------------------------------
// CL42/CL46 — savePlace / saveFromTripPlaces inserts
// ---------------------------------------------------------------------
/**
* CL42 (`savePlace`, TX) AND CL46 (`saveFromTripPlaces`, PREPARED/looped,
* TX) — collapsed onto ONE method, not two: both legacy statements share
* the IDENTICAL 22-column `INSERT INTO collection_places (collection_id,
* owner_id, saved_by, name, description, lat, lng, address, category_id,
* price, currency, notes, image_url, google_place_id, google_ftid,
* osm_id, website, phone, status, source_trip_id, source_place_id,
* links)` list in the SAME order — CL46's only difference is that
* `status`/`links` are bound SQL literals (`'idea'`/`NULL`) instead of
* placeholders, which is a caller-side VALUE difference, not a distinct
* statement shape (unlike CL23's file-import insert, which genuinely
* carries a different column set — `sort_order`, no `source_trip_id`/
* `source_place_id` — and stays its own method on `CollectionsRepository`,
* per the plan's own "do not collapse" instruction for that pair).
* `saveFromTripPlaces`'s own call site passes `status: 'idea', links:
* null` explicitly, reproducing the literal exactly. `em.insert()`
* returns the generated id; `sort_order` is never in the column list
* either statement writes, so the table's own `DEFAULT 0` fills it,
* matching both legacy statements.
*/
async insertSavedPlace(row: {
collection_id: number;
owner_id: number;
saved_by: number;
name: string;
description: string | null;
lat: number | null;
lng: number | null;
address: string | null;
category_id: number | null;
price: number | null;
currency: string | null;
notes: string | null;
image_url: string | null;
google_place_id: string | null;
google_ftid: string | null;
osm_id: string | null;
website: string | null;
phone: string | null;
status: string;
source_trip_id: number | null;
source_place_id: number | null;
links: string | null;
}): Promise<number> {
return await this.insert({
collection: row.collection_id,
owner: row.owner_id,
savedByRef: row.saved_by,
name: row.name,
description: row.description,
lat: row.lat,
lng: row.lng,
address: row.address,
category: row.category_id,
price: row.price,
currency: row.currency,
notes: row.notes,
image_url: row.image_url,
google_place_id: row.google_place_id,
google_ftid: row.google_ftid,
osm_id: row.osm_id,
website: row.website,
phone: row.phone,
status: row.status,
source_trip_id: row.source_trip_id,
source_place_id: row.source_place_id,
links: row.links,
});
}
// ---------------------------------------------------------------------
// CL47/CL48 — updatePlace
// ---------------------------------------------------------------------
/** CL47 (`updatePlace`'s pre-image read, dup text also `deletePlace`/`deletePlacesMany`/`setPlaceImage`) — `SELECT image_url FROM collection_places WHERE id=?`. Plain (non-FK) column — safe through the entity API, `fields: ['image_url']`. */
async imageUrl(id: number): Promise<string | null | undefined> {
const row = await this.findOne({ id }, { fields: ['image_url'] });
return row?.image_url;
}
/**
* CL48 (`updatePlace`, TX) — the allow-listed dynamic `UPDATE
* collection_places SET ... WHERE id=?`, including the cross-list move
* branch (`collection_id`/`owner_id`). `write` carries exactly the
* columns the caller built (the service resolves `body.field !==
* undefined` itself, `CollectionsRepository.updateFields`'s same shape)
* — an empty `write` short-circuits, matching the legacy `if
* (updates.length > 0)` guard. FK columns are translated to their
* entity relation property names for the write
* (`collection_id`→`collection`, `owner_id`→`owner`, `category_id`→
* `category`) — `PlaceRatingsRepository.upsertRating`'s precedent for
* writing a `persist(false)` mirror through its owning relation.
*/
async updateFields(
id: number,
write: Partial<{
name: string;
description: string | null;
notes: string | null;
lat: number | null;
lng: number | null;
address: string | null;
status: string;
category_id: number | null;
image_url: string | null;
links: string | null;
collection_id: number;
owner_id: number;
}>,
): Promise<void> {
if (Object.keys(write).length === 0) return;
const platform = this.getEntityManager().getPlatform();
const { category_id, collection_id, owner_id, ...rest } = write;
await this.nativeUpdate(
{ id },
{
...rest,
...(category_id !== undefined ? { category: category_id } : {}),
...(collection_id !== undefined ? { collection: collection_id } : {}),
...(owner_id !== undefined ? { owner: owner_id } : {}),
updated_at: currentTimestamp(platform),
},
);
}
/** CL49 (`updatePlace`, TX) — `DELETE FROM collection_place_tags WHERE collection_place_id=?`. Pivot table, Kysely. */
async deleteTags(collectionPlaceId: number): Promise<void> {
await this.db_().deleteFrom('collection_place_tags').where('collection_place_id', '=', collectionPlaceId).execute();
}
/** CL50 (`updatePlace`'s move branch, TX, dup text also `setPlaceLabels`) — `DELETE FROM collection_place_labels WHERE collection_place_id=?`. Pivot table, Kysely. */
async deleteLabelAssignments(collectionPlaceId: number): Promise<void> {
await this.db_().deleteFrom('collection_place_labels').where('collection_place_id', '=', collectionPlaceId).execute();
}
// ---------------------------------------------------------------------
// CL51/CL52/CL53 — setStatus / setRating
// ---------------------------------------------------------------------
/** CL51 (`setStatus`) — `UPDATE collection_places SET status=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`. */
async setStatus(id: number, status: string): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ id }, { status, updated_at: currentTimestamp(platform) });
}
// ---------------------------------------------------------------------
// CL54 — deletePlace / deletePlacesMany
// ---------------------------------------------------------------------
/** CL54 (`deletePlace`, dup text also `deletePlacesMany`'s TX loop) — `DELETE FROM collection_places WHERE id=?` (CASCADE drops tags/labels/ratings). */
async deleteById(id: number): Promise<void> {
await this.nativeDelete({ id });
}
// ---------------------------------------------------------------------
// CL56 — setStatusMany
// ---------------------------------------------------------------------
/**
* CL56 (`setStatusMany`, TX) — `UPDATE collection_places SET status=?,
* updated_at=CURRENT_TIMESTAMP WHERE id=? AND status IS NOT ?`, distinct
* from CL51 by the extra `status IS NOT ?` guard. Returns the affected
* row count (0 or 1) — the caller sums it across the batch, matching the
* legacy `res.changes` accumulation.
*/
async setStatusIfChanged(id: number, status: string): Promise<number> {
const platform = this.getEntityManager().getPlatform();
return await this.nativeUpdate({ id, status: { $ne: status } }, { status, updated_at: currentTimestamp(platform) });
}
// ---------------------------------------------------------------------
// CL58 — matchingCollectionPlaces (setStatusFromTrip's own private helper)
// ---------------------------------------------------------------------
/**
* CL58 (`matchingCollectionPlaces`) — `SELECT cp.id FROM collection_places
* cp WHERE cp.collection_id IN (...) AND (${dynamic OR conditions})`.
* RULE 23: the dynamic OR is a typed array of Kysely expressions built
* conditionally (never a string-concatenated WHERE) — the base
* `source_trip_id`/`source_place_id` pair is always present (an AND'd
* sub-clause inside the outer OR, matching the legacy's own parenthesised
* first condition), and each provider-id/coordinate-tolerance clause is
* pushed onto the array only when the corresponding input field is
* present, exactly reproducing the legacy `conditions.push(...)` guards.
* `tolerance` is caller-supplied (`CollectionsRepository
* .findDuplicateByCoords`'s own precedent), not imported from
* `nest/places/places.helpers` here — a `db/` repository does not reach
* into `nest/`.
*/
async matchingByTripSource(
collectionIds: number[],
tripId: number,
place: { id: number; lat: number | null; lng: number | null; google_place_id: string | null; google_ftid: string | null; osm_id: string | null },
tolerance: number,
): Promise<{ id: number }[]> {
if (collectionIds.length === 0) return [];
return await this.db_()
.selectFrom('collection_places as cp')
.select('cp.id')
.where('cp.collection_id', 'in', collectionIds)
.where((eb) => {
const clauses = [eb.and([eb('cp.source_trip_id', '=', tripId), eb('cp.source_place_id', '=', place.id)])];
if (place.google_place_id) clauses.push(eb('cp.google_place_id', '=', place.google_place_id));
if (place.google_ftid) clauses.push(eb('cp.google_ftid', '=', place.google_ftid));
if (place.osm_id) clauses.push(eb('cp.osm_id', '=', place.osm_id));
if (place.lat != null && place.lng != null) {
clauses.push(
eb.and([
eb('cp.lat', 'is not', null),
eb('cp.lng', 'is not', null),
eb(eb.fn('abs', [eb('cp.lat', '-', place.lat)]), '<=', tolerance),
eb(eb.fn('abs', [eb('cp.lng', '-', place.lng)]), '<=', tolerance),
]),
);
}
return eb.or(clauses);
})
.execute();
}
// ---------------------------------------------------------------------
// CL59 — setPlaceImage
// ---------------------------------------------------------------------
/** CL59 (`setPlaceImage`) — `UPDATE collection_places SET image_url=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`. */
async setImageUrl(id: number, imageUrl: string | null): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.nativeUpdate({ id }, { image_url: imageUrl, updated_at: currentTimestamp(platform) });
}
// ---------------------------------------------------------------------
// CL62 — copyToTrip's per-source-id read
// ---------------------------------------------------------------------
/**
* CL62 (`copyToTrip`, per source id) — `SELECT id, collection_id, name,
* description, lat, lng, address, category_id, price, currency, notes,
* image_url, google_place_id, google_ftid, osm_id, website, phone FROM
* collection_places WHERE id=?`. `collection_id`/`category_id` in the
* projection — Kysely, the class docstring's read-side rule.
*/
async findForCopy(id: number): Promise<CollectionPlaceCopyRow | undefined> {
return await this.db_()
.selectFrom('collection_places')
.select([
'id', 'collection_id', 'name', 'description', 'lat', 'lng', 'address', 'category_id', 'price', 'currency',
'notes', 'image_url', 'google_place_id', 'google_ftid', 'osm_id', 'website', 'phone',
])
.where('id', '=', id)
.executeTakeFirst();
}
// ---------------------------------------------------------------------
// CL67 — copyToTrip's per-source tag read (loop, TX)
// ---------------------------------------------------------------------
/** CL67 (`copyToTrip`, loop, TX) — `SELECT tag_id FROM collection_place_tags WHERE collection_place_id=?`. Pivot table, Kysely. */
async tagIdsFor(collectionPlaceId: number): Promise<number[]> {
const rows = await this.db_().selectFrom('collection_place_tags').select('tag_id').where('collection_place_id', '=', collectionPlaceId).execute();
return rows.map((r) => r.tag_id);
}
// ---------------------------------------------------------------------
// CL69 — findMembership (library-wide membership lookup)
// ---------------------------------------------------------------------
/**
* CL69 (`findMembership`) — `SELECT cp.id AS place_id, cp.collection_id,
* c.name, cp.status FROM collection_places cp JOIN collections c ON
* c.id=cp.collection_id WHERE cp.collection_id IN (...) AND (${dynamic
* conditions})`. RULE 23, same shape as {@link matchingByTripSource}
* above, but genuinely a DIFFERENT statement (no `source_trip_id`/
* `source_place_id` base clause, no `osm_id` condition — the legacy
* `findMembership` never checks it — and an extra `collections` join for
* the list name), so this is its own method rather than a parameterised
* reuse of `matchingByTripSource` (one repository method per legacy
* statement). Returns `[]` when `query` carries no usable condition,
* matching the service's own `if (conditions.length === 0) return
* { saved: false, lists: [] };` guard — defensive here too, though the
* caller already checks first.
*/
async searchMembership(
collectionIds: number[],
query: { google_place_id?: string; google_ftid?: string; lat?: number; lng?: number },
tolerance: number,
): Promise<{ place_id: number; collection_id: number; name: string; status: string }[]> {
if (collectionIds.length === 0) return [];
const hasCoords = query.lat != null && query.lng != null;
if (!query.google_place_id && !query.google_ftid && !hasCoords) return [];
return await this.kysely<CollectionPlacesMembershipKyselyDB>()
.selectFrom('collection_places as cp')
.innerJoin('collections as c', 'c.id', 'cp.collection_id')
.select(['cp.id as place_id', 'cp.collection_id', 'c.name', 'cp.status'])
.where('cp.collection_id', 'in', collectionIds)
.where((eb) => {
const clauses = [];
if (query.google_place_id) clauses.push(eb('cp.google_place_id', '=', query.google_place_id));
if (query.google_ftid) clauses.push(eb('cp.google_ftid', '=', query.google_ftid));
if (hasCoords) {
clauses.push(
eb.and([
eb('cp.lat', 'is not', null),
eb('cp.lng', 'is not', null),
eb(eb.fn('abs', [eb('cp.lat', '-', query.lat as number)]), '<=', tolerance),
eb(eb.fn('abs', [eb('cp.lng', '-', query.lng as number)]), '<=', tolerance),
]),
);
}
return eb.or(clauses);
})
.execute();
}
// ---------------------------------------------------------------------
// CL78 — assignLabels' remove branch (TX)
// ---------------------------------------------------------------------
/**
* CL78 (`assignLabels`'s remove branch, PREPARED/looped, TX) — `DELETE
* FROM collection_place_labels WHERE collection_place_id=? AND
* label_id=?`, per pair in the service's own nested loop (mirrors
* `CollectionsRepository.assignPlaceLabel`'s CL24 per-pair shape, the
* insert branch's own repository call). Pivot table, Kysely. Returns the
* deleted row count (0 or 1) for the caller's `changed +=` accumulation.
*/
async unassignLabel(collectionPlaceId: number, labelId: number): Promise<number> {
const result = await this.db_()
.deleteFrom('collection_place_labels')
.where('collection_place_id', '=', collectionPlaceId)
.where('label_id', '=', labelId)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
/**
* `assignLabels`'s own insert branch (its own text is `CL24`'s dup, `:1488`
* per Task 1's report) — same `INSERT OR IGNORE INTO collection_place_labels
* (collection_place_id, label_id) VALUES (?, ?)` shape as
* `CollectionsRepository.assignPlaceLabel`, but with a COUNT-returning
* contract that method doesn't have (it returns `void` — `setPlaceLabels`'s
* own call site, the sole other CL24 consumer, never needed one). `assignLabels`
* sums the affected-row count across every pair (matching the legacy's own
* `res.changes` accumulation — an already-assigned label contributes 0, a
* newly-assigned one contributes 1), which `void` cannot answer. A second
* method rather than widening Task 1's committed signature, per the
* brief's "Task 1's methods untouched" instruction.
*/
async assignLabel(collectionPlaceId: number, labelId: number): Promise<number> {
const result = await this.db_()
.insertInto('collection_place_labels')
.values({ collection_place_id: collectionPlaceId, label_id: labelId })
.onConflict((oc) => oc.columns(['collection_place_id', 'label_id']).doNothing())
.executeTakeFirst();
return Number(result.numInsertedOrUpdatedRows ?? 0);
}
}
/** {@link CollectionPlacesRepository.findForCopy}'s narrow projection (CL62). */
export interface CollectionPlaceCopyRow {
id: number;
collection_id: number;
name: string;
description: string | null;
lat: number | null;
lng: number | null;
address: string | null;
category_id: number | null;
price: number | null;
currency: string | null;
notes: string | null;
image_url: string | null;
google_place_id: string | null;
google_ftid: string | null;
osm_id: string | null;
website: string | null;
phone: string | null;
}
interface CollectionPlacesKyselyDB {
collection_places: Omit<CollectionPlaceRow, 'category_name' | 'category_color' | 'category_icon'>;
collection_place_tags: { collection_place_id: number; tag_id: number };
collection_place_labels: { collection_place_id: number; label_id: number };
}
interface CollectionPlacesMembershipKyselyDB {
collection_places: Pick<CollectionPlaceRow, 'id' | 'collection_id' | 'google_place_id' | 'google_ftid' | 'lat' | 'lng' | 'status'>;
collections: { id: number; name: string };
}
@@ -73,4 +73,39 @@ export class PlaceRatingsRepository extends TrekRepository<PlaceRatings> {
async deleteRating(place_id: number, user_id: number): Promise<void> {
await this.nativeDelete({ place: place_id, user: user_id });
}
// ---------------------------------------------------------------------------
// Plan 3h Task 2 (`CollectionsService`) — additive, cross-domain. Flagged in
// the task's own report: these touch `place_ratings`, a 3c-owned table,
// from the collections cluster's own save/copy surface (#1435 vote carry).
// ---------------------------------------------------------------------------
/**
* CL40 (`copyTripRatings`) — `SELECT user_id, rating FROM place_ratings
* WHERE place_id=?`. `user_id` is a `persist(false)` relation mirror with
* no active join in this statement — Kysely, the program-wide "bare
* mirror column silently dropped, with or without a join" trap (3d/3e
* ledgers; `listForPlaces`'s own docstring above documents the joined
* variant of the same finding).
*/
async listVotesForPlace(place_id: number): Promise<{ user_id: number; rating: number }[]> {
return await this.kysely<{ place_ratings: { place_id: number; user_id: number; rating: number } }>()
.selectFrom('place_ratings')
.select(['user_id', 'rating'])
.where('place_id', '=', place_id)
.execute();
}
/**
* CL66 (`copyToTrip`, PREPARED/looped, TX) — `INSERT OR IGNORE INTO
* place_ratings (place_id, user_id, rating) VALUES (?, ?, ?)`. Distinct
* from {@link upsertRating}'s `DO UPDATE` shape — a trip member's
* existing vote on the destination place (unlikely on a freshly copied
* row, but not impossible if the place already existed) is left alone,
* `onConflictAction: 'ignore'` on the same `['place', 'user']` composite
* unique {@link upsertRating} documents.
*/
async insertIgnore(place_id: number, user_id: number, rating: number): Promise<void> {
await this.upsert({ place: place_id, user: user_id, rating }, { onConflictFields: ['place', 'user'], onConflictAction: 'ignore' });
}
}
@@ -1244,6 +1244,91 @@ export class UsersRepository extends TrekRepository<Users> {
const row = await this.findOne({ id, is_guest: 0 }, { fields: ['email'] });
return row?.email ?? null;
}
// ---------------------------------------------------------------------
// Plan 3h Task 2 (`CollectionsService.sendInvite`) — additive.
// ---------------------------------------------------------------------
/** CL79 (`sendInvite`) — `SELECT id, username FROM users WHERE id = ?`. */
async findIdUsername(id: number): Promise<{ id: number; username: string } | null> {
const row = await this.findOne({ id }, { fields: ['id', 'username'] });
return row ? { id: row.id, username: row.username } : null;
}
// ---------------------------------------------------------------------
// Plan 3h Task 4 (`AirtrailService` — R7, the encrypt-in-service
// discipline identical to Task 3's `DawarichConnectionsRepository`:
// every value below is exactly what the SERVICE hands this repository —
// encrypted, plaintext or null, at the same point in the pipeline the
// raw SQL saw it. This repository never calls
// maybe_encrypt_api_key/decrypt_api_key itself.
// ---------------------------------------------------------------------
/** ATC1 (`airtrail.service.ts#readRow`) — `SELECT airtrail_url, airtrail_api_key, airtrail_allow_insecure_tls, airtrail_write_enabled FROM users WHERE id = ?`. */
async getAirtrailConnRow(id: number): Promise<{
airtrail_url: string | null;
airtrail_api_key: string | null;
airtrail_allow_insecure_tls: number | null;
airtrail_write_enabled: number | null;
} | null> {
const row = await this.findOne(
{ id },
{ fields: ['airtrail_url', 'airtrail_api_key', 'airtrail_allow_insecure_tls', 'airtrail_write_enabled'] },
);
return row
? {
airtrail_url: row.airtrail_url ?? null,
airtrail_api_key: row.airtrail_api_key ?? null,
airtrail_allow_insecure_tls: row.airtrail_allow_insecure_tls ?? null,
airtrail_write_enabled: row.airtrail_write_enabled ?? null,
}
: null;
}
/** ATC2 (`airtrail.service.ts#isAirtrailWriteEnabled`) — `SELECT airtrail_write_enabled FROM users WHERE id = ?`. */
async getAirtrailWriteEnabled(id: number): Promise<number | null> {
const row = await this.findOne({ id }, { fields: ['airtrail_write_enabled'] });
return row?.airtrail_write_enabled ?? null;
}
/**
* ATC3 (`airtrail.service.ts#saveSettings`, newKey branch) — `UPDATE users
* SET airtrail_url = ?, airtrail_api_key = ?, airtrail_allow_insecure_tls
* = ?, airtrail_write_enabled = ? WHERE id = ?`. **No transaction** — the
* plan's Risks section flags this as a pre-existing asymmetry with
* `DawarichConnectionsRepository`'s equivalent `saveSettings` (which DOES
* wrap its writes in `uow.transactional`): preserved exactly, not
* "fixed" to match Dawarich's shape.
*/
async setAirtrailSettingsWithKey(id: number, url: string | null, apiKey: string, allowInsecureTls: number, writeEnabled: number): Promise<void> {
await this.nativeUpdate(
{ id },
{ airtrail_url: url, airtrail_api_key: apiKey, airtrail_allow_insecure_tls: allowInsecureTls, airtrail_write_enabled: writeEnabled },
);
}
/**
* ATC4 (`airtrail.service.ts#saveSettings`, no-newKey branch) — `UPDATE
* users SET airtrail_url = ?, airtrail_allow_insecure_tls = ?,
* airtrail_write_enabled = ? WHERE id = ?`. Same no-transaction asymmetry
* as {@link setAirtrailSettingsWithKey} — preserved, not fixed.
*/
async setAirtrailSettings(id: number, url: string | null, allowInsecureTls: number, writeEnabled: number): Promise<void> {
await this.nativeUpdate({ id }, { airtrail_url: url, airtrail_allow_insecure_tls: allowInsecureTls, airtrail_write_enabled: writeEnabled });
}
/**
* ATC5 (`airtrail.service.ts#saveSettings`, URL-cleared branch) — `UPDATE
* users SET airtrail_api_key = NULL WHERE id = ?`. **SECURITY**:
* credential scrub — a cleared URL with no key left makes the connection
* meaningless, so the key is dropped too. Same no-transaction asymmetry
* as the two methods above — this is a THIRD, separate statement in the
* legacy `saveSettings` (its own `if (!trimmedUrl)` branch), not folded
* into {@link setAirtrailSettings}.
*/
async clearAirtrailApiKey(id: number): Promise<void> {
await this.nativeUpdate({ id }, { airtrail_api_key: null });
}
}
/**
@@ -3,8 +3,15 @@ import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Collections } from '../../db/entities/Collections.entity';
import { CollectionMembers } from '../../db/entities/CollectionMembers.entity';
import { CollectionLabels } from '../../db/entities/CollectionLabels.entity';
import { CollectionPlaces } from '../../db/entities/CollectionPlaces.entity';
import { CollectionPlaceRatings } from '../../db/entities/CollectionPlaceRatings.entity';
import { Categories } from '../../db/entities/Categories.entity';
import { Users } from '../../db/entities/Users.entity';
import { Trips } from '../../db/entities/Trips.entity';
import { TripMembers } from '../../db/entities/TripMembers.entity';
import { Places } from '../../db/entities/Places.entity';
import { PlaceRatings } from '../../db/entities/PlaceRatings.entity';
import { Tags } from '../../db/entities/Tags.entity';
import { CollectionsController } from './collections.controller';
import { CollectionsService } from './collections.service';
import { CollectionsRpc } from './collections.rpc';
@@ -42,7 +49,10 @@ import { MAX_COVER_SIZE } from './collections.controller';
}),
StorageModule,
NotificationsModule, AddonsModule, PermissionsModule, AuthModule, AppConfigModule, PluginGuardsModule,
MikroOrmModule.forFeature([Collections, CollectionMembers, CollectionLabels, Categories, Users])],
MikroOrmModule.forFeature([
Collections, CollectionMembers, CollectionLabels, CollectionPlaces, CollectionPlaceRatings,
Categories, Users, Trips, TripMembers, Places, PlaceRatings, Tags,
])],
controllers: [CollectionsController],
providers: [CollectionsService, CollectionsMcp, CollectionsRpc],
exports: [CollectionsService],
+188 -260
View File
@@ -1,7 +1,6 @@
import path from 'path';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { DatabaseService } from '../database/database.service';
import { PermissionsService } from '../permissions/permissions.service';
import { RealtimeService } from '../realtime/realtime.service';
import { reclaimPlaceImage } from '../places/place-image';
@@ -15,6 +14,22 @@ import { CollectionLabelsRepository } from '../../db/repositories/CollectionLabe
import { Categories } from '../../db/entities/Categories.entity';
import type { CategoriesRepository } from '../../db/repositories/Categories.repository';
import { resolveCollectionRole, type CollectionRole } from '../../db/repositories/_shared/collection-role';
import { CollectionPlaces } from '../../db/entities/CollectionPlaces.entity';
import { CollectionPlacesRepository, type CollectionPlaceCopyRow } from '../../db/repositories/CollectionPlaces.repository';
import { CollectionPlaceRatings } from '../../db/entities/CollectionPlaceRatings.entity';
import { CollectionPlaceRatingsRepository } from '../../db/repositories/CollectionPlaceRatings.repository';
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';
import { Places } from '../../db/entities/Places.entity';
import type { PlacesRepository } from '../../db/repositories/Places.repository';
import { PlaceRatings } from '../../db/entities/PlaceRatings.entity';
import type { PlaceRatingsRepository } from '../../db/repositories/PlaceRatings.repository';
import { Tags } from '../../db/entities/Tags.entity';
import type { TagsRepository } from '../../db/repositories/Tags.repository';
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import {
COORD_DEDUP_TOLERANCE,
externalIdsOf,
@@ -109,7 +124,6 @@ const MAX_LABELS_PER_COLLECTION = 50;
@Injectable()
export class CollectionsService {
constructor(
private readonly db: DatabaseService,
private readonly permissions: PermissionsService,
private readonly realtime: RealtimeService,
private readonly notifications: NotificationsService,
@@ -119,6 +133,19 @@ export class CollectionsService {
@InjectRepository(CollectionMembers) private readonly members: CollectionMembersRepository,
@InjectRepository(CollectionLabels) private readonly labels: CollectionLabelsRepository,
@InjectRepository(Categories) private readonly categories: CategoriesRepository,
// Plan 3h Task 2 (part B) — savePlace onward. `collectionPlaces`/
// `collectionPlaceRatings` own this service's own two remaining tables;
// `trips`/`tripMembers`/`tripPlaces`/`tripPlaceRatings`/`tags`/`users`
// are 3b/3c's, injected directly (AP1-AP6 each become a
// `TripsRepository.findAccessible` call, replacing `this.db.canAccessTrip`).
@InjectRepository(CollectionPlaces) private readonly collectionPlaces: CollectionPlacesRepository,
@InjectRepository(CollectionPlaceRatings) private readonly collectionPlaceRatings: CollectionPlaceRatingsRepository,
@InjectRepository(Trips) private readonly trips: TripsRepository,
@InjectRepository(TripMembers) private readonly tripMembers: TripMembersRepository,
@InjectRepository(Places) private readonly tripPlaces: PlacesRepository,
@InjectRepository(PlaceRatings) private readonly tripPlaceRatings: PlaceRatingsRepository,
@InjectRepository(Tags) private readonly tags: TagsRepository,
@InjectRepository(Users) private readonly users: UsersRepository,
) {}
/**
@@ -687,19 +714,16 @@ export class CollectionsService {
if (!tagIds || tagIds.length === 0) return;
const unique = [...new Set(tagIds)];
const eligible = await this.collectionMemberIds(await this.collectionIdOfPlace(collectionPlaceId));
const owned = this.db.all<{ id: number; user_id: number }>(
`SELECT id, user_id FROM tags WHERE id IN (${unique.map(() => '?').join(',')})`,
...unique,
);
const stmt = this.db.prepare('INSERT OR IGNORE INTO collection_place_tags (collection_place_id, tag_id) VALUES (?, ?)');
for (const t of owned) if (eligible.has(t.user_id)) stmt.run(collectionPlaceId, t.id);
const owned = await this.tags.findByIds(unique);
const eligibleTagIds = owned.filter(t => eligible.has(t.user_id)).map(t => t.id);
await this.collectionPlaces.attachTags(collectionPlaceId, eligibleTagIds);
}
/** Owner + accepted members — the users whose votes may live in this list. */
private async collectionMemberIds(collectionId: number): Promise<Set<number>> {
const ids = new Set<number>([await this.ownerOf(collectionId)]);
const rows = this.db.all<{ user_id: number }>("SELECT user_id FROM collection_members WHERE collection_id = ? AND status = 'accepted'", collectionId);
rows.forEach(r => ids.add(r.user_id));
const accepted = await this.members.acceptedUserIds(collectionId);
accepted.forEach(id => ids.add(id));
return ids;
}
@@ -710,10 +734,9 @@ export class CollectionsService {
*/
private async copyTripRatings(sourcePlaceId: number, collectionPlaceId: number, collectionId: number): Promise<void> {
const eligible = await this.collectionMemberIds(collectionId);
const rows = this.db.all<{ user_id: number; rating: number }>('SELECT user_id, rating FROM place_ratings WHERE place_id = ?', sourcePlaceId);
const ins = this.db.prepare('INSERT OR IGNORE INTO collection_place_ratings (collection_place_id, user_id, rating) VALUES (?, ?, ?)');
const rows = await this.tripPlaceRatings.listVotesForPlace(sourcePlaceId);
for (const r of rows) {
if (eligible.has(r.user_id)) ins.run(collectionPlaceId, r.user_id, r.rating);
if (eligible.has(r.user_id)) await this.collectionPlaceRatings.insertIgnoreRating(collectionPlaceId, r.user_id, r.rating);
}
}
@@ -732,33 +755,28 @@ export class CollectionsService {
// Insert + tags + ratings-copy are one logical write — atomic since the
// post-fold quirk pass (the relocation carried them un-transacted).
const placeId = await this.uow.transactional(async () => {
const result = this.db.run(`
INSERT INTO collection_places (
collection_id, owner_id, saved_by, name, description, lat, lng, address,
category_id, price, currency, notes, image_url, google_place_id, google_ftid,
osm_id, website, phone, status, source_trip_id, source_place_id, links
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
body.collection_id, ownerId, userId,
body.name, body.description ?? null, body.lat ?? null, body.lng ?? null, body.address ?? null,
body.category_id ?? null, body.price ?? null, body.currency ?? null, body.notes ?? null,
body.image_url ?? null, body.google_place_id ?? null, body.google_ftid ?? null,
body.osm_id ?? null, body.website ?? null, body.phone ?? null,
body.status ?? 'idea', body.source_trip_id ?? null, body.source_place_id ?? null,
serializeLinks(body.links),
);
const id = await this.collectionPlaces.insertSavedPlace({
collection_id: body.collection_id, owner_id: ownerId, saved_by: userId,
name: body.name, description: body.description ?? null, lat: body.lat ?? null, lng: body.lng ?? null, address: body.address ?? null,
category_id: body.category_id ?? null, price: body.price ?? null, currency: body.currency ?? null, notes: body.notes ?? null,
image_url: body.image_url ?? null, google_place_id: body.google_place_id ?? null, google_ftid: body.google_ftid ?? null,
osm_id: body.osm_id ?? null, website: body.website ?? null, phone: body.phone ?? null,
status: body.status ?? 'idea', source_trip_id: body.source_trip_id ?? null, source_place_id: body.source_place_id ?? null,
links: serializeLinks(body.links),
});
const id = Number(result.lastInsertRowid);
await this.attachTags(id, body.tag_ids);
// Carry trip ratings ONLY when the caller can actually see the source place.
// source_place_id/source_trip_id are raw client input, so verify trip access +
// that the place lives in that trip before reading place_ratings — otherwise a
// member could harvest co-members' votes on places in trips they cannot access
// (mirrors the canAccessTrip gate in saveFromTripPlace).
// (mirrors the canAccessTrip gate in saveFromTripPlace). R6's two-layer order:
// assertCanEdit (this method's own entry guard, above) ran FIRST; the trip-access
// check (AP1) runs SECOND, here, inside the write path — never reversed.
if (
body.source_place_id && body.source_trip_id &&
(await this.db.canAccessTrip(body.source_trip_id, userId)) &&
this.db.get('SELECT 1 FROM places WHERE id = ? AND trip_id = ?', body.source_place_id, body.source_trip_id)
(await this.trips.findAccessible(body.source_trip_id, userId)) &&
(await this.tripPlaces.existsInTrip(body.source_place_id, body.source_trip_id))
) {
await this.copyTripRatings(body.source_place_id, id, body.collection_id);
}
@@ -772,28 +790,28 @@ export class CollectionsService {
userId: number, collectionId: number, tripId: number, placeId: number, force?: boolean, socketId?: string,
): Promise<CollectionSaveResult> {
await this.assertCanEdit(userId, collectionId);
if (!(await this.db.canAccessTrip(tripId, userId))) httpError(404, 'Trip not found');
if (!(await this.trips.findAccessible(tripId, userId))) httpError(404, 'Trip not found');
const place = this.db.get<Record<string, unknown>>('SELECT * FROM places WHERE id = ? AND trip_id = ?', placeId, tripId);
const place = await this.tripPlaces.findInTrip(placeId, tripId);
if (!place) httpError(404, 'Place not found');
return this.savePlace(userId, {
collection_id: collectionId,
name: place.name as string,
description: (place.description as string | null) ?? null,
lat: (place.lat as number | null) ?? null,
lng: (place.lng as number | null) ?? null,
address: (place.address as string | null) ?? null,
category_id: (place.category_id as number | null) ?? null,
price: (place.price as number | null) ?? null,
currency: (place.currency as string | null) ?? null,
notes: (place.notes as string | null) ?? null,
image_url: (place.image_url as string | null) ?? null,
google_place_id: (place.google_place_id as string | null) ?? null,
google_ftid: (place.google_ftid as string | null) ?? null,
osm_id: (place.osm_id as string | null) ?? null,
website: (place.website as string | null) ?? null,
phone: (place.phone as string | null) ?? null,
name: place.name,
description: place.description ?? null,
lat: place.lat ?? null,
lng: place.lng ?? null,
address: place.address ?? null,
category_id: place.category_id ?? null,
price: place.price ?? null,
currency: place.currency ?? null,
notes: place.notes ?? null,
image_url: place.image_url ?? null,
google_place_id: place.google_place_id ?? null,
google_ftid: place.google_ftid ?? null,
osm_id: place.osm_id ?? null,
website: place.website ?? null,
phone: place.phone ?? null,
source_trip_id: tripId,
source_place_id: placeId,
force,
@@ -810,28 +828,11 @@ export class CollectionsService {
* what this import exists for, so the dialog pre-selects them. */
async importablePlaces(userId: number, collectionId: number, tripId: number): Promise<CollectionImportablesResponse> {
await this.assertCanEdit(userId, collectionId);
if (!(await this.db.canAccessTrip(tripId, userId))) httpError(404, 'Trip not found');
if (!(await this.trips.findAccessible(tripId, userId))) httpError(404, 'Trip not found');
// One row per place: a place can sit on several days, so the day columns resolve to the
// earliest one rather than multiplying the place out across its assignments.
const rows = this.db.all<{
place_id: number; name: string; address: string | null; lat: number | null; lng: number | null;
category_id: number | null; image_url: string | null; day_number: number | null; date: string | null;
google_place_id: string | null; google_ftid: string | null; osm_id: string | null;
}>(`
SELECT p.id AS place_id, p.name, p.address, p.lat, p.lng, p.category_id, p.image_url,
p.google_place_id, p.google_ftid, p.osm_id,
(SELECT MIN(d.day_number) FROM day_assignments da
JOIN days d ON d.id = da.day_id
WHERE da.place_id = p.id AND d.trip_id = p.trip_id) AS day_number,
(SELECT d.date FROM day_assignments da
JOIN days d ON d.id = da.day_id
WHERE da.place_id = p.id AND d.trip_id = p.trip_id
ORDER BY d.day_number ASC LIMIT 1) AS date
FROM places p
WHERE p.trip_id = ?
ORDER BY p.name COLLATE NOCASE
`, tripId);
const rows = await this.tripPlaces.listImportable(tripId);
const places: CollectionImportablesResponse['places'] = [];
for (const r of rows) {
@@ -853,48 +854,45 @@ export class CollectionsService {
userId: number, collectionId: number, tripId: number, placeIds: number[], force?: boolean, socketId?: string,
): Promise<{ copied: number; skipped: { id: number; name: string }[] }> {
await this.assertCanEdit(userId, collectionId);
if (!(await this.db.canAccessTrip(tripId, userId))) httpError(404, 'Trip not found');
if (!(await this.trips.findAccessible(tripId, userId))) httpError(404, 'Trip not found');
const ownerId = await this.ownerOf(collectionId);
const insert = this.db.prepare(`
INSERT INTO collection_places (
collection_id, owner_id, saved_by, name, description, lat, lng, address,
category_id, price, currency, notes, image_url, google_place_id, google_ftid,
osm_id, website, phone, status, source_trip_id, source_place_id, links
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'idea', ?, ?, NULL)
`);
let copied = 0;
const skipped: { id: number; name: string }[] = [];
// The whole batch is one logical write — atomic since the post-fold quirk pass.
await this.uow.transactional(async () => {
for (const placeId of placeIds) {
const p = this.db.get<Record<string, unknown>>('SELECT * FROM places WHERE id = ? AND trip_id = ?', placeId, tripId);
const p = await this.tripPlaces.findInTrip(placeId, tripId);
if (!p) continue;
const name = p.name as string;
const lat = (p.lat as number | null) ?? null;
const lng = (p.lng as number | null) ?? null;
const name = p.name;
const lat = p.lat ?? null;
const lng = p.lng ?? null;
// The provider ids go with it: they are already carried into the insert
// below, so leaving them out here would recognise less than the row that
// gets written knows about.
const candidate = {
name, lat, lng,
google_place_id: (p.google_place_id as string | null) ?? null,
google_ftid: (p.google_ftid as string | null) ?? null,
osm_id: (p.osm_id as string | null) ?? null,
google_place_id: p.google_place_id ?? null,
google_ftid: p.google_ftid ?? null,
osm_id: p.osm_id ?? null,
};
if (!force && await this.findDuplicateCollectionPlace(collectionId, candidate)) {
skipped.push({ id: placeId, name });
continue;
}
const res = insert.run(
collectionId, ownerId, userId,
name, (p.description as string | null) ?? null, lat, lng, (p.address as string | null) ?? null,
(p.category_id as number | null) ?? null, (p.price as number | null) ?? null, (p.currency as string | null) ?? null, (p.notes as string | null) ?? null,
(p.image_url as string | null) ?? null, (p.google_place_id as string | null) ?? null, (p.google_ftid as string | null) ?? null,
(p.osm_id as string | null) ?? null, (p.website as string | null) ?? null, (p.phone as string | null) ?? null,
tripId, placeId,
);
await this.copyTripRatings(placeId, Number(res.lastInsertRowid), collectionId);
// Same 22-column insert shape as `savePlace` (CL42), with `status`/`links`
// hardcoded ('idea'/null) exactly the way the legacy statement bound them
// as literals rather than placeholders — see `insertSavedPlace`'s own
// docstring for why this is the SAME method, not a second insert shape.
const newId = await this.collectionPlaces.insertSavedPlace({
collection_id: collectionId, owner_id: ownerId, saved_by: userId,
name, description: p.description ?? null, lat, lng, address: p.address ?? null,
category_id: p.category_id ?? null, price: p.price ?? null, currency: p.currency ?? null, notes: p.notes ?? null,
image_url: p.image_url ?? null, google_place_id: p.google_place_id ?? null, google_ftid: p.google_ftid ?? null,
osm_id: p.osm_id ?? null, website: p.website ?? null, phone: p.phone ?? null,
status: 'idea', source_trip_id: tripId, source_place_id: placeId, links: null,
});
await this.copyTripRatings(placeId, newId, collectionId);
copied++;
}
});
@@ -908,48 +906,41 @@ export class CollectionsService {
// Capture the previous thumbnail so a replaced/cleared custom upload (#1136)
// can be reclaimed once nothing references it any more.
const prevImage = body.image_url !== undefined
? this.db.get<{ image_url: string | null }>('SELECT image_url FROM collection_places WHERE id = ?', placeId)?.image_url ?? null
: null;
const prevImage = body.image_url !== undefined ? (await this.collectionPlaces.imageUrl(placeId)) ?? null : null;
const updates: string[] = [];
const params: (string | number | null)[] = [];
if (body.name !== undefined) { updates.push('name = ?'); params.push(body.name); }
if (body.description !== undefined) { updates.push('description = ?'); params.push(body.description ?? null); }
if (body.notes !== undefined) { updates.push('notes = ?'); params.push(body.notes ?? null); }
if (body.lat !== undefined) { updates.push('lat = ?'); params.push(body.lat ?? null); }
if (body.lng !== undefined) { updates.push('lng = ?'); params.push(body.lng ?? null); }
if (body.address !== undefined) { updates.push('address = ?'); params.push(body.address ?? null); }
if (body.status !== undefined) { updates.push('status = ?'); params.push(body.status); }
if (body.category_id !== undefined) { updates.push('category_id = ?'); params.push(body.category_id ?? null); }
if (body.image_url !== undefined) { updates.push('image_url = ?'); params.push(body.image_url ?? null); }
if (body.links !== undefined) { updates.push('links = ?'); params.push(serializeLinks(body.links)); }
const write: Parameters<CollectionPlacesRepository['updateFields']>[1] = {};
if (body.name !== undefined) write.name = body.name;
if (body.description !== undefined) write.description = body.description ?? null;
if (body.notes !== undefined) write.notes = body.notes ?? null;
if (body.lat !== undefined) write.lat = body.lat ?? null;
if (body.lng !== undefined) write.lng = body.lng ?? null;
if (body.address !== undefined) write.address = body.address ?? null;
if (body.status !== undefined) write.status = body.status;
if (body.category_id !== undefined) write.category_id = body.category_id ?? null;
if (body.image_url !== undefined) write.image_url = body.image_url ?? null;
if (body.links !== undefined) write.links = serializeLinks(body.links);
let movedTo: number | null = null;
if (body.collection_id !== undefined && body.collection_id !== currentCollection) {
await this.assertCanEdit(userId, body.collection_id);
updates.push('collection_id = ?'); params.push(body.collection_id);
updates.push('owner_id = ?'); params.push(await this.ownerOf(body.collection_id));
write.collection_id = body.collection_id;
write.owner_id = await this.ownerOf(body.collection_id);
movedTo = body.collection_id;
}
// Field update + tag rewrite + label rewrite are one logical write — atomic
// since the post-fold quirk pass.
await this.uow.transactional(async () => {
if (updates.length > 0) {
updates.push("updated_at = CURRENT_TIMESTAMP");
params.push(placeId);
this.db.run(`UPDATE collection_places SET ${updates.join(', ')} WHERE id = ?`, ...params);
}
await this.collectionPlaces.updateFields(placeId, write);
if (body.tag_ids !== undefined) {
this.db.run('DELETE FROM collection_place_tags WHERE collection_place_id = ?', placeId);
await this.collectionPlaces.deleteTags(placeId);
await this.attachTags(placeId, body.tag_ids);
}
// Labels are collection-scoped: a move invalidates the source list's labels;
// a provided label_ids set replaces them against the (target) collection.
if (movedTo) this.db.run('DELETE FROM collection_place_labels WHERE collection_place_id = ?', placeId);
if (movedTo) await this.collectionPlaces.deleteLabelAssignments(placeId);
if (body.label_ids !== undefined) await this.setPlaceLabels(placeId, movedTo ?? currentCollection, body.label_ids);
});
@@ -965,7 +956,7 @@ export class CollectionsService {
async setStatus(userId: number, placeId: number, status: CollectionStatus, socketId?: string): Promise<CollectionPlace> {
const collectionId = await this.collectionIdOfPlace(placeId);
await this.assertCanEdit(userId, collectionId);
this.db.run("UPDATE collection_places SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", status, placeId);
await this.collectionPlaces.setStatus(placeId, status);
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
return this.getPlaceById(placeId);
}
@@ -979,12 +970,9 @@ export class CollectionsService {
const collectionId = await this.collectionIdOfPlace(placeId);
await this.assertAccess(userId, collectionId);
if (rating === null) {
this.db.run('DELETE FROM collection_place_ratings WHERE collection_place_id = ? AND user_id = ?', placeId, userId);
await this.collectionPlaceRatings.deleteRating(placeId, userId);
} else {
this.db.run(`
INSERT INTO collection_place_ratings (collection_place_id, user_id, rating) VALUES (?, ?, ?)
ON CONFLICT(collection_place_id, user_id) DO UPDATE SET rating = excluded.rating
`, placeId, userId, rating);
await this.collectionPlaceRatings.upsertRating(placeId, userId, rating);
}
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
return this.getPlaceById(placeId);
@@ -993,8 +981,8 @@ export class CollectionsService {
async deletePlace(userId: number, placeId: number, socketId?: string): Promise<void> {
const collectionId = await this.collectionIdOfPlace(placeId);
await this.assertCanDelete(userId, collectionId);
const image = this.db.get<{ image_url: string | null }>('SELECT image_url FROM collection_places WHERE id = ?', placeId)?.image_url ?? null;
this.db.run('DELETE FROM collection_places WHERE id = ?', placeId); // CASCADE drops tags. NO photo-cache reclaim.
const image = (await this.collectionPlaces.imageUrl(placeId)) ?? null;
await this.collectionPlaces.deleteById(placeId); // CASCADE drops tags. NO photo-cache reclaim.
await reclaimPlaceImage(this.storage, image);
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
}
@@ -1010,12 +998,12 @@ export class CollectionsService {
for (const id of ids) {
const collectionId = await this.collectionIdOfPlace(id);
await this.assertCanDelete(userId, collectionId);
images.push(this.db.get<{ image_url: string | null }>('SELECT image_url FROM collection_places WHERE id = ?', id)?.image_url ?? null);
images.push((await this.collectionPlaces.imageUrl(id)) ?? null);
touched.add(collectionId);
}
await this.uow.transactional(async () => {
for (const id of ids) {
this.db.run('DELETE FROM collection_places WHERE id = ?', id);
await this.collectionPlaces.deleteById(id);
deleted.push(id);
}
});
@@ -1042,11 +1030,7 @@ export class CollectionsService {
let updated = 0;
await this.uow.transactional(async () => {
for (const id of ids) {
const res = this.db.run(
"UPDATE collection_places SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND status IS NOT ?",
status, id, status,
);
updated += res.changes;
updated += await this.collectionPlaces.setStatusIfChanged(id, status);
}
});
if (updated > 0) for (const cid of touched) await this.notifyCollectionUsers(cid, socketId, 'collections:updated');
@@ -1070,14 +1054,9 @@ export class CollectionsService {
status: CollectionStatus,
socketId?: string,
): Promise<{ updated: number; places: number }> {
if (!(await this.db.canAccessTrip(tripId, userId))) httpError(404, 'Trip not found');
if (!(await this.trips.findAccessible(tripId, userId))) httpError(404, 'Trip not found');
const sources = placeIds.length
? this.db.all<{ id: number; name: string; lat: number | null; lng: number | null; google_place_id: string | null; google_ftid: string | null; osm_id: string | null }>(`
SELECT id, name, lat, lng, google_place_id, google_ftid, osm_id
FROM places WHERE trip_id = ? AND id IN (${placeIds.map(() => '?').join(',')})
`, tripId, ...placeIds)
: [];
const sources = placeIds.length ? await this.tripPlaces.listByTripAndIds(tripId, placeIds) : [];
if (sources.length === 0) return { updated: 0, places: 0 };
const editable: number[] = [];
@@ -1113,27 +1092,15 @@ export class CollectionsService {
tripId: number,
place: { id: number; lat: number | null; lng: number | null; google_place_id: string | null; google_ftid: string | null; osm_id: string | null },
): Promise<Array<{ id: number }>> {
const conditions: string[] = ['(cp.source_trip_id = ? AND cp.source_place_id = ?)'];
const params: (string | number)[] = [...collectionIds, tripId, place.id];
if (place.google_place_id) { conditions.push('cp.google_place_id = ?'); params.push(place.google_place_id); }
if (place.google_ftid) { conditions.push('cp.google_ftid = ?'); params.push(place.google_ftid); }
if (place.osm_id) { conditions.push('cp.osm_id = ?'); params.push(place.osm_id); }
if (place.lat != null && place.lng != null) {
conditions.push('(cp.lat IS NOT NULL AND cp.lng IS NOT NULL AND abs(cp.lat - ?) <= ? AND abs(cp.lng - ?) <= ?)');
params.push(place.lat, COORD_DEDUP_TOLERANCE, place.lng, COORD_DEDUP_TOLERANCE);
}
return this.db.all<{ id: number }>(`
SELECT cp.id FROM collection_places cp
WHERE cp.collection_id IN (${collectionIds.map(() => '?').join(',')}) AND (${conditions.join(' OR ')})
`, ...params);
return this.collectionPlaces.matchingByTripSource(collectionIds, tripId, place, COORD_DEDUP_TOLERANCE);
}
/** Set (or clear) a saved place's custom thumbnail, reclaiming the previous upload. */
async setPlaceImage(userId: number, placeId: number, imageUrl: string | null, socketId?: string): Promise<CollectionPlace> {
const collectionId = await this.collectionIdOfPlace(placeId);
await this.assertCanEdit(userId, collectionId);
const prev = this.db.get<{ image_url: string | null }>('SELECT image_url FROM collection_places WHERE id = ?', placeId)?.image_url ?? null;
this.db.run('UPDATE collection_places SET image_url = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', imageUrl, placeId);
const prev = (await this.collectionPlaces.imageUrl(placeId)) ?? null;
await this.collectionPlaces.setImageUrl(placeId, imageUrl);
if (prev !== imageUrl) await reclaimPlaceImage(this.storage, prev);
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
return this.getPlaceById(placeId);
@@ -1144,9 +1111,12 @@ export class CollectionsService {
// -------------------------------------------------------------------------
async copyToTrip(userId: number, body: CollectionCopyToTripRequest): Promise<{ copied: number; skipped: { id: number; name: string }[] }> {
const trip = await this.db.canAccessTrip(body.trip_id, userId);
// R6's OPPOSITE order from `savePlace`: trip access (AP6, this method's own
// entry guard) FIRST, then the `place_edit` permission check SECOND — each
// method preserves its OWN legacy order independently, never forced to match.
const trip = await this.trips.findAccessible(body.trip_id, userId);
if (!trip) httpError(404, 'Trip not found');
const role = this.db.get<{ role: string }>('SELECT role FROM users WHERE id = ?', userId)?.role ?? 'user';
const role = (await this.users.getRole(userId)) ?? 'user';
if (!(await this.permissions.checkPermission('place_edit', role, trip.user_id, userId, trip.user_id !== userId))) {
httpError(403, 'Not allowed to edit this trip');
}
@@ -1155,21 +1125,14 @@ export class CollectionsService {
// so copying never surfaces a collection member with no tie to the trip.
// Symmetric with copyTripRatings' collection-member filter (#1435).
const tripMemberIds = new Set<number>([trip.user_id]);
for (const r of this.db.all<{ user_id: number }>('SELECT user_id FROM trip_members WHERE trip_id = ?', body.trip_id)) {
tripMemberIds.add(r.user_id);
for (const memberId of await this.tripMembers.listUserIdsByTrip(body.trip_id)) {
tripMemberIds.add(memberId);
}
// Visibility on every SOURCE place — no cross-user exfiltration via copy.
const sources: Array<{ id: number; name: string; description: string | null; lat: number | null; lng: number | null;
address: string | null; category_id: number | null; price: number | null; currency: string | null;
notes: string | null; image_url: string | null; google_place_id: string | null; google_ftid: string | null;
osm_id: string | null; website: string | null; phone: string | null; collection_id: number }> = [];
const sources: CollectionPlaceCopyRow[] = [];
for (const pid of body.place_ids) {
const row = this.db.get<(typeof sources)[number]>(`
SELECT id, collection_id, name, description, lat, lng, address, category_id, price, currency,
notes, image_url, google_place_id, google_ftid, osm_id, website, phone
FROM collection_places WHERE id = ?
`, pid);
const row = await this.collectionPlaces.findForCopy(pid);
if (!row) httpError(404, 'Place not found');
await this.assertAccess(userId, row.collection_id);
sources.push(row);
@@ -1177,10 +1140,7 @@ export class CollectionsService {
// Trip dedup set — same helpers the importers use, so a place renamed in the
// trip is still recognised by its provider id when it is copied again (#1550).
const existing = this.db.all<{
name: string | null; lat: number | null; lng: number | null;
google_place_id: string | null; google_ftid: string | null; osm_id: string | null;
}>('SELECT name, lat, lng, google_place_id, google_ftid, osm_id FROM places WHERE trip_id = ?', body.trip_id);
const existing = await this.tripPlaces.dedupCandidatesForTrip(body.trip_id);
const dedup: DedupSet = { names: new Set(), coords: [], externalIds: new Set() };
for (const r of existing) {
for (const id of externalIdsOf(r)) dedup.externalIds.add(id);
@@ -1188,14 +1148,6 @@ export class CollectionsService {
else if (r.lat != null && r.lng != null) dedup.coords.push({ lat: r.lat, lng: r.lng });
}
const insertPlace = this.db.prepare(`
INSERT INTO places (trip_id, name, description, lat, lng, address, category_id, price,
currency, notes, image_url, google_place_id, google_ftid, website, phone, osm_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const insertTag = this.db.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)');
const insertRating = this.db.prepare('INSERT OR IGNORE INTO place_ratings (place_id, user_id, rating) VALUES (?, ?, ?)');
let copied = 0;
const skipped: { id: number; name: string }[] = [];
// The whole copy is one logical write — atomic since the post-fold quirk pass.
@@ -1208,18 +1160,22 @@ export class CollectionsService {
skipped.push({ id: s.id, name: s.name });
continue;
}
const res = insertPlace.run(
body.trip_id, s.name, s.description, s.lat, s.lng, s.address, s.category_id, s.price,
s.currency, s.notes, s.image_url, s.google_place_id, s.google_ftid, s.website, s.phone, s.osm_id,
);
const newPlaceId = Number(res.lastInsertRowid);
const tagIds = this.db.all<{ tag_id: number }>('SELECT tag_id FROM collection_place_tags WHERE collection_place_id = ?', s.id);
for (const t of tagIds) insertTag.run(newPlaceId, t.tag_id);
// CL64 — cross-domain WRITE into 3c's `places`, gated by the trip-access +
// permission checks above (the cross-tenant guard: a caller who can see
// the collection place but not the target trip never reaches this write).
const newPlaceId = await this.tripPlaces.insertFromCollectionPlace({
trip_id: body.trip_id, name: s.name, description: s.description, lat: s.lat, lng: s.lng,
address: s.address, category_id: s.category_id, price: s.price, currency: s.currency,
notes: s.notes, image_url: s.image_url, google_place_id: s.google_place_id, google_ftid: s.google_ftid,
website: s.website, phone: s.phone, osm_id: s.osm_id,
});
const tagIds = await this.collectionPlaces.tagIdsFor(s.id);
await this.tags.insertIgnore(newPlaceId, tagIds);
// Ratings travel into the trip too (#1435), but only for trip members — a
// collection voter who isn't on the trip stays out of it. Trip members keep
// voting there; nothing is mirrored back.
const votes = this.db.all<{ user_id: number; rating: number }>('SELECT user_id, rating FROM collection_place_ratings WHERE collection_place_id = ?', s.id);
for (const v of votes) if (tripMemberIds.has(v.user_id)) insertRating.run(newPlaceId, v.user_id, v.rating);
const votes = await this.collectionPlaceRatings.listForPlace(s.id);
for (const v of votes) if (tripMemberIds.has(v.user_id)) await this.tripPlaceRatings.insertIgnore(newPlaceId, v.user_id, v.rating);
trackInsertedInDedupSet(s, dedup);
copied++;
@@ -1238,29 +1194,15 @@ export class CollectionsService {
): Promise<CollectionMembership> {
const ids = await this.accessibleCollectionIds(userId);
if (ids.length === 0) return { saved: false, lists: [] };
const placeholders = ids.map(() => '?').join(',');
const conditions: string[] = [];
const params: (string | number)[] = [...ids];
if (query.google_place_id) { conditions.push('cp.google_place_id = ?'); params.push(query.google_place_id); }
if (query.google_ftid) { conditions.push('cp.google_ftid = ?'); params.push(query.google_ftid); }
// Coordinate proximity is the location signal. A bare NAME match is deliberately
// NOT a condition on its own — "Starbucks" (or any repeated name) would otherwise
// false-positive the inspector's "already saved" bookmark. When coords are given
// the name still effectively matches via the same-location row below; without an
// id or coords there is nothing strong enough to claim it's the same place.
if (query.lat != null && query.lng != null) {
conditions.push('(cp.lat IS NOT NULL AND cp.lng IS NOT NULL AND abs(cp.lat - ?) <= ? AND abs(cp.lng - ?) <= ?)');
params.push(query.lat, COORD_DEDUP_TOLERANCE, query.lng, COORD_DEDUP_TOLERANCE);
}
if (conditions.length === 0) return { saved: false, lists: [] };
const rows = this.db.all<{ place_id: number; collection_id: number; name: string; status: CollectionStatus }>(`
SELECT cp.id AS place_id, cp.collection_id, c.name, cp.status
FROM collection_places cp
JOIN collections c ON c.id = cp.collection_id
WHERE cp.collection_id IN (${placeholders}) AND (${conditions.join(' OR ')})
`, ...params);
// RULE 23: `searchMembership` builds this OR as typed Kysely expressions, never
// a string-built WHERE — `query.name` plays no part in the SQL either way.
const rows = await this.collectionPlaces.searchMembership(ids, query, COORD_DEDUP_TOLERANCE);
const lists: CollectionMembership['lists'] = [];
for (const r of rows) {
@@ -1269,7 +1211,7 @@ export class CollectionsService {
collection_id: r.collection_id,
name: r.name,
place_id: r.place_id,
status: r.status ?? 'idea',
status: (r.status as CollectionStatus) ?? 'idea',
can_edit: role !== null && role !== 'viewer',
});
}
@@ -1285,11 +1227,11 @@ export class CollectionsService {
excludeSid: string | undefined,
event: 'collections:updated' | 'collections:accepted' | 'collections:declined' | 'collections:left' = 'collections:updated',
): Promise<void> {
const owner = this.db.get<{ owner_id: number }>('SELECT owner_id FROM collections WHERE id = ?', collectionId);
if (!owner) return;
const userIds = [owner.owner_id];
const members = this.db.all<{ user_id: number }>("SELECT user_id FROM collection_members WHERE collection_id = ? AND status = 'accepted'", collectionId);
members.forEach(m => userIds.push(m.user_id));
const ownerId = await this.collectionsRepo.ownerId(collectionId);
if (ownerId === undefined) return;
const userIds = [ownerId];
const members = await this.members.acceptedUserIds(collectionId);
members.forEach(id => userIds.push(id));
userIds.forEach(id => this.realtime.broadcastToUser(id, { type: event, collectionId }, excludeSid));
}
@@ -1300,59 +1242,53 @@ export class CollectionsService {
// -------------------------------------------------------------------------
private async collectionIdOfLabel(labelId: number): Promise<number> {
const row = this.db.get<{ collection_id: number }>('SELECT collection_id FROM collection_labels WHERE id = ?', labelId);
if (!row) httpError(404, 'Label not found');
return row.collection_id;
const collectionId = await this.labels.collectionIdOf(labelId);
if (collectionId === undefined) httpError(404, 'Label not found');
return collectionId;
}
private async getLabelById(labelId: number): Promise<CollectionLabel> {
return this.db.get<CollectionLabel>('SELECT id, collection_id, name, color, sort_order FROM collection_labels WHERE id = ?', labelId) as CollectionLabel;
return (await this.labels.findById(labelId)) as CollectionLabel;
}
/** Replace a place's label assignments, keeping only labels of `collectionId`. */
private async setPlaceLabels(placeId: number, collectionId: number, labelIds: number[]): Promise<void> {
this.db.run('DELETE FROM collection_place_labels WHERE collection_place_id = ?', placeId);
await this.collectionPlaces.deleteLabelAssignments(placeId);
if (labelIds.length === 0) return;
const valid = new Set((await this.loadLabelsByCollection(collectionId)).map(l => l.id));
const stmt = this.db.prepare('INSERT OR IGNORE INTO collection_place_labels (collection_place_id, label_id) VALUES (?, ?)');
for (const id of labelIds) if (valid.has(id)) stmt.run(placeId, id);
for (const id of labelIds) if (valid.has(id)) await this.collectionsRepo.assignPlaceLabel(placeId, id);
}
async createLabel(userId: number, collectionId: number, name: string, color?: string, socketId?: string): Promise<CollectionLabel> {
await this.assertCanEdit(userId, collectionId);
const trimmed = name.trim();
if (!trimmed) httpError(400, 'Label name is required');
const count = this.db.get<{ n: number }>('SELECT COUNT(*) AS n FROM collection_labels WHERE collection_id = ?', collectionId)!.n;
const count = await this.labels.countByCollection(collectionId);
if (count >= MAX_LABELS_PER_COLLECTION) httpError(400, `A list can have at most ${MAX_LABELS_PER_COLLECTION} labels`);
if (this.db.get('SELECT 1 FROM collection_labels WHERE collection_id = ? AND lower(name) = lower(?)', collectionId, trimmed)) {
if (await this.labels.nameExists(collectionId, trimmed)) {
httpError(409, 'A label with this name already exists');
}
const nextSort = this.db.get<{ m: number }>('SELECT COALESCE(MAX(sort_order), -1) AS m FROM collection_labels WHERE collection_id = ?', collectionId)!.m + 1;
const res = this.db.run('INSERT INTO collection_labels (collection_id, name, color, sort_order) VALUES (?, ?, ?, ?)',
collectionId, trimmed, color ?? '#6366f1', nextSort);
const nextSort = (await this.labels.maxSortOrder(collectionId)) + 1;
const newId = await this.labels.insertLabel({ collection_id: collectionId, name: trimmed, color: color ?? '#6366f1', sort_order: nextSort });
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
return this.getLabelById(Number(res.lastInsertRowid));
return this.getLabelById(newId);
}
async updateLabel(userId: number, labelId: number, body: { name?: string; color?: string; sort_order?: number }, socketId?: string): Promise<CollectionLabel> {
const collectionId = await this.collectionIdOfLabel(labelId);
await this.assertCanEdit(userId, collectionId);
const updates: string[] = [];
const params: (string | number)[] = [];
const write: Parameters<CollectionLabelsRepository['updateFields']>[1] = {};
if (body.name !== undefined) {
const trimmed = body.name.trim();
if (!trimmed) httpError(400, 'Label name is required');
if (this.db.get('SELECT 1 FROM collection_labels WHERE collection_id = ? AND lower(name) = lower(?) AND id != ?', collectionId, trimmed, labelId)) {
if (await this.labels.nameExistsExcluding(collectionId, trimmed, labelId)) {
httpError(409, 'A label with this name already exists');
}
updates.push('name = ?'); params.push(trimmed);
}
if (body.color !== undefined) { updates.push('color = ?'); params.push(body.color); }
if (body.sort_order !== undefined) { updates.push('sort_order = ?'); params.push(body.sort_order); }
if (updates.length > 0) {
params.push(labelId);
this.db.run(`UPDATE collection_labels SET ${updates.join(', ')} WHERE id = ?`, ...params);
write.name = trimmed;
}
if (body.color !== undefined) write.color = body.color;
if (body.sort_order !== undefined) write.sort_order = body.sort_order;
await this.labels.updateFields(labelId, write);
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
return this.getLabelById(labelId);
}
@@ -1360,7 +1296,7 @@ export class CollectionsService {
async deleteLabel(userId: number, labelId: number, socketId?: string): Promise<void> {
const collectionId = await this.collectionIdOfLabel(labelId);
await this.assertCanEdit(userId, collectionId);
this.db.run('DELETE FROM collection_labels WHERE id = ?', labelId); // CASCADE clears place assignments
await this.labels.deleteById(labelId); // CASCADE clears place assignments
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
}
@@ -1388,11 +1324,9 @@ export class CollectionsService {
const applicable = labelIds.filter(id => valid.has(id));
if (applicable.length === 0) continue;
if (remove) {
const del = this.db.prepare('DELETE FROM collection_place_labels WHERE collection_place_id = ? AND label_id = ?');
for (const pid of pids) for (const lid of applicable) changed += del.run(pid, lid).changes;
for (const pid of pids) for (const lid of applicable) changed += await this.collectionPlaces.unassignLabel(pid, lid);
} else {
const ins = this.db.prepare('INSERT OR IGNORE INTO collection_place_labels (collection_place_id, label_id) VALUES (?, ?)');
for (const pid of pids) for (const lid of applicable) changed += ins.run(pid, lid).changes;
for (const pid of pids) for (const lid of applicable) changed += await this.collectionPlaces.assignLabel(pid, lid);
}
notified.push(cid);
}
@@ -1412,16 +1346,16 @@ export class CollectionsService {
if (!(await this.isOwner(inviterId, collectionId))) return { error: 'Not allowed', status: 403 };
if (targetUserId === inviterId) return { error: 'Cannot invite yourself', status: 400 };
const targetUser = this.db.get('SELECT id, username FROM users WHERE id = ?', targetUserId);
const targetUser = await this.users.findIdUsername(targetUserId);
if (!targetUser) return { error: 'User not found', status: 404 };
const existing = this.db.get<{ id: number; status: string }>('SELECT id, status FROM collection_members WHERE collection_id = ? AND user_id = ?', collectionId, targetUserId);
const existing = await this.members.findByCollectionAndUser(collectionId, targetUserId);
if (existing) {
if (existing.status === 'accepted') return { error: 'Already a member', status: 400 };
if (existing.status === 'pending') return { error: 'Invite already pending', status: 400 };
}
this.db.run("INSERT INTO collection_members (collection_id, user_id, status, role) VALUES (?, ?, 'pending', ?)", collectionId, targetUserId, role);
await this.members.insertInvite(collectionId, targetUserId, role);
this.realtime.broadcastToUser(targetUserId, { type: 'collections:invite', from: { id: inviterId, username: inviterUsername }, collectionId });
@@ -1435,27 +1369,27 @@ export class CollectionsService {
}
async acceptInvite(userId: number, collectionId: number, socketId: string | undefined): Promise<{ error?: string; status?: number }> {
const invite = this.db.get<{ id: number }>("SELECT id FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'pending'", collectionId, userId);
if (!invite) return { error: 'No pending invite', status: 404 };
this.db.run("UPDATE collection_members SET status = 'accepted' WHERE id = ?", invite.id);
const inviteId = await this.members.findPendingInvite(collectionId, userId);
if (inviteId === undefined) return { error: 'No pending invite', status: 404 };
await this.members.accept(inviteId);
await this.notifyCollectionUsers(collectionId, socketId, 'collections:accepted');
return {};
}
async declineInvite(userId: number, collectionId: number, socketId: string | undefined): Promise<void> {
this.db.run("DELETE FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'pending'", collectionId, userId);
await this.members.deletePending(collectionId, userId);
await this.notifyCollectionUsers(collectionId, socketId, 'collections:declined');
}
async cancelInvite(collectionId: number, ownerId: number, targetUserId: number): Promise<void> {
if (!(await this.isOwner(ownerId, collectionId))) httpError(403, 'Not allowed');
this.db.run("DELETE FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'pending'", collectionId, targetUserId);
await this.members.deletePending(collectionId, targetUserId);
this.realtime.broadcastToUser(targetUserId, { type: 'collections:cancelled', collectionId });
}
async leaveCollection(userId: number, collectionId: number, socketId: string | undefined): Promise<void> {
if (await this.isOwner(userId, collectionId)) httpError(400, 'Owner cannot leave; delete the list');
this.db.run("DELETE FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'accepted'", collectionId, userId);
await this.members.deleteAccepted(collectionId, userId);
await this.notifyCollectionUsers(collectionId, socketId, 'collections:left');
}
@@ -1463,8 +1397,8 @@ export class CollectionsService {
async removeMember(ownerId: number, collectionId: number, targetUserId: number): Promise<void> {
if (!(await this.isOwner(ownerId, collectionId))) httpError(403, 'Not allowed');
if (targetUserId === ownerId) httpError(400, 'Owner cannot be removed');
const res = this.db.run("DELETE FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'accepted'", collectionId, targetUserId);
if (res.changes === 0) httpError(404, 'Member not found');
const changed = await this.members.deleteAccepted(collectionId, targetUserId);
if (changed === 0) httpError(404, 'Member not found');
await this.notifyCollectionUsers(collectionId, undefined, 'collections:left'); // refresh remaining members
this.realtime.broadcastToUser(targetUserId, { type: 'collections:removed', collectionId }); // bounce the removed user
}
@@ -1472,25 +1406,19 @@ export class CollectionsService {
/** Owner changes an accepted member's permission role (viewer/editor/admin). */
async setMemberRole(ownerId: number, collectionId: number, targetUserId: number, role: 'viewer' | 'editor' | 'admin'): Promise<void> {
if (!(await this.isOwner(ownerId, collectionId))) httpError(403, 'Not allowed');
const res = this.db.run("UPDATE collection_members SET role = ? WHERE collection_id = ? AND user_id = ? AND status = 'accepted'", role, collectionId, targetUserId);
if (res.changes === 0) httpError(404, 'Member not found');
const changed = await this.members.setRole(collectionId, targetUserId, role);
if (changed === 0) httpError(404, 'Member not found');
await this.notifyCollectionUsers(collectionId, undefined, 'collections:updated'); // re-gate the member live
this.realtime.broadcastToUser(targetUserId, { type: 'collections:updated', collectionId });
}
async availableUsers(ownerId: number, collectionId: number): Promise<{ id: number; username: string }[]> {
return this.db.all<{ id: number; username: string }>(`
SELECT u.id, u.username FROM users u
WHERE u.id != ?
AND u.id NOT IN (SELECT user_id FROM collection_members WHERE collection_id = ?)
AND u.is_guest = 0
ORDER BY u.username
`, ownerId, collectionId);
return this.members.availableUsers(ownerId, collectionId);
}
async findMembershipForUser(userId: number, collectionId: number): Promise<{ is_member: boolean; is_owner: boolean; status: string | null }> {
if (await this.isOwner(userId, collectionId)) return { is_member: true, is_owner: true, status: 'accepted' };
const row = this.db.get<{ status: string }>('SELECT status FROM collection_members WHERE collection_id = ? AND user_id = ?', collectionId, userId);
return { is_member: row?.status === 'accepted', is_owner: false, status: row?.status ?? null };
const status = await this.members.statusFor(collectionId, userId);
return { is_member: status === 'accepted', is_owner: false, status: status ?? null };
}
}
+11 -1
View File
@@ -132,6 +132,7 @@ import {
createTestDayAccommodationsRepo,
createTestUsersRepo,
createTestCollectionsRepo, createTestCollectionMembersRepo, createTestCollectionLabelsRepo,
createTestCollectionPlacesRepo, createTestCollectionPlaceRatingsRepo,
} from './test-uow';
import { createTestOrm } from './test-orm';
import { createTestTripFilesRepo, createTestFileLinksRepo, createTestBudgetItemsRepo } from './files-repos';
@@ -436,12 +437,21 @@ export async function createMcpTestRegistry(): Promise<McpRegistry> {
new PlacesMcp(placesService, mapsService, await createTestTripsRepo(dbService.connection), authService, journeyDomain, assignmentsService, guards, await createTestUnitOfWork(dbService.connection)),
new CollectionsMcp(
new CollectionsService(
dbService, permissionsService, realtimeService, notificationsStub(), generalStorage, await createTestUnitOfWork(dbService.connection),
permissionsService, realtimeService, notificationsStub(), generalStorage, await createTestUnitOfWork(dbService.connection),
// Plan 3h Task 1 — the constructor-ripple fix: collections part A's
// own repositories, first cut, plus the already-DONE
// `CategoriesRepository` (CL21 reuse).
await createTestCollectionsRepo(dbService.connection), await createTestCollectionMembersRepo(dbService.connection),
await createTestCollectionLabelsRepo(dbService.connection), await createTestCategoriesRepo(dbService.connection),
// Plan 3h Task 2 — part B's own repositories: `DatabaseService`
// dropped entirely (this service's LAST use of it — savePlace
// onward is now 100% off `this.db`), the trip/place/tag/user
// repositories AP1-AP6's `TripsRepository.findAccessible` calls
// and the cross-domain writes need, injected directly.
await createTestCollectionPlacesRepo(dbService.connection), await createTestCollectionPlaceRatingsRepo(dbService.connection),
await createTestTripsRepo(dbService.connection), await createTestTripMembersRepo(dbService.connection),
await createTestPlacesRepo(dbService.connection), await createTestPlaceRatingsRepo(dbService.connection),
await createTestTagsRepo(dbService.connection), usersRepo,
),
// Plan 3h Task 1 — `CollectionsMcp`'s own constructor-ripple fix:
// `DatabaseService` dropped (CL89's only use), `UsersRepository`
+10 -1
View File
@@ -77,6 +77,7 @@ import { makeStorageFixture } from './storage-fixture';
import {
createTestUnitOfWork, createTestAppSettingsRepo, createTestCategoriesRepo, createTestTagsRepo, createTestSettingsRepo, sharedTestOrm,
createTestCollectionsRepo, createTestCollectionMembersRepo, createTestCollectionLabelsRepo,
createTestCollectionPlacesRepo, createTestCollectionPlaceRatingsRepo,
createTestDaysRepo, createTestDayAssignmentsRepo, createTestDayNotesRepo, createTestTripsRepo,
createTestTripMembersRepo, createTestPlaceRatingsRepo, createTestAssignmentParticipantsRepo,
createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo, createTestRoadtripViasRepo,
@@ -204,12 +205,20 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise<
await createTestPlacesRepo(dbs.connection),
);
const collections = new CollectionsService(
dbs, permissions, realtime, notificationsStub(), generalStorage, await createTestUnitOfWork(dbs.connection),
permissions, realtime, notificationsStub(), generalStorage, await createTestUnitOfWork(dbs.connection),
// Plan 3h Task 1 — the constructor-ripple fix: collections part A's own
// repositories, first cut (`CollectionMembersRepository` extended by
// Task 2), plus the already-DONE `CategoriesRepository` (CL21 reuse).
await createTestCollectionsRepo(dbs.connection), await createTestCollectionMembersRepo(dbs.connection),
await createTestCollectionLabelsRepo(dbs.connection), await createTestCategoriesRepo(dbs.connection),
// Plan 3h Task 2 — part B's own repositories: `DatabaseService` dropped
// entirely (this service's last use of it), the trip/place/tag/user
// repositories AP1-AP6's `TripsRepository.findAccessible` calls and the
// cross-domain writes need, injected directly.
await createTestCollectionPlacesRepo(dbs.connection), await createTestCollectionPlaceRatingsRepo(dbs.connection),
await createTestTripsRepo(dbs.connection), await createTestTripMembersRepo(dbs.connection),
await createTestPlacesRepo(dbs.connection), await createTestPlaceRatingsRepo(dbs.connection),
await createTestTagsRepo(dbs.connection), usersRepo,
);
const atlas = new AtlasService(
await createTestBucketListRepo(dbs.connection), await createTestHiddenCountriesRepo(dbs.connection),
+31
View File
@@ -71,6 +71,10 @@ import { CollectionMembers } from '../../src/db/entities/CollectionMembers.entit
import type { CollectionMembersRepository } from '../../src/db/repositories/CollectionMembers.repository';
import { CollectionLabels } from '../../src/db/entities/CollectionLabels.entity';
import type { CollectionLabelsRepository } from '../../src/db/repositories/CollectionLabels.repository';
import { CollectionPlaces } from '../../src/db/entities/CollectionPlaces.entity';
import type { CollectionPlacesRepository } from '../../src/db/repositories/CollectionPlaces.repository';
import { CollectionPlaceRatings } from '../../src/db/entities/CollectionPlaceRatings.entity';
import type { CollectionPlaceRatingsRepository } from '../../src/db/repositories/CollectionPlaceRatings.repository';
const perHandle = new WeakMap<Database.Database, Promise<UnitOfWork>>();
const appSettingsPerHandle = new WeakMap<Database.Database, Promise<AppSettingsRepository>>();
@@ -630,3 +634,30 @@ export function createTestCollectionLabelsRepo(db: Database.Database): Promise<C
collectionLabelsRepoPerHandle.set(db, pending);
return pending;
}
// ---------------------------------------------------------------------------
// Plan 3h Task 2 (collections part B) — `CollectionPlacesRepository`/
// `CollectionPlaceRatingsRepository` a hand-constructed `CollectionsService`
// needs. Same memoisation-per-handle pattern as every helper above.
// ---------------------------------------------------------------------------
const collectionPlacesRepoPerHandle = new WeakMap<Database.Database, Promise<CollectionPlacesRepository>>();
const collectionPlaceRatingsRepoPerHandle = new WeakMap<Database.Database, Promise<CollectionPlaceRatingsRepository>>();
/** The `CollectionPlacesRepository` a hand-constructed `CollectionsService` needs. */
export function createTestCollectionPlacesRepo(db: Database.Database): Promise<CollectionPlacesRepository> {
const existing = collectionPlacesRepoPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(CollectionPlaces));
collectionPlacesRepoPerHandle.set(db, pending);
return pending;
}
/** The `CollectionPlaceRatingsRepository` a hand-constructed `CollectionsService` needs. */
export function createTestCollectionPlaceRatingsRepo(db: Database.Database): Promise<CollectionPlaceRatingsRepository> {
const existing = collectionPlaceRatingsRepoPerHandle.get(db);
if (existing !== undefined) return existing;
const pending = sharedTestOrm(db).then((t) => t.repo(CollectionPlaceRatings));
collectionPlaceRatingsRepoPerHandle.set(db, pending);
return pending;
}
@@ -47,7 +47,7 @@ import fs from 'fs';
import path from 'path';
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { createUser, createTrip, createPlace, createCategory, createTag, addTripMember } from '../../helpers/factories';
import { createUser, createTrip, createPlace, createCategory, createTag, addTripMember, createDay, createDayAssignment } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
@@ -56,12 +56,21 @@ import { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-pho
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { notificationsStub } from '../../helpers/notifications';
import {
createTestUnitOfWork, createTestAppSettingsRepo, createTestDatabaseService, createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo,
createTestUnitOfWork, createTestAppSettingsRepo, createTestGooglePlacePhotoMetaRepo, createTestPlacesRepo,
createTestCollectionsRepo, createTestCollectionMembersRepo, createTestCollectionLabelsRepo, createTestCategoriesRepo,
createTestCollectionPlacesRepo, createTestCollectionPlaceRatingsRepo, createTestTripsRepo, createTestTripMembersRepo,
createTestPlaceRatingsRepo, createTestTagsRepo, createTestUsersRepo,
} from '../../helpers/test-uow';
const storageFx = makeStorageFixture('');
let svc: CollectionsService;
// R6's two-layer-order proof (savePlace/copyToTrip) needs a distinguishable
// spy on the TRIP-access call — captured here so the tests below can assert
// on call order/count, not just the final HTTP status (the brief's own
// warning: a reversed check order still refuses in the end, via a different
// path, so an ordinary pass/fail test would not catch a regression).
let tripsRepoForSpy: Awaited<ReturnType<typeof createTestTripsRepo>>;
let permissionsForSpy: PermissionsService;
// The real cache: these cases assert what removeIfUnreferenced actually does
// about collection_places (#1081), so a stub would assert nothing.
// Plan 3c Task 1: built inside the async `beforeAll` below now — the
@@ -73,18 +82,22 @@ const removeIfUnreferenced = (id: string) => photoCache.removeIfUnreferenced(id)
// test (`atlas.service.test.ts`/`journey-domain.service.test.ts` precedent) — real
// repositories resolved off `sharedTestOrm(testDb)` (via `createTestXRepo` helpers,
// `allowGlobalContext: true` by default, `test-orm.ts`'s own docstring), no
// `withRequestContext` wrapper needed or added anywhere in this file. `db` (the raw
// `DatabaseService`) stays a constructor param and is still exercised directly:
// Part B's methods (saved places CRUD, copy-to-trip, labels-assignment, invites —
// Task 2's own, unconverted by this task) still issue raw `this.db.prepare(...)`
// calls the describe blocks below covering them exercise unchanged.
// `withRequestContext` wrapper needed or added anywhere in this file. Plan 3h Task 2
// (part B) finished the conversion: `DatabaseService` is GONE from the constructor
// entirely (savePlace onward was its last use) — the trip/place/tag/user
// repositories below are Task 2's own additions.
beforeAll(async () => {
tripsRepoForSpy = await createTestTripsRepo(testDb);
permissionsForSpy = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
svc = new CollectionsService(
await createTestDatabaseService(testDb),
new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)),
permissionsForSpy,
new RealtimeService(), notificationsStub(notifSend), storageFx.storage, await createTestUnitOfWork(testDb),
await createTestCollectionsRepo(testDb), await createTestCollectionMembersRepo(testDb),
await createTestCollectionLabelsRepo(testDb), await createTestCategoriesRepo(testDb),
await createTestCollectionPlacesRepo(testDb), await createTestCollectionPlaceRatingsRepo(testDb),
tripsRepoForSpy, await createTestTripMembersRepo(testDb),
await createTestPlacesRepo(testDb), await createTestPlaceRatingsRepo(testDb),
await createTestTagsRepo(testDb), await createTestUsersRepo(testDb),
);
photoCache = new PlacePhotoCacheService(
new DatabaseService(testDb),
@@ -1654,3 +1667,118 @@ describe('Plan 3h Task 1 — repository conversion parity', () => {
expect(memberCountAtBroadcastTime.length).toBeGreaterThan(0);
});
});
// ── Plan 3h Task 2 (collections part B) — R6's two-layer order + CL45/CL69 parity ──
describe('Plan 3h Task 2 — R6 two-layer authorization order', () => {
it('COLLECTIONS-SVC-210: savePlace refuses on the collection-edit gate BEFORE the trip-access check ever runs', async () => {
const owner = createUser(testDb).user;
const attacker = createUser(testDb).user;
// The attacker has NO role on this list at all (not owner, not a member).
const col = await svc.createCollection(owner.id, { name: 'No access' });
// A trip/place the ATTACKER genuinely CAN access — if the check order
// were reversed (trip-access first), this call would sail straight past
// the trip-access check and only be refused later, if at all. The spy is
// the brief's own warning made concrete: the final status alone (404,
// same as a "trip not found" 404) would not distinguish the two orders —
// only proof that the trip-access call never fired does.
const attackerTrip = createTrip(testDb, attacker.id);
const attackerPlace = createPlace(testDb, attackerTrip.id, { name: 'Mine' });
const spy = vi.spyOn(tripsRepoForSpy, 'findAccessible');
spy.mockClear();
try {
await svc.savePlace(attacker.id, {
collection_id: col.id, name: 'x', source_trip_id: attackerTrip.id, source_place_id: attackerPlace.id,
});
expect.unreachable('savePlace should have refused');
} catch (e) {
expect((e as { status: number }).status).toBe(404);
expect((e as Error).message).toBe('Collection not found');
}
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('COLLECTIONS-SVC-211: copyToTrip checks trip access BEFORE the place_edit permission check — the OPPOSITE order from savePlace', async () => {
const owner = createUser(testDb).user;
const col = await svc.createCollection(owner.id, { name: 'Copy order' });
const cp = (await svc.savePlace(owner.id, { collection_id: col.id, name: 'Somewhere' })).place!;
const strangerTrip = createTrip(testDb, createUser(testDb).user.id); // owner has no access to this trip
const spy = vi.spyOn(permissionsForSpy, 'checkPermission');
spy.mockClear();
try {
await svc.copyToTrip(owner.id, { trip_id: strangerTrip.id, place_ids: [cp.id] });
expect.unreachable('copyToTrip should have refused');
} catch (e) {
expect((e as { status: number }).status).toBe(404);
expect((e as Error).message).toBe('Trip not found');
}
// The permission check is the SECOND layer for this method — never
// reached when the first layer (trip access) already refused.
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('COLLECTIONS-SVC-212: copyToTrip into a trip the caller cannot access writes NOTHING into places (CL64/65/66 cross-tenant guard)', async () => {
const owner = createUser(testDb).user;
const col = await svc.createCollection(owner.id, { name: 'Guard proof' });
// The caller can see this collection place perfectly well (they own the
// list it lives on) — the guard that matters is the TARGET TRIP, not the
// source collection.
const cp = (await svc.savePlace(owner.id, { collection_id: col.id, name: 'Guarded' })).place!;
const strangerOwner = createUser(testDb).user;
const strangerTrip = createTrip(testDb, strangerOwner.id); // owner (the caller) is not on this trip
const before = (testDb.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = ?').get(strangerTrip.id) as { n: number }).n;
await expect(svc.copyToTrip(owner.id, { trip_id: strangerTrip.id, place_ids: [cp.id] })).rejects.toThrow();
const after = (testDb.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = ?').get(strangerTrip.id) as { n: number }).n;
expect(after).toBe(before); // no places row (CL64), and therefore no place_tags/place_ratings rows either
});
});
describe('Plan 3h Task 2 — CL45/CL69 full-key parity', () => {
it('COLLECTIONS-SVC-213: importablePlaces resolves the EARLIEST day for a place assigned to several days (CL45)', async () => {
const owner = createUser(testDb).user;
const col = await svc.createCollection(owner.id, { name: 'Import parity' });
const trip = createTrip(testDb, owner.id);
const place = createPlace(testDb, trip.id, { name: 'Multi-day spot' });
// Created (and assigned) LATER day first, earlier day second — the
// correlated MIN(day_number)/ORDER BY ... LIMIT 1 subqueries must not
// accidentally resolve to insertion order or assignment order.
const day2 = createDay(testDb, trip.id, { day_number: 2, date: '2024-06-02' });
const day1 = createDay(testDb, trip.id, { day_number: 1, date: '2024-06-01' });
createDayAssignment(testDb, day2.id, place.id);
createDayAssignment(testDb, day1.id, place.id);
const { places } = await svc.importablePlaces(owner.id, col.id, trip.id);
expect(places).toHaveLength(1);
expect(places[0].place_id).toBe(place.id);
expect(places[0].day_number).toBe(1); // MIN(day_number), not the first assignment written
expect(places[0].date).toBe('2024-06-01'); // the SAME earliest day's own date, not day2's
expect(places[0].scheduled).toBe(true);
expect(places[0].already_in_list).toBe(false);
});
it('COLLECTIONS-SVC-214: findMembership matches BOTH a provider-id-only place and a coordinate-tolerance-only place in the same OR (CL69, rule 23)', async () => {
const owner = createUser(testDb).user;
const colA = await svc.createCollection(owner.id, { name: 'Provider match' });
const colB = await svc.createCollection(owner.id, { name: 'Coord match' });
// Matches ONLY by google_place_id — its own coordinates are far from the query's.
const byProvider = (await svc.savePlace(owner.id, {
collection_id: colA.id, name: 'Provider Place', google_place_id: 'gp-parity-123', lat: 10, lng: 10,
})).place!;
// Matches ONLY by coordinate tolerance — no provider id of its own at all.
const byCoords = (await svc.savePlace(owner.id, {
collection_id: colB.id, name: 'Coord Place', lat: 48.8566, lng: 2.3522,
})).place!;
const result = await svc.findMembership(owner.id, { google_place_id: 'gp-parity-123', lat: 48.8566, lng: 2.3522 });
expect(result.saved).toBe(true);
const placeIds = result.lists.map(l => l.place_id).sort((a, b) => a - b);
// Neither branch of the typed OR dropped the other's match: a narrowed
// condition set would return only one of these two rows.
expect(placeIds).toEqual([byProvider.id, byCoords.id].sort((a, b) => a - b));
});
});