mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
feat(collections): list details, place detail sheet, add-place, fusion kick (#1081)
Dashboard widget (B): the collections tool now shows the user's LISTS as compact colour-washed badges (cover image tinted with the list colour, or a gradient) that jump to the list — one list() call, no N+1. List details (C): lists gain a description, a custom cover image (uploaded to /uploads/covers, tinted with the list colour in the hero) and links. A shared ListEditorModal handles both create and edit; the hero shows the description + link chips. New `links` JSON column on collections + collection_places (migration 151) with parse/serialize in the service; a POST :id/cover upload endpoint mirroring trips; cover-file cleanup path-confined locally. Place detail (D): clicking a place opens a bottom sheet (no backdrop, so the map stays visible) — status cycle, copy-to-trip, remove, and an edit mode with a markdown description + links editor (collectionsApi.updatePlace, now wired via a store action). A "+" next to the search adds a place to the list via the maps search. Fusion + fixes (E): the owner can now remove an accepted member (kick) — new removeMember service/route/store + a button in ShareCollectionModal, with a collections:removed WS bounce. findMembership no longer matches on name alone (coordinate proximity required, killing "Starbucks everywhere" false positives). loadCollection swallows a 403/404 after a leave/remove so the URL sync can't throw uncaught. Grid remnants gone; the map select toggle moved onto the map. New strings across all 22 locales; i18n parity strict passes.
This commit is contained in:
@@ -3255,6 +3255,12 @@ function runMigrations(db: Database.Database): void {
|
||||
CREATE INDEX IF NOT EXISTS idx_collection_place_tags_tag ON collection_place_tags(tag_id);
|
||||
`);
|
||||
},
|
||||
|
||||
// Migration 151: user-added links on collections + saved places (JSON text)
|
||||
() => {
|
||||
try { db.exec('ALTER TABLE collections ADD COLUMN links TEXT'); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
|
||||
try { db.exec('ALTER TABLE collection_places ADD COLUMN links TEXT'); } catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
|
||||
},
|
||||
];
|
||||
|
||||
if (currentVersion < migrations.length) {
|
||||
|
||||
@@ -380,6 +380,7 @@ function createTables(db: Database.Database): void {
|
||||
color TEXT DEFAULT '#6366f1',
|
||||
icon TEXT DEFAULT 'Bookmark',
|
||||
cover_image TEXT,
|
||||
links TEXT,
|
||||
sort_order INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
@@ -417,6 +418,7 @@ function createTables(db: Database.Database): void {
|
||||
status TEXT NOT NULL DEFAULT 'idea',
|
||||
source_trip_id INTEGER,
|
||||
source_place_id INTEGER,
|
||||
links TEXT,
|
||||
sort_order INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
|
||||
@@ -10,8 +10,16 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UploadedFile,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import type { Request } from 'express';
|
||||
import { diskStorage } from 'multer';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { User } from '../../types';
|
||||
import { CollectionsService } from './collections.service';
|
||||
import { CollectionsAddonGuard } from './collections-addon.guard';
|
||||
@@ -29,6 +37,7 @@ import {
|
||||
collectionInviteRequestSchema,
|
||||
collectionInviteActionRequestSchema,
|
||||
collectionInviteCancelRequestSchema,
|
||||
collectionRemoveMemberRequestSchema,
|
||||
type CollectionCreateRequest,
|
||||
type CollectionUpdateRequest,
|
||||
type CollectionSavePlaceRequest,
|
||||
@@ -39,8 +48,28 @@ import {
|
||||
type CollectionInviteRequest,
|
||||
type CollectionInviteActionRequest,
|
||||
type CollectionInviteCancelRequest,
|
||||
type CollectionRemoveMemberRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
const MAX_COVER_SIZE = 20 * 1024 * 1024;
|
||||
const coversDir = path.join(__dirname, '../../../uploads/covers');
|
||||
const COVER_UPLOAD = {
|
||||
storage: diskStorage({
|
||||
destination: (_req, _file, cb) => {
|
||||
if (!fs.existsSync(coversDir)) fs.mkdirSync(coversDir, { recursive: true });
|
||||
cb(null, coversDir);
|
||||
},
|
||||
filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`),
|
||||
}),
|
||||
limits: { fileSize: MAX_COVER_SIZE },
|
||||
fileFilter: (_req: Request, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
|
||||
if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowed.includes(ext)) cb(null, true);
|
||||
else cb(new Error('Only jpg, png, gif, webp images allowed'), false);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* /api/addons/collections — saved-place library (lists, places, fusion sharing).
|
||||
*
|
||||
@@ -200,6 +229,17 @@ export class CollectionsController {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Post('members/remove')
|
||||
@HttpCode(200)
|
||||
removeMember(@CurrentUser() user: User, @Body(new ZodValidationPipe(collectionRemoveMemberRequestSchema)) body: CollectionRemoveMemberRequest) {
|
||||
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 remove members' }, 403);
|
||||
}
|
||||
this.collections.removeMember(user.id, body.collection_id, body.user_id);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// ── /:id (declared last so static prefixes win) ─────────────────────────────
|
||||
@Get(':id/available-users')
|
||||
availableUsers(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
@@ -210,6 +250,14 @@ export class CollectionsController {
|
||||
return { users: this.collections.availableUsers(user.id, Number(id)) };
|
||||
}
|
||||
|
||||
@Post(':id/cover')
|
||||
@UseInterceptors(FileInterceptor('cover', COVER_UPLOAD))
|
||||
uploadCover(@CurrentUser() user: User, @Param('id') id: string, @UploadedFile() file: Express.Multer.File | undefined) {
|
||||
if (!file) throw new HttpException({ error: 'No image uploaded' }, 400);
|
||||
const coverUrl = `/uploads/covers/${file.filename}`;
|
||||
return this.collections.setCollectionCover(user.id, Number(id), coverUrl);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
get(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
return this.collections.getCollection(user.id, Number(id));
|
||||
|
||||
@@ -20,6 +20,7 @@ export class CollectionsService {
|
||||
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); }
|
||||
setCollectionCover(userId: number, id: number, coverUrl: string | null) { return svc.setCollectionCover(userId, id, coverUrl); }
|
||||
deleteCollection(userId: number, id: number) { return svc.deleteCollection(userId, id); }
|
||||
reorderCollections(userId: number, orderedIds: number[]) { return svc.reorderCollections(userId, orderedIds); }
|
||||
|
||||
@@ -48,5 +49,6 @@ export class CollectionsService {
|
||||
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); }
|
||||
removeMember(ownerId: number, collectionId: number, targetUserId: number) { return svc.removeMember(ownerId, collectionId, targetUserId); }
|
||||
availableUsers(ownerId: number, collectionId: number) { return svc.availableUsers(ownerId, collectionId); }
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { db, canAccessTrip } from '../db/database';
|
||||
import { broadcastToUser } from '../websocket';
|
||||
import { checkPermission } from './permissions';
|
||||
@@ -8,6 +10,7 @@ import type {
|
||||
CollectionMember,
|
||||
CollectionMembership,
|
||||
CollectionPlace,
|
||||
CollectionLink,
|
||||
CollectionCreateRequest,
|
||||
CollectionUpdateRequest,
|
||||
CollectionSavePlaceRequest,
|
||||
@@ -16,6 +19,33 @@ import type {
|
||||
CollectionStatus,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Links are stored as a JSON TEXT column; parse on read, stringify on write. */
|
||||
function parseLinks(raw: unknown): CollectionLink[] | undefined {
|
||||
if (typeof raw !== 'string' || !raw) return undefined;
|
||||
try {
|
||||
const v = JSON.parse(raw);
|
||||
return Array.isArray(v) ? (v as CollectionLink[]) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function serializeLinks(links: CollectionLink[] | undefined): string | null {
|
||||
return links && links.length ? JSON.stringify(links) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reclaim a replaced cover file. Path-confined to uploads/covers (mirrors
|
||||
* tripService.deleteOldCover — kept local so this service doesn't pull the
|
||||
* trips import graph). Collection + trip covers share the same directory.
|
||||
*/
|
||||
function deleteOldCollectionCover(coverImage: string | null | undefined): void {
|
||||
if (!coverImage) return;
|
||||
const coversDir = path.resolve(__dirname, '../../uploads/covers');
|
||||
const resolved = path.resolve(path.join(coversDir, path.basename(coverImage)));
|
||||
if (resolved.startsWith(coversDir + path.sep) && fs.existsSync(resolved)) fs.unlinkSync(resolved);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Errors — thrown as plain Errors carrying a status; TrekExceptionFilter maps
|
||||
// `err.status` → that HTTP code with an `{ error: message }` body.
|
||||
@@ -100,6 +130,7 @@ function hydratePlaces(rows: PlaceRow[]): CollectionPlace[] {
|
||||
const { category_name, category_color, category_icon, ...rest } = r;
|
||||
return {
|
||||
...rest,
|
||||
links: parseLinks((r as { links?: unknown }).links),
|
||||
category: r.category_id
|
||||
? { id: r.category_id, name: category_name ?? '', color: category_color ?? null, icon: category_icon ?? null }
|
||||
: undefined,
|
||||
@@ -144,10 +175,10 @@ function buildMembers(collectionId: number): CollectionMember[] {
|
||||
}
|
||||
|
||||
function getCollectionRow(id: number): Collection {
|
||||
const col = db.prepare('SELECT * FROM collections WHERE id = ?').get(id) as Collection | undefined;
|
||||
const col = db.prepare('SELECT * FROM collections WHERE id = ?').get(id) as (Collection & { links?: unknown }) | 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) };
|
||||
return { ...col, links: parseLinks(col.links), place_count: placeCount, members: buildMembers(id) };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -191,14 +222,16 @@ export function getCollection(userId: number, id: number): CollectionDetailRespo
|
||||
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 (?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO collections (owner_id, name, description, color, icon, cover_image, links, sort_order)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
userId,
|
||||
body.name,
|
||||
body.description ?? null,
|
||||
body.color ?? '#6366f1',
|
||||
body.icon ?? 'Bookmark',
|
||||
body.cover_image ?? null,
|
||||
serializeLinks(body.links),
|
||||
max + 1,
|
||||
);
|
||||
const col = getCollectionRow(Number(result.lastInsertRowid));
|
||||
@@ -213,6 +246,8 @@ export function updateCollection(userId: number, id: number, body: CollectionUpd
|
||||
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.cover_image !== undefined) { updates.push('cover_image = ?'); params.push(body.cover_image ?? null); }
|
||||
if (body.links !== undefined) { updates.push('links = ?'); params.push(serializeLinks(body.links)); }
|
||||
if (body.sort_order !== undefined) { updates.push('sort_order = ?'); params.push(body.sort_order); }
|
||||
if (updates.length > 0) {
|
||||
updates.push("updated_at = CURRENT_TIMESTAMP");
|
||||
@@ -224,6 +259,17 @@ export function updateCollection(userId: number, id: number, body: CollectionUpd
|
||||
return { ...col, is_owner: col.owner_id === userId };
|
||||
}
|
||||
|
||||
/** Set (or clear) a list's cover image, reclaiming the previous file. */
|
||||
export function setCollectionCover(userId: number, id: number, coverUrl: string | null): Collection {
|
||||
assertAccess(userId, id);
|
||||
const prev = (db.prepare('SELECT cover_image FROM collections WHERE id = ?').get(id) as { cover_image: string | null } | undefined)?.cover_image ?? null;
|
||||
db.prepare('UPDATE collections SET cover_image = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(coverUrl, id);
|
||||
if (prev && prev !== coverUrl) deleteOldCollectionCover(prev);
|
||||
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');
|
||||
@@ -333,8 +379,8 @@ export function savePlace(userId: number, body: CollectionSavePlaceRequest): Col
|
||||
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
osm_id, website, phone, status, source_trip_id, source_place_id, links
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
body.collection_id, ownerId, userId,
|
||||
body.name, body.description ?? null, body.lat ?? null, body.lng ?? null, body.address ?? null,
|
||||
@@ -342,6 +388,7 @@ export function savePlace(userId: number, body: CollectionSavePlaceRequest): Col
|
||||
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 placeId = Number(result.lastInsertRowid);
|
||||
@@ -389,9 +436,11 @@ export function updatePlace(userId: number, placeId: number, body: import('@trek
|
||||
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.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.links !== undefined) { updates.push('links = ?'); params.push(serializeLinks(body.links)); }
|
||||
|
||||
let movedTo: number | null = null;
|
||||
if (body.collection_id !== undefined && body.collection_id !== currentCollection) {
|
||||
@@ -527,7 +576,11 @@ export function findMembership(
|
||||
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()); }
|
||||
// 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);
|
||||
@@ -612,6 +665,16 @@ export function leaveCollection(userId: number, collectionId: number, socketId:
|
||||
notifyCollectionUsers(collectionId, socketId, 'collections:left');
|
||||
}
|
||||
|
||||
/** Owner removes an already-accepted member (a "kick"). */
|
||||
export function removeMember(ownerId: number, collectionId: number, targetUserId: number): void {
|
||||
if (!isOwner(ownerId, collectionId)) httpError(403, 'Not allowed');
|
||||
if (targetUserId === ownerId) httpError(400, 'Owner cannot be removed');
|
||||
const res = db.prepare("DELETE FROM collection_members WHERE collection_id = ? AND user_id = ? AND status = 'accepted'").run(collectionId, targetUserId);
|
||||
if (res.changes === 0) httpError(404, 'Member not found');
|
||||
notifyCollectionUsers(collectionId, undefined, 'collections:left'); // refresh remaining members
|
||||
broadcastToUser(targetUserId, { type: 'collections:removed', collectionId }); // bounce the removed user
|
||||
}
|
||||
|
||||
export function availableUsers(ownerId: number, collectionId: number): { id: number; username: string }[] {
|
||||
return db.prepare(`
|
||||
SELECT u.id, u.username FROM users u
|
||||
|
||||
Reference in New Issue
Block a user