Give the packing templates and the feature flags back to their domains

Twelve admin packing-template routes sat on AdminController and reached
PackingService through eleven pass-through methods on AdminService that did
nothing but forward and cast. PackingService already owns all three template
tables, so the routes move to AdminPackingTemplatesController next to it and the
pass-through block is gone. AdminService no longer injects PackingService at all.

The three places flags were raw app_settings SQL on AdminService, sitting beside
bag-tracking and collab-features which it already delegated to AddonsService.
They move to AddonsService, which owns every other flag, and AdminController now
calls it directly rather than through delegating methods.

The toggle ROUTES stay on AdminController, which is a departure from the plan and
worth stating: an admin-gated controller in AddonsModule makes that module import
AuthModule, and PluginGuardsModule imports AddonsModule precisely because it is a
leaf — Nest refused to build the graph. Same for the addon CRUD, whose PUT
cascades into PluginRuntimeService. Both notes are in the code.

Paths, response shapes, the {error,status} envelope, the create-201 split and
every audit action are unchanged.
This commit is contained in:
Maurice
2026-08-09 20:20:20 +02:00
committed by Maurice
parent 94221a6d91
commit d4a1601855
12 changed files with 395 additions and 202 deletions
+25
View File
@@ -149,4 +149,29 @@ export class AddonsService {
],
};
}
// ── Places provider flags ──────────────────────────────────────────────────
// These three sat as raw app_settings SQL on AdminService, next to the
// bag-tracking and collab flags it already delegated here. They read
// `=== 'true'` — fail-closed, matching getBagTracking(). They read
// `!== 'false'` (fail-open) before the 2026-08 quirk fix; a migration
// backfills 'true' for installs that never touched the switches, so nobody
// loses a feature on upgrade.
private readFlag(key: string) {
const row = this.db.prepare('SELECT value FROM app_settings WHERE key = ?').get(key) as { value: string } | undefined;
return { enabled: row?.value === 'true' };
}
private writeFlag(key: string, enabled: boolean) {
this.db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(key, enabled ? 'true' : 'false');
return { enabled: !!enabled };
}
getPlacesPhotos() { return this.readFlag('places_photos_enabled'); }
updatePlacesPhotos(enabled: boolean) { return this.writeFlag('places_photos_enabled', enabled); }
getPlacesAutocomplete() { return this.readFlag('places_autocomplete_enabled'); }
updatePlacesAutocomplete(enabled: boolean) { return this.writeFlag('places_autocomplete_enabled', enabled); }
getPlacesDetails() { return this.readFlag('places_details_enabled'); }
updatePlacesDetails(enabled: boolean) { return this.writeFlag('places_details_enabled', enabled); }
}
-1
View File
@@ -47,7 +47,6 @@ const admin = new AdminService(
new SettingsService(dbs),
new AddonsService(dbs),
new PasskeyService(dbs, auth, webauthn),
new PackingService(dbs, permissions, realtime),
auth,
permissions,
new NotificationsService(dbs, realtime, mailer, new WebhookService(dbs), new NtfyService(dbs), notifPrefs),
+21 -67
View File
@@ -17,6 +17,7 @@ import {
AdminTestNotificationDto,
} from './admin.dto';
import { PluginRuntimeService } from '../plugins/plugin-runtime.service';
import { AddonsService } from '../addons/addons.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -56,6 +57,7 @@ function ok<T>(result: T): Exclude<T, { error: string }> {
export class AdminController {
constructor(
private readonly admin: AdminService,
private readonly addons: AddonsService,
private readonly pluginRuntime: PluginRuntimeService,
private readonly audit: AuditService,
private readonly notifications: NotificationsService,
@@ -181,52 +183,61 @@ export class AdminController {
}
// ── Feature toggles ──
// ── Feature toggles ──
// Straight to AddonsService, which owns every one of these flags. They used to go
// through eleven-plus pass-through methods on AdminService, and the three places
// flags were raw app_settings SQL there even though the other flags lived in the
// addons domain. The routes stay HERE rather than moving next to the service: an
// admin-gated controller in AddonsModule would make that module import AuthModule,
// and PluginGuardsModule imports AddonsModule precisely because it is a leaf — the
// edge would close a cycle.
@Get('bag-tracking')
getBagTracking() { return this.admin.getBagTracking(); }
getBagTracking() { return this.addons.getBagTracking(); }
@Put('bag-tracking')
updateBagTracking(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.admin.updateBagTracking(body.enabled);
const result = this.addons.updateBagTracking(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.bag_tracking', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('places-photos')
getPlacesPhotos() { return this.admin.getPlacesPhotos(); }
getPlacesPhotos() { return this.addons.getPlacesPhotos(); }
@Put('places-photos')
updatePlacesPhotos(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.admin.updatePlacesPhotos(body.enabled);
const result = this.addons.updatePlacesPhotos(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.places_photos', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('places-autocomplete')
getPlacesAutocomplete() { return this.admin.getPlacesAutocomplete(); }
getPlacesAutocomplete() { return this.addons.getPlacesAutocomplete(); }
@Put('places-autocomplete')
updatePlacesAutocomplete(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.admin.updatePlacesAutocomplete(body.enabled);
const result = this.addons.updatePlacesAutocomplete(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.places_autocomplete', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('places-details')
getPlacesDetails() { return this.admin.getPlacesDetails(); }
getPlacesDetails() { return this.addons.getPlacesDetails(); }
@Put('places-details')
updatePlacesDetails(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.admin.updatePlacesDetails(body.enabled);
const result = this.addons.updatePlacesDetails(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.places_details', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('collab-features')
getCollabFeatures() { return this.admin.getCollabFeatures(); }
getCollabFeatures() { return this.addons.getCollabFeatures(); }
@Put('collab-features')
updateCollabFeatures(@CurrentUser() user: User, @Body() body: AdminCollabFeaturesDto, @Req() req: Request) {
const { features, changed } = this.admin.updateCollabFeatures(body);
const { features, changed } = this.addons.updateCollabFeatures(body);
// Collab flags gate MCP registration, but a no-op save must not tear down
// every live MCP session (#1414).
if (changed) this.admin.invalidateMcpSessions();
@@ -234,63 +245,6 @@ export class AdminController {
return features;
}
// ── Packing templates ──
@Get('packing-templates')
listPackingTemplates() { return { templates: this.admin.listPackingTemplates() }; }
@Get('packing-templates/:id')
getPackingTemplate(@Param('id') id: string) { return ok(this.admin.getPackingTemplate(id)); }
@Post('packing-templates')
@HttpCode(201)
createPackingTemplate(@CurrentUser() user: User, @Body() body: AdminTemplateNameDto, @Req() req: Request) {
const result = ok(this.admin.createPackingTemplate(body.name, user.id));
this.audit.writeAudit({ userId: user.id, action: 'admin.packing_template_create', resource: String((result.template as { id?: number } | undefined)?.id ?? ''), ip: getClientIp(req), details: { name: body.name } });
return result;
}
@Put('packing-templates/:id')
updatePackingTemplate(@Param('id') id: string, @Body() body: AdminTemplateNameDto) { return ok(this.admin.updatePackingTemplate(id, body)); }
@Delete('packing-templates/:id')
deletePackingTemplate(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
const result = ok(this.admin.deletePackingTemplate(id));
this.audit.writeAudit({ userId: user.id, action: 'admin.packing_template_delete', resource: String(id), ip: getClientIp(req), details: { name: result.name } });
return { success: true };
}
@Post('packing-templates/:id/categories')
@HttpCode(201)
createTemplateCategory(@Param('id') id: string, @Body() body: AdminTemplateNameDto) {
return ok(this.admin.createTemplateCategory(id, body.name));
}
@Put('packing-templates/:templateId/categories/:catId')
updateTemplateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: AdminTemplateNameDto) {
return ok(this.admin.updateTemplateCategory(templateId, catId, body));
}
@Delete('packing-templates/:templateId/categories/:catId')
deleteTemplateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string) {
ok(this.admin.deleteTemplateCategory(templateId, catId));
return { success: true };
}
@Post('packing-templates/:templateId/categories/:catId/items')
@HttpCode(201)
createTemplateItem(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: AdminTemplateNameDto) {
return ok(this.admin.createTemplateItem(templateId, catId, body.name));
}
@Put('packing-templates/:templateId/items/:itemId')
updateTemplateItem(@Param('templateId') templateId: string, @Param('itemId') itemId: string, @Body() body: AdminTemplateNameDto) { return ok(this.admin.updateTemplateItem(templateId, itemId, body)); }
@Delete('packing-templates/:templateId/items/:itemId')
deleteTemplateItem(@Param('templateId') templateId: string, @Param('itemId') itemId: string) {
ok(this.admin.deleteTemplateItem(templateId, itemId));
return { success: true };
}
// ── Addons ──
@Get('addons')
listAddons() { return { addons: this.admin.listAddons() }; }
-60
View File
@@ -27,7 +27,6 @@ import { AddonsService } from '../addons/addons.service';
import { SettingsService } from '../settings/settings.service';
import { PasskeyService } from '../auth/passkey.service';
import { AuthService } from '../auth/auth.service';
import { PackingService } from '../packing/packing.service';
import { PermissionsService } from '../permissions/permissions.service';
import { PERMISSION_ACTIONS } from '../permissions/permissions.service';
import { NotificationsService } from '../notifications/notifications.service';
@@ -73,7 +72,6 @@ export class AdminService {
private readonly settings: SettingsService,
private readonly addons: AddonsService,
private readonly passkeys: PasskeyService,
private readonly packing: PackingService,
private readonly auth: AuthService,
private readonly permissions: PermissionsService,
private readonly notifications: NotificationsService,
@@ -571,64 +569,6 @@ export class AdminService {
return {};
}
// ── Feature toggles ────────────────────────────────────────────────────────
// Bag-tracking and the collab features are owned by AddonsService (finding
// `admin-1`). The three places flags read `=== 'true'` — fail-closed, matching
// AddonsService.getBagTracking(). They read `!== 'false'` (fail-open) before
// the 2026-08 quirk fix; a migration backfills 'true' for installs that never
// touched the switches, so nobody loses a feature on upgrade.
getBagTracking() { return this.addons.getBagTracking(); }
updateBagTracking(enabled: unknown) { return this.addons.updateBagTracking(enabled as boolean); }
getCollabFeatures() { return this.addons.getCollabFeatures(); }
updateCollabFeatures(body: unknown) { return this.addons.updateCollabFeatures(body as Parameters<AddonsService['updateCollabFeatures']>[0]); }
getPlacesPhotos() {
const row = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_photos_enabled'");
return { enabled: row?.value === 'true' };
}
updatePlacesPhotos(enabled: boolean) {
this.db.run("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_photos_enabled', ?)", enabled ? 'true' : 'false');
return { enabled: !!enabled };
}
getPlacesAutocomplete() {
const row = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_autocomplete_enabled'");
return { enabled: row?.value === 'true' };
}
updatePlacesAutocomplete(enabled: boolean) {
this.db.run("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_autocomplete_enabled', ?)", enabled ? 'true' : 'false');
return { enabled: !!enabled };
}
getPlacesDetails() {
const row = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_details_enabled'");
return { enabled: row?.value === 'true' };
}
updatePlacesDetails(enabled: boolean) {
this.db.run("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_details_enabled', ?)", enabled ? 'true' : 'false');
return { enabled: !!enabled };
}
// ── Packing templates ──────────────────────────────────────────────────────
// The SQL lives in PackingService, which owns all three template tables (see
// its "Admin Template CRUD" block).
listPackingTemplates() { return this.packing.listPackingTemplates(); }
getPackingTemplate(id: string) { return this.packing.getPackingTemplate(id); }
createPackingTemplate(name: unknown, userId: number) { return this.packing.createPackingTemplate(name as string, userId); }
updatePackingTemplate(id: string, body: unknown) { return this.packing.updatePackingTemplate(id, body as Parameters<PackingService['updatePackingTemplate']>[1]); }
deletePackingTemplate(id: string) { return this.packing.deletePackingTemplate(id); }
createTemplateCategory(templateId: string, name: unknown) { return this.packing.createTemplateCategory(templateId, name as string); }
updateTemplateCategory(templateId: string, catId: string, body: unknown) { return this.packing.updateTemplateCategory(templateId, catId, body as Parameters<PackingService['updateTemplateCategory']>[2]); }
deleteTemplateCategory(templateId: string, catId: string) { return this.packing.deleteTemplateCategory(templateId, catId); }
createTemplateItem(templateId: string, catId: string, name: unknown) { return this.packing.createTemplateItem(templateId, catId, name as string); }
updateTemplateItem(templateId: string, itemId: string, body: unknown) { return this.packing.updateTemplateItem(templateId, itemId, body as Parameters<PackingService['updateTemplateItem']>[2]); }
deleteTemplateItem(templateId: string, itemId: string) { return this.packing.deleteTemplateItem(templateId, itemId); }
// ── Addons ─────────────────────────────────────────────────────────────────
listAddons() {
@@ -0,0 +1,116 @@
import { Body, Controller, Delete, Get, HttpCode, HttpException, Param, Post, Put, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { PackingService } from './packing.service';
import { AdminTemplateNameDto } from '../admin/admin.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { getClientIp } from '../audit/client-ip';
import { AuditService } from '../audit/audit.service';
import type { User } from '../../types';
/** Throw the legacy {error,status} envelope when a service call reports failure. */
function ok<T>(result: T): Exclude<T, { error: string }> {
if (result && typeof result === 'object' && 'error' in (result as Record<string, unknown>)) {
const r = result as unknown as { error: string; status?: number };
throw new HttpException({ error: r.error }, r.status ?? 400);
}
return result as Exclude<T, { error: string }>;
}
/**
* /api/admin/packing-templates — the admin CRUD for packing templates.
*
* These twelve routes sat on AdminController and reached PackingService through
* eleven pass-through methods on AdminService that did nothing but forward and cast.
* PackingService already owns all three template tables, so the routes belong here:
* the pass-through block is gone, and there is one owner instead of a controller in
* one domain calling a service in another through a third.
*
* The path, the admin gate, the {error,status} envelope, the create-201-vs-rest-200
* split and the audit-log writes are unchanged — this is a move, not a redesign.
*/
@Controller('api/admin/packing-templates')
@UseGuards(JwtAuthGuard, AdminGuard)
export class AdminPackingTemplatesController {
constructor(
private readonly packing: PackingService,
private readonly audit: AuditService,
) {}
@Get()
list() {
return { templates: this.packing.listPackingTemplates() };
}
@Get(':id')
get(@Param('id') id: string) {
return ok(this.packing.getPackingTemplate(id));
}
@Post()
@HttpCode(201)
create(@CurrentUser() user: User, @Body() body: AdminTemplateNameDto, @Req() req: Request) {
const result = ok(this.packing.createPackingTemplate(body.name, user.id));
this.audit.writeAudit({
userId: user.id,
action: 'admin.packing_template_create',
resource: String((result.template as { id?: number } | undefined)?.id ?? ''),
ip: getClientIp(req),
details: { name: body.name },
});
return result;
}
@Put(':id')
update(@Param('id') id: string, @Body() body: AdminTemplateNameDto) {
return ok(this.packing.updatePackingTemplate(id, body));
}
@Delete(':id')
remove(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
const result = ok(this.packing.deletePackingTemplate(id));
this.audit.writeAudit({
userId: user.id,
action: 'admin.packing_template_delete',
resource: String(id),
ip: getClientIp(req),
details: { name: result.name },
});
return { success: true };
}
@Post(':id/categories')
@HttpCode(201)
createCategory(@Param('id') id: string, @Body() body: AdminTemplateNameDto) {
return ok(this.packing.createTemplateCategory(id, body.name));
}
@Put(':templateId/categories/:catId')
updateCategory(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: AdminTemplateNameDto) {
return ok(this.packing.updateTemplateCategory(templateId, catId, body));
}
@Delete(':templateId/categories/:catId')
deleteCategory(@Param('templateId') templateId: string, @Param('catId') catId: string) {
ok(this.packing.deleteTemplateCategory(templateId, catId));
return { success: true };
}
@Post(':templateId/categories/:catId/items')
@HttpCode(201)
createItem(@Param('templateId') templateId: string, @Param('catId') catId: string, @Body() body: AdminTemplateNameDto) {
return ok(this.packing.createTemplateItem(templateId, catId, body.name));
}
@Put(':templateId/items/:itemId')
updateItem(@Param('templateId') templateId: string, @Param('itemId') itemId: string, @Body() body: AdminTemplateNameDto) {
return ok(this.packing.updateTemplateItem(templateId, itemId, body));
}
@Delete(':templateId/items/:itemId')
deleteItem(@Param('templateId') templateId: string, @Param('itemId') itemId: string) {
ok(this.packing.deleteTemplateItem(templateId, itemId));
return { success: true };
}
}
+4 -2
View File
@@ -1,19 +1,21 @@
import { Module } from '@nestjs/common';
import { PackingController } from './packing.controller';
import { AdminPackingTemplatesController } from './admin-packing-templates.controller';
import { PackingMcp } from './packing.mcp';
import { PackingService } from './packing.service';
import { PackingRpc } from './packing.rpc';
import { PluginGuardsModule } from '../plugins/host/plugin-guards.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { AuditModule } from '../audit/audit.module';
import { AuthModule } from '../auth/auth.module';
/** Packing domain (S2 — Phase 2 trip sub-domain). Registered in AppModule.
* Exports PackingService for in-container consumers (TripsService bundle,
* PackingRpc). */
@Module({
imports: [PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule],
controllers: [PackingController],
imports: [PermissionsModule, AuthModule, RealtimeModule, PluginGuardsModule, AuditModule],
controllers: [PackingController, AdminPackingTemplatesController],
providers: [PackingService, PackingMcp, PackingRpc],
exports: [PackingService],
})
+7
View File
@@ -19,3 +19,10 @@ export function expectRegisteredProvider(moduleClass: object, provider: object):
expect(Array.isArray(providers)).toBe(true);
expect(providers).toEqual(expect.arrayContaining([provider]));
}
/** The same check for a module's `controllers: []`, with the same soundness caveat. */
export function expectRegisteredController(moduleClass: object, controller: object): void {
const controllers = Reflect.getMetadata('controllers', moduleClass) as unknown[] | undefined;
expect(Array.isArray(controllers)).toBe(true);
expect(controllers).toEqual(expect.arrayContaining([controller]));
}
@@ -296,3 +296,50 @@ describe('AddonsService addon/feature flags', () => {
expect(dbMock._stmt.run).not.toHaveBeenCalled();
});
});
/**
* The three places flags moved here from AdminService, where they were raw
* app_settings SQL sitting next to flags that already delegated to this service.
* They are fail-CLOSED (`=== 'true'`), matching getBagTracking: unset used to read as
* ON (`!== 'false'`), and a migration backfills 'true' for existing installs so
* nobody loses a feature on upgrade.
*/
describe('AddonsService places flags', () => {
beforeEach(() => {
vi.clearAllMocks();
});
const cases = [
['getPlacesPhotos', 'updatePlacesPhotos', 'places_photos_enabled'],
['getPlacesAutocomplete', 'updatePlacesAutocomplete', 'places_autocomplete_enabled'],
['getPlacesDetails', 'updatePlacesDetails', 'places_details_enabled'],
] as const;
it('ADDONS-SVC-080 an unset flag reads as OFF, and anything but the literal true does too', () => {
for (const [getter, , key] of cases) {
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(svc()[getter]()).toEqual({ enabled: false });
expect(dbMock.prepare).toHaveBeenLastCalledWith('SELECT value FROM app_settings WHERE key = ?');
expect(dbMock._stmt.get).toHaveBeenLastCalledWith(key);
dbMock._stmt.get.mockReturnValueOnce({ value: 'garbage' });
expect(svc()[getter]()).toEqual({ enabled: false });
}
});
it('ADDONS-SVC-081 a stored "true" reads as ON', () => {
for (const [getter] of cases) {
dbMock._stmt.get.mockReturnValueOnce({ value: 'true' });
expect(svc()[getter]()).toEqual({ enabled: true });
}
});
it('ADDONS-SVC-082 the setters persist the literal string and echo the boolean back', () => {
for (const [, setter, key] of cases) {
expect(svc()[setter](true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith(key, 'true');
expect(svc()[setter](false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith(key, 'false');
}
});
});
@@ -0,0 +1,108 @@
/**
* The admin packing-template CRUD, after it moved off AdminController into the packing
* domain that owns the three template tables. Same paths, same {error,status}
* envelope, same create-201 split, same audit actions — these cases came over from
* admin.controller.test.ts with the routes.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpException } from '@nestjs/common';
import { AdminPackingTemplatesController } from '../../../src/nest/packing/admin-packing-templates.controller';
import { PackingModule } from '../../../src/nest/packing/packing.module';
import type { PackingService } from '../../../src/nest/packing/packing.service';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { User } from '../../../src/types';
import { expectRegisteredController } from '../../helpers/module-providers';
const user = { id: 1, role: 'admin' } as User;
const req = { headers: {}, socket: {} } as never;
const writeAudit = vi.fn();
function controller(over: Partial<PackingService> = {}) {
const packing = {
listPackingTemplates: vi.fn(() => [{ id: 1 }]),
getPackingTemplate: vi.fn(() => ({ template: { id: 1 } })),
createPackingTemplate: vi.fn(() => ({ template: { id: 9 } })),
updatePackingTemplate: vi.fn(() => ({ template: { id: 1 } })),
deletePackingTemplate: vi.fn(() => ({ name: 'Beach' })),
createTemplateCategory: vi.fn(() => ({ category: { id: 2 } })),
updateTemplateCategory: vi.fn(() => ({ category: { id: 2 } })),
deleteTemplateCategory: vi.fn(() => ({ ok: true })),
createTemplateItem: vi.fn(() => ({ item: { id: 3 } })),
updateTemplateItem: vi.fn(() => ({ item: { id: 3 } })),
deleteTemplateItem: vi.fn(() => ({ ok: true })),
...over,
} as unknown as PackingService;
return { c: new AdminPackingTemplatesController(packing, { writeAudit } as unknown as AuditService), packing };
}
const thrown = (run: () => unknown) => {
try {
run();
return null;
} catch (e) {
return e instanceof HttpException ? { status: e.getStatus(), body: e.getResponse() } : e;
}
};
describe('AdminPackingTemplatesController', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('PACKTPL-001 list wraps the service result in the { templates } envelope', () => {
expect(controller().c.list()).toEqual({ templates: [{ id: 1 }] });
});
it('PACKTPL-002 a service {error,status} becomes that HTTP status, not a 200 body', () => {
const { c } = controller({ getPackingTemplate: vi.fn(() => ({ error: 'not found', status: 404 })) } as Partial<PackingService>);
expect(thrown(() => c.get('9'))).toEqual({ status: 404, body: { error: 'not found' } });
});
it('PACKTPL-003 an error without a status defaults to 400', () => {
const { c } = controller({ createTemplateCategory: vi.fn(() => ({ error: 'name required' })) } as Partial<PackingService>);
expect(thrown(() => c.createCategory('1', { name: '' }))).toEqual({ status: 400, body: { error: 'name required' } });
});
it('PACKTPL-004 create audits with the new template id', () => {
const { c, packing } = controller();
expect(c.create(user, { name: 'Beach' }, req)).toEqual({ template: { id: 9 } });
expect(packing.createPackingTemplate).toHaveBeenCalledWith('Beach', 1);
expect(writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ action: 'admin.packing_template_create', resource: '9', details: { name: 'Beach' } }),
);
});
it('PACKTPL-005 delete audits the removed name and answers { success: true }', () => {
const { c } = controller();
expect(c.remove(user, '1', req)).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ action: 'admin.packing_template_delete', resource: '1', details: { name: 'Beach' } }),
);
});
it('PACKTPL-006 the nested category and item routes forward their ids in order', () => {
const { c, packing } = controller();
c.createCategory('1', { name: 'Clothes' });
expect(packing.createTemplateCategory).toHaveBeenCalledWith('1', 'Clothes');
c.updateCategory('1', '2', { name: 'Warm' });
expect(packing.updateTemplateCategory).toHaveBeenCalledWith('1', '2', { name: 'Warm' });
expect(c.deleteCategory('1', '2')).toEqual({ success: true });
c.createItem('1', '2', { name: 'Socks' });
expect(packing.createTemplateItem).toHaveBeenCalledWith('1', '2', 'Socks');
c.updateItem('1', '3', { name: 'Wool socks' });
expect(packing.updateTemplateItem).toHaveBeenCalledWith('1', '3', { name: 'Wool socks' });
expect(c.deleteItem('1', '3')).toEqual({ success: true });
});
it('PACKTPL-007 the delete routes answer { success: true } rather than the service payload', () => {
// The client branches on `success`; leaking the raw service result here would be a
// silent shape change for every caller.
const { c } = controller();
expect(c.deleteCategory('1', '2')).toEqual({ success: true });
expect(c.deleteItem('1', '3')).toEqual({ success: true });
});
it('PACKTPL-008 the class is listed in its module controllers', () => {
expectRegisteredController(PackingModule, AdminPackingTemplatesController);
});
});
+67 -57
View File
@@ -5,6 +5,7 @@ import type { Request } from 'express';
vi.mock('../../../src/nest/audit/client-ip', () => ({ getClientIp: vi.fn(() => '1.2.3.4') }));
vi.mock('../../../src/nest/audit/audit-log.logger', () => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logDebug: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { AdminController } from '../../../src/nest/admin/admin.controller';
import type { AdminService } from '../../../src/nest/admin/admin.service';
import type { PluginRuntimeService } from '../../../src/nest/plugins/plugin-runtime.service';
@@ -27,8 +28,22 @@ const audit = { writeAudit } as unknown as AuditService;
// (same behavior as the old services/notificationService path mock).
const sendNotification = vi.fn().mockResolvedValue(undefined);
const notifications = { send: sendNotification } as unknown as NotificationsService;
const adminCtl = (s: AdminService, rt?: PluginRuntimeService) =>
new AdminController(s, rt as unknown as PluginRuntimeService, audit, notifications);
/** The flags live on AddonsService now; the toggle routes reach it directly. */
const addonsStub = () => ({
getBagTracking: vi.fn(() => ({ enabled: false })),
updateBagTracking: vi.fn((enabled: boolean) => ({ enabled })),
getPlacesPhotos: vi.fn(() => ({ enabled: false })),
updatePlacesPhotos: vi.fn((enabled: boolean) => ({ enabled })),
getPlacesAutocomplete: vi.fn(() => ({ enabled: false })),
updatePlacesAutocomplete: vi.fn((enabled: boolean) => ({ enabled })),
getPlacesDetails: vi.fn(() => ({ enabled: false })),
updatePlacesDetails: vi.fn((enabled: boolean) => ({ enabled })),
getCollabFeatures: vi.fn(() => ({ chat: false })),
updateCollabFeatures: vi.fn(() => ({ features: { chat: true }, changed: true })),
}) as unknown as AddonsService;
const adminCtl = (s: AdminService, rt?: PluginRuntimeService, addons: AddonsService = addonsStub()) =>
new AdminController(s, addons, rt as unknown as PluginRuntimeService, audit, notifications);
function thrown(fn: () => unknown): { status: number; body: unknown } {
try { fn(); } catch (err) {
if (err instanceof NotFoundException) return { status: 404, body: err.getResponse() };
@@ -80,7 +95,10 @@ describe('AdminController permissions + oidc + misc', () => {
});
});
describe('AdminController invites + feature toggles', () => {
// The feature toggles and the packing-template CRUD moved to the addons and packing
// domains; their cases live in admin-feature-toggles.controller.test.ts and
// admin-packing-templates.controller.test.ts.
describe('AdminController invites', () => {
it('invites: create 201 + audit, delete maps error', () => {
const c = adminCtl(svc({ createInvite: vi.fn().mockReturnValue({ invite: { id: 5 }, inviteId: 5, uses: 1, expiresInDays: 7 }) } as Partial<AdminService>));
expect(c.createInvite(user, {}, req)).toEqual({ invite: { id: 5 } });
@@ -88,31 +106,9 @@ describe('AdminController invites + feature toggles', () => {
expect(thrown(() => adminCtl(svc({ deleteInvite: vi.fn().mockReturnValue({ error: 'not found', status: 404 }) } as Partial<AdminService>)).deleteInvite(user, '5', req))).toEqual({ status: 404, body: { error: 'not found' } });
});
it('places-photos: updates + audits', () => {
expect(adminCtl(svc({ updatePlacesPhotos: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).updatePlacesPhotos(user, { enabled: true }, req)).toEqual({ enabled: true });
});
it('collab-features update invalidates MCP sessions only when a flag actually flipped (#1414)', () => {
const invalidateMcpSessions = vi.fn();
const c = adminCtl(svc({ updateCollabFeatures: vi.fn().mockReturnValue({ features: { chat: true }, changed: true }), invalidateMcpSessions } as Partial<AdminService>));
expect(c.updateCollabFeatures(user, { chat: true }, req)).toEqual({ chat: true });
expect(invalidateMcpSessions).toHaveBeenCalled();
const noopInvalidate = vi.fn();
const noop = adminCtl(svc({ updateCollabFeatures: vi.fn().mockReturnValue({ features: { chat: true }, changed: false }), invalidateMcpSessions: noopInvalidate } as Partial<AdminService>));
expect(noop.updateCollabFeatures(user, { chat: true }, req)).toEqual({ chat: true });
expect(noopInvalidate).not.toHaveBeenCalled();
});
});
describe('AdminController packing templates', () => {
it('get 404, create 201, delete audits', () => {
expect(thrown(() => adminCtl(svc({ getPackingTemplate: vi.fn().mockReturnValue({ error: 'not found', status: 404 }) } as Partial<AdminService>)).getPackingTemplate('9'))).toEqual({ status: 404, body: { error: 'not found' } });
expect(adminCtl(svc({ createPackingTemplate: vi.fn().mockReturnValue({ id: 3, name: 'Beach' }) } as Partial<AdminService>)).createPackingTemplate(user, { name: 'Beach' })).toEqual({ id: 3, name: 'Beach' });
expect(adminCtl(svc({ deletePackingTemplate: vi.fn().mockReturnValue({ name: 'Beach' }) } as Partial<AdminService>)).deletePackingTemplate(user, '3', req)).toEqual({ success: true });
expect(adminCtl(svc({ createTemplateItem: vi.fn().mockReturnValue({ id: 7 }) } as Partial<AdminService>)).createTemplateItem('3', '4', { name: 'Towel' })).toEqual({ id: 7 });
});
});
describe('AdminController addons + sessions + jwt + defaults', () => {
it('addon update audits + invalidates MCP sessions only when the MCP surface changed (#1414)', async () => {
@@ -175,12 +171,6 @@ describe('AdminController read-only getters', () => {
expect(adminCtl(svc({ checkVersion: vi.fn().mockResolvedValue({ current: '1' }) } as Partial<AdminService>)).versionCheck()).resolves.toEqual({ current: '1' });
expect(adminCtl(svc({ getPreferencesMatrix: vi.fn().mockReturnValue({ rows: [] }) } as Partial<AdminService>)).getNotificationPrefs(user)).toEqual({ rows: [] });
expect(adminCtl(svc({ listInvites: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listInvites()).toEqual({ invites: [{ id: 1 }] });
expect(adminCtl(svc({ getBagTracking: vi.fn().mockReturnValue({ enabled: false }) } as Partial<AdminService>)).getBagTracking()).toEqual({ enabled: false });
expect(adminCtl(svc({ getPlacesPhotos: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).getPlacesPhotos()).toEqual({ enabled: true });
expect(adminCtl(svc({ getPlacesAutocomplete: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).getPlacesAutocomplete()).toEqual({ enabled: true });
expect(adminCtl(svc({ getPlacesDetails: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).getPlacesDetails()).toEqual({ enabled: true });
expect(adminCtl(svc({ getCollabFeatures: vi.fn().mockReturnValue({ chat: false }) } as Partial<AdminService>)).getCollabFeatures()).toEqual({ chat: false });
expect(adminCtl(svc({ listPackingTemplates: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listPackingTemplates()).toEqual({ templates: [{ id: 1 }] });
expect(adminCtl(svc({ listAddons: vi.fn().mockReturnValue([{ id: 'mcp' }]) } as Partial<AdminService>)).listAddons()).toEqual({ addons: [{ id: 'mcp' }] });
expect(adminCtl(svc({ listMcpTokens: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listMcpTokens()).toEqual({ tokens: [{ id: 1 }] });
expect(adminCtl(svc({ listOAuthSessions: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listOAuthSessions()).toEqual({ sessions: [{ id: 1 }] });
@@ -204,33 +194,7 @@ describe('AdminController read-only getters', () => {
});
});
describe('AdminController feature toggles + audit', () => {
it('bag-tracking updates and audits', () => {
const c = adminCtl(svc({ updateBagTracking: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>));
expect(c.updateBagTracking(user, { enabled: true }, req)).toEqual({ enabled: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'admin.bag_tracking' }));
});
it('places-autocomplete: updates + audits', () => {
expect(adminCtl(svc({ updatePlacesAutocomplete: vi.fn().mockReturnValue({ enabled: false }) } as Partial<AdminService>)).updatePlacesAutocomplete(user, { enabled: false }, req)).toEqual({ enabled: false });
});
it('places-details: updates + audits', () => {
expect(adminCtl(svc({ updatePlacesDetails: vi.fn().mockReturnValue({ enabled: true }) } as Partial<AdminService>)).updatePlacesDetails(user, { enabled: true }, req)).toEqual({ enabled: true });
});
});
describe('AdminController packing template sub-routes', () => {
it('update/delete templates, categories and items map errors + return success', () => {
expect(adminCtl(svc({ updatePackingTemplate: vi.fn().mockReturnValue({ id: 3 }) } as Partial<AdminService>)).updatePackingTemplate('3', {})).toEqual({ id: 3 });
expect(adminCtl(svc({ createTemplateCategory: vi.fn().mockReturnValue({ id: 4 }) } as Partial<AdminService>)).createTemplateCategory('3', { name: 'Tops' })).toEqual({ id: 4 });
expect(adminCtl(svc({ updateTemplateCategory: vi.fn().mockReturnValue({ id: 4 }) } as Partial<AdminService>)).updateTemplateCategory('3', '4', {})).toEqual({ id: 4 });
expect(adminCtl(svc({ deleteTemplateCategory: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).deleteTemplateCategory('3', '4')).toEqual({ success: true });
expect(adminCtl(svc({ updateTemplateItem: vi.fn().mockReturnValue({ id: 7 }) } as Partial<AdminService>)).updateTemplateItem('7', {})).toEqual({ id: 7 });
expect(adminCtl(svc({ deleteTemplateItem: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).deleteTemplateItem('7')).toEqual({ success: true });
expect(thrown(() => adminCtl(svc({ deleteTemplateItem: vi.fn().mockReturnValue({ error: 'gone', status: 404 }) } as Partial<AdminService>)).deleteTemplateItem('9'))).toEqual({ status: 404, body: { error: 'gone' } });
});
});
describe('AdminController tokens + sessions', () => {
it('mcp token + oauth session deletes return success and map errors', () => {
@@ -284,3 +248,49 @@ describe('AdminController dev test-notification', () => {
await expect(adminCtl(svc()).devTestNotification(user, { event: 'trip_reminder' })).rejects.toMatchObject({ response: { error: 'weird' } });
});
});
// The feature toggles now go straight to AddonsService — these cases used to assert
// the same thing through AdminService pass-throughs that no longer exist.
describe('AdminController feature toggles', () => {
it('ADMIN-TOGGLE-001 each toggle forwards to AddonsService and writes its own audit action', () => {
const addons = addonsStub();
const c = adminCtl(svc(), undefined, addons);
const cases: Array<[() => unknown, string, keyof AddonsService]> = [
[() => c.updateBagTracking(user, { enabled: true }, req), 'admin.bag_tracking', 'updateBagTracking'],
[() => c.updatePlacesPhotos(user, { enabled: true }, req), 'admin.places_photos', 'updatePlacesPhotos'],
[() => c.updatePlacesAutocomplete(user, { enabled: true }, req), 'admin.places_autocomplete', 'updatePlacesAutocomplete'],
[() => c.updatePlacesDetails(user, { enabled: true }, req), 'admin.places_details', 'updatePlacesDetails'],
];
for (const [run, action, method] of cases) {
writeAudit.mockClear();
expect(run()).toEqual({ enabled: true });
expect(addons[method]).toHaveBeenCalledWith(true);
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action, details: { enabled: true } }));
}
});
it('ADMIN-TOGGLE-002 the getters return the AddonsService value verbatim', () => {
const c = adminCtl(svc());
expect(c.getBagTracking()).toEqual({ enabled: false });
expect(c.getPlacesPhotos()).toEqual({ enabled: false });
expect(c.getPlacesAutocomplete()).toEqual({ enabled: false });
expect(c.getPlacesDetails()).toEqual({ enabled: false });
expect(c.getCollabFeatures()).toEqual({ chat: false });
});
it('ADMIN-TOGGLE-003 collab-features invalidates MCP sessions only when a flag flipped (#1414)', () => {
const invalidateMcpSessions = vi.fn();
const c = adminCtl(svc({ invalidateMcpSessions } as Partial<AdminService>));
expect(c.updateCollabFeatures(user, { chat: true }, req)).toEqual({ chat: true });
expect(invalidateMcpSessions).toHaveBeenCalled();
const noopInvalidate = vi.fn();
const noop = adminCtl(
svc({ invalidateMcpSessions: noopInvalidate } as Partial<AdminService>),
undefined,
{ ...addonsStub(), updateCollabFeatures: vi.fn(() => ({ features: { chat: true }, changed: false })) } as unknown as AddonsService,
);
expect(noop.updateCollabFeatures(user, { chat: true }, req)).toEqual({ chat: true });
expect(noopInvalidate).not.toHaveBeenCalled();
});
});
@@ -85,7 +85,6 @@ const svc = new AdminService(
new SettingsService(dbs),
new AddonsService(dbs),
new PasskeyService(dbs, auth, webauthn),
new PackingService(dbs, permissions, realtime),
auth,
permissions,
makeNotificationsService(dbs, realtime),
@@ -592,19 +591,6 @@ describe('admin.bridge', () => {
// ── Quirk fixes landed after the 2026-08 fold ─────────────────────────────────
describe('admin quirk fixes (post-fold)', () => {
it('ADMIN-SVC-071 — the three places toggles are fail-closed (=== true), matching bag-tracking', () => {
// Unset used to read as ON (`!== 'false'`); a migration backfills 'true' for
// existing installs so nobody loses a feature on upgrade.
expect(svc.getPlacesPhotos()).toEqual({ enabled: false });
expect(svc.getPlacesAutocomplete()).toEqual({ enabled: false });
expect(svc.getPlacesDetails()).toEqual({ enabled: false });
svc.updatePlacesPhotos(true);
expect(svc.getPlacesPhotos()).toEqual({ enabled: true });
testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('places_details_enabled', 'garbage')").run();
expect(svc.getPlacesDetails()).toEqual({ enabled: false });
});
it('ADMIN-SVC-072 — updateUser rejects an empty username/email instead of silently no-opping', () => {
const { user } = createUser(testDb);
@@ -68,7 +68,6 @@ const svc = new AdminService(
new SettingsService(dbs),
new AddonsService(dbs),
new PasskeyService(dbs, auth, webauthn),
new PackingService(dbs, permissions, realtime),
auth,
permissions,
makeNotificationsService(dbs, realtime),