feat(packing): three-tier sharing — personal, shared-with-people, common pool (#858)

Rework the private-packing flag into a full sharing model. Every item is now
Common (the group pool — where all existing items live, so nothing breaks),
Personal (private to its owner) or Shared with specific people (it shows up on
those travelers' own lists, marked "by <bringer>"). is_private discriminates
restricted from common; a new packing_item_recipients table holds who a shared
item covers, and packing_item_contributors records "I can bring that too"
pledges on Common items.

The panel gains a Gemeinsam / Meine Liste view switch, each item a sharing
control (owner sets the tier + the people it covers), and Common items can be
co-brought or cloned onto your personal list. Visibility is enforced server-side
in listItems and the WebSocket broadcasts are scoped to exactly who can see an
item across every tier transition. All 22 locales stay in parity.
This commit is contained in:
Maurice
2026-06-30 16:15:24 +02:00
committed by Maurice
parent 04f2ec72c6
commit 743b724cbc
42 changed files with 1292 additions and 96 deletions
+22
View File
@@ -3158,6 +3158,28 @@ function runMigrations(db: Database.Database): void {
if (!err.message?.includes('duplicate column name')) throw err;
}
},
// Three-tier packing sharing (#858 follow-up): an item is Common (is_private=0,
// every existing item — non-breaking), Personal (is_private=1, owner only) or
// Shared-with-people (is_private=1 + recipient rows). owner_id is the "bringer".
// Contributors are extra people who said "I can bring that too" on a Common item
// (status 'pending' until the owner accepts).
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS packing_item_recipients (
item_id INTEGER NOT NULL REFERENCES packing_items(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (item_id, user_id)
);
CREATE INDEX IF NOT EXISTS idx_packing_item_recipients_user ON packing_item_recipients(user_id);
CREATE TABLE IF NOT EXISTS packing_item_contributors (
item_id INTEGER NOT NULL REFERENCES packing_items(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'accepted',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (item_id, user_id)
);
`);
},
];
if (currentVersion < migrations.length) {
+101 -6
View File
@@ -18,7 +18,7 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
/** A packing item row carrying the privacy fields (#858) used to scope broadcasts. */
type PackingItemRow = { is_private?: number; owner_id?: number | null; [key: string]: unknown };
type PackingItemRow = { is_private?: number; owner_id?: number | null; recipients?: { user_id: number }[]; [key: string]: unknown };
/**
* /api/trips/:tripId/packing — trip-scoped packing list (items, bags, templates,
@@ -81,7 +81,7 @@ export class PackingController {
create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: { name?: string; category?: string; checked?: boolean; is_private?: boolean },
@Body() body: { name?: string; category?: string; checked?: boolean; is_private?: boolean; visibility?: 'common' | 'personal' | 'shared'; recipient_ids?: number[] },
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
@@ -89,11 +89,22 @@ export class PackingController {
if (!body.name) {
throw new HttpException({ error: 'Item name is required' }, 400);
}
const item = this.packing.createItem(tripId, { name: body.name, category: body.category, checked: body.checked, is_private: body.is_private }, user.id);
this.packing.broadcastItem(tripId, 'packing:created', { item }, item, socketId);
const item = this.packing.createItem(tripId, { name: body.name, category: body.category, checked: body.checked, is_private: body.is_private, visibility: body.visibility, recipient_ids: body.recipient_ids }, user.id);
this.emitToViewers(tripId, 'packing:created', { item }, item, socketId);
return { item };
}
/** Deliver an item event to exactly the people who can see it (#858): the whole
* room for a Common item, or owner + recipients for a restricted one. */
private emitToViewers(tripId: string, event: string, payload: Record<string, unknown>, item: PackingItemRow, socketId: string | undefined): void {
const viewers = this.packing.viewersOf(item);
if (viewers === null) {
this.packing.broadcast(tripId, event, payload, socketId);
} else {
this.packing.broadcastToViewers(tripId, event, payload, viewers, socketId);
}
}
@Put('reorder')
reorder(
@CurrentUser() user: User,
@@ -178,11 +189,95 @@ export class PackingController {
if (!deleted) {
throw new HttpException({ error: 'Item not found' }, 404);
}
// Scope the delete to the owner when the item was private (#858).
this.packing.broadcastItem(tripId, 'packing:deleted', { itemId: Number(id) }, deleted, socketId);
// Scope the delete to the people who could see it (owner + recipients, #858).
this.emitToViewers(tripId, 'packing:deleted', { itemId: Number(id) }, deleted as PackingItemRow, socketId);
return { success: true };
}
@Put(':id/sharing')
setSharing(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Body() body: { visibility?: 'common' | 'personal' | 'shared'; recipient_ids?: number[] },
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
if (body.visibility !== 'common' && body.visibility !== 'personal' && body.visibility !== 'shared') {
throw new HttpException({ error: 'Invalid visibility' }, 400);
}
const updated = this.packing.setItemSharing(tripId, id, user.id, body.visibility, Array.isArray(body.recipient_ids) ? body.recipient_ids : []);
if (!updated) {
throw new HttpException({ error: 'Item not found' }, 404);
}
if ((updated as { forbidden?: boolean }).forbidden) {
throw new HttpException({ error: 'Only the owner can change sharing' }, 403);
}
// The viewer set just changed: drop the item from the whole room, then re-add
// it for whoever can now see it (owner + recipients, or everyone if Common).
this.packing.broadcast(tripId, 'packing:deleted', { itemId: Number(id) }, socketId);
this.emitToViewers(tripId, 'packing:created', { item: updated }, updated as PackingItemRow, socketId);
return { item: updated };
}
@Post(':id/clone')
@HttpCode(201)
clone(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const item = this.packing.cloneItem(tripId, id, user.id);
if (!item) {
throw new HttpException({ error: 'Item not found' }, 404);
}
// The clone is personal to the caller — only their sockets need it.
this.emitToViewers(tripId, 'packing:created', { item }, item, socketId);
return { item };
}
@Post(':id/contributors')
addContributor(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
const item = this.packing.addContributor(tripId, id, user.id);
if (!item) {
throw new HttpException({ error: 'Item not found or not a shared list item' }, 404);
}
// Common item — visible to all, so the contributor change broadcasts to the room.
this.packing.broadcast(tripId, 'packing:updated', { item }, socketId);
return { item };
}
@Delete(':id/contributors/:userId')
removeContributor(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Param('userId') userId: string,
@Headers('x-socket-id') socketId?: string,
) {
const trip = this.requireTrip(tripId, user);
this.requireEdit(trip, user);
// You can drop your own pledge; the owner can remove anyone's.
const target = parseInt(userId);
const item = this.packing.removeContributor(tripId, id, target);
if (!item) {
throw new HttpException({ error: 'Item not found' }, 404);
}
this.packing.broadcast(tripId, 'packing:updated', { item }, socketId);
return { item };
}
@Get('bags')
listBags(@CurrentUser() user: User, @Param('tripId') tripId: string) {
this.requireTrip(tripId, user);
+33 -1
View File
@@ -40,6 +40,22 @@ export class PackingService {
broadcast(tripId, event, payload, socketId, onlyUserId);
}
/** Deliver an item event to a specific set of viewers (#858 shared items) — the
* owner plus the recipients it was shared with — without leaking to the room. */
broadcastToViewers(tripId: string, event: string, payload: Record<string, unknown>, viewerIds: number[], socketId: string | undefined): void {
for (const uid of new Set(viewerIds)) {
if (uid != null) broadcast(tripId, event, payload, socketId, uid);
}
}
/** The users who can currently see an item: everyone (null) for Common, or
* owner + recipients for a restricted item. */
viewersOf(item: { is_private?: number; owner_id?: number | null; recipients?: { user_id: number }[] } | null | undefined): number[] | null {
if (!item || !item.is_private) return null; // Common — visible to the whole room
const ids = [item.owner_id, ...(item.recipients || []).map(r => r.user_id)].filter((x): x is number => x != null);
return ids;
}
listItems(tripId: string, userId?: number) {
return svc.listItems(tripId, userId);
}
@@ -50,10 +66,26 @@ export class PackingService {
return db.prepare('SELECT is_private, owner_id FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId) as PrivacyFields | undefined;
}
createItem(tripId: string, data: { name: string; category?: string; checked?: boolean; is_private?: boolean }, ownerId?: number) {
createItem(tripId: string, data: Parameters<typeof svc.createItem>[1], ownerId?: number) {
return svc.createItem(tripId, data, ownerId);
}
setItemSharing(tripId: string, id: string, actingUserId: number, visibility: svc.PackingVisibility, recipientIds: number[]) {
return svc.setItemSharing(tripId, id, actingUserId, visibility, recipientIds);
}
addContributor(tripId: string, id: string, userId: number) {
return svc.addContributor(tripId, id, userId);
}
removeContributor(tripId: string, id: string, userId: number) {
return svc.removeContributor(tripId, id, userId);
}
cloneItem(tripId: string, id: string, userId: number) {
return svc.cloneItem(tripId, id, userId);
}
updateItem(tripId: string, id: string, data: Parameters<typeof svc.updateItem>[2], changedKeys: string[], ifMatch?: string, actingUserId?: number) {
return svc.updateItem(tripId, id, data, changedKeys, ifMatch, actingUserId);
}
+155 -17
View File
@@ -8,30 +8,105 @@ export { verifyTripAccess } from './tripAccess';
// ── Items ──────────────────────────────────────────────────────────────────
export function listItems(tripId: string | number, userId?: number) {
// Private items (#858) are visible only to their owner; shared items
// (is_private = 0) are visible to everyone. Without a userId (internal callers
// such as trip export) the unfiltered list is returned for back-compat.
if (userId == null) {
return db.prepare(
'SELECT * FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC, created_at ASC'
).all(tripId);
/**
* Attach the bringer name, recipients and co-contributors to a set of packing
* items (#858 three-tier sharing). Batched so the list endpoint stays one round
* of queries regardless of item count.
*/
function enrichItems(items: any[]): any[] {
if (items.length === 0) return items;
const ids = items.map(i => i.id);
const placeholders = ids.map(() => '?').join(',');
const owners = db.prepare(`SELECT id, username FROM users WHERE id IN (SELECT owner_id FROM packing_items WHERE id IN (${placeholders}))`).all(...ids) as { id: number; username: string }[];
const ownerName = new Map(owners.map(o => [o.id, o.username]));
const recipientRows = db.prepare(`
SELECT r.item_id, r.user_id, u.username
FROM packing_item_recipients r JOIN users u ON u.id = r.user_id
WHERE r.item_id IN (${placeholders})
`).all(...ids) as { item_id: number; user_id: number; username: string }[];
const recipientsByItem = new Map<number, { user_id: number; username: string }[]>();
for (const r of recipientRows) {
if (!recipientsByItem.has(r.item_id)) recipientsByItem.set(r.item_id, []);
recipientsByItem.get(r.item_id)!.push({ user_id: r.user_id, username: r.username });
}
return db.prepare(
'SELECT * FROM packing_items WHERE trip_id = ? AND (is_private = 0 OR owner_id = ?) ORDER BY sort_order ASC, created_at ASC'
).all(tripId, userId);
const contributorRows = db.prepare(`
SELECT c.item_id, c.user_id, c.status, u.username
FROM packing_item_contributors c JOIN users u ON u.id = c.user_id
WHERE c.item_id IN (${placeholders})
`).all(...ids) as { item_id: number; user_id: number; status: string; username: string }[];
const contributorsByItem = new Map<number, { user_id: number; username: string; status: string }[]>();
for (const c of contributorRows) {
if (!contributorsByItem.has(c.item_id)) contributorsByItem.set(c.item_id, []);
contributorsByItem.get(c.item_id)!.push({ user_id: c.user_id, username: c.username, status: c.status });
}
return items.map(i => ({
...i,
owner_username: i.owner_id != null ? ownerName.get(i.owner_id) ?? null : null,
recipients: recipientsByItem.get(i.id) || [],
contributors: contributorsByItem.get(i.id) || [],
}));
}
export function createItem(tripId: string | number, data: { name: string; category?: string; checked?: boolean; quantity?: number; is_private?: boolean }, ownerId?: number) {
export function listItems(tripId: string | number, userId?: number) {
// Three-tier visibility (#858): Common (is_private=0) is visible to everyone;
// Personal/Shared (is_private=1) only to the owner (bringer) and the recipients
// it was explicitly shared with. Without a userId (internal callers such as
// trip export) the unfiltered list is returned for back-compat.
let rows: any[];
if (userId == null) {
rows = db.prepare(
'SELECT * FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC, created_at ASC'
).all(tripId) as any[];
} else {
rows = db.prepare(`
SELECT * FROM packing_items
WHERE trip_id = ?
AND (is_private = 0
OR owner_id = ?
OR EXISTS (SELECT 1 FROM packing_item_recipients r WHERE r.item_id = packing_items.id AND r.user_id = ?))
ORDER BY sort_order ASC, created_at ASC
`).all(tripId, userId, userId) as any[];
}
return enrichItems(rows);
}
export type PackingVisibility = 'common' | 'personal' | 'shared';
/** Maps the three-tier visibility (#858) onto the stored is_private flag. */
function visibilityToPrivate(visibility?: PackingVisibility, isPrivateFallback?: boolean): number {
if (visibility) return visibility === 'common' ? 0 : 1;
return isPrivateFallback ? 1 : 0;
}
export function createItem(
tripId: string | number,
data: { name: string; category?: string; checked?: boolean; quantity?: number; is_private?: boolean; visibility?: PackingVisibility; recipient_ids?: number[] },
ownerId?: number,
) {
const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null };
const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const qty = Math.max(1, Math.min(999, Number(data.quantity) || 1));
const isPrivate = visibilityToPrivate(data.visibility, data.is_private);
const result = db.prepare(
'INSERT INTO packing_items (trip_id, name, checked, category, sort_order, quantity, is_private, owner_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)'
).run(tripId, data.name, data.checked ? 1 : 0, data.category || 'Allgemein', sortOrder, qty, data.is_private ? 1 : 0, ownerId ?? null);
const create = db.transaction(() => {
const result = db.prepare(
'INSERT INTO packing_items (trip_id, name, checked, category, sort_order, quantity, is_private, owner_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)'
).run(tripId, data.name, data.checked ? 1 : 0, data.category || 'Allgemein', sortOrder, qty, isPrivate, ownerId ?? null);
const itemId = Number(result.lastInsertRowid);
// "Shared with specific people" — record the recipients it covers.
if (data.visibility === 'shared' && Array.isArray(data.recipient_ids)) {
const ins = db.prepare('INSERT OR IGNORE INTO packing_item_recipients (item_id, user_id) VALUES (?, ?)');
for (const uid of data.recipient_ids) if (uid !== ownerId) ins.run(itemId, uid);
}
return itemId;
});
const itemId = create();
return db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid);
return enrichItems([db.prepare('SELECT * FROM packing_items WHERE id = ?').get(itemId)])[0];
}
export function updateItem(
@@ -85,7 +160,70 @@ export function updateItem(
id
);
return db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id);
return enrichItems([db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id)])[0];
}
// ── Three-tier sharing (#858): recipients, contributors, clone ───────────────
/** Loads an item scoped to its trip (the trip-access check happens in the controller). */
function getItemInTrip(tripId: string | number, id: string | number) {
return db.prepare('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId) as
{ id: number; owner_id: number | null; is_private: number; name: string; category: string | null; quantity: number } | undefined;
}
/**
* Re-set who a "shared with specific people" item covers, and its visibility tier.
* Only the owner (bringer) may change this; a non-owner caller is rejected with null.
*/
export function setItemSharing(
tripId: string | number,
id: string | number,
actingUserId: number,
visibility: PackingVisibility,
recipientIds: number[],
) {
const item = getItemInTrip(tripId, id);
if (!item) return null;
// The owner controls sharing; an unowned legacy item is claimed by the actor.
if (item.owner_id != null && item.owner_id !== actingUserId) return { forbidden: true as const };
const run = db.transaction(() => {
db.prepare('UPDATE packing_items SET is_private = ?, owner_id = COALESCE(owner_id, ?), updated_at = CURRENT_TIMESTAMP WHERE id = ?')
.run(visibilityToPrivate(visibility), actingUserId, id);
db.prepare('DELETE FROM packing_item_recipients WHERE item_id = ?').run(id);
if (visibility === 'shared') {
const ins = db.prepare('INSERT OR IGNORE INTO packing_item_recipients (item_id, user_id) VALUES (?, ?)');
const owner = item.owner_id ?? actingUserId;
for (const uid of recipientIds) if (uid !== owner) ins.run(id, uid);
}
// Leaving the Common tier drops any co-contributors (they only apply to Common).
if (visibility !== 'common') db.prepare('DELETE FROM packing_item_contributors WHERE item_id = ?').run(id);
});
run();
return enrichItems([db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id)])[0];
}
/** "I can bring that too" — adds the user as a co-contributor on a Common item. */
export function addContributor(tripId: string | number, id: string | number, userId: number) {
const item = getItemInTrip(tripId, id);
if (!item || item.is_private !== 0) return null; // co-contribution is a Common-list concept
if (item.owner_id === userId) return null; // the bringer is already covering it
db.prepare("INSERT OR IGNORE INTO packing_item_contributors (item_id, user_id, status) VALUES (?, ?, 'accepted')").run(id, userId);
return enrichItems([db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id)])[0];
}
export function removeContributor(tripId: string | number, id: string | number, userId: number) {
const item = getItemInTrip(tripId, id);
if (!item) return null;
db.prepare('DELETE FROM packing_item_contributors WHERE item_id = ? AND user_id = ?').run(id, userId);
return enrichItems([db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id)])[0];
}
/** Clone a (Common) item onto the caller's Personal list as a private starting point. */
export function cloneItem(tripId: string | number, id: string | number, userId: number) {
const item = getItemInTrip(tripId, id);
if (!item) return null;
return createItem(tripId, { name: item.name, category: item.category || undefined, quantity: item.quantity, visibility: 'personal' }, userId);
}
export function deleteItem(tripId: string | number, id: string | number) {