fix(packing): serialize bringer and privacy updates

Use the shared write transaction for packing item updates and contributor edits. Remove Common bringers when an item becomes restricted and scope contributor broadcasts to the returned item viewers.
This commit is contained in:
Maurice
2026-12-05 12:34:02 +01:00
parent b79d104349
commit 09567d32c4
5 changed files with 112 additions and 59 deletions
@@ -187,7 +187,7 @@ export class PackingWritesService {
await this.gate(tripId, writer);
const item = await this.packing.setBringers(tripId, itemId, userIds, writer.userId);
if (!item) throw itemNotFound();
writer.events.emit('packing:updated', { item } as TrekWsPayload<'packing:updated'>);
writer.events.emit('packing:updated', { item } as TrekWsPayload<'packing:updated'>, this.packing.viewersOf(item));
return item;
}
@@ -270,8 +270,7 @@ export class PackingController {
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);
this.packing.emitToViewers(tripId, 'packing:updated', { item }, item, socketId);
return { item };
}
@@ -298,7 +297,7 @@ export class PackingController {
if (!item) {
throw new HttpException({ error: 'Item not found' }, 404);
}
this.packing.broadcast(tripId, 'packing:updated', { item }, socketId);
this.packing.emitToViewers(tripId, 'packing:updated', { item }, item, socketId);
return { item };
}
+63 -55
View File
@@ -318,48 +318,54 @@ export class PackingService {
ifMatch?: string,
actingUserId?: number,
): Promise<unknown | UpdateConflict | null> {
// Was a trip-scoped lookup, which let any member with packing_edit write to
// another member's restricted item (and read it back off the response).
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// Bringer changes and privacy changes share the same write transaction.
return this.uow.transactional(async () => {
// Was a trip-scoped lookup, which let any member with packing_edit write to
// another member's restricted item (and read it back off the response).
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// Optimistic concurrency (#1135): reject a stale offline overwrite. Absent
// token => unconditional update (back-compat with older clients).
if (ifMatch !== undefined && item.updated_at != null && String(item.updated_at) !== ifMatch) {
return { conflict: true, server: await this.itemsRepo.findById(id) };
}
// Optimistic concurrency (#1135): reject a stale offline overwrite. Absent
// token => unconditional update (back-compat with older clients).
if (ifMatch !== undefined && item.updated_at != null && String(item.updated_at) !== ifMatch) {
return { conflict: true, server: await this.itemsRepo.findById(id) };
}
// A non-null bag about to be bound must belong to this trip (#2154) — the
// FK alone let any member point an item at another trip's bag.
if (bodyKeys.includes('bag_id') && data.bag_id != null && !(await this.bagInTrip(tripId, data.bag_id))) {
return { invalidBag: true } as const;
}
// A non-null bag about to be bound must belong to this trip (#2154) — the
// FK alone let any member point an item at another trip's bag.
if (bodyKeys.includes('bag_id') && data.bag_id != null && !(await this.bagInTrip(tripId, data.bag_id))) {
return { invalidBag: true } as const;
}
// Privatizing an unowned (legacy) item stamps the acting user as its owner so
// the visibility filter still has someone to match (#858).
const claimOwner = bodyKeys.includes('is_private') && !!data.is_private && item.owner_id == null && actingUserId != null;
// Privatizing an unowned (legacy) item stamps the acting user as its owner so
// the visibility filter still has someone to match (#858).
const claimOwner = bodyKeys.includes('is_private') && !!data.is_private && item.owner_id == null && actingUserId != null;
// The box and the packed count (#2296) are settled together, so a count
// that reaches the quantity ticks the item and a tick clears the count.
const quantity = bodyKeys.includes('quantity') ? Math.max(1, Math.min(999, Number(data.quantity) || 1)) : (item.quantity || 1);
const packed = resolvePackedState(
{ checked: item.checked ? 1 : 0, packed_quantity: item.packed_quantity ?? null },
{ bodyKeys, checked: data.checked, packed_quantity: data.packed_quantity, quantity },
);
// The box and the packed count (#2296) are settled together, so a count
// that reaches the quantity ticks the item and a tick clears the count.
const quantity = bodyKeys.includes('quantity') ? Math.max(1, Math.min(999, Number(data.quantity) || 1)) : (item.quantity || 1);
const packed = resolvePackedState(
{ checked: item.checked ? 1 : 0, packed_quantity: item.packed_quantity ?? null },
{ bodyKeys, checked: data.checked, packed_quantity: data.packed_quantity, quantity },
);
await this.itemsRepo.update(id, {
name: [!!data.name, data.name || null],
checked: [true, packed.checked],
packed_quantity: [true, packed.packed_quantity],
category: [!!data.category, data.category || null],
weight_grams: [bodyKeys.includes('weight_grams'), data.weight_grams ?? null],
bag_id: [bodyKeys.includes('bag_id'), data.bag_id ?? null],
quantity: [true, quantity],
is_private: [bodyKeys.includes('is_private'), data.is_private ? 1 : 0],
owner_id: [claimOwner, actingUserId ?? null],
await this.itemsRepo.update(id, {
name: [!!data.name, data.name || null],
checked: [true, packed.checked],
packed_quantity: [true, packed.packed_quantity],
category: [!!data.category, data.category || null],
weight_grams: [bodyKeys.includes('weight_grams'), data.weight_grams ?? null],
bag_id: [bodyKeys.includes('bag_id'), data.bag_id ?? null],
quantity: [true, quantity],
is_private: [bodyKeys.includes('is_private'), data.is_private ? 1 : 0],
owner_id: [claimOwner, actingUserId ?? null],
});
if (item.is_private === 0 && bodyKeys.includes('is_private') && data.is_private) {
await this.contributorsRepo.deleteForItem(id);
}
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
});
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
}
// ── Three-tier sharing (#858): recipients, contributors, clone ───────────────
@@ -376,12 +382,12 @@ export class PackingService {
visibility: PackingVisibility,
recipientIds: number[],
) {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
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 };
return this.uow.transactional(async () => {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
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 };
await this.uow.transactional(async () => {
// COALESCE(owner_id, ?) at the SQL level kept the existing owner if one was
// set; passing the claim only when the pre-image had none reproduces that
// exactly (nothing else touches owner_id inside this same transaction).
@@ -396,8 +402,8 @@ export class PackingService {
}
// Leaving the Common tier drops any co-contributors (they only apply to Common).
if (visibility !== 'common') await this.contributorsRepo.deleteForItem(id);
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
});
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
}
/**
@@ -407,26 +413,28 @@ export class PackingService {
* with no pre-ORM Express precedent — #858 landed post-migration).
*/
async addContributor(tripId: string | number, id: number, userId: number, actingUserId: number = userId) {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
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
// Putting someone else down as a bringer (#3098) only reaches people on the trip.
if (userId !== actingUserId && !(await this.tripRosterIds(tripId)).has(userId)) return null;
await this.contributorsRepo.insertIgnore(id, userId);
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
return this.uow.transactional(async () => {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
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
// Putting someone else down as a bringer (#3098) only reaches people on the trip.
if (userId !== actingUserId && !(await this.tripRosterIds(tripId)).has(userId)) return null;
await this.contributorsRepo.insertIgnore(id, userId);
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
});
}
/** `id: number` — same Plan 4 Task 8b (U6) narrowing as {@link addContributor}; `userId` here is the target being removed, not the acting viewer (`PackingController.removeContributor` now parses both `:id`/`:userId` via `toRowId` instead of a bare `Number.parseInt`). */
async removeContributor(tripId: string | number, id: number, userId: number, actingUserId: number = userId) {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// On a Common item the owner is its first bringer, so taking them off the
// item has to clear the owner too; otherwise their avatar stuck for good (#3098).
await this.uow.transactional(async () => {
return this.uow.transactional(async () => {
const item = await this.itemsRepo.findVisibleInTrip(id, tripId, actingUserId);
if (!item) return null;
// On a Common item the owner is its first bringer, so taking them off the
// item has to clear the owner too; otherwise their avatar stuck for good (#3098).
if (item.is_private === 0 && item.owner_id === userId) await this.itemsRepo.clearOwner(id);
await this.contributorsRepo.deleteOne(id, userId);
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
});
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
}
/** Replace the bringers of a Common item without changing who may see it. */
@@ -979,6 +979,39 @@ describe('Tool: set_packing_item_bringers', () => {
});
});
it('serializes competing replacements and removes bringers when the item becomes private', async () => {
const { user: owner } = await makeUser(orm);
const { user: first } = await makeUser(orm);
const { user: second } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id);
await addTripMember(orm, trip.id, first.id, owner.id);
await addTripMember(orm, trip.id, second.id, owner.id);
const item = await makePackingItem(orm, trip.id);
await withHarness(owner.id, async (h) => {
const replacements = await Promise.all([
setBringers(h, trip.id, item.id, [first.id]),
setBringers(h, trip.id, item.id, [second.id]),
]);
for (const result of replacements) expect(result.isError).not.toBe(true);
expect(parseToolResult(replacements[0])).toMatchObject({ item: { contributors: [{ user_id: first.id }] } });
expect(parseToolResult(replacements[1])).toMatchObject({ item: { contributors: [{ user_id: second.id }] } });
const restricted = await h.client.callTool({
name: 'update_packing_item',
arguments: { tripId: trip.id, itemId: item.id, is_private: true },
});
expect(parseToolResult(restricted)).toMatchObject({ item: { is_private: 1, contributors: [] } });
expect(broadcastMock).toHaveBeenLastCalledWith(
trip.id,
'packing:created',
expect.objectContaining({ item: expect.objectContaining({ is_private: 1 }) }),
undefined,
owner.id,
);
});
});
it('validates every bringer before changing the current selection', async () => {
const { user: owner } = await makeUser(orm);
const { user: outsider } = await makeUser(orm);
@@ -434,6 +434,19 @@ describe('PackingController (parity with the legacy /api/trips/:tripId/packing r
});
describe('sharing, contributors, clone (#858 three-tier)', () => {
it('sends a restricted contributor update only to the item viewers', async () => {
const item = { id: 9, is_private: 1, owner_id: 1, recipients: [{ user_id: 2 }] };
const removeContributor = vi.fn().mockResolvedValue(item);
const broadcast = vi.fn();
const broadcastToViewers = vi.fn();
const svc = makeService({ removeContributor, broadcast, broadcastToViewers });
expect(await new PackingController(svc).removeContributor(user, '5', '9', '1', 'sock')).toEqual({ item });
expect(broadcast).not.toHaveBeenCalled();
expect(broadcastToViewers).toHaveBeenCalledOnce();
expect(broadcastToViewers).toHaveBeenCalledWith('5', 'packing:updated', { item }, [1, 2], 'sock');
});
// The invalid-visibility 400 moved into the ZodValidationPipe
// (packingSetSharingRequestSchema requires the enum) — direct method calls
// bypass parameter pipes, so that path is covered by the e2e suite and the