mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 18:54:17 +00:00
feat(collections): per-collection custom labels
Each list can now define its own labels (e.g. Berlin, Hamburg, Ostsee in a "Germany 2026" list) and organise its places by them: - manage labels (create / rename / recolor / delete) from a label manager - assign labels to a place from its detail sheet, or to many places at once from the selection toolbar - filter the place list AND the map by label (multi-select, any-match) Labels are scoped to a collection and shared by all its members. Managing and assigning labels needs edit rights; filtering is available to everyone. Moving a place to another list drops its labels, since they belong to the source list.
This commit is contained in:
@@ -3398,6 +3398,27 @@ function runMigrations(db: Database.Database): void {
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_plugin_audit_plugin ON plugin_capability_audit (plugin_id, id);');
|
||||
} catch (err) { console.warn('[migrations] Non-fatal migration step failed:', err); }
|
||||
},
|
||||
// Migration 160: per-collection custom labels (#collections). Each list owns
|
||||
// its own label set (unlike the instance-wide `tags` table), and a place can
|
||||
// carry several labels. Used for grouping + filtering places within a list.
|
||||
() => {
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS collection_labels (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT DEFAULT '#6366f1',
|
||||
sort_order INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);`);
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS collection_place_labels (
|
||||
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
|
||||
label_id INTEGER NOT NULL REFERENCES collection_labels(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (collection_place_id, label_id)
|
||||
);`);
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_collection_labels_collection ON collection_labels(collection_id);');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_collection_place_labels_place ON collection_place_labels(collection_place_id);');
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_collection_place_labels_label ON collection_place_labels(label_id);');
|
||||
},
|
||||
];
|
||||
|
||||
if (currentVersion < migrations.length) {
|
||||
|
||||
@@ -436,6 +436,27 @@ function createTables(db: Database.Database): void {
|
||||
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);
|
||||
|
||||
-- Per-collection custom labels (distinct from the instance-wide tags table):
|
||||
-- each list defines its own labels and every place can carry several.
|
||||
CREATE TABLE IF NOT EXISTS collection_labels (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT DEFAULT '#6366f1',
|
||||
sort_order INTEGER DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS collection_place_labels (
|
||||
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
|
||||
label_id INTEGER NOT NULL REFERENCES collection_labels(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (collection_place_id, label_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_collection_labels_collection ON collection_labels(collection_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_collection_place_labels_place ON collection_place_labels(collection_place_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_collection_place_labels_label ON collection_place_labels(label_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS day_accommodations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
|
||||
|
||||
@@ -41,6 +41,12 @@ import {
|
||||
collectionInviteCancelRequestSchema,
|
||||
collectionRemoveMemberRequestSchema,
|
||||
collectionSetMemberRoleRequestSchema,
|
||||
collectionLabelCreateRequestSchema,
|
||||
collectionLabelUpdateRequestSchema,
|
||||
collectionLabelAssignRequestSchema,
|
||||
type CollectionLabelCreateRequest,
|
||||
type CollectionLabelUpdateRequest,
|
||||
type CollectionLabelAssignRequest,
|
||||
type CollectionCreateRequest,
|
||||
type CollectionUpdateRequest,
|
||||
type CollectionSavePlaceRequest,
|
||||
@@ -173,6 +179,53 @@ export class CollectionsController {
|
||||
return this.collections.copyToTrip(user.id, body);
|
||||
}
|
||||
|
||||
// ── Labels (per-collection custom labels; static prefixes before /:id) ───────
|
||||
@Post('labels')
|
||||
@HttpCode(200)
|
||||
createLabel(
|
||||
@CurrentUser() user: User,
|
||||
@Body(new ZodValidationPipe(collectionLabelCreateRequestSchema)) body: CollectionLabelCreateRequest,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.collections.createLabel(user.id, body.collection_id, body.name, body.color, socketId);
|
||||
}
|
||||
|
||||
@Patch('labels/:lid')
|
||||
updateLabel(
|
||||
@CurrentUser() user: User,
|
||||
@Param('lid') lid: string,
|
||||
@Body(new ZodValidationPipe(collectionLabelUpdateRequestSchema)) body: CollectionLabelUpdateRequest,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.collections.updateLabel(user.id, Number(lid), body, socketId);
|
||||
}
|
||||
|
||||
@Delete('labels/:lid')
|
||||
deleteLabel(@CurrentUser() user: User, @Param('lid') lid: string, @Headers('x-socket-id') socketId?: string) {
|
||||
this.collections.deleteLabel(user.id, Number(lid), socketId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Post('labels/assign')
|
||||
@HttpCode(200)
|
||||
assignLabels(
|
||||
@CurrentUser() user: User,
|
||||
@Body(new ZodValidationPipe(collectionLabelAssignRequestSchema)) body: CollectionLabelAssignRequest,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.collections.assignLabels(user.id, body.label_ids, body.place_ids, false, socketId);
|
||||
}
|
||||
|
||||
@Post('labels/unassign')
|
||||
@HttpCode(200)
|
||||
unassignLabels(
|
||||
@CurrentUser() user: User,
|
||||
@Body(new ZodValidationPipe(collectionLabelAssignRequestSchema)) body: CollectionLabelAssignRequest,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.collections.assignLabels(user.id, body.label_ids, body.place_ids, true, socketId);
|
||||
}
|
||||
|
||||
// ── Library-wide membership lookup ──────────────────────────────────────────
|
||||
@Get('membership')
|
||||
membership(
|
||||
|
||||
@@ -41,6 +41,11 @@ export class CollectionsService {
|
||||
return svc.findMembership(userId, query);
|
||||
}
|
||||
|
||||
createLabel(userId: number, collectionId: number, name: string, color: string | undefined, socketId?: string) { return svc.createLabel(userId, collectionId, name, color, socketId); }
|
||||
updateLabel(userId: number, labelId: number, body: { name?: string; color?: string; sort_order?: number }, socketId?: string) { return svc.updateLabel(userId, labelId, body, socketId); }
|
||||
deleteLabel(userId: number, labelId: number, socketId?: string) { return svc.deleteLabel(userId, labelId, socketId); }
|
||||
assignLabels(userId: number, labelIds: number[], placeIds: number[], remove: boolean, socketId?: string) { return svc.assignLabels(userId, labelIds, placeIds, remove, socketId); }
|
||||
|
||||
// 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); }
|
||||
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
CollectionSaveResult,
|
||||
CollectionCopyToTripRequest,
|
||||
CollectionStatus,
|
||||
CollectionLabel,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Links are stored as a JSON TEXT column; parse on read, stringify on write. */
|
||||
@@ -147,9 +148,32 @@ function loadTagsByCollectionPlaceIds(placeIds: number[]): Record<number, { id:
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A list's own label definitions, in display order. */
|
||||
function loadLabelsByCollection(collectionId: number): CollectionLabel[] {
|
||||
return db.prepare(
|
||||
'SELECT id, collection_id, name, color, sort_order FROM collection_labels WHERE collection_id = ? ORDER BY sort_order, id',
|
||||
).all(collectionId) as CollectionLabel[];
|
||||
}
|
||||
|
||||
/** Assigned label ids per place, batched (mirrors loadTagsByCollectionPlaceIds). */
|
||||
function loadLabelIdsByPlaceIds(placeIds: number[]): Record<number, number[]> {
|
||||
const out: Record<number, number[]> = {};
|
||||
if (placeIds.length === 0) return out;
|
||||
const placeholders = placeIds.map(() => '?').join(',');
|
||||
const rows = db.prepare(
|
||||
`SELECT collection_place_id AS pid, label_id FROM collection_place_labels WHERE collection_place_id IN (${placeholders})`,
|
||||
).all(...placeIds) as { pid: number; label_id: number }[];
|
||||
for (const r of rows) {
|
||||
if (!out[r.pid]) out[r.pid] = [];
|
||||
out[r.pid].push(r.label_id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function hydratePlaces(rows: PlaceRow[]): CollectionPlace[] {
|
||||
const ids = rows.map(r => r.id);
|
||||
const tagsByPlace = loadTagsByCollectionPlaceIds(ids);
|
||||
const labelsByPlace = loadLabelIdsByPlaceIds(ids);
|
||||
return rows.map(r => {
|
||||
const { category_name, category_color, category_icon, ...rest } = r;
|
||||
return {
|
||||
@@ -159,6 +183,7 @@ function hydratePlaces(rows: PlaceRow[]): CollectionPlace[] {
|
||||
? { id: r.category_id, name: category_name ?? '', color: category_color ?? null, icon: category_icon ?? null }
|
||||
: undefined,
|
||||
tags: tagsByPlace[r.id] || [],
|
||||
label_ids: labelsByPlace[r.id] || [],
|
||||
} as CollectionPlace;
|
||||
});
|
||||
}
|
||||
@@ -240,7 +265,10 @@ export function getCollection(userId: number, id: number): CollectionDetailRespo
|
||||
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) };
|
||||
return {
|
||||
collection: { ...collection, is_owner: collection.owner_id === userId, labels: loadLabelsByCollection(id) },
|
||||
places: hydratePlaces(rows),
|
||||
};
|
||||
}
|
||||
|
||||
export function createCollection(userId: number, body: CollectionCreateRequest): Collection {
|
||||
@@ -528,6 +556,11 @@ export function updatePlace(userId: number, placeId: number, body: import('@trek
|
||||
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) db.prepare('DELETE FROM collection_place_labels WHERE collection_place_id = ?').run(placeId);
|
||||
if (body.label_ids !== undefined) setPlaceLabels(placeId, movedTo ?? currentCollection, body.label_ids);
|
||||
|
||||
notifyCollectionUsers(currentCollection, socketId, 'collections:updated');
|
||||
if (movedTo) notifyCollectionUsers(movedTo, socketId, 'collections:updated');
|
||||
return getPlaceById(placeId);
|
||||
@@ -677,6 +710,106 @@ export function notifyCollectionUsers(collectionId: number, excludeSid: string |
|
||||
userIds.forEach(id => broadcastToUser(id, { type: event, collectionId }, excludeSid));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Labels — per-collection custom labels. Managing + assigning both require edit
|
||||
// rights (owner/admin/editor); filtering is a read available to every member.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const MAX_LABELS_PER_COLLECTION = 50;
|
||||
|
||||
function collectionIdOfLabel(labelId: number): number {
|
||||
const row = db.prepare('SELECT collection_id FROM collection_labels WHERE id = ?').get(labelId) as { collection_id: number } | undefined;
|
||||
if (!row) httpError(404, 'Label not found');
|
||||
return row.collection_id;
|
||||
}
|
||||
|
||||
function getLabelById(labelId: number): CollectionLabel {
|
||||
return db.prepare('SELECT id, collection_id, name, color, sort_order FROM collection_labels WHERE id = ?').get(labelId) as CollectionLabel;
|
||||
}
|
||||
|
||||
/** Replace a place's label assignments, keeping only labels of `collectionId`. */
|
||||
function setPlaceLabels(placeId: number, collectionId: number, labelIds: number[]): void {
|
||||
db.prepare('DELETE FROM collection_place_labels WHERE collection_place_id = ?').run(placeId);
|
||||
if (labelIds.length === 0) return;
|
||||
const valid = new Set(loadLabelsByCollection(collectionId).map(l => l.id));
|
||||
const stmt = 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);
|
||||
}
|
||||
|
||||
export function createLabel(userId: number, collectionId: number, name: string, color?: string, socketId?: string): CollectionLabel {
|
||||
assertCanEdit(userId, collectionId);
|
||||
const trimmed = name.trim();
|
||||
if (!trimmed) httpError(400, 'Label name is required');
|
||||
const count = (db.prepare('SELECT COUNT(*) AS n FROM collection_labels WHERE collection_id = ?').get(collectionId) as { n: number }).n;
|
||||
if (count >= MAX_LABELS_PER_COLLECTION) httpError(400, `A list can have at most ${MAX_LABELS_PER_COLLECTION} labels`);
|
||||
if (db.prepare('SELECT 1 FROM collection_labels WHERE collection_id = ? AND lower(name) = lower(?)').get(collectionId, trimmed)) {
|
||||
httpError(409, 'A label with this name already exists');
|
||||
}
|
||||
const nextSort = (db.prepare('SELECT COALESCE(MAX(sort_order), -1) AS m FROM collection_labels WHERE collection_id = ?').get(collectionId) as { m: number }).m + 1;
|
||||
const res = db.prepare('INSERT INTO collection_labels (collection_id, name, color, sort_order) VALUES (?, ?, ?, ?)')
|
||||
.run(collectionId, trimmed, color ?? '#6366f1', nextSort);
|
||||
notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
return getLabelById(Number(res.lastInsertRowid));
|
||||
}
|
||||
|
||||
export function updateLabel(userId: number, labelId: number, body: { name?: string; color?: string; sort_order?: number }, socketId?: string): CollectionLabel {
|
||||
const collectionId = collectionIdOfLabel(labelId);
|
||||
assertCanEdit(userId, collectionId);
|
||||
const updates: string[] = [];
|
||||
const params: (string | number)[] = [];
|
||||
if (body.name !== undefined) {
|
||||
const trimmed = body.name.trim();
|
||||
if (!trimmed) httpError(400, 'Label name is required');
|
||||
if (db.prepare('SELECT 1 FROM collection_labels WHERE collection_id = ? AND lower(name) = lower(?) AND id != ?').get(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);
|
||||
db.prepare(`UPDATE collection_labels SET ${updates.join(', ')} WHERE id = ?`).run(...params);
|
||||
}
|
||||
notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
return getLabelById(labelId);
|
||||
}
|
||||
|
||||
export function deleteLabel(userId: number, labelId: number, socketId?: string): void {
|
||||
const collectionId = collectionIdOfLabel(labelId);
|
||||
assertCanEdit(userId, collectionId);
|
||||
db.prepare('DELETE FROM collection_labels WHERE id = ?').run(labelId); // CASCADE clears place assignments
|
||||
notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
}
|
||||
|
||||
/** Bulk add (or remove) one or more labels across a selection of places.
|
||||
* Places are grouped by list so each list is permission-checked once, and only
|
||||
* labels that belong to that list are applied. */
|
||||
export function assignLabels(userId: number, labelIds: number[], placeIds: number[], remove: boolean, socketId?: string): { changed: number } {
|
||||
const byCollection = new Map<number, number[]>();
|
||||
for (const pid of placeIds) {
|
||||
const cid = collectionIdOfPlace(pid);
|
||||
if (!byCollection.has(cid)) byCollection.set(cid, []);
|
||||
byCollection.get(cid)!.push(pid);
|
||||
}
|
||||
let changed = 0;
|
||||
for (const [cid, pids] of byCollection) {
|
||||
assertCanEdit(userId, cid);
|
||||
const valid = new Set(loadLabelsByCollection(cid).map(l => l.id));
|
||||
const applicable = labelIds.filter(id => valid.has(id));
|
||||
if (applicable.length === 0) continue;
|
||||
if (remove) {
|
||||
const del = 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;
|
||||
} else {
|
||||
const ins = 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;
|
||||
}
|
||||
notifyCollectionUsers(cid, socketId, 'collections:updated');
|
||||
}
|
||||
return { changed };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fusion invitations (mirror vacayService, dropping the one-fusion guards)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -190,6 +190,39 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
|
||||
expect(res.status).toBe(403); // visible (member) but not owner
|
||||
});
|
||||
|
||||
// ── Labels ─────────────────────────────────────────────────────────────────
|
||||
it('COLLECTIONS-E2E-060: a label route is addon-gated (404 when disabled)', async () => {
|
||||
isAddonEnabled.mockReturnValue(false);
|
||||
expect((await request(server).post('/api/addons/collections/labels').send({ collection_id: 1, name: 'X' })).status).toBe(404);
|
||||
});
|
||||
|
||||
it('COLLECTIONS-E2E-061: create a label, assign it to a place, read it back on the detail', async () => {
|
||||
const col = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Germany' })).body;
|
||||
const place = (await request(server).post('/api/addons/collections/places')
|
||||
.set('Cookie', sessionCookie(ownerId)).send({ collection_id: col.id, name: 'Gate' })).body.place;
|
||||
|
||||
const label = await request(server).post('/api/addons/collections/labels')
|
||||
.set('Cookie', sessionCookie(ownerId)).set('X-Socket-Id', 'sock-2').send({ collection_id: col.id, name: 'Berlin', color: '#ff0000' });
|
||||
expect(label.status).toBe(200);
|
||||
expect(label.body.name).toBe('Berlin');
|
||||
|
||||
const assign = await request(server).post('/api/addons/collections/labels/assign')
|
||||
.set('Cookie', sessionCookie(ownerId)).send({ label_ids: [label.body.id], place_ids: [place.id] });
|
||||
expect(assign.status).toBe(200);
|
||||
expect(assign.body.changed).toBe(1);
|
||||
|
||||
const detail = await request(server).get(`/api/addons/collections/${col.id}`).set('Cookie', sessionCookie(ownerId));
|
||||
expect(detail.body.collection.labels.map((l: { name: string }) => l.name)).toContain('Berlin');
|
||||
expect(detail.body.places.find((p: { id: number }) => p.id === place.id).label_ids).toContain(label.body.id);
|
||||
});
|
||||
|
||||
it('COLLECTIONS-E2E-062: a stranger cannot create a label on someone else’s list (404)', async () => {
|
||||
const col = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Secret' })).body;
|
||||
const res = await request(server).post('/api/addons/collections/labels')
|
||||
.set('Cookie', sessionCookie(otherId)).send({ collection_id: col.id, name: 'Nope' });
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
// ── delete ───────────────────────────────────────────────────────────────
|
||||
it('COLLECTIONS-E2E-050: owner deletes; non-owner member cannot (403)', async () => {
|
||||
const col = (await request(server).post('/api/addons/collections').set('Cookie', sessionCookie(ownerId)).send({ name: 'Doomed' })).body;
|
||||
|
||||
@@ -33,6 +33,10 @@ function makeService(overrides: Partial<Record<keyof CollectionsService, unknown
|
||||
leaveCollection: vi.fn(),
|
||||
removeMember: vi.fn(),
|
||||
availableUsers: vi.fn().mockReturnValue([{ id: 2 }]),
|
||||
createLabel: vi.fn().mockReturnValue({ id: 5, collection_id: 3, name: 'Berlin' }),
|
||||
updateLabel: vi.fn().mockReturnValue({ id: 5, collection_id: 3, name: 'Hamburg' }),
|
||||
deleteLabel: vi.fn(),
|
||||
assignLabels: vi.fn().mockReturnValue({ changed: 2 }),
|
||||
...overrides,
|
||||
} as unknown as CollectionsService;
|
||||
}
|
||||
@@ -191,4 +195,26 @@ describe('CollectionsController', () => {
|
||||
expect(svc.setCollectionCover).toHaveBeenCalledWith(1, 3, '/uploads/covers/x.jpg', 'sid');
|
||||
});
|
||||
});
|
||||
|
||||
describe('labels', () => {
|
||||
it('create / update / delete / assign / unassign forward user + socket id', () => {
|
||||
const svc = makeService();
|
||||
const c = new CollectionsController(svc);
|
||||
|
||||
c.createLabel(user, { collection_id: 3, name: 'Berlin', color: '#ff0000' } as never, 'sock');
|
||||
expect(svc.createLabel).toHaveBeenCalledWith(1, 3, 'Berlin', '#ff0000', 'sock');
|
||||
|
||||
c.updateLabel(user, '5', { name: 'Hamburg' } as never, 'sock');
|
||||
expect(svc.updateLabel).toHaveBeenCalledWith(1, 5, { name: 'Hamburg' }, 'sock');
|
||||
|
||||
expect(c.deleteLabel(user, '5', 'sock')).toEqual({ success: true });
|
||||
expect(svc.deleteLabel).toHaveBeenCalledWith(1, 5, 'sock');
|
||||
|
||||
c.assignLabels(user, { label_ids: [5], place_ids: [9, 10] } as never, 'sock');
|
||||
expect(svc.assignLabels).toHaveBeenCalledWith(1, [5], [9, 10], false, 'sock');
|
||||
|
||||
c.unassignLabels(user, { label_ids: [5], place_ids: [9] } as never, 'sock');
|
||||
expect(svc.assignLabels).toHaveBeenCalledWith(1, [5], [9], true, 'sock');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -47,6 +47,8 @@ import { removeIfUnreferenced } from '../../../src/services/placePhotoCache';
|
||||
|
||||
function clearCollections() {
|
||||
testDb.exec(`
|
||||
DELETE FROM collection_place_labels;
|
||||
DELETE FROM collection_labels;
|
||||
DELETE FROM collection_place_tags;
|
||||
DELETE FROM collection_places;
|
||||
DELETE FROM collection_members;
|
||||
@@ -482,3 +484,87 @@ describe('photo-cache widening', () => {
|
||||
expect(meta).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ── Labels ───────────────────────────────────────────────────────────────────
|
||||
|
||||
function addMember(colId: number, userId: number, role: 'viewer' | 'editor' | 'admin') {
|
||||
testDb.prepare("INSERT INTO collection_members (collection_id, user_id, status, role) VALUES (?, ?, 'accepted', ?)").run(colId, userId, role);
|
||||
}
|
||||
|
||||
describe('collection labels', () => {
|
||||
it('COLLECTIONS-SVC-050: createLabel is returned by getCollection; duplicate name is 409', () => {
|
||||
const u = createUser(testDb).user;
|
||||
const col = svc.createCollection(u.id, { name: 'Germany' });
|
||||
const label = svc.createLabel(u.id, col.id, 'Berlin', '#ff0000');
|
||||
expect(label.name).toBe('Berlin');
|
||||
expect(label.collection_id).toBe(col.id);
|
||||
expect(svc.getCollection(u.id, col.id).collection.labels).toHaveLength(1);
|
||||
|
||||
expect(() => svc.createLabel(u.id, col.id, 'berlin')).toThrow(); // case-insensitive dup
|
||||
try { svc.createLabel(u.id, col.id, 'berlin'); } catch (e) { expect((e as { status: number }).status).toBe(409); }
|
||||
});
|
||||
|
||||
it('COLLECTIONS-SVC-051: a viewer cannot manage labels (403); an editor can', () => {
|
||||
const owner = createUser(testDb).user;
|
||||
const viewer = createUser(testDb).user;
|
||||
const col = svc.createCollection(owner.id, { name: 'Trip' });
|
||||
addMember(col.id, viewer.id, 'viewer');
|
||||
try { svc.createLabel(viewer.id, col.id, 'X'); } catch (e) { expect((e as { status: number }).status).toBe(403); }
|
||||
|
||||
const editor = createUser(testDb).user;
|
||||
addMember(col.id, editor.id, 'editor');
|
||||
expect(svc.createLabel(editor.id, col.id, 'Museums').id).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('COLLECTIONS-SVC-052: updatePlace label_ids sets labels; a label from another list is ignored', () => {
|
||||
const u = createUser(testDb).user;
|
||||
const col = svc.createCollection(u.id, { name: 'DE' });
|
||||
const other = svc.createCollection(u.id, { name: 'Other' });
|
||||
const l1 = svc.createLabel(u.id, col.id, 'Berlin');
|
||||
const foreign = svc.createLabel(u.id, other.id, 'Paris');
|
||||
const place = svc.savePlace(u.id, { collection_id: col.id, name: 'Gate' }).place!;
|
||||
svc.updatePlace(u.id, place.id, { label_ids: [l1.id, foreign.id] });
|
||||
const stored = svc.getCollection(u.id, col.id).places.find(p => p.id === place.id)!;
|
||||
expect(stored.label_ids).toEqual([l1.id]);
|
||||
});
|
||||
|
||||
it('COLLECTIONS-SVC-053: assignLabels bulk-adds then unassigns across places', () => {
|
||||
const u = createUser(testDb).user;
|
||||
const col = svc.createCollection(u.id, { name: 'DE' });
|
||||
const l = svc.createLabel(u.id, col.id, 'Coast');
|
||||
const p1 = svc.savePlace(u.id, { collection_id: col.id, name: 'A' }).place!;
|
||||
const p2 = svc.savePlace(u.id, { collection_id: col.id, name: 'B' }).place!;
|
||||
|
||||
expect(svc.assignLabels(u.id, [l.id], [p1.id, p2.id], false).changed).toBe(2);
|
||||
expect(svc.getCollection(u.id, col.id).places.every(p => p.label_ids?.includes(l.id))).toBe(true);
|
||||
|
||||
svc.assignLabels(u.id, [l.id], [p1.id], true);
|
||||
const after = svc.getCollection(u.id, col.id).places;
|
||||
expect(after.find(p => p.id === p1.id)!.label_ids).toEqual([]);
|
||||
expect(after.find(p => p.id === p2.id)!.label_ids).toEqual([l.id]);
|
||||
});
|
||||
|
||||
it('COLLECTIONS-SVC-054: deleteLabel removes it and cascades its place assignments', () => {
|
||||
const u = createUser(testDb).user;
|
||||
const col = svc.createCollection(u.id, { name: 'DE' });
|
||||
const l = svc.createLabel(u.id, col.id, 'Berlin');
|
||||
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Gate' }).place!;
|
||||
svc.updatePlace(u.id, p.id, { label_ids: [l.id] });
|
||||
|
||||
svc.deleteLabel(u.id, l.id);
|
||||
expect(svc.getCollection(u.id, col.id).collection.labels).toHaveLength(0);
|
||||
expect(svc.getCollection(u.id, col.id).places.find(x => x.id === p.id)!.label_ids).toEqual([]);
|
||||
});
|
||||
|
||||
it('COLLECTIONS-SVC-055: moving a place to another list drops its labels', () => {
|
||||
const u = createUser(testDb).user;
|
||||
const a = svc.createCollection(u.id, { name: 'A' });
|
||||
const b = svc.createCollection(u.id, { name: 'B' });
|
||||
const l = svc.createLabel(u.id, a.id, 'Berlin');
|
||||
const p = svc.savePlace(u.id, { collection_id: a.id, name: 'Gate' }).place!;
|
||||
svc.updatePlace(u.id, p.id, { label_ids: [l.id] });
|
||||
|
||||
svc.updatePlace(u.id, p.id, { collection_id: b.id });
|
||||
expect(svc.getCollection(u.id, b.id).places.find(x => x.id === p.id)!.label_ids).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user