feat(mcp): set bringers for a packing item

Let packing editors replace the bringers on a Common item in one write. Use the existing trip roster, item visibility and packing edit policy, and leave the sharing tier and recipients alone.

Closes #3313
This commit is contained in:
Maurice
2026-12-05 12:29:48 +01:00
parent f7c45a2d85
commit 06ee5a850b
6 changed files with 193 additions and 20 deletions
@@ -23,11 +23,8 @@ type PackingItemContributorsKyselyDB = Pick<DB, 'packing_item_contributors' | 'u
* `Migration20200101022900_three_tier_packing_sharing.ts:23-30`'s own
* `PRIMARY KEY (item_id, user_id)`), the only join table in this cluster
* shaped that way (every sibling uses a surrogate `id` PK + a `uniques`
* array instead). So it gets a normal, entity-backed repository, and its
* writes use the composite-key form of `em.upsert`/`nativeDelete` (the
* conflict/match target is the two-column PK, not a synthetic id) — the
* `ReservationDayPositionsRepository`/`ReservationDayPositions.entity.ts`
* precedent for a genuine composite-PK relation table.
* array instead). Both columns identify a contribution, including when a
* bulk write keeps an existing person's record.
*/
export class PackingItemContributorsRepository extends TrekRepository<PackingItemContributors> {
/**
@@ -52,20 +49,28 @@ export class PackingItemContributorsRepository extends TrekRepository<PackingIte
.execute();
}
/**
* PK20 (`addContributor`) — `INSERT OR IGNORE INTO
* packing_item_contributors (item_id, user_id, status) VALUES (?, ?,
* 'accepted')`. `em.upsert` with the composite-PK conflict target
* (`onConflictFields: ['item', 'user']`, the entity's real `PRIMARY KEY
* (item_id, user_id)` — R5/§16, NOT a synthetic-id workaround), named by
* entity property (the `AssignmentParticipantsRepository.insertIgnore`
* precedent).
*/
/** Keep an existing bringer's record when the same person is selected again. */
async insertIgnore(item_id: number, user_id: number): Promise<void> {
await this.upsert(
{ item: item_id, user: user_id, status: 'accepted' },
{ onConflictFields: ['item', 'user'], onConflictAction: 'ignore' },
);
await this.insertManyIgnore(item_id, [user_id]);
}
async insertManyIgnore(item_id: number, user_ids: number[]): Promise<void> {
if (user_ids.length === 0) return;
await this.kysely<PackingItemContributorsKyselyDB>()
.insertInto('packing_item_contributors')
.values(user_ids.map((user_id) => ({ item_id, user_id, status: 'accepted' })))
.onConflict((conflict) => conflict.columns(['item_id', 'user_id']).doNothing())
.execute();
}
/** Remove former bringers when an editor replaces the whole selection. */
async deleteExcept(item_id: number, user_ids: number[]): Promise<void> {
if (user_ids.length === 0) return this.deleteForItem(item_id);
await this.kysely<PackingItemContributorsKyselyDB>()
.deleteFrom('packing_item_contributors')
.where('item_id', '=', item_id)
.where('user_id', 'not in', user_ids)
.execute();
}
/** PK18 (`setItemSharing`'s leaving-Common cleanup) — `DELETE FROM packing_item_contributors WHERE item_id = ?`. */
@@ -183,6 +183,14 @@ export class PackingWritesService {
return item;
}
async setBringers(tripId: number, itemId: number, userIds: number[], writer: TripWriter) {
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'>);
return item;
}
/** The list's new order, for every other tab on both surfaces. */
async reorder(tripId: string | number, orderedIds: number[], writer: TripWriter) {
await this.gate(tripId, writer);
+26
View File
@@ -292,6 +292,32 @@ export class PackingMcp {
return ok({ item });
}
@Tool({
name: 'set_packing_item_bringers',
description:
'Set who brings a Common packing item. Replaces the full selection, including the original bringer if omitted. Pass an empty list to clear it. To find the current selection, read owner_id and contributors in list_packing_items. Does not change sharing or recipients.',
inputSchema: {
tripId: idSchema,
itemId: idSchema,
user_ids: z.array(idSchema).describe('User IDs of the trip members who bring this item'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async setPackingItemBringers(
{ tripId, itemId, user_ids }: { tripId: number; itemId: number; user_ids: number[] },
ctx: McpContext,
) {
const item = await this.writes.setBringers(
tripId,
itemId,
user_ids,
await this.guards.tripWriter(tripId, ctx.userId),
);
return ok({ item });
}
// --- PACKING ADVANCED ---
@Tool({
@@ -429,6 +429,27 @@ export class PackingService {
return (await this.enrichItems([await this.itemsRepo.findById(id)]))[0];
}
/** Replace the bringers of a Common item without changing who may see it. */
async setBringers(tripId: string | number, itemId: number, userIds: number[], actingUserId: number) {
return this.uow.transactional(async () => {
const item = await this.itemsRepo.findVisibleInTrip(itemId, tripId, actingUserId);
if (!item || item.is_private !== 0) return null;
const roster = await this.tripRosterIds(tripId);
if (userIds.some((id) => !roster.has(id))) {
throw new DomainError(400, 'Every bringer must be a trip member');
}
// The Common item's owner is its first bringer in the UI. When omitted,
// release them the same way as the single-person removal on REST.
const selected = new Set(userIds);
const contributors = [...selected].filter((id) => id !== item.owner_id);
if (item.owner_id != null && !selected.has(item.owner_id)) await this.itemsRepo.clearOwner(itemId);
await this.contributorsRepo.deleteExcept(itemId, contributors);
await this.contributorsRepo.insertManyIgnore(itemId, contributors);
return (await this.enrichItems([await this.itemsRepo.findById(itemId)]))[0];
});
}
/** True when the bag exists AND belongs to the trip — the referenced-id rule
* the FK cannot enforce (it only checks existence). */
private async bagInTrip(tripId: string | number, bagId: number): Promise<boolean> {
+114 -2
View File
@@ -14,6 +14,7 @@
import { ADDON_IDS } from '../../../src/addons';
import { PackingBags } from '../../../src/db/entities/PackingBags.entity';
import { PackingItems } from '../../../src/db/entities/PackingItems.entity';
import { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import { inContext } from '../../helpers/factories/context';
import {
addPackingBagMembers,
@@ -22,7 +23,7 @@ import {
makePackingItem,
} from '../../helpers/factories/packing';
import { countRows, findRow, insertRow, updateRows } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
import { setAddonEnabled, setAppSetting, setTripAddon } from '../../helpers/factories/settings';
import { addTripMember, makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { FakeRealtimeService } from '../../helpers/fake-realtime';
@@ -935,6 +936,116 @@ describe('Tool: list_packing_items', () => {
});
});
describe('Tool: set_packing_item_bringers', () => {
function setBringers(h: McpHarness, tripId: number, itemId: number, userIds: number[]) {
return h.client.callTool({
name: 'set_packing_item_bringers',
arguments: { tripId, itemId, user_ids: userIds },
});
}
it('replaces the full selection and keeps the Common item and its other fields', async () => {
const { user: owner } = await makeUser(orm);
const { user: member } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id);
await addTripMember(orm, trip.id, member.id, owner.id);
const item = await makePackingItem(orm, trip.id, { owner: owner.id, name: 'Tent', quantity: 2 });
await withHarness(member.id, async (h) => {
const both = parseToolResult(await setBringers(h, trip.id, item.id, [owner.id, member.id, member.id]));
expect(both).toMatchObject({
item: { owner_id: owner.id, contributors: [{ user_id: member.id }] },
});
expect(broadcastMock).toHaveBeenLastCalledWith(
trip.id,
'packing:updated',
expect.objectContaining({ item: expect.objectContaining({ id: item.id }) }),
);
const one = parseToolResult(await setBringers(h, trip.id, item.id, [member.id]));
expect(one).toMatchObject({
item: {
name: 'Tent',
quantity: 2,
is_private: 0,
owner_id: null,
contributors: [{ user_id: member.id }],
recipients: [],
},
});
const none = parseToolResult(await setBringers(h, trip.id, item.id, []));
expect(none).toMatchObject({ item: { owner_id: null, contributors: [] } });
});
});
it('validates every bringer before changing the current selection', async () => {
const { user: owner } = await makeUser(orm);
const { user: outsider } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id);
const item = await makePackingItem(orm, trip.id, { owner: owner.id });
await withHarness(owner.id, async (h) => {
const result = await setBringers(h, trip.id, item.id, [outsider.id]);
expect(result.isError).toBe(true);
expect(errorText(result)).toContain('Every bringer must be a trip member');
});
expect((await itemRow(item.id)).owner_id).toBe(owner.id);
expect(broadcastMock).not.toHaveBeenCalled();
});
it('refuses private items and items on a different trip', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
const other = await makeTrip(orm, user.id);
const personal = await makePackingItem(orm, trip.id, { is_private: 1, owner: user.id });
const outsideTrip = await makePackingItem(orm, other.id, { owner: user.id });
await withHarness(user.id, async (h) => {
expect((await setBringers(h, trip.id, personal.id, [])).isError).toBe(true);
expect((await setBringers(h, trip.id, outsideTrip.id, [])).isError).toBe(true);
});
expect(broadcastMock).not.toHaveBeenCalled();
});
it('requires the configured packing edit permission', async () => {
const { user: owner } = await makeUser(orm);
const { user: member } = await makeUser(orm);
const trip = await makeTrip(orm, owner.id);
await addTripMember(orm, trip.id, member.id, owner.id);
const item = await makePackingItem(orm, trip.id, { owner: owner.id });
const permissions = (await bootTestApp(realtime)).get(PermissionsService);
await setAppSetting(orm, 'perm_packing_edit', 'trip_owner');
await permissions.invalidatePermissionsCache();
try {
await withHarness(member.id, async (h) => {
const result = await setBringers(h, trip.id, item.id, [member.id]);
expect(result.isError).toBe(true);
expect(errorText(result)).toContain('You do not have permission');
});
expect(broadcastMock).not.toHaveBeenCalled();
} finally {
await setAppSetting(orm, 'perm_packing_edit', 'trip_member');
await permissions.invalidatePermissionsCache();
}
});
it('respects the target trip addon switch', async () => {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
const item = await makePackingItem(orm, trip.id, { owner: user.id });
await setTripAddon(orm, trip.id, ADDON_IDS.PACKING, false);
await withHarness(user.id, async (h) => {
const result = await setBringers(h, trip.id, item.id, []);
expect(result.isError).toBe(true);
expect(errorText(result)).toMatch(/Packing addon is not enabled/i);
});
expect(broadcastMock).not.toHaveBeenCalled();
});
});
// ---------------------------------------------------------------------------
// Scope gating (packing read/write, registration-time)
// ---------------------------------------------------------------------------
@@ -962,6 +1073,7 @@ describe('Packing tools — scope gating', () => {
'delete_packing_template',
'bulk_import_packing',
'set_packing_item_sharing',
'set_packing_item_bringers',
];
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
@@ -973,7 +1085,7 @@ describe('Packing tools — scope gating', () => {
}
}
it('registers all nineteen tools with null scopes (full access)', async () => {
it('registers all packing tools with null scopes (full access)', async () => {
const { user } = await makeUser(orm);
const names = await listToolNames(user.id, null);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool);
+1
View File
@@ -16,6 +16,7 @@ Requires `packing:read` or `packing:write` scope. The Packing addon is listed as
| `create_packing_item` | Add an item to the packing checklist with optional category. |
| `update_packing_item` | Rename an item, change its category, or count how many of it are already packed. |
| `set_packing_item_sharing` | Move an item between the three sharing tiers: `common` puts it in the pool the whole trip packs from, `personal` keeps it to its owner, `shared` covers the trip members in `recipient_ids`. Only the item's owner may change this. |
| `set_packing_item_bringers` | Replace who brings a Common packing item with `user_ids`, including the original bringer in that list if they should stay. An empty list clears all bringers. Read the item's `owner_id` and `contributors` with `list_packing_items` for its current bringers. Sharing and recipients stay as they are. |
| `toggle_packing_item` | Check or uncheck a packing item. |
| `delete_packing_item` | Remove a packing item. |
| `reorder_packing_items` | Set the display order of packing items within a trip. |