fix(server): plan 3i close-out — DemoModule imported where its service is consumed (e2e restored); admin addons list selects the provider relation; saveDemoBaseline awaited; backup tests on the maintenance repository

This commit is contained in:
jubnl
2026-09-24 02:58:37 +02:00
parent ab63eaf9ad
commit 2ba5534c65
19 changed files with 476 additions and 40 deletions
+6 -4
View File
@@ -186,10 +186,12 @@ export default tseslint.config(
// task-3-report.md / the plan's R1 ruling — not debt for a later plan
// to close.
'src/nest/backup/backup.impl.ts',
// Demo-mode seeding, and the legacy schema/migration/seed scripts the test
// suite still builds its throwaway databases from (guarded by
// tests/unit/db/schema-parity.test.ts).
'src/demo/**',
// The legacy schema/migration/seed scripts the test suite still builds
// its throwaway databases from (guarded by
// tests/unit/db/schema-parity.test.ts). Plan 3i Task 3 converted
// `src/demo/**` (demo-seed.ts/demo-reset.ts) onto
// DemoRepository/MaintenanceRepository — no file under `src/demo/`
// imports `better-sqlite3` anymore, so that entry is dropped here.
'src/db/schema.ts',
'src/db/migrations.ts',
'src/db/seeds.ts',
@@ -45,17 +45,32 @@ export class PhotoProviderFieldsRepository extends TrekRepository<PhotoProviderF
* id`. A NARROWER projection than {@link listAllOrdered} — no `id`, no
* `hint` — a genuinely different column set for a different caller, not a
* superset reuse (Task 0's report: parity is column-exact here).
*
* Plan 3i Task 4 fix wave: the `fields` list below names `'provider'` (the
* real relation), not `provider_id` — `provider_id` is the `persist(false)`
* shadow scalar and MikroORM's `fields` projection never selects it, so
* every row came back with `provider_id: undefined` and every photo
* provider grouped under `undefined` (`fields: []` in the admin response).
* `toRow`'s `AssertRowKeys` maps the populated `provider` relation back onto
* the flat `provider_id` column the same way {@link listAllOrdered} does.
*/
async listAllOrderedForAdminShelf(): Promise<PhotoProviderFieldForAdminRow[]> {
const rows = await this.find(
{},
{
fields: ['provider_id', 'field_key', 'label', 'input_type', 'placeholder', 'required', 'secret', 'settings_key', 'payload_key', 'sort_order'],
fields: ['provider', 'field_key', 'label', 'input_type', 'placeholder', 'required', 'secret', 'settings_key', 'payload_key', 'sort_order'],
orderBy: { sort_order: 'asc', id: 'asc' },
},
);
return rows.map((row) => ({
provider_id: row.provider_id,
// `row.provider.id` reads the raw `provider_id` COLUMN VALUE off the
// (unpopulated) relation reference the `fields: ['provider', …]`
// projection loaded — the same `row.<relation>.id` shape
// `OauthTokens.repository.ts`/`McpTokens.repository.ts` already use,
// not `row.provider_id`: that shadow scalar is never selected by a
// narrowed `fields` projection (this method's own fix-wave docstring
// above).
provider_id: row.provider.id,
field_key: row.field_key,
label: row.label,
input_type: row.input_type,
@@ -1485,8 +1485,10 @@ export class UsersRepository extends TrekRepository<Users> {
* password_version=COALESCE(?,password_version), updated_at=CURRENT_TIMESTAMP
* WHERE id=?`. The legacy binds a NULL parameter for "no change" — a
* `nativeUpdate` that simply omits an unchanged key from `patch` has the
* identical net effect (coalesceParam: the new value wins when the
* caller supplies a key, the existing column wins when it is left out) —
* identical net effect (coalesceOverride: `COALESCE(?, column)` — the new
* value wins when the caller supplies a key, the existing column wins
* when it is left out; `coalesceParam`'s `COALESCE(column, ?)` is the
* opposite direction — see `dialect/sql-functions.ts`) —
* the caller decides which keys to include, the same discipline
* `patchProfile` (UP7) already uses for this table. `updated_at` is
* ALWAYS stamped, even when `patch` is `{}` — matching the legacy
+1 -1
View File
@@ -135,7 +135,7 @@ export class AdminController {
@Post('save-demo-baseline')
@HttpCode(200)
async saveDemoBaseline(@CurrentUser() user: User, @Req() req: Request) {
const result = this.admin.saveDemoBaseline();
const result = await this.admin.saveDemoBaseline();
if (result.error) {
throw new HttpException({ error: result.error }, result.status!);
}
+2 -2
View File
@@ -392,14 +392,14 @@ export class AdminService {
// ── Demo Baseline ──────────────────────────────────────────────────────────
saveDemoBaseline(): { error?: string; status?: number; message?: string } {
async saveDemoBaseline(): Promise<{ error?: string; status?: number; message?: string }> {
if (!readEnv().demo.enabled) {
return { error: 'Not found', status: 404 };
}
try {
// Lazy require: demo-reset is a demo-only module.
const { saveBaseline } = require('../../demo/demo-reset');
saveBaseline();
await saveBaseline();
return { message: 'Demo baseline saved. Hourly resets will restore to this state.' };
} catch (err: unknown) {
console.error(err);
+22 -2
View File
@@ -17,6 +17,7 @@ import Database from 'better-sqlite3';
import { RequestContext } from '@mikro-orm/core';
import { closeDb, reinitialize } from '../../db/database';
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
import { logWarn } from '../audit/audit-log.logger';
import { VALID_INTERVALS } from './auto-backup.settings';
import { invalidatePermissionsCache } from '../permissions/permissions-cache';
import { pluginsCodeRoot, pluginsDataRoot } from '../plugins/paths';
@@ -198,7 +199,18 @@ export async function createBackup(storage: StorageService, prefix: 'backup' | '
// best-effort: the swallowing try/catch matches the legacy shape.
try {
const em = RequestContext.getEntityManager();
if (em) await new MaintenanceRepository(em).walCheckpoint();
if (em) {
await new MaintenanceRepository(em).walCheckpoint();
} else {
// Plan 3i Task 4 fix wave (should-land 7): this used to fail
// silently exactly like a real checkpoint failure would — no signal
// distinguished "no request context around this run" (a
// mis-wired caller; legacy always snapshotted) from "the checkpoint
// itself errored" (best-effort, fine to swallow). Loud enough to
// show up in the backup's own logs, still non-fatal: the fallback
// (archive the live file) is unchanged.
logWarn('Backup: no EntityManager available, skipping the WAL checkpoint before snapshot');
}
} catch (e) {}
// Enumerate the archived categories up front (the archiver reads entries
@@ -255,7 +267,15 @@ export async function createBackup(storage: StorageService, prefix: 'backup' | '
try {
if (fs.existsSync(dbSnap)) fs.rmSync(dbSnap, { force: true });
const em = RequestContext.getEntityManager();
if (!em) throw new Error('no EntityManager available for VACUUM INTO');
if (!em) {
// Plan 3i Task 4 fix wave (should-land 7): same distinction as
// BK1 above — without this, a backup silently archiving the LIVE
// travel.db (the exact WAL-tear risk this whole snapshot exists to
// avoid) left no trace anywhere. The fallback itself is unchanged
// (parity with legacy, which always had SOME db to archive).
logWarn('Backup: no EntityManager available, archiving the live travel.db instead of a VACUUM INTO snapshot');
throw new Error('no EntityManager available for VACUUM INTO');
}
await new MaintenanceRepository(em).vacuumInto(dbSnap);
dbToArchive = dbSnap;
} catch (e) {
+6 -2
View File
@@ -21,6 +21,7 @@ import { AppConfigModule } from '../app-config/app-config.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { AddonsModule } from '../addons/addons.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { DemoModule } from '../common/demo.module';
/** Budget domain (S4 — Phase 2 trip sub-domain). Registered in AppModule.
* BudgetMcp carries the decorator-registered MCP tools + resources.
@@ -28,9 +29,12 @@ import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
* RuntimeEnvService + the users table, not AuthService) — that absence is
* what lets AuthModule import BudgetModule for UserCleanupService.
* AppConfigModule is @Global in the app graph; the explicit import keeps the
* partial e2e TestingModules resolving RuntimeEnvService. */
* partial e2e TestingModules resolving RuntimeEnvService. DemoModule is
* @Global for the same reason (Plan 3i Task 4 fix wave) — BudgetMcp injects
* DemoService, and a hand-built TestingModule never imports AppModule, so
* the @Global broadcast never happens unless this module imports it directly. */
@Module({
imports: [McpSharedModule, PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule, AddonsModule, TripMembershipModule, MikroOrmModule.forFeature([BudgetItems, BudgetItemMembers, BudgetItemPayers, BudgetSettlements, BudgetCategoryOrder, Reservations, Places, Trips])],
imports: [McpSharedModule, PermissionsModule, AppConfigModule, DemoModule, RealtimeModule, PluginGuardsModule, AddonsModule, TripMembershipModule, MikroOrmModule.forFeature([BudgetItems, BudgetItemMembers, BudgetItemPayers, BudgetSettlements, BudgetCategoryOrder, Reservations, Places, Trips])],
controllers: [BudgetController],
providers: [BudgetService, ExchangeRatesService, BudgetMcp, ExchangeRatesRpc, CostsRpc],
// For in-container consumers (CostsRpc, TripsService,
@@ -7,6 +7,7 @@ import { CategoriesController } from './categories.controller';
import { CategoriesMcp } from './categories.mcp';
import { CategoriesService } from './categories.service';
import { CategoriesRpc } from './categories.rpc';
import { DemoModule } from '../common/demo.module';
/** Categories domain (L4 leaf module). Registered in AppModule. */
@Module({
@@ -17,8 +18,10 @@ import { CategoriesRpc } from './categories.rpc';
// for the same reason budget/ does it. MikroOrmModule.forFeature registers
// CategoriesRepository for @InjectRepository(Categories) in the service —
// the forFeature + @InjectRepository wiring pattern every domain copies
// (settings.module.ts's precedent comment).
imports: [McpSharedModule, AppConfigModule, MikroOrmModule.forFeature([Categories])],
// (settings.module.ts's precedent comment). DemoModule is imported for the
// same reason: CategoriesMcp injects DemoService, and @Global only reaches a
// hand-built e2e TestingModule that actually imports it (Plan 3i Task 4 fix wave).
imports: [McpSharedModule, AppConfigModule, DemoModule, MikroOrmModule.forFeature([Categories])],
controllers: [CategoriesController],
providers: [CategoriesService, CategoriesMcp, CategoriesRpc],
// For in-container consumers (CategoriesRpc).
+7 -4
View File
@@ -11,6 +11,7 @@ import { Users } from '../../db/entities/Users.entity';
import { FeedsService } from './feeds.service';
import { FeedsMcp } from './feeds.mcp';
import { FeedsPublicController, TripFeedTokenController, UserFeedTokenController } from './feeds.controller';
import { DemoModule } from '../common/demo.module';
@Module({
// Calendars, not the trip aggregate: feeds only ever needed an ICS string, and
@@ -19,11 +20,12 @@ import { FeedsPublicController, TripFeedTokenController, UserFeedTokenController
// `MikroOrmModule.forFeature([Trips, Users])` registers `TripsRepository`/
// `UsersRepository` for `FeedsService`'s `@InjectRepository` constructor
// params (Plan 3d Task 5, FD1–FD11) — the same forFeature + `@InjectRepository`
// wiring `days.module.ts` documents. The last three are FeedsMcp's:
// wiring `days.module.ts` documents. The last four are FeedsMcp's:
// McpSharedModule for the RBAC check the route gets from its guard,
// AppConfigModule and RealtimeModule because a module graph assembled without
// AppModule (the e2e harnesses) has to instantiate those two @Global modules
// itself before anything can inject out of them.
// AppConfigModule, RealtimeModule and DemoModule because a module graph
// assembled without AppModule (the e2e harnesses) has to instantiate those
// @Global modules itself before anything can inject out of them (DemoModule
// added Plan 3i Task 4 fix wave — FeedsMcp injects DemoService).
imports: [
CalendarModule,
DatabaseModule,
@@ -31,6 +33,7 @@ import { FeedsPublicController, TripFeedTokenController, UserFeedTokenController
McpSharedModule,
AppConfigModule,
RealtimeModule,
DemoModule,
MikroOrmModule.forFeature([Trips, Users]),
],
controllers: [FeedsPublicController, TripFeedTokenController, UserFeedTokenController],
@@ -4,6 +4,7 @@ import { PluginsRuntimeModule } from '../plugins-runtime.module';
import { AddonsModule } from '../../addons/addons.module';
import { JourneyDomainModule } from '../../journey/journey-domain.module';
import { JourneyEntries } from '../../../db/entities/JourneyEntries.entity';
import { Plugins } from '../../../db/entities/Plugins.entity';
import { PlaceDetailsController } from './place-details.controller';
import { PluginSearchController } from './plugin-search.controller';
import { TripWarningsController } from './trip-warnings.controller';
@@ -22,6 +23,7 @@ import { DayTintsController } from './day-tints.controller';
import { PdfSectionsController } from './pdf-sections.controller';
import { AtlasLayersController } from './atlas-layers.controller';
import { JournalEntryRowsController } from './journal-entry-rows.controller';
import { DemoModule } from '../../common/demo.module';
/**
* The read-only surface plugins contribute to the app: photos, calendar events,
@@ -35,15 +37,24 @@ import { JournalEntryRowsController } from './journal-entry-rows.controller';
* activate or configure anything, which is why they are separated from the CRUD
* surface in PluginsModule.
*
* `MikroOrmModule.forFeature([JourneyEntries])` registers
* `MikroOrmModule.forFeature([JourneyEntries, Plugins])` registers
* `JourneyEntriesRepository` for `JournalEntryRowsController`'s own
* `@InjectRepository` constructor param (JEC1, Plan 3g Task 4) — importing
* `JourneyDomainModule` above brings in `JourneyDomainService` for the
* `canAccessJourney` call but does NOT export `MikroOrmModule`, so the
* entity needs its own registration here too.
* entity needs its own registration here too. `Plugins` is the same shape
* (Plan 3j Task 3): `PluginRoutesController`'s `declaredProfiles` call now
* takes `PluginsRepository`, and `PluginsRuntimeModule`'s own registration
* of the same entity isn't exported either.
*
* `DemoModule` is imported explicitly (Plan 3i Task 4 fix wave): it is
* `@Global()`, but that broadcast only reaches a module graph that actually
* imports it somewhere — a hand-built e2e `TestingModule` that never pulls in
* `AppModule` otherwise leaves `PluginMcpToolsService`'s `DemoService`
* dependency unresolved.
*/
@Module({
imports: [PluginsRuntimeModule, AddonsModule, JourneyDomainModule, MikroOrmModule.forFeature([JourneyEntries])],
imports: [PluginsRuntimeModule, AddonsModule, JourneyDomainModule, DemoModule, MikroOrmModule.forFeature([JourneyEntries, Plugins])],
controllers: [
PlaceDetailsController,
PluginSearchController,
@@ -9,13 +9,15 @@ import { PermissionsModule } from '../permissions/permissions.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { AuditModule } from '../audit/audit.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { DemoModule } from '../common/demo.module';
@Module({
// The last three carry TripInviteMcp: McpSharedModule for the RBAC check the
// controller does inline, and the two @Global modules it injects out of,
// which a graph assembled without AppModule (the e2e harness) must
// instantiate itself.
imports: [RateLimitModule, PermissionsModule, AuditModule, TripMembershipModule, McpSharedModule, AppConfigModule, RealtimeModule],
// The last four carry TripInviteMcp: McpSharedModule for the RBAC check the
// controller does inline, and the three @Global modules it injects out of
// (DemoModule added Plan 3i Task 4 fix wave — TripInviteMcp injects
// DemoService), which a graph assembled without AppModule (the e2e harness)
// must instantiate itself.
imports: [RateLimitModule, PermissionsModule, AuditModule, TripMembershipModule, McpSharedModule, AppConfigModule, RealtimeModule, DemoModule],
controllers: [TripInviteLinkController, TripInviteController],
providers: [TripInviteService, TripInviteMcp],
})
+38 -6
View File
@@ -62,11 +62,16 @@ vi.mock('../../src/config', () => ({
}));
import path from 'node:path';
import type Database from 'better-sqlite3';
import { AutoBackupJob } from '../../src/nest/backup/auto-backup.job';
import { createBackup } from '../../src/nest/backup/backup.impl';
import type { BackupService } from '../../src/nest/backup/backup.service';
import type { StorageService } from '../../src/nest/storage/storage.service';
import type { CronRegistrarService } from '../../src/nest/scheduling/cron-registrar.service';
import { createTestDb } from '../helpers/test-db';
import { createTestOrm } from '../helpers/test-orm';
import { withRequestContext } from '../../src/nest/database/request-context';
import { MaintenanceRepository } from '../../src/db/repositories/MaintenanceRepository';
const liveDb = path.join(__dirname, '../../data', 'travel.db');
@@ -157,13 +162,40 @@ describe('auto-backup run', () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db') || String(p).endsWith('backup-settings.json'));
stubArchiver();
await scheduledRun()();
// Plan 3i Task 4 fix wave: BK2 now runs through
// `MaintenanceRepository.vacuumInto()` on a resolved `RequestContext`
// EntityManager (backup.impl.ts), not the raw `db.exec` this test used
// to spy on — that assertion went stale and silently stopped proving
// anything the moment BK2 moved off the legacy `db` proxy: with no
// request context around the tick, `RequestContext.getEntityManager()`
// returned null, createBackup silently fell back to archiving the LIVE
// file (the exact bug this suite's own header describes), and
// `dbMock.db.exec` was simply never called — a false green.
// A real (throwaway) ORM over a real test DB supplies that
// EntityManager; `vacuumInto` itself is spied and stubbed so no real
// VACUUM INTO touches disk (fs is mocked wholesale above, but
// better-sqlite3's native VACUUM INTO would bypass that mock).
const maintDb: Database.Database = createTestDb();
const testOrm = await createTestOrm(maintDb);
const vacuumIntoSpy = vi.spyOn(MaintenanceRepository.prototype, 'vacuumInto').mockResolvedValue(undefined);
const walCheckpointSpy = vi.spyOn(MaintenanceRepository.prototype, 'walCheckpoint').mockResolvedValue(undefined);
try {
await withRequestContext(testOrm.orm, () => scheduledRun()());
expect(dbMock.db.exec).toHaveBeenCalledWith(expect.stringContaining('VACUUM INTO'));
const dbEntry = archiveMock.file.mock.calls.find(([, opts]) => opts?.name === 'travel.db');
expect(dbEntry).toBeDefined();
expect(dbEntry?.[0]).toContain('/stub/spool/travel-snap-auto-backup-');
expect(dbEntry?.[0]).not.toBe(liveDb);
// Assertions run BEFORE the spies are restored: `mockRestore()` also
// clears recorded calls (same as `mockReset()`), so checking after
// cleanup would always read an empty call list.
expect(vacuumIntoSpy).toHaveBeenCalledWith(expect.stringContaining('/stub/spool/travel-snap-auto-backup-'));
const dbEntry = archiveMock.file.mock.calls.find(([, opts]) => opts?.name === 'travel.db');
expect(dbEntry).toBeDefined();
expect(dbEntry?.[0]).toContain('/stub/spool/travel-snap-auto-backup-');
expect(dbEntry?.[0]).not.toBe(liveDb);
} finally {
vacuumIntoSpy.mockRestore();
walCheckpointSpy.mockRestore();
await testOrm.close();
maintDb.close();
}
});
it('bundles the at-rest encryption key', async () => {
@@ -109,4 +109,41 @@ describe('AddonsRepository', () => {
});
});
});
// Plan 3i Task 4 fix wave (should-land 5): AD26 (listAllOrdered) and
// AD30/AD39 (findById) shipped in Task 1 with no repository-level test —
// full-key parity against the exact legacy SQL each method's own docstring
// names.
describe('listAllOrdered (AD26)', () => {
it('ADDONSREPO-010: matches SELECT * FROM addons ORDER BY sort_order, id — unfiltered, including a disabled addon', async () => {
insertAddon({ id: 'vacay', name: 'Vacay', type: 'page', icon: 'sun', enabled: 0, sort_order: 1 });
insertAddon({ id: 'budget', name: 'Costs', type: 'trip', icon: 'wallet', enabled: 1, sort_order: 0 });
const legacy = testDb.prepare('SELECT * FROM addons ORDER BY sort_order, id').all();
const rows = await addons.listAllOrdered();
expect(rows.map((r) => r.id)).toEqual(['budget', 'vacay']); // includes the disabled one, unlike listEnabled
expect(rows).toEqual(
(legacy as Array<{ enabled: number; config: string | null }>).map((r) => ({ ...r, enabled: !!r.enabled, config: JSON.parse(r.config ?? '{}') })),
);
});
it('ADDONSREPO-011: an empty table returns an empty array', async () => {
expect(await addons.listAllOrdered()).toEqual([]);
});
});
describe('findById (AD30/AD39)', () => {
it('ADDONSREPO-012: matches SELECT * FROM addons WHERE id = ?, on both a pre-write read and a post-write re-select (byte-identical text at both call sites)', async () => {
insertAddon({ id: 'budget', name: 'Costs', description: 'Track spend', type: 'trip', icon: 'wallet', enabled: 0, sort_order: 4 });
const preWrite = await addons.findById('budget');
expect(preWrite).toEqual({ id: 'budget', name: 'Costs', description: 'Track spend', type: 'trip', icon: 'wallet', enabled: false, config: {}, sort_order: 4 });
testDb.prepare('UPDATE addons SET enabled = 1 WHERE id = ?').run('budget');
const postWrite = await addons.findById('budget');
expect(postWrite?.enabled).toBe(true);
});
it('ADDONSREPO-013: a missing id returns null', async () => {
expect(await addons.findById('does-not-exist')).toBeNull();
});
});
});
@@ -0,0 +1,79 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { DocumentProviders } from '../../../../src/db/entities/DocumentProviders.entity';
import type { DocumentProvidersRepository } from '../../../../src/db/repositories/DocumentProviders.repository';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let documentProviders: DocumentProvidersRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
documentProviders = t.repo(DocumentProviders);
});
beforeEach(() => {
resetTestDb(testDb);
// document_provider_fields FK-references document_providers, so clear the
// child first — resetTestDb keeps both tables (test-db.ts's KEEP_TABLES).
testDb.exec('DELETE FROM document_provider_fields');
testDb.exec('DELETE FROM document_providers');
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
function insertProvider(row: {
id: string;
name: string;
description?: string | null;
icon?: string | null;
enabled: 0 | 1;
sort_order?: number;
}): void {
testDb
.prepare('INSERT INTO document_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)')
.run(row.id, row.name, row.description ?? null, row.icon ?? null, row.enabled, row.sort_order ?? 0);
}
// Plan 3i Task 4 fix wave (should-land 5): AD29 (listAllOrdered) and AD32
// (findById) shipped in Task 1 with no repository-level test at all — this
// shared table (owned by 3h's doc-sync task; these two methods are 3i's
// additive admin-reuse per R6) had zero coverage of its own. One seeded
// world, full-key parity against the exact legacy SQL each method's own
// docstring names.
describe('DocumentProvidersRepository — admin (AD29/AD32) read methods, full-key parity', () => {
it('DOCPROVREPO-001 (AD29): listAllOrdered matches SELECT * FROM document_providers ORDER BY sort_order, id — unfiltered, including a disabled provider', async () => {
insertProvider({ id: 'paperless', name: 'Paperless', description: 'Self-hosted document management', icon: 'FileText', enabled: 0, sort_order: 1 });
insertProvider({ id: 'papra', name: 'Papra', enabled: 1, sort_order: 0 });
const legacy = testDb.prepare('SELECT * FROM document_providers ORDER BY sort_order, id').all();
const rows = await documentProviders.listAllOrdered();
expect(rows.map((r) => r.id)).toEqual(['papra', 'paperless']); // includes the disabled one, unlike listEnabledCatalog
// `enabled` stays the raw stored integer on this entity (no boolean
// coercion, unlike Addons.enabled), so the row shape is identical to the
// legacy `SELECT *` — no per-column remap needed.
expect(rows).toEqual(legacy);
});
it('DOCPROVREPO-002: listAllOrdered on an empty table returns an empty array', async () => {
expect(await documentProviders.listAllOrdered()).toEqual([]);
});
it('DOCPROVREPO-003 (AD32): findById matches SELECT * FROM document_providers WHERE id = ?, on both a pre-write read and a post-write re-select', async () => {
insertProvider({ id: 'paperless', name: 'Paperless', description: 'Self-hosted document management', icon: 'FileText', enabled: 0, sort_order: 3 });
const preWrite = await documentProviders.findById('paperless');
expect(preWrite).toEqual({ id: 'paperless', name: 'Paperless', description: 'Self-hosted document management', icon: 'FileText', enabled: 0, sort_order: 3 });
testDb.prepare('UPDATE document_providers SET enabled = 1 WHERE id = ?').run('paperless');
const postWrite = await documentProviders.findById('paperless');
expect(postWrite?.enabled).toBe(1);
});
it('DOCPROVREPO-004: findById on a missing id returns null', async () => {
expect(await documentProviders.findById('does-not-exist')).toBeNull();
});
});
@@ -109,3 +109,38 @@ describe('PhotoProviderFieldsRepository.listAllOrdered', () => {
expect(await fields.listAllOrdered()).toEqual([]);
});
});
describe('PhotoProviderFieldsRepository.listAllOrderedForAdminShelf', () => {
// Plan 3i Task 4 fix wave: `listAllOrderedForAdminShelf` used to project a
// bare `'provider_id'` — the `persist(false)` shadow of the `provider`
// relation — which MikroORM's `fields` selector never hydrates (same trap
// `RoadtripDayBoundariesRepository` and `TripPhotosRepository` document).
// Every row came back with `provider_id: undefined`, so `listAddons`
// grouped every photo provider's fields under `undefined` and every
// provider answered `fields: []`. Full-key parity against AD28's legacy
// `SELECT provider_id, field_key, label, input_type, placeholder,
// required, secret, settings_key, payload_key, sort_order FROM
// photo_provider_fields ORDER BY sort_order, id` pins every column, not
// just `provider_id`, so a future narrowed-projection regression on any
// other column fails here too.
it('AD28: returns the full legacy row shape, ordered by sort_order then id, across all providers', async () => {
insertProvider('immich');
insertProvider('synology');
insertField({ provider_id: 'synology', field_key: 'url', label: 'Server URL', input_type: 'text', placeholder: 'https://photos.example.com', hint: 'ignored: not in the AD28 shape', required: 1, secret: 0, settings_key: 'synology_url', payload_key: 'url', sort_order: 1 });
insertField({ provider_id: 'immich', field_key: 'url', label: 'Server URL', input_type: 'text', placeholder: 'https://immich.example.com', required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'url', sort_order: 0 });
insertField({ provider_id: 'immich', field_key: 'api_key', label: 'API Key', input_type: 'password', required: 1, secret: 1, settings_key: 'immich_api_key', payload_key: 'apiKey', sort_order: 1 });
const rows = await fields.listAllOrderedForAdminShelf();
// sort_order 0 first; the sort_order-1 tie breaks by id (insertion order:
// synology's url row was inserted before immich's api_key row).
expect(rows).toEqual([
{ provider_id: 'immich', field_key: 'url', label: 'Server URL', input_type: 'text', placeholder: 'https://immich.example.com', required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'url', sort_order: 0 },
{ provider_id: 'synology', field_key: 'url', label: 'Server URL', input_type: 'text', placeholder: 'https://photos.example.com', required: 1, secret: 0, settings_key: 'synology_url', payload_key: 'url', sort_order: 1 },
{ provider_id: 'immich', field_key: 'api_key', label: 'API Key', input_type: 'password', placeholder: null, required: 1, secret: 1, settings_key: 'immich_api_key', payload_key: 'apiKey', sort_order: 1 },
]);
});
it('AD28: an empty table returns an empty array', async () => {
expect(await fields.listAllOrderedForAdminShelf()).toEqual([]);
});
});
@@ -96,3 +96,37 @@ describe('PhotoProvidersRepository.listAll / findEnabled', () => {
expect(await photoProviders.findEnabled('does-not-exist')).toBeNull();
});
});
// Plan 3i Task 4 fix wave (should-land 5): AD27 (listAllOrdered) and
// AD31/AD40 (findById) shipped in Task 1 with no repository-level test —
// full-key parity against the exact legacy SQL each method's own docstring
// names.
describe('PhotoProvidersRepository.listAllOrdered (AD27) / findById (AD31/AD40)', () => {
it('ADDONSPPREPO-005: listAllOrdered matches SELECT id, name, description, icon, enabled, sort_order FROM photo_providers ORDER BY sort_order, id — unfiltered, including a disabled provider', async () => {
insertProvider({ id: 'off', name: 'Off', enabled: 0, sort_order: 1 });
insertProvider({ id: 'immich', name: 'Immich', enabled: 1, sort_order: 0 });
const legacy = testDb.prepare('SELECT id, name, description, icon, enabled, sort_order FROM photo_providers ORDER BY sort_order, id').all();
const rows = await photoProviders.listAllOrdered();
expect(rows.map((r) => r.id)).toEqual(['immich', 'off']); // includes the disabled one, unlike listEnabled
expect(rows).toEqual(legacy);
});
it('ADDONSPPREPO-006: listAllOrdered on an empty table returns an empty array', async () => {
expect(await photoProviders.listAllOrdered()).toEqual([]);
});
it('ADDONSPPREPO-007: findById matches SELECT * FROM photo_providers WHERE id = ?, on both a pre-write read and a post-write re-select (byte-identical text at both call sites)', async () => {
insertProvider({ id: 'immich', name: 'Immich', description: 'Self-hosted photos', icon: 'image', enabled: 0, sort_order: 2 });
const preWrite = await photoProviders.findById('immich');
expect(preWrite).toEqual({ id: 'immich', name: 'Immich', description: 'Self-hosted photos', icon: 'image', enabled: 0, sort_order: 2 });
testDb.prepare('UPDATE photo_providers SET enabled = 1 WHERE id = ?').run('immich');
const postWrite = await photoProviders.findById('immich');
expect(postWrite?.enabled).toBe(1);
});
it('ADDONSPPREPO-008: findById on a missing id returns null', async () => {
expect(await photoProviders.findById('does-not-exist')).toBeNull();
});
});
@@ -2,7 +2,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { createUser, createAdmin } from '../../../helpers/factories';
import { createUser, createAdmin, type TestUser } from '../../../helpers/factories';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { UsersRepository } from '../../../../src/db/repositories/Users.repository';
@@ -1000,3 +1000,101 @@ describe('UsersRepository — feed tokens (Plan 3d Task 5, FD5-FD8/FD10)', () =>
expect(await users.findUsernameEmail(999999)).toBeUndefined();
});
});
// Plan 3i Task 4 fix wave (should-land 5): admin's AD1-AD17 read methods
// (listForAdmin, findAdminSummary, findIdEmailMfaEnabled, and the four
// exact/excluding uniqueness lookups) shipped in Task 1 (862799062) with no
// repository-level parity test of their own — only the live HTTP surface was
// checked. One seeded world (an admin, a plain user and a guest, so the
// `is_guest` exclusion has something to exclude), one full-key `toEqual`
// test per read method against the exact legacy projection named in each
// method's own docstring.
describe('UsersRepository — admin (AD1-AD17) read methods, full-key parity', () => {
let admin: TestUser;
let plain: TestUser;
let guest: TestUser;
beforeEach(() => {
admin = createAdmin(testDb, { username: 'ad-admin', email: 'ad-admin@example.com' }).user;
plain = createUser(testDb, { username: 'ad-plain', email: 'ad-plain@example.com' }).user;
const { user: guestRow } = createUser(testDb, { username: 'ad-guest', email: 'ad-guest@example.com' });
testDb.prepare('UPDATE users SET is_guest = 1 WHERE id = ?').run(guestRow.id);
guest = { ...guestRow, } as TestUser;
});
it('USERSREPO-078 (AD1): listForAdmin matches SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users WHERE COALESCE(is_guest, 0) = 0 ORDER BY created_at DESC, and excludes the guest row', async () => {
const legacy = testDb
.prepare('SELECT id, username, email, role, avatar, created_at, updated_at, last_login FROM users WHERE COALESCE(is_guest, 0) = 0 ORDER BY created_at DESC')
.all();
const rows = await users.listForAdmin();
expect(rows).toEqual(legacy);
expect(rows.map((r) => r.id)).not.toContain(guest.id);
expect(rows.map((r) => r.id)).toEqual(expect.arrayContaining([admin.id, plain.id]));
});
it('USERSREPO-079 (AD2/AD3): findIdByUsernameExact/findIdByEmailExact are case-sensitive and exclude guests', async () => {
expect(await users.findIdByUsernameExact('ad-admin')).toBe(admin.id);
expect(await users.findIdByUsernameExact('AD-ADMIN')).toBeNull(); // case-sensitive, unlike findIdByUsernameCIAny
expect(await users.findIdByUsernameExact('ad-guest')).toBeNull(); // guest excluded
expect(await users.findIdByEmailExact('ad-plain@example.com')).toBe(plain.id);
expect(await users.findIdByEmailExact('AD-PLAIN@EXAMPLE.COM')).toBeNull();
expect(await users.findIdByEmailExact('ad-guest@example.com')).toBeNull();
});
it('USERSREPO-080 (AD4/AD5): insertAdminCreatedUser stores exactly the four named columns, every other column left to the entity default, then findAdminSummary re-selects it', async () => {
const id = await users.insertAdminCreatedUser({ username: 'ad-new', email: 'ad-new@example.com', password_hash: 'hash-x', role: 'user' });
const legacyRow = testDb.prepare('SELECT * FROM users WHERE id = ?').get(id) as Record<string, unknown>;
expect(legacyRow.username).toBe('ad-new');
expect(legacyRow.email).toBe('ad-new@example.com');
expect(legacyRow.password_hash).toBe('hash-x');
expect(legacyRow.role).toBe('user');
// Every column the legacy INSERT omitted falls back to the schema DEFAULT
// — the AUDIT for the 3i review's own "INSERT entity defaults" pass.
expect(legacyRow.mfa_enabled).toBe(0);
expect(legacyRow.first_seen_version).toBe('0.0.0');
expect(legacyRow.login_count).toBe(0);
expect(legacyRow.is_guest).toBe(0);
const legacySummary = testDb.prepare('SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?').get(id);
expect(await users.findAdminSummary(id)).toEqual(legacySummary);
});
it('USERSREPO-081 (AD14): findAdminSummary matches the byte-identical re-select text on an EXISTING (updated) row too', async () => {
testDb.prepare('UPDATE users SET username = ?, role = ? WHERE id = ?').run('ad-plain-renamed', 'admin', plain.id);
const legacy = testDb.prepare('SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ?').get(plain.id);
expect(await users.findAdminSummary(plain.id)).toEqual(legacy);
expect(await users.findAdminSummary(999999)).toBeNull();
});
it('USERSREPO-082 (AD7/AD8): findIdByUsernameExactExcluding/findIdByEmailExactExcluding exclude the caller\'s own row, case-sensitive, guests excluded', async () => {
// Renaming plain to admin's own username, excluding plain's own id, must
// still find admin's row — that's the whole point of the check.
expect(await users.findIdByUsernameExactExcluding('ad-admin', plain.id)).toBe(admin.id);
expect(await users.findIdByUsernameExactExcluding('ad-plain', plain.id)).toBeNull(); // excludes self
expect(await users.findIdByUsernameExactExcluding('ad-guest', plain.id)).toBeNull(); // guest excluded
expect(await users.findIdByEmailExactExcluding('ad-admin@example.com', plain.id)).toBe(admin.id);
expect(await users.findIdByEmailExactExcluding('ad-plain@example.com', plain.id)).toBeNull();
});
it('USERSREPO-083 (AD11): applyAdminEdit only touches the keys supplied (coalesceParam semantics) and always stamps updated_at', async () => {
const before = testDb.prepare('SELECT email, updated_at FROM users WHERE id = ?').get(plain.id) as { email: string; updated_at: string };
// CURRENT_TIMESTAMP has 1-second resolution — wait past a tick so a
// genuine "always stamped" pass is distinguishable from a no-op.
await new Promise((r) => setTimeout(r, 1100));
await users.applyAdminEdit(plain.id, { username: 'ad-plain-2' });
const after = testDb.prepare('SELECT username, email, updated_at FROM users WHERE id = ?').get(plain.id) as { username: string; email: string; updated_at: string };
expect(after.username).toBe('ad-plain-2');
// email was NOT in the patch, so it is unchanged — the coalesceParam
// "new value wins when supplied, existing column wins when omitted" shape.
expect(after.email).toBe(before.email);
// updated_at is stamped unconditionally, even though only username changed.
expect(after.updated_at).not.toBe(before.updated_at);
});
it('USERSREPO-084 (AD16): findIdEmailMfaEnabled matches SELECT id, email, mfa_enabled FROM users WHERE id = ?', async () => {
testDb.prepare('UPDATE users SET mfa_enabled = 1 WHERE id = ?').run(admin.id);
const legacy = testDb.prepare('SELECT id, email, mfa_enabled FROM users WHERE id = ?').get(admin.id);
expect(await users.findIdEmailMfaEnabled(admin.id)).toEqual(legacy);
expect(await users.findIdEmailMfaEnabled(999999)).toBeNull();
});
});
+52 -4
View File
@@ -406,25 +406,46 @@ describe('saveDemoBaseline', () => {
vi.unstubAllEnvs();
});
it('ADMIN-SVC-050 — returns 404 when DEMO_MODE is not "true"', () => {
it('ADMIN-SVC-050 — returns 404 when DEMO_MODE is not "true"', async () => {
vi.stubEnv('DEMO_MODE', 'false');
const result = saveDemoBaseline() as any;
const result = (await saveDemoBaseline()) as any;
expect(result.status).toBe(404);
expect(result.error).toBeDefined();
});
it('ADMIN-SVC-051 — returns a defined result object when DEMO_MODE is "true"', () => {
it('ADMIN-SVC-051 — returns a defined result object when DEMO_MODE is "true"', async () => {
// saveDemoBaseline() uses a dynamic CJS require() whose mock cannot be
// intercepted via vi.mock in this test environment (tsx runtime + CJS loader).
// The function either succeeds (message) or falls through the catch to a
// 500 error. Either way the result must be a defined, non-null object.
vi.stubEnv('DEMO_MODE', 'true');
const result = saveDemoBaseline() as any;
const result = (await saveDemoBaseline()) as any;
expect(result).toBeDefined();
expect(typeof result).toBe('object');
// The 404 branch must NOT be taken — DEMO_MODE is "true".
expect(result.status).not.toBe(404);
});
// Plan 3i Task 4 fix wave (must-land 3): before this fix, AdminService
// #saveDemoBaseline called the now-async saveBaseline() without awaiting
// it, so a copy failure (proven live in task-4-review.md with a real
// EISDIR from fs.copyFileSync) went nowhere — the route answered 200 and
// the rejection later surfaced as an unhandled rejection that crashed the
// process. This suite's dynamic require()s of demo-reset.ts (and, inside
// it, db/database.ts) bypass this file's top-of-file vi.mock, same
// documented limitation as ADMIN-SVC-051 — so instead of mocking, this
// test lets the REAL saveBaseline() run with no RequestContext
// established, which deterministically rejects at its own
// requireEntityManager() guard: the same "the copy failed" shape a real
// EISDIR would produce, without touching the filesystem. Awaiting that
// rejection (the fix) means the service's own try/catch converts it into
// the legacy 500 body, and this test resolving cleanly (not hanging, no
// unhandledRejection) is itself proof the rejection was actually caught.
it('ADMIN-SVC-095 — a failed baseline save is awaited and answers the legacy 500, not an unhandled rejection', async () => {
vi.stubEnv('DEMO_MODE', 'true');
const result = await saveDemoBaseline();
expect(result).toEqual({ error: 'Failed to save baseline', status: 500 });
});
});
// ── getGithubReleases ─────────────────────────────────────────────────────────
@@ -534,6 +555,33 @@ describe('listAddons', () => {
expect(addonIds).toContain('packing');
expect(addonIds).toContain('budget');
});
// Plan 3i Task 4 fix wave (AD28): `listAllOrderedForAdminShelf` used to
// project the `persist(false)` shadow `provider_id`, which MikroORM never
// hydrates through a narrowed `fields` selection — every photo provider's
// `fields` grouped under `undefined` and every provider answered `fields:
// []`. Immich's own connection settings live on `users` columns from an
// earlier schema shape (see `users_add_immich_url`), so it seeds no
// `photo_provider_fields` rows and is not useful for this assertion —
// Synology Photos is the seeded provider that actually owns rows in the
// generic catalog (url/username/password/otp/skip_ssl), so it is the one
// that pins the defect: before the fix every one of its 5 seeded fields
// vanished into the `undefined` group instead.
it('ADMIN-SVC-066 — Synology Photos carries its seeded field catalog, not fields: []', async () => {
const result = await listAddons();
const immich = result.find((entry) => entry.id === 'immich');
const synology = result.find((entry) => entry.id === 'synologyphotos');
expect(immich).toBeDefined();
expect(synology).toBeDefined();
if (!synology || !('fields' in synology)) throw new Error('synologyphotos entry is missing a fields array');
expect(synology.fields.map((f) => f.key)).toEqual([
'synology_url',
'synology_username',
'synology_password',
'synology_otp',
'synology_skip_ssl',
]);
});
});
// ── updateAddon ───────────────────────────────────────────────────────────────
@@ -72,10 +72,13 @@ const maintenanceRepoMock = vi.hoisted(() => ({
vacuumInto: vi.fn().mockResolvedValue(undefined),
}));
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/db/repositories/MaintenanceRepository', () => ({
MaintenanceRepository: vi.fn().mockImplementation(() => maintenanceRepoMock),
}));
vi.mock('../../../src/nest/audit/audit-log.logger', () => logMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
ENCRYPTION_KEY: 'a'.repeat(64),
@@ -579,6 +582,14 @@ describe('BACKUP-036 createBackup', () => {
expect.stringContaining('travel-snap-backup-'),
expect.anything(),
);
// Plan 3i Task 4 fix wave (should-land 7): the missing-EntityManager
// fallback used to be entirely silent — same swallowed shape as a real
// disk/lock VACUUM INTO failure, with no way for an operator to tell
// "archived the live file because no request context wrapped this run"
// apart from any other reason. Both guards (BK1's checkpoint skip, BK2's
// snapshot skip) now log a warning; the fallback itself is unchanged.
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('skipping the WAL checkpoint'));
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('archiving the live travel.db instead of a VACUUM INTO snapshot'));
});
it('BACKUP-036e — excludes the re-derivable photo caches nested under photos/', async () => {