refactor(addons): addon catalog and photo providers through repositories

This commit is contained in:
jubnl
2026-09-22 14:06:57 +02:00
parent aa1067035f
commit 6db91c8bf3
31 changed files with 1083 additions and 462 deletions
+329 -298
View File
@@ -1,27 +1,53 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Three distinct prepare(...).all() reads (addons, photo_providers, photo_provider_fields).
// A single shared statement is reused, so .all() is fed result sets in call order.
const { dbMock } = vi.hoisted(() => {
const stmt = { get: vi.fn(), all: vi.fn(() => []), run: vi.fn() };
// Takes the statement text, as the real one does: a reader that inlines its
// key in the SQL is identified by that string and by nothing else.
return { dbMock: { prepare: vi.fn((_sql?: string) => stmt), _stmt: stmt } };
});
vi.mock('../../../src/db/database', () => ({ db: dbMock, closeDb: () => {}, reinitialize: () => {} }));
import { db as dbConn } from '../../../src/db/database';
/**
* Unit tests for AddonsService — rebuilt on real rows (Plan 3a Task 4).
*
* The legacy version of this file fully stubbed DatabaseService at the
* `db.prepare(sql).{get,all,run}` level: a single shared fake `stmt` fed
* canned rows *in call order* (three `.all()` reads for addons/providers/
* fields, a `.get()` for the journey gate, and so on). That coupling cannot
* survive AddonsService now calling four different repositories instead of
* one shared prepared statement, so every case here runs against a real
* in-memory SQLite DB (createTestOrm) and inserts the exact rows it needs.
*
* Two cases needed their INTENT re-expressed, not just their mechanics
* (noted at each): the legacy `list()` SQL filters `WHERE enabled = 1` on
* both `addons` and `photo_providers`, so a disabled row is never returned by
* the real query — the old mocked tests fed a disabled row through anyway
* (mocks don't enforce a WHERE clause) to prove the service's `!!enabled`
* coercion handled `0`. That coercion is still real (and still asserted
* directly, on `isAddonEnabled` and on an enabled row's boolean in `list()`),
* but "list() returns a disabled addon/provider with enabled: false" is not a
* reachable production behaviour, so those two cases now assert the WHERE
* filter itself (the disabled row is excluded) alongside the boolean coercion
* of the enabled row that remains.
*/
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach, afterAll } from 'vitest';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { resetTestDb } from '../../helpers/test-db';
import { createUser } from '../../helpers/factories';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { PlaceShadowService } from '../../../src/nest/place-shadow/place-shadow.service';
import { Addons } from '../../../src/db/entities/Addons.entity';
import type { AddonsRepository } from '../../../src/db/repositories/Addons.repository';
import { PhotoProviders } from '../../../src/db/entities/PhotoProviders.entity';
import type { PhotoProvidersRepository } from '../../../src/db/repositories/PhotoProviders.repository';
import { PhotoProviderFields } from '../../../src/db/entities/PhotoProviderFields.entity';
import type { PhotoProviderFieldsRepository } from '../../../src/db/repositories/PhotoProviderFields.repository';
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository';
const { getPhotoProviderConfig } = vi.hoisted(() => ({ getPhotoProviderConfig: vi.fn(() => ({})) }));
vi.mock('../../../src/nest/memories/memories.helpers', () => ({ getPhotoProviderConfig }));
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { PlaceShadowService } from '../../../src/nest/place-shadow/place-shadow.service';
import { MapsService } from '../../../src/nest/maps/maps.service';
function svc() {
return new AddonsService(new DatabaseService(dbConn));
}
const testDb = createSnapshotTestDb();
let t: TestOrm;
let addonsRepo: AddonsRepository;
let photoProvidersRepo: PhotoProvidersRepository;
let photoProviderFieldsRepo: PhotoProviderFieldsRepository;
let appSettingsRepo: AppSettingsRepository;
let svc: AddonsService;
type ListAddon = Awaited<ReturnType<AddonsService['list']>>['addons'][number];
@@ -47,68 +73,143 @@ function providerFields(addon: ListAddon): PhotoProviderField[] {
return (addon as ListAddon & { fields: PhotoProviderField[] }).fields;
}
// Feed list()'s reads in call order: addons, providers, fields (.all), then the
// collab-features rows (.all) and the bag-tracking row (.get) from app_settings.
// The provider query now sits behind an isAddonEnabled(journey) read (.get), fed
// first as enabled so every case below sees its providers.
function feedReads(
addons: unknown[],
providers: unknown[],
fields: unknown[],
collabRows: unknown[] = [],
bagRow: { value: string } | undefined = undefined,
) {
dbMock._stmt.all
.mockReturnValueOnce(addons)
.mockReturnValueOnce(providers)
.mockReturnValueOnce(fields)
.mockReturnValueOnce(collabRows);
dbMock._stmt.get.mockReturnValueOnce({ enabled: 1 }).mockReturnValueOnce(bagRow);
function insertAddon(row: { id: string; name: string; type?: string; icon?: string | null; enabled: 0 | 1; sort_order?: number }): void {
testDb
.prepare('INSERT INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, NULL, ?, ?, ?, ?)')
.run(row.id, row.name, row.type ?? 'global', row.icon ?? null, row.enabled, row.sort_order ?? 0);
}
/**
* Stubs the journey gate `list()` checks before reading photo providers,
* WITHOUT inserting a real 'journey' addons row. A real row is what the
* migration seeds (`journey_addon.ts`) and is exactly what `isAddonEnabled`
* should read in production — but inserting one here would also make it a
* genuine, `enabled: true` member of `listEnabled()`'s own result (the same
* WHERE-clause reality the file header's two re-expressed cases describe),
* which would pollute every one of these provider/field-shape assertions
* with an unrelated 'journey' entry. Spying on the one repository call the
* gate makes keeps these tests about provider/field shaping, not about
* `list()`'s addons array — that array is already covered by the addons-
* focused cases above.
*/
function stubJourneyEnabled(): ReturnType<typeof vi.spyOn> {
return vi.spyOn(addonsRepo, 'isEnabled').mockImplementation(async (id: string) => id === 'journey');
}
function insertProvider(row: { id: string; name: string; icon?: string | null; enabled: 0 | 1; sort_order?: number }): void {
testDb
.prepare('INSERT INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, NULL, ?, ?, ?)')
.run(row.id, row.name, row.icon ?? null, row.enabled, row.sort_order ?? 0);
}
function insertField(row: {
provider_id: string;
field_key: string;
label: string;
input_type?: string;
placeholder?: string | null;
hint?: string | null;
required?: 0 | 1;
secret?: 0 | 1;
settings_key?: string | null;
payload_key?: string | null;
sort_order?: number;
}): void {
testDb
.prepare(
`INSERT INTO photo_provider_fields
(provider_id, field_key, label, input_type, placeholder, hint, required, secret, settings_key, payload_key, sort_order)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
row.provider_id,
row.field_key,
row.label,
row.input_type ?? 'text',
row.placeholder ?? null,
row.hint ?? null,
row.required ?? 0,
row.secret ?? 0,
row.settings_key ?? null,
row.payload_key ?? null,
row.sort_order ?? 0,
);
}
function setAppSetting(key: string, value: string | null): void {
testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(key, value);
}
function rawAppSetting(key: string): { key: string; value: string | null } | undefined {
return testDb.prepare('SELECT key, value FROM app_settings WHERE key = ?').get(key) as
| { key: string; value: string | null }
| undefined;
}
beforeAll(async () => {
t = await createTestOrm(testDb);
addonsRepo = t.repo(Addons) as AddonsRepository;
photoProvidersRepo = t.repo(PhotoProviders) as PhotoProvidersRepository;
photoProviderFieldsRepo = t.repo(PhotoProviderFields) as PhotoProviderFieldsRepository;
appSettingsRepo = t.repo(AppSettings) as AppSettingsRepository;
});
beforeEach(() => {
vi.clearAllMocks();
dbMock._stmt.all.mockReturnValue([]);
dbMock._stmt.get.mockReturnValue(undefined);
resetTestDb(testDb);
// resetTestDb keeps the seeded addons/photo_providers/photo_provider_fields
// catalogue (test-db.ts's KEEP_TABLES) — every case here wants a known,
// empty starting point and inserts exactly the rows it needs.
testDb.exec('DELETE FROM photo_provider_fields');
testDb.exec('DELETE FROM photo_providers');
testDb.exec('DELETE FROM addons');
t.clear();
getPhotoProviderConfig.mockReset();
getPhotoProviderConfig.mockReturnValue({});
svc = new AddonsService(addonsRepo, photoProvidersRepo, photoProviderFieldsRepo, appSettingsRepo, new DatabaseService(testDb));
});
afterEach(() => {
// Restores stubJourneyEnabled's spy on addonsRepo.isEnabled (and the "drops
// the photo providers" case's spy on photoProvidersRepo.listEnabled) so no
// stub outlives the test that set it up.
vi.restoreAllMocks();
});
afterAll(async () => {
await t.close();
testDb.close();
});
describe('AddonsService.list', () => {
it('returns the collab features and the bag-tracking flag from app_settings', async () => {
feedReads([], [], [], [{ key: 'collab_chat_enabled', value: 'false' }], { value: 'true' });
setAppSetting('collab_chat_enabled', 'false');
setAppSetting('bag_tracking_enabled', 'true');
const res = await svc().list();
const res = await svc.list();
expect(res.collabFeatures).toEqual({ chat: false, notes: true, links: true, polls: true, whatsnext: true });
expect(res.bagTracking).toBe(true);
expect(res.addons).toEqual([]);
});
it('coerces the addon enabled column to a boolean (both 1 and 0)', async () => {
feedReads(
[
{ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: 1 },
{ id: 'vacay', name: 'Vacay', type: 'page', icon: 'sun', enabled: 0 },
],
[],
[],
);
// Re-expressed (see file header): the legacy WHERE enabled = 1 makes a
// disabled row in list()'s output unreachable, so this now proves the
// filter (the disabled row never surfaces) and the boolean coercion of the
// enabled row that does (the entity's `enabled` is p.boolean(), so the
// stored int comes back as a real JS boolean, not just truthy).
it('only returns enabled addons, with the stored int coerced to a JS boolean', async () => {
insertAddon({ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: 1 });
insertAddon({ id: 'vacay', name: 'Vacay', type: 'page', icon: 'sun', enabled: 0 });
const res = await svc().list();
expect(res.addons).toEqual([
{ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: true },
{ id: 'vacay', name: 'Vacay', type: 'page', icon: 'sun', enabled: false },
]);
const res = await svc.list();
expect(res.addons).toEqual([{ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: true }]);
});
it('maps a photo provider with no fields to an empty fields array (the || [] fallback)', async () => {
feedReads(
[],
[{ id: 'immich', name: 'Immich', icon: 'image', enabled: 1, sort_order: 0 }],
[],
);
stubJourneyEnabled();
insertProvider({ id: 'immich', name: 'Immich', icon: 'image', enabled: 1 });
getPhotoProviderConfig.mockReturnValue({ baseUrl: 'http://x' });
const res = await svc().list();
const res = await svc.list();
expect(res.addons).toEqual([
{
id: 'immich',
@@ -123,53 +224,49 @@ describe('AddonsService.list', () => {
expect(getPhotoProviderConfig).toHaveBeenCalledWith('immich');
});
it('coerces a disabled photo provider enabled flag to false', async () => {
feedReads(
[],
[{ id: 'synology', name: 'Synology', icon: 'image', enabled: 0, sort_order: 1 }],
[],
);
// Re-expressed for the same reason as the addons case above: a disabled
// photo_providers row is filtered out by listEnabled()'s WHERE clause, so
// this now proves that filter alongside the enabled row's integer→boolean
// coercion (photo_providers.enabled is p.integer(), not p.boolean() —
// AddonsService does the `!!` itself, unlike the Addons entity above).
it('only returns enabled photo providers, with the stored integer coerced to a JS boolean', async () => {
stubJourneyEnabled();
insertProvider({ id: 'synology', name: 'Synology', icon: 'image', enabled: 1, sort_order: 1 });
insertProvider({ id: 'off-provider', name: 'Off', icon: 'image', enabled: 0, sort_order: 2 });
const res = await svc().list();
expect((res.addons[0] as { enabled: boolean }).enabled).toBe(false);
const res = await svc.list();
expect(res.addons.map((a) => (a as { id: string }).id)).toEqual(['synology']);
expect((res.addons[0] as { enabled: boolean }).enabled).toBe(true);
});
it('groups multiple fields under their provider and keeps insertion order', async () => {
feedReads(
[],
[{ id: 'immich', name: 'Immich', icon: 'image', enabled: 1, sort_order: 0 }],
[
{
provider_id: 'immich',
field_key: 'url',
label: 'URL',
input_type: 'text',
placeholder: 'https://',
hint: 'Base URL',
required: 1,
secret: 0,
settings_key: 'immich_url',
payload_key: 'url',
sort_order: 0,
},
// Second field for the SAME provider exercises the `get(...) || []` truthy branch.
{
provider_id: 'immich',
field_key: 'token',
label: 'Token',
input_type: 'password',
placeholder: null,
hint: null,
required: 0,
secret: 1,
settings_key: null,
payload_key: null,
sort_order: 1,
},
],
);
stubJourneyEnabled();
insertProvider({ id: 'immich', name: 'Immich', icon: 'image', enabled: 1 });
insertField({
provider_id: 'immich',
field_key: 'url',
label: 'URL',
input_type: 'text',
placeholder: 'https://',
hint: 'Base URL',
required: 1,
secret: 0,
settings_key: 'immich_url',
payload_key: 'url',
sort_order: 0,
});
// Second field for the SAME provider exercises the `get(...) || []` truthy branch.
insertField({
provider_id: 'immich',
field_key: 'token',
label: 'Token',
input_type: 'password',
required: 0,
secret: 1,
sort_order: 1,
});
const res = await svc().list();
const res = await svc.list();
expect(providerFields(res.addons[0])).toEqual([
{
key: 'url',
@@ -199,24 +296,11 @@ describe('AddonsService.list', () => {
});
it('falls back placeholder→"", hint→null, settings/payload keys→null when columns are missing/empty', async () => {
feedReads(
[],
[{ id: 'p', name: 'P', icon: 'i', enabled: 1, sort_order: 0 }],
[
{
provider_id: 'p',
field_key: 'k',
label: 'L',
input_type: 'text',
// placeholder/hint/settings_key/payload_key omitted entirely (undefined)
required: 0,
secret: 0,
sort_order: 0,
},
],
);
stubJourneyEnabled();
insertProvider({ id: 'p', name: 'P', icon: 'i', enabled: 1 });
insertField({ provider_id: 'p', field_key: 'k', label: 'L' }); // placeholder/hint/settings_key/payload_key all null
const res = await svc().list();
const res = await svc.list();
const field = providerFields(res.addons[0])[0];
expect(field).toMatchObject({
placeholder: '',
@@ -227,53 +311,38 @@ describe('AddonsService.list', () => {
});
it('keeps fields belonging to other providers out of a provider with none of its own', async () => {
stubJourneyEnabled();
// A field exists, but for a DIFFERENT provider than the one returned — exercises
// the `fieldsByProvider.get(p.id) || []` fallback while the map is non-empty.
feedReads(
[],
[{ id: 'has-none', name: 'X', icon: 'i', enabled: 1, sort_order: 0 }],
[
{
provider_id: 'other',
field_key: 'k',
label: 'L',
input_type: 'text',
required: 0,
secret: 0,
sort_order: 0,
},
],
);
insertProvider({ id: 'has-none', name: 'X', icon: 'i', enabled: 1 });
insertProvider({ id: 'other', name: 'Other', icon: 'i', enabled: 0 }); // FK target for the field below
insertField({ provider_id: 'other', field_key: 'k', label: 'L' });
const res = await svc().list();
const res = await svc.list();
expect(providerFields(res.addons[0])).toEqual([]);
});
it('concatenates regular addons before the photo providers', async () => {
feedReads(
[{ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: 1 }],
[{ id: 'immich', name: 'Immich', icon: 'image', enabled: 1, sort_order: 0 }],
[],
);
stubJourneyEnabled();
insertAddon({ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: 1 });
insertProvider({ id: 'immich', name: 'Immich', icon: 'image', enabled: 1 });
const res = await svc().list();
const res = await svc.list();
expect(res.addons.map((a) => (a as { id: string }).id)).toEqual(['atlas', 'immich']);
expect((res.addons[1] as { type: string }).type).toBe('photo_provider');
});
it('drops the photo providers while the journey addon is off, whatever their rows say', async () => {
// The journey gate (.get) answers disabled, so the provider query is never
// made and the .all chain shortens to addons, fields, collab.
dbMock._stmt.get.mockReturnValueOnce({ enabled: 0 });
dbMock._stmt.all
.mockReturnValueOnce([{ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: 1 }])
.mockReturnValueOnce([])
.mockReturnValueOnce([]);
// No 'journey' row at all — isAddonEnabled('journey') reads false, same as
// the legacy `!!undefined`.
insertAddon({ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: 1 });
insertProvider({ id: 'immich', name: 'Immich', icon: 'image', enabled: 1 });
const listSpy = vi.spyOn(photoProvidersRepo, 'listEnabled');
const res = await svc().list();
const res = await svc.list();
expect(res.addons).toEqual([{ id: 'atlas', name: 'Atlas', type: 'page', icon: 'globe', enabled: true }]);
const providerReads = (dbMock.prepare.mock.calls as unknown[][]).filter((call) => String(call[0]).includes('FROM photo_providers'));
expect(providerReads).toEqual([]);
expect(listSpy).not.toHaveBeenCalled();
listSpy.mockRestore();
});
});
@@ -282,62 +351,65 @@ describe('AddonsService.list', () => {
// purpose: bag tracking is opt-in (=== 'true'), collab flags opt-out (!== 'false').
describe('AddonsService addon/feature flags', () => {
it('isAddonEnabled coerces the enabled column (1/0/missing row)', async () => {
dbMock._stmt.get.mockReturnValueOnce({ enabled: 1 });
expect(await svc().isAddonEnabled('budget')).toBe(true);
dbMock._stmt.get.mockReturnValueOnce({ enabled: 0 });
expect(await svc().isAddonEnabled('budget')).toBe(false);
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(await svc().isAddonEnabled('nope')).toBe(false);
insertAddon({ id: 'budget', name: 'Budget', enabled: 1 });
expect(await svc.isAddonEnabled('budget')).toBe(true);
testDb.prepare('UPDATE addons SET enabled = 0 WHERE id = ?').run('budget');
expect(await svc.isAddonEnabled('budget')).toBe(false);
expect(await svc.isAddonEnabled('nope')).toBe(false);
});
it('getBagTracking is opt-in: only the literal string true enables it', async () => {
dbMock._stmt.get.mockReturnValueOnce({ value: 'true' });
expect(await svc().getBagTracking()).toEqual({ enabled: true });
dbMock._stmt.get.mockReturnValueOnce({ value: 'false' });
expect(await svc().getBagTracking()).toEqual({ enabled: false });
dbMock._stmt.get.mockReturnValueOnce(undefined); // absent row → OFF
expect(await svc().getBagTracking()).toEqual({ enabled: false });
setAppSetting('bag_tracking_enabled', 'true');
expect(await svc.getBagTracking()).toEqual({ enabled: true });
setAppSetting('bag_tracking_enabled', 'false');
expect(await svc.getBagTracking()).toEqual({ enabled: false });
testDb.prepare("DELETE FROM app_settings WHERE key = 'bag_tracking_enabled'").run();
expect(await svc.getBagTracking()).toEqual({ enabled: false }); // absent row → OFF
});
it('updateBagTracking persists true/false strings and echoes the flag (ADMIN-SVC-030)', async () => {
expect(await svc().updateBagTracking(true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenCalledWith('true');
expect(await svc().updateBagTracking(false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenCalledWith('false');
expect(await svc.updateBagTracking(true)).toEqual({ enabled: true });
expect(rawAppSetting('bag_tracking_enabled')).toEqual({ key: 'bag_tracking_enabled', value: 'true' });
expect(await svc.updateBagTracking(false)).toEqual({ enabled: false });
expect(rawAppSetting('bag_tracking_enabled')).toEqual({ key: 'bag_tracking_enabled', value: 'false' });
});
it('getCollabFeatures is opt-out: absent rows default ON, only false disables', async () => {
dbMock._stmt.all.mockReturnValueOnce([
{ key: 'collab_chat_enabled', value: 'false' },
{ key: 'collab_polls_enabled', value: 'true' },
]);
expect(await svc().getCollabFeatures()).toEqual({ chat: false, notes: true, links: true, polls: true, whatsnext: true });
setAppSetting('collab_chat_enabled', 'false');
setAppSetting('collab_polls_enabled', 'true');
expect(await svc.getCollabFeatures()).toEqual({ chat: false, notes: true, links: true, polls: true, whatsnext: true });
});
it('updateCollabFeatures writes only the provided flags and reports changed (#1414, ADMIN-SVC-070)', async () => {
const setValueSpy = vi.spyOn(appSettingsRepo, 'setValue');
// before-read: all default ON; after-read: chat flipped off → changed
dbMock._stmt.all.mockReturnValueOnce([]).mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }]);
const first = await svc().updateCollabFeatures({ chat: false });
const first = await svc.updateCollabFeatures({ chat: false });
expect(first.changed).toBe(true);
expect(first.features.chat).toBe(false);
expect(dbMock._stmt.run).toHaveBeenCalledTimes(1);
expect(dbMock._stmt.run).toHaveBeenCalledWith('collab_chat_enabled', 'false');
expect(setValueSpy).toHaveBeenCalledTimes(1);
expect(setValueSpy).toHaveBeenCalledWith('collab_chat_enabled', 'false');
expect(rawAppSetting('collab_chat_enabled')).toEqual({ key: 'collab_chat_enabled', value: 'false' });
// identical save → before and after read the same → no change, MCP sessions must survive
dbMock._stmt.run.mockClear();
dbMock._stmt.all
.mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }])
.mockReturnValueOnce([{ key: 'collab_chat_enabled', value: 'false' }]);
const second = await svc().updateCollabFeatures({ chat: false });
setValueSpy.mockClear();
const second = await svc.updateCollabFeatures({ chat: false });
expect(second.changed).toBe(false);
expect(dbMock._stmt.run).toHaveBeenCalledWith('collab_chat_enabled', 'false');
expect(setValueSpy).toHaveBeenCalledWith('collab_chat_enabled', 'false');
// undefined flags are not written
dbMock._stmt.run.mockClear();
dbMock._stmt.all.mockReturnValueOnce([]).mockReturnValueOnce([]);
const third = await svc().updateCollabFeatures({});
setValueSpy.mockClear();
const third = await svc.updateCollabFeatures({});
expect(third.changed).toBe(false);
expect(dbMock._stmt.run).not.toHaveBeenCalled();
expect(setValueSpy).not.toHaveBeenCalled();
setValueSpy.mockRestore();
});
});
@@ -349,10 +421,6 @@ describe('AddonsService addon/feature flags', () => {
* 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'],
@@ -361,29 +429,28 @@ describe('AddonsService places flags', () => {
it('ADDONS-SVC-080 an unset flag reads as OFF, and anything but the literal true does too', async () => {
for (const [getter, , key] of cases) {
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(await svc()[getter]()).toEqual({ enabled: false });
expect(dbMock.prepare).toHaveBeenLastCalledWith('SELECT value FROM app_settings WHERE key = ?');
expect(dbMock._stmt.get).toHaveBeenLastCalledWith(key);
testDb.prepare('DELETE FROM app_settings WHERE key = ?').run(key);
expect(await svc[getter]()).toEqual({ enabled: false });
dbMock._stmt.get.mockReturnValueOnce({ value: 'garbage' });
expect(await svc()[getter]()).toEqual({ enabled: false });
setAppSetting(key, 'garbage');
expect(await svc[getter]()).toEqual({ enabled: false });
}
});
it('ADDONS-SVC-081 a stored "true" reads as ON', async () => {
for (const [getter] of cases) {
dbMock._stmt.get.mockReturnValueOnce({ value: 'true' });
expect(await svc()[getter]()).toEqual({ enabled: true });
for (const [getter, , key] of cases) {
setAppSetting(key, 'true');
expect(await svc[getter]()).toEqual({ enabled: true });
}
});
it('ADDONS-SVC-082 the setters persist the literal string and echo the boolean back', async () => {
for (const [, setter, key] of cases) {
expect(await svc()[setter](true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith(key, 'true');
expect(await svc()[setter](false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith(key, 'false');
expect(await svc[setter](true)).toEqual({ enabled: true });
expect(rawAppSetting(key)).toEqual({ key, value: 'true' });
expect(await svc[setter](false)).toEqual({ enabled: false });
expect(rawAppSetting(key)).toEqual({ key, value: 'false' });
}
});
});
@@ -399,30 +466,26 @@ describe('AddonsService places flags', () => {
* feature runs.
*/
describe('AddonsService places enrichment flag', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('ADDONS-SVC-083 an unset flag reads as ON', async () => {
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(await svc().getPlacesEnrich()).toEqual({ enabled: true });
expect(await svc.getPlacesEnrich()).toEqual({ enabled: true });
});
it('ADDONS-SVC-084 only the literal "false" switches it off', async () => {
dbMock._stmt.get.mockReturnValueOnce({ value: 'false' });
expect(await svc().getPlacesEnrich()).toEqual({ enabled: false });
setAppSetting('places_enrich_enabled', 'false');
expect(await svc.getPlacesEnrich()).toEqual({ enabled: false });
for (const value of ['true', 'garbage', '']) {
dbMock._stmt.get.mockReturnValueOnce({ value });
expect(await svc().getPlacesEnrich()).toEqual({ enabled: true });
setAppSetting('places_enrich_enabled', value);
expect(await svc.getPlacesEnrich()).toEqual({ enabled: true });
}
});
it('ADDONS-SVC-085 the setter persists the literal string and echoes the boolean back', async () => {
expect(await svc().updatePlacesEnrich(false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith('places_enrich_enabled', 'false');
expect(await svc().updatePlacesEnrich(true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith('places_enrich_enabled', 'true');
expect(await svc.updatePlacesEnrich(false)).toEqual({ enabled: false });
expect(rawAppSetting('places_enrich_enabled')).toEqual({ key: 'places_enrich_enabled', value: 'false' });
expect(await svc.updatePlacesEnrich(true)).toEqual({ enabled: true });
expect(rawAppSetting('places_enrich_enabled')).toEqual({ key: 'places_enrich_enabled', value: 'true' });
});
});
@@ -431,34 +494,33 @@ describe('AddonsService places enrichment flag', () => {
* unrecognised-value case the booleans get for free: anything that is not a
* known provider must read as Transitous rather than silently billing the
* install's Google key.
*
* NOT one of this task's 11 app_settings/addons/photo_provider(_fields) sites
* (transit-provider.ts and instance-api-keys.ts are other domains, out of this
* plan's six) — still on DatabaseService, exercised here over the same real
* connection every other case uses.
*/
describe('AddonsService transit provider', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('ADDONS-SVC-086 an unset provider reads as Transitous, with no key anywhere', async () => {
dbMock._stmt.get.mockReturnValue(undefined);
expect(await svc().getTransitProvider()).toEqual({ provider: 'transitous', googleKeySource: null });
expect(await svc.getTransitProvider()).toEqual({ provider: 'transitous', googleKeySource: null });
});
it('ADDONS-SVC-087 only a known provider name is honoured', async () => {
dbMock._stmt.get.mockReturnValueOnce({ value: 'google' }).mockReturnValue(undefined);
expect((await svc().getTransitProvider()).provider).toBe('google');
setAppSetting('transit_provider', 'google');
expect((await svc.getTransitProvider()).provider).toBe('google');
for (const value of ['someday-maps', '', 'GOOGLE']) {
dbMock._stmt.get.mockReset();
dbMock._stmt.get.mockReturnValueOnce({ value }).mockReturnValue(undefined);
expect((await svc().getTransitProvider()).provider).toBe('transitous');
setAppSetting('transit_provider', value);
expect((await svc.getTransitProvider()).provider).toBe('transitous');
}
});
it('ADDONS-SVC-088 the setter persists the name and echoes it back', async () => {
dbMock._stmt.get.mockReturnValue(undefined);
expect((await svc().updateTransitProvider('google')).provider).toBe('google');
expect(dbMock._stmt.run).toHaveBeenLastCalledWith('transit_provider', 'google');
expect((await svc().updateTransitProvider('transitous')).provider).toBe('transitous');
expect(dbMock._stmt.run).toHaveBeenLastCalledWith('transit_provider', 'transitous');
expect((await svc.updateTransitProvider('google')).provider).toBe('google');
expect(rawAppSetting('transit_provider')).toEqual({ key: 'transit_provider', value: 'google' });
expect((await svc.updateTransitProvider('transitous')).provider).toBe('transitous');
expect(rawAppSetting('transit_provider')).toEqual({ key: 'transit_provider', value: 'transitous' });
});
/**
@@ -467,23 +529,19 @@ describe('AddonsService transit provider', () => {
* means "works for this admin, Transitous for everybody else".
*/
it('ADDONS-SVC-089 reports where the Google key resolved from', async () => {
// provider row, then the instance maps_api_key row.
dbMock._stmt.get.mockReset();
dbMock._stmt.get.mockReturnValueOnce({ value: 'google' }).mockReturnValueOnce({ value: 'instance-key' });
expect((await svc().getTransitProvider(7)).googleKeySource).toBe('instance');
setAppSetting('transit_provider', 'google');
setAppSetting('maps_api_key', 'instance-key');
expect((await svc.getTransitProvider(7)).googleKeySource).toBe('instance');
// No instance row, but the caller's own users column has one.
dbMock._stmt.get.mockReset();
dbMock._stmt.get
.mockReturnValueOnce({ value: 'google' })
.mockReturnValueOnce(undefined)
.mockReturnValueOnce({ maps_api_key: 'personal-key' });
expect((await svc().getTransitProvider(7)).googleKeySource).toBe('user-row');
testDb.prepare("DELETE FROM app_settings WHERE key = 'maps_api_key'").run();
const { user } = createUser(testDb);
testDb.prepare('UPDATE users SET maps_api_key = ? WHERE id = ?').run('personal-key', user.id);
expect((await svc.getTransitProvider(user.id)).googleKeySource).toBe('user-row');
// Nothing anywhere.
dbMock._stmt.get.mockReset();
dbMock._stmt.get.mockReturnValue(undefined);
expect((await svc().getTransitProvider(7)).googleKeySource).toBeNull();
const { user: bareUser } = createUser(testDb);
expect((await svc.getTransitProvider(bareUser.id)).googleKeySource).toBeNull();
});
});
@@ -496,76 +554,49 @@ describe('AddonsService transit provider', () => {
* diverge the admin panel shows "off" while the log keeps collecting picks.
*/
describe('AddonsService place shadow flag', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('ADDONS-SVC-090 an unset flag reads as OFF, and so does every value but the literal "true"', async () => {
dbMock._stmt.get.mockReturnValueOnce(undefined);
expect(await svc().getPlaceShadow()).toEqual({ enabled: false });
expect(dbMock.prepare).toHaveBeenLastCalledWith('SELECT value FROM app_settings WHERE key = ?');
expect(dbMock._stmt.get).toHaveBeenLastCalledWith('place_shadow_enabled');
expect(await svc.getPlaceShadow()).toEqual({ enabled: false });
for (const value of ['false', 'TRUE', '1', '']) {
dbMock._stmt.get.mockReturnValueOnce({ value });
expect(await svc().getPlaceShadow()).toEqual({ enabled: false });
setAppSetting('place_shadow_enabled', value);
expect(await svc.getPlaceShadow()).toEqual({ enabled: false });
}
});
it('ADDONS-SVC-091 a stored "true" reads as ON', async () => {
dbMock._stmt.get.mockReturnValueOnce({ value: 'true' });
expect(await svc().getPlaceShadow()).toEqual({ enabled: true });
setAppSetting('place_shadow_enabled', 'true');
expect(await svc.getPlaceShadow()).toEqual({ enabled: true });
});
it('ADDONS-SVC-092 the setter round-trips through the getter under its own key', async () => {
// Keyed store instead of an echo assertion: the write has to produce the
// exact string the read compares against, so a setter persisting '1' fails
// here rather than silently reading back OFF in production.
const stored = new Map<string, string>();
dbMock._stmt.run.mockImplementation((key: string, value: string) => {
stored.set(key, value);
});
dbMock._stmt.get.mockImplementation((key: string) => {
const value = stored.get(key);
return value === undefined ? undefined : { value };
});
expect(await svc.updatePlaceShadow(true)).toEqual({ enabled: true });
expect(rawAppSetting('place_shadow_enabled')).toEqual({ key: 'place_shadow_enabled', value: 'true' });
expect(await svc.getPlaceShadow()).toEqual({ enabled: true });
// a sibling switch must not ride along
expect(await svc.getPlacesDetails()).toEqual({ enabled: false });
expect(await svc().updatePlaceShadow(true)).toEqual({ enabled: true });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith('place_shadow_enabled', 'true');
expect(await svc().getPlaceShadow()).toEqual({ enabled: true });
// a sibling switch must not ride along on the shared statement
expect(await svc().getPlacesDetails()).toEqual({ enabled: false });
expect(await svc().updatePlaceShadow(false)).toEqual({ enabled: false });
expect(dbMock._stmt.run).toHaveBeenLastCalledWith('place_shadow_enabled', 'false');
expect(await svc().getPlaceShadow()).toEqual({ enabled: false });
expect([...stored.keys()]).toEqual(['place_shadow_enabled']);
expect(await svc.updatePlaceShadow(false)).toEqual({ enabled: false });
expect(rawAppSetting('place_shadow_enabled')).toEqual({ key: 'place_shadow_enabled', value: 'false' });
expect(await svc.getPlaceShadow()).toEqual({ enabled: false });
// no sibling key was ever written
expect(rawAppSetting('places_details_enabled')).toBeUndefined();
});
it('ADDONS-SVC-093 answers the same as PlaceShadowService.enabled() for every stored value', async () => {
const shadow = new PlaceShadowService(new DatabaseService(dbConn));
const rows: Array<[{ value: string } | undefined, boolean]> = [
const shadow = new PlaceShadowService(new DatabaseService(testDb));
const cases: Array<[string | undefined, boolean]> = [
[undefined, false],
[{ value: 'true' }, true],
[{ value: 'false' }, false],
[{ value: 'garbage' }, false],
['true', true],
['false', false],
['garbage', false],
];
for (const [row, expected] of rows) {
// one read for the admin getter, one for the service that gates the log
dbMock._stmt.get.mockReturnValueOnce(row).mockReturnValueOnce(row);
// The shared statement hands both readers this row whatever they ask for,
// so the key each one names has to be asserted too: the getter binds it,
// the gate inlines it, and a divergence there would still look like
// agreement on the value alone.
expect(await svc().getPlaceShadow()).toEqual({ enabled: expected });
expect(dbMock._stmt.get).toHaveBeenLastCalledWith('place_shadow_enabled');
for (const [value, expected] of cases) {
if (value === undefined) testDb.prepare("DELETE FROM app_settings WHERE key = 'place_shadow_enabled'").run();
else setAppSetting('place_shadow_enabled', value);
expect(await svc.getPlaceShadow()).toEqual({ enabled: expected });
expect(await shadow.enabled()).toBe(expected);
expect(dbMock.prepare).toHaveBeenLastCalledWith(
"SELECT value FROM app_settings WHERE key = 'place_shadow_enabled'",
);
}
});
});
+2 -2
View File
@@ -60,7 +60,7 @@ import { resetTestDb } from '../../helpers/test-db';
import { createUser, createUserWithMfa, createAdmin, createInviteToken } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { createTestAddonsService } from '../../helpers/test-addons';
import { SettingsService } from '../../../src/nest/settings/settings.service';
import { AtlasService } from '../../../src/nest/atlas/atlas.service';
import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
@@ -104,7 +104,7 @@ beforeAll(async () => {
auth = new AuthService(dbs, permissions, new TripMembershipService(dbs), webauthn, userCleanup, new MailerService(dbs), new EphemeralTokenService(), new AllowedFileTypesService(dbs), await createTestUnitOfWork(dbs.connection));
svc = new AdminService(
dbs,
new AddonsService(dbs),
await createTestAddonsService(testDb, dbs),
new PasskeyService(dbs, auth, webauthn, await createTestUnitOfWork(dbs.connection)),
auth,
permissions,
@@ -43,7 +43,7 @@ vi.mock('../../../src/mcp/sessionManager', () => ({ revokeUserSessions: vi.fn(),
import { DatabaseService } from '../../../src/nest/database/database.service';
import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { createTestAddonsService } from '../../helpers/test-addons';
import { SettingsService } from '../../../src/nest/settings/settings.service';
import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service';
import { UserCleanupService } from '../../../src/nest/auth/user-cleanup.service';
@@ -82,7 +82,7 @@ beforeAll(async () => {
auth = new AuthService(dbs, permissions, new TripMembershipService(dbs), webauthn, userCleanup, new MailerService(dbs), new EphemeralTokenService(), new AllowedFileTypesService(dbs), await createTestUnitOfWork(dbs.connection));
svc = new AdminService(
dbs,
new AddonsService(dbs),
await createTestAddonsService(testDb, dbs),
new PasskeyService(dbs, auth, webauthn, await createTestUnitOfWork(dbs.connection)),
auth,
permissions,
@@ -45,7 +45,8 @@ import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb, setAddonEnabled } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { DatabaseService } from '../../../src/nest/database/database.service';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import { createTestAddonsService } from '../../helpers/test-addons';
import { DawarichSyncService } from '../../../src/nest/integrations/dawarich-sync.service';
import { createTestUnitOfWork } from '../../helpers/test-uow';
import { DawarichError } from '../../../src/nest/integrations/dawarich.client';
@@ -112,7 +113,7 @@ const dawarich = {
// Direct construction over the shared test connection — no TestingModule
// (repo convention for DI-native service unit tests).
const dbs = new DatabaseService(testDb);
const addons = new AddonsService(dbs);
let addons: AddonsService;
let svc: DawarichSyncService;
// ── Fixtures ─────────────────────────────────────────────────────────────────
@@ -226,6 +227,7 @@ function withVisits(...visits: DawarichVisitRaw[]): void {
beforeAll(async () => {
createTables(testDb);
runMigrations(testDb);
addons = await createTestAddonsService(testDb, dbs);
svc = new DawarichSyncService(dbs, addons, client, dawarich, await createTestUnitOfWork(dbs.connection));
});
@@ -28,6 +28,7 @@ import { DiscoveryController } from '../../../src/nest/platform/discovery.contro
import { PlatformModule } from '../../../src/nest/platform/platform.module';
import { ALL_SCOPES } from '../../../src/mcp/scopes';
import type { AddonsService } from '../../../src/nest/addons/addons.service';
import type { MikroORM } from '@mikro-orm/core';
function makeRes() {
const res = {
@@ -47,6 +48,19 @@ function addons(enabled: boolean) {
return { isAddonEnabled: vi.fn(() => enabled) } as unknown as AddonsService;
}
/**
* createMcpMetadataMiddleware wraps the addon check in withRequestContext
* (Plan 3a Task 4: this pathless pre-init mount runs before
* @mikro-orm/nestjs's per-request EM fork, so once isAddonEnabled became
* repository-backed it needed its own context). The mocked AddonsService
* above never touches the ORM, so this fake only needs to satisfy
* RequestContext.create's em.fork()/em.name contract.
*/
function fakeOrm(): MikroORM {
const em = { name: 'default', fork: () => ({ name: 'default' }) };
return { em } as unknown as MikroORM;
}
beforeEach(() => {
vi.clearAllMocks();
h.getMcpSafeUrl.mockReturnValue('https://trek.example.test');
@@ -105,7 +119,7 @@ async function flushMicrotasks(): Promise<void> {
describe('createMcpMetadataMiddleware', () => {
it('DISC-010: 404s a /.well-known path with an empty body when MCP is disabled', async () => {
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), addons(false));
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), addons(false), fakeOrm());
const res = makeRes();
const next = vi.fn();
mw({ path: '/.well-known/oauth-authorization-server' } as never, res as never, next);
@@ -117,7 +131,7 @@ describe('createMcpMetadataMiddleware', () => {
});
it('DISC-011: delegates a /.well-known path to the SDK router when MCP is enabled', async () => {
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), addons(true));
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), addons(true), fakeOrm());
const next = vi.fn();
mw({ path: '/.well-known/oauth-authorization-server' } as never, makeRes() as never, next);
await flushMicrotasks();
@@ -126,16 +140,16 @@ describe('createMcpMetadataMiddleware', () => {
it('DISC-012: delegates non-well-known paths without consulting the addon gate', () => {
const gate = addons(false);
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), gate);
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), gate, fakeOrm());
mw({ path: '/api/trips' } as never, makeRes() as never, vi.fn());
expect(gate.isAddonEnabled).not.toHaveBeenCalled();
expect(h.metaRouter).toHaveBeenCalled();
});
it('DISC-013: the factory provider wires the token to the factory with its two deps', () => {
it('DISC-013: the factory provider wires the token to the factory with its three deps (MikroORM added — Plan 3a Task 4)', () => {
expect(mcpMetadataMiddlewareProvider.provide).toBe(MCP_METADATA_MIDDLEWARE);
expect(mcpMetadataMiddlewareProvider.useFactory).toBe(createMcpMetadataMiddleware);
expect(mcpMetadataMiddlewareProvider.inject.length).toBe(2);
expect(mcpMetadataMiddlewareProvider.inject.length).toBe(3);
});
});
@@ -43,7 +43,7 @@ import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb, setAddonEnabled } from '../../helpers/test-db';
import { createUser, createTrip } from '../../helpers/factories';
import { ADDON_IDS } from '../../../src/addons';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { createTestAddonsService } from '../../helpers/test-addons';
import { UnifiedMemoriesService } from '../../../src/nest/memories/unified-memories.service';
import { MemoriesAccessService } from '../../../src/nest/memories/memories-access.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
@@ -81,7 +81,7 @@ beforeAll(async () => {
{} as SynologyService,
new MemoriesAccessService(dbs),
notificationsStub(),
new AddonsService(dbs),
await createTestAddonsService(testDb, dbs),
await createTestUnitOfWork(testDb),
);
});