chore: move packing backend to proper DI

This commit is contained in:
jubnl
2026-07-26 16:55:20 +02:00
parent 67b3005d36
commit f1960dc364
28 changed files with 2175 additions and 1815 deletions
+4 -26
View File
@@ -4,7 +4,6 @@ import { listTrips, getTrip, getTripOwner, listMembers } from '../services/tripS
import { listDays, listAccommodations } from '../services/dayService';
import { listPlaces } from '../services/placeService';
import { listBudgetItems, getPerPersonSummary, calculateSettlement } from '../services/budgetService';
import { listItems as listPackingItems, listBags } from '../services/packingService';
import { listReservations } from '../services/reservationService';
import { listNotes as listDayNotes } from '../services/dayNoteService';
import { listNotes as listCollabNotes, listPolls, listMessages } from '../services/collabService';
@@ -117,19 +116,8 @@ export function registerResources(server: McpServer, userId: number, scopes: str
}
);
// Packing checklist
if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'packing')) server.registerResource(
'trip-packing',
new ResourceTemplate('trek://trips/{tripId}/packing', { list: undefined }),
{ description: 'Packing checklist for a trip', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
// Hide other members' private items (#858) from the requesting user.
const items = listPackingItems(id, userId);
return jsonContent(uri.href, items);
}
);
// The trip-packing resource moved to the DI-discovered
// src/nest/packing/packing.mcp.ts (@ResourceTemplate).
// Reservations (flights, hotels, restaurants)
if (canRead(scopes, 'reservations')) server.registerResource(
@@ -256,18 +244,8 @@ export function registerResources(server: McpServer, userId: number, scopes: str
}
);
// Packing bags
if (isAddonEnabled(ADDON_IDS.PACKING) && canRead(scopes, 'packing')) server.registerResource(
'trip-packing-bags',
new ResourceTemplate('trek://trips/{tripId}/packing/bags', { list: undefined }),
{ description: 'All packing bags for a trip with their members', mimeType: 'application/json' },
async (uri, { tripId }) => {
const id = parseId(tripId);
if (id === null || !canAccessTrip(id, userId)) return accessDenied(uri.href);
const bags = listBags(id);
return jsonContent(uri.href, bags);
}
);
// The trip-packing-bags resource moved to the DI-discovered
// src/nest/packing/packing.mcp.ts (@ResourceTemplate).
// In-app notifications
if (canRead(scopes, 'notifications')) server.registerResource(
+2 -2
View File
@@ -9,7 +9,6 @@ import { registerPlaceTools } from './tools/places';
import { registerCollectionTools } from './tools/collections';
import { registerDayTools } from './tools/days';
import { registerBudgetTools } from './tools/budget';
import { registerPackingTools } from './tools/packing';
import { registerCollabTools } from './tools/collab';
import { registerTripTools } from './tools/trips';
import { registerTransportTools } from './tools/transports';
@@ -27,7 +26,8 @@ export function registerTools(server: McpServer, userId: number, scopes: string[
registerBudgetTools(server, userId, scopes);
registerPackingTools(server, userId, scopes);
// The packing tools moved to the DI-discovered src/nest/packing/packing.mcp.ts
// (@McpController, attached via the nest-mcp registry below).
registerReservationTools(server, userId, scopes);
-394
View File
@@ -1,394 +0,0 @@
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { isDemoUser } from '../../services/authService';
import {
createItem as createPackingItem, updateItem as updatePackingItem,
deleteItem as deletePackingItem,
reorderItems as reorderPackingItems,
listBags, createBag, updateBag, deleteBag, setBagMembers,
getCategoryAssignees as getPackingCategoryAssignees,
updateCategoryAssignees as updatePackingCategoryAssignees,
applyTemplate, saveAsTemplate, listTemplates, bulkImport,
} from '../../services/packingService';
import {
safeBroadcast, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, noAccess, ok, hasTripPermission, permissionDenied,
isAdminUser, adminRequired,
} from './_shared';
import { canRead, canWrite } from '../scopes';
import { isAddonEnabled, deletePackingTemplate } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
export function registerPackingTools(server: McpServer, userId: number, scopes: string[] | null): void {
const R = canRead(scopes, 'packing');
const W = canWrite(scopes, 'packing');
if (!isAddonEnabled(ADDON_IDS.PACKING)) return;
// --- PACKING ---
if (W) server.registerTool(
'create_packing_item',
{
description: 'Add an item to the packing checklist for a trip.',
inputSchema: {
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)'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, category }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const item = createPackingItem(tripId, { name, category: category || 'General' }, userId);
safeBroadcast(tripId, 'packing:created', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'toggle_packing_item',
{
description: 'Check or uncheck a packing item.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
checked: z.boolean(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, checked }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const item = updatePackingItem(tripId, itemId, { checked: checked ? 1 : 0 }, ['checked']);
if (!item) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
safeBroadcast(tripId, 'packing:updated', { item });
return ok({ item });
}
);
if (W) server.registerTool(
'delete_packing_item',
{
description: 'Remove an item from the packing checklist.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, itemId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const deleted = deletePackingItem(tripId, itemId);
if (!deleted) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
safeBroadcast(tripId, 'packing:deleted', { itemId });
return ok({ success: true });
}
);
// --- PACKING (update) ---
if (W) server.registerTool(
'update_packing_item',
{
description: 'Rename a packing item or change its category.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
name: z.string().min(1).max(200).optional(),
category: z.string().max(100).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, itemId, name, category }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const bodyKeys = ['name', 'category'].filter(k => k === 'name' ? name !== undefined : category !== undefined);
const item = updatePackingItem(tripId, itemId, { name, category }, bodyKeys);
if (!item) return { content: [{ type: 'text' as const, text: 'Packing item not found.' }], isError: true };
safeBroadcast(tripId, 'packing:updated', { item });
return ok({ item });
}
);
// --- PACKING ADVANCED ---
if (W) server.registerTool(
'reorder_packing_items',
{
description: 'Set the display order of packing items within a trip.',
inputSchema: {
tripId: z.number().int().positive(),
orderedIds: z.array(z.number().int().positive()).describe('Packing item IDs in desired order'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, orderedIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
reorderPackingItems(tripId, orderedIds);
safeBroadcast(tripId, 'packing:reordered', { orderedIds });
return ok({ success: true });
}
);
if (R) server.registerTool(
'list_packing_bags',
{
description: 'List all packing bags for a trip.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const bags = listBags(tripId);
return ok({ bags });
}
);
if (W) server.registerTool(
'create_packing_bag',
{
description: 'Create a new packing bag (e.g. "Carry-on", "Checked bag").',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(100),
color: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, name, color }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, 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 = { ...(createBag(tripId, { name, color }) as object), members: [] };
safeBroadcast(tripId, 'packing:bag-created', { bag });
return ok({ bag });
}
);
if (W) server.registerTool(
'update_packing_bag',
{
description: 'Rename or recolor a packing bag.',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
name: z.string().optional(),
color: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, bagId, name, color }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const fields: Record<string, unknown> = {};
const bodyKeys: string[] = [];
if (name !== undefined) { fields.name = name; bodyKeys.push('name'); }
if (color !== undefined) { fields.color = color; bodyKeys.push('color'); }
const updated = updateBag(tripId, bagId, fields, bodyKeys);
if (!updated) return { content: [{ type: 'text' as const, text: 'Bag not found.' }], isError: true };
// Hydrate with the members array (matches create_packing_bag, listBags, and the schema).
const bag = listBags(tripId).find(b => b.id === (updated as { id: number }).id) ?? { ...(updated as object), members: [] };
safeBroadcast(tripId, 'packing:bag-updated', { bag });
return ok({ bag });
}
);
if (W) server.registerTool(
'delete_packing_bag',
{
description: 'Delete a packing bag (items in the bag are unassigned, not deleted).',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ tripId, bagId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
deleteBag(tripId, bagId);
safeBroadcast(tripId, 'packing:bag-deleted', { id: bagId });
return ok({ success: true });
}
);
if (W) server.registerTool(
'set_bag_members',
{
description: 'Assign trip members to a packing bag (determines who packs what bag).',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
userIds: z.array(z.number().int().positive()),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, bagId, userIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const members = setBagMembers(tripId, bagId, userIds);
if (!members) return { content: [{ type: 'text' as const, text: 'Bag not found.' }], isError: true };
safeBroadcast(tripId, 'packing:bag-members-updated', { bagId, members });
return ok({ members });
}
);
if (R) server.registerTool(
'get_packing_category_assignees',
{
description: 'Get which trip members are assigned to each packing category.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
const assignees = getPackingCategoryAssignees(tripId);
return ok({ assignees });
}
);
if (W) server.registerTool(
'set_packing_category_assignees',
{
description: 'Assign trip members to a packing category.',
inputSchema: {
tripId: z.number().int().positive(),
categoryName: z.string().min(1).max(100),
userIds: z.array(z.number().int().positive()),
},
annotations: TOOL_ANNOTATIONS_WRITE,
},
async ({ tripId, categoryName, userIds }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const assignees = updatePackingCategoryAssignees(tripId, categoryName, userIds);
safeBroadcast(tripId, 'packing:assignees', { category: categoryName, assignees });
return ok({ assignees });
}
);
if (W) server.registerTool(
'apply_packing_template',
{
description: 'Apply a packing template to a trip (adds items from the template).',
inputSchema: {
tripId: z.number().int().positive(),
templateId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, templateId }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const items = applyTemplate(tripId, templateId);
if (items === null) return { content: [{ type: 'text' as const, text: 'Template not found.' }], isError: true };
safeBroadcast(tripId, 'packing:template-applied', { items });
return ok({ items, count: items.length });
}
);
if (R) server.registerTool(
'list_packing_templates',
{
description: 'List the reusable packing templates (id, name, item count) so one can be applied with apply_packing_template.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
},
async ({ tripId }) => {
if (!canAccessTrip(tripId, userId)) return noAccess();
return ok({ templates: listTemplates() });
}
);
if (W) server.registerTool(
'save_packing_template',
{
description: 'Save the current packing list as a reusable template. Returns the new template (id, name, category/item counts). Admin only.',
inputSchema: {
tripId: z.number().int().positive(),
templateName: z.string().min(1).max(100),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, templateName }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
// Templates are global; the REST route restricts saving to admins. Match it.
if (!isAdminUser(userId)) return adminRequired();
const template = saveAsTemplate(tripId, userId, templateName);
if (!template) return { content: [{ type: 'text' as const, text: 'Nothing to save — the packing list is empty.' }], isError: true };
return ok({ template });
}
);
if (W) server.registerTool(
'delete_packing_template',
{
description: 'Delete a reusable packing template. Templates are global, so deletion is admin only.',
inputSchema: {
templateId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
},
async ({ templateId }) => {
if (isDemoUser(userId)) return demoDenied();
// Templates are global; the REST route restricts management to admins. Match it.
if (!isAdminUser(userId)) return adminRequired();
const result = deletePackingTemplate(String(templateId));
if ('error' in result) return { content: [{ type: 'text' as const, text: result.error }], isError: true };
return ok({ success: true, name: result.name });
}
);
if (W) server.registerTool(
'bulk_import_packing',
{
description: 'Import multiple packing items at once from a list. Optionally assign each to a bag (by name — created if missing), set its weight, or pre-check it.',
inputSchema: {
tripId: z.number().int().positive(),
items: z.array(z.object({
name: z.string().min(1).max(200),
category: z.string().optional(),
quantity: z.number().int().positive().optional(),
bag: z.string().max(100).optional().describe('Bag name to assign the item to; created if it does not exist'),
weight_grams: z.number().nonnegative().optional(),
checked: z.boolean().optional(),
})).min(1),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
},
async ({ tripId, items }) => {
if (isDemoUser(userId)) return demoDenied();
if (!canAccessTrip(tripId, userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, userId)) return permissionDenied();
const created = bulkImport(tripId, items, userId);
for (const item of created) safeBroadcast(tripId, 'packing:created', { item });
return ok({ items: created, count: created.length });
}
);
}
+1 -1
View File
@@ -2,7 +2,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
import { z } from 'zod';
import { canAccessTrip } from '../../db/database';
import { getTripSummary } from '../../services/tripService';
import { listItems as listPackingItems } from '../../services/packingService';
import { listItems as listPackingItems } from '../../nest/packing/packing.bridge';
import { isAddonEnabled } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
+6 -3
View File
@@ -27,7 +27,7 @@ mount to Nest and leaves the sibling trip routes (days, places, ...) on Express.
categories, tags, notifications, atlas.
- **Phase 2 (trip sub-domains):** vacay (addon), packing, todo.
- **DI-native services (legacy `src/services/*` deleted):** tags, categories,
todo — see the migration recipe below.
todo, packing — see the migration recipe below.
## Cross-cutting Foundation pieces
@@ -98,8 +98,11 @@ Pilot: **tags** (`services/tagService.ts` → `nest/tags/tags.service.ts` +
first `@Resource` in `categories.mcp.ts`); todo followed too (and piloted the
first `@ResourceTemplate` plus the `when` addon gate in `todo.mcp.ts`, and the
first in-container consumer wiring: `TripsService` injects `TodoService` via
`exports: [TodoService]` instead of using the bridge). Repeat these steps per
service (next up: packingService). This is a **pure relocation** — byte-identical
`exports: [TodoService]` instead of using the bridge); packing followed (the
largest port so far: a 17-tool + 2-resource `packing.mcp.ts` with inline admin
gates, and the first `PluginHostDepsFactory` swap done as part of a service
migration — no bridge entry for the plugin host). Repeat these steps per
service (next up: dayNoteService). This is a **pure relocation** — byte-identical
SQL, statuses, bodies, and error strings. The plugin RPC host is **no longer a
bridge consumer**: since Option A of `src/nest/plugins/DI-MIGRATION.md` it
injects domain services via `PluginHostDepsFactory`, so a migrated domain adds
+23
View File
@@ -0,0 +1,23 @@
import { db } from '../../db/database';
import { DatabaseService } from '../database/database.service';
import { PackingService } from './packing.service';
/**
* Non-Nest entry point for the packing domain — for code running OUTSIDE the
* Nest container (the legacy packing-list prompt registrar in
* src/mcp/tools/prompts.ts and the trip-summary packing counts in
* services/tripService.ts; the packing MCP tools and resources moved to the
* DI-discovered packing.mcp.ts, and the plugin RPC host injects PackingService
* via PluginHostDepsFactory). Exports only the legacy services/packingService
* names still consumed outside the container, 1:1, so repointing a consumer is
* an import-path-only diff. Inside the container, inject PackingService
* instead. Delete this file when those legacy consumers migrate.
*
* Module-level construction is safe: `db` is the reinitialize-proof Proxy onto
* the shared better-sqlite3 singleton.
*/
const packing = new PackingService(new DatabaseService(db));
export function listItems(tripId: string | number, userId?: number) {
return packing.listItems(tripId, userId);
}
+463
View File
@@ -0,0 +1,463 @@
import {
McpController, Tool, ResourceTemplate, type McpContext,
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE,
TOOL_ANNOTATIONS_DELETE, TOOL_ANNOTATIONS_NON_IDEMPOTENT,
demoDenied, errorResult, ok,
} from '@trek/nest-mcp';
import { z } from 'zod';
import { isDemoUser } from '../../services/authService';
import { isAddonEnabled, deletePackingTemplate } from '../../services/adminService';
import { ADDON_IDS } from '../../addons';
import { safeBroadcast, noAccess, hasTripPermission, permissionDenied, isAdminUser, adminRequired } from '../../mcp/tools/_shared';
import { PackingService } from './packing.service';
/** Legacy registrar gate: the whole packing surface rides the packing addon. */
const packingAddonOn = () => isAddonEnabled(ADDON_IDS.PACKING);
function parseId(value: string | string[]): number | null {
const n = Number(Array.isArray(value) ? value[0] : value);
return Number.isInteger(n) && n > 0 ? n : null;
}
/**
* Packing MCP surface — ported 1:1 from the legacy registrars: the seventeen
* tools from src/mcp/tools/packing.ts and the trek://trips/{tripId}/packing +
* trek://trips/{tripId}/packing/bags resources from src/mcp/resources.ts
* (identical names, descriptions, schemas, annotations, error/payload shapes
* and broadcasts). The registration-time gates map to `when` (the
* whole-registrar packing-addon early return) plus the declarative packing
* read/write access markers (the legacy `if (R)` / `if (W)` checks, resolved
* by trekMcpAccessPolicy). The two template-management tools keep their inline
* admin gate (isAdminUser), matching the REST routes.
*/
@McpController()
export class PackingMcp {
constructor(private readonly packing: PackingService) {}
// --- PACKING ---
@Tool({
name: 'create_packing_item',
description: 'Add an item to the packing checklist for a trip.',
inputSchema: {
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)'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async createPackingItem({ tripId, name, category }: { tripId: number; name: string; category?: string }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const item = this.packing.createItem(tripId, { name, category: category || 'General' }, ctx.userId);
safeBroadcast(tripId, 'packing:created', { item });
return ok({ item });
}
@Tool({
name: 'toggle_packing_item',
description: 'Check or uncheck a packing item.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
checked: z.boolean(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async togglePackingItem({ tripId, itemId, checked }: { tripId: number; itemId: number; checked: boolean }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const item = this.packing.updateItem(tripId, itemId, { checked: checked ? 1 : 0 }, ['checked']);
if (!item) return errorResult('Packing item not found.');
safeBroadcast(tripId, 'packing:updated', { item });
return ok({ item });
}
@Tool({
name: 'delete_packing_item',
description: 'Remove an item from the packing checklist.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async deletePackingItem({ tripId, itemId }: { tripId: number; itemId: number }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const deleted = this.packing.deleteItem(tripId, itemId);
if (!deleted) return errorResult('Packing item not found.');
safeBroadcast(tripId, 'packing:deleted', { itemId });
return ok({ success: true });
}
// --- PACKING (update) ---
@Tool({
name: 'update_packing_item',
description: 'Rename a packing item or change its category.',
inputSchema: {
tripId: z.number().int().positive(),
itemId: z.number().int().positive(),
name: z.string().min(1).max(200).optional(),
category: z.string().max(100).optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async updatePackingItem({ tripId, itemId, name, category }: { tripId: number; itemId: number; name?: string; category?: string }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const bodyKeys = ['name', 'category'].filter(k => k === 'name' ? name !== undefined : category !== undefined);
const item = this.packing.updateItem(tripId, itemId, { name, category }, bodyKeys);
if (!item) return errorResult('Packing item not found.');
safeBroadcast(tripId, 'packing:updated', { item });
return ok({ item });
}
// --- PACKING ADVANCED ---
@Tool({
name: 'reorder_packing_items',
description: 'Set the display order of packing items within a trip.',
inputSchema: {
tripId: z.number().int().positive(),
orderedIds: z.array(z.number().int().positive()).describe('Packing item IDs in desired order'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async reorderPackingItems({ tripId, orderedIds }: { tripId: number; orderedIds: number[] }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
this.packing.reorderItems(tripId, orderedIds);
safeBroadcast(tripId, 'packing:reordered', { orderedIds });
return ok({ success: true });
}
@Tool({
name: 'list_packing_bags',
description: 'List all packing bags for a trip.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
when: packingAddonOn,
access: { group: 'packing', mode: 'read' },
})
async listPackingBags({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
const bags = this.packing.listBags(tripId);
return ok({ bags });
}
@Tool({
name: 'create_packing_bag',
description: 'Create a new packing bag (e.g. "Carry-on", "Checked bag").',
inputSchema: {
tripId: z.number().int().positive(),
name: z.string().min(1).max(100),
color: z.string().optional(),
},
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) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!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: [] };
safeBroadcast(tripId, 'packing:bag-created', { bag });
return ok({ bag });
}
@Tool({
name: 'update_packing_bag',
description: 'Rename or recolor a packing bag.',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
name: z.string().optional(),
color: z.string().optional(),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async updatePackingBag({ tripId, bagId, name, color }: { tripId: number; bagId: number; name?: string; color?: string }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const fields: Record<string, unknown> = {};
const bodyKeys: string[] = [];
if (name !== undefined) { fields.name = name; bodyKeys.push('name'); }
if (color !== undefined) { fields.color = color; bodyKeys.push('color'); }
const updated = this.packing.updateBag(tripId, bagId, fields, bodyKeys);
if (!updated) return errorResult('Bag not found.');
// Hydrate with the members array (matches create_packing_bag, listBags, and the schema).
const bag = this.packing.listBags(tripId).find(b => b.id === (updated as { id: number }).id) ?? { ...(updated as object), members: [] };
safeBroadcast(tripId, 'packing:bag-updated', { bag });
return ok({ bag });
}
@Tool({
name: 'delete_packing_bag',
description: 'Delete a packing bag (items in the bag are unassigned, not deleted).',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async deletePackingBag({ tripId, bagId }: { tripId: number; bagId: number }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
this.packing.deleteBag(tripId, bagId);
safeBroadcast(tripId, 'packing:bag-deleted', { id: bagId });
return ok({ success: true });
}
@Tool({
name: 'set_bag_members',
description: 'Assign trip members to a packing bag (determines who packs what bag).',
inputSchema: {
tripId: z.number().int().positive(),
bagId: z.number().int().positive(),
userIds: z.array(z.number().int().positive()),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async setBagMembers({ tripId, bagId, userIds }: { tripId: number; bagId: number; userIds: number[] }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const members = this.packing.setBagMembers(tripId, bagId, userIds);
if (!members) return errorResult('Bag not found.');
safeBroadcast(tripId, 'packing:bag-members-updated', { bagId, members });
return ok({ members });
}
@Tool({
name: 'get_packing_category_assignees',
description: 'Get which trip members are assigned to each packing category.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
when: packingAddonOn,
access: { group: 'packing', mode: 'read' },
})
async getPackingCategoryAssignees({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
const assignees = this.packing.getCategoryAssignees(tripId);
return ok({ assignees });
}
@Tool({
name: 'set_packing_category_assignees',
description: 'Assign trip members to a packing category.',
inputSchema: {
tripId: z.number().int().positive(),
categoryName: z.string().min(1).max(100),
userIds: z.array(z.number().int().positive()),
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async setPackingCategoryAssignees({ tripId, categoryName, userIds }: { tripId: number; categoryName: string; userIds: number[] }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const assignees = this.packing.updateCategoryAssignees(tripId, categoryName, userIds);
safeBroadcast(tripId, 'packing:assignees', { category: categoryName, assignees });
return ok({ assignees });
}
@Tool({
name: 'apply_packing_template',
description: 'Apply a packing template to a trip (adds items from the template).',
inputSchema: {
tripId: z.number().int().positive(),
templateId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async applyPackingTemplate({ tripId, templateId }: { tripId: number; templateId: number }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const items = this.packing.applyTemplate(tripId, templateId);
if (items === null) return errorResult('Template not found.');
safeBroadcast(tripId, 'packing:template-applied', { items });
return ok({ items, count: items.length });
}
@Tool({
name: 'list_packing_templates',
description: 'List the reusable packing templates (id, name, item count) so one can be applied with apply_packing_template.',
inputSchema: {
tripId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_READONLY,
when: packingAddonOn,
access: { group: 'packing', mode: 'read' },
})
async listPackingTemplates({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
return ok({ templates: this.packing.listTemplates() });
}
@Tool({
name: 'save_packing_template',
description: 'Save the current packing list as a reusable template. Returns the new template (id, name, category/item counts). Admin only.',
inputSchema: {
tripId: z.number().int().positive(),
templateName: z.string().min(1).max(100),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async savePackingTemplate({ tripId, templateName }: { tripId: number; templateName: string }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
// Templates are global; the REST route restricts saving to admins. Match it.
if (!isAdminUser(ctx.userId)) return adminRequired();
const template = this.packing.saveAsTemplate(tripId, ctx.userId, templateName);
if (!template) return errorResult('Nothing to save — the packing list is empty.');
return ok({ template });
}
@Tool({
name: 'delete_packing_template',
description: 'Delete a reusable packing template. Templates are global, so deletion is admin only.',
inputSchema: {
templateId: z.number().int().positive(),
},
annotations: TOOL_ANNOTATIONS_DELETE,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async deletePackingTemplate({ templateId }: { templateId: number }, ctx: McpContext) {
if (isDemoUser(ctx.userId)) return demoDenied();
// Templates are global; the REST route restricts management to admins. Match it.
if (!isAdminUser(ctx.userId)) return adminRequired();
const result = deletePackingTemplate(String(templateId));
if ('error' in result) return errorResult(result.error);
return ok({ success: true, name: result.name });
}
@Tool({
name: 'bulk_import_packing',
description: 'Import multiple packing items at once from a list. Optionally assign each to a bag (by name — created if missing), set its weight, or pre-check it.',
inputSchema: {
tripId: z.number().int().positive(),
items: z.array(z.object({
name: z.string().min(1).max(200),
category: z.string().optional(),
quantity: z.number().int().positive().optional(),
bag: z.string().max(100).optional().describe('Bag name to assign the item to; created if it does not exist'),
weight_grams: z.number().nonnegative().optional(),
checked: z.boolean().optional(),
})).min(1),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: packingAddonOn,
access: { group: 'packing', mode: 'write' },
})
async bulkImportPacking(
{ tripId, items }: { tripId: number; items: { name: string; category?: string; quantity?: number; bag?: string; weight_grams?: number; checked?: boolean }[] },
ctx: McpContext,
) {
if (isDemoUser(ctx.userId)) return demoDenied();
if (!this.packing.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!hasTripPermission('packing_edit', tripId, ctx.userId)) return permissionDenied();
const created = this.packing.bulkImport(tripId, items, ctx.userId);
for (const item of created) safeBroadcast(tripId, 'packing:created', { item });
return ok({ items: created, count: created.length });
}
@ResourceTemplate({
name: 'trip-packing',
uriTemplate: 'trek://trips/{tripId}/packing',
description: 'Packing checklist for a trip',
mimeType: 'application/json',
when: packingAddonOn,
access: { group: 'packing', mode: 'read' },
})
async tripPackingResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
const id = parseId(tripId);
if (id === null || !this.packing.verifyTripAccess(id, ctx.userId)) {
return {
contents: [{
uri: uri.href,
mimeType: 'application/json',
text: JSON.stringify({ error: 'Trip not found or access denied' }),
}],
};
}
// Hide other members' private items (#858) from the requesting user.
const items = this.packing.listItems(id, ctx.userId);
return {
contents: [{
uri: uri.href,
mimeType: 'application/json',
text: JSON.stringify(items, null, 2),
}],
};
}
@ResourceTemplate({
name: 'trip-packing-bags',
uriTemplate: 'trek://trips/{tripId}/packing/bags',
description: 'All packing bags for a trip with their members',
mimeType: 'application/json',
when: packingAddonOn,
access: { group: 'packing', mode: 'read' },
})
async tripPackingBagsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
const id = parseId(tripId);
if (id === null || !this.packing.verifyTripAccess(id, ctx.userId)) {
return {
contents: [{
uri: uri.href,
mimeType: 'application/json',
text: JSON.stringify({ error: 'Trip not found or access denied' }),
}],
};
}
const bags = this.packing.listBags(id);
return {
contents: [{
uri: uri.href,
mimeType: 'application/json',
text: JSON.stringify(bags, null, 2),
}],
};
}
}
+6 -2
View File
@@ -1,10 +1,14 @@
import { Module } from '@nestjs/common';
import { PackingController } from './packing.controller';
import { PackingMcp } from './packing.mcp';
import { PackingService } from './packing.service';
/** Packing domain (S2 — Phase 2 trip sub-domain). Registered in AppModule. */
/** Packing domain (S2 — Phase 2 trip sub-domain). Registered in AppModule.
* Exports PackingService for in-container consumers (TripsService bundle,
* PluginHostDepsFactory). */
@Module({
controllers: [PackingController],
providers: [PackingService],
providers: [PackingService, PackingMcp],
exports: [PackingService],
})
export class PackingModule {}
+474 -55
View File
@@ -1,30 +1,46 @@
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { broadcast } from '../../websocket';
import { checkPermission } from '../../services/permissions';
import { verifyTripAccess } from '../../services/tripAccess';
import { avatarUrl } from '../../services/avatarUrl';
import type { UpdateConflict } from '../../services/conflictResult';
import type { User } from '../../types';
import * as svc from '../../services/packingService';
import { DatabaseService } from '../database/database.service';
/** Privacy fields stamped on a packing item (#858). */
type PrivacyFields = { is_private?: number; owner_id?: number | null };
type Trip = NonNullable<ReturnType<typeof svc.verifyTripAccess>>;
type Trip = NonNullable<ReturnType<typeof verifyTripAccess>>;
export type PackingVisibility = 'common' | 'personal' | 'shared';
interface ImportItem {
name?: string;
checked?: boolean;
category?: string;
weight_grams?: string | number;
bag?: string;
quantity?: number;
is_private?: boolean;
}
const BAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b', '#3b82f6', '#84cc16', '#d946ef', '#14b8a6', '#f43f5e', '#a855f7', '#eab308', '#64748b'];
/**
* Thin Nest wrapper around the existing packing service. Trip-access checks, the
* 'packing_edit' permission, the item/bag SQL, templates and the WebSocket
* broadcasts all reuse the legacy code unchanged, so behaviour is identical.
* Packing domain service — owns the packing SQL (moved 1:1 from the legacy
* services/packingService.ts: identical statements, the `||` falsy-coercion
* defaults, the bodyKeys sentinel protocol on the updates, the #858 three-tier
* sharing model and the post-write re-selects). Trip access, the
* 'packing_edit' permission and the WebSocket broadcast keep their legacy call
* paths. The remaining non-Nest consumer (the legacy MCP prompts registrar)
* goes through packing.bridge.ts instead of importing this class directly.
*/
@Injectable()
export class PackingService {
constructor(private readonly dbs: DatabaseService) {}
constructor(private readonly db: DatabaseService) {}
private get db() {
return this.dbs.connection;
}
verifyTripAccess(tripId: string, userId: number) {
return svc.verifyTripAccess(tripId, userId);
verifyTripAccess(tripId: string | number, userId: number) {
return verifyTripAccess(tripId, userId);
}
/** Mirrors the inline checkPermission('packing_edit', ...) the legacy route runs. */
@@ -62,97 +78,500 @@ export class PackingService {
return ids;
}
listItems(tripId: string, userId?: number) {
return svc.listItems(tripId, userId);
// ── Items ──────────────────────────────────────────────────────────────────
/**
* 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.
*/
private enrichItems(items: any[]): any[] {
if (items.length === 0) return items;
const ids = items.map(i => i.id);
const placeholders = ids.map(() => '?').join(',');
const owners = this.db.all<{ id: number; username: string }>(`SELECT id, username FROM users WHERE id IN (SELECT owner_id FROM packing_items WHERE id IN (${placeholders}))`, ...ids);
const ownerName = new Map(owners.map(o => [o.id, o.username]));
const recipientRows = this.db.all<{ item_id: number; user_id: number; username: string }>(`
SELECT r.item_id, r.user_id, COALESCE(u.display_name, u.username) AS username
FROM packing_item_recipients r JOIN users u ON u.id = r.user_id
WHERE r.item_id IN (${placeholders})
`, ...ids);
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 });
}
const contributorRows = this.db.all<{ item_id: number; user_id: number; status: string; username: string }>(`
SELECT c.item_id, c.user_id, c.status, COALESCE(u.display_name, u.username) AS username
FROM packing_item_contributors c JOIN users u ON u.id = c.user_id
WHERE c.item_id IN (${placeholders})
`, ...ids);
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) || [],
}));
}
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 = this.db.all(
'SELECT * FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC, created_at ASC',
tripId
);
} else {
rows = this.db.all(`
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
`, tripId, userId, userId);
}
return this.enrichItems(rows);
}
/** Reads an item's current privacy fields (#858) before an update, so the
* controller can detect a public↔private transition and route the broadcast. */
getItemPrivacy(tripId: string, id: string): PrivacyFields | undefined {
return this.db.prepare('SELECT is_private, owner_id FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId) as PrivacyFields | undefined;
getItemPrivacy(tripId: string | number, id: string | number): PrivacyFields | undefined {
return this.db.get<PrivacyFields>('SELECT is_private, owner_id FROM packing_items WHERE id = ? AND trip_id = ?', id, tripId);
}
createItem(tripId: string, data: Parameters<typeof svc.createItem>[1], ownerId?: number) {
return svc.createItem(tripId, data, ownerId);
/** Maps the three-tier visibility (#858) onto the stored is_private flag. */
private visibilityToPrivate(visibility?: PackingVisibility, isPrivateFallback?: boolean): number {
if (visibility) return visibility === 'common' ? 0 : 1;
return isPrivateFallback ? 1 : 0;
}
setItemSharing(tripId: string, id: string, actingUserId: number, visibility: svc.PackingVisibility, recipientIds: number[]) {
return svc.setItemSharing(tripId, id, actingUserId, visibility, recipientIds);
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 = 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));
const isPrivate = this.visibilityToPrivate(data.visibility, data.is_private);
const itemId = this.db.transaction(() => {
const result = this.db.run(
'INSERT INTO packing_items (trip_id, name, checked, category, sort_order, quantity, is_private, owner_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)',
tripId, data.name, data.checked ? 1 : 0, data.category || 'Allgemein', sortOrder, qty, isPrivate, ownerId ?? null
);
const id = Number(result.lastInsertRowid);
// "Shared with specific people" — record the recipients it covers.
if (data.visibility === 'shared' && Array.isArray(data.recipient_ids)) {
const ins = this.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(id, uid);
}
return id;
});
return this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', itemId)])[0];
}
addContributor(tripId: string, id: string, userId: number) {
return svc.addContributor(tripId, id, userId);
updateItem(
tripId: string | number,
id: string | number,
data: { name?: string; checked?: number; category?: string; weight_grams?: number | null; bag_id?: number | null; quantity?: number; is_private?: boolean },
bodyKeys: string[],
ifMatch?: string,
actingUserId?: number,
): unknown | UpdateConflict | null {
const item = this.db.get<{ updated_at?: string | null; owner_id?: number | null }>('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?', id, tripId);
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: this.db.get('SELECT * FROM packing_items WHERE id = ?', id) };
}
// 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;
this.db.run(`
UPDATE packing_items SET
name = COALESCE(?, name),
checked = CASE WHEN ? IS NOT NULL THEN ? ELSE checked END,
category = COALESCE(?, category),
weight_grams = CASE WHEN ? THEN ? ELSE weight_grams END,
bag_id = CASE WHEN ? THEN ? ELSE bag_id END,
quantity = CASE WHEN ? THEN ? ELSE quantity END,
is_private = CASE WHEN ? THEN ? ELSE is_private END,
owner_id = CASE WHEN ? THEN ? ELSE owner_id END,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`,
data.name || null,
data.checked !== undefined ? 1 : null,
data.checked ? 1 : 0,
data.category || null,
bodyKeys.includes('weight_grams') ? 1 : 0,
data.weight_grams ?? null,
bodyKeys.includes('bag_id') ? 1 : 0,
data.bag_id ?? null,
bodyKeys.includes('quantity') ? 1 : 0,
data.quantity ? Math.max(1, Math.min(999, Number(data.quantity))) : 1,
bodyKeys.includes('is_private') ? 1 : 0,
data.is_private ? 1 : 0,
claimOwner ? 1 : 0,
actingUserId ?? null,
id
);
return this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)])[0];
}
removeContributor(tripId: string, id: string, userId: number) {
return svc.removeContributor(tripId, id, userId);
// ── Three-tier sharing (#858): recipients, contributors, clone ───────────────
/** Loads an item scoped to its trip (the trip-access check happens in the controller). */
private getItemInTrip(tripId: string | number, id: string | number) {
return this.db.get<{ id: number; owner_id: number | null; is_private: number; name: string; category: string | null; quantity: number }>(
'SELECT * FROM packing_items WHERE id = ? AND trip_id = ?', id, tripId
);
}
cloneItem(tripId: string, id: string, userId: number) {
return svc.cloneItem(tripId, id, userId);
/**
* 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.
*/
setItemSharing(
tripId: string | number,
id: string | number,
actingUserId: number,
visibility: PackingVisibility,
recipientIds: number[],
) {
const item = this.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 };
this.db.transaction(() => {
this.db.run('UPDATE packing_items SET is_private = ?, owner_id = COALESCE(owner_id, ?), updated_at = CURRENT_TIMESTAMP WHERE id = ?',
this.visibilityToPrivate(visibility), actingUserId, id);
this.db.run('DELETE FROM packing_item_recipients WHERE item_id = ?', id);
if (visibility === 'shared') {
const ins = this.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') this.db.run('DELETE FROM packing_item_contributors WHERE item_id = ?', id);
});
return this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)])[0];
}
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);
/** "I can bring that too" — adds the user as a co-contributor on a Common item. */
addContributor(tripId: string | number, id: string | number, userId: number) {
const item = this.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
this.db.run("INSERT OR IGNORE INTO packing_item_contributors (item_id, user_id, status) VALUES (?, ?, 'accepted')", id, userId);
return this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)])[0];
}
deleteItem(tripId: string, id: string) {
return svc.deleteItem(tripId, id);
removeContributor(tripId: string | number, id: string | number, userId: number) {
const item = this.getItemInTrip(tripId, id);
if (!item) return null;
this.db.run('DELETE FROM packing_item_contributors WHERE item_id = ? AND user_id = ?', id, userId);
return this.enrichItems([this.db.get('SELECT * FROM packing_items WHERE id = ?', id)])[0];
}
bulkImport(tripId: string, items: Parameters<typeof svc.bulkImport>[1], ownerId?: number) {
return svc.bulkImport(tripId, items, ownerId);
/** Clone a (Common) item onto the caller's Personal list as a private starting point. */
cloneItem(tripId: string | number, id: string | number, userId: number) {
const item = this.getItemInTrip(tripId, id);
if (!item) return null;
return this.createItem(tripId, { name: item.name, category: item.category || undefined, quantity: item.quantity, visibility: 'personal' }, userId);
}
reorderItems(tripId: string, orderedIds: Parameters<typeof svc.reorderItems>[1]): void {
svc.reorderItems(tripId, orderedIds);
deleteItem(tripId: string | number, id: string | number) {
// Return the deleted row (not just a boolean) so callers can target the
// delete broadcast at the owner when the item was private (#858).
const item = this.db.get<{ is_private?: number; owner_id?: number | null }>('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?', id, tripId);
if (!item) return null;
this.db.run('DELETE FROM packing_items WHERE id = ?', id);
return item;
}
listBags(tripId: string) {
return svc.listBags(tripId);
// ── Bulk Import ────────────────────────────────────────────────────────────
bulkImport(tripId: string | number, items: ImportItem[], ownerId?: number) {
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?', tripId)!;
let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const stmt = this.db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, weight_grams, bag_id, sort_order, quantity, is_private, owner_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
const created: any[] = [];
this.db.transaction(() => {
for (const item of items) {
if (!item.name?.trim()) continue;
const checked = item.checked ? 1 : 0;
const weight = item.weight_grams ? parseInt(String(item.weight_grams)) || null : null;
// Resolve bag by name if provided
let bagId = null;
if (item.bag?.trim()) {
const bagName = item.bag.trim();
const existing = this.db.get<{ id: number }>('SELECT id FROM packing_bags WHERE trip_id = ? AND name = ?', tripId, bagName);
if (existing) {
bagId = existing.id;
} else {
const bagCount = this.db.get<{ c: number }>('SELECT COUNT(*) as c FROM packing_bags WHERE trip_id = ?', tripId)!.c;
const newBag = this.db.run('INSERT INTO packing_bags (trip_id, name, color) VALUES (?, ?, ?)', tripId, bagName, BAG_COLORS[bagCount % BAG_COLORS.length]);
bagId = newBag.lastInsertRowid;
}
}
const qty = Math.max(1, Math.min(999, Number(item.quantity) || 1));
const result = stmt.run(tripId, item.name.trim(), checked, item.category?.trim() || 'Other', weight, bagId, sortOrder++, qty, item.is_private ? 1 : 0, ownerId ?? null);
created.push(this.db.get('SELECT * FROM packing_items WHERE id = ?', result.lastInsertRowid));
}
});
return created;
}
createBag(tripId: string, data: { name: string; color?: string }) {
return svc.createBag(tripId, data);
// ── Bags ───────────────────────────────────────────────────────────────────
listBags(tripId: string | number) {
const bags = this.db.all<any>('SELECT * FROM packing_bags WHERE trip_id = ? ORDER BY sort_order, id', tripId);
const members = this.db.all<{ bag_id: number; user_id: number; username: string; avatar: string | null }>(`
SELECT bm.bag_id, bm.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM packing_bag_members bm
JOIN users u ON bm.user_id = u.id
JOIN packing_bags b ON bm.bag_id = b.id
WHERE b.trip_id = ?
`, tripId);
const membersByBag = new Map<number, typeof members>();
for (const m of members) {
if (!membersByBag.has(m.bag_id)) membersByBag.set(m.bag_id, []);
membersByBag.get(m.bag_id)!.push(m);
}
return bags.map(b => ({
...b,
members: (membersByBag.get(b.id) || []).map(m => ({ ...m, avatar: avatarUrl(m) })),
}));
}
updateBag(tripId: string, bagId: string, data: Parameters<typeof svc.updateBag>[2], changedKeys: string[]) {
return svc.updateBag(tripId, bagId, data, changedKeys);
/** Owner + collaborators of a trip — the only user ids that may be assigned to a bag. */
private tripRosterIds(tripId: string | number): Set<number> {
const rows = this.db.all<{ user_id: number }>('SELECT user_id FROM trip_members WHERE trip_id = ? UNION SELECT user_id FROM trips WHERE id = ?', tripId, tripId);
return new Set(rows.map(r => r.user_id));
}
deleteBag(tripId: string, bagId: string): boolean {
return svc.deleteBag(tripId, bagId);
setBagMembers(tripId: string | number, bagId: string | number, userIds: number[]) {
const bag = this.db.get('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
if (!bag) return null;
this.db.run('DELETE FROM packing_bag_members WHERE bag_id = ?', bagId);
const ins = this.db.prepare('INSERT OR IGNORE INTO packing_bag_members (bag_id, user_id) VALUES (?, ?)');
// Only real trip members may be bag members — never write an arbitrary account id.
const roster = this.tripRosterIds(tripId);
for (const uid of userIds) if (roster.has(uid)) ins.run(bagId, uid);
const rows = this.db.all<{ user_id: number; username: string; avatar: string | null }>(`
SELECT bm.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM packing_bag_members bm JOIN users u ON bm.user_id = u.id
WHERE bm.bag_id = ?
`, bagId);
return rows.map(m => ({ ...m, avatar: avatarUrl(m) }));
}
setBagMembers(tripId: string, bagId: string, userIds: number[]) {
return svc.setBagMembers(tripId, bagId, userIds);
createBag(tripId: string | number, data: { name: string; color?: string }) {
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
);
return this.db.get('SELECT * FROM packing_bags WHERE id = ?', result.lastInsertRowid);
}
updateBag(
tripId: string | number,
bagId: string | number,
data: { name?: string; color?: string; weight_limit_grams?: number | null; user_id?: number | null },
bodyKeys?: string[]
) {
const bag = this.db.get('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
if (!bag) return null;
// A bag may only be assigned to a real trip member; an off-roster id becomes unassigned.
const assignUser = data.user_id != null && this.tripRosterIds(tripId).has(data.user_id) ? data.user_id : null;
this.db.run(`UPDATE packing_bags SET
name = COALESCE(?, name),
color = COALESCE(?, color),
weight_limit_grams = ?,
user_id = CASE WHEN ? THEN ? ELSE user_id END
WHERE id = ?`,
data.name?.trim() || null,
data.color || null,
data.weight_limit_grams ?? (bag as any).weight_limit_grams ?? null,
bodyKeys?.includes('user_id') ? 1 : 0,
assignUser,
bagId
);
return this.db.get('SELECT b.*, COALESCE(u.display_name, u.username) as assigned_username FROM packing_bags b LEFT JOIN users u ON b.user_id = u.id WHERE b.id = ?', bagId);
}
deleteBag(tripId: string | number, bagId: string | number): boolean {
const bag = this.db.get('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?', bagId, tripId);
if (!bag) return false;
this.db.run('DELETE FROM packing_bags WHERE id = ?', bagId);
return true;
}
// ── List Templates ─────────────────────────────────────────────────────────
/**
* Read-only template list for trip members (name + item count), so non-admins
* can pick a template to apply. Management (create/edit/delete) stays admin-only
* under /api/admin/packing-templates.
*/
listTemplates() {
return svc.listTemplates();
return this.db.all<{ id: number; name: string; item_count: number }>(`
SELECT pt.id, pt.name,
(SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count
FROM packing_templates pt
ORDER BY pt.created_at DESC
`);
}
applyTemplate(tripId: string, templateId: string, visibility: 'common' | 'personal', ownerId: number) {
return svc.applyTemplate(tripId, templateId, visibility, ownerId);
// ── Apply Template ─────────────────────────────────────────────────────────
applyTemplate(
tripId: string | number,
templateId: string | number,
visibility: 'common' | 'personal' = 'common',
ownerId?: number,
) {
const templateItems = this.db.all<{ name: string; category: string }>(`
SELECT ti.name, tc.name as category
FROM packing_template_items ti
JOIN packing_template_categories tc ON ti.category_id = tc.id
WHERE tc.template_id = ?
ORDER BY tc.sort_order, ti.sort_order
`, templateId);
if (templateItems.length === 0) return null;
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?', tripId)!;
let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const isPrivate = ownerId != null ? this.visibilityToPrivate(visibility) : 0;
const owner = isPrivate ? ownerId! : null;
const insert = this.db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order, is_private, owner_id, updated_at) VALUES (?, ?, 0, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
const added: any[] = [];
for (const ti of templateItems) {
const result = insert.run(tripId, ti.name, ti.category, sortOrder++, isPrivate, owner);
const item = this.db.get('SELECT * FROM packing_items WHERE id = ?', result.lastInsertRowid);
added.push(item);
}
return added;
}
saveAsTemplate(tripId: string, userId: number, name: string) {
return svc.saveAsTemplate(tripId, userId, name);
// ── Save as Template ──────────────────────────────────────────────────────
saveAsTemplate(tripId: string | number, userId: number, templateName: string) {
const items = this.db.all<{ name: string; category: string }>(
'SELECT name, category FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC', tripId
);
if (items.length === 0) return null;
const result = this.db.run('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)', templateName, userId);
const templateId = result.lastInsertRowid;
const categories = [...new Set(items.map(i => i.category || 'Other'))];
const catIdMap = new Map<string, number | bigint>();
for (let i = 0; i < categories.length; i++) {
const catResult = this.db.run('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)', templateId, categories[i], i);
catIdMap.set(categories[i], catResult.lastInsertRowid);
}
const itemsByCategory = new Map<string, number>();
for (const item of items) {
const catId = catIdMap.get(item.category || 'Other')!;
const order = itemsByCategory.get(item.category || 'Other') || 0;
this.db.run('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)', catId, item.name, order);
itemsByCategory.set(item.category || 'Other', order + 1);
}
return { id: Number(templateId), name: templateName, categoryCount: categories.length, itemCount: items.length };
}
getCategoryAssignees(tripId: string) {
return svc.getCategoryAssignees(tripId);
// ── Category Assignees ─────────────────────────────────────────────────────
getCategoryAssignees(tripId: string | number) {
const rows = this.db.all<{ category_name: string; user_id: number; username: string; avatar: string | null }>(`
SELECT pca.category_name, pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM packing_category_assignees pca
JOIN users u ON pca.user_id = u.id
WHERE pca.trip_id = ?
`, tripId);
// Group by category
const assignees: Record<string, { user_id: number; username: string; avatar: string | null }[]> = {};
for (const row of rows) {
if (!assignees[row.category_name]) assignees[row.category_name] = [];
assignees[row.category_name].push({ user_id: row.user_id, username: row.username, avatar: avatarUrl(row) });
}
return assignees;
}
updateCategoryAssignees(tripId: string, category: string, userIds: number[]) {
return svc.updateCategoryAssignees(tripId, category, userIds);
updateCategoryAssignees(tripId: string | number, categoryName: string, userIds: number[] | undefined) {
this.db.run('DELETE FROM packing_category_assignees WHERE trip_id = ? AND category_name = ?', tripId, categoryName);
if (Array.isArray(userIds) && userIds.length > 0) {
const insert = this.db.prepare('INSERT OR IGNORE INTO packing_category_assignees (trip_id, category_name, user_id) VALUES (?, ?, ?)');
for (const uid of userIds) insert.run(tripId, categoryName, uid);
}
const updated = this.db.all<{ user_id: number; username: string; avatar: string | null }>(`
SELECT pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM packing_category_assignees pca
JOIN users u ON pca.user_id = u.id
WHERE pca.trip_id = ? AND pca.category_name = ?
`, tripId, categoryName);
return updated.map(m => ({ ...m, avatar: avatarUrl(m) }));
}
// ── Reorder ────────────────────────────────────────────────────────────────
reorderItems(tripId: string | number, orderedIds: number[]): void {
const update = this.db.prepare('UPDATE packing_items SET sort_order = ? WHERE id = ? AND trip_id = ?');
this.db.transaction(() => {
orderedIds.forEach((id, index) => {
update.run(index, id, tripId);
});
});
}
/** Fire-and-forget tag notification, mirroring the legacy dynamic import. */
notifyTagged(tripId: string, actor: User, category: string, userIds: unknown): void {
if (!Array.isArray(userIds) || userIds.length === 0) return;
import('../../services/notificationService').then(({ send }) => {
const tripInfo = this.db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined;
const tripInfo = this.db.get<{ title: string }>('SELECT title FROM trips WHERE id = ?', tripId);
send({
event: 'packing_tagged',
actorId: actor.id,
+12 -11
View File
@@ -88,18 +88,18 @@ injects it) and binds `this.hostDeps.create(id, granted, this)` in the
supervisor field initializer.
**Module wiring:** `TagsModule`/`CategoriesModule`/`BudgetModule`/
`ReservationsModule` gained `exports: [XService]` (`TodoModule` already
exported), and `PluginsModule` imports all five. The dependency graph moved
from hidden (bridge files) to explicit (the container). `DatabaseModule` is
`@Global`, so no import needed for it.
`ReservationsModule`/`PackingModule` gained `exports: [XService]` (`TodoModule`
already exported), and `PluginsModule` imports all six. The dependency graph
moved from hidden (bridge files) to explicit (the container). `DatabaseModule`
is `@Global`, so no import needed for it.
**Interaction with the service-migration track:** legacy `services/*` functions
(place, day, packing, files, collab, …) stay as plain imports inside the
(place, day, files, collab, …) stay as plain imports inside the
factory *until their own domain migrates*. Each future migration then swaps one
import for one injected service (+ module export/import) — **no more bridge
files for the plugin host, ever**. The factory's import list shrinks
monotonically as the recipe in `src/nest/README.md` proceeds (next up:
packingService).
monotonically as the recipe in `src/nest/README.md` proceeds (packing swapped
in 2026-07; next up: dayNoteService).
### Test impact (as landed)
@@ -215,10 +215,11 @@ none of it is throwaway.
1. ~~**Now / opportunistically — Option A.**~~ **Done (2026-07).** Injectable
factory, tags/categories bridges deleted, wiring test rewritten against
stubs (see §2).
2. **Per domain, as the service migrations proceed** (`packingService` next,
per `src/nest/README.md`): migrate the service to DI as usual; the factory
swaps one legacy import for one injected service. Optionally pilot
`tags.rpc.ts` here — tags is small and already fully DI on HTTP + MCP.
2. **Per domain, as the service migrations proceed** (`packingService` done
2026-07; `dayNoteService` next, per `src/nest/README.md`): migrate the
service to DI as usual; the factory swaps one legacy import for one
injected service. Optionally pilot `tags.rpc.ts` here — tags is small and
already fully DI on HTTP + MCP.
3. **Once ~half the domains are DI-native — commit to Option B.** Build the
registry package, validate() against `envelope.ts`, then drain the method
map domain by domain — the same strangler pattern that retired the Express
@@ -3,7 +3,6 @@ import { readEnv } from '../../../app-config';
import { db, canAccessTrip } from '../../../db/database';
import { broadcast, broadcastToUser } from '../../../websocket';
import { listBudgetItems } from '../../../services/budgetService';
import { listItems as listPackingItemsSvc, createItem as createPackingItemSvc, updateItem as updatePackingItemSvc, deleteItem as deletePackingItemSvc, listBags, createBag as createBagSvc, updateBag as updateBagSvc, deleteBag as deleteBagSvc, setBagMembers } from '../../../services/packingService';
import { isUpdateConflict } from '../../../services/conflictResult';
import { getWeather } from '../../../services/weatherService';
import { listFiles, createFile, createFileLink, getFileById, updateFile, softDeleteFile, findForeignLinkTarget, resolveFilePath, BLOCKED_EXTENSIONS, filesDir } from '../../../services/fileService';
@@ -36,6 +35,7 @@ import { ReservationsService } from '../../reservations/reservations.service';
import { TagsService } from '../../tags/tags.service';
import { CategoriesService } from '../../categories/categories.service';
import { TodoService } from '../../todo/todo.service';
import { PackingService } from '../../packing/packing.service';
import { notifyBookingChange } from '../../../services/reservationService';
import { PluginRpcHost, ForbiddenResource, BadParams } from './rpc-host';
import { appendAudit } from './plugin-audit';
@@ -82,19 +82,17 @@ function mapCollectionError<T>(fn: () => T): T {
}
}
// --- #858 packing privacy: viewer-scoped fan-out replicated from packing.controller +
// packing.service (their helpers aren't exported). A private item's events reach ONLY
// --- #858 packing privacy: viewer-scoped fan-out mirrored from
// packing.controller.broadcastUpdate/emitToViewers and PackingService's
// broadcastItem/viewersOf/broadcastToViewers. A private item's events reach ONLY
// its owner (+ recipients for a shared item), never the whole trip room; passing the
// wrong onlyUserId — or forgetting to drop a freshly-privatized item from the room —
// leaks it. Keep in lockstep with packing.controller.broadcastUpdate/emitToViewers. ---
// leaks it. Kept as a local copy (rather than delegating to the injected
// PackingService) so the factory's unit test can assert the fan-out through the
// websocket mock while PackingService stays a plain data stub. Keep in lockstep
// with packing.controller.ts + packing.service.ts. ---
type PackingPrivacy = { is_private?: number; owner_id?: number | null; recipients?: { user_id: number }[] };
function packingItemPrivacy(tripId: number, itemId: number): { is_private?: number; owner_id?: number | null } | undefined {
return db.prepare('SELECT is_private, owner_id FROM packing_items WHERE id = ? AND trip_id = ?').get(itemId, tripId) as
| { is_private?: number; owner_id?: number | null }
| undefined;
}
function packingViewersOf(item: PackingPrivacy | null | undefined): number[] | null {
if (!item || !item.is_private) return null; // Common — visible to the whole room
return [item.owner_id, ...(item.recipients || []).map((r) => r.user_id)].filter((x): x is number => x != null);
@@ -152,9 +150,9 @@ export interface PluginCallRouter {
* `plugin:{id}:{event}` so a plugin can't forge a core event.
*
* DI-native domain services (budget, reservations, tags, categories, todo,
* oauth) are constructor-injected; legacy `services/*` domains stay plain
* function imports until their own migration lands (DI-MIGRATION.md), at which
* point each swaps one import for one injected service.
* packing, oauth) are constructor-injected; legacy `services/*` domains stay
* plain function imports until their own migration lands (DI-MIGRATION.md), at
* which point each swaps one import for one injected service.
*/
@Injectable()
export class PluginHostDepsFactory {
@@ -164,6 +162,7 @@ export class PluginHostDepsFactory {
private readonly tags: TagsService,
private readonly categories: CategoriesService,
private readonly todos: TodoService,
private readonly packing: PackingService,
private readonly oauth: PluginOAuthService,
) {}
@@ -211,7 +210,7 @@ export class PluginHostDepsFactory {
},
// --- Read scopes (packing/files). Membership is checked by the host (tripRead);
// these just delegate to the same services the REST paths use. ---
listPackingItems: (tripId, userId) => listPackingItemsSvc(tripId, userId),
listPackingItems: (tripId, userId) => this.packing.listItems(tripId, userId),
listTripFiles: (tripId) => listFiles(tripId, false),
// A file's bytes as base64, size-capped BEFORE the read so a 500MB video can't
// be pulled (~667MB base64) through the IPC pipe. 10MB matches the plugin upload
@@ -749,52 +748,52 @@ export class PluginHostDepsFactory {
notifyBooking(actingUserId, tripId, deleted.title, deleted.type || '');
return { deleted: true };
},
// --- Packing (packing_edit). Reuses packingService + replicates the #858
// --- Packing (packing_edit). Reuses PackingService + replicates the #858
// privacy-scoped broadcasts (create/delete via emitPackingToViewers, update via
// the four-case broadcastPackingUpdate) so a private item never leaks room-wide. ---
canEditPacking: (tripId, userId) => canEditTripAs('packing_edit', tripId, userId),
createPackingItem: (tripId, input, actingUserId) => {
const i = input as { name: string; category?: string; checked?: boolean; is_private?: boolean; visibility?: 'common' | 'personal' | 'shared'; recipient_ids?: number[] };
const item = createPackingItemSvc(String(tripId), i, actingUserId) as PackingPrivacy;
const item = this.packing.createItem(String(tripId), i, actingUserId) as PackingPrivacy;
emitPackingToViewers(tripId, 'packing:created', { item }, item);
return item;
},
updatePackingItem: (tripId, itemId, input, actingUserId) => {
// Privacy BEFORE the write, so a public<->private toggle routes correctly.
const before = packingItemPrivacy(tripId, itemId);
const updated = updatePackingItemSvc(String(tripId), String(itemId), input as never, Object.keys(input), undefined, actingUserId);
const before = this.packing.getItemPrivacy(tripId, itemId);
const updated = this.packing.updateItem(String(tripId), String(itemId), input as never, Object.keys(input), undefined, actingUserId);
if (!updated) throw new ForbiddenResource(`no packing item ${itemId} on trip ${tripId}`);
if (isUpdateConflict(updated)) throw new BadParams('packing item was modified concurrently');
broadcastPackingUpdate(tripId, itemId, updated as PackingPrivacy, !!before?.is_private);
return updated;
},
deletePackingItem: (tripId, itemId) => {
const deleted = deletePackingItemSvc(String(tripId), String(itemId)) as PackingPrivacy | null;
const deleted = this.packing.deleteItem(String(tripId), String(itemId)) as PackingPrivacy | null;
if (!deleted) throw new ForbiddenResource(`no packing item ${itemId} on trip ${tripId}`);
emitPackingToViewers(tripId, 'packing:deleted', { itemId }, deleted);
return { deleted: true };
},
// --- Packing bags (no privacy — plain room broadcasts). ---
listPackingBags: (tripId) => listBags(String(tripId)) as unknown[],
listPackingBags: (tripId) => this.packing.listBags(String(tripId)) as unknown[],
createPackingBag: (tripId, input) => {
const i = input as { name: string; color?: string };
const bag = createBagSvc(String(tripId), { name: i.name, color: i.color });
const bag = this.packing.createBag(String(tripId), { name: i.name, color: i.color });
broadcast(tripId, 'packing:bag-created', { bag }, undefined);
return bag;
},
updatePackingBag: (tripId, bagId, input) => {
const bag = updateBagSvc(String(tripId), String(bagId), input as never, Object.keys(input));
const bag = this.packing.updateBag(String(tripId), String(bagId), input as never, Object.keys(input));
if (!bag) throw new ForbiddenResource(`no packing bag ${bagId} on trip ${tripId}`);
broadcast(tripId, 'packing:bag-updated', { bag }, undefined);
return bag;
},
deletePackingBag: (tripId, bagId) => {
if (!deleteBagSvc(String(tripId), String(bagId))) throw new ForbiddenResource(`no packing bag ${bagId} on trip ${tripId}`);
if (!this.packing.deleteBag(String(tripId), String(bagId))) throw new ForbiddenResource(`no packing bag ${bagId} on trip ${tripId}`);
broadcast(tripId, 'packing:bag-deleted', { bagId }, undefined);
return { deleted: true };
},
setPackingBagMembers: (tripId, bagId, userIds) => {
const members = setBagMembers(String(tripId), String(bagId), userIds);
const members = this.packing.setBagMembers(String(tripId), String(bagId), userIds);
if (!members) throw new ForbiddenResource(`no packing bag ${bagId} on trip ${tripId}`);
broadcast(tripId, 'packing:bag-members-updated', { bagId, members }, undefined);
return members;
+2 -1
View File
@@ -29,6 +29,7 @@ import { CategoriesModule } from '../categories/categories.module';
import { BudgetModule } from '../budget/budget.module';
import { ReservationsModule } from '../reservations/reservations.module';
import { TodoModule } from '../todo/todo.module';
import { PackingModule } from '../packing/packing.module';
/**
* Plugin system (#plugins). M0 read side + M2 isolated runtime + M3 frontend:
@@ -40,7 +41,7 @@ import { TodoModule } from '../todo/todo.module';
@Module({
// The DI-native domain services the plugin host wiring injects
// (PluginHostDepsFactory); DatabaseModule is @Global, so not listed.
imports: [TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule],
imports: [TagsModule, CategoriesModule, BudgetModule, ReservationsModule, TodoModule, PackingModule],
controllers: [PluginsController, PluginsFeedController, PluginsProxyController, PluginFrameController, PlaceDetailsController, TripWarningsController, ViewContributionsController, TripCardContributionsController, PluginPhotosController, PluginCalendarController, MapMarkersController, MapLayersController, PluginRoutesController, DayScheduleController, PdfSectionsController, AtlasLayersController, JournalEntryRowsController, PluginUserSettingsController, PluginOAuthController, PluginActivityController],
providers: [PluginsService, PluginRuntimeService, PluginRegistryService, PluginOAuthService, PluginHostDepsFactory],
// Exported so the admin addon-toggle handler can cascade-disable plugins whose
+2 -1
View File
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { PackingModule } from '../packing/packing.module';
import { TodoModule } from '../todo/todo.module';
import { TripsController } from './trips.controller';
import { TripsService } from './trips.service';
@@ -6,7 +7,7 @@ import { TripsService } from './trips.service';
/** Trips aggregate root (C1 — Phase 3). Uses exact strangler prefixes so it does
* not capture the nested sub-domain mounts (collab, files, ...). */
@Module({
imports: [TodoModule],
imports: [TodoModule, PackingModule],
controllers: [TripsController],
providers: [TripsService],
})
+3 -2
View File
@@ -6,7 +6,7 @@ import type { User } from '../../types';
import * as tripSvc from '../../services/tripService';
import { listDays, listAccommodations } from '../../services/dayService';
import { listPlaces } from '../../services/placeService';
import { listItems as listPackingItems } from '../../services/packingService';
import { PackingService } from '../packing/packing.service';
import { TodoService } from '../todo/todo.service';
import { listBudgetItems, rebaseTripCurrency } from '../../services/budgetService';
import { listReservations } from '../../services/reservationService';
@@ -25,6 +25,7 @@ export class TripsService {
constructor(
private readonly dbs: DatabaseService,
private readonly todo: TodoService,
private readonly packing: PackingService,
) {}
private get db() {
@@ -136,7 +137,7 @@ export class TripsService {
trip,
days,
places: listPlaces(String(tripId), {}),
packingItems: listPackingItems(tripId),
packingItems: this.packing.listItems(tripId),
todoItems: this.todo.listItems(tripId),
budgetItems: listBudgetItems(tripId),
reservations: listReservations(tripId),
-503
View File
@@ -1,503 +0,0 @@
import { db } from '../db/database';
import { avatarUrl } from './authService';
import type { UpdateConflict } from './conflictResult';
const BAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b', '#3b82f6', '#84cc16', '#d946ef', '#14b8a6', '#f43f5e', '#a855f7', '#eab308', '#64748b'];
export { verifyTripAccess } from './tripAccess';
// ── Items ──────────────────────────────────────────────────────────────────
/**
* 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, COALESCE(u.display_name, u.username) AS 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 });
}
const contributorRows = db.prepare(`
SELECT c.item_id, c.user_id, c.status, COALESCE(u.display_name, u.username) AS 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 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 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 enrichItems([db.prepare('SELECT * FROM packing_items WHERE id = ?').get(itemId)])[0];
}
export function updateItem(
tripId: string | number,
id: string | number,
data: { name?: string; checked?: number; category?: string; weight_grams?: number | null; bag_id?: number | null; quantity?: number; is_private?: boolean },
bodyKeys: string[],
ifMatch?: string,
actingUserId?: number,
): unknown | UpdateConflict | null {
const item = db.prepare('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId) as { updated_at?: string | null; owner_id?: number | null } | undefined;
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: db.prepare('SELECT * FROM packing_items WHERE id = ?').get(id) };
}
// 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;
db.prepare(`
UPDATE packing_items SET
name = COALESCE(?, name),
checked = CASE WHEN ? IS NOT NULL THEN ? ELSE checked END,
category = COALESCE(?, category),
weight_grams = CASE WHEN ? THEN ? ELSE weight_grams END,
bag_id = CASE WHEN ? THEN ? ELSE bag_id END,
quantity = CASE WHEN ? THEN ? ELSE quantity END,
is_private = CASE WHEN ? THEN ? ELSE is_private END,
owner_id = CASE WHEN ? THEN ? ELSE owner_id END,
updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`).run(
data.name || null,
data.checked !== undefined ? 1 : null,
data.checked ? 1 : 0,
data.category || null,
bodyKeys.includes('weight_grams') ? 1 : 0,
data.weight_grams ?? null,
bodyKeys.includes('bag_id') ? 1 : 0,
data.bag_id ?? null,
bodyKeys.includes('quantity') ? 1 : 0,
data.quantity ? Math.max(1, Math.min(999, Number(data.quantity))) : 1,
bodyKeys.includes('is_private') ? 1 : 0,
data.is_private ? 1 : 0,
claimOwner ? 1 : 0,
actingUserId ?? null,
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) {
// Return the deleted row (not just a boolean) so callers can target the
// delete broadcast at the owner when the item was private (#858).
const item = db.prepare('SELECT * FROM packing_items WHERE id = ? AND trip_id = ?').get(id, tripId) as { is_private?: number; owner_id?: number | null } | undefined;
if (!item) return null;
db.prepare('DELETE FROM packing_items WHERE id = ?').run(id);
return item;
}
// ── Bulk Import ────────────────────────────────────────────────────────────
interface ImportItem {
name?: string;
checked?: boolean;
category?: string;
weight_grams?: string | number;
bag?: string;
quantity?: number;
is_private?: boolean;
}
export function bulkImport(tripId: string | number, items: ImportItem[], ownerId?: number) {
const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null };
let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const stmt = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, weight_grams, bag_id, sort_order, quantity, is_private, owner_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
const created: any[] = [];
const insertAll = db.transaction(() => {
for (const item of items) {
if (!item.name?.trim()) continue;
const checked = item.checked ? 1 : 0;
const weight = item.weight_grams ? parseInt(String(item.weight_grams)) || null : null;
// Resolve bag by name if provided
let bagId = null;
if (item.bag?.trim()) {
const bagName = item.bag.trim();
const existing = db.prepare('SELECT id FROM packing_bags WHERE trip_id = ? AND name = ?').get(tripId, bagName) as { id: number } | undefined;
if (existing) {
bagId = existing.id;
} else {
const bagCount = (db.prepare('SELECT COUNT(*) as c FROM packing_bags WHERE trip_id = ?').get(tripId) as { c: number }).c;
const newBag = db.prepare('INSERT INTO packing_bags (trip_id, name, color) VALUES (?, ?, ?)').run(tripId, bagName, BAG_COLORS[bagCount % BAG_COLORS.length]);
bagId = newBag.lastInsertRowid;
}
}
const qty = Math.max(1, Math.min(999, Number(item.quantity) || 1));
const result = stmt.run(tripId, item.name.trim(), checked, item.category?.trim() || 'Other', weight, bagId, sortOrder++, qty, item.is_private ? 1 : 0, ownerId ?? null);
created.push(db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid));
}
});
insertAll();
return created;
}
// ── Bags ───────────────────────────────────────────────────────────────────
export function listBags(tripId: string | number) {
const bags = db.prepare('SELECT * FROM packing_bags WHERE trip_id = ? ORDER BY sort_order, id').all(tripId) as any[];
const members = db.prepare(`
SELECT bm.bag_id, bm.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM packing_bag_members bm
JOIN users u ON bm.user_id = u.id
JOIN packing_bags b ON bm.bag_id = b.id
WHERE b.trip_id = ?
`).all(tripId) as { bag_id: number; user_id: number; username: string; avatar: string | null }[];
const membersByBag = new Map<number, typeof members>();
for (const m of members) {
if (!membersByBag.has(m.bag_id)) membersByBag.set(m.bag_id, []);
membersByBag.get(m.bag_id)!.push(m);
}
return bags.map(b => ({
...b,
members: (membersByBag.get(b.id) || []).map(m => ({ ...m, avatar: avatarUrl(m) })),
}));
}
/** Owner + collaborators of a trip — the only user ids that may be assigned to a bag. */
function tripRosterIds(tripId: string | number): Set<number> {
const rows = db.prepare('SELECT user_id FROM trip_members WHERE trip_id = ? UNION SELECT user_id FROM trips WHERE id = ?').all(tripId, tripId) as { user_id: number }[];
return new Set(rows.map(r => r.user_id));
}
export function setBagMembers(tripId: string | number, bagId: string | number, userIds: number[]) {
const bag = db.prepare('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?').get(bagId, tripId);
if (!bag) return null;
db.prepare('DELETE FROM packing_bag_members WHERE bag_id = ?').run(bagId);
const ins = db.prepare('INSERT OR IGNORE INTO packing_bag_members (bag_id, user_id) VALUES (?, ?)');
// Only real trip members may be bag members — never write an arbitrary account id.
const roster = tripRosterIds(tripId);
for (const uid of userIds) if (roster.has(uid)) ins.run(bagId, uid);
const rows = db.prepare(`
SELECT bm.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM packing_bag_members bm JOIN users u ON bm.user_id = u.id
WHERE bm.bag_id = ?
`).all(bagId) as { user_id: number; username: string; avatar: string | null }[];
return rows.map(m => ({ ...m, avatar: avatarUrl(m) }));
}
export function createBag(tripId: string | number, data: { name: string; color?: string }) {
const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_bags WHERE trip_id = ?').get(tripId) as { max: number | null };
const result = db.prepare('INSERT INTO packing_bags (trip_id, name, color, sort_order) VALUES (?, ?, ?, ?)').run(
tripId, data.name.trim(), data.color || '#6366f1', (maxOrder.max ?? -1) + 1
);
return db.prepare('SELECT * FROM packing_bags WHERE id = ?').get(result.lastInsertRowid);
}
export function updateBag(
tripId: string | number,
bagId: string | number,
data: { name?: string; color?: string; weight_limit_grams?: number | null; user_id?: number | null },
bodyKeys?: string[]
) {
const bag = db.prepare('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?').get(bagId, tripId);
if (!bag) return null;
// A bag may only be assigned to a real trip member; an off-roster id becomes unassigned.
const assignUser = data.user_id != null && tripRosterIds(tripId).has(data.user_id) ? data.user_id : null;
db.prepare(`UPDATE packing_bags SET
name = COALESCE(?, name),
color = COALESCE(?, color),
weight_limit_grams = ?,
user_id = CASE WHEN ? THEN ? ELSE user_id END
WHERE id = ?`).run(
data.name?.trim() || null,
data.color || null,
data.weight_limit_grams ?? (bag as any).weight_limit_grams ?? null,
bodyKeys?.includes('user_id') ? 1 : 0,
assignUser,
bagId
);
return db.prepare('SELECT b.*, COALESCE(u.display_name, u.username) as assigned_username FROM packing_bags b LEFT JOIN users u ON b.user_id = u.id WHERE b.id = ?').get(bagId);
}
export function deleteBag(tripId: string | number, bagId: string | number) {
const bag = db.prepare('SELECT * FROM packing_bags WHERE id = ? AND trip_id = ?').get(bagId, tripId);
if (!bag) return false;
db.prepare('DELETE FROM packing_bags WHERE id = ?').run(bagId);
return true;
}
// ── List Templates ─────────────────────────────────────────────────────────
/**
* Read-only template list for trip members (name + item count), so non-admins
* can pick a template to apply. Management (create/edit/delete) stays admin-only
* under /api/admin/packing-templates.
*/
export function listTemplates() {
return db.prepare(`
SELECT pt.id, pt.name,
(SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count
FROM packing_templates pt
ORDER BY pt.created_at DESC
`).all() as { id: number; name: string; item_count: number }[];
}
// ── Apply Template ─────────────────────────────────────────────────────────
export function applyTemplate(
tripId: string | number,
templateId: string | number,
visibility: 'common' | 'personal' = 'common',
ownerId?: number,
) {
const templateItems = db.prepare(`
SELECT ti.name, tc.name as category
FROM packing_template_items ti
JOIN packing_template_categories tc ON ti.category_id = tc.id
WHERE tc.template_id = ?
ORDER BY tc.sort_order, ti.sort_order
`).all(templateId) as { name: string; category: string }[];
if (templateItems.length === 0) return null;
const maxOrder = db.prepare('SELECT MAX(sort_order) as max FROM packing_items WHERE trip_id = ?').get(tripId) as { max: number | null };
let sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
const isPrivate = ownerId != null ? visibilityToPrivate(visibility) : 0;
const owner = isPrivate ? ownerId! : null;
const insert = db.prepare('INSERT INTO packing_items (trip_id, name, checked, category, sort_order, is_private, owner_id, updated_at) VALUES (?, ?, 0, ?, ?, ?, ?, CURRENT_TIMESTAMP)');
const added: any[] = [];
for (const ti of templateItems) {
const result = insert.run(tripId, ti.name, ti.category, sortOrder++, isPrivate, owner);
const item = db.prepare('SELECT * FROM packing_items WHERE id = ?').get(result.lastInsertRowid);
added.push(item);
}
return added;
}
// ── Save as Template ──────────────────────────────────────────────────────
export function saveAsTemplate(tripId: string | number, userId: number, templateName: string) {
const items = db.prepare(
'SELECT name, category FROM packing_items WHERE trip_id = ? ORDER BY sort_order ASC'
).all(tripId) as { name: string; category: string }[];
if (items.length === 0) return null;
const result = db.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run(templateName, userId);
const templateId = result.lastInsertRowid;
const categories = [...new Set(items.map(i => i.category || 'Other'))];
const catIdMap = new Map<string, number | bigint>();
for (let i = 0; i < categories.length; i++) {
const catResult = db.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, categories[i], i);
catIdMap.set(categories[i], catResult.lastInsertRowid);
}
const itemsByCategory = new Map<string, number>();
for (const item of items) {
const catId = catIdMap.get(item.category || 'Other')!;
const order = itemsByCategory.get(item.category || 'Other') || 0;
db.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, item.name, order);
itemsByCategory.set(item.category || 'Other', order + 1);
}
return { id: Number(templateId), name: templateName, categoryCount: categories.length, itemCount: items.length };
}
// ── Category Assignees ─────────────────────────────────────────────────────
export function getCategoryAssignees(tripId: string | number) {
const rows = db.prepare(`
SELECT pca.category_name, pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM packing_category_assignees pca
JOIN users u ON pca.user_id = u.id
WHERE pca.trip_id = ?
`).all(tripId);
// Group by category
const assignees: Record<string, { user_id: number; username: string; avatar: string | null }[]> = {};
for (const row of rows as any[]) {
if (!assignees[row.category_name]) assignees[row.category_name] = [];
assignees[row.category_name].push({ user_id: row.user_id, username: row.username, avatar: avatarUrl(row) });
}
return assignees;
}
export function updateCategoryAssignees(tripId: string | number, categoryName: string, userIds: number[] | undefined) {
db.prepare('DELETE FROM packing_category_assignees WHERE trip_id = ? AND category_name = ?').run(tripId, categoryName);
if (Array.isArray(userIds) && userIds.length > 0) {
const insert = db.prepare('INSERT OR IGNORE INTO packing_category_assignees (trip_id, category_name, user_id) VALUES (?, ?, ?)');
for (const uid of userIds) insert.run(tripId, categoryName, uid);
}
const updated = db.prepare(`
SELECT pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar
FROM packing_category_assignees pca
JOIN users u ON pca.user_id = u.id
WHERE pca.trip_id = ? AND pca.category_name = ?
`).all(tripId, categoryName) as { user_id: number; username: string; avatar: string | null }[];
return updated.map(m => ({ ...m, avatar: avatarUrl(m) }));
}
// ── Reorder ────────────────────────────────────────────────────────────────
export function reorderItems(tripId: string | number, orderedIds: number[]) {
const update = db.prepare('UPDATE packing_items SET sort_order = ? WHERE id = ? AND trip_id = ?');
const updateMany = db.transaction((ids: number[]) => {
ids.forEach((id, index) => {
update.run(index, id, tripId);
});
});
updateMany(orderedIds);
}
+1 -1
View File
@@ -8,7 +8,7 @@ import { emitUserDeleted } from '../plugin-user-lifecycle';
import { Trip, User } from '../types';
import { listDays, listAccommodations, addDays, resyncAccommodationDays, restampReservationDates } from './dayService';
import { listBudgetItems, removeUserFromBudgetItems } from './budgetService';
import { listItems as listPackingItems } from './packingService';
import { listItems as listPackingItems } from '../nest/packing/packing.bridge';
import { listReservations, loadEndpointsByTrip, resyncReservationDays } from './reservationService';
import { listNotes as listCollabNotes } from './collabService';
import { shiftOwnerEntriesForTripWindow } from './vacayService';
+280 -33
View File
@@ -1,14 +1,15 @@
/**
* Packing module e2e — exercises the migrated /api/trips/:tripId/packing
* endpoints through the real JwtAuthGuard against a temp SQLite db. The packing
* service, permission check and WebSocket broadcast are mocked; this focuses on
* auth, trip-access 404, permission 403, status codes and bodies.
* endpoints through the real JwtAuthGuard against a temp SQLite db.
* PackingService runs its real SQL via DatabaseModule (the DATABASE_CONNECTION
* factory picks up the mocked db singleton); trip access resolves through a
* real-SQL canAccessTrip over the temp db. Only the permission check, the
* WebSocket broadcast and the notification sender stay mocked.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
import request from 'supertest';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import { DatabaseModule } from '../../src/nest/database/database.module';
import { Test } from '@nestjs/testing';
import { seedUser, sessionCookie } from './harness';
@@ -18,35 +19,117 @@ const { db } = vi.hoisted(() => {
const tmp = new Database(':memory:');
tmp.exec('PRAGMA journal_mode = WAL');
tmp.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0);`);
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);');
email TEXT NOT NULL UNIQUE, role TEXT NOT NULL DEFAULT 'user', password_version INTEGER NOT NULL DEFAULT 0,
display_name TEXT, avatar TEXT);`);
tmp.exec('CREATE TABLE trips (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, title TEXT);');
tmp.exec('CREATE TABLE trip_members (trip_id INTEGER NOT NULL, user_id INTEGER NOT NULL);');
// The post-migration shape of the packing tables (schema.ts + migrations.ts).
tmp.exec(`CREATE TABLE packing_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL,
name TEXT NOT NULL,
checked INTEGER DEFAULT 0,
category TEXT,
sort_order INTEGER DEFAULT 0,
weight_grams INTEGER,
bag_id INTEGER,
quantity INTEGER NOT NULL DEFAULT 1,
is_private INTEGER NOT NULL DEFAULT 0,
owner_id INTEGER,
updated_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);`);
tmp.exec(`CREATE TABLE packing_bags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL,
name TEXT NOT NULL,
color TEXT NOT NULL DEFAULT '#6366f1',
weight_limit_grams INTEGER,
sort_order INTEGER DEFAULT 0,
user_id INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);`);
tmp.exec(`CREATE TABLE packing_bag_members (
bag_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (bag_id, user_id)
);`);
tmp.exec(`CREATE TABLE packing_item_recipients (
item_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (item_id, user_id)
);`);
tmp.exec(`CREATE TABLE packing_item_contributors (
item_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'accepted',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (item_id, user_id)
);`);
tmp.exec(`CREATE TABLE packing_category_assignees (
id INTEGER PRIMARY KEY AUTOINCREMENT,
trip_id INTEGER NOT NULL,
category_name TEXT NOT NULL,
user_id INTEGER NOT NULL,
UNIQUE(trip_id, category_name, user_id)
);`);
tmp.exec(`CREATE TABLE packing_templates (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
created_by INTEGER NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);`);
tmp.exec(`CREATE TABLE packing_template_categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
template_id INTEGER NOT NULL,
name TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0
);`);
tmp.exec(`CREATE TABLE packing_template_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category_id INTEGER NOT NULL,
name TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0
);`);
return { db: tmp };
});
vi.mock('../../src/db/database', () => ({ db, closeDb: () => {}, reinitialize: () => {} }));
vi.mock('../../src/db/database', () => ({
db,
// Real-SQL trip access over the temp db — PackingService.verifyTripAccess and
// DatabaseModule both read the mocked singleton.
canAccessTrip: (tripId: number | string, userId: number) =>
db.prepare(`
SELECT t.id, t.user_id FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
`).get(userId, tripId, userId),
isOwner: () => false,
getPlaceWithTags: () => null,
closeDb: () => {},
reinitialize: () => {},
}));
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn() }));
vi.mock('../../src/services/notificationService', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn() }));
vi.mock('../../src/services/permissions', () => ({ checkPermission }));
const { svc } = vi.hoisted(() => ({
svc: {
verifyTripAccess: vi.fn(), listItems: vi.fn(), createItem: vi.fn(), updateItem: vi.fn(),
deleteItem: vi.fn(), bulkImport: vi.fn(), reorderItems: vi.fn(), listBags: vi.fn(),
createBag: vi.fn(), updateBag: vi.fn(), deleteBag: vi.fn(), applyTemplate: vi.fn(),
saveAsTemplate: vi.fn(), setBagMembers: vi.fn(), getCategoryAssignees: vi.fn(),
updateCategoryAssignees: vi.fn(),
},
}));
vi.mock('../../src/services/packingService', () => svc);
import { PackingModule } from '../../src/nest/packing/packing.module';
import { DatabaseModule } from '../../src/nest/database/database.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
describe('Packing e2e (real auth guard + temp SQLite)', () => {
function insertItem(tripId: number, name: string, extra: Partial<{ sort_order: number; category: string; is_private: number; owner_id: number }> = {}): number {
const res = db
.prepare('INSERT INTO packing_items (trip_id, name, sort_order, category, is_private, owner_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)')
.run(tripId, name, extra.sort_order ?? 0, extra.category ?? null, extra.is_private ?? 0, extra.owner_id ?? null);
return Number(res.lastInsertRowid);
}
describe('Packing e2e (real auth guard + real SQL over temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
let tripId: number;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, PackingModule] }).compile();
@@ -59,14 +142,25 @@ describe('Packing e2e (real auth guard + temp SQLite)', () => {
beforeAll(async () => {
seedUser(db as never, { id: 1 });
seedUser(db as never, { id: 2, email: 'stranger@example.test' });
seedUser(db as never, { id: 3, email: 'admin@example.test', role: 'admin' });
app = await build();
server = app.getHttpServer();
svc.listItems.mockReturnValue([{ id: 1, name: 'Socks' }]);
svc.createItem.mockReturnValue({ id: 9, name: 'Socks' });
});
beforeEach(() => {
svc.verifyTripAccess.mockReturnValue({ id: 5, user_id: 1 });
db.exec('DELETE FROM packing_category_assignees');
db.exec('DELETE FROM packing_template_items');
db.exec('DELETE FROM packing_template_categories');
db.exec('DELETE FROM packing_templates');
db.exec('DELETE FROM packing_item_recipients');
db.exec('DELETE FROM packing_item_contributors');
db.exec('DELETE FROM packing_bag_members');
db.exec('DELETE FROM packing_items');
db.exec('DELETE FROM packing_bags');
db.exec('DELETE FROM trip_members');
db.exec('DELETE FROM trips');
tripId = Number(db.prepare('INSERT INTO trips (user_id, title) VALUES (1, ?)').run('Trip').lastInsertRowid);
checkPermission.mockReturnValue(true);
});
@@ -75,33 +169,186 @@ describe('Packing e2e (real auth guard + temp SQLite)', () => {
});
it('401 without a session cookie', async () => {
const res = await request(server).get('/api/trips/5/packing');
const res = await request(server).get(`/api/trips/${tripId}/packing`);
expect(res.status).toBe(401);
});
it('200 list for an accessible trip', async () => {
const res = await request(server).get('/api/trips/5/packing').set('Cookie', sessionCookie(1));
it('200 list, hiding another member\'s private items from the viewer (#858)', async () => {
insertItem(tripId, 'Shared', { sort_order: 0 });
insertItem(tripId, 'Secret', { sort_order: 1, is_private: 1, owner_id: 2 });
const res = await request(server).get(`/api/trips/${tripId}/packing`).set('Cookie', sessionCookie(1));
expect(res.status).toBe(200);
expect(res.body).toEqual({ items: [{ id: 1, name: 'Socks' }] });
expect(res.body.items.map((i: { name: string }) => i.name)).toEqual(['Shared']);
});
it('404 when the trip is not accessible', async () => {
svc.verifyTripAccess.mockReturnValue(undefined);
const res = await request(server).get('/api/trips/5/packing').set('Cookie', sessionCookie(1));
const res = await request(server).get(`/api/trips/${tripId}/packing`).set('Cookie', sessionCookie(2));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
});
it('201 on create with permission', async () => {
const res = await request(server).post('/api/trips/5/packing').set('Cookie', sessionCookie(1)).send({ name: 'Socks' });
it('201 on create, inserting the row with the legacy defaults', async () => {
insertItem(tripId, 'Existing', { sort_order: 4 });
const res = await request(server).post(`/api/trips/${tripId}/packing`).set('Cookie', sessionCookie(1)).send({ name: 'Socks' });
expect(res.status).toBe(201);
expect(res.body).toEqual({ item: { id: 9, name: 'Socks' } });
// 'Allgemein' is the legacy createItem category default; quantity clamps to 1.
expect(res.body.item).toMatchObject({ name: 'Socks', checked: 0, category: 'Allgemein', quantity: 1, sort_order: 5, owner_id: 1 });
expect(db.prepare('SELECT name FROM packing_items WHERE id = ?').get(res.body.item.id)).toEqual({ name: 'Socks' });
});
it('403 on create without permission', async () => {
it('403 on create without permission, writing nothing', async () => {
checkPermission.mockReturnValue(false);
const res = await request(server).post('/api/trips/5/packing').set('Cookie', sessionCookie(1)).send({ name: 'Socks' });
const res = await request(server).post(`/api/trips/${tripId}/packing`).set('Cookie', sessionCookie(1)).send({ name: 'X' });
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: 'No permission' });
expect((db.prepare('SELECT COUNT(*) AS n FROM packing_items').get() as { n: number }).n).toBe(0);
});
it('200 on update; bodyKeys gate the sentinel columns, omitted keys stay', async () => {
const id = insertItem(tripId, 'Tent', { category: 'Gear' });
const renamed = await request(server).put(`/api/trips/${tripId}/packing/${id}`).set('Cookie', sessionCookie(1)).send({ name: 'Big tent' });
expect(renamed.status).toBe(200);
expect(renamed.body.item).toMatchObject({ id, name: 'Big tent', category: 'Gear' });
// weight_grams only writes when its key is present in the body.
const weighted = await request(server).put(`/api/trips/${tripId}/packing/${id}`).set('Cookie', sessionCookie(1)).send({ weight_grams: 1200 });
expect(weighted.body.item.weight_grams).toBe(1200);
const untouched = await request(server).put(`/api/trips/${tripId}/packing/${id}`).set('Cookie', sessionCookie(1)).send({ name: 'Still big' });
expect(untouched.body.item.weight_grams).toBe(1200);
});
it('404 on update of a missing item', async () => {
const res = await request(server).put(`/api/trips/${tripId}/packing/9999`).set('Cookie', sessionCookie(1)).send({ name: 'X' });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Item not found' });
});
it('409 with the server row when the x-base-updated-at token is stale (#1135)', async () => {
const id = insertItem(tripId, 'Original');
const res = await request(server)
.put(`/api/trips/${tripId}/packing/${id}`)
.set('Cookie', sessionCookie(1))
.set('x-base-updated-at', '1999-01-01 00:00:00')
.send({ name: 'Mine' });
expect(res.status).toBe(409);
expect(res.body.error).toBe('conflict');
expect(res.body.server.name).toBe('Original');
// The row must NOT have been overwritten.
expect((db.prepare('SELECT name FROM packing_items WHERE id = ?').get(id) as { name: string }).name).toBe('Original');
});
it('200 on delete, removing the row; 404 when already gone', async () => {
const id = insertItem(tripId, 'Gone');
const ok = await request(server).delete(`/api/trips/${tripId}/packing/${id}`).set('Cookie', sessionCookie(1));
expect(ok.status).toBe(200);
expect(ok.body).toEqual({ success: true });
expect(db.prepare('SELECT id FROM packing_items WHERE id = ?').get(id)).toBeUndefined();
const missing = await request(server).delete(`/api/trips/${tripId}/packing/${id}`).set('Cookie', sessionCookie(1));
expect(missing.status).toBe(404);
expect(missing.body).toEqual({ error: 'Item not found' });
});
it('200 on reorder, persisting the new sort_order', async () => {
const a = insertItem(tripId, 'A', { sort_order: 0 });
const b = insertItem(tripId, 'B', { sort_order: 1 });
const res = await request(server).put(`/api/trips/${tripId}/packing/reorder`).set('Cookie', sessionCookie(1)).send({ orderedIds: [b, a] });
expect(res.status).toBe(200);
expect(res.body).toEqual({ success: true });
const rows = db.prepare('SELECT id FROM packing_items WHERE trip_id = ? ORDER BY sort_order').all(tripId) as { id: number }[];
expect(rows.map((r) => r.id)).toEqual([b, a]);
});
it('201 on import, skipping empty names and creating named bags', async () => {
const res = await request(server)
.post(`/api/trips/${tripId}/packing/import`)
.set('Cookie', sessionCookie(1))
.send({ items: [{ name: 'Shirt', bag: 'Carry-On' }, { name: ' ' }, { name: 'Pants', bag: 'Carry-On' }] });
expect(res.status).toBe(201);
expect(res.body.count).toBe(2);
const bags = db.prepare('SELECT * FROM packing_bags WHERE trip_id = ?').all(tripId) as { name: string }[];
expect(bags).toHaveLength(1);
expect(bags[0].name).toBe('Carry-On');
});
it('400 on import with an empty array', async () => {
const res = await request(server).post(`/api/trips/${tripId}/packing/import`).set('Cookie', sessionCookie(1)).send({ items: [] });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'items must be a non-empty array' });
});
it('bags round-trip: 201 create (default color), 200 update (COALESCE), 200 delete, then 404', async () => {
const created = await request(server).post(`/api/trips/${tripId}/packing/bags`).set('Cookie', sessionCookie(1)).send({ name: 'Duffel' });
expect(created.status).toBe(201);
expect(created.body.bag).toMatchObject({ name: 'Duffel', color: '#6366f1' });
const bagId = created.body.bag.id;
const updated = await request(server).put(`/api/trips/${tripId}/packing/bags/${bagId}`).set('Cookie', sessionCookie(1)).send({ color: '#ff0000' });
expect(updated.status).toBe(200);
expect(updated.body.bag).toMatchObject({ name: 'Duffel', color: '#ff0000' });
const deleted = await request(server).delete(`/api/trips/${tripId}/packing/bags/${bagId}`).set('Cookie', sessionCookie(1));
expect(deleted.status).toBe(200);
expect(deleted.body).toEqual({ success: true });
const missing = await request(server).delete(`/api/trips/${tripId}/packing/bags/${bagId}`).set('Cookie', sessionCookie(1));
expect(missing.status).toBe(404);
expect(missing.body).toEqual({ error: 'Bag not found' });
});
it('bag members: sets roster members only, dropping off-trip user ids', async () => {
db.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, 2);
const created = await request(server).post(`/api/trips/${tripId}/packing/bags`).set('Cookie', sessionCookie(1)).send({ name: 'Main' });
const bagId = created.body.bag.id;
const res = await request(server)
.put(`/api/trips/${tripId}/packing/bags/${bagId}/members`)
.set('Cookie', sessionCookie(1))
.send({ user_ids: [1, 2, 999] });
expect(res.status).toBe(200);
expect(res.body.members.map((m: { user_id: number }) => m.user_id).sort()).toEqual([1, 2]);
});
it('apply-template: 200 with the added items; 404 for an empty template', async () => {
const templateId = Number(db.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, 1)').run('Camping').lastInsertRowid);
const catId = Number(db.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, 0)').run(templateId, 'Gear').lastInsertRowid);
db.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, 0)').run(catId, 'Tent');
const ok = await request(server).post(`/api/trips/${tripId}/packing/apply-template/${templateId}`).set('Cookie', sessionCookie(1)).send({});
expect(ok.status).toBe(200); // @HttpCode(200) — the legacy POST returned 200
expect(ok.body.count).toBe(1);
expect(ok.body.items[0]).toMatchObject({ name: 'Tent', category: 'Gear' });
const emptyId = Number(db.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, 1)').run('Empty').lastInsertRowid);
const missing = await request(server).post(`/api/trips/${tripId}/packing/apply-template/${emptyId}`).set('Cookie', sessionCookie(1)).send({});
expect(missing.status).toBe(404);
expect(missing.body).toEqual({ error: 'Template not found or empty' });
});
it('save-as-template: 403 for non-admins, 201 for an admin with items', async () => {
db.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, 3);
insertItem(tripId, 'Shirt', { category: 'Clothes' });
const denied = await request(server).post(`/api/trips/${tripId}/packing/save-as-template`).set('Cookie', sessionCookie(1)).send({ name: 'Tpl' });
expect(denied.status).toBe(403);
expect(denied.body).toEqual({ error: 'Admin access required' });
const saved = await request(server).post(`/api/trips/${tripId}/packing/save-as-template`).set('Cookie', sessionCookie(3)).send({ name: 'Tpl' });
expect(saved.status).toBe(201);
expect(saved.body.template).toMatchObject({ name: 'Tpl', categoryCount: 1, itemCount: 1 });
});
it('category assignees round-trip: PUT replaces, GET groups by category', async () => {
db.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(tripId, 2);
const put = await request(server)
.put(`/api/trips/${tripId}/packing/category-assignees/Clothes`)
.set('Cookie', sessionCookie(1))
.send({ user_ids: [1, 2] });
expect(put.status).toBe(200);
expect(put.body.assignees).toHaveLength(2);
const get = await request(server).get(`/api/trips/${tripId}/packing/category-assignees`).set('Cookie', sessionCookie(1));
expect(get.status).toBe(200);
expect(get.body.assignees.Clothes).toHaveLength(2);
const replaced = await request(server)
.put(`/api/trips/${tripId}/packing/category-assignees/Clothes`)
.set('Cookie', sessionCookie(1))
.send({ user_ids: [2] });
expect(replaced.body.assignees.map((m: { user_id: number }) => m.user_id)).toEqual([2]);
});
});
+6 -1
View File
@@ -25,6 +25,12 @@ const { db } = vi.hoisted(() => {
name TEXT NOT NULL, checked INTEGER NOT NULL DEFAULT 0, category TEXT, sort_order INTEGER NOT NULL DEFAULT 0,
due_date TEXT, description TEXT, assigned_user_id INTEGER, priority INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
// bundle()'s packingItems now runs PackingService's real SQL (DI-injected, no mock).
tmp.exec(`CREATE TABLE packing_items (id INTEGER PRIMARY KEY AUTOINCREMENT, trip_id INTEGER NOT NULL,
name TEXT NOT NULL, checked INTEGER DEFAULT 0, category TEXT, sort_order INTEGER DEFAULT 0,
weight_grams INTEGER, bag_id INTEGER, quantity INTEGER NOT NULL DEFAULT 1,
is_private INTEGER NOT NULL DEFAULT 0, owner_id INTEGER, updated_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP);`);
return { db: tmp };
});
@@ -51,7 +57,6 @@ const { tripSvc } = vi.hoisted(() => ({
vi.mock('../../src/services/tripService', () => tripSvc);
vi.mock('../../src/services/dayService', () => ({ listDays: () => ({ days: [] }), listAccommodations: () => [] }));
vi.mock('../../src/services/placeService', () => ({ listPlaces: () => [] }));
vi.mock('../../src/services/packingService', () => ({ listItems: () => [] }));
vi.mock('../../src/services/budgetService', () => ({ listBudgetItems: () => [] }));
vi.mock('../../src/services/reservationService', () => ({ listReservations: () => [] }));
vi.mock('../../src/services/fileService', () => ({ listFiles: () => [] }));
@@ -4,6 +4,8 @@ import { trekMcpAccessPolicy } from '../../src/mcp/nest-mcp-policy';
import { CategoriesMcp } from '../../src/nest/categories/categories.mcp';
import { CategoriesService } from '../../src/nest/categories/categories.service';
import { DatabaseService } from '../../src/nest/database/database.service';
import { PackingMcp } from '../../src/nest/packing/packing.mcp';
import { PackingService } from '../../src/nest/packing/packing.service';
import { TagsMcp } from '../../src/nest/tags/tags.mcp';
import { TagsService } from '../../src/nest/tags/tags.service';
import { TodoMcp } from '../../src/nest/todo/todo.mcp';
@@ -23,6 +25,7 @@ export function createMcpTestRegistry(): McpRegistry {
new TagsMcp(new TagsService(dbService)),
new CategoriesMcp(new CategoriesService(dbService)),
new TodoMcp(new TodoService(dbService)),
new PackingMcp(new PackingService(dbService)),
],
{ accessPolicy: trekMcpAccessPolicy },
);
+2
View File
@@ -8,6 +8,7 @@ import { ReservationsService } from '../../src/nest/reservations/reservations.se
import { TagsService } from '../../src/nest/tags/tags.service';
import { CategoriesService } from '../../src/nest/categories/categories.service';
import { TodoService } from '../../src/nest/todo/todo.service';
import { PackingService } from '../../src/nest/packing/packing.service';
/**
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
@@ -22,6 +23,7 @@ export function createHostDepsFactory(dbs: DatabaseService): PluginHostDepsFacto
new TagsService(dbs),
new CategoriesService(dbs),
new TodoService(dbs),
new PackingService(dbs),
new PluginOAuthService(dbs),
);
}
+6 -29
View File
@@ -1,9 +1,10 @@
/**
* Unit tests for MCP resources (resources.ts).
* Tests all 12 legacy-registrar resources via InMemoryTransport + Client
* Tests all 10 legacy-registrar resources via InMemoryTransport + Client
* (trek://categories moved to the DI-discovered CategoriesMcp — see
* tools-categories.test.ts; trek://trips/{tripId}/todos moved to TodoMcp —
* see tools-todos.test.ts).
* see tools-todos.test.ts; trek://trips/{tripId}/packing and .../packing/bags
* moved to PackingMcp — see tools-packing.test.ts).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
@@ -42,7 +43,7 @@ vi.mock('../../../src/websocket', () => ({ broadcast: vi.fn() }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, addTripMember, createBudgetItem, createPackingItem, createReservation, createDayNote, createCollabNote, createBucketListItem, createVisitedCountry, createDayAssignment, createDayAccommodation } from '../../helpers/factories';
import { createUser, createTrip, createDay, createPlace, addTripMember, createBudgetItem, createReservation, createDayNote, createCollabNote, createBucketListItem, createVisitedCountry, createDayAssignment, createDayAccommodation } from '../../helpers/factories';
import { createMcpHarness, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
beforeAll(() => {
@@ -237,32 +238,8 @@ describe('Resource: trek://trips/{tripId}/budget', () => {
});
});
describe('Resource: trek://trips/{tripId}/packing', () => {
it('returns packing items for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPackingItem(testDb, trip.id, { name: 'Passport' });
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
const items = parseResourceResult(result) as any[];
expect(items).toHaveLength(1);
expect(items[0].name).toBe('Passport');
});
});
it('returns access denied for unauthorized trip', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (harness) => {
const result = await harness.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
const data = parseResourceResult(result) as any;
expect(data.error).toBeTruthy();
});
});
});
// The trek://trips/{tripId}/packing and .../packing/bags resources moved to the
// DI-discovered PackingMcp — see tools-packing.test.ts.
describe('Resource: trek://trips/{tripId}/reservations', () => {
it('returns reservations for a trip', async () => {
@@ -1,9 +1,10 @@
/**
* Unit tests for MCP packing advanced tools:
* Unit tests for the advanced packing MCP tools (PackingMcp, DI-discovered):
* reorder_packing_items, list_packing_bags, create_packing_bag, update_packing_bag,
* delete_packing_bag, set_bag_members, get_packing_category_assignees,
* set_packing_category_assignees, apply_packing_template, save_packing_template,
* bulk_import_packing.
* bulk_import_packing. The basic item tools + scope/addon gating + resources
* live in tools-packing.test.ts.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
+156 -3
View File
@@ -1,6 +1,14 @@
/**
* Unit tests for MCP packing tools: create_packing_item, update_packing_item,
* toggle_packing_item, delete_packing_item.
* Unit tests for the packing MCP surface (PackingMcp, DI-discovered):
* create_packing_item, update_packing_item, toggle_packing_item,
* delete_packing_item, plus the registration-time scope/addon gating and the
* trek://trips/{tripId}/packing + .../packing/bags resources (moved from the
* legacy registerResources — see resources.test.ts). The advanced tools live
* in tools-packing-advanced.test.ts.
*
* All of it attaches via the nest-mcp registry inside registerTools, so every
* harness here keeps withTools on (the resources are NOT registered by the
* legacy registerResources fan-out anymore).
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
@@ -37,7 +45,8 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createPackingItem } from '../../helpers/factories';
import { createMcpHarness, parseToolResult, type McpHarness } from '../../helpers/mcp-harness';
import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness';
import { ADDON_IDS } from '../../../src/addons';
beforeAll(() => {
createTables(testDb);
@@ -285,3 +294,147 @@ describe('Tool: delete_packing_item', () => {
});
});
});
// ---------------------------------------------------------------------------
// Scope gating (packing read/write, registration-time)
// ---------------------------------------------------------------------------
describe('Packing tools — scope gating', () => {
const READ_TOOLS = ['list_packing_bags', 'get_packing_category_assignees', 'list_packing_templates'];
const WRITE_TOOLS = [
'create_packing_item', 'toggle_packing_item', 'delete_packing_item', 'update_packing_item',
'reorder_packing_items', 'create_packing_bag', 'update_packing_bag', 'delete_packing_bag',
'set_bag_members', 'set_packing_category_assignees', 'apply_packing_template',
'save_packing_template', 'delete_packing_template', 'bulk_import_packing',
];
async function listToolNames(userId: number, scopes: string[] | null): Promise<string[]> {
const h = await createMcpHarness({ userId, withResources: false, scopes });
try {
return (await h.client.listTools()).tools.map((t) => t.name);
} finally {
await h.cleanup();
}
}
it('registers all seventeen tools with null scopes (full access)', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, null);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).toContain(tool);
});
it('registers only the read tools with packing:read', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['packing:read']);
for (const tool of READ_TOOLS) expect(names).toContain(tool);
for (const tool of WRITE_TOOLS) expect(names).not.toContain(tool);
});
it('registers no packing tools for an unrelated scope', async () => {
const { user } = createUser(testDb);
const names = await listToolNames(user.id, ['budget:read']);
for (const tool of [...READ_TOOLS, ...WRITE_TOOLS]) expect(names).not.toContain(tool);
});
});
// ---------------------------------------------------------------------------
// Addon gating (packing addon, the legacy whole-registrar early return —
// now the `when` predicate on every PackingMcp entry)
// ---------------------------------------------------------------------------
describe('Packing tools — packing addon gating', () => {
it('registers nothing (tools or resources) when the packing addon is disabled', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('UPDATE addons SET enabled = 0 WHERE id = ?').run(ADDON_IDS.PACKING);
try {
await withHarness(user.id, async (h) => {
const names = (await h.client.listTools()).tools.map((t) => t.name);
expect(names).not.toContain('create_packing_item');
expect(names).not.toContain('list_packing_bags');
await expect(h.client.readResource({ uri: `trek://trips/${trip.id}/packing` })).rejects.toThrow();
await expect(h.client.readResource({ uri: `trek://trips/${trip.id}/packing/bags` })).rejects.toThrow();
});
} finally {
testDb.prepare('UPDATE addons SET enabled = 1 WHERE id = ?').run(ADDON_IDS.PACKING);
}
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/packing resource (moved from the legacy registerResources)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/packing', () => {
it('returns packing items for a trip', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
createPackingItem(testDb, trip.id, { name: 'Passport' });
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
const items = parseResourceResult(result) as { name: string }[];
expect(items).toHaveLength(1);
expect(items[0].name).toBe('Passport');
});
});
it('hides another member\'s private items from the requesting user (#858)', async () => {
const { user } = createUser(testDb);
const { user: owner } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order, is_private, owner_id) VALUES (?, ?, 0, 0, 1, ?)')
.run(trip.id, 'Secret gift', owner.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
expect(parseResourceResult(result)).toEqual([]);
});
});
it('returns the access-denied payload for a non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing` });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
it('returns the access-denied payload for a malformed trip id', async () => {
const { user } = createUser(testDb);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: 'trek://trips/not-a-number/packing' });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
});
// ---------------------------------------------------------------------------
// trek://trips/{tripId}/packing/bags resource (moved from the legacy registerResources)
// ---------------------------------------------------------------------------
describe('Resource: trek://trips/{tripId}/packing/bags', () => {
it('returns the bags with their members', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bagId = Number(testDb.prepare('INSERT INTO packing_bags (trip_id, name) VALUES (?, ?)').run(trip.id, 'Carry-On').lastInsertRowid);
testDb.prepare('INSERT INTO packing_bag_members (bag_id, user_id) VALUES (?, ?)').run(bagId, user.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing/bags` });
const bags = parseResourceResult(result) as { name: string; members: { user_id: number }[] }[];
expect(bags).toHaveLength(1);
expect(bags[0].name).toBe('Carry-On');
expect(bags[0].members.map((m) => m.user_id)).toEqual([user.id]);
});
});
it('returns the access-denied payload for a non-member', async () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, other.id);
await withHarness(user.id, async (h) => {
const result = await h.client.readResource({ uri: `trek://trips/${trip.id}/packing/bags` });
expect(parseResourceResult(result)).toEqual({ error: 'Trip not found or access denied' });
});
});
});
+664 -130
View File
@@ -1,150 +1,684 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
/**
* Unit tests for the DI-native PackingService — PACK-SVC-001 through
* PACK-SVC-049 moved 1:1 from the legacy tests/unit/services/packingService.test.ts
* (real in-memory SQLite so the SQL logic is exercised faithfully), plus the
* wrapper-helper cases (canEdit, the #858 broadcast scoping, getItemPrivacy,
* notifyTagged) carried over from the old delegation suite — now running
* against real SQL — and PACK-SVC-050 pinning the packing.bridge delegation.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
const { dbMock } = vi.hoisted(() => {
const stmt = { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() };
return { dbMock: { prepare: vi.fn(() => stmt), _stmt: stmt } };
// ── DB setup ──────────────────────────────────────────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: (tripId: any, userId: number) =>
db.prepare(`
SELECT t.id, t.user_id FROM trips t
LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ?
WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL)
`).get(userId, tripId, userId),
isOwner: (tripId: any, userId: number) =>
!!db.prepare('SELECT id FROM trips WHERE id = ? AND user_id = ?').get(tripId, userId),
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => ({ db: dbMock, closeDb: () => {}, reinitialize: () => {} }));
import { db as dbConn } from '../../../src/db/database';
import { DatabaseService } from '../../../src/nest/database/database.service';
const { broadcast } = vi.hoisted(() => ({ broadcast: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast }));
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
const { broadcastMock } = vi.hoisted(() => ({ broadcastMock: vi.fn() }));
vi.mock('../../../src/websocket', () => ({ broadcast: broadcastMock }));
const { checkPermission } = vi.hoisted(() => ({ checkPermission: vi.fn(() => true) }));
vi.mock('../../../src/services/permissions', () => ({ checkPermission }));
const { pk } = vi.hoisted(() => ({
pk: {
verifyTripAccess: vi.fn(), listItems: vi.fn(), createItem: vi.fn(), updateItem: vi.fn(), deleteItem: vi.fn(),
bulkImport: vi.fn(), listBags: vi.fn(), createBag: vi.fn(), updateBag: vi.fn(), deleteBag: vi.fn(),
listTemplates: vi.fn(), applyTemplate: vi.fn(), saveAsTemplate: vi.fn(), setBagMembers: vi.fn(), getCategoryAssignees: vi.fn(),
updateCategoryAssignees: vi.fn(), reorderItems: vi.fn(),
setItemSharing: vi.fn(), addContributor: vi.fn(), removeContributor: vi.fn(), cloneItem: vi.fn(),
},
}));
vi.mock('../../../src/services/packingService', () => pk);
const { send } = vi.hoisted(() => ({ send: vi.fn(() => Promise.resolve()) }));
vi.mock('../../../src/services/notificationService', () => ({ send }));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PackingService } from '../../../src/nest/packing/packing.service';
import { listItems as bridgeListItems } from '../../../src/nest/packing/packing.bridge';
function svc() {
return new PackingService(new DatabaseService(dbConn));
}
const svc = new PackingService(new DatabaseService(testDb));
beforeEach(() => vi.clearAllMocks());
// ── Lifecycle ─────────────────────────────────────────────────────────────────
describe('PackingService (wrapper delegation + helpers)', () => {
it('canEdit delegates to checkPermission with packing_edit', () => {
svc().canEdit({ user_id: 2 } as never, { id: 1, role: 'user' } as never);
expect(checkPermission).toHaveBeenCalledWith('packing_edit', 'user', 2, 1, true);
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
vi.clearAllMocks();
});
afterAll(() => {
testDb.close();
});
// ── saveAsTemplate ────────────────────────────────────────────────────────────
describe('saveAsTemplate', () => {
it('PACK-SVC-001: saves packing items as a template with correct categories and item count', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shirt', 'Clothes', 0);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shorts', 'Clothes', 1);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Toothbrush', 'Toiletries', 2);
const result = svc.saveAsTemplate(trip.id, user.id, 'My Template');
expect(result).not.toBeNull();
expect(result!.name).toBe('My Template');
expect(result!.categoryCount).toBe(2);
expect(result!.itemCount).toBe(3);
const template = testDb.prepare('SELECT * FROM packing_templates WHERE id = ?').get(result!.id) as any;
expect(template).toBeDefined();
expect(template.name).toBe('My Template');
expect(template.created_by).toBe(user.id);
});
it('broadcast forwards to the websocket helper', () => {
svc().broadcast('5', 'packing:created', { item: 1 }, 'sock');
expect(broadcast).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock');
});
it('PACK-SVC-002: returns null when trip has no packing items', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
describe('broadcastItem (private-item scoping, #858)', () => {
it('broadcasts a shared item to the whole room (no onlyUserId)', () => {
svc().broadcastItem('5', 'packing:created', { item: 1 }, { is_private: 0, owner_id: 7 }, 'sock');
expect(broadcast).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', undefined);
});
const result = svc.saveAsTemplate(trip.id, user.id, 'Empty');
it('scopes a private item to its owner', () => {
svc().broadcastItem('5', 'packing:created', { item: 1 }, { is_private: 1, owner_id: 7 }, 'sock');
expect(broadcast).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', 7);
});
it('falls back to a room broadcast when the private item has no owner', () => {
svc().broadcastItem('5', 'packing:created', { item: 1 }, { is_private: 1, owner_id: null }, 'sock');
expect(broadcast).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', undefined);
});
});
it('getItemPrivacy reads the privacy fields for an item', () => {
dbMock._stmt.get.mockReturnValueOnce({ is_private: 1, owner_id: 3 });
expect(svc().getItemPrivacy('5', '9')).toEqual({ is_private: 1, owner_id: 3 });
expect(dbMock.prepare).toHaveBeenCalledWith(expect.stringContaining('is_private, owner_id'));
});
it('forwards every item/bag/template/assignee call to the legacy service', () => {
const s = svc();
s.verifyTripAccess('5', 1); expect(pk.verifyTripAccess).toHaveBeenCalledWith('5', 1);
s.listItems('5'); expect(pk.listItems).toHaveBeenCalledWith('5', undefined);
s.createItem('5', { name: 'a' }); expect(pk.createItem).toHaveBeenCalledWith('5', { name: 'a' }, undefined);
s.updateItem('5', '2', { name: 'b' } as never, ['name']); expect(pk.updateItem).toHaveBeenCalledWith('5', '2', { name: 'b' }, ['name'], undefined, undefined);
s.deleteItem('5', '2'); expect(pk.deleteItem).toHaveBeenCalledWith('5', '2');
s.bulkImport('5', [{ name: 'x' }] as never); expect(pk.bulkImport).toHaveBeenCalledWith('5', [{ name: 'x' }], undefined);
s.reorderItems('5', [3, 1] as never); expect(pk.reorderItems).toHaveBeenCalledWith('5', [3, 1]);
s.listBags('5'); expect(pk.listBags).toHaveBeenCalledWith('5');
s.createBag('5', { name: 'Bag' }); expect(pk.createBag).toHaveBeenCalledWith('5', { name: 'Bag' });
s.updateBag('5', '2', { name: 'B' } as never, ['name']); expect(pk.updateBag).toHaveBeenCalledWith('5', '2', { name: 'B' }, ['name']);
s.deleteBag('5', '2'); expect(pk.deleteBag).toHaveBeenCalledWith('5', '2');
s.setBagMembers('5', '2', [1, 2]); expect(pk.setBagMembers).toHaveBeenCalledWith('5', '2', [1, 2]);
s.listTemplates(); expect(pk.listTemplates).toHaveBeenCalled();
s.applyTemplate('5', 't1', 'personal', 1); expect(pk.applyTemplate).toHaveBeenCalledWith('5', 't1', 'personal', 1);
s.saveAsTemplate('5', 1, 'Tpl'); expect(pk.saveAsTemplate).toHaveBeenCalledWith('5', 1, 'Tpl');
s.getCategoryAssignees('5'); expect(pk.getCategoryAssignees).toHaveBeenCalledWith('5');
s.updateCategoryAssignees('5', 'Clothes', [2]); expect(pk.updateCategoryAssignees).toHaveBeenCalledWith('5', 'Clothes', [2]);
s.setItemSharing('5', '2', 1, 'shared', [3]); expect(pk.setItemSharing).toHaveBeenCalledWith('5', '2', 1, 'shared', [3]);
s.addContributor('5', '2', 3); expect(pk.addContributor).toHaveBeenCalledWith('5', '2', 3);
s.removeContributor('5', '2', 3); expect(pk.removeContributor).toHaveBeenCalledWith('5', '2', 3);
s.cloneItem('5', '2', 7); expect(pk.cloneItem).toHaveBeenCalledWith('5', '2', 7);
});
describe('viewersOf + broadcastToViewers (#858 three-tier)', () => {
it('viewersOf: Common → null (whole room); restricted → owner + recipients', () => {
expect(svc().viewersOf({ is_private: 0, owner_id: 1 })).toBeNull();
expect(svc().viewersOf(null)).toBeNull();
expect(svc().viewersOf({ is_private: 1, owner_id: 1, recipients: [{ user_id: 2 }, { user_id: 3 }] })).toEqual([1, 2, 3]);
});
it('broadcastToViewers delivers to each viewer (deduped) via onlyUserId', () => {
svc().broadcastToViewers('5', 'packing:created', { item: 1 }, [1, 2, 2], 'sock');
expect(broadcast).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', 1);
expect(broadcast).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', 2);
expect(broadcast).toHaveBeenCalledTimes(2);
});
});
describe('notifyTagged', () => {
it('does nothing when no users are tagged', () => {
svc().notifyTagged('5', { id: 1, email: 'a@b.c' } as never, 'Clothes', []);
svc().notifyTagged('5', { id: 1, email: 'a@b.c' } as never, 'Clothes', 'nope');
expect(dbMock.prepare).not.toHaveBeenCalled();
});
it('fires the notification when users are tagged (fire-and-forget, no throw)', () => {
expect(() => svc().notifyTagged('5', { id: 1, email: 'a@b.c' } as never, 'Clothes', [2, 3])).not.toThrow();
});
it('queries the trip title and dispatches the notification with the resolved title', async () => {
dbMock._stmt.get.mockReturnValue({ title: 'Iceland 2026' });
svc().notifyTagged('5', { id: 1, email: 'a@b.c' } as never, 'Clothes', [2, 3]);
// Flush the dynamic import().then microtask chain.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(dbMock.prepare).toHaveBeenCalledWith('SELECT title FROM trips WHERE id = ?');
expect(send).toHaveBeenCalledWith(
expect.objectContaining({
event: 'packing_tagged',
actorId: 1,
scope: 'trip',
targetId: 5,
params: expect.objectContaining({ trip: 'Iceland 2026', actor: 'a@b.c', category: 'Clothes', tripId: '5' }),
}),
);
});
it('falls back to "Untitled" when the trip row is missing (?? / default branch)', async () => {
dbMock._stmt.get.mockReturnValue(undefined);
svc().notifyTagged('5', { id: 1, email: 'a@b.c' } as never, 'Clothes', [2]);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(send).toHaveBeenCalledWith(
expect.objectContaining({ params: expect.objectContaining({ trip: 'Untitled' }) }),
);
});
expect(result).toBeNull();
});
});
// ── listTemplates ───────────────────────────────────────────────────────────────
describe('listTemplates', () => {
it('PACK-SVC-LIST-001: returns templates with id, name and item_count', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shirt', 'Clothes', 0);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Toothbrush', 'Toiletries', 1);
const saved = svc.saveAsTemplate(trip.id, user.id, 'Weekend');
const templates = svc.listTemplates();
expect(templates).toHaveLength(1);
expect(templates[0]).toMatchObject({ id: saved!.id, name: 'Weekend', item_count: 2 });
});
it('PACK-SVC-LIST-002: returns an empty array when no templates exist', () => {
expect(svc.listTemplates()).toEqual([]);
});
});
// ── applyTemplate ─────────────────────────────────────────────────────────────
/** A one-category template with the given item names. Returns its id. */
function seedTemplate(userId: number, itemNames: string[]): number {
const templateId = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Camping', userId).lastInsertRowid as number;
const catId = testDb.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, 'Gear', 0).lastInsertRowid as number;
itemNames.forEach((name, i) => {
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, name, i);
});
return templateId;
}
describe('applyTemplate', () => {
it('PACK-SVC-003: adds template items to a trip packing list', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Insert a template with one category and two items directly
const templateResult = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Camping', user.id);
const templateId = templateResult.lastInsertRowid as number;
const catResult = testDb.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, 'Gear', 0);
const catId = catResult.lastInsertRowid as number;
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, 'Tent', 0);
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, 'Sleeping Bag', 1);
const result = svc.applyTemplate(trip.id, templateId);
expect(result).not.toBeNull();
expect(Array.isArray(result)).toBe(true);
expect((result as any[]).length).toBe(2);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items.length).toBe(2);
expect(items.map((i: any) => i.name)).toContain('Tent');
expect(items.map((i: any) => i.name)).toContain('Sleeping Bag');
});
it('PACK-SVC-004: returns null when template has no items', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateResult = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Empty Template', user.id);
const templateId = templateResult.lastInsertRowid as number;
const result = svc.applyTemplate(trip.id, templateId);
expect(result).toBeNull();
});
// #1565: the applied items must land in the view the user is on, not always Common.
it('PACK-SVC-046: applies into the personal list when visibility is personal', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
const result = svc.applyTemplate(trip.id, templateId, 'personal', user.id) as any[];
expect(result[0].is_private).toBe(1);
expect(result[0].owner_id).toBe(user.id);
expect(svc.listItems(trip.id, user.id).filter((i: any) => i.is_private)).toHaveLength(1);
});
it('PACK-SVC-047: a personally applied template stays hidden from other members', () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(trip.id, other.id);
const templateId = seedTemplate(user.id, ['Tent']);
svc.applyTemplate(trip.id, templateId, 'personal', user.id);
expect(svc.listItems(trip.id, other.id)).toHaveLength(0);
});
it('PACK-SVC-048: applies into the common pool by default, leaving items unowned', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
const result = svc.applyTemplate(trip.id, templateId, 'common', user.id) as any[];
expect(result[0].is_private).toBe(0);
// Unowned, so any member may still re-share it (setItemSharing claims a null owner).
expect(result[0].owner_id).toBeNull();
});
it('PACK-SVC-049: falls back to common when no owner is given, so items stay visible', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
// A private item with no owner would be invisible to everyone.
const result = svc.applyTemplate(trip.id, templateId, 'personal') as any[];
expect(result[0].is_private).toBe(0);
expect(svc.listItems(trip.id, user.id)).toHaveLength(1);
});
});
// ── createBag / deleteBag ─────────────────────────────────────────────────────
describe('createBag / deleteBag', () => {
it('PACK-SVC-005: createBag inserts a bag and returns it', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = svc.createBag(trip.id, { name: 'Carry-On', color: '#ff0000' }) as any;
expect(result).not.toBeNull();
expect(result.name).toBe('Carry-On');
expect(result.color).toBe('#ff0000');
expect(result.trip_id).toBe(trip.id);
const bag = testDb.prepare('SELECT * FROM packing_bags WHERE id = ?').get(result.id) as any;
expect(bag).toBeDefined();
expect(bag.name).toBe('Carry-On');
});
it('PACK-SVC-006: deleteBag removes the bag and returns true', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = svc.createBag(trip.id, { name: 'Checked Bag' }) as any;
expect(bag).not.toBeNull();
const deleted = svc.deleteBag(trip.id, bag.id);
expect(deleted).toBe(true);
const row = testDb.prepare('SELECT * FROM packing_bags WHERE id = ?').get(bag.id);
expect(row).toBeUndefined();
});
it('PACK-SVC-007: deleteBag returns false for non-existent bag', () => {
const result = svc.deleteBag(1, 99999);
expect(result).toBe(false);
});
});
// ── setBagMembers ─────────────────────────────────────────────────────────────
describe('setBagMembers', () => {
it('PACK-SVC-008: sets bag members (replaces existing)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = svc.createBag(trip.id, { name: 'Main Bag' }) as any;
const result = svc.setBagMembers(trip.id, bag.id, [user.id]) as any[];
expect(result).not.toBeNull();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(1);
expect(result[0].user_id).toBe(user.id);
});
it('PACK-SVC-009: setBagMembers with empty array clears all members', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = svc.createBag(trip.id, { name: 'Main Bag' }) as any;
// First add a member
svc.setBagMembers(trip.id, bag.id, [user.id]);
// Then clear
const result = svc.setBagMembers(trip.id, bag.id, []) as any[];
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(0);
});
it('PACK-SVC-010: setBagMembers returns null for non-existent bag', () => {
const result = svc.setBagMembers(1, 99999, []);
expect(result).toBeNull();
});
it('PACK-SVC-010a: setBagMembers drops a user who is not on the trip roster', () => {
const { user } = createUser(testDb);
const outsider = createUser(testDb).user;
const trip = createTrip(testDb, user.id);
const bag = svc.createBag(trip.id, { name: 'Main Bag' }) as any;
// owner is on the roster; the outsider (not owner, not a member) must be filtered out
const result = svc.setBagMembers(trip.id, bag.id, [user.id, outsider.id]) as any[];
const ids = result.map((m) => m.user_id);
expect(ids).toContain(user.id);
expect(ids).not.toContain(outsider.id);
});
it('PACK-SVC-010b: updateBag ignores an off-roster user_id, leaving the bag unassigned', () => {
const { user } = createUser(testDb);
const outsider = createUser(testDb).user;
const trip = createTrip(testDb, user.id);
const bag = svc.createBag(trip.id, { name: 'Main Bag' }) as any;
// assigning to an outsider must not stick — the CASE keeps user_id null
svc.updateBag(trip.id, bag.id, { user_id: outsider.id }, ['user_id']);
const stored = testDb.prepare('SELECT user_id FROM packing_bags WHERE id = ?').get(bag.id) as { user_id: number | null };
expect(stored.user_id).toBeNull();
// assigning to the owner (on the roster) does stick
svc.updateBag(trip.id, bag.id, { user_id: user.id }, ['user_id']);
const stored2 = testDb.prepare('SELECT user_id FROM packing_bags WHERE id = ?').get(bag.id) as { user_id: number | null };
expect(stored2.user_id).toBe(user.id);
});
});
// ── bulkImport with bag field ─────────────────────────────────────────────────
describe('bulkImport with bag field', () => {
it('PACK-SVC-011: bulk import with bag field creates the bag if it does not exist', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = svc.bulkImport(trip.id, [{ name: 'Shirt', bag: 'Carry-On' }]);
expect(result).toHaveLength(1);
expect(result[0]).toBeDefined();
const bags = testDb.prepare('SELECT * FROM packing_bags WHERE trip_id = ? AND name = ?').all(trip.id, 'Carry-On') as any[];
expect(bags).toHaveLength(1);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items).toHaveLength(1);
expect(items[0].bag_id).toBe(bags[0].id);
});
it('PACK-SVC-012: bulk import with same bag name reuses existing bag', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = svc.bulkImport(trip.id, [
{ name: 'Shirt', bag: 'Carry-On' },
{ name: 'Pants', bag: 'Carry-On' },
]);
expect(result).toHaveLength(2);
const bags = testDb.prepare('SELECT * FROM packing_bags WHERE trip_id = ? AND name = ?').all(trip.id, 'Carry-On') as any[];
expect(bags).toHaveLength(1);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items).toHaveLength(2);
expect(items[0].bag_id).toBe(bags[0].id);
expect(items[1].bag_id).toBe(bags[0].id);
});
});
// ── bulkImport with quantity field ────────────────────────────────────────────
describe('bulkImport with quantity field', () => {
it('PACK-SVC-013: bulk import respects per-item quantity, defaults to 1, and clamps out-of-range', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
svc.bulkImport(trip.id, [
{ name: 'Socks', quantity: 5 },
{ name: 'Toothbrush' },
{ name: 'Batteries', quantity: 9999 },
{ name: 'Charger', quantity: 0 },
]);
const byName = (n: string) =>
testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ? AND name = ?').get(trip.id, n) as any;
expect(byName('Socks').quantity).toBe(5);
expect(byName('Toothbrush').quantity).toBe(1);
expect(byName('Batteries').quantity).toBe(999);
expect(byName('Charger').quantity).toBe(1);
});
});
// ── Private items (#858) ──────────────────────────────────────────────────────
describe('private items (#858)', () => {
it('PACK-SVC-014: createItem stamps the owner and is_private flag', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const shared = svc.createItem(trip.id, { name: 'Tent' }, user.id) as any;
const secret = svc.createItem(trip.id, { name: 'Gift', is_private: true }, user.id) as any;
expect(shared.is_private).toBe(0);
expect(shared.owner_id).toBe(user.id);
expect(secret.is_private).toBe(1);
expect(secret.owner_id).toBe(user.id);
});
it('PACK-SVC-015: listItems hides another member\'s private items but shows the owner theirs', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
svc.createItem(trip.id, { name: 'Shared' }, owner.id);
svc.createItem(trip.id, { name: 'Private', is_private: true }, owner.id);
const ownerView = svc.listItems(trip.id, owner.id) as any[];
const otherView = svc.listItems(trip.id, other.id) as any[];
const unscoped = svc.listItems(trip.id) as any[];
expect(ownerView.map(i => i.name).sort()).toEqual(['Private', 'Shared']);
expect(otherView.map(i => i.name)).toEqual(['Shared']);
// Without a viewer (internal callers) nothing is filtered.
expect(unscoped).toHaveLength(2);
});
it('PACK-SVC-016: updateItem toggles privacy and claims an unowned item for the actor', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Legacy-style row with no owner.
const id = Number((testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order) VALUES (?, ?, 0, 0)').run(trip.id, 'Legacy') as any).lastInsertRowid);
const updated = svc.updateItem(trip.id, id, { is_private: true }, ['is_private'], undefined, user.id) as any;
expect(updated.is_private).toBe(1);
expect(updated.owner_id).toBe(user.id);
const back = svc.updateItem(trip.id, id, { is_private: false }, ['is_private'], undefined, user.id) as any;
expect(back.is_private).toBe(0);
// Ownership is retained once claimed.
expect(back.owner_id).toBe(user.id);
});
it('PACK-SVC-017: deleteItem returns the removed row (with privacy fields)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = svc.createItem(trip.id, { name: 'Private', is_private: true }, user.id) as any;
const deleted = svc.deleteItem(trip.id, item.id) as any;
expect(deleted).not.toBeNull();
expect(deleted.is_private).toBe(1);
expect(deleted.owner_id).toBe(user.id);
expect(svc.deleteItem(trip.id, item.id)).toBeNull();
});
it('PACK-SVC-018: bulkImport stamps the owner on every item', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
svc.bulkImport(trip.id, [{ name: 'A' }, { name: 'B', is_private: true }], user.id);
const rows = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ? ORDER BY name').all(trip.id) as any[];
expect(rows.every(r => r.owner_id === user.id)).toBe(true);
expect(rows.find(r => r.name === 'B').is_private).toBe(1);
expect(rows.find(r => r.name === 'A').is_private).toBe(0);
});
});
// ── Three-tier sharing (#858 follow-up) ───────────────────────────────────────
describe('three-tier packing sharing (#858)', () => {
const names = (rows: any[]) => rows.map(r => r.name).sort();
it('PACK-SVC-040: existing/common items are visible to everyone (non-breaking)', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
// A legacy-style row written directly (is_private defaults 0) = Common.
testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order) VALUES (?, ?, 0, 0)').run(trip.id, 'Tent');
svc.createItem(trip.id, { name: 'Stove', visibility: 'common' }, owner.id);
expect(names(svc.listItems(trip.id, owner.id) as any[])).toEqual(['Stove', 'Tent']);
expect(names(svc.listItems(trip.id, other.id) as any[])).toEqual(['Stove', 'Tent']);
});
it('PACK-SVC-041: a Shared item is visible to its owner + recipients only, marked with the bringer', () => {
const { user: owner } = createUser(testDb);
const { user: friend } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const item = svc.createItem(trip.id, { name: 'Power bank', visibility: 'shared', recipient_ids: [friend.id] }, owner.id) as any;
expect(item.is_private).toBe(1);
expect(item.owner_username).toBe(owner.username);
expect(item.recipients.map((r: any) => r.user_id)).toEqual([friend.id]);
expect(names(svc.listItems(trip.id, owner.id) as any[])).toEqual(['Power bank']); // bringer
expect(names(svc.listItems(trip.id, friend.id) as any[])).toEqual(['Power bank']); // covered person
expect(names(svc.listItems(trip.id, stranger.id) as any[])).toEqual([]); // nobody else
});
it('PACK-SVC-042: a Personal item is visible only to its owner', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
svc.createItem(trip.id, { name: 'Diary', visibility: 'personal' }, owner.id);
expect(names(svc.listItems(trip.id, owner.id) as any[])).toEqual(['Diary']);
expect(names(svc.listItems(trip.id, other.id) as any[])).toEqual([]);
});
it('PACK-SVC-043: setItemSharing changes the tier + recipients; only the owner may', () => {
const { user: owner } = createUser(testDb);
const { user: friend } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const item = svc.createItem(trip.id, { name: 'First aid', visibility: 'personal' }, owner.id) as any;
// A non-owner is rejected.
expect((svc.setItemSharing(trip.id, item.id, friend.id, 'shared', [friend.id]) as any).forbidden).toBe(true);
const updated = svc.setItemSharing(trip.id, item.id, owner.id, 'shared', [friend.id]) as any;
expect(updated.recipients.map((r: any) => r.user_id)).toEqual([friend.id]);
expect(names(svc.listItems(trip.id, friend.id) as any[])).toEqual(['First aid']);
// Back to common → visible to everyone, recipients cleared.
svc.setItemSharing(trip.id, item.id, owner.id, 'common', []);
const { user: stranger } = createUser(testDb);
expect(names(svc.listItems(trip.id, stranger.id) as any[])).toEqual(['First aid']);
});
it('PACK-SVC-044: contributors ("I can bring that too") only attach to Common items', () => {
const { user: owner } = createUser(testDb);
const { user: helper } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const common = svc.createItem(trip.id, { name: 'Sunscreen', visibility: 'common' }, owner.id) as any;
const personal = svc.createItem(trip.id, { name: 'Meds', visibility: 'personal' }, owner.id) as any;
const withHelper = svc.addContributor(trip.id, common.id, helper.id) as any;
expect(withHelper.contributors.map((c: any) => c.user_id)).toEqual([helper.id]);
// The bringer can't co-contribute to their own item, and personal items have no pool.
expect(svc.addContributor(trip.id, common.id, owner.id)).toBeNull();
expect(svc.addContributor(trip.id, personal.id, helper.id)).toBeNull();
const cleared = svc.removeContributor(trip.id, common.id, helper.id) as any;
expect(cleared.contributors).toEqual([]);
});
it('PACK-SVC-045: cloneItem copies an item onto the cloner\'s personal list', () => {
const { user: owner } = createUser(testDb);
const { user: cloner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const common = svc.createItem(trip.id, { name: 'Travel adapter', category: 'Electronics', visibility: 'common' }, owner.id) as any;
const clone = svc.cloneItem(trip.id, common.id, cloner.id) as any;
expect(clone.name).toBe('Travel adapter');
expect(clone.category).toBe('Electronics');
expect(clone.is_private).toBe(1);
expect(clone.owner_id).toBe(cloner.id);
// The clone is the cloner's alone.
expect(names(svc.listItems(trip.id, owner.id) as any[])).toEqual(['Travel adapter']); // owner sees only the common one
expect(names(svc.listItems(trip.id, cloner.id) as any[])).toEqual(['Travel adapter', 'Travel adapter']); // common + own clone
});
});
// ── Wrapper helpers (carried over from the old delegation suite) ──────────────
describe('canEdit', () => {
it('delegates to checkPermission with packing_edit', () => {
svc.canEdit({ user_id: 2 } as never, { id: 1, role: 'user' } as never);
expect(checkPermission).toHaveBeenCalledWith('packing_edit', 'user', 2, 1, true);
});
});
describe('broadcast helpers (#858 scoping)', () => {
it('broadcast forwards to the websocket helper', () => {
svc.broadcast('5', 'packing:created', { item: 1 }, 'sock');
expect(broadcastMock).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock');
});
it('broadcastItem broadcasts a shared item to the whole room (no onlyUserId)', () => {
svc.broadcastItem('5', 'packing:created', { item: 1 }, { is_private: 0, owner_id: 7 }, 'sock');
expect(broadcastMock).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', undefined);
});
it('broadcastItem scopes a private item to its owner', () => {
svc.broadcastItem('5', 'packing:created', { item: 1 }, { is_private: 1, owner_id: 7 }, 'sock');
expect(broadcastMock).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', 7);
});
it('broadcastItem falls back to a room broadcast when the private item has no owner', () => {
svc.broadcastItem('5', 'packing:created', { item: 1 }, { is_private: 1, owner_id: null }, 'sock');
expect(broadcastMock).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', undefined);
});
it('viewersOf: Common → null (whole room); restricted → owner + recipients', () => {
expect(svc.viewersOf({ is_private: 0, owner_id: 1 })).toBeNull();
expect(svc.viewersOf(null)).toBeNull();
expect(svc.viewersOf({ is_private: 1, owner_id: 1, recipients: [{ user_id: 2 }, { user_id: 3 }] })).toEqual([1, 2, 3]);
});
it('broadcastToViewers delivers to each viewer (deduped) via onlyUserId', () => {
svc.broadcastToViewers('5', 'packing:created', { item: 1 }, [1, 2, 2], 'sock');
expect(broadcastMock).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', 1);
expect(broadcastMock).toHaveBeenCalledWith('5', 'packing:created', { item: 1 }, 'sock', 2);
expect(broadcastMock).toHaveBeenCalledTimes(2);
});
});
describe('getItemPrivacy', () => {
it('reads the privacy fields for an item (real SQL)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = svc.createItem(trip.id, { name: 'Gift', is_private: true }, user.id) as any;
expect(svc.getItemPrivacy(trip.id, item.id)).toEqual({ is_private: 1, owner_id: user.id });
expect(svc.getItemPrivacy(trip.id, 99999)).toBeUndefined();
});
});
describe('notifyTagged', () => {
it('does nothing when no users are tagged', async () => {
svc.notifyTagged('5', { id: 1, email: 'a@b.c' } as never, 'Clothes', []);
svc.notifyTagged('5', { id: 1, email: 'a@b.c' } as never, 'Clothes', 'nope');
await new Promise((resolve) => setTimeout(resolve, 0));
expect(send).not.toHaveBeenCalled();
});
it('queries the trip title and dispatches the notification with the resolved title', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const { title } = testDb.prepare('SELECT title FROM trips WHERE id = ?').get(trip.id) as { title: string };
svc.notifyTagged(String(trip.id), { id: 1, email: 'a@b.c' } as never, 'Clothes', [2, 3]);
// Flush the dynamic import().then microtask chain.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(send).toHaveBeenCalledWith(
expect.objectContaining({
event: 'packing_tagged',
actorId: 1,
scope: 'trip',
targetId: trip.id,
params: expect.objectContaining({ trip: title, actor: 'a@b.c', category: 'Clothes', tripId: String(trip.id) }),
}),
);
});
it('falls back to "Untitled" when the trip row is missing (?? / default branch)', async () => {
svc.notifyTagged('999999', { id: 1, email: 'a@b.c' } as never, 'Clothes', [2]);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(send).toHaveBeenCalledWith(
expect.objectContaining({ params: expect.objectContaining({ trip: 'Untitled' }) }),
);
});
});
// ── Bridge delegation ─────────────────────────────────────────────────────────
describe('packing.bridge', () => {
it('PACK-SVC-050: listItems delegates to PackingService over the shared db Proxy', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
svc.createItem(trip.id, { name: 'Shared' }, owner.id);
svc.createItem(trip.id, { name: 'Private', is_private: true }, owner.id);
// Unscoped (internal callers) — unfiltered; viewer-scoped — #858 filtering applies.
expect((bridgeListItems(trip.id) as { name: string }[]).map(i => i.name).sort()).toEqual(['Private', 'Shared']);
expect((bridgeListItems(trip.id, other.id) as { name: string }[]).map(i => i.name)).toEqual(['Shared']);
});
});
+3 -2
View File
@@ -27,7 +27,6 @@ const { tripSvc } = vi.hoisted(() => ({
vi.mock('../../../src/services/tripService', () => tripSvc);
vi.mock('../../../src/services/dayService', () => ({ listDays: () => ({ days: [1] }), listAccommodations: () => [] }));
vi.mock('../../../src/services/placeService', () => ({ listPlaces: () => [] }));
vi.mock('../../../src/services/packingService', () => ({ listItems: () => [] }));
vi.mock('../../../src/services/budgetService', () => ({
listBudgetItems: () => [],
rebaseTripCurrency: vi.fn(async () => {}),
@@ -37,10 +36,12 @@ vi.mock('../../../src/services/fileService', () => ({ listFiles: () => [] }));
import { TripsService } from '../../../src/nest/trips/trips.service';
import type { TodoService } from '../../../src/nest/todo/todo.service';
import type { PackingService } from '../../../src/nest/packing/packing.service';
import { rebaseTripCurrency } from '../../../src/services/budgetService';
const todoStub = { listItems: () => [] } as unknown as TodoService;
function svc() { return new TripsService(new DatabaseService(dbConn), todoStub); }
const packingStub = { listItems: () => [] } as unknown as PackingService;
function svc() { return new TripsService(new DatabaseService(dbConn), todoStub, packingStub); }
beforeEach(() => vi.clearAllMocks());
describe('TripsService (wrapper delegation + bundle/copy/notify helpers)', () => {
@@ -3,8 +3,8 @@
* capability host to the real privileged modules (#plugins, M1). Verifies the
* per-plugin data db is cached, a granted db:own call works through the wired
* host, and trip broadcasts are force-namespaced to plugin:{id}:{event}.
* DI-native domains (budget/reservations/tags/categories/todo/oauth) are
* constructor-injected stubs; legacy services/* domains stay path-mocked
* DI-native domains (budget/reservations/tags/categories/todo/packing/oauth)
* are constructor-injected stubs; legacy services/* domains stay path-mocked
* until their own DI migration lands.
*/
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
@@ -126,26 +126,33 @@ vi.mock('../../../src/services/budgetService', () => ({
deleteBudgetItem: vi.fn(),
linkBudgetItemToReservation: vi.fn(),
}));
vi.mock('../../../src/services/packingService', () => ({
listItems: vi.fn((tid: number, userId: number) => [{ id: 1, trip_id: tid, name: 'Socks', _uid: userId }]),
// Packing is a constructor-injected stub (same behaviors as the old path mock).
const packingStub = {
listItems: vi.fn((tid: number | string, userId?: number) => [{ id: 1, trip_id: tid, name: 'Socks', _uid: userId }]),
// Return the item with the #858 privacy fields the host deps scope on.
createItem: vi.fn((tid: number, input: { name: string; visibility?: string; recipient_ids?: number[] }, ownerId?: number) => {
createItem: vi.fn((tid: number | string, input: { name: string; visibility?: string; recipient_ids?: number[] }, ownerId?: number) => {
if (input.visibility === 'personal') return { id: 70, trip_id: Number(tid), name: input.name, is_private: 1, owner_id: ownerId, recipients: [] };
if (input.visibility === 'shared') return { id: 70, trip_id: Number(tid), name: input.name, is_private: 1, owner_id: ownerId, recipients: (input.recipient_ids || []).map((id) => ({ user_id: id })) };
return { id: 70, trip_id: Number(tid), name: input.name, is_private: 0, owner_id: ownerId };
}),
// itemId 99 => a stale-write conflict result; otherwise the after-state (is_private per input).
updateItem: vi.fn((tid: number, id: string, input: { is_private?: boolean }) =>
updateItem: vi.fn((tid: number | string, id: string, input: { is_private?: boolean }) =>
Number(id) === 99 ? { conflict: true, server: { id: 99 } } : { id: Number(id), trip_id: Number(tid), is_private: input.is_private ? 1 : 0, owner_id: 5 },
),
// The raw deleted row (owner-only for a private item, no recipients — #858).
deleteItem: vi.fn((_tid: number, id: string) => (Number(id) === 404 ? null : Number(id) === 71 ? { id: 71, is_private: 1, owner_id: 5 } : { id: Number(id), is_private: 0 })),
listBags: vi.fn((tid: number) => [{ id: 80, trip_id: Number(tid), name: 'Backpack' }]),
createBag: vi.fn((tid: number, data: { name: string }) => ({ id: 80, trip_id: Number(tid), name: data.name })),
updateBag: vi.fn((_tid: number, bagId: string) => (Number(bagId) === 404 ? null : { id: Number(bagId), name: 'Renamed' })),
deleteBag: vi.fn((_tid: number, bagId: string) => Number(bagId) !== 404),
setBagMembers: vi.fn((_tid: number, bagId: string, userIds: number[]) => (Number(bagId) === 404 ? null : userIds.map((u) => ({ user_id: u })))),
}));
deleteItem: vi.fn((_tid: number | string, id: string) => (Number(id) === 404 ? null : Number(id) === 71 ? { id: 71, is_private: 1, owner_id: 5 } : { id: Number(id), is_private: 0 })),
// Mirrors the packing_items rows seeded above: 70 = public, 71 = private (was
// the inline packingItemPrivacy SQL before the DI move).
getItemPrivacy: vi.fn((tid: number | string, id: number | string) =>
Number(tid) === 1 && Number(id) === 70 ? { is_private: 0, owner_id: 5 }
: Number(tid) === 1 && Number(id) === 71 ? { is_private: 1, owner_id: 5 }
: undefined),
listBags: vi.fn((tid: number | string) => [{ id: 80, trip_id: Number(tid), name: 'Backpack' }]),
createBag: vi.fn((tid: number | string, data: { name: string }) => ({ id: 80, trip_id: Number(tid), name: data.name })),
updateBag: vi.fn((_tid: number | string, bagId: string) => (Number(bagId) === 404 ? null : { id: Number(bagId), name: 'Renamed' })),
deleteBag: vi.fn((_tid: number | string, bagId: string) => Number(bagId) !== 404),
setBagMembers: vi.fn((_tid: number | string, bagId: string, userIds: number[]) => (Number(bagId) === 404 ? null : userIds.map((u) => ({ user_id: u })))),
} as unknown as PackingService;
vi.mock('../../../src/services/conflictResult', () => ({ isUpdateConflict: (r: unknown) => !!(r as { conflict?: boolean })?.conflict }));
vi.mock('../../../src/services/weatherService', () => ({ getWeather: vi.fn(async (lat: string, lng: string) => ({ lat, lng, temp: 20 })) }));
const categoriesStub = { list: vi.fn(() => [{ id: 1, name: 'Food' }]) } as unknown as CategoriesService;
@@ -283,12 +290,13 @@ import type { ReservationsService } from '../../../src/nest/reservations/reserva
import type { TagsService } from '../../../src/nest/tags/tags.service';
import type { CategoriesService } from '../../../src/nest/categories/categories.service';
import type { TodoService } from '../../../src/nest/todo/todo.service';
import type { PackingService } from '../../../src/nest/packing/packing.service';
import type { PluginOAuthService } from '../../../src/nest/plugins/plugin-oauth.service';
// The factory under test, wired exactly like PluginsModule does — but with the
// DI-native domain services replaced by the stubs above. The shim keeps the
// ~45 historical call sites unchanged and supplies a default no-op router.
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, oauthStub);
const factory = new PluginHostDepsFactory(budgetStub, reservationsStub, tagsStub, categoriesStub, todoStub, packingStub, oauthStub);
const stubRouter: PluginCallRouter = { callPlugin: async () => undefined, emitPluginEvent: () => {} };
const createRealRpcHost = (id: string, granted: ReadonlySet<string>, router: PluginCallRouter = stubRouter) => factory.create(id, granted, router);
@@ -39,8 +39,11 @@ import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { updatePlace, createPlace } from '../../../src/services/placeService';
import { createItem, updateItem } from '../../../src/services/packingService';
import { isUpdateConflict } from '../../../src/services/conflictResult';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { PackingService } from '../../../src/nest/packing/packing.service';
const packing = new PackingService(new DatabaseService(testDb));
beforeAll(() => {
createTables(testDb);
@@ -110,19 +113,19 @@ describe('updateItem (packing) — optimistic concurrency', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string | null };
const item = packing.createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string | null };
expect(item.updated_at).toBeTruthy();
});
it('returns a conflict when the packing token is stale', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string };
const item = packing.createItem(trip.id, { name: 'Socks' }) as { id: number; updated_at: string };
const stale = updateItem(trip.id, item.id, { name: 'Mine' }, ['name'], '1999-01-01 00:00:00');
const stale = packing.updateItem(trip.id, item.id, { name: 'Mine' }, ['name'], '1999-01-01 00:00:00');
expect(isUpdateConflict(stale)).toBe(true);
const fresh = updateItem(trip.id, item.id, { name: 'Edited' }, ['name'], item.updated_at);
const fresh = packing.updateItem(trip.id, item.id, { name: 'Edited' }, ['name'], item.updated_at);
expect(isUpdateConflict(fresh)).toBe(false);
expect((fresh as { name: string }).name).toBe('Edited');
});
@@ -1,570 +0,0 @@
/**
* Unit tests for packingService.ts — uncovered functions.
* Covers PACK-SVC-001 to PACK-SVC-012.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest';
// ── DB mock setup (vi.hoisted so it is available before vi.mock calls) ────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
const mock = {
db,
closeDb: () => {},
reinitialize: () => {},
getPlaceWithTags: () => null,
canAccessTrip: () => null,
isOwner: () => false,
};
return { testDb: db, dbMock: mock };
});
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
updateJwtSecret: () => {},
}));
import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import {
saveAsTemplate,
applyTemplate,
listTemplates,
setBagMembers,
createBag,
updateBag,
deleteBag,
bulkImport,
createItem,
updateItem,
deleteItem,
listItems,
setItemSharing,
addContributor,
removeContributor,
cloneItem,
} from '../../../src/services/packingService';
// ── Lifecycle ─────────────────────────────────────────────────────────────────
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
beforeEach(() => {
resetTestDb(testDb);
});
afterAll(() => {
testDb.close();
});
// ── saveAsTemplate ────────────────────────────────────────────────────────────
describe('saveAsTemplate', () => {
it('PACK-SVC-001: saves packing items as a template with correct categories and item count', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shirt', 'Clothes', 0);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shorts', 'Clothes', 1);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Toothbrush', 'Toiletries', 2);
const result = saveAsTemplate(trip.id, user.id, 'My Template');
expect(result).not.toBeNull();
expect(result!.name).toBe('My Template');
expect(result!.categoryCount).toBe(2);
expect(result!.itemCount).toBe(3);
const template = testDb.prepare('SELECT * FROM packing_templates WHERE id = ?').get(result!.id) as any;
expect(template).toBeDefined();
expect(template.name).toBe('My Template');
expect(template.created_by).toBe(user.id);
});
it('PACK-SVC-002: returns null when trip has no packing items', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = saveAsTemplate(trip.id, user.id, 'Empty');
expect(result).toBeNull();
});
});
// ── listTemplates ───────────────────────────────────────────────────────────────
describe('listTemplates', () => {
it('PACK-SVC-LIST-001: returns templates with id, name and item_count', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Shirt', 'Clothes', 0);
testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked, sort_order) VALUES (?, ?, ?, 0, ?)').run(trip.id, 'Toothbrush', 'Toiletries', 1);
const saved = saveAsTemplate(trip.id, user.id, 'Weekend');
const templates = listTemplates();
expect(templates).toHaveLength(1);
expect(templates[0]).toMatchObject({ id: saved!.id, name: 'Weekend', item_count: 2 });
});
it('PACK-SVC-LIST-002: returns an empty array when no templates exist', () => {
expect(listTemplates()).toEqual([]);
});
});
// ── applyTemplate ─────────────────────────────────────────────────────────────
/** A one-category template with the given item names. Returns its id. */
function seedTemplate(userId: number, itemNames: string[]): number {
const templateId = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Camping', userId).lastInsertRowid as number;
const catId = testDb.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, 'Gear', 0).lastInsertRowid as number;
itemNames.forEach((name, i) => {
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, name, i);
});
return templateId;
}
describe('applyTemplate', () => {
it('PACK-SVC-003: adds template items to a trip packing list', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Insert a template with one category and two items directly
const templateResult = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Camping', user.id);
const templateId = templateResult.lastInsertRowid as number;
const catResult = testDb.prepare('INSERT INTO packing_template_categories (template_id, name, sort_order) VALUES (?, ?, ?)').run(templateId, 'Gear', 0);
const catId = catResult.lastInsertRowid as number;
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, 'Tent', 0);
testDb.prepare('INSERT INTO packing_template_items (category_id, name, sort_order) VALUES (?, ?, ?)').run(catId, 'Sleeping Bag', 1);
const result = applyTemplate(trip.id, templateId);
expect(result).not.toBeNull();
expect(Array.isArray(result)).toBe(true);
expect((result as any[]).length).toBe(2);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items.length).toBe(2);
expect(items.map((i: any) => i.name)).toContain('Tent');
expect(items.map((i: any) => i.name)).toContain('Sleeping Bag');
});
it('PACK-SVC-004: returns null when template has no items', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateResult = testDb.prepare('INSERT INTO packing_templates (name, created_by) VALUES (?, ?)').run('Empty Template', user.id);
const templateId = templateResult.lastInsertRowid as number;
const result = applyTemplate(trip.id, templateId);
expect(result).toBeNull();
});
// #1565: the applied items must land in the view the user is on, not always Common.
it('PACK-SVC-046: applies into the personal list when visibility is personal', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
const result = applyTemplate(trip.id, templateId, 'personal', user.id) as any[];
expect(result[0].is_private).toBe(1);
expect(result[0].owner_id).toBe(user.id);
expect(listItems(trip.id, user.id).filter((i: any) => i.is_private)).toHaveLength(1);
});
it('PACK-SVC-047: a personally applied template stays hidden from other members', () => {
const { user } = createUser(testDb);
const { user: other } = createUser(testDb, { username: 'other' });
const trip = createTrip(testDb, user.id);
testDb.prepare('INSERT INTO trip_members (trip_id, user_id) VALUES (?, ?)').run(trip.id, other.id);
const templateId = seedTemplate(user.id, ['Tent']);
applyTemplate(trip.id, templateId, 'personal', user.id);
expect(listItems(trip.id, other.id)).toHaveLength(0);
});
it('PACK-SVC-048: applies into the common pool by default, leaving items unowned', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
const result = applyTemplate(trip.id, templateId, 'common', user.id) as any[];
expect(result[0].is_private).toBe(0);
// Unowned, so any member may still re-share it (setItemSharing claims a null owner).
expect(result[0].owner_id).toBeNull();
});
it('PACK-SVC-049: falls back to common when no owner is given, so items stay visible', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const templateId = seedTemplate(user.id, ['Tent']);
// A private item with no owner would be invisible to everyone.
const result = applyTemplate(trip.id, templateId, 'personal') as any[];
expect(result[0].is_private).toBe(0);
expect(listItems(trip.id, user.id)).toHaveLength(1);
});
});
// ── createBag / deleteBag ─────────────────────────────────────────────────────
describe('createBag / deleteBag', () => {
it('PACK-SVC-005: createBag inserts a bag and returns it', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = createBag(trip.id, { name: 'Carry-On', color: '#ff0000' }) as any;
expect(result).not.toBeNull();
expect(result.name).toBe('Carry-On');
expect(result.color).toBe('#ff0000');
expect(result.trip_id).toBe(trip.id);
const bag = testDb.prepare('SELECT * FROM packing_bags WHERE id = ?').get(result.id) as any;
expect(bag).toBeDefined();
expect(bag.name).toBe('Carry-On');
});
it('PACK-SVC-006: deleteBag removes the bag and returns true', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Checked Bag' }) as any;
expect(bag).not.toBeNull();
const deleted = deleteBag(trip.id, bag.id);
expect(deleted).toBe(true);
const row = testDb.prepare('SELECT * FROM packing_bags WHERE id = ?').get(bag.id);
expect(row).toBeUndefined();
});
it('PACK-SVC-007: deleteBag returns false for non-existent bag', () => {
const result = deleteBag(1, 99999);
expect(result).toBe(false);
});
});
// ── setBagMembers ─────────────────────────────────────────────────────────────
describe('setBagMembers', () => {
it('PACK-SVC-008: sets bag members (replaces existing)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Main Bag' }) as any;
const result = setBagMembers(trip.id, bag.id, [user.id]) as any[];
expect(result).not.toBeNull();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(1);
expect(result[0].user_id).toBe(user.id);
});
it('PACK-SVC-009: setBagMembers with empty array clears all members', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Main Bag' }) as any;
// First add a member
setBagMembers(trip.id, bag.id, [user.id]);
// Then clear
const result = setBagMembers(trip.id, bag.id, []) as any[];
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(0);
});
it('PACK-SVC-010: setBagMembers returns null for non-existent bag', () => {
const result = setBagMembers(1, 99999, []);
expect(result).toBeNull();
});
it('PACK-SVC-010a: setBagMembers drops a user who is not on the trip roster', () => {
const { user } = createUser(testDb);
const outsider = createUser(testDb).user;
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Main Bag' }) as any;
// owner is on the roster; the outsider (not owner, not a member) must be filtered out
const result = setBagMembers(trip.id, bag.id, [user.id, outsider.id]) as any[];
const ids = result.map((m) => m.user_id);
expect(ids).toContain(user.id);
expect(ids).not.toContain(outsider.id);
});
it('PACK-SVC-010b: updateBag ignores an off-roster user_id, leaving the bag unassigned', () => {
const { user } = createUser(testDb);
const outsider = createUser(testDb).user;
const trip = createTrip(testDb, user.id);
const bag = createBag(trip.id, { name: 'Main Bag' }) as any;
// assigning to an outsider must not stick — the CASE keeps user_id null
updateBag(trip.id, bag.id, { user_id: outsider.id }, ['user_id']);
const stored = testDb.prepare('SELECT user_id FROM packing_bags WHERE id = ?').get(bag.id) as { user_id: number | null };
expect(stored.user_id).toBeNull();
// assigning to the owner (on the roster) does stick
updateBag(trip.id, bag.id, { user_id: user.id }, ['user_id']);
const stored2 = testDb.prepare('SELECT user_id FROM packing_bags WHERE id = ?').get(bag.id) as { user_id: number | null };
expect(stored2.user_id).toBe(user.id);
});
});
// ── bulkImport with bag field ─────────────────────────────────────────────────
describe('bulkImport with bag field', () => {
it('PACK-SVC-011: bulk import with bag field creates the bag if it does not exist', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = bulkImport(trip.id, [{ name: 'Shirt', bag: 'Carry-On' }]);
expect(result).toHaveLength(1);
expect(result[0]).toBeDefined();
const bags = testDb.prepare('SELECT * FROM packing_bags WHERE trip_id = ? AND name = ?').all(trip.id, 'Carry-On') as any[];
expect(bags).toHaveLength(1);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items).toHaveLength(1);
expect(items[0].bag_id).toBe(bags[0].id);
});
it('PACK-SVC-012: bulk import with same bag name reuses existing bag', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const result = bulkImport(trip.id, [
{ name: 'Shirt', bag: 'Carry-On' },
{ name: 'Pants', bag: 'Carry-On' },
]);
expect(result).toHaveLength(2);
const bags = testDb.prepare('SELECT * FROM packing_bags WHERE trip_id = ? AND name = ?').all(trip.id, 'Carry-On') as any[];
expect(bags).toHaveLength(1);
const items = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ?').all(trip.id) as any[];
expect(items).toHaveLength(2);
expect(items[0].bag_id).toBe(bags[0].id);
expect(items[1].bag_id).toBe(bags[0].id);
});
});
// ── bulkImport with quantity field ────────────────────────────────────────────
describe('bulkImport with quantity field', () => {
it('PACK-SVC-013: bulk import respects per-item quantity, defaults to 1, and clamps out-of-range', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
bulkImport(trip.id, [
{ name: 'Socks', quantity: 5 },
{ name: 'Toothbrush' },
{ name: 'Batteries', quantity: 9999 },
{ name: 'Charger', quantity: 0 },
]);
const byName = (n: string) =>
testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ? AND name = ?').get(trip.id, n) as any;
expect(byName('Socks').quantity).toBe(5);
expect(byName('Toothbrush').quantity).toBe(1);
expect(byName('Batteries').quantity).toBe(999);
expect(byName('Charger').quantity).toBe(1);
});
});
// ── Private items (#858) ──────────────────────────────────────────────────────
describe('private items (#858)', () => {
it('PACK-SVC-014: createItem stamps the owner and is_private flag', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const shared = createItem(trip.id, { name: 'Tent' }, user.id) as any;
const secret = createItem(trip.id, { name: 'Gift', is_private: true }, user.id) as any;
expect(shared.is_private).toBe(0);
expect(shared.owner_id).toBe(user.id);
expect(secret.is_private).toBe(1);
expect(secret.owner_id).toBe(user.id);
});
it('PACK-SVC-015: listItems hides another member\'s private items but shows the owner theirs', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
createItem(trip.id, { name: 'Shared' }, owner.id);
createItem(trip.id, { name: 'Private', is_private: true }, owner.id);
const ownerView = listItems(trip.id, owner.id) as any[];
const otherView = listItems(trip.id, other.id) as any[];
const unscoped = listItems(trip.id) as any[];
expect(ownerView.map(i => i.name).sort()).toEqual(['Private', 'Shared']);
expect(otherView.map(i => i.name)).toEqual(['Shared']);
// Without a viewer (internal callers) nothing is filtered.
expect(unscoped).toHaveLength(2);
});
it('PACK-SVC-016: updateItem toggles privacy and claims an unowned item for the actor', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
// Legacy-style row with no owner.
const id = Number((testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order) VALUES (?, ?, 0, 0)').run(trip.id, 'Legacy') as any).lastInsertRowid);
const updated = updateItem(trip.id, id, { is_private: true }, ['is_private'], undefined, user.id) as any;
expect(updated.is_private).toBe(1);
expect(updated.owner_id).toBe(user.id);
const back = updateItem(trip.id, id, { is_private: false }, ['is_private'], undefined, user.id) as any;
expect(back.is_private).toBe(0);
// Ownership is retained once claimed.
expect(back.owner_id).toBe(user.id);
});
it('PACK-SVC-017: deleteItem returns the removed row (with privacy fields)', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const item = createItem(trip.id, { name: 'Private', is_private: true }, user.id) as any;
const deleted = deleteItem(trip.id, item.id) as any;
expect(deleted).not.toBeNull();
expect(deleted.is_private).toBe(1);
expect(deleted.owner_id).toBe(user.id);
expect(deleteItem(trip.id, item.id)).toBeNull();
});
it('PACK-SVC-018: bulkImport stamps the owner on every item', () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
bulkImport(trip.id, [{ name: 'A' }, { name: 'B', is_private: true }], user.id);
const rows = testDb.prepare('SELECT * FROM packing_items WHERE trip_id = ? ORDER BY name').all(trip.id) as any[];
expect(rows.every(r => r.owner_id === user.id)).toBe(true);
expect(rows.find(r => r.name === 'B').is_private).toBe(1);
expect(rows.find(r => r.name === 'A').is_private).toBe(0);
});
});
// ── Three-tier sharing (#858 follow-up) ───────────────────────────────────────
describe('three-tier packing sharing (#858)', () => {
const names = (rows: any[]) => rows.map(r => r.name).sort();
it('PACK-SVC-040: existing/common items are visible to everyone (non-breaking)', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
// A legacy-style row written directly (is_private defaults 0) = Common.
testDb.prepare('INSERT INTO packing_items (trip_id, name, checked, sort_order) VALUES (?, ?, 0, 0)').run(trip.id, 'Tent');
createItem(trip.id, { name: 'Stove', visibility: 'common' }, owner.id);
expect(names(listItems(trip.id, owner.id) as any[])).toEqual(['Stove', 'Tent']);
expect(names(listItems(trip.id, other.id) as any[])).toEqual(['Stove', 'Tent']);
});
it('PACK-SVC-041: a Shared item is visible to its owner + recipients only, marked with the bringer', () => {
const { user: owner } = createUser(testDb);
const { user: friend } = createUser(testDb);
const { user: stranger } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const item = createItem(trip.id, { name: 'Power bank', visibility: 'shared', recipient_ids: [friend.id] }, owner.id) as any;
expect(item.is_private).toBe(1);
expect(item.owner_username).toBe(owner.username);
expect(item.recipients.map((r: any) => r.user_id)).toEqual([friend.id]);
expect(names(listItems(trip.id, owner.id) as any[])).toEqual(['Power bank']); // bringer
expect(names(listItems(trip.id, friend.id) as any[])).toEqual(['Power bank']); // covered person
expect(names(listItems(trip.id, stranger.id) as any[])).toEqual([]); // nobody else
});
it('PACK-SVC-042: a Personal item is visible only to its owner', () => {
const { user: owner } = createUser(testDb);
const { user: other } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
createItem(trip.id, { name: 'Diary', visibility: 'personal' }, owner.id);
expect(names(listItems(trip.id, owner.id) as any[])).toEqual(['Diary']);
expect(names(listItems(trip.id, other.id) as any[])).toEqual([]);
});
it('PACK-SVC-043: setItemSharing changes the tier + recipients; only the owner may', () => {
const { user: owner } = createUser(testDb);
const { user: friend } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const item = createItem(trip.id, { name: 'First aid', visibility: 'personal' }, owner.id) as any;
// A non-owner is rejected.
expect((setItemSharing(trip.id, item.id, friend.id, 'shared', [friend.id]) as any).forbidden).toBe(true);
const updated = setItemSharing(trip.id, item.id, owner.id, 'shared', [friend.id]) as any;
expect(updated.recipients.map((r: any) => r.user_id)).toEqual([friend.id]);
expect(names(listItems(trip.id, friend.id) as any[])).toEqual(['First aid']);
// Back to common → visible to everyone, recipients cleared.
setItemSharing(trip.id, item.id, owner.id, 'common', []);
const { user: stranger } = createUser(testDb);
expect(names(listItems(trip.id, stranger.id) as any[])).toEqual(['First aid']);
});
it('PACK-SVC-044: contributors ("I can bring that too") only attach to Common items', () => {
const { user: owner } = createUser(testDb);
const { user: helper } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const common = createItem(trip.id, { name: 'Sunscreen', visibility: 'common' }, owner.id) as any;
const personal = createItem(trip.id, { name: 'Meds', visibility: 'personal' }, owner.id) as any;
const withHelper = addContributor(trip.id, common.id, helper.id) as any;
expect(withHelper.contributors.map((c: any) => c.user_id)).toEqual([helper.id]);
// The bringer can't co-contribute to their own item, and personal items have no pool.
expect(addContributor(trip.id, common.id, owner.id)).toBeNull();
expect(addContributor(trip.id, personal.id, helper.id)).toBeNull();
const cleared = removeContributor(trip.id, common.id, helper.id) as any;
expect(cleared.contributors).toEqual([]);
});
it('PACK-SVC-045: cloneItem copies an item onto the cloner\'s personal list', () => {
const { user: owner } = createUser(testDb);
const { user: cloner } = createUser(testDb);
const trip = createTrip(testDb, owner.id);
const common = createItem(trip.id, { name: 'Travel adapter', category: 'Electronics', visibility: 'common' }, owner.id) as any;
const clone = cloneItem(trip.id, common.id, cloner.id) as any;
expect(clone.name).toBe('Travel adapter');
expect(clone.category).toBe('Electronics');
expect(clone.is_private).toBe(1);
expect(clone.owner_id).toBe(cloner.id);
// The clone is the cloner's alone.
expect(names(listItems(trip.id, owner.id) as any[])).toEqual(['Travel adapter']); // owner sees only the common one
expect(names(listItems(trip.id, cloner.id) as any[])).toEqual(['Travel adapter', 'Travel adapter']); // common + own clone
});
});