feat(collections): backend for the Overall Places addon (#1081)

Adds the Collections addon backend: a server-wide-per-user library of saved
places, independent of any trip, with multiple named lists, an idea/want/visited
status, and Vacay-style fusion invitations to share a list with other users.

- Data: collection / collection_members / collection_places / collection_place_tags
  tables (+ migration and baseline schema). Saved places carry the owner plus a
  nullable saved_by so a member deleting their account can't drop shared content.
- Service: list + place CRUD with owner-or-accepted-member visibility, dedup,
  status, save-from-trip and copy-to-trip (reusing the trip copy column list),
  and the full fusion-invitation state machine mirrored from vacay (send / accept
  / decline / cancel / leave) with a websocket broadcast and an invite
  notification. Deleting a list snapshots its members and notifies them.
- NestJS module + addon guard (404 before auth), registered in the app module.
- Widens the place photo cache reference check to count collection places so the
  nightly sweep no longer evicts photos a saved place still uses.
- collection_invite notification wired across all 22 locales.
This commit is contained in:
Maurice
2026-06-30 21:19:19 +02:00
committed by Maurice
parent 37ef3a9d18
commit ec8509f2de
67 changed files with 2150 additions and 14 deletions
+1
View File
@@ -9,6 +9,7 @@ export const ADDON_IDS = {
JOURNEY: 'journey',
AIRTRAIL: 'airtrail',
LLM_PARSING: 'llm_parsing',
COLLECTIONS: 'collections',
} as const;
export type AddonId = typeof ADDON_IDS[keyof typeof ADDON_IDS];
+75
View File
@@ -3180,6 +3180,81 @@ function runMigrations(db: Database.Database): void {
);
`);
},
// Migration 150: Collections addon — personal place library (#1081).
// Multi-list + per-place status (idea/want/visited) + fusion sharing.
// (150 = migrations.length of this array after appending — the runner uses
// migrations.length, not this comment; the label is cosmetic.)
() => {
db.prepare(
`
INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, config, sort_order)
VALUES ('collections', 'Collections', 'Personal place library — save places across trips into named lists, copy into any trip, share with others', 'global', 'Bookmark', 0, '{}', 16)
`,
).run();
db.exec(`
CREATE TABLE IF NOT EXISTS collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
color TEXT DEFAULT '#6366f1',
icon TEXT DEFAULT 'Bookmark',
cover_image TEXT,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'pending',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(collection_id, user_id)
);
CREATE TABLE IF NOT EXISTS collection_places (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
saved_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
name TEXT NOT NULL,
description TEXT,
lat REAL,
lng REAL,
address TEXT,
category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
price REAL,
currency TEXT,
notes TEXT,
image_url TEXT,
google_place_id TEXT,
google_ftid TEXT,
osm_id TEXT,
website TEXT,
phone TEXT,
status TEXT NOT NULL DEFAULT 'idea',
source_trip_id INTEGER,
source_place_id INTEGER,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_place_tags (
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
PRIMARY KEY (collection_place_id, tag_id)
);
CREATE INDEX IF NOT EXISTS idx_collection_places_collection ON collection_places(collection_id);
CREATE INDEX IF NOT EXISTS idx_collection_members_user ON collection_members(user_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_place ON collection_place_tags(collection_place_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_tag ON collection_place_tags(tag_id);
`);
},
];
if (currentVersion < migrations.length) {
+62
View File
@@ -371,6 +371,68 @@ function createTables(db: Database.Database): void {
sort_order INTEGER NOT NULL DEFAULT 0
);
-- Collections addon tables
CREATE TABLE IF NOT EXISTS collections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT,
color TEXT DEFAULT '#6366f1',
icon TEXT DEFAULT 'Bookmark',
cover_image TEXT,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'pending',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(collection_id, user_id)
);
CREATE TABLE IF NOT EXISTS collection_places (
id INTEGER PRIMARY KEY AUTOINCREMENT,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
owner_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
saved_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
name TEXT NOT NULL,
description TEXT,
lat REAL,
lng REAL,
address TEXT,
category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
price REAL,
currency TEXT,
notes TEXT,
image_url TEXT,
google_place_id TEXT,
google_ftid TEXT,
osm_id TEXT,
website TEXT,
phone TEXT,
status TEXT NOT NULL DEFAULT 'idea',
source_trip_id INTEGER,
source_place_id INTEGER,
sort_order INTEGER DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS collection_place_tags (
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
PRIMARY KEY (collection_place_id, tag_id)
);
CREATE INDEX IF NOT EXISTS idx_collection_places_collection ON collection_places(collection_id);
CREATE INDEX IF NOT EXISTS idx_collection_members_user ON collection_members(user_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_place ON collection_place_tags(collection_place_id);
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_tag ON collection_place_tags(tag_id);
CREATE TABLE IF NOT EXISTS day_accommodations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
+1
View File
@@ -121,6 +121,7 @@ function seedAddons(db: Database.Database): void {
{ id: 'journey', name: 'Journey', description: 'Trip tracking & travel journal — check-ins, photos, daily stories', type: 'global', icon: 'Compass', enabled: 0, sort_order: 35 },
{ id: 'airtrail', name: 'AirTrail', description: 'Sync flights from your self-hosted AirTrail instance', type: 'integration', icon: 'Plane', enabled: 0, sort_order: 14 },
{ id: 'llm_parsing', name: 'AI Parsing', description: 'LLM fallback for booking imports kitinerary cannot read', type: 'integration', icon: 'Sparkles', enabled: 0, sort_order: 15 },
{ id: 'collections', name: 'Collections', description: 'Personal place library — save places across trips into named lists, copy into any trip, share with others', type: 'global', icon: 'Bookmark', enabled: 0, sort_order: 16 },
];
const insertAddon = db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)');
for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order);
+2 -1
View File
@@ -28,6 +28,7 @@ import { PhotosModule } from './photos/photos.module';
import { MemoriesModule } from './memories/memories.module';
import { AirtrailModule } from './integrations/airtrail.module';
import { JourneyModule } from './journey/journey.module';
import { CollectionsModule } from './collections/collections.module';
import { ShareModule } from './share/share.module';
import { FeedsModule } from './feeds/feeds.module';
import { SettingsModule } from './settings/settings.module';
@@ -48,7 +49,7 @@ import { IdempotencyInterceptor } from './common/idempotency.interceptor';
* migrated.
*/
@Module({
imports: [DatabaseModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, MapsModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, ShareModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, BookingImportModule],
imports: [DatabaseModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, MapsModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, BookingImportModule],
controllers: [HealthController],
providers: [
HealthService,
@@ -0,0 +1,18 @@
import { CanActivate, HttpException, Injectable } from '@nestjs/common';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
/**
* Mirrors the addon mount gate: when the Collections addon is disabled the whole
* route group answers 404, regardless of auth. Declared before JwtAuthGuard so
* the addon check wins over the 401, exactly as the Journey addon guard does.
*/
@Injectable()
export class CollectionsAddonGuard implements CanActivate {
canActivate(): boolean {
if (!isAddonEnabled(ADDON_IDS.COLLECTIONS)) {
throw new HttpException({ error: 'Collections addon is not enabled' }, 404);
}
return true;
}
}
@@ -0,0 +1,228 @@
import {
Body,
Controller,
Delete,
Get,
Headers,
HttpCode,
HttpException,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import type { User } from '../../types';
import { CollectionsService } from './collections.service';
import { CollectionsAddonGuard } from './collections-addon.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { ZodValidationPipe } from '../common/zod-validation.pipe';
import {
collectionCreateRequestSchema,
collectionUpdateRequestSchema,
collectionSavePlaceRequestSchema,
collectionSaveFromTripRequestSchema,
collectionPlaceUpdateRequestSchema,
collectionSetStatusRequestSchema,
collectionCopyToTripRequestSchema,
collectionInviteRequestSchema,
collectionInviteActionRequestSchema,
collectionInviteCancelRequestSchema,
type CollectionCreateRequest,
type CollectionUpdateRequest,
type CollectionSavePlaceRequest,
type CollectionSaveFromTripRequest,
type CollectionPlaceUpdateRequest,
type CollectionSetStatusRequest,
type CollectionCopyToTripRequest,
type CollectionInviteRequest,
type CollectionInviteActionRequest,
type CollectionInviteCancelRequest,
} from '@trek/shared';
/**
* /api/addons/collections — saved-place library (lists, places, fusion sharing).
*
* The addon guard (404) runs before JwtAuthGuard so a disabled addon answers 404
* regardless of auth. Access control lives in the service (assertAccess / isOwner
* throw 404/403/400). /invite, /invite/cancel and /:id/available-users add an
* explicit owner check in the controller so they cannot be used to enumerate.
* The X-Socket-Id header is forwarded to the service so the originating client is
* excluded from the WS broadcast.
*/
@Controller('api/addons/collections')
@UseGuards(CollectionsAddonGuard, JwtAuthGuard)
export class CollectionsController {
constructor(private readonly collections: CollectionsService) {}
// ── Lists ─────────────────────────────────────────────────────────────────
@Get()
list(@CurrentUser() user: User) {
return this.collections.listCollections(user.id);
}
@Post()
create(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionCreateRequestSchema)) body: CollectionCreateRequest) {
return this.collections.createCollection(user.id, body);
}
@Post('reorder')
@HttpCode(200)
reorder(@CurrentUser() user: User, @Body('orderedIds') orderedIds: unknown) {
if (!Array.isArray(orderedIds) || !orderedIds.every((v) => Number.isFinite(Number(v)))) {
throw new HttpException({ error: 'orderedIds must be an array of numbers' }, 400);
}
this.collections.reorderCollections(user.id, orderedIds.map(Number));
return { success: true };
}
// ── Places (static prefixes before /:id) ────────────────────────────────────
@Post('places')
@HttpCode(200)
savePlace(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionSavePlaceRequestSchema)) body: CollectionSavePlaceRequest) {
return this.collections.savePlace(user.id, body);
}
@Post('places/from-trip')
@HttpCode(200)
saveFromTrip(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionSaveFromTripRequestSchema)) body: CollectionSaveFromTripRequest) {
return this.collections.saveFromTripPlace(user.id, body.collection_id, body.source_trip_id, body.source_place_id, body.force);
}
@Post('places/delete-many')
@HttpCode(200)
deleteMany(@CurrentUser() user: User, @Body('ids') ids: unknown) {
if (!Array.isArray(ids) || !ids.every((v) => Number.isFinite(Number(v)))) {
throw new HttpException({ error: 'ids must be an array of numbers' }, 400);
}
return { deleted: this.collections.deletePlacesMany(user.id, ids.map(Number)) };
}
@Patch('places/:pid')
updatePlace(
@CurrentUser() user: User,
@Param('pid') pid: string,
@Body(new ZodValidationPipe(collectionPlaceUpdateRequestSchema)) body: CollectionPlaceUpdateRequest,
) {
return this.collections.updatePlace(user.id, Number(pid), body);
}
@Post('places/:pid/status')
@HttpCode(200)
setStatus(
@CurrentUser() user: User,
@Param('pid') pid: string,
@Body(new ZodValidationPipe(collectionSetStatusRequestSchema)) body: CollectionSetStatusRequest,
) {
return this.collections.setStatus(user.id, Number(pid), body.status);
}
@Delete('places/:pid')
deletePlace(@CurrentUser() user: User, @Param('pid') pid: string) {
this.collections.deletePlace(user.id, Number(pid));
return { success: true };
}
// ── Copy to trip ────────────────────────────────────────────────────────────
@Post('copy-to-trip')
@HttpCode(200)
copyToTrip(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionCopyToTripRequestSchema)) body: CollectionCopyToTripRequest) {
return this.collections.copyToTrip(user.id, body);
}
// ── Library-wide membership lookup ──────────────────────────────────────────
@Get('membership')
membership(
@CurrentUser() user: User,
@Query('google_place_id') googlePlaceId?: string,
@Query('google_ftid') googleFtid?: string,
@Query('name') name?: string,
@Query('lat') lat?: string,
@Query('lng') lng?: string,
) {
return this.collections.findMembership(user.id, {
google_place_id: googlePlaceId,
google_ftid: googleFtid,
name,
lat: lat != null && lat !== '' ? Number(lat) : undefined,
lng: lng != null && lng !== '' ? Number(lng) : undefined,
});
}
// ── Fusion invitations ──────────────────────────────────────────────────────
@Post('invite')
@HttpCode(200)
invite(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteRequestSchema)) body: CollectionInviteRequest) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible (no enumeration)
if (!this.collections.isOwner(user.id, body.collection_id)) {
throw new HttpException({ error: 'Only the owner can invite' }, 403);
}
const result = this.collections.sendInvite(body.collection_id, user.id, user.username, user.email, body.user_id);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
return { success: true };
}
@Post('invite/accept')
@HttpCode(200)
acceptInvite(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteActionRequestSchema)) body: CollectionInviteActionRequest, @Headers('x-socket-id') socketId?: string) {
const result = this.collections.acceptInvite(user.id, body.collection_id, socketId);
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
return { success: true };
}
@Post('invite/decline')
@HttpCode(200)
declineInvite(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteActionRequestSchema)) body: CollectionInviteActionRequest, @Headers('x-socket-id') socketId?: string) {
this.collections.declineInvite(user.id, body.collection_id, socketId);
return { success: true };
}
@Post('invite/cancel')
@HttpCode(200)
cancelInvite(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteCancelRequestSchema)) body: CollectionInviteCancelRequest) {
this.collections.assertAccess(user.id, body.collection_id); // 404 if not visible
if (!this.collections.isOwner(user.id, body.collection_id)) {
throw new HttpException({ error: 'Only the owner can cancel invites' }, 403);
}
this.collections.cancelInvite(body.collection_id, user.id, body.user_id);
return { success: true };
}
@Post('leave')
@HttpCode(200)
leave(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionInviteActionRequestSchema)) body: CollectionInviteActionRequest, @Headers('x-socket-id') socketId?: string) {
this.collections.leaveCollection(user.id, body.collection_id, socketId);
return { success: true };
}
// ── /:id (declared last so static prefixes win) ─────────────────────────────
@Get(':id/available-users')
availableUsers(@CurrentUser() user: User, @Param('id') id: string) {
this.collections.assertAccess(user.id, Number(id)); // 404 if not visible (no enumeration)
if (!this.collections.isOwner(user.id, Number(id))) {
throw new HttpException({ error: 'Only the owner can manage members' }, 403);
}
return { users: this.collections.availableUsers(user.id, Number(id)) };
}
@Get(':id')
get(@CurrentUser() user: User, @Param('id') id: string) {
return this.collections.getCollection(user.id, Number(id));
}
@Patch(':id')
update(@CurrentUser() user: User, @Param('id') id: string, @Body(new ZodValidationPipe(collectionUpdateRequestSchema)) body: CollectionUpdateRequest) {
return this.collections.updateCollection(user.id, Number(id), body);
}
@Delete(':id')
remove(@CurrentUser() user: User, @Param('id') id: string) {
this.collections.deleteCollection(user.id, Number(id));
return { success: true };
}
}
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { CollectionsController } from './collections.controller';
import { CollectionsService } from './collections.service';
import { CollectionsAddonGuard } from './collections-addon.guard';
@Module({
controllers: [CollectionsController],
providers: [CollectionsService, CollectionsAddonGuard],
})
export class CollectionsModule {}
@@ -0,0 +1,52 @@
import { Injectable } from '@nestjs/common';
import * as svc from '../../services/collectionsService';
import type {
CollectionCreateRequest,
CollectionUpdateRequest,
CollectionSavePlaceRequest,
CollectionPlaceUpdateRequest,
CollectionCopyToTripRequest,
CollectionStatus,
} from '@trek/shared';
/**
* Thin Nest wrapper around services/collectionsService. All access control lives
* in the legacy service (assertAccess / isOwner throw, fusion returns {error});
* this just re-exposes the functions one-to-one.
*/
@Injectable()
export class CollectionsService {
listCollections(userId: number) { return svc.listCollections(userId); }
getCollection(userId: number, id: number) { return svc.getCollection(userId, id); }
createCollection(userId: number, body: CollectionCreateRequest) { return svc.createCollection(userId, body); }
updateCollection(userId: number, id: number, body: CollectionUpdateRequest) { return svc.updateCollection(userId, id, body); }
deleteCollection(userId: number, id: number) { return svc.deleteCollection(userId, id); }
reorderCollections(userId: number, orderedIds: number[]) { return svc.reorderCollections(userId, orderedIds); }
savePlace(userId: number, body: CollectionSavePlaceRequest) { return svc.savePlace(userId, body); }
saveFromTripPlace(userId: number, collectionId: number, tripId: number, placeId: number, force?: boolean) {
return svc.saveFromTripPlace(userId, collectionId, tripId, placeId, force);
}
updatePlace(userId: number, placeId: number, body: CollectionPlaceUpdateRequest) { return svc.updatePlace(userId, placeId, body); }
setStatus(userId: number, placeId: number, status: CollectionStatus) { return svc.setStatus(userId, placeId, status); }
deletePlace(userId: number, placeId: number) { return svc.deletePlace(userId, placeId); }
deletePlacesMany(userId: number, ids: number[]) { return svc.deletePlacesMany(userId, ids); }
copyToTrip(userId: number, body: CollectionCopyToTripRequest) { return svc.copyToTrip(userId, body); }
findMembership(userId: number, query: { google_place_id?: string; google_ftid?: string; name?: string; lat?: number; lng?: number }) {
return svc.findMembership(userId, query);
}
// Access helpers used by the controller's owner guards.
assertAccess(userId: number, collectionId: number) { return svc.assertAccess(userId, collectionId); }
isOwner(userId: number, collectionId: number) { return svc.isOwner(userId, collectionId); }
sendInvite(collectionId: number, inviterId: number, inviterUsername: string, inviterEmail: string, targetUserId: number) {
return svc.sendInvite(collectionId, inviterId, inviterUsername, inviterEmail, targetUserId);
}
acceptInvite(userId: number, collectionId: number, socketId?: string) { return svc.acceptInvite(userId, collectionId, socketId); }
declineInvite(userId: number, collectionId: number, socketId?: string) { return svc.declineInvite(userId, collectionId, socketId); }
cancelInvite(collectionId: number, ownerId: number, targetUserId: number) { return svc.cancelInvite(collectionId, ownerId, targetUserId); }
leaveCollection(userId: number, collectionId: number, socketId?: string) { return svc.leaveCollection(userId, collectionId, socketId); }
availableUsers(ownerId: number, collectionId: number) { return svc.availableUsers(ownerId, collectionId); }
}
+629
View File
@@ -0,0 +1,629 @@
import { db, canAccessTrip } from '../db/database';
import { broadcastToUser } from '../websocket';
import { checkPermission } from './permissions';
import type {
Collection,
CollectionDetailResponse,
CollectionListResponse,
CollectionMember,
CollectionMembership,
CollectionPlace,
CollectionCreateRequest,
CollectionUpdateRequest,
CollectionSavePlaceRequest,
CollectionSaveResult,
CollectionCopyToTripRequest,
CollectionStatus,
} from '@trek/shared';
// ---------------------------------------------------------------------------
// Errors — thrown as plain Errors carrying a status; TrekExceptionFilter maps
// `err.status` → that HTTP code with an `{ error: message }` body.
// ---------------------------------------------------------------------------
function httpError(status: number, message: string): never {
const err = new Error(message) as Error & { status: number };
err.status = status;
throw err;
}
// ---------------------------------------------------------------------------
// Visibility — a user may see/edit a collection if they own it OR are an
// accepted member. Every read/write goes through assertAccess.
// ---------------------------------------------------------------------------
export function accessibleCollectionIds(userId: number): number[] {
const rows = db.prepare(`
SELECT id FROM collections WHERE owner_id = ?
UNION
SELECT collection_id FROM collection_members WHERE user_id = ? AND status = 'accepted'
`).all(userId, userId) as { id: number }[];
return rows.map(r => r.id);
}
function isVisible(userId: number, collectionId: number): boolean {
const row = db.prepare(`
SELECT 1 FROM collections WHERE id = ? AND owner_id = ?
UNION
SELECT 1 FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'accepted'
LIMIT 1
`).get(collectionId, userId, collectionId, userId);
return !!row;
}
export function assertAccess(userId: number, collectionId: number): void {
if (!isVisible(userId, collectionId)) httpError(404, 'Collection not found');
}
export function isOwner(userId: number, collectionId: number): boolean {
const row = db.prepare('SELECT 1 FROM collections WHERE id = ? AND owner_id = ?').get(collectionId, userId);
return !!row;
}
function ownerOf(collectionId: number): number {
const row = db.prepare('SELECT owner_id FROM collections WHERE id = ?').get(collectionId) as { owner_id: number } | undefined;
if (!row) httpError(404, 'Collection not found');
return row.owner_id;
}
// ---------------------------------------------------------------------------
// Hydration helpers
// ---------------------------------------------------------------------------
interface PlaceRow extends CollectionPlace {
category_name?: string | null;
category_color?: string | null;
category_icon?: string | null;
}
function loadTagsByCollectionPlaceIds(placeIds: number[]): Record<number, { id: number; name: string; color: string }[]> {
const out: Record<number, { id: number; name: string; color: string }[]> = {};
if (placeIds.length === 0) return out;
const placeholders = placeIds.map(() => '?').join(',');
const rows = db.prepare(`
SELECT cpt.collection_place_id AS pid, t.id, t.name, t.color
FROM collection_place_tags cpt
JOIN tags t ON t.id = cpt.tag_id
WHERE cpt.collection_place_id IN (${placeholders})
`).all(...placeIds) as { pid: number; id: number; name: string; color: string }[];
for (const r of rows) {
if (!out[r.pid]) out[r.pid] = [];
out[r.pid].push({ id: r.id, name: r.name, color: r.color });
}
return out;
}
function hydratePlaces(rows: PlaceRow[]): CollectionPlace[] {
const ids = rows.map(r => r.id);
const tagsByPlace = loadTagsByCollectionPlaceIds(ids);
return rows.map(r => {
const { category_name, category_color, category_icon, ...rest } = r;
return {
...rest,
category: r.category_id
? { id: r.category_id, name: category_name ?? '', color: category_color ?? null, icon: category_icon ?? null }
: undefined,
tags: tagsByPlace[r.id] || [],
} as CollectionPlace;
});
}
function getPlaceById(placeId: number): CollectionPlace {
const row = db.prepare(`
SELECT cp.*, c.name AS category_name, c.color AS category_color, c.icon AS category_icon
FROM collection_places cp
LEFT JOIN categories c ON cp.category_id = c.id
WHERE cp.id = ?
`).get(placeId) as PlaceRow | undefined;
if (!row) httpError(404, 'Place not found');
return hydratePlaces([row])[0];
}
function collectionIdOfPlace(placeId: number): number {
const row = db.prepare('SELECT collection_id FROM collection_places WHERE id = ?').get(placeId) as { collection_id: number } | undefined;
if (!row) httpError(404, 'Place not found');
return row.collection_id;
}
function buildMembers(collectionId: number): CollectionMember[] {
const owner = db.prepare(`
SELECT u.id AS user_id, u.username, u.email, u.avatar
FROM collections col JOIN users u ON u.id = col.owner_id
WHERE col.id = ?
`).get(collectionId) as Omit<CollectionMember, 'status' | 'is_owner'> | undefined;
const members = db.prepare(`
SELECT u.id AS user_id, u.username, u.email, u.avatar, cm.status
FROM collection_members cm JOIN users u ON u.id = cm.user_id
WHERE cm.collection_id = ?
ORDER BY u.username
`).all(collectionId) as Omit<CollectionMember, 'is_owner'>[];
const result: CollectionMember[] = [];
if (owner) result.push({ ...owner, status: 'accepted', is_owner: true });
for (const m of members) result.push({ ...m, is_owner: false });
return result;
}
function getCollectionRow(id: number): Collection {
const col = db.prepare('SELECT * FROM collections WHERE id = ?').get(id) as Collection | undefined;
if (!col) httpError(404, 'Collection not found');
const placeCount = (db.prepare('SELECT COUNT(*) AS n FROM collection_places WHERE collection_id = ?').get(id) as { n: number }).n;
return { ...col, place_count: placeCount, members: buildMembers(id) };
}
// ---------------------------------------------------------------------------
// Lists CRUD
// ---------------------------------------------------------------------------
export function listCollections(userId: number): CollectionListResponse {
const ids = accessibleCollectionIds(userId);
const collections: Collection[] = ids
.map(id => {
const col = getCollectionRow(id);
return { ...col, is_owner: col.owner_id === userId };
})
.sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0) || a.id - b.id);
const incomingInvites = (db.prepare(`
SELECT cm.collection_id, c.name, u.id AS from_id, u.username AS from_username
FROM collection_members cm
JOIN collections c ON c.id = cm.collection_id
JOIN users u ON u.id = c.owner_id
WHERE cm.user_id = ? AND cm.status = 'pending'
`).all(userId) as { collection_id: number; name: string; from_id: number; from_username: string }[])
.map(r => ({ collection_id: r.collection_id, name: r.name, from: { id: r.from_id, username: r.from_username } }));
return { collections, incomingInvites };
}
export function getCollection(userId: number, id: number): CollectionDetailResponse {
assertAccess(userId, id);
const collection = getCollectionRow(id);
const rows = db.prepare(`
SELECT cp.*, c.name AS category_name, c.color AS category_color, c.icon AS category_icon
FROM collection_places cp
LEFT JOIN categories c ON cp.category_id = c.id
WHERE cp.collection_id = ?
ORDER BY cp.sort_order, cp.created_at
`).all(id) as PlaceRow[];
return { collection: { ...collection, is_owner: collection.owner_id === userId }, places: hydratePlaces(rows) };
}
export function createCollection(userId: number, body: CollectionCreateRequest): Collection {
const max = (db.prepare('SELECT COALESCE(MAX(sort_order), -1) AS m FROM collections WHERE owner_id = ?').get(userId) as { m: number }).m;
const result = db.prepare(`
INSERT INTO collections (owner_id, name, description, color, icon, sort_order)
VALUES (?, ?, ?, ?, ?, ?)
`).run(
userId,
body.name,
body.description ?? null,
body.color ?? '#6366f1',
body.icon ?? 'Bookmark',
max + 1,
);
const col = getCollectionRow(Number(result.lastInsertRowid));
return { ...col, is_owner: true };
}
export function updateCollection(userId: number, id: number, body: CollectionUpdateRequest): Collection {
assertAccess(userId, id);
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.color !== undefined) { updates.push('color = ?'); params.push(body.color ?? null); }
if (body.icon !== undefined) { updates.push('icon = ?'); params.push(body.icon ?? null); }
if (body.sort_order !== undefined) { updates.push('sort_order = ?'); params.push(body.sort_order); }
if (updates.length > 0) {
updates.push("updated_at = CURRENT_TIMESTAMP");
params.push(id);
db.prepare(`UPDATE collections SET ${updates.join(', ')} WHERE id = ?`).run(...params);
}
notifyCollectionUsers(id, undefined, 'collections:updated');
const col = getCollectionRow(id);
return { ...col, is_owner: col.owner_id === userId };
}
export function deleteCollection(userId: number, id: number): void {
assertAccess(userId, id);
if (!isOwner(userId, id)) httpError(403, 'Only the owner can delete this list');
// Snapshot recipients BEFORE the cascade wipes collection_members.
const accepted = (db.prepare("SELECT user_id FROM collection_members WHERE collection_id = ? AND status = 'accepted'").all(id) as { user_id: number }[]).map(r => r.user_id);
const pending = (db.prepare("SELECT user_id FROM collection_members WHERE collection_id = ? AND status = 'pending'").all(id) as { user_id: number }[]).map(r => r.user_id);
db.prepare('DELETE FROM collections WHERE id = ?').run(id); // CASCADE drops members + places + tags
[...new Set([...accepted, ...pending])]
.filter(uid => uid !== userId)
.forEach(uid => broadcastToUser(uid, { type: 'collections:deleted', collectionId: id }));
}
export function reorderCollections(userId: number, orderedIds: number[]): void {
const visible = new Set(accessibleCollectionIds(userId));
const stmt = db.prepare('UPDATE collections SET sort_order = ? WHERE id = ?');
orderedIds.forEach((cid, index) => {
if (visible.has(cid)) stmt.run(index, cid);
});
}
// ---------------------------------------------------------------------------
// Dedup (collection-scoped ports of placeService helpers)
// ---------------------------------------------------------------------------
const COORD_DEDUP_TOLERANCE = 0.0001; // ≈ 11 m
interface DedupSet {
names: Set<string>;
coords: Array<{ lat: number; lng: number }>;
}
function buildDedupSet(collectionId: number): DedupSet {
const rows = db.prepare('SELECT name, lat, lng FROM collection_places WHERE collection_id = ?').all(collectionId) as Array<{
name: string | null; lat: number | null; lng: number | null;
}>;
const names = new Set<string>();
const coords: Array<{ lat: number; lng: number }> = [];
for (const row of rows) {
if (row.name) names.add(row.name.trim().toLowerCase());
else if (row.lat != null && row.lng != null) coords.push({ lat: row.lat, lng: row.lng });
}
return { names, coords };
}
function isCollectionPlaceDuplicate(
candidate: { name: string | null | undefined; lat: number | null | undefined; lng: number | null | undefined },
dedup: DedupSet,
): boolean {
const normalizedName = candidate.name?.trim().toLowerCase();
if (normalizedName) return dedup.names.has(normalizedName);
if (candidate.lat != null && candidate.lng != null) {
return dedup.coords.some(c =>
Math.abs(c.lat - candidate.lat!) <= COORD_DEDUP_TOLERANCE &&
Math.abs(c.lng - candidate.lng!) <= COORD_DEDUP_TOLERANCE,
);
}
return false;
}
function findDuplicateCollectionPlace(
collectionId: number,
candidate: { name: string | null | undefined; lat: number | null | undefined; lng: number | null | undefined },
): { id: number; name: string } | null {
const normalizedName = candidate.name?.trim().toLowerCase();
if (normalizedName) {
const dup = db.prepare(`
SELECT id, name FROM collection_places
WHERE collection_id = ? AND lower(trim(name)) = ?
ORDER BY id ASC LIMIT 1
`).get(collectionId, normalizedName) as { id: number; name: string } | undefined;
if (dup) return dup;
}
if (candidate.lat != null && candidate.lng != null) {
return (db.prepare(`
SELECT id, name FROM collection_places
WHERE collection_id = ? AND lat IS NOT NULL AND lng IS NOT NULL
AND abs(lat - ?) <= ? AND abs(lng - ?) <= ?
ORDER BY id ASC LIMIT 1
`).get(collectionId, candidate.lat, COORD_DEDUP_TOLERANCE, candidate.lng, COORD_DEDUP_TOLERANCE) as { id: number; name: string } | undefined) || null;
}
return null;
}
// ---------------------------------------------------------------------------
// Saved places CRUD
// ---------------------------------------------------------------------------
function attachTags(collectionPlaceId: number, tagIds: number[] | undefined): void {
if (!tagIds || tagIds.length === 0) return;
const stmt = db.prepare('INSERT OR IGNORE INTO collection_place_tags (collection_place_id, tag_id) VALUES (?, ?)');
for (const tid of tagIds) stmt.run(collectionPlaceId, tid);
}
export function savePlace(userId: number, body: CollectionSavePlaceRequest): CollectionSaveResult {
assertAccess(userId, body.collection_id);
if (!body.force) {
const dup = findDuplicateCollectionPlace(body.collection_id, { name: body.name, lat: body.lat, lng: body.lng });
if (dup) return { duplicate: true, duplicateOf: dup };
}
const ownerId = ownerOf(body.collection_id);
const result = 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
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
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,
);
const placeId = Number(result.lastInsertRowid);
attachTags(placeId, body.tag_ids);
notifyCollectionUsers(body.collection_id, undefined, 'collections:updated');
return { place: getPlaceById(placeId) };
}
export function saveFromTripPlace(
userId: number, collectionId: number, tripId: number, placeId: number, force?: boolean,
): CollectionSaveResult {
assertAccess(userId, collectionId);
if (!canAccessTrip(tripId, userId)) httpError(404, 'Trip not found');
const place = db.prepare('SELECT * FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId) as Record<string, unknown> | undefined;
if (!place) httpError(404, 'Place not found');
return 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,
source_trip_id: tripId,
source_place_id: placeId,
force,
});
}
export function updatePlace(userId: number, placeId: number, body: import('@trek/shared').CollectionPlaceUpdateRequest): CollectionPlace {
const currentCollection = collectionIdOfPlace(placeId);
assertAccess(userId, currentCollection);
const updates: string[] = [];
const params: (string | number | null)[] = [];
if (body.name !== undefined) { updates.push('name = ?'); params.push(body.name); }
if (body.notes !== undefined) { updates.push('notes = ?'); params.push(body.notes ?? 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); }
let movedTo: number | null = null;
if (body.collection_id !== undefined && body.collection_id !== currentCollection) {
assertAccess(userId, body.collection_id);
updates.push('collection_id = ?'); params.push(body.collection_id);
updates.push('owner_id = ?'); params.push(ownerOf(body.collection_id));
movedTo = body.collection_id;
}
if (updates.length > 0) {
updates.push("updated_at = CURRENT_TIMESTAMP");
params.push(placeId);
db.prepare(`UPDATE collection_places SET ${updates.join(', ')} WHERE id = ?`).run(...params);
}
if (body.tag_ids !== undefined) {
db.prepare('DELETE FROM collection_place_tags WHERE collection_place_id = ?').run(placeId);
attachTags(placeId, body.tag_ids);
}
notifyCollectionUsers(currentCollection, undefined, 'collections:updated');
if (movedTo) notifyCollectionUsers(movedTo, undefined, 'collections:updated');
return getPlaceById(placeId);
}
export function setStatus(userId: number, placeId: number, status: CollectionStatus): CollectionPlace {
const collectionId = collectionIdOfPlace(placeId);
assertAccess(userId, collectionId);
db.prepare("UPDATE collection_places SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?").run(status, placeId);
notifyCollectionUsers(collectionId, undefined, 'collections:updated');
return getPlaceById(placeId);
}
export function deletePlace(userId: number, placeId: number): void {
const collectionId = collectionIdOfPlace(placeId);
assertAccess(userId, collectionId);
db.prepare('DELETE FROM collection_places WHERE id = ?').run(placeId); // CASCADE drops tags. NO photo-cache reclaim.
notifyCollectionUsers(collectionId, undefined, 'collections:updated');
}
export function deletePlacesMany(userId: number, ids: number[]): number[] {
const deleted: number[] = [];
const touched = new Set<number>();
for (const id of ids) {
const collectionId = collectionIdOfPlace(id);
assertAccess(userId, collectionId);
db.prepare('DELETE FROM collection_places WHERE id = ?').run(id);
deleted.push(id);
touched.add(collectionId);
}
touched.forEach(cid => notifyCollectionUsers(cid, undefined, 'collections:updated'));
return deleted;
}
// ---------------------------------------------------------------------------
// Copy to trip
// ---------------------------------------------------------------------------
export function copyToTrip(userId: number, body: CollectionCopyToTripRequest): { copied: number; skipped: { id: number; name: string }[] } {
const trip = canAccessTrip(body.trip_id, userId) as { id: number; user_id: number } | undefined;
if (!trip) httpError(404, 'Trip not found');
const role = (db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role: string } | undefined)?.role ?? 'user';
if (!checkPermission('place_edit', role, trip.user_id, userId, trip.user_id !== userId)) {
httpError(403, 'Not allowed to edit this trip');
}
// 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 }> = [];
for (const pid of body.place_ids) {
const row = db.prepare(`
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 = ?
`).get(pid) as (typeof sources)[number] | undefined;
if (!row) httpError(404, 'Place not found');
assertAccess(userId, row.collection_id);
sources.push(row);
}
// Trip dedup set (mirrors placeService.buildDedupSet).
const existing = db.prepare('SELECT name, lat, lng FROM places WHERE trip_id = ?').all(body.trip_id) as Array<{ name: string | null; lat: number | null; lng: number | null }>;
const dedup: DedupSet = { names: new Set(), coords: [] };
for (const r of existing) {
if (r.name) dedup.names.add(r.name.trim().toLowerCase());
else if (r.lat != null && r.lng != null) dedup.coords.push({ lat: r.lat, lng: r.lng });
}
const insertPlace = 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 = db.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)');
let copied = 0;
const skipped: { id: number; name: string }[] = [];
for (const s of sources) {
if (!body.force && isCollectionPlaceDuplicate({ name: s.name, lat: s.lat, lng: s.lng }, dedup)) {
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 = db.prepare('SELECT tag_id FROM collection_place_tags WHERE collection_place_id = ?').all(s.id) as { tag_id: number }[];
for (const t of tagIds) insertTag.run(newPlaceId, t.tag_id);
if (s.name) dedup.names.add(s.name.trim().toLowerCase());
else if (s.lat != null && s.lng != null) dedup.coords.push({ lat: s.lat, lng: s.lng });
copied++;
}
return { copied, skipped };
}
// ---------------------------------------------------------------------------
// Library-wide membership lookup (inspector indicator)
// ---------------------------------------------------------------------------
export function findMembership(
userId: number,
query: { google_place_id?: string; google_ftid?: string; name?: string; lat?: number; lng?: number },
): CollectionMembership {
const ids = 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); }
if (query.name && query.name.trim()) { conditions.push('lower(trim(cp.name)) = ?'); params.push(query.name.trim().toLowerCase()); }
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 = db.prepare(`
SELECT cp.id AS place_id, cp.collection_id, c.name
FROM collection_places cp
JOIN collections c ON c.id = cp.collection_id
WHERE cp.collection_id IN (${placeholders}) AND (${conditions.join(' OR ')})
`).all(...params) as { place_id: number; collection_id: number; name: string }[];
return { saved: rows.length > 0, lists: rows.map(r => ({ collection_id: r.collection_id, name: r.name, place_id: r.place_id })) };
}
// ---------------------------------------------------------------------------
// WebSocket notify
// ---------------------------------------------------------------------------
export function notifyCollectionUsers(collectionId: number, excludeSid: string | undefined, event = 'collections:updated'): void {
const owner = db.prepare('SELECT owner_id FROM collections WHERE id = ?').get(collectionId) as { owner_id: number } | undefined;
if (!owner) return;
const userIds = [owner.owner_id];
const members = db.prepare("SELECT user_id FROM collection_members WHERE collection_id = ? AND status = 'accepted'").all(collectionId) as { user_id: number }[];
members.forEach(m => userIds.push(m.user_id));
userIds.forEach(id => broadcastToUser(id, { type: event, collectionId }, excludeSid));
}
// ---------------------------------------------------------------------------
// Fusion invitations (mirror vacayService, dropping the one-fusion guards)
// ---------------------------------------------------------------------------
export function sendInvite(
collectionId: number, inviterId: number, inviterUsername: string, inviterEmail: string, targetUserId: number,
): { error?: string; status?: number } {
if (!isOwner(inviterId, collectionId)) return { error: 'Not allowed', status: 403 };
if (targetUserId === inviterId) return { error: 'Cannot invite yourself', status: 400 };
const targetUser = db.prepare('SELECT id, username FROM users WHERE id = ?').get(targetUserId);
if (!targetUser) return { error: 'User not found', status: 404 };
const existing = db.prepare('SELECT id, status FROM collection_members WHERE collection_id = ? AND user_id = ?').get(collectionId, targetUserId) as { id: number; status: string } | undefined;
if (existing) {
if (existing.status === 'accepted') return { error: 'Already a member', status: 400 };
if (existing.status === 'pending') return { error: 'Invite already pending', status: 400 };
}
db.prepare("INSERT INTO collection_members (collection_id, user_id, status) VALUES (?, ?, 'pending')").run(collectionId, targetUserId);
broadcastToUser(targetUserId, { type: 'collections:invite', from: { id: inviterId, username: inviterUsername }, collectionId });
import('../services/notificationService').then(({ send }) => {
send({ event: 'collection_invite', actorId: inviterId, scope: 'user', targetId: targetUserId, params: { actor: inviterEmail, collectionId: String(collectionId) } }).catch(() => {});
}).catch(() => {});
return {};
}
export function acceptInvite(userId: number, collectionId: number, socketId: string | undefined): { error?: string; status?: number } {
const invite = db.prepare("SELECT id FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'pending'").get(collectionId, userId) as { id: number } | undefined;
if (!invite) return { error: 'No pending invite', status: 404 };
db.prepare("UPDATE collection_members SET status = 'accepted' WHERE id = ?").run(invite.id);
notifyCollectionUsers(collectionId, socketId, 'collections:accepted');
return {};
}
export function declineInvite(userId: number, collectionId: number, socketId: string | undefined): void {
db.prepare("DELETE FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'pending'").run(collectionId, userId);
notifyCollectionUsers(collectionId, socketId, 'collections:declined');
}
export function cancelInvite(collectionId: number, ownerId: number, targetUserId: number): void {
if (!isOwner(ownerId, collectionId)) httpError(403, 'Not allowed');
db.prepare("DELETE FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'pending'").run(collectionId, targetUserId);
broadcastToUser(targetUserId, { type: 'collections:cancelled', collectionId });
}
export function leaveCollection(userId: number, collectionId: number, socketId: string | undefined): void {
if (isOwner(userId, collectionId)) httpError(400, 'Owner cannot leave; delete the list');
db.prepare("DELETE FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'accepted'").run(collectionId, userId);
notifyCollectionUsers(collectionId, socketId, 'collections:left');
}
export function availableUsers(ownerId: number, collectionId: number): { id: number; username: string }[] {
return db.prepare(`
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
`).all(ownerId, collectionId) as { id: number; username: string }[];
}
export function findMembershipForUser(userId: number, collectionId: number): { is_member: boolean; is_owner: boolean; status: string | null } {
if (isOwner(userId, collectionId)) return { is_member: true, is_owner: true, status: 'accepted' };
const row = db.prepare('SELECT status FROM collection_members WHERE collection_id = ? AND user_id = ?').get(collectionId, userId) as { status: string } | undefined;
return { is_member: row?.status === 'accepted', is_owner: false, status: row?.status ?? null };
}
@@ -12,6 +12,7 @@ export type NotifEventType =
| 'trip_reminder'
| 'todo_due'
| 'vacay_invite'
| 'collection_invite'
| 'photos_shared'
| 'collab_message'
| 'packing_tagged'
@@ -33,6 +34,7 @@ const IMPLEMENTED_COMBOS: Record<NotifEventType, NotifChannel[]> = {
trip_reminder: ['inapp', 'email', 'webhook', 'ntfy'],
todo_due: ['inapp', 'email', 'webhook', 'ntfy'],
vacay_invite: ['inapp', 'email', 'webhook', 'ntfy'],
collection_invite: ['inapp', 'email', 'webhook', 'ntfy'],
photos_shared: ['inapp', 'email', 'webhook', 'ntfy'],
collab_message: ['inapp', 'email', 'webhook', 'ntfy'],
packing_tagged: ['inapp', 'email', 'webhook', 'ntfy'],
@@ -96,6 +96,13 @@ const EVENT_NOTIFICATION_CONFIG: Record<string, EventNotifConfig> = {
navigateTextKey: 'notif.action.view_vacay',
navigateTarget: p => (p.planId ? `/vacay/${p.planId}` : null),
},
collection_invite: {
inAppType: 'navigate',
titleKey: 'notif.collection_invite.title',
textKey: 'notif.collection_invite.text',
navigateTextKey: 'notif.action.view_collection',
navigateTarget: p => (p.collectionId ? `/collections/${p.collectionId}` : '/collections'),
},
photos_shared: {
inAppType: 'navigate',
titleKey: 'notif.photos_shared.title',
+11 -2
View File
@@ -148,9 +148,18 @@ export function serveFilePath(placeId: string): string | null {
// Google place_id (the dedup key) or by the stable proxy URL stored in image_url
// (covers coords: pseudo-ids, which never have a google_place_id).
function isReferenced(placeId: string): boolean {
// A collection-saved place copies image_url = proxyUrl(google_place_id) and/or
// the google_place_id itself, so collection_places must count as a referencing
// table — otherwise the nightly sweep + trip-place delete would evict a photo
// still shown on a collection thumbnail (#1081 photo-cache pitfall).
const row = db
.prepare('SELECT 1 FROM places WHERE google_place_id = ? OR image_url = ? LIMIT 1')
.get(placeId, proxyUrl(placeId));
.prepare(
`SELECT 1 FROM places WHERE google_place_id = ? OR image_url = ?
UNION ALL
SELECT 1 FROM collection_places WHERE google_place_id = ? OR image_url = ?
LIMIT 1`,
)
.get(placeId, proxyUrl(placeId), placeId, proxyUrl(placeId));
return !!row;
}