fix(packing): accept weight, bag and quantity on create across REST, MCP and plugin RPC (#2154)

This commit is contained in:
Maurice
2026-09-01 14:41:45 +02:00
committed by Maurice
parent a0c089baa4
commit d5a3427cbb
12 changed files with 353 additions and 13 deletions
+12 -3
View File
@@ -13,7 +13,7 @@ import {
} from '@nestjs/common';
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import type { User } from '../../types';
import { PackingService } from './packing.service';
import { PackingService, isInvalidBagRef } from './packing.service';
import { isUpdateConflict } from '../common/conflictResult';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -97,7 +97,12 @@ export class PackingController {
@Headers('x-socket-id') socketId?: string,
) {
// checked arrives as boolean or legacy 0/1 — the service coerces by truthiness.
const item = this.packing.createItem(tripId, { name: body.name, category: body.category, checked: body.checked === undefined ? undefined : !!body.checked, is_private: body.is_private, visibility: body.visibility, recipient_ids: body.recipient_ids }, user.id);
const item = this.packing.createItem(tripId, { name: body.name, category: body.category, checked: body.checked === undefined ? undefined : !!body.checked, weight_grams: body.weight_grams, bag_id: body.bag_id, quantity: body.quantity, is_private: body.is_private, visibility: body.visibility, recipient_ids: body.recipient_ids }, user.id);
// A bag referenced in the body must exist on this trip (#2154). The payload
// is at fault, so 400 — the 404 'Bag not found' stays with the path routes.
if (isInvalidBagRef(item)) {
throw new HttpException({ error: 'Bag not found' }, 400);
}
this.packing.emitToViewers(tripId, 'packing:created', { item }, item, socketId);
return { item };
}
@@ -139,6 +144,10 @@ export class PackingController {
if (isUpdateConflict(updated)) {
throw new HttpException({ error: 'conflict', server: updated.server }, 409);
}
// A bag referenced in the body must exist on this trip (#2154) — see create.
if (isInvalidBagRef(updated)) {
throw new HttpException({ error: 'Bag not found' }, 400);
}
this.packing.broadcastUpdate(tripId, id, updated as PackingItemRow, !!before?.is_private, socketId);
return { item: updated };
}
@@ -254,7 +263,7 @@ export class PackingController {
if (!body.name.trim()) {
throw new HttpException({ error: 'Name is required' }, 400);
}
const bag = this.packing.createBag(tripId, { name: body.name, color: body.color });
const bag = this.packing.createBag(tripId, { name: body.name, color: body.color, weight_limit_grams: body.weight_limit_grams });
this.packing.broadcast(tripId, 'packing:bag-created', { bag }, socketId);
return { bag };
}
+16 -4
View File
@@ -9,8 +9,9 @@ import { z } from 'zod';
import { AuthService } from '../auth/auth.service';
import { ADDON_IDS } from '../../addons';
import { noAccess, permissionDenied, adminRequired } from '../../mcp/tools/_shared';
import { PackingService } from './packing.service';
import { PackingService, isInvalidBagRef } from './packing.service';
import {
packingCreateBagRequestSchema,
packingCreateItemRequestSchema,
packingSetSharingRequestSchema,
packingUpdateBagRequestSchema,
@@ -62,6 +63,9 @@ export class PackingMcp {
tripId: z.number().int().positive(),
name: z.string().min(1).max(200),
category: z.string().max(100).optional().describe('Packing category (e.g. Clothes, Electronics)'),
bag_id: packingCreateItemRequestSchema.shape.bag_id.describe('Bag to pack the item into (ids come from list_packing_bags)'),
quantity: packingCreateItemRequestSchema.shape.quantity.describe('How many to pack, clamped to 1-999'),
weight_grams: packingCreateItemRequestSchema.shape.weight_grams.describe('Weight in grams, which feeds the bag fill bar'),
checked: packingCreateItemRequestSchema.shape.checked.describe('Create the item already ticked off'),
is_private: packingCreateItemRequestSchema.shape.is_private.describe('Keep the item to yourself; visibility says the same thing with more nuance'),
visibility: packingCreateItemRequestSchema.shape.visibility.describe("Which list the item belongs to: 'common' (the group pool, the default), 'personal' (yours alone), or 'shared' (yours plus recipient_ids)"),
@@ -72,7 +76,7 @@ export class PackingMcp {
access: { group: 'packing', mode: 'write' },
})
async createPackingItem(
{ tripId, name, category, checked, is_private, visibility, recipient_ids }: { tripId: number; name: string; category?: string; checked?: boolean | number; is_private?: boolean; visibility?: PackingVisibility; recipient_ids?: number[] },
{ tripId, name, category, bag_id, quantity, weight_grams, checked, is_private, visibility, recipient_ids }: { tripId: number; name: string; category?: string; bag_id?: number | null; quantity?: number; weight_grams?: number | null; checked?: boolean | number; is_private?: boolean; visibility?: PackingVisibility; recipient_ids?: number[] },
ctx: McpContext,
) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
@@ -81,12 +85,17 @@ export class PackingMcp {
const item = this.packing.createItem(tripId, {
name,
category: category || 'General',
bag_id,
quantity,
weight_grams,
// checked takes a boolean or the legacy 0/1, exactly as the REST body does.
checked: checked === undefined ? undefined : !!checked,
is_private,
visibility,
recipient_ids,
}, ctx.userId);
// A referenced bag must exist on this trip (#2154), as on the REST route.
if (isInvalidBagRef(item)) return errorResult('Bag not found.');
// A restricted item (#858) reaches its owner and recipients only; a Common
// one answers null here and goes to the whole room.
this.guards.safeBroadcast(tripId, 'packing:created', { item }, this.packing.viewersOf(item));
@@ -176,6 +185,8 @@ export class PackingMcp {
const wasPrivate = !!this.packing.getItemPrivacy(tripId, itemId)?.is_private;
const item = this.packing.updateItem(tripId, itemId, fields, bodyKeys, undefined, ctx.userId);
if (!item) return errorResult('Packing item not found.');
// A referenced bag must exist on this trip (#2154), as on the REST route.
if (isInvalidBagRef(item)) return errorResult('Bag not found.');
this.broadcastItemUpdate(tripId, itemId, item, wasPrivate);
return ok({ item });
}
@@ -274,18 +285,19 @@ export class PackingMcp {
tripId: z.number().int().positive(),
name: z.string().min(1).max(100),
color: z.string().optional(),
weight_limit_grams: packingCreateBagRequestSchema.shape.weight_limit_grams.describe('Allowance in grams the bag is measured against (the fill bar)'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async createPackingBag({ tripId, name, color }: { tripId: number; name: string; color?: string }, ctx: McpContext) {
async createPackingBag({ tripId, name, color, weight_limit_grams }: { tripId: number; name: string; color?: string; weight_limit_grams?: number | null }, ctx: McpContext) {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
// createBag returns a bare row; hydrate with the empty members array that
// listBags and the schema always carry, so the client/AI consumer matches.
const bag = { ...(this.packing.createBag(tripId, { name, color }) as object), members: [] };
const bag = { ...(this.packing.createBag(tripId, { name, color, weight_limit_grams }) as object), members: [] };
this.guards.safeBroadcast(tripId, 'packing:bag-created', { bag });
return ok({ bag });
}
+10 -2
View File
@@ -5,7 +5,7 @@ import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
import { asPayload, num, schemaMessage } from '../plugins/host/rpc-params';
import type { PluginRpcContext } from '../plugins/host/rpc-kit/types';
import { RealtimeService } from '../realtime/realtime.service';
import { PackingService } from './packing.service';
import { PackingService, isInvalidBagRef } from './packing.service';
import { isUpdateConflict } from '../common/conflictResult';
/** Packing rides on the app's own 'packing_edit' permission, exactly like the REST path. */
@@ -48,6 +48,8 @@ export class PackingRpc {
if (!parsed.success) throw new BadParams(`invalid packing item: ${schemaMessage(parsed.error)}`);
this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);
const item = this.packing.createItem(String(tripId), parsed.data as never, actor) as PrivacyItem;
// A referenced bag must exist on this trip (#2154), as on the REST route.
if (isInvalidBagRef(item)) throw new BadParams(`no packing bag ${parsed.data.bag_id} on trip ${tripId}`);
this.packing.emitToViewers(String(tripId), 'packing:created', { item }, item, undefined);
return item;
}
@@ -66,6 +68,8 @@ export class PackingRpc {
const updated = this.packing.updateItem(String(tripId), String(itemId), input as never, Object.keys(input), undefined, actor);
if (!updated) throw new ForbiddenResource(`no packing item ${itemId} on trip ${tripId}`);
if (isUpdateConflict(updated)) throw new BadParams('packing item was modified concurrently');
// A referenced bag must exist on this trip (#2154), as on the REST route.
if (isInvalidBagRef(updated)) throw new BadParams(`no packing bag ${parsed.data.bag_id} on trip ${tripId}`);
this.packing.broadcastUpdate(String(tripId), itemId, updated as PrivacyItem, !!before?.is_private, undefined);
return updated;
}
@@ -96,7 +100,11 @@ export class PackingRpc {
const input = asPayload(params.input);
if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('bag name is required');
this.guards.requireTripEdit(tripId, actor, PACKING_EDIT_ACTION);
const bag = this.packing.createBag(String(tripId), { name: input.name, color: typeof input.color === 'string' ? input.color : undefined });
const bag = this.packing.createBag(String(tripId), {
name: input.name,
color: typeof input.color === 'string' ? input.color : undefined,
weight_limit_grams: typeof input.weight_limit_grams === 'number' ? input.weight_limit_grams : undefined,
});
this.realtime.broadcast(tripId, 'packing:bag-created', { bag }, undefined);
return bag;
}
+31 -3
View File
@@ -11,6 +11,21 @@ import { NotificationsService } from '../notifications/notifications.service';
/** Privacy fields stamped on a packing item (#858). */
type PrivacyFields = { is_private?: number; owner_id?: number | null };
/**
* Rejection sentinel for a body-referenced bag that does not exist on the trip
* (#2154). The packing_bags FK only guarantees the id exists somewhere: a
* cross-trip bag_id used to be accepted silently and a dead one surfaced as an
* SQLite FK error. Returned by createItem/updateItem so REST, MCP and the
* plugin RPC all map it to their surface's 400/BadParams.
*/
export interface InvalidBagRef {
invalidBag: true;
}
export function isInvalidBagRef(result: unknown): result is InvalidBagRef {
return !!result && typeof result === 'object' && (result as { invalidBag?: unknown }).invalidBag === true;
}
type Trip = TripAccess;
export type PackingVisibility = 'common' | 'personal' | 'shared';
@@ -217,6 +232,7 @@ export class PackingService {
data: { name: string; category?: string; checked?: boolean; quantity?: number; weight_grams?: number | null; bag_id?: number | null; is_private?: boolean; visibility?: PackingVisibility; recipient_ids?: number[] },
ownerId?: number,
) {
if (data.bag_id != null && !this.bagInTrip(tripId, data.bag_id)) return { invalidBag: true } as const;
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?', tripId)!;
const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const qty = Math.max(1, Math.min(999, Number(data.quantity) || 1));
@@ -259,6 +275,12 @@ export class PackingService {
return { conflict: true, server: this.db.get('SELECT * FROM packing_items WHERE id = ?', 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 && !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;
@@ -376,6 +398,12 @@ export class PackingService {
return this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)])[0];
}
/** True when the bag exists AND belongs to the trip — the referenced-id rule
* the FK cannot enforce (it only checks existence). */
private bagInTrip(tripId: string | number, bagId: number): boolean {
return !!this.db.get('SELECT id FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
}
/**
* A copy keeps the original's bag only when that bag is the caller's to pack: one nobody
* owns, or one they belong to. Inheriting someone else's bag would drop the copy into
@@ -509,10 +537,10 @@ export class PackingService {
return rows.map(m => ({ ...m, avatar: avatarUrl(m) }));
}
createBag(tripId: string | number, data: { name: string; color?: string }) {
createBag(tripId: string | number, data: { name: string; color?: string; weight_limit_grams?: number | null }) {
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_bags WHERE trip_id = ?', tripId)!;
const result = this.db.run('INSERT INTO packing_bags (trip_id, name, color, sort_order) VALUES (?, ?, ?, ?)',
tripId, data.name.trim(), data.color || '#6366f1', (maxOrder.max ?? -1) + 1
const result = this.db.run('INSERT INTO packing_bags (trip_id, name, color, sort_order, weight_limit_grams) VALUES (?, ?, ?, ?, ?)',
tripId, data.name.trim(), data.color || '#6366f1', (maxOrder.max ?? -1) + 1, data.weight_limit_grams ?? null
);
return this.db.get('SELECT * FROM packing_bags WHERE id = ?', result.lastInsertRowid);
}