Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(demo): a fixed addon set on every boot and after every hourly reset

Maurice03493d4f795d
diff --git a/server/src/db/repositories/DemoRepository.ts b/server/src/db/repositories/DemoRepository.ts
index de24a6046..ac6a4565b 100644
--- a/server/src/db/repositories/DemoRepository.ts
+++ b/server/src/db/repositories/DemoRepository.ts
@@ -1,5 +1,9 @@
import { currentTimestampKysely } from '../dialect/kysely-functions';
+import { Addons } from '../entities/Addons.entity';
import { AppSettings } from '../entities/AppSettings.entity';
+import { DocumentProviders } from '../entities/DocumentProviders.entity';
+import { PhotoProviders } from '../entities/PhotoProviders.entity';
+import { Settings } from '../entities/Settings.entity';
import { Trips } from '../entities/Trips.entity';
import { Users } from '../entities/Users.entity';
import type { DB } from '../kysely/db';
@@ -36,6 +40,20 @@ export interface DemoInstanceKeyRow {
value: string | null;
}
+/** One shelf of the demo addon policy (`demo/demo-addon-policy.ts`): the rows it switches on and off. */
+export interface DemoShelfStates {
+ readonly on: readonly string[];
+ readonly off: readonly string[];
+}
+
+/** The states `applyAddonStates` writes: three shelves and the switches under them in `app_settings`. */
+export interface DemoAddonStates {
+ readonly addons: DemoShelfStates;
+ readonly photoProviders: DemoShelfStates;
+ readonly documentProviders: DemoShelfStates;
+ readonly appSettings: Readonly<Record<string, string>>;
+}
+
/**
* DMS9's 13-column `places` insert tuple — kept as a tuple, not an object,
* so `demo-seed.ts`'s three ~30-row example-trip data arrays (Tokyo/Kyoto,
@@ -400,4 +418,36 @@ export class DemoRepository {
await repo.upsert({ key: row.key, value: row.value }, { onConflictFields: ['key'], onConflictAction: 'merge' });
}
}
+
+ // ---------------------------------------------------------------------
+ // The fixed demo set (demo-addon-policy.ts), applied by the seed and the reset
+ // ---------------------------------------------------------------------
+
+ /**
+ * Writes the demo's addon states in one transaction, so a reset that fails
+ * halfway does not leave half the shelf switched. A named row the database
+ * does not hold is an update that matches nothing, never an insert: the
+ * seeders own which rows exist.
+ */
+ async applyAddonStates(states: DemoAddonStates): Promise<void> {
+ this.validateRequestContext();
+ await this.em.transactional(async () => {
+ const addons = this.em.getRepository(Addons);
+ for (const id of states.addons.on) await addons.setEnabled(id, true);
+ for (const id of states.addons.off) await addons.setEnabled(id, false);
+ const photos = this.em.getRepository(PhotoProviders);
+ for (const id of states.photoProviders.on) await photos.setEnabled(id, 1);
+ for (const id of states.photoProviders.off) await photos.setEnabled(id, 0);
+ const documents = this.em.getRepository(DocumentProviders);
+ for (const id of states.documentProviders.on) await documents.setEnabled(id, 1);
+ for (const id of states.documentProviders.off) await documents.setEnabled(id, 0);
+ const settings = this.em.getRepository(AppSettings);
+ for (const [key, value] of Object.entries(states.appSettings)) await settings.setValue(key, value);
+ });
+ }
+
+ /** A user's own settings row, written as given (the demo account's fixed language). Composes `SettingsRepository#upsertForUser`. */
+ async setUserSetting(userId: number, key: string, value: string): Promise<void> {
+ await this.em.getRepository(Settings).upsertForUser(userId, key, value);
+ }
}
diff --git a/server/src/demo/demo-addon-policy.ts b/server/src/demo/demo-addon-policy.ts
new file mode 100644
index 000000000..549f78aaf
--- /dev/null
+++ b/server/src/demo/demo-addon-policy.ts
@@ -0,0 +1,77 @@
+import type { DemoAddonStates, DemoRepository } from '../db/repositories/DemoRepository';
+
+/**
+ * What a demo instance offers, whatever its admin switched during the hour.
+ *
+ * The demo shows everything TREK can do on its own: every trip, global and
+ * integration addon is on. What stays off is what needs a server of the
+ * visitor's own, which a public demo has no address for and no business
+ * reaching: the document sync providers, the wanderer connection under Tours,
+ * the photo providers under Journey, AirTrail and Dawarich.
+ *
+ * Each list names its rows outright instead of "everything but", so a release
+ * that adds an addon has to decide where it goes: the policy test fails on a
+ * seeded row that is in neither list. The demo seed applies this on every boot
+ * and after every reopen, and the hourly reset applies it once more after the
+ * swap, so the baseline cannot bring back an admin's toggle.
+ */
+export const DEMO_ADDON_POLICY = {
+ /** Rows of the `addons` table. */
+ addons: {
+ on: [
+ // Trip addons
+ 'packing',
+ 'budget',
+ 'documents',
+ 'collab',
+ 'roadtrip',
+ 'tours',
+ // Global addons
+ 'vacay',
+ 'atlas',
+ 'journey',
+ 'collections',
+ // Integrations TREK runs by itself
+ 'mcp',
+ 'naver_list_import',
+ 'llm_parsing',
+ 'ai_assistant',
+ ],
+ off: ['airtrail', 'dawarich'],
+ },
+ /** Rows of `photo_providers`, Journey's shelf. */
+ photoProviders: {
+ on: [],
+ off: ['immich', 'synologyphotos'],
+ },
+ /** Rows of `document_providers`, the Documents addon's shelf. */
+ documentProviders: {
+ on: [],
+ off: ['paperless', 'papra', 'nextcloud', 'opencloud', 'synologydrive'],
+ },
+ /**
+ * The switches that sit under an addon in the admin panel, stored in
+ * `app_settings`. wanderer is the one under Tours that reaches a server of
+ * the visitor's own; the rest are on.
+ */
+ appSettings: {
+ tours_wanderer_enabled: 'false',
+ tours_hiking_map_enabled: 'true',
+ tours_cycle_map_enabled: 'true',
+ ski_routing_enabled: 'true',
+ bag_tracking_enabled: 'true',
+ collab_chat_enabled: 'true',
+ collab_notes_enabled: 'true',
+ collab_links_enabled: 'true',
+ collab_polls_enabled: 'true',
+ collab_whatsnext_enabled: 'true',
+ },
+} as const satisfies DemoAddonStates;
+
+/** Puts the instance's addon states to the demo set, in one transaction. A row the database does not hold is skipped. */
+export async function applyDemoAddonPolicy(
+ demo: DemoRepository,
+ policy: DemoAddonStates = DEMO_ADDON_POLICY,
+): Promise<void> {
+ await demo.applyAddonStates(policy);
+}
diff --git a/server/src/demo/demo-reset.ts b/server/src/demo/demo-reset.ts
index 1618aaad6..f28dd98dd 100644
--- a/server/src/demo/demo-reset.ts
+++ b/server/src/demo/demo-reset.ts
@@ -9,6 +9,7 @@ import {
import type { CarriedUserSessionRow } from '../db/repositories/UserSessions.repository';
import { dbNow } from '../db/types';
import { DatabaseConnectionLostError, type DatabaseBackupStrategy } from '../nest/database/database-backup.interface';
+import { applyDemoAddonPolicy } from './demo-addon-policy';
import { RequestContext, type EntityManager } from '@mikro-orm/core';
import fs from 'fs';
@@ -155,6 +156,15 @@ async function resetDemoUser(database: DatabaseBackupStrategy): Promise<void> {
console.error('[Demo Reset] Failed to restore the active sessions:', e instanceof Error ? e.message : e);
}
}
+
+ // The reopen's schema bootstrap ran the demo seed, which applies the demo
+ // addon set already. Applied here once more so the reset itself states
+ // what the demo offers after the hour, whatever the baseline holds.
+ try {
+ await applyDemoAddonPolicy(demoFresh);
+ } catch (e: unknown) {
+ console.error('[Demo Reset] Failed to apply the demo addon set:', e instanceof Error ? e.message : e);
+ }
});
console.log('[Demo Reset] Database restored from baseline');
diff --git a/server/src/demo/demo-seed.ts b/server/src/demo/demo-seed.ts
index 9908ea621..9ef9f185e 100644
--- a/server/src/demo/demo-seed.ts
+++ b/server/src/demo/demo-seed.ts
@@ -1,6 +1,7 @@
import { readEnv } from '../app-config';
import { DemoRepository, type NewDemoPlaceRow } from '../db/repositories/DemoRepository';
-import { DEMO_PASS } from '../nest/common/demo';
+import { DEMO_ACCOUNT_SETTINGS, DEMO_PASS } from '../nest/common/demo';
+import { applyDemoAddonPolicy } from './demo-addon-policy';
// Static like in demo-reset.job.ts: the module top is inert, everything that
// touches the database happens inside the functions.
import { markExampleTripsSeeded, requireEntityManager } from './demo-reset';
@@ -53,6 +54,13 @@ async function seedDemoData(): Promise<{ adminId: number; demoId: number }> {
// Disable registration in demo mode
await demo.setAllowRegistrationFalse();
+ // The fixed demo set: the addons every visitor can try, and the demo
+ // account's language. This runs on every boot and again after every reopen
+ // (the hourly reset included), so neither an admin's toggle nor an old
+ // baseline outlasts the hour.
+ await applyDemoAddonPolicy(demo);
+ for (const [key, value] of Object.entries(DEMO_ACCOUNT_SETTINGS)) await demo.setUserSetting(demoId, key, value);
+
// Check if admin already has example trips
const adminTripCount = await demo.countTripsByUser(adminId);
if (adminTripCount > 0) {
diff --git a/server/tests/unit/demo/demo-addon-policy.test.ts b/server/tests/unit/demo/demo-addon-policy.test.ts
new file mode 100644
index 000000000..00363e41c
--- /dev/null
+++ b/server/tests/unit/demo/demo-addon-policy.test.ts
@@ -0,0 +1,167 @@
+/**
+ * The demo addon policy: which addons, providers and addon switches a demo
+ * instance runs with, and that the seed and the hourly reset both put them back.
+ *
+ * The lists are explicit on purpose, so a release that adds an addon has to say
+ * whether a demo shows it: DEMOPOL-001 fails on a seeded row that is in neither
+ * list, and on a listed id the database does not hold.
+ */
+import { Addons } from '../../../src/db/entities/Addons.entity';
+import { DocumentProviders } from '../../../src/db/entities/DocumentProviders.entity';
+import { PhotoProviders } from '../../../src/db/entities/PhotoProviders.entity';
+import { Users } from '../../../src/db/entities/Users.entity';
+import { DEMO_ADDON_POLICY } from '../../../src/demo/demo-addon-policy';
+import { resetDemoUser } from '../../../src/demo/demo-reset';
+import { seedDemoData } from '../../../src/demo/demo-seed';
+import type { DatabaseBackupStrategy } from '../../../src/nest/database/database-backup.interface';
+import { withRequestContext } from '../../../src/nest/database/request-context';
+import { createSnapshotTestDb } from '../../helpers/db-mock';
+import { findRow, findRows, updateRows } from '../../helpers/factories/rows';
+import { readAppSetting, readUserSetting, setAppSetting, setUserSetting } from '../../helpers/factories/settings';
+import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
+
+import type Database from 'better-sqlite3';
+import fs from 'node:fs';
+import path from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const BASELINE = path.resolve(__dirname, '..', '..', '..', 'data', 'travel-baseline.db');
+
+let db: Database.Database;
+let t: TestOrm;
+
+beforeEach(async () => {
+ vi.spyOn(console, 'log').mockImplementation(() => undefined);
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ db = createSnapshotTestDb();
+ t = await createTestOrm(db);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await t.close();
+ db.close();
+});
+
+const seed = () => withRequestContext(t.orm, () => seedDemoData());
+
+async function enabledIds(entity: typeof Addons | typeof PhotoProviders | typeof DocumentProviders) {
+ const rows = (await findRows(t, entity as typeof Addons)) as { id: string; enabled: unknown }[];
+ return {
+ on: rows
+ .filter((r) => !!r.enabled)
+ .map((r) => r.id)
+ .sort(),
+ off: rows
+ .filter((r) => !r.enabled)
+ .map((r) => r.id)
+ .sort(),
+ };
+}
+
+const sorted = (ids: readonly string[]) => [...ids].sort();
+
+/** What an admin of a demo instance might have switched during the hour. */
+async function scramble(): Promise<void> {
+ await updateRows(t, Addons, { id: 'airtrail' }, { enabled: true });
+ await updateRows(t, Addons, { id: 'packing' }, { enabled: false });
+ await updateRows(t, Addons, { id: 'journey' }, { enabled: false });
+ await updateRows(t, PhotoProviders, { id: 'immich' }, { enabled: 1 });
+ await updateRows(t, DocumentProviders, { id: 'paperless' }, { enabled: 1 });
+ await setAppSetting(t, 'tours_wanderer_enabled', 'true');
+ await setAppSetting(t, 'collab_chat_enabled', 'false');
+}
+
+async function expectPolicyApplied(): Promise<void> {
+ expect(await enabledIds(Addons)).toEqual({
+ on: sorted(DEMO_ADDON_POLICY.addons.on),
+ off: sorted(DEMO_ADDON_POLICY.addons.off),
+ });
+ expect(await enabledIds(PhotoProviders)).toEqual({ on: [], off: sorted(DEMO_ADDON_POLICY.photoProviders.off) });
+ expect(await enabledIds(DocumentProviders)).toEqual({
+ on: [],
+ off: sorted(DEMO_ADDON_POLICY.documentProviders.off),
+ });
+ for (const [key, value] of Object.entries(DEMO_ADDON_POLICY.appSettings)) {
+ expect([key, await readAppSetting(t, key)]).toEqual([key, value]);
+ }
+}
+
+describe('demo addon policy', () => {
+ it('DEMOPOL-001: names every seeded addon and provider exactly once, and nothing the database lacks', async () => {
+ const shelves = [
+ [Addons, DEMO_ADDON_POLICY.addons],
+ [PhotoProviders, DEMO_ADDON_POLICY.photoProviders],
+ [DocumentProviders, DEMO_ADDON_POLICY.documentProviders],
+ ] as const;
+ for (const [entity, shelf] of shelves) {
+ const seeded = (await findRows(t, entity as typeof Addons)).map((r) => r.id).sort();
+ const listed = [...shelf.on, ...shelf.off];
+ expect(new Set(listed).size).toBe(listed.length);
+ expect(sorted(listed)).toEqual(seeded);
+ }
+ });
+
+ it('DEMOPOL-002: keeps off exactly what reaches a server of the visitor’s own', () => {
+ expect(sorted(DEMO_ADDON_POLICY.addons.off)).toEqual(['airtrail', 'dawarich']);
+ expect(sorted(DEMO_ADDON_POLICY.photoProviders.off)).toEqual(['immich', 'synologyphotos']);
+ expect(sorted(DEMO_ADDON_POLICY.documentProviders.off)).toEqual(
+ sorted(['paperless', 'papra', 'nextcloud', 'opencloud', 'synologydrive']),
+ );
+ expect(DEMO_ADDON_POLICY.appSettings.tours_wanderer_enabled).toBe('false');
+ const otherSwitches = Object.entries(DEMO_ADDON_POLICY.appSettings).filter(
+ ([key]) => key !== 'tours_wanderer_enabled',
+ );
+ expect(otherSwitches.every(([, value]) => value === 'true')).toBe(true);
+ });
+
+ it('DEMOPOL-003: the first demo boot puts the whole shelf to the demo set', async () => {
+ await scramble();
+ await seed();
+ await expectPolicyApplied();
+ });
+
+ it('DEMOPOL-004: a later boot, with the example trips already there, puts it back again', async () => {
+ await seed();
+ await scramble();
+ await seed();
+ await expectPolicyApplied();
+ });
+
+ it('DEMOPOL-005: the demo account runs in English, whatever a visitor picked before', async () => {
+ const { demoId } = await seed();
+ await setUserSetting(t, demoId, 'language', 'de');
+ await seed();
+ expect(await readUserSetting(t, demoId, 'language')).toBe('en');
+ });
+
+ it('DEMOPOL-006: the admin account keeps the language it chose', async () => {
+ const { adminId } = await seed();
+ await setUserSetting(t, adminId, 'language', 'de');
+ await seed();
+ expect(await readUserSetting(t, adminId, 'language')).toBe('de');
+ });
+});
+
+describe('demo addon policy across the hourly reset', () => {
+ it('DEMOPOL-007: the reset puts the demo set back after the baseline swap, whatever the baseline held', async () => {
+ await seed();
+ vi.spyOn(fs, 'existsSync').mockImplementation(((p: fs.PathLike) => String(p) === BASELINE) as typeof fs.existsSync);
+ // The stand-in swap brings back a baseline whose shelf an admin had changed.
+ const database = {
+ canSnapshot: () => true,
+ checkpoint: vi.fn(async () => undefined),
+ replace: vi.fn(async () => {
+ await scramble();
+ return { reopenError: undefined };
+ }),
+ } as unknown as DatabaseBackupStrategy;
+
+ await withRequestContext(t.orm, () => resetDemoUser(database));
+ t.clear();
+
+ expect(database.replace).toHaveBeenCalled();
+ await expectPolicyApplied();
+ expect(await findRow(t, Users, { email: '[email protected]' })).not.toBeNull();
+ });
+});