From dff590785fec2f9951ac96996345f564e446b375 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Tue, 10 Nov 2026 15:36:59 +1100 Subject: [PATCH 1/2] fix(mocks): mock every endpoint the app calls and keep changes for the session Ten endpoints had no mock, and several mocks used paths that ts-client does not call (metadata, OAuth apps, system functions and exec, clusters). Metadata, start and stop, system modules and system triggers were not saved, so a reload lost them. All handlers now use one store that saves to session storage on every change. Requests that have no mock write a warning to the console. Co-Authored-By: Claude Opus 5.5 --- e2e/README.md | 2 + e2e/src/admin.spec.ts | 16 +- src/app/mocks/backend/admin.mock.ts | 753 ++++--------------- src/app/mocks/backend/auth-sources.mock.ts | 370 +-------- src/app/mocks/backend/domains.mock.ts | 31 +- src/app/mocks/backend/drivers.mock.ts | 5 +- src/app/mocks/backend/general.mock.ts | 123 ++- src/app/mocks/backend/groups.mock.ts | 89 ++- src/app/mocks/backend/history.mock.ts | 70 -- src/app/mocks/backend/index.ts | 5 +- src/app/mocks/backend/metadata.mock.ts | 251 +++---- src/app/mocks/backend/modules.mock.ts | 116 +-- src/app/mocks/backend/repositories.mock.ts | 217 +++--- src/app/mocks/backend/settings.mock.ts | 118 +-- src/app/mocks/backend/staff-api.mock.ts | 247 +++--- src/app/mocks/backend/system-control.mock.ts | 170 +++++ src/app/mocks/backend/systems.mock.ts | 297 +++++--- src/app/mocks/backend/triggers.mock.ts | 128 +++- src/app/mocks/backend/users.mock.ts | 38 +- src/app/mocks/backend/zones.mock.ts | 42 +- src/app/mocks/common.mock.ts | 248 +++--- src/app/mocks/index.ts | 9 + 22 files changed, 1463 insertions(+), 1882 deletions(-) delete mode 100644 src/app/mocks/backend/history.mock.ts create mode 100644 src/app/mocks/backend/system-control.mock.ts diff --git a/e2e/README.md b/e2e/README.md index d1831f2af..3f6cea55b 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -11,6 +11,8 @@ The mock tests run the app against the mock backend in `src/app/mocks/`. Each test gets a new browser context, so it starts with fresh mock data. The mock backend keeps creates, edits and deletes in session storage, so a change stays after `page.reload()` in the same test. +A request that has no mock handler fails with a 404 and writes +`[mock] No handler for ` to the browser console. ## Run the tests diff --git a/e2e/src/admin.spec.ts b/e2e/src/admin.spec.ts index 2b399bb31..dcbaeec01 100644 --- a/e2e/src/admin.spec.ts +++ b/e2e/src/admin.spec.ts @@ -1,5 +1,10 @@ import { Page } from '@playwright/test'; -import { expect, seedSession, test } from './fixtures/test-fixtures'; +import { + expect, + seedMockData, + seedSession, + test, +} from './fixtures/test-fixtures'; import { AdminPage } from './pages'; /** @@ -71,7 +76,10 @@ const TENANT = { /** Tenant as saved by the mock staff API */ async function storedTenant(page: Page): Promise { return page.evaluate( - () => JSON.parse(sessionStorage.getItem('PLACEOS.mocks.tenants'))[0], + () => + JSON.parse( + sessionStorage.getItem('PLACEOS.mocks.api_staff_v1_tenants'), + )[0], ); } @@ -197,7 +205,7 @@ test.describe('Admin', () => { test.describe('Maximum booking length', () => { test.beforeEach(async ({ page }) => { - await seedSession(page, 'tenants', [TENANT]); + await seedSession(page, 'api_staff_v1_tenants', [TENANT]); await admin.gotoSection('staff-api'); }); @@ -289,7 +297,7 @@ test.describe('Admin', () => { test.describe('US-ADM-011: Manage API Keys', () => { test.beforeEach(async ({ page }) => { - await seedSession(page, 'api_keys', API_KEYS); + await seedMockData(page, 'api_keys', API_KEYS); await admin.gotoSection('api-keys'); await admin.selectApiKeyDomain(); }); diff --git a/src/app/mocks/backend/admin.mock.ts b/src/app/mocks/backend/admin.mock.ts index 4809880f6..06d3a9076 100644 --- a/src/app/mocks/backend/admin.mock.ts +++ b/src/app/mocks/backend/admin.mock.ts @@ -1,657 +1,198 @@ -import { - MockHttpRequestHandler, - registerMockEndpoint, -} from '@placeos/ts-client'; +import { registerMockEndpoint } from '@placeos/ts-client'; import { HashMap } from '../../common/types'; import { API, + createMockStore, + generateBasicHandlers, generateID, - loadFromSession, - saveToSession, + nameFilter, + notFound, } from '../common.mock'; +import { AUTHORITY_ID } from './domains.mock'; -/** In-memory storage with session persistence */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const API_KEYS: Record[] = loadFromSession('api_keys', []); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const BROKERS: Record[] = loadFromSession('brokers', []); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const EDGES: Record[] = loadFromSession('edges', []); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const APPLICATIONS: Record[] = loadFromSession('applications', []); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const UPLOADS: Record[] = loadFromSession('uploads', []); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const STORAGE_PROVIDERS: Record[] = loadFromSession( - 'storage_providers', - [], -); -const AVAILABLE_SCOPES = [ - 'public', - 'read', - 'write', - 'systems', - 'zones', - 'users', - 'admin', -]; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const createFilter = (items: Record[]) => (q: HashMap) => { - if (!q || Object.keys(q).length <= 0) { - return items; - } - return items.filter((item) => { - let match = true; - if (q.authority_id) { - match = match && item.authority_id === q.authority_id; - } - if (q.q) { - match = - match && - (item.name || '') - .toLowerCase() - .indexOf(((q.q as string) || '').toLowerCase()) >= 0; - } - return match; - }); -}; +/** Matches `q` against the name and `authority_id` against the item */ +const AUTHORITY_FILTER = (item: Record, q: HashMap) => + nameFilter(item, q) && + (!q.authority_id || item.authority_id === q.authority_id); // ============ API KEYS ============ -/** GET available API key scopes */ registerMockEndpoint({ path: `${API}/scopes`, - metadata: AVAILABLE_SCOPES, - method: 'GET', -} as MockHttpRequestHandler); - -/** GET API keys list */ -registerMockEndpoint({ - path: `${API}/api_keys`, - metadata: [], - method: 'GET', - callback: (event) => createFilter(API_KEYS)(event.query_params), -} as MockHttpRequestHandler); - -/** GET API key by ID */ -registerMockEndpoint({ - path: `${API}/api_keys/:id`, - metadata: [], method: 'GET', - callback: (event) => { - const key = API_KEYS.find((k) => k.id === event.route_params.id); - if (key) return key; - throw { status: 404, message: 'API key not found' }; - }, -} as MockHttpRequestHandler); - -/** POST create API key */ -registerMockEndpoint({ - path: `${API}/api_keys`, - metadata: [], - method: 'POST', - callback: (event) => { - const key = { - id: `api_key-${generateID()}`, - ...event.body, - x_api_key: `sk_${generateID(32)}`, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - API_KEYS.push(key); - saveToSession('api_keys', API_KEYS); - return key; - }, -} as MockHttpRequestHandler); - -/** PATCH update API key */ -registerMockEndpoint({ - path: `${API}/api_keys/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = API_KEYS.findIndex( - (k) => k.id === event.route_params.id, - ); - if (index >= 0) { - const updated_key = { - ...API_KEYS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - API_KEYS[index] = updated_key; - saveToSession('api_keys', API_KEYS); - return updated_key; - } - throw { status: 404, message: 'API key not found' }; - }, -} as MockHttpRequestHandler); - -/** DELETE API key */ -registerMockEndpoint({ - path: `${API}/api_keys/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = API_KEYS.findIndex((k) => k.id === event.route_params.id); - if (index >= 0) { - API_KEYS.splice(index, 1); - saveToSession('api_keys', API_KEYS); - return {}; - } - throw { status: 404, message: 'API key not found' }; - }, -} as MockHttpRequestHandler); + callback: () => [ + 'public', + 'read', + 'write', + 'systems', + 'zones', + 'users', + 'admin', + ], +}); + +generateBasicHandlers(`${API}/api_keys`, [], { + filter: AUTHORITY_FILTER, + id_prefix: 'api_key-', + prepare: (item) => ({ x_api_key: `sk_${generateID(32)}`, ...item }), +}); // ============ BROKERS ============ -/** GET brokers list */ -registerMockEndpoint({ - path: `${API}/brokers`, - metadata: [], - method: 'GET', - callback: (event) => createFilter(BROKERS)(event.query_params), -} as MockHttpRequestHandler); - -/** GET broker by ID */ -registerMockEndpoint({ - path: `${API}/brokers/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const broker = BROKERS.find((b) => b.id === event.route_params.id); - if (broker) return broker; - throw { status: 404, message: 'Broker not found' }; - }, -} as MockHttpRequestHandler); - -/** POST create broker */ -registerMockEndpoint({ - path: `${API}/brokers`, - metadata: [], - method: 'POST', - callback: (event) => { - const broker = { - id: `broker-${generateID()}`, - ...event.body, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - BROKERS.push(broker); - saveToSession('brokers', BROKERS); - return broker; - }, -} as MockHttpRequestHandler); - -/** PUT/PATCH update broker */ -registerMockEndpoint({ - path: `${API}/brokers/:id`, - metadata: [], - method: 'PUT', - callback: (event) => { - const index = BROKERS.findIndex((b) => b.id === event.route_params.id); - if (index >= 0) { - BROKERS[index] = { - ...BROKERS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('brokers', BROKERS); - return BROKERS[index]; - } - throw { status: 404, message: 'Broker not found' }; - }, -} as MockHttpRequestHandler); - -registerMockEndpoint({ - path: `${API}/brokers/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = BROKERS.findIndex((b) => b.id === event.route_params.id); - if (index >= 0) { - BROKERS[index] = { - ...BROKERS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('brokers', BROKERS); - return BROKERS[index]; - } - throw { status: 404, message: 'Broker not found' }; - }, -} as MockHttpRequestHandler); - -/** DELETE broker */ -registerMockEndpoint({ - path: `${API}/brokers/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = BROKERS.findIndex((b) => b.id === event.route_params.id); - if (index >= 0) { - BROKERS.splice(index, 1); - saveToSession('brokers', BROKERS); - return {}; - } - throw { status: 404, message: 'Broker not found' }; - }, -} as MockHttpRequestHandler); +generateBasicHandlers(`${API}/brokers`, [], { + filter: AUTHORITY_FILTER, + id_prefix: 'broker-', +}); // ============ EDGES ============ -/** GET edges list */ -registerMockEndpoint({ - path: `${API}/edges`, - metadata: [], - method: 'GET', - callback: (event) => createFilter(EDGES)(event.query_params), -} as MockHttpRequestHandler); - -/** GET edge by ID */ -registerMockEndpoint({ - path: `${API}/edges/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const edge = EDGES.find((e) => e.id === event.route_params.id); - if (edge) return edge; - throw { status: 404, message: 'Edge not found' }; - }, -} as MockHttpRequestHandler); - -/** POST create edge */ -registerMockEndpoint({ - path: `${API}/edges`, - metadata: [], - method: 'POST', - callback: (event) => { - const edge = { - id: `edge-${generateID()}`, - ...event.body, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - EDGES.push(edge); - saveToSession('edges', EDGES); - return edge; - }, -} as MockHttpRequestHandler); - -/** PUT/PATCH update edge */ -registerMockEndpoint({ - path: `${API}/edges/:id`, - metadata: [], - method: 'PUT', - callback: (event) => { - const index = EDGES.findIndex((e) => e.id === event.route_params.id); - if (index >= 0) { - EDGES[index] = { - ...EDGES[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('edges', EDGES); - return EDGES[index]; - } - throw { status: 404, message: 'Edge not found' }; +/** Modules in `../data/modules` run on this edge */ +const EDGE_DATA = [ + { + id: 'edge-KiBexw2DWK', + name: 'Master Node', + description: 'Edge in the server room', + created_at: 1551149982, + updated_at: 1551149982, }, -} as MockHttpRequestHandler); - -registerMockEndpoint({ - path: `${API}/edges/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = EDGES.findIndex((e) => e.id === event.route_params.id); - if (index >= 0) { - EDGES[index] = { - ...EDGES[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('edges', EDGES); - return EDGES[index]; - } - throw { status: 404, message: 'Edge not found' }; - }, -} as MockHttpRequestHandler); +]; -/** DELETE edge */ -registerMockEndpoint({ - path: `${API}/edges/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = EDGES.findIndex((e) => e.id === event.route_params.id); - if (index >= 0) { - EDGES.splice(index, 1); - saveToSession('edges', EDGES); - return {}; - } - throw { status: 404, message: 'Edge not found' }; - }, -} as MockHttpRequestHandler); +generateBasicHandlers(`${API}/edges`, EDGE_DATA, { + filter: nameFilter, + id_prefix: 'edge-', +}); -/** Edge token */ registerMockEndpoint({ path: `${API}/edges/:id/token`, - metadata: [], method: 'GET', - callback: (_event) => { - return { token: `edge_token_${generateID(32)}` }; - }, -} as MockHttpRequestHandler); + callback: () => ({ token: `edge_token_${generateID(32)}` }), +}); // ============ APPLICATIONS (OAuth/OIDC) ============ -/** GET applications list */ -registerMockEndpoint({ - path: `${API}/doorkeeper/applications`, - metadata: [], - method: 'GET', - callback: (event) => createFilter(APPLICATIONS)(event.query_params), -} as MockHttpRequestHandler); - -/** GET application by ID */ -registerMockEndpoint({ - path: `${API}/doorkeeper/applications/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const app = APPLICATIONS.find((a) => a.id === event.route_params.id); - if (app) return app; - throw { status: 404, message: 'Application not found' }; - }, -} as MockHttpRequestHandler); +generateBasicHandlers(`${API}/oauth_apps`, [], { + filter: AUTHORITY_FILTER, + id_prefix: 'app-', + prepare: (item) => ({ + uid: generateID(32), + secret: generateID(64), + ...item, + }), +}); -/** POST create application */ -registerMockEndpoint({ - path: `${API}/doorkeeper/applications`, - metadata: [], - method: 'POST', - callback: (event) => { - const app = { - id: `app-${generateID()}`, - uid: generateID(32), - secret: generateID(64), - ...event.body, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - APPLICATIONS.push(app); - saveToSession('applications', APPLICATIONS); - return app; - }, -} as MockHttpRequestHandler); - -/** PUT/PATCH update application */ -registerMockEndpoint({ - path: `${API}/doorkeeper/applications/:id`, - metadata: [], - method: 'PUT', - callback: (event) => { - const index = APPLICATIONS.findIndex( - (a) => a.id === event.route_params.id, - ); - if (index >= 0) { - APPLICATIONS[index] = { - ...APPLICATIONS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('applications', APPLICATIONS); - return APPLICATIONS[index]; - } - throw { status: 404, message: 'Application not found' }; - }, -} as MockHttpRequestHandler); - -registerMockEndpoint({ - path: `${API}/doorkeeper/applications/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = APPLICATIONS.findIndex( - (a) => a.id === event.route_params.id, - ); - if (index >= 0) { - APPLICATIONS[index] = { - ...APPLICATIONS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('applications', APPLICATIONS); - return APPLICATIONS[index]; - } - throw { status: 404, message: 'Application not found' }; - }, -} as MockHttpRequestHandler); +// ============ UPLOADS ============ -/** DELETE application */ -registerMockEndpoint({ - path: `${API}/doorkeeper/applications/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = APPLICATIONS.findIndex( - (a) => a.id === event.route_params.id, - ); - if (index >= 0) { - APPLICATIONS.splice(index, 1); - saveToSession('applications', APPLICATIONS); - return {}; - } - throw { status: 404, message: 'Application not found' }; - }, -} as MockHttpRequestHandler); +generateBasicHandlers(`${API}/uploads`, [], { + filter: AUTHORITY_FILTER, + id_prefix: 'upload-', + prepare: (item) => ({ file_path: `/uploads/${generateID()}.bin`, ...item }), +}); -// ============ UPLOADS ============ +// ============ STORAGE PROVIDERS ============ -/** GET uploads list */ -registerMockEndpoint({ - path: `${API}/uploads`, - metadata: [], - method: 'GET', - callback: (event) => createFilter(UPLOADS)(event.query_params), -} as MockHttpRequestHandler); +generateBasicHandlers(`${API}/storages`, [], { + filter: AUTHORITY_FILTER, + id_prefix: 'storage-', +}); + +// ============ SIGNAGE ============ + +generateBasicHandlers(`${API}/signage/plugins`, [], { + filter: AUTHORITY_FILTER, + id_prefix: 'plugin-', +}); + +const PLAYLIST_DATA = ['Lobby', 'Cafe Specials', 'Safety Notices'].map( + (name) => ({ + id: `playlist-${name.toLowerCase().replace(/\W+/g, '-')}`, + name, + description: '', + authority_id: AUTHORITY_ID, + default_animation: 'cut', + orientation: 'landscape', + play_count: 0, + play_through_count: 0, + created_at: 1709283600, + updated_at: 1709283600, + }), +); -/** GET upload by ID */ -registerMockEndpoint({ - path: `${API}/uploads/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const upload = UPLOADS.find((u) => u.id === event.route_params.id); - if (upload) return upload; - throw { status: 404, message: 'Upload not found' }; - }, -} as MockHttpRequestHandler); +generateBasicHandlers(`${API}/signage/playlists`, PLAYLIST_DATA, { + filter: AUTHORITY_FILTER, + id_prefix: 'playlist-', +}); -/** POST create upload */ +/** Prove the credentials work. The mock always succeeds */ registerMockEndpoint({ - path: `${API}/uploads`, - metadata: [], + path: `${API}/signage/ai/providers/:id/test`, method: 'POST', - callback: (event) => { - const upload = { - id: `upload-${generateID()}`, - ...event.body, - file_path: `/uploads/${generateID()}.bin`, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - UPLOADS.push(upload); - saveToSession('uploads', UPLOADS); - return upload; - }, -} as MockHttpRequestHandler); - -/** DELETE upload */ -registerMockEndpoint({ - path: `${API}/uploads/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = UPLOADS.findIndex((u) => u.id === event.route_params.id); - if (index >= 0) { - UPLOADS.splice(index, 1); - saveToSession('uploads', UPLOADS); - return {}; - } - throw { status: 404, message: 'Upload not found' }; - }, -} as MockHttpRequestHandler); + callback: () => ({ ok: true, latency_ms: 420, model: 'mock-image-1' }), +}); -// ============ STORAGE PROVIDERS ============ +generateBasicHandlers(`${API}/signage/ai/providers`, [], { + filter: AUTHORITY_FILTER, + id_prefix: 'ai-provider-', +}); -/** GET storage providers list */ registerMockEndpoint({ - path: `${API}/storages`, - metadata: [], + path: `${API}/signage/ai/usage`, method: 'GET', - callback: (event) => createFilter(STORAGE_PROVIDERS)(event.query_params), -} as MockHttpRequestHandler); + callback: () => [], +}); -/** GET storage provider by ID */ -registerMockEndpoint({ - path: `${API}/storages/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const provider = STORAGE_PROVIDERS.find( - (p) => p.id === event.route_params.id, - ); - if (provider) return provider; - throw { status: 404, message: 'Storage provider not found' }; - }, -} as MockHttpRequestHandler); +// ============ BUILD JOBS ============ -/** POST create storage provider */ -registerMockEndpoint({ - path: `${API}/storages`, - metadata: [], - method: 'POST', - callback: (event) => { - const provider = { - id: `storage-${generateID()}`, - ...event.body, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - STORAGE_PROVIDERS.push(provider); - saveToSession('storage_providers', STORAGE_PROVIDERS); - return provider; - }, -} as MockHttpRequestHandler); +const BUILD_API = '/api/build/v1'; -/** PUT/PATCH update storage provider */ -registerMockEndpoint({ - path: `${API}/storages/:id`, - metadata: [], - method: 'PUT', - callback: (event) => { - const index = STORAGE_PROVIDERS.findIndex( - (p) => p.id === event.route_params.id, - ); - if (index >= 0) { - STORAGE_PROVIDERS[index] = { - ...STORAGE_PROVIDERS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('storage_providers', STORAGE_PROVIDERS); - return STORAGE_PROVIDERS[index]; - } - throw { status: 404, message: 'Storage provider not found' }; +/** Build jobs of the build service. Cancelled jobs stay in the list */ +const build_jobs = createMockStore('build_jobs', [ + { + id: `job-${generateID()}`, + state: 'running', + message: 'Compiling', + driver: 'drivers/place/meet.cr', + repo: 'https://github.com/PlaceOS/drivers', + branch: 'master', + commit: 'HEAD', + timestamp: new Date().toISOString(), }, -} as MockHttpRequestHandler); + { + id: `job-${generateID()}`, + state: 'done', + message: 'Compiled', + driver: 'drivers/place/bookings.cr', + repo: 'https://github.com/PlaceOS/drivers', + branch: 'master', + commit: 'HEAD', + timestamp: new Date(Date.now() - 3_600_000).toISOString(), + }, +]); registerMockEndpoint({ - path: `${API}/storages/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = STORAGE_PROVIDERS.findIndex( - (p) => p.id === event.route_params.id, - ); - if (index >= 0) { - STORAGE_PROVIDERS[index] = { - ...STORAGE_PROVIDERS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('storage_providers', STORAGE_PROVIDERS); - return STORAGE_PROVIDERS[index]; - } - throw { status: 404, message: 'Storage provider not found' }; - }, -} as MockHttpRequestHandler); + path: `${BUILD_API}/monitor`, + method: 'GET', + callback: (event) => ({ + data: build_jobs().filter( + (job) => + !event.query_params.state || + job.state === event.query_params.state, + ), + }), +}); -/** DELETE storage provider */ registerMockEndpoint({ - path: `${API}/storages/:id`, - metadata: [], + path: `${BUILD_API}/cancel/:id`, method: 'DELETE', callback: (event) => { - const index = STORAGE_PROVIDERS.findIndex( - (p) => p.id === event.route_params.id, + const job = build_jobs().find(({ id }) => id === event.route_params.id); + if (!job) return notFound('Build job'); + build_jobs.set( + build_jobs().map((item) => + item === job + ? { ...item, state: 'cancelled', message: 'Cancelled' } + : item, + ), ); - if (index >= 0) { - STORAGE_PROVIDERS.splice(index, 1); - saveToSession('storage_providers', STORAGE_PROVIDERS); - return {}; - } - throw { status: 404, message: 'Storage provider not found' }; - }, -} as MockHttpRequestHandler); - -// ============ CLUSTER / SYSTEM INFO ============ - -/** GET cluster details */ -registerMockEndpoint({ - path: `${API}/cluster/details`, - metadata: [], - method: 'GET', - callback: (_event) => { - return { - compiled_drivers: ['driver-1', 'driver-2'], - available_repositories: ['repo-1'], - running_drivers: 5, - module_instances: 10, - unavailable_repositories: [], - unavailable_drivers: [], - }; - }, -} as MockHttpRequestHandler); - -/** GET processes */ -registerMockEndpoint({ - path: `${API}/cluster/processes`, - metadata: [], - method: 'GET', - callback: (_event) => { - return []; - }, -} as MockHttpRequestHandler); - -/** GET core load */ -registerMockEndpoint({ - path: `${API}/cluster/core_load`, - metadata: [], - method: 'GET', - callback: (_event) => { - return { - local: { - hostname: 'localhost', - cpu_count: 4, - core_cpu: 5.2, - total_cpu: 12.5, - memory_total: 16000000000, - memory_usage: 8000000000, - core_memory: 500000000, - }, - }; + return null; }, -} as MockHttpRequestHandler); +}); diff --git a/src/app/mocks/backend/auth-sources.mock.ts b/src/app/mocks/backend/auth-sources.mock.ts index 5ce7d8c8b..b880a7837 100644 --- a/src/app/mocks/backend/auth-sources.mock.ts +++ b/src/app/mocks/backend/auth-sources.mock.ts @@ -1,350 +1,22 @@ -import { - MockHttpRequestHandler, - registerMockEndpoint, -} from '@placeos/ts-client'; import { HashMap } from '../../common/types'; -import { - API, - generateID, - loadFromSession, - saveToSession, -} from '../common.mock'; - -/** In-memory storage for auth sources with session persistence */ -const OAUTH_SOURCES: Record[] = loadFromSession( - 'oauth_sources', - [], -); -const SAML_SOURCES: Record[] = loadFromSession( - 'saml_sources', - [], -); -const LDAP_SOURCES: Record[] = loadFromSession( - 'ldap_sources', - [], -); - -const createFilter = (items: Record[]) => (q: HashMap) => { - if (!q || Object.keys(q).length <= 0) { - return items; - } - return items.filter((item) => { - let match = true; - if (q.authority_id) { - match = match && item.authority_id === q.authority_id; - } - if (q.q) { - match = - match && - `${item.name || ''}` - .toLowerCase() - .indexOf(((q.q as string) || '').toLowerCase()) >= 0; - } - return match; - }); -}; - -// ============ OAUTH SOURCES ============ - -/** GET OAuth sources list */ -registerMockEndpoint({ - path: `${API}/oauth_auths`, - metadata: [], - method: 'GET', - callback: (event) => createFilter(OAUTH_SOURCES)(event.query_params), -} as MockHttpRequestHandler); - -/** GET OAuth source by ID */ -registerMockEndpoint({ - path: `${API}/oauth_auths/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const source = OAUTH_SOURCES.find( - (s) => s.id === event.route_params.id, - ); - if (source) return source; - throw { status: 404, message: 'OAuth source not found' }; - }, -} as MockHttpRequestHandler); - -/** POST create OAuth source */ -registerMockEndpoint({ - path: `${API}/oauth_auths`, - metadata: [], - method: 'POST', - callback: (event) => { - const source = { - id: `oauth-${generateID()}`, - ...event.body, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - OAUTH_SOURCES.push(source); - saveToSession('oauth_sources', OAUTH_SOURCES); - return source; - }, -} as MockHttpRequestHandler); - -/** PUT/PATCH update OAuth source */ -registerMockEndpoint({ - path: `${API}/oauth_auths/:id`, - metadata: [], - method: 'PUT', - callback: (event) => { - const index = OAUTH_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - OAUTH_SOURCES[index] = { - ...OAUTH_SOURCES[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('oauth_sources', OAUTH_SOURCES); - return OAUTH_SOURCES[index]; - } - throw { status: 404, message: 'OAuth source not found' }; - }, -} as MockHttpRequestHandler); - -registerMockEndpoint({ - path: `${API}/oauth_auths/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = OAUTH_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - OAUTH_SOURCES[index] = { - ...OAUTH_SOURCES[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('oauth_sources', OAUTH_SOURCES); - return OAUTH_SOURCES[index]; - } - throw { status: 404, message: 'OAuth source not found' }; - }, -} as MockHttpRequestHandler); - -/** DELETE OAuth source */ -registerMockEndpoint({ - path: `${API}/oauth_auths/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = OAUTH_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - OAUTH_SOURCES.splice(index, 1); - saveToSession('oauth_sources', OAUTH_SOURCES); - return {}; - } - throw { status: 404, message: 'OAuth source not found' }; - }, -} as MockHttpRequestHandler); - -// ============ SAML SOURCES ============ - -/** GET SAML sources list */ -registerMockEndpoint({ - path: `${API}/saml_auths`, - metadata: [], - method: 'GET', - callback: (event) => createFilter(SAML_SOURCES)(event.query_params), -} as MockHttpRequestHandler); - -/** GET SAML source by ID */ -registerMockEndpoint({ - path: `${API}/saml_auths/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const source = SAML_SOURCES.find((s) => s.id === event.route_params.id); - if (source) return source; - throw { status: 404, message: 'SAML source not found' }; - }, -} as MockHttpRequestHandler); - -/** POST create SAML source */ -registerMockEndpoint({ - path: `${API}/saml_auths`, - metadata: [], - method: 'POST', - callback: (event) => { - const source = { - id: `saml-${generateID()}`, - ...event.body, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - SAML_SOURCES.push(source); - saveToSession('saml_sources', SAML_SOURCES); - return source; - }, -} as MockHttpRequestHandler); - -/** PUT/PATCH update SAML source */ -registerMockEndpoint({ - path: `${API}/saml_auths/:id`, - metadata: [], - method: 'PUT', - callback: (event) => { - const index = SAML_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - SAML_SOURCES[index] = { - ...SAML_SOURCES[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('saml_sources', SAML_SOURCES); - return SAML_SOURCES[index]; - } - throw { status: 404, message: 'SAML source not found' }; - }, -} as MockHttpRequestHandler); - -registerMockEndpoint({ - path: `${API}/saml_auths/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = SAML_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - SAML_SOURCES[index] = { - ...SAML_SOURCES[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('saml_sources', SAML_SOURCES); - return SAML_SOURCES[index]; - } - throw { status: 404, message: 'SAML source not found' }; - }, -} as MockHttpRequestHandler); - -/** DELETE SAML source */ -registerMockEndpoint({ - path: `${API}/saml_auths/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = SAML_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - SAML_SOURCES.splice(index, 1); - saveToSession('saml_sources', SAML_SOURCES); - return {}; - } - throw { status: 404, message: 'SAML source not found' }; - }, -} as MockHttpRequestHandler); - -// ============ LDAP SOURCES ============ - -/** GET LDAP sources list */ -registerMockEndpoint({ - path: `${API}/ldap_auths`, - metadata: [], - method: 'GET', - callback: (event) => createFilter(LDAP_SOURCES)(event.query_params), -} as MockHttpRequestHandler); - -/** GET LDAP source by ID */ -registerMockEndpoint({ - path: `${API}/ldap_auths/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const source = LDAP_SOURCES.find((s) => s.id === event.route_params.id); - if (source) return source; - throw { status: 404, message: 'LDAP source not found' }; - }, -} as MockHttpRequestHandler); - -/** POST create LDAP source */ -registerMockEndpoint({ - path: `${API}/ldap_auths`, - metadata: [], - method: 'POST', - callback: (event) => { - const source = { - id: `ldap-${generateID()}`, - ...event.body, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - LDAP_SOURCES.push(source); - saveToSession('ldap_sources', LDAP_SOURCES); - return source; - }, -} as MockHttpRequestHandler); - -/** PUT/PATCH update LDAP source */ -registerMockEndpoint({ - path: `${API}/ldap_auths/:id`, - metadata: [], - method: 'PUT', - callback: (event) => { - const index = LDAP_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - LDAP_SOURCES[index] = { - ...LDAP_SOURCES[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('ldap_sources', LDAP_SOURCES); - return LDAP_SOURCES[index]; - } - throw { status: 404, message: 'LDAP source not found' }; - }, -} as MockHttpRequestHandler); - -registerMockEndpoint({ - path: `${API}/ldap_auths/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = LDAP_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - LDAP_SOURCES[index] = { - ...LDAP_SOURCES[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('ldap_sources', LDAP_SOURCES); - return LDAP_SOURCES[index]; - } - throw { status: 404, message: 'LDAP source not found' }; - }, -} as MockHttpRequestHandler); - -/** DELETE LDAP source */ -registerMockEndpoint({ - path: `${API}/ldap_auths/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = LDAP_SOURCES.findIndex( - (s) => s.id === event.route_params.id, - ); - if (index >= 0) { - LDAP_SOURCES.splice(index, 1); - saveToSession('ldap_sources', LDAP_SOURCES); - return {}; - } - throw { status: 404, message: 'LDAP source not found' }; - }, -} as MockHttpRequestHandler); +import { API, generateBasicHandlers, nameFilter } from '../common.mock'; + +/** Matches `q` against the name and `authority_id` against the source */ +const FILTER_FN = (item: Record, q: HashMap) => + nameFilter(item, q) && + (!q.authority_id || item.authority_id === q.authority_id); + +generateBasicHandlers(`${API}/oauth_auths`, [], { + filter: FILTER_FN, + id_prefix: 'oauth-', +}); + +generateBasicHandlers(`${API}/saml_auths`, [], { + filter: FILTER_FN, + id_prefix: 'saml-', +}); + +generateBasicHandlers(`${API}/ldap_auths`, [], { + filter: FILTER_FN, + id_prefix: 'ldap-', +}); diff --git a/src/app/mocks/backend/domains.mock.ts b/src/app/mocks/backend/domains.mock.ts index 6eb7efec4..8dba7ec25 100644 --- a/src/app/mocks/backend/domains.mock.ts +++ b/src/app/mocks/backend/domains.mock.ts @@ -1,20 +1,5 @@ -import { HashMap } from '../../common/types'; -import { API, DOMAIN, generateBasicHandlers } from '../common.mock'; - -const FILTER_FN = (item: Record, q: HashMap) => { - if (!q || Object.keys(q).length <= 0) { - return true; - } - let match = true; - if (q.q) { - match = - match && - `${item.name || ''}` - .toLowerCase() - .indexOf(((q.q as string) || '').toLowerCase()) >= 0; - } - return match; -}; +import { registerMockEndpoint } from '@placeos/ts-client'; +import { API, DOMAIN, generateBasicHandlers, nameFilter } from '../common.mock'; /** Id of the authority the ts-client mock signs in to. Every mock user and * group belongs to it */ @@ -30,4 +15,14 @@ const DOMAIN_DATA = [ ]; /** Add basic API handlers for domains */ -generateBasicHandlers(`${API}/domains`, DOMAIN_DATA, FILTER_FN); +generateBasicHandlers(`${API}/domains`, DOMAIN_DATA, { + filter: nameFilter, + id_prefix: 'authority-', +}); + +/** Azure admin consent link for the domain */ +registerMockEndpoint({ + path: `${API}/admin_consent/:id`, + method: 'GET', + callback: () => ({ url: 'about:blank' }), +}); diff --git a/src/app/mocks/backend/drivers.mock.ts b/src/app/mocks/backend/drivers.mock.ts index d638d7194..a423212d1 100644 --- a/src/app/mocks/backend/drivers.mock.ts +++ b/src/app/mocks/backend/drivers.mock.ts @@ -26,7 +26,10 @@ const FILTER_FN = (item: Record, q: HashMap) => { }; /** Add basic API handlers for drivers */ -generateBasicHandlers(`${API}/drivers`, DRIVER_DATA, FILTER_FN); +generateBasicHandlers(`${API}/drivers`, DRIVER_DATA, { + filter: FILTER_FN, + id_prefix: 'driver-', +}); /** Check if driver is compiled */ registerMockEndpoint({ diff --git a/src/app/mocks/backend/general.mock.ts b/src/app/mocks/backend/general.mock.ts index 69c84b61e..c293e2f8a 100644 --- a/src/app/mocks/backend/general.mock.ts +++ b/src/app/mocks/backend/general.mock.ts @@ -1,5 +1,12 @@ import { registerMockEndpoint } from '@placeos/ts-client'; -import { API, generateBasicHandlers } from '../common.mock'; +import { + API, + createMockStore, + endpointData, + generateBasicHandlers, + notFound, + now, +} from '../common.mock'; registerMockEndpoint({ path: `${API}/version`, @@ -13,11 +20,18 @@ registerMockEndpoint({ }); registerMockEndpoint({ - path: `${API}/clusters`, + path: `${API}/platform`, method: 'GET', - callback: () => [], + callback: () => ({ version: 'mock', changelog: '' }), }); +/** Custom schemas in the admin section */ +generateBasicHandlers(`${API}/schema`, [], { id_prefix: 'schema-' }); + +// ============ CLUSTERS ============ + +const CLUSTER_ID = 'core-mock'; + /** Backend versions for the admin about section */ registerMockEndpoint({ path: `${API}/cluster/versions`, @@ -25,11 +39,106 @@ registerMockEndpoint({ callback: () => [], }); +/** Driver files whose process was terminated */ +const terminated = createMockStore('cluster_terminated', []); + +/** Running driver processes of the cluster, made from the mock drivers */ +function clusterProcesses() { + const modules = endpointData(`${API}/modules`); + return endpointData(`${API}/drivers`) + .filter((driver) => !terminated().includes(driver.file_name)) + .map((driver, idx) => { + const driver_modules = modules + .filter((mod) => mod.driver_id === driver.id) + .map((mod) => mod.id); + return { + id: driver.file_name || driver.id, + modules: driver_modules, + running: true, + module_instances: driver_modules.length, + last_exit_code: 0, + launch_count: 1, + launch_time: now() - idx * 3600, + percentage_cpu: (idx % 5) * 0.4, + memory_total: 16_000_000, + memory_usage: 40_000 + idx * 2_000, + }; + }); +} + registerMockEndpoint({ - path: `${API}/platform`, + path: `${API}/cluster`, method: 'GET', - callback: () => ({ version: 'mock', changelog: '' }), + callback: () => [ + { + id: CLUSTER_ID, + compiled_drivers: clusterProcesses().map(({ id }) => id), + available_repositories: endpointData(`${API}/repositories`).map( + ({ folder_name }) => folder_name, + ), + running_drivers: clusterProcesses().length, + module_instances: endpointData(`${API}/modules`).length, + unavailable_repositories: [], + unavailable_drivers: [], + hostname: 'core.place.tech', + cpu_count: 4, + core_cpu: 5.2, + total_cpu: 12.5, + memory_total: 16_000_000, + memory_usage: 8_000_000, + core_memory: 500_000, + }, + ], }); -/** Custom schemas in the admin section */ -generateBasicHandlers(`${API}/schema`, []); +/** Processes of a cluster */ +registerMockEndpoint({ + path: `${API}/cluster/:id`, + method: 'GET', + callback: (event) => + event.route_params.id === CLUSTER_ID + ? clusterProcesses() + : notFound('Cluster'), +}); + +/** Terminate the process of a driver */ +registerMockEndpoint({ + path: `${API}/cluster/:id`, + method: 'DELETE', + callback: (event) => { + const driver = event.query_params.driver; + if (!driver) throw { status: 400, message: 'driver is required' }; + terminated.set([...terminated(), driver]); + return null; + }, +}); + +// ============ MQTT RE-SYNC ============ + +/** Where the last MQTT re-sync got to */ +const resync = createMockStore>('source_resync', { + state: 'idle', +}); + +registerMockEndpoint({ + path: `${API}/source/resync`, + method: 'GET', + callback: () => resync(), +}); + +/** Re-sync finishes at once, as the mock has no brokers to publish to */ +registerMockEndpoint({ + path: `${API}/source/resync`, + method: 'POST', + callback: (event) => { + const clear = event.query_params.clear === 'true'; + resync.set({ + state: 'complete', + clear, + cleared: clear ? 42 : 0, + started_at: new Date().toISOString(), + finished_at: new Date().toISOString(), + }); + return resync(); + }, +}); diff --git a/src/app/mocks/backend/groups.mock.ts b/src/app/mocks/backend/groups.mock.ts index faff0b17a..82e829682 100644 --- a/src/app/mocks/backend/groups.mock.ts +++ b/src/app/mocks/backend/groups.mock.ts @@ -2,10 +2,10 @@ import { MockHttpRequest, registerMockEndpoint } from '@placeos/ts-client'; import { HashMap } from '../../common/types'; import { API, + createMockStore, endpointData, + endpointToStorageKey, generateBasicHandlers, - loadFromSession, - saveToSession, } from '../common.mock'; import { AUTHORITY_ID } from './domains.mock'; @@ -108,11 +108,34 @@ const GROUP_FILTER_FN = (item: MockGroup, q: HashMap) => { return true; }; -const groups = generateBasicHandlers( - `${API}/groups`, - GROUP_DATA, - GROUP_FILTER_FN, -); +/** + * Groups of the current user, with their permissions. + * Registered before `groups/:id`. `subsystem` limits the list to groups + * that have the subsystem + */ +registerMockEndpoint({ + path: `${API}/groups/current`, + method: 'GET', + callback: (event) => { + const { subsystem } = event.query_params; + return group_users() + .filter(({ user_id }) => user_id === 'current') + .map((row) => ({ + group: findGroup(row.group_id), + permissions: row.permissions, + })) + .filter( + ({ group }) => + group && + (!subsystem || group.subsystems.includes(subsystem)), + ); + }, +}); + +const groups = generateBasicHandlers(`${API}/groups`, GROUP_DATA, { + filter: GROUP_FILTER_FN, + id_prefix: 'group-', +}); /** Count of direct children, which the API adds to group details */ function withChildCount(group: MockGroup) { @@ -141,24 +164,21 @@ registerMockEndpoint({ * tests can seed them with `seedMockData`. * @param endpoint API endpoint path * @param keys Names of the two ID fields, in path order - * @param seed Rows used when session storage has none. Called on first use + * @param seed Rows used when session storage has none * @param create Makes a full row from the POST body * @param expand Adds related details to rows in responses + * @returns Store of the rows */ function generateJoinHandlers( endpoint: string, keys: [keyof T & string, keyof T & string], - seed: () => T[], + seed: T[], create: (body: Partial) => T, expand: (row: T) => T & Record, ) { - const storage_key = endpoint.replace(/\//g, '_').replace(/^_/, ''); - let rows: T[] | null = null; - const list = () => (rows ??= loadFromSession(storage_key, seed())); - const save = (next: T[]) => { - rows = next; - saveToSession(storage_key, next); - }; + const rows = createMockStore(endpointToStorageKey(endpoint), seed); + const list = () => rows(); + const save = (next: T[]) => rows.set(next); const matches = (row: T, ids: HashMap) => keys.every((key) => !ids[key] || `${row[key]}` === ids[key]); const indexOf = (event: MockHttpRequest) => { @@ -224,6 +244,7 @@ function generateJoinHandlers( return null; }, }); + return rows; } /** Group details for the user and zone pages */ @@ -231,18 +252,17 @@ function findGroup(group_id: string) { return groups().find(({ id }) => id === group_id); } -generateJoinHandlers( +const group_users = generateJoinHandlers( `${API}/group_users`, ['user_id', 'group_id'], - () => - GROUP_USER_SEED.map(([user_id, group_id, permissions]) => ({ - user_id, - group_id, - permissions, - auto_assigned: '', - created_at: SEED_TIME, - updated_at: SEED_TIME, - })), + GROUP_USER_SEED.map(([user_id, group_id, permissions]) => ({ + user_id, + group_id, + permissions, + auto_assigned: '', + created_at: SEED_TIME, + updated_at: SEED_TIME, + })), (body) => { const now = new Date().toISOString(); return { @@ -268,15 +288,14 @@ generateJoinHandlers( generateJoinHandlers( `${API}/group_zones`, ['group_id', 'zone_id'], - () => - GROUP_ZONE_SEED.map(([group_id, zone_id, permissions, deny]) => ({ - group_id, - zone_id, - permissions, - deny, - created_at: SEED_TIME, - updated_at: SEED_TIME, - })), + GROUP_ZONE_SEED.map(([group_id, zone_id, permissions, deny]) => ({ + group_id, + zone_id, + permissions, + deny, + created_at: SEED_TIME, + updated_at: SEED_TIME, + })), (body) => { const now = new Date().toISOString(); return { diff --git a/src/app/mocks/backend/history.mock.ts b/src/app/mocks/backend/history.mock.ts deleted file mode 100644 index 131a640dd..000000000 --- a/src/app/mocks/backend/history.mock.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { - MockHttpRequestHandler, - registerMockEndpoint, -} from '@placeos/ts-client'; -import { API, generateID } from '../common.mock'; - -/** - * Generate mock history entries - */ -function generateHistory( - parent_id: string, - count = 5, -): Record[] { - const actions = ['create', 'update', 'delete']; - const users = ['admin@place.tech', 'user@place.tech', 'system']; - - return Array(count) - .fill(0) - .map((_, i) => ({ - id: `history-${generateID()}`, - parent_id, - action: actions[Math.floor(Math.random() * actions.length)], - user_id: `user-${i}`, - user_email: users[Math.floor(Math.random() * users.length)], - changes: { - name: { from: 'Old Name', to: 'New Name' }, - }, - created_at: Date.now() / 1000 - i * 86400, // One day apart - })); -} - -// Parent types that support history -const PARENT_TYPES = [ - 'systems', - 'zones', - 'drivers', - 'modules', - 'users', - 'triggers', - 'repositories', -]; - -// Register history endpoints for each parent type -PARENT_TYPES.forEach((parent_type) => { - /** GET history for parent */ - registerMockEndpoint({ - path: `${API}/${parent_type}/:id/history`, - metadata: [], - method: 'GET', - callback: (event) => { - const parent_id = event.route_params.id; - const limit = parseInt(event.query_params?.limit) || 10; - return generateHistory(parent_id, limit); - }, - } as MockHttpRequestHandler); -}); - -// Settings history -registerMockEndpoint({ - path: `${API}/settings/:id/history`, - metadata: [], - method: 'GET', - callback: (event) => { - const parent_id = event.route_params.id; - return generateHistory(parent_id, 5).map((h) => ({ - ...h, - settings_string: '{}', - })); - }, -} as MockHttpRequestHandler); diff --git a/src/app/mocks/backend/index.ts b/src/app/mocks/backend/index.ts index 8e7569caf..4c491dd1d 100644 --- a/src/app/mocks/backend/index.ts +++ b/src/app/mocks/backend/index.ts @@ -11,7 +11,10 @@ import './zones.mock'; import './admin.mock'; import './auth-sources.mock'; import './general.mock'; -import './history.mock'; import './metadata.mock'; +// Settings are made from the items above, so import it after them import './settings.mock'; import './staff-api.mock'; + +// Matches any `systems/:id/:module` path, so it must be last +import './system-control.mock'; diff --git a/src/app/mocks/backend/metadata.mock.ts b/src/app/mocks/backend/metadata.mock.ts index 603760d59..6537b4c36 100644 --- a/src/app/mocks/backend/metadata.mock.ts +++ b/src/app/mocks/backend/metadata.mock.ts @@ -1,177 +1,124 @@ -import { - MockHttpRequestHandler, - registerMockEndpoint, -} from '@placeos/ts-client'; -import { HashMap } from '../../common/types'; -import { API } from '../common.mock'; +import { registerMockEndpoint } from '@placeos/ts-client'; +import { API, createMockStore, now } from '../common.mock'; -/** In-memory metadata storage */ -const METADATA_STORE: HashMap>> = {}; - -/** - * Get metadata for a parent - */ -function getMetadata(parent_id: string): Record[] { - if (!METADATA_STORE[parent_id]) { - METADATA_STORE[parent_id] = {}; - } - return Object.entries(METADATA_STORE[parent_id]).map(([name, data]) => ({ - id: `${parent_id}_${name}`, - name, - parent_id, - details: data.details || {}, - description: data.description || '', - editors: data.editors || [], - schema: data.schema || {}, - modified_by_id: 'current', - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - })); +interface MockMetadata { + id: string; + parent_id: string; + name: string; + description: string; + details: unknown; + editors: string[]; + schema: string; + modified_by_id: string; + created_at: number; + updated_at: number; } -/** - * Add or update metadata - */ -function setMetadata( - parent_id: string, - name: string, - data: Record, -): Record { - if (!METADATA_STORE[parent_id]) { - METADATA_STORE[parent_id] = {}; - } - METADATA_STORE[parent_id][name] = data; - return { - id: `${parent_id}_${name}`, - name, - parent_id, - details: data.details || {}, - description: data.description || '', - editors: data.editors || [], - schema: data.schema || {}, - modified_by_id: 'current', - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; -} +/** Most old versions kept for each metadata block */ +const HISTORY_LIMIT = 20; -/** - * Delete metadata - */ -function deleteMetadata(parent_id: string, name: string): void { - if (METADATA_STORE[parent_id]) { - delete METADATA_STORE[parent_id][name]; - } -} +/** Metadata blocks of every parent */ +const metadata = createMockStore('metadata', []); +/** Old versions of metadata blocks, newest first */ +const history = createMockStore('metadata_history', []); -// Parent types that support metadata -const PARENT_TYPES = ['systems', 'zones', 'drivers', 'users']; +/** Group a list of blocks by name, which is how the API returns them */ +function byName(list: T[]) { + return Object.fromEntries(list.map((item) => [item.name, item])); +} -function delayedMetadata(parent_id: string) { +/** Blocks of a parent, with an optional delay that e2e tests set */ +function listFor(parent_id: string, name?: string) { + const result = byName( + metadata().filter( + (item) => + item.parent_id === parent_id && (!name || item.name === name), + ), + ); const delay = Number( sessionStorage.getItem('PLACEOS.mocks.metadata_delay') || 0, ); - if (!delay) return getMetadata(parent_id); - return new Promise((resolve) => - setTimeout(() => resolve(getMetadata(parent_id)), delay), + if (!delay) return result; + return new Promise((resolve) => setTimeout(() => resolve(result), delay)); +} + +/** Add or change a block. The old version goes to the history */ +function save(parent_id: string, body: Partial) { + if (!body.name) throw { status: 400, message: 'name is required' }; + const old = metadata().find( + (item) => item.parent_id === parent_id && item.name === body.name, ); + const item: MockMetadata = { + description: '', + details: {}, + editors: [], + schema: '', + created_at: now(), + ...old, + ...body, + id: `${parent_id}_${body.name}`, + parent_id, + name: body.name, + modified_by_id: 'current', + updated_at: now(), + }; + if (old) { + const versions = history().filter((v) => v.id === old.id); + const others = history().filter((v) => v.id !== old.id); + history.set([old, ...versions].slice(0, HISTORY_LIMIT).concat(others)); + } + metadata.set([...metadata().filter((i) => i !== old), item]); + return item; } -/** GET metadata list for parent */ registerMockEndpoint({ path: `${API}/metadata/:id`, - metadata: [], method: 'GET', - callback: (event) => delayedMetadata(event.route_params.id), -} as MockHttpRequestHandler); - -// Register metadata endpoints for each parent type -PARENT_TYPES.forEach((parent_type) => { - /** GET metadata list for parent */ - registerMockEndpoint({ - path: `${API}/${parent_type}/:id/metadata`, - metadata: [], - method: 'GET', - callback: (event) => { - const parent_id = event.route_params.id; - return delayedMetadata(parent_id); - }, - } as MockHttpRequestHandler); - - /** GET specific metadata by name */ - registerMockEndpoint({ - path: `${API}/${parent_type}/:id/metadata/:name`, - metadata: [], - method: 'GET', - callback: (event) => { - const parent_id = event.route_params.id; - const name = event.route_params.name; - const all_metadata = getMetadata(parent_id); - const metadata = all_metadata.find((m) => m.name === name); - if (metadata) { - return metadata; - } - throw { status: 404, message: 'Metadata not found' }; - }, - } as MockHttpRequestHandler); - - /** POST create metadata */ - registerMockEndpoint({ - path: `${API}/${parent_type}/:id/metadata`, - metadata: [], - method: 'POST', - callback: (event) => { - const parent_id = event.route_params.id; - const data = event.body; - return setMetadata(parent_id, data.name, data); - }, - } as MockHttpRequestHandler); + callback: (event) => + listFor(event.route_params.id, event.query_params.name), +}); - /** PUT/PATCH update metadata */ - registerMockEndpoint({ - path: `${API}/${parent_type}/:id/metadata/:name`, - metadata: [], - method: 'PUT', - callback: (event) => { - const parent_id = event.route_params.id; - const name = event.route_params.name; - const data = event.body; - return setMetadata(parent_id, name, data); - }, - } as MockHttpRequestHandler); +registerMockEndpoint({ + path: `${API}/metadata`, + method: 'POST', + callback: (event) => save(event.body.parent_id, event.body), +}); +for (const method of ['PUT', 'PATCH'] as const) { registerMockEndpoint({ - path: `${API}/${parent_type}/:id/metadata/:name`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const parent_id = event.route_params.id; - const name = event.route_params.name; - const data = event.body; - return setMetadata(parent_id, name, data); - }, - } as MockHttpRequestHandler); + path: `${API}/metadata/:id`, + method, + callback: (event) => save(event.route_params.id, event.body), + }); +} - /** DELETE metadata */ - registerMockEndpoint({ - path: `${API}/${parent_type}/:id/metadata/:name`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const parent_id = event.route_params.id; - const name = event.route_params.name; - deleteMetadata(parent_id, name); - return {}; - }, - } as MockHttpRequestHandler); +registerMockEndpoint({ + path: `${API}/metadata/:id`, + method: 'DELETE', + callback: (event) => { + const { id } = event.route_params; + const { name } = event.query_params; + metadata.set( + metadata().filter( + (item) => !(item.parent_id === id && item.name === name), + ), + ); + return null; + }, }); -/** History endpoint for metadata */ +/** Old versions of the blocks of a parent, grouped by name */ registerMockEndpoint({ path: `${API}/metadata/:id/history`, - metadata: [], method: 'GET', - callback: (_event) => { - return []; + callback: (event) => { + const { id } = event.route_params; + const { name } = event.query_params; + const groups: Record = {}; + for (const item of history()) { + if (item.parent_id !== id || (name && item.name !== name)) continue; + (groups[item.name] ||= []).push(item); + } + return groups; }, -} as MockHttpRequestHandler); +}); diff --git a/src/app/mocks/backend/modules.mock.ts b/src/app/mocks/backend/modules.mock.ts index c4442db25..21ae1323c 100644 --- a/src/app/mocks/backend/modules.mock.ts +++ b/src/app/mocks/backend/modules.mock.ts @@ -1,9 +1,12 @@ -import { - MockHttpRequestHandler, - registerMockEndpoint, -} from '@placeos/ts-client'; +import { registerMockEndpoint } from '@placeos/ts-client'; import { HashMap } from '../../common/types'; -import { API, endpointData, generateBasicHandlers } from '../common.mock'; +import { + API, + endpointData, + generateBasicHandlers, + notFound, + updateItem, +} from '../common.mock'; import { MODULES as MODULE_DATA } from '../data/modules'; const FILTER_FN = (item: Record, q: HashMap) => { @@ -34,72 +37,79 @@ const FILTER_FN = (item: Record, q: HashMap) => { }; /** Add basic API handlers for modules */ -generateBasicHandlers(`${API}/modules`, MODULE_DATA, FILTER_FN); +generateBasicHandlers(`${API}/modules`, MODULE_DATA, { + filter: FILTER_FN, + id_prefix: 'mod-', +}); -/** Add handler for starting a module */ registerMockEndpoint({ path: `${API}/modules/:id/start`, - metadata: [], method: 'POST', - callback: (event) => { - if (event.route_params.id) { - const module = endpointData(`${API}/modules`).find( - (mod) => mod.id === event.route_params.id, - ); - if (module) { - module.running = true; - return module; - } - } - throw { status: 404, message: 'Module not found' }; - }, -} as MockHttpRequestHandler); + callback: (event) => + updateItem(`${API}/modules`, event.route_params.id, { running: true }), +}); -/** Add handler for stopping a module */ registerMockEndpoint({ path: `${API}/modules/:id/stop`, - metadata: [], method: 'POST', - callback: (event) => { - if (event.route_params.id) { - const module = endpointData(`${API}/modules`).find( - (mod) => mod.id === event.route_params.id, - ); - if (module) { - module.running = false; - return module; - } - } - throw { status: 404, message: 'Module not found' }; - }, -} as MockHttpRequestHandler); + callback: (event) => + updateItem(`${API}/modules`, event.route_params.id, { running: false }), +}); + +/** Load the module on the cluster */ +registerMockEndpoint({ + path: `${API}/modules/:id/load`, + method: 'POST', + callback: (event) => + updateItem(`${API}/modules`, event.route_params.id, { running: true }), +}); -/** Add handler for pinging a module */ registerMockEndpoint({ path: `${API}/modules/:id/ping`, - metadata: [], method: 'POST', - callback: (_event) => { - return { host: 'localhost', pingable: true, warning: null }; - }, -} as MockHttpRequestHandler); + callback: () => ({ host: 'localhost', pingable: true, warning: null }), +}); -/** Add handler for module settings */ registerMockEndpoint({ path: `${API}/modules/:id/settings`, - metadata: [], method: 'GET', - callback: (_event) => { - return []; - }, -} as MockHttpRequestHandler); + callback: (event) => + endpointData(`${API}/settings`).filter( + (setting) => setting.parent_id === event.route_params.id, + ), +}); -/** Add handler for module state */ registerMockEndpoint({ path: `${API}/modules/:id/state`, - metadata: [], method: 'GET', - callback: (_event) => { - return { connected: true, running: true }; + callback: (event) => { + const module = findModule(event.route_params.id); + return { + connected: module.connected ?? true, + running: !!module.running, + }; }, -} as MockHttpRequestHandler); +}); + +/** Runtime errors of the module. Modules with `has_runtime_error` have one */ +registerMockEndpoint({ + path: `${API}/modules/:id/error`, + method: 'GET', + callback: (event) => + findModule(event.route_params.id).has_runtime_error + ? [ + JSON.stringify({ + message: 'Connection refused', + backtrace: ['mock.cr:1'], + }), + ] + : [], +}); + +/** Find a module, or fail with a 404 */ +function findModule(id: string) { + return ( + endpointData(`${API}/modules`).find((mod) => mod.id === id) || + notFound('Module') + ); +} diff --git a/src/app/mocks/backend/repositories.mock.ts b/src/app/mocks/backend/repositories.mock.ts index 2e5872fad..580545581 100644 --- a/src/app/mocks/backend/repositories.mock.ts +++ b/src/app/mocks/backend/repositories.mock.ts @@ -1,137 +1,152 @@ -import { - MockHttpRequestHandler, - PlaceRepositoryType, - registerMockEndpoint, -} from '@placeos/ts-client'; +import { PlaceRepositoryType, registerMockEndpoint } from '@placeos/ts-client'; import { DISCOVERY as DISCOVERY_DATA } from '../data/discovery'; -import { subMinutes } from 'date-fns'; -import { HashMap } from '../../common/types'; -import { API, generateBasicHandlers, generateID } from '../common.mock'; - -const FILTER_FN = (item: Record, q: HashMap) => { - if (!q || Object.keys(q).length <= 0) { - return true; - } - let match = true; - if (q.q) { - match = - match && - `${item.name || ''}` - .toLowerCase() - .indexOf(((q.q as string) || '').toLowerCase()) >= 0; - } - return match; -}; +import { + API, + endpointData, + generateBasicHandlers, + generateID, + nameFilter, + notFound, + updateItem, +} from '../common.mock'; const REPO_DATA = [ { - id: `repo-${generateID()}`, + id: 'repo-placeos-drivers', name: 'PlaceOS Drivers', folder_name: 'drivers/placeos', uri: 'https://github.com/PlaceOS/drivers', + branch: 'master', + commit_hash: 'HEAD', + repo_type: PlaceRepositoryType.Driver, + }, + { + id: 'repo-placeos-interfaces', + name: 'PlaceOS Interfaces', + folder_name: 'interfaces/placeos', + uri: 'https://github.com/PlaceOS/interfaces', + branch: 'main', commit_hash: 'HEAD', - type: PlaceRepositoryType.Driver, + repo_type: PlaceRepositoryType.Interface, }, ]; +const BRANCHES = ['master', 'main', 'develop', 'release/2.0']; + const DRIVER_LIST = (DISCOVERY_DATA as Record[]).map( (driver) => driver.id, ); +const DAY = 24 * 60 * 60 * 1000; + +/** Commits of every repository and branch, newest first */ const COMMIT_LIST = [ - { - commit: generateID(6, '1234567890abcdef'.split('')), - date: subMinutes( - Date.now(), - Math.floor(Math.random() * 30 * 24 * 60), - ).valueOf(), - author: 'alex@place.tech', - subject: 'feat(drivers): cleanup drivers', - }, - { - commit: generateID(6, '1234567890abcdef'.split('')), - date: subMinutes( - Date.now(), - Math.floor(Math.random() * 30 * 24 * 60), - ).valueOf(), - author: 'alex@place.tech', - subject: 'chore(readme): update readme', - }, - { - commit: generateID(6, '1234567890abcdef'.split('')), - date: subMinutes( - Date.now(), - Math.floor(Math.random() * 30 * 24 * 60), - ).valueOf(), - author: 'alex@place.tech', - subject: 'refactor(drivers): cleanup lighting driver', - }, - { - commit: generateID(6, '1234567890abcdef'.split('')), - date: subMinutes( - Date.now(), - Math.floor(Math.random() * 30 * 24 * 60), - ).valueOf(), - author: 'alex@place.tech', - subject: 'test(drivers): update test coverage', - }, -]; + 'feat(drivers): cleanup drivers', + 'chore(readme): update readme', + 'refactor(drivers): cleanup lighting driver', + 'test(drivers): update test coverage', +].map((subject, idx) => ({ + commit: generateID(6, '1234567890abcdef'.split('')), + date: new Date(Date.now() - (idx + 1) * 3 * DAY).toISOString(), + author: 'dev@place.tech', + subject, +})); -COMMIT_LIST.sort((a, b) => b.date - a.date); +/** HTML files of an interface repository, for the signage plugin import */ +const INTERFACE_FILES = ['weather/index.html', 'clock/index.html']; -/** Add GET for show */ +/** Names of the interface repositories. Registered before `repositories/:id` */ registerMockEndpoint({ path: `${API}/repositories/interfaces`, - metadata: REPO_DATA, method: 'GET', - callback: (_) => - REPO_DATA.filter( - (repo) => repo.type === PlaceRepositoryType.Interface, - ).map((repo) => repo.name), -} as MockHttpRequestHandler); + callback: () => + endpointData(`${API}/repositories`) + .filter((repo) => repo.repo_type === PlaceRepositoryType.Interface) + .map((repo) => repo.name), +}); -/** Add basic API handlers for systems */ -generateBasicHandlers(`${API}/repositories`, REPO_DATA, FILTER_FN); +/** Details of a repository that is not added yet */ +registerMockEndpoint({ + path: `${API}/repositories/remote_branches`, + method: 'GET', + callback: () => BRANCHES, +}); -/** Add handlers for getting respository drivers */ registerMockEndpoint({ - path: `${API}/repositories/:id/drivers`, - metadata: [], + path: `${API}/repositories/remote_default_branch`, method: 'GET', - callback: (event) => { - if (event.route_params.id) { - return DRIVER_LIST; - } - throw { status: 404, message: 'System not found' }; - }, -} as MockHttpRequestHandler); + callback: () => 'master', +}); -/** Add handlers for getting respository driver's commits */ registerMockEndpoint({ - path: `${API}/repositories/:id/commits`, - metadata: [], + path: `${API}/repositories/remote_commits`, method: 'GET', - callback: (_event) => { - if (_event.route_params.id) { - return COMMIT_LIST; - } - throw { status: 404, message: 'System not found' }; - }, -} as MockHttpRequestHandler); + callback: () => COMMIT_LIST, +}); + +/** Add basic API handlers for repositories */ +generateBasicHandlers(`${API}/repositories`, REPO_DATA, { + filter: nameFilter, + id_prefix: 'repo-', +}); + +/** Find a repository, or fail with a 404 */ +function findRepo(id: string) { + return ( + endpointData(`${API}/repositories`).find((repo) => repo.id === id) || + notFound('Repository') + ); +} + +/** Register a GET handler for a detail of a repository */ +function repoDetail( + name: string, + value: (repo: Record) => unknown, +) { + registerMockEndpoint({ + path: `${API}/repositories/:id/${name}`, + method: 'GET', + callback: (event) => value(findRepo(event.route_params.id)), + }); +} + +repoDetail('drivers', () => DRIVER_LIST); +repoDetail('commits', () => COMMIT_LIST); +repoDetail('branches', () => BRANCHES); +repoDetail('default_branch', (repo) => repo.branch || 'master'); +repoDetail('files', (repo) => + repo.repo_type === PlaceRepositoryType.Interface ? INTERFACE_FILES : [], +); -/** Add handlers for getting respository driver's details */ registerMockEndpoint({ path: `${API}/repositories/:id/details`, - metadata: [], method: 'GET', callback: (event) => { - if (event.route_params.id) { - return DISCOVERY_DATA.find( - (driver) => driver.id === event.query_params.driver, - ); - } - throw { status: 404, message: 'System not found' }; + findRepo(event.route_params.id); + const driver = DISCOVERY_DATA.find( + ({ id }) => id === event.query_params.driver, + ); + if (!driver) return notFound('Driver'); + // The API sends the default settings as a JSON string + return { + ...driver, + default_settings: JSON.stringify(driver.settings || {}), + }; + }, +}); + +/** Pull the latest commit. The mock is always up to date */ +registerMockEndpoint({ + path: `${API}/repositories/:id/pull`, + method: 'POST', + callback: (event) => { + findRepo(event.route_params.id); + const commit_hash = COMMIT_LIST[0].commit; + updateItem(`${API}/repositories`, event.route_params.id, { + commit_hash, + }); + return { commit_hash }; }, -} as MockHttpRequestHandler); +}); diff --git a/src/app/mocks/backend/settings.mock.ts b/src/app/mocks/backend/settings.mock.ts index 2dd5614ca..28c5897ff 100644 --- a/src/app/mocks/backend/settings.mock.ts +++ b/src/app/mocks/backend/settings.mock.ts @@ -1,68 +1,72 @@ +import { EncryptionLevel, registerMockEndpoint } from '@placeos/ts-client'; import { HashMap } from '../../common/types'; import { API, + createMockStore, + endpointData, generateBasicHandlers, - generateID, - listenToHandlerChanges, + nameFilter, } from '../common.mock'; -import { EncryptionLevel } from '@placeos/ts-client'; +/** Most old versions kept in the settings history */ +const HISTORY_LIMIT = 200; -const FILTER_FN = (item: Record, q: HashMap) => { - if (!q || Object.keys(q).length <= 0) { - return true; - } - let match = true; - if (q.q) { - match = - match && - `${item.name || ''}` - .toLowerCase() - .indexOf(((q.q as string) || '').toLowerCase()) >= 0; - } - if (q.parent_id) { - match = match && item.parent_id === q.parent_id; - } - return match; -}; +/** Matches `q` against the name and `parent_id` (a comma list) */ +const FILTER_FN = (item: Record, q: HashMap) => + nameFilter(item, q) && + (!q.parent_id || `${q.parent_id}`.split(',').includes(`${item.parent_id}`)); -const SETTINGS_DATA: Record[] = []; +/** Settings of the seed systems, modules, zones and drivers */ +const SETTINGS_DATA = ['systems', 'modules', 'zones', 'drivers'] + .flatMap((type) => endpointData(`${API}/${type}`)) + .filter( + (item) => + typeof item.settings === 'string' || + Object.keys(item.settings || {}).length, + ) + .map((item) => ({ + id: `setting-${item.id}`, + parent_id: item.id, + encryption_level: EncryptionLevel.None, + settings_string: + typeof item.settings === 'string' + ? item.settings + : JSON.stringify(item.settings), + keys: Object.keys( + typeof item.settings === 'object' ? item.settings : {}, + ), + })); -const handle_items_fn = (list: Record[]) => { - list.forEach((item) => { - if ( - item.settings && - !SETTINGS_DATA.find((s) => s.parent_id === item.id) - ) { - SETTINGS_DATA.push({ - id: `setting-${generateID()}`, - parent_id: item.id, - encryption_level: EncryptionLevel.None, - settings_string: - item.settings instanceof Object - ? JSON.stringify(item.settings) - : item.settings, - }); - } - }); -}; +type MockSetting = (typeof SETTINGS_DATA)[number]; -let changes = listenToHandlerChanges(`${API}/systems`); -if (changes) { - changes.subscribe(handle_items_fn); -} -changes = listenToHandlerChanges(`${API}/modules`); -if (changes) { - changes.subscribe(handle_items_fn); -} -changes = listenToHandlerChanges(`${API}/zones`); -if (changes) { - changes.subscribe(handle_items_fn); -} -changes = listenToHandlerChanges(`${API}/drivers`); -if (changes) { - changes.subscribe(handle_items_fn); -} +const settings = generateBasicHandlers( + `${API}/settings`, + SETTINGS_DATA, + { + filter: FILTER_FN, + id_prefix: 'setting-', + }, +); + +/** Old versions of settings, newest first */ +const history = createMockStore('settings_history', []); + +/** Keep the old version of each changed setting */ +let previous = settings(); +settings.subscribe((list) => { + const changed = previous.filter((old) => { + const item = list.find(({ id }) => id === old.id); + return item && item.settings_string !== old.settings_string; + }); + previous = list; + if (changed.length) { + history.set([...changed, ...history()].slice(0, HISTORY_LIMIT)); + } +}); -/** Add basic API handlers for systems */ -generateBasicHandlers(`${API}/settings`, SETTINGS_DATA, FILTER_FN); +registerMockEndpoint({ + path: `${API}/settings/:id/history`, + method: 'GET', + callback: (event) => + history().filter(({ id }) => id === event.route_params.id), +}); diff --git a/src/app/mocks/backend/staff-api.mock.ts b/src/app/mocks/backend/staff-api.mock.ts index 71e9dffb9..0d78e46dd 100644 --- a/src/app/mocks/backend/staff-api.mock.ts +++ b/src/app/mocks/backend/staff-api.mock.ts @@ -1,19 +1,17 @@ -import { - MockHttpRequestHandler, - registerMockEndpoint, -} from '@placeos/ts-client'; +import { registerMockEndpoint } from '@placeos/ts-client'; import { HashMap } from '../../common/types'; import { DOMAIN, - generateID, - loadFromSession, - saveToSession, + STAFF_API, + endpointData, + generateBasicHandlers, + nameFilter, + updateItem, } from '../common.mock'; -const STAFF_API = '/api/staff/v1'; +// ============ TENANTS ============ -/** Default tenant data */ -const DEFAULT_TENANTS = [ +const TENANT_DATA = [ { id: 'tenant-default', name: 'Default Tenant', @@ -23,175 +21,108 @@ const DEFAULT_TENANTS = [ booking_limits: {}, early_checkin: 30, secret_expiry: null, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, + created_at: 1709283600, + updated_at: 1709283600, }, ]; -/** In-memory storage with session persistence */ -const TENANTS: Record[] = loadFromSession( - 'tenants', - DEFAULT_TENANTS, -); +/** Matches `q` against the name and `domain` against the tenant */ +const TENANT_FILTER = (item: Record, q: HashMap) => + nameFilter(item, q) && (!q.domain || item.domain === q.domain); -const createFilter = (items: Record[]) => (q: HashMap) => { - if (!q || Object.keys(q).length <= 0) { - return items; - } - return items.filter((item) => { - let match = true; - if (q.domain) { - match = match && item.domain === q.domain; - } - if (q.q) { - match = - match && - `${item.name || ''}` - .toLowerCase() - .indexOf(((q.q as string) || '').toLowerCase()) >= 0; - } - return match; - }); -}; +generateBasicHandlers(`${STAFF_API}/tenants`, TENANT_DATA, { + filter: TENANT_FILTER, + id_prefix: 'tenant-', +}); -// ============ TENANTS ============ +/** Find a tenant, or fail with a 404 */ +function findTenant(id: string) { + const tenant = endpointData(`${STAFF_API}/tenants`).find( + (item) => item.id === id, + ); + if (!tenant) throw { status: 404, message: 'Tenant not found' }; + return tenant; +} -/** GET tenants list */ registerMockEndpoint({ - path: `${STAFF_API}/tenants`, - metadata: [], + path: `${STAFF_API}/tenants/:id/limits`, method: 'GET', - callback: (event) => createFilter(TENANTS)(event.query_params), -} as MockHttpRequestHandler); + callback: (event) => findTenant(event.route_params.id).booking_limits || {}, +}); -/** GET tenant by ID */ registerMockEndpoint({ - path: `${STAFF_API}/tenants/:id`, - metadata: [], - method: 'GET', - callback: (event) => { - const tenant = TENANTS.find((t) => t.id === event.route_params.id); - if (tenant) return tenant; - throw { status: 404, message: 'Tenant not found' }; - }, -} as MockHttpRequestHandler); - -/** POST create tenant */ -registerMockEndpoint({ - path: `${STAFF_API}/tenants`, - metadata: [], - method: 'POST', - callback: (event) => { - const tenant = { - id: `tenant-${generateID()}`, - ...event.body, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, - }; - TENANTS.push(tenant); - saveToSession('tenants', TENANTS); - return tenant; - }, -} as MockHttpRequestHandler); - -/** PUT/PATCH update tenant */ -registerMockEndpoint({ - path: `${STAFF_API}/tenants/:id`, - metadata: [], + path: `${STAFF_API}/tenants/:id/limits`, method: 'PUT', - callback: (event) => { - const index = TENANTS.findIndex((t) => t.id === event.route_params.id); - if (index >= 0) { - TENANTS[index] = { - ...TENANTS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('tenants', TENANTS); - return TENANTS[index]; - } - throw { status: 404, message: 'Tenant not found' }; - }, -} as MockHttpRequestHandler); + callback: (event) => + updateItem( + `${STAFF_API}/tenants`, + findTenant(event.route_params.id).id, + { + booking_limits: event.body, + }, + ).booking_limits, +}); -registerMockEndpoint({ - path: `${STAFF_API}/tenants/:id`, - metadata: [], - method: 'PATCH', - callback: (event) => { - const index = TENANTS.findIndex((t) => t.id === event.route_params.id); - if (index >= 0) { - TENANTS[index] = { - ...TENANTS[index], - ...event.body, - updated_at: Date.now() / 1000, - }; - saveToSession('tenants', TENANTS); - return TENANTS[index]; - } - throw { status: 404, message: 'Tenant not found' }; - }, -} as MockHttpRequestHandler); +// ============ DIRECTORY ============ -/** DELETE tenant */ -registerMockEndpoint({ - path: `${STAFF_API}/tenants/:id`, - metadata: [], - method: 'DELETE', - callback: (event) => { - const index = TENANTS.findIndex((t) => t.id === event.route_params.id); - if (index >= 0) { - TENANTS.splice(index, 1); - saveToSession('tenants', TENANTS); - return {}; - } - throw { status: 404, message: 'Tenant not found' }; - }, -} as MockHttpRequestHandler); +/** Groups in the directory of the tenant */ +const DIRECTORY_GROUPS = [ + 'All Staff', + 'Facilities', + 'IT Support', + 'Reception', + 'Executive Assistants', +].map((name) => ({ + id: `directory-group-${name.toLowerCase().replace(/\W+/g, '-')}`, + name, + email: `${name.toLowerCase().replace(/\W+/g, '.')}@${DOMAIN}`, + description: `${name} directory group`, +})); -/** GET tenant booking limits */ registerMockEndpoint({ - path: `${STAFF_API}/tenants/:id/limits`, - metadata: [], + path: `${STAFF_API}/groups`, method: 'GET', - callback: (event) => { - const tenant = TENANTS.find((t) => t.id === event.route_params.id); - if (tenant) return tenant.booking_limits || {}; - throw { status: 404, message: 'Tenant not found' }; - }, -} as MockHttpRequestHandler); + callback: (event) => + DIRECTORY_GROUPS.filter((group) => + nameFilter(group, event.query_params), + ), +}); + +/** Rooms in the calendar of the tenant, for the resource import page */ +const ROOM_RESOURCES = [ + ['2.30.08 - Activity Space', 'room-2.30.08', 12], + ['Board Room', 'room-board', 20], + ['Focus Room 1', 'room-focus-1', 2], + ['Focus Room 2', 'room-focus-2', 2], +].map(([name, user, capacity]) => ({ + id: `resource-${user}`, + displayName: name, + emailAddress: `${user}@${DOMAIN}`, + capacity, + bookingType: 'standard', + isWheelChairAccessible: true, + nickname: name, + phone: '', + tags: [], +})); -/** PUT update tenant booking limits */ registerMockEndpoint({ - path: `${STAFF_API}/tenants/:id/limits`, - metadata: [], - method: 'PUT', - callback: (event) => { - const index = TENANTS.findIndex((t) => t.id === event.route_params.id); - if (index >= 0) { - TENANTS[index].booking_limits = event.body; - saveToSession('tenants', TENANTS); - return TENANTS[index].booking_limits; - } - throw { status: 404, message: 'Tenant not found' }; - }, -} as MockHttpRequestHandler); + path: `${STAFF_API}/place`, + method: 'GET', + callback: () => ROOM_RESOURCES, +}); // ============ CURRENT USER ============ -/** GET current user */ registerMockEndpoint({ path: `${STAFF_API}/users/current`, - metadata: [], method: 'GET', - callback: (_event) => { - return { - id: 'current', - name: 'Place Admin', - email: 'admin@place.tech', - sys_admin: true, - support: true, - groups: [], - }; - }, -} as MockHttpRequestHandler); + callback: () => ({ + id: 'current', + name: 'Place Admin', + email: 'admin@place.tech', + sys_admin: true, + support: true, + groups: [], + }), +}); diff --git a/src/app/mocks/backend/system-control.mock.ts b/src/app/mocks/backend/system-control.mock.ts new file mode 100644 index 000000000..99a80f923 --- /dev/null +++ b/src/app/mocks/backend/system-control.mock.ts @@ -0,0 +1,170 @@ +/** + * Module control of systems: function lists, execute, state and the + * websocket bindings. Import this file last. Its `systems/:id/:module` + * paths match any name, so they must come after the fixed paths such as + * `systems/:id/zones`. + */ +import { + MockHttpRequest, + mockSystem, + registerMockEndpoint, + registerSystem, +} from '@placeos/ts-client'; +import { + API, + MockItem, + createMockStore, + listenToHandlerChanges, + notFound, +} from '../common.mock'; +import { findSystem } from './systems.mock'; +import { TRIGGER_INSTANCES } from './triggers.mock'; + +/** Functions of every mock module. Each sets the status of the same name */ +const FUNCTIONS = { + power: { arity: 1, params: { state: ['Bool'] }, order: ['state'] }, + volume: { arity: 1, params: { level: ['Int32', 50] }, order: ['level'] }, + mute: { arity: 1, params: { state: ['Bool', true] }, order: ['state'] }, +}; + +/** Status variables of a module */ +type State = Record; + +/** Status that functions changed, keyed by `system_id|Class_index` */ +const changed_state = createMockStore>( + 'module_state', + {}, +); + +interface SystemModule { + /** Binding name, e.g. `Display_1` */ + key: string; + name: string; + index: number; + module: MockItem; +} + +/** Modules of a system, named like `calculateModuleIndex` in the app */ +function systemModules(system: MockItem): SystemModule[] { + const modules = listenToHandlerChanges(`${API}/modules`)?.() || []; + const counts: Record = {}; + return ((system.modules as string[]) || []).flatMap((id) => { + const module = modules.find((mod) => mod.id === id); + if (!module) return []; + const name = `${module.custom_name || module.name || 'Blank'}`; + const index = (counts[name] = (counts[name] || 0) + 1); + return [{ key: `${name}_${index}`, name, index, module }]; + }); +} + +/** Find a module of a system from a binding name, e.g. `Display_1` */ +function findModule(event: MockHttpRequest) { + const system = findSystem(event.route_params.id); + const key = decodeURIComponent(event.route_params.module); + const found = systemModules(system).find((mod) => mod.key === key); + return found ? { system, found } : notFound('Module'); +} + +/** Current status of a system module */ +function stateOf(system_id: string, { key, module }: SystemModule): State { + return { + connected: module.connected ?? true, + running: module.running ?? false, + power: false, + volume: 50, + mute: false, + ...changed_state()[`${system_id}|${key}`], + }; +} + +/** Run a module function. Its status changes to the first argument */ +function execute( + system_id: string, + mod: SystemModule, + method: string, + args: unknown[], +) { + if (!(method in FUNCTIONS)) return notFound('Function'); + const value = args[0] ?? null; + const id = `${system_id}|${mod.key}`; + changed_state.set({ + ...changed_state(), + [id]: { ...changed_state()[id], [method]: value }, + }); + // Show the change on open websocket bindings + const binding = mockSystem(system_id)?.[mod.name]?.[mod.index - 1]; + if (binding) binding[method] = value; + return value; +} + +/** Register the websocket mock of every system, so bindings get values */ +function registerRealtime() { + const systems = listenToHandlerChanges(`${API}/systems`)?.() || []; + for (const system of systems) { + const classes: Record = {}; + for (const mod of systemModules(system)) { + const methods = Object.fromEntries( + Object.keys(FUNCTIONS).map((name) => [ + name, + (...args: unknown[]) => execute(system.id, mod, name, args), + ]), + ); + (classes[mod.name] ||= []).push({ + ...stateOf(system.id, mod), + ...methods, + }); + } + // State of each trigger of the system, keyed by trigger instance ID + const triggers = TRIGGER_INSTANCES().filter( + ({ control_system_id }) => control_system_id === system.id, + ); + classes['_TRIGGER_'] = [ + Object.fromEntries( + triggers.map((trigger) => [ + trigger.id, + { + triggered: !!trigger.triggered, + trigger_count: trigger.trigger_count || 0, + action_errors: 0, + comparison_errors: 0, + conditions: {}, + }, + ]), + ), + ]; + registerSystem(system.id, classes); + } +} +listenToHandlerChanges(`${API}/systems`)?.subscribe(registerRealtime); +listenToHandlerChanges(`${API}/modules`)?.subscribe(registerRealtime); +TRIGGER_INSTANCES.subscribe(registerRealtime); + +registerMockEndpoint({ + path: `${API}/systems/:id/functions/:module`, + method: 'GET', + callback: (event) => { + findModule(event); + return FUNCTIONS; + }, +}); + +registerMockEndpoint({ + path: `${API}/systems/:id/:module`, + method: 'GET', + callback: (event) => { + const { system, found } = findModule(event); + return stateOf(system.id, found); + }, +}); + +registerMockEndpoint({ + path: `${API}/systems/:id/:module/:method`, + method: 'POST', + callback: (event) => { + const { system, found } = findModule(event); + const args = Array.isArray(event.body) + ? event.body + : Object.values(event.body || {}); + return execute(system.id, found, event.route_params.method, args); + }, +}); diff --git a/src/app/mocks/backend/systems.mock.ts b/src/app/mocks/backend/systems.mock.ts index 1c6b7f079..9c2626dbc 100644 --- a/src/app/mocks/backend/systems.mock.ts +++ b/src/app/mocks/backend/systems.mock.ts @@ -1,11 +1,16 @@ +import { registerMockEndpoint } from '@placeos/ts-client'; import { HashMap } from '../../common/types'; -import { API, endpointData, generateBasicHandlers } from '../common.mock'; -import { SYSTEMS as SYSTEM_DATA } from '../data/systems'; - import { - MockHttpRequestHandler, - registerMockEndpoint, -} from '@placeos/ts-client'; + API, + endpointData, + generateBasicHandlers, + generateID, + notFound, + now, + updateItem, +} from '../common.mock'; +import { SYSTEMS as SYSTEM_DATA } from '../data/systems'; +import { TRIGGER_INSTANCES, expandInstance } from './triggers.mock'; const FILTER_FN = (item: Record, q: HashMap) => { if (!q || Object.keys(q).length <= 0) { @@ -29,151 +34,211 @@ const FILTER_FN = (item: Record, q: HashMap) => { return match; }; +/** Systems whose email is in the `in` list. Registered before `systems/:id` */ +registerMockEndpoint({ + path: `${API}/systems/with_emails`, + method: 'GET', + callback: (event) => { + const emails = `${event.query_params.in || ''}` + .toLowerCase() + .split(','); + return endpointData(`${API}/systems`).filter((sys) => + emails.includes(`${sys.email || ''}`.toLowerCase()), + ); + }, +}); + /** Add basic API handlers for systems */ -generateBasicHandlers(`${API}/systems`, SYSTEM_DATA, FILTER_FN); +generateBasicHandlers(`${API}/systems`, SYSTEM_DATA, { + filter: FILTER_FN, + id_prefix: 'sys-', +}); + +/** Find a system, or fail with a 404 */ +export function findSystem(id: string) { + return ( + endpointData(`${API}/systems`).find((sys) => sys.id === id) || + notFound('System') + ); +} -/** Add handlers for getting system's zones */ registerMockEndpoint({ path: `${API}/systems/:id/zones`, - metadata: [], method: 'GET', callback: (event) => { - if (event.route_params.id) { - const system = endpointData(`${API}/systems`).find( - (sys) => sys.id === event.route_params.id, - ); - if (system) { - const zones = endpointData(`${API}/zones`); - return zones.filter((item) => system.zones.includes(item.id)); - } - } - throw { status: 404, message: 'System not found' }; + const system = findSystem(event.route_params.id); + return endpointData(`${API}/zones`).filter((zone) => + system.zones.includes(zone.id), + ); }, -} as MockHttpRequestHandler); +}); -/** Add handlers for getting system's modules */ registerMockEndpoint({ path: `${API}/systems/:id/modules`, - metadata: [], method: 'GET', callback: (event) => { - if (event.route_params.id) { - const system = endpointData(`${API}/systems`).find( - (sys) => sys.id === event.route_params.id, - ); - if (system) { - const modules = endpointData(`${API}/modules`); - return modules.filter((item) => - system.modules.includes(item.id), - ); - } - } - throw { status: 404, message: 'System not found' }; + const system = findSystem(event.route_params.id); + return endpointData(`${API}/modules`).filter((mod) => + system.modules.includes(mod.id), + ); }, -} as MockHttpRequestHandler); +}); -/** Add handlers for getting system's triggers */ +/** Add a module to the system */ registerMockEndpoint({ - path: `${API}/systems/:id/triggers`, - metadata: [], - method: 'GET', - callback: (_event) => { - if (_event.route_params.id) { - return []; - } - throw { status: 404, message: 'System not found' }; + path: `${API}/systems/:id/module/:module_id`, + method: 'PUT', + callback: (event) => { + const { id, module_id } = event.route_params; + const system = findSystem(id); + if (system.modules.includes(module_id)) return system; + return updateItem(`${API}/systems`, id, { + modules: [...system.modules, module_id], + }); }, -} as MockHttpRequestHandler); +}); -/** Add handlers for getting system's inherited settings */ +/** Remove a module from the system */ registerMockEndpoint({ - path: `${API}/systems/:id/settings`, - metadata: [], - method: 'GET', + path: `${API}/systems/:id/module/:module_id`, + method: 'DELETE', callback: (event) => { - if (event.route_params.id) { - const settings = endpointData(`${API}/settings`).filter( - (sys) => sys.id === event.route_params.id, - ); - return settings.reduce((map, item) => ({ - ...map, - ...JSON.parse(item.settings_string), - })); - } - throw { status: 404, message: 'System not found' }; + const { id, module_id } = event.route_params; + const system = findSystem(id); + return updateItem(`${API}/systems`, id, { + modules: system.modules.filter((mod: string) => mod !== module_id), + }); }, -} as MockHttpRequestHandler); +}); + +// ============ TRIGGERS ============ -/** Add handler for starting a system */ registerMockEndpoint({ - path: `${API}/systems/:id/start`, - metadata: [], - method: 'POST', + path: `${API}/systems/:id/triggers`, + method: 'GET', callback: (event) => { - if (event.route_params.id) { - const system = endpointData(`${API}/systems`).find( - (sys) => sys.id === event.route_params.id, - ); - if (system) { - system.running = true; - return system; - } - } - throw { status: 404, message: 'System not found' }; + const { id } = findSystem(event.route_params.id); + return TRIGGER_INSTANCES() + .filter(({ control_system_id }) => control_system_id === id) + .map(expandInstance); }, -} as MockHttpRequestHandler); +}); -/** Add handler for stopping a system */ registerMockEndpoint({ - path: `${API}/systems/:id/stop`, - metadata: [], + path: `${API}/systems/:id/triggers`, method: 'POST', callback: (event) => { - if (event.route_params.id) { - const system = endpointData(`${API}/systems`).find( - (sys) => sys.id === event.route_params.id, - ); - if (system) { - system.running = false; - return system; - } - } - throw { status: 404, message: 'System not found' }; + const { id } = findSystem(event.route_params.id); + const instance = { + enabled: true, + important: false, + triggered: false, + trigger_count: 0, + exec_enabled: false, + webhook_secret: generateID(32), + ...event.body, + id: `inst-${generateID()}`, + control_system_id: id, + created_at: now(), + updated_at: now(), + }; + TRIGGER_INSTANCES.set([...TRIGGER_INSTANCES(), instance]); + return expandInstance(instance); }, -} as MockHttpRequestHandler); +}); + +/** Find a trigger of a system, or fail with a 404 */ +function findInstance(system_id: string, id: string) { + return ( + TRIGGER_INSTANCES().find( + (item) => item.id === id && item.control_system_id === system_id, + ) || notFound('Trigger') + ); +} + +for (const method of ['PUT', 'PATCH'] as const) { + registerMockEndpoint({ + path: `${API}/systems/:id/triggers/:trigger_id`, + method, + callback: (event) => { + const { id, trigger_id } = event.route_params; + const old = findInstance(id, trigger_id); + const { enabled, important, exec_enabled } = { + ...old, + ...event.body, + }; + const instance = { + ...old, + enabled, + important, + exec_enabled, + updated_at: now(), + }; + TRIGGER_INSTANCES.set( + TRIGGER_INSTANCES().map((item) => + item === old ? instance : item, + ), + ); + return expandInstance(instance); + }, + }); +} -/** Add handler for executing module methods on system */ registerMockEndpoint({ - path: `${API}/systems/:id/exec/:module/:index/:method`, - metadata: [], - method: 'POST', - callback: (_event) => { - return { result: 'ok' }; + path: `${API}/systems/:id/triggers/:trigger_id`, + method: 'DELETE', + callback: (event) => { + const { id, trigger_id } = event.route_params; + const old = findInstance(id, trigger_id); + TRIGGER_INSTANCES.set( + TRIGGER_INSTANCES().filter((item) => item !== old), + ); + return null; }, -} as MockHttpRequestHandler); +}); + +// ============ SETTINGS AND CONTROL ============ -/** Add handler for system functions list */ +/** Settings of the system and of its zones, modules and drivers */ registerMockEndpoint({ - path: `${API}/systems/:id/funcs/:module/:index`, - metadata: [], + path: `${API}/systems/:id/settings`, method: 'GET', - callback: (_event) => { - return { - functions: { - power: { arity: 1, params: ['state'] }, - volume: { arity: 1, params: ['level'] }, - mute: { arity: 1, params: ['state'] }, - }, - }; + callback: (event) => { + const system = findSystem(event.route_params.id); + const drivers = endpointData(`${API}/modules`) + .filter((mod) => system.modules.includes(mod.id)) + .map((mod) => mod.driver_id); + const parents = [ + system.id, + ...system.zones, + ...system.modules, + ...drivers, + ]; + return endpointData(`${API}/settings`).filter((setting) => + parents.includes(setting.parent_id), + ); }, -} as MockHttpRequestHandler); +}); + +/** Start or stop every module of the system */ +function setRunning(system_id: string, running: boolean) { + const system = findSystem(system_id); + for (const id of system.modules) { + if (endpointData(`${API}/modules`).some((mod) => mod.id === id)) { + updateItem(`${API}/modules`, id, { running }); + } + } + return null; +} -/** Add handler for counting systems */ registerMockEndpoint({ - path: `${API}/systems/count`, - metadata: [], - method: 'GET', - callback: (_event) => { - return { count: endpointData(`${API}/systems`).length }; - }, -} as MockHttpRequestHandler); + path: `${API}/systems/:id/start`, + method: 'POST', + callback: (event) => setRunning(event.route_params.id, true), +}); + +registerMockEndpoint({ + path: `${API}/systems/:id/stop`, + method: 'POST', + callback: (event) => setRunning(event.route_params.id, false), +}); diff --git a/src/app/mocks/backend/triggers.mock.ts b/src/app/mocks/backend/triggers.mock.ts index 663808de2..7ed560f41 100644 --- a/src/app/mocks/backend/triggers.mock.ts +++ b/src/app/mocks/backend/triggers.mock.ts @@ -1,22 +1,112 @@ -import { HashMap } from '../../common/types'; -import { API, generateBasicHandlers } from '../common.mock'; +import { registerMockEndpoint } from '@placeos/ts-client'; +import { + API, + MockItem, + createMockStore, + endpointData, + generateBasicHandlers, + nameFilter, +} from '../common.mock'; -const FILTER_FN = (item: Record, q: HashMap) => { - if (!q || Object.keys(q).length <= 0) { - return true; - } - let match = true; - if (q.q) { - match = - match && - `${item.name || ''}` - .toLowerCase() - .indexOf(((q.q as string) || '').toLowerCase()) >= 0; - } - return match; -}; +const SEED_TIME = 1709283600; -const TRIGGER_DATA: Record[] = []; +const TRIGGER_DATA = [ + { + id: 'trigger-room-occupied', + name: 'Room Occupied', + description: 'Turns the lights on when people are in the room', + conditions: { + comparisons: [ + { + left: { mod: 'Sensor_1', status: 'people_count', keys: [] }, + operator: 'greater_than', + right: 0, + }, + ], + time_dependents: [], + }, + actions: { + functions: [ + { mod: 'Lighting_1', method: 'power', args: { state: true } }, + ], + mailers: [], + }, + debounce_period: 0, + important: false, + enable_webhook: false, + supported_methods: ['POST'], + created_at: SEED_TIME, + updated_at: SEED_TIME, + }, + { + id: 'trigger-after-hours', + name: 'After Hours', + description: 'Powers off displays every evening', + conditions: { + comparisons: [], + time_dependents: [ + { type: 'cron', cron: '0 19 * * 1-5', timezone: 'UTC' }, + ], + }, + actions: { + functions: [ + { mod: 'Display_1', method: 'power', args: { state: false } }, + ], + mailers: [], + }, + debounce_period: 0, + important: true, + enable_webhook: true, + supported_methods: ['POST'], + created_at: SEED_TIME, + updated_at: SEED_TIME, + }, +]; -/** Add basic API handlers for systems */ -generateBasicHandlers(`${API}/triggers`, TRIGGER_DATA, FILTER_FN); +generateBasicHandlers(`${API}/triggers`, TRIGGER_DATA, { + filter: nameFilter, + id_prefix: 'trigger-', +}); + +/** Trigger added to a system. Has the ID of the trigger and the system */ +export interface MockTriggerInstance extends MockItem { + trigger_id: string; + control_system_id: string; +} + +/** Triggers added to systems */ +export const TRIGGER_INSTANCES = createMockStore( + 'trigger_instances', + [ + { + id: 'inst-room-occupied', + trigger_id: 'trigger-room-occupied', + control_system_id: 'sys-QjJvCH7_dA', + enabled: true, + important: false, + triggered: false, + trigger_count: 3, + exec_enabled: true, + webhook_secret: 'mock-secret', + created_at: SEED_TIME, + updated_at: SEED_TIME, + }, + ], +); + +/** Instance with the details of its trigger, like the API returns */ +export function expandInstance(instance: MockTriggerInstance) { + const trigger = endpointData(`${API}/triggers`).find( + ({ id }) => id === instance.trigger_id, + ); + return { ...trigger, ...instance }; +} + +registerMockEndpoint({ + path: `${API}/triggers/:id/instances`, + method: 'GET', + callback: (event) => + TRIGGER_INSTANCES() + .filter(({ trigger_id }) => trigger_id === event.route_params.id) + .map(expandInstance), +}); diff --git a/src/app/mocks/backend/users.mock.ts b/src/app/mocks/backend/users.mock.ts index 050611bbf..bbe50594a 100644 --- a/src/app/mocks/backend/users.mock.ts +++ b/src/app/mocks/backend/users.mock.ts @@ -1,5 +1,6 @@ +import { registerMockEndpoint } from '@placeos/ts-client'; import { HashMap } from '../../common/types'; -import { API, generateBasicHandlers, generateID } from '../common.mock'; +import { API, generateBasicHandlers, updateItem } from '../common.mock'; import { AUTHORITY_ID } from './domains.mock'; const FILTER_FN = (item: Record, q: HashMap) => { @@ -32,7 +33,8 @@ function withNames(user: MockUser): MockUser { return { ...user, first_name, last_name: rest.join(' ') }; } -const PREDFINED_USERS = [ +/** Seed users. Jeremy West is a support user, Stephen von Takach an admin */ +const USER_DATA = [ 'Alex Sorafumo', 'Jonathan McFarlane', 'Stephen von Takach', @@ -46,31 +48,16 @@ const PREDFINED_USERS = [ name, email: `${name.split(' ').join('.')}@place.tech`, authority_id: AUTHORITY_ID, - support: Math.floor(Math.random() * 999_999) % 10 === 0, - sys_admin: Math.floor(Math.random() * 999_999) % 10 === 0, + support: name === 'Jeremy West', + sys_admin: name === 'Stephen von Takach', })); -const USER_DATA = Array(0) - .fill(0) - .map((_, idx) => { - const name = `No. ${idx}`; - return { - id: `user-${generateID()}`, - name, - email: `${name.split(' ').join('.')}@place.tech`, - authority_id: AUTHORITY_ID, - support: Math.floor(Math.random() * 999_999) % 10 === 0, - sys_admin: Math.floor(Math.random() * 999_999) % 10 === 0, - }; - }) - .concat(PREDFINED_USERS); - const CURRENT_USER = { id: `current`, name: 'Place Admin', email: `admin@place.tech`, authority_id: AUTHORITY_ID, - support: Math.floor(Math.random() * 999_999) % 10 === 0, + support: false, sys_admin: true, }; @@ -78,6 +65,13 @@ const CURRENT_USER = { generateBasicHandlers( `${API}/users`, [...USER_DATA, CURRENT_USER].map(withNames), - FILTER_FN, - withNames, + { filter: FILTER_FN, prepare: withNames, id_prefix: 'user-' }, ); + +/** Restore a deleted user */ +registerMockEndpoint({ + path: `${API}/users/:id/revive`, + method: 'POST', + callback: (event) => + updateItem(`${API}/users`, event.route_params.id, { deleted: false }), +}); diff --git a/src/app/mocks/backend/zones.mock.ts b/src/app/mocks/backend/zones.mock.ts index 4a674b4ad..512e19fba 100644 --- a/src/app/mocks/backend/zones.mock.ts +++ b/src/app/mocks/backend/zones.mock.ts @@ -1,5 +1,11 @@ +import { registerMockEndpoint } from '@placeos/ts-client'; import { HashMap } from '../../common/types'; -import { API, endpointData, generateBasicHandlers } from '../common.mock'; +import { + API, + endpointData, + generateBasicHandlers, + notFound, +} from '../common.mock'; import { ZONES as ZONE_DATA } from '../data/zones'; const FILTER_FN = (item: Record, q: HashMap) => { @@ -34,5 +40,35 @@ const FILTER_FN = (item: Record, q: HashMap) => { return match; }; -/** Add basic API handlers for systems */ -generateBasicHandlers(`${API}/zones`, ZONE_DATA, FILTER_FN); +/** Tags used by the zones. Registered before `zones/:id` */ +registerMockEndpoint({ + path: `${API}/zones/tags`, + method: 'GET', + callback: () => + [ + ...new Set( + endpointData(`${API}/zones`).flatMap((zone) => zone.tags || []), + ), + ].sort(), +}); + +/** Add basic API handlers for zones */ +generateBasicHandlers(`${API}/zones`, ZONE_DATA, { + filter: FILTER_FN, + id_prefix: 'zone-', +}); + +/** Triggers added to the zone */ +registerMockEndpoint({ + path: `${API}/zones/:id/triggers`, + method: 'GET', + callback: (event) => { + const zone = + endpointData(`${API}/zones`).find( + ({ id }) => id === event.route_params.id, + ) || notFound('Zone'); + return endpointData(`${API}/triggers`).filter(({ id }) => + (zone.triggers || []).includes(id), + ); + }, +}); diff --git a/src/app/mocks/common.mock.ts b/src/app/mocks/common.mock.ts index 14a80a886..77a25a176 100644 --- a/src/app/mocks/common.mock.ts +++ b/src/app/mocks/common.mock.ts @@ -1,25 +1,28 @@ import { WritableSignal, signal } from '@angular/core'; import { HashMap } from '../common/types'; -import { - MockHttpRequestHandler, - registerMockEndpoint, -} from '@placeos/ts-client'; +import { MockHttpRequest, registerMockEndpoint } from '@placeos/ts-client'; /** Domain of the organisation */ export const DOMAIN = 'place.tech'; -/** Endpoint where the staff API is located */ +/** Endpoint where the engine API is located */ export const API = '/api/engine/v2'; +/** Endpoint where the staff API is located */ +export const STAFF_API = '/api/staff/v1'; interface MockSubscription { unsubscribe(): void; } -interface MockChangeSignal extends WritableSignal { +/** Signal that also tells listeners about each change */ +export interface MockChangeSignal extends WritableSignal { subscribe(next: (value: T) => void): MockSubscription; dispose(): void; } +/** Item with an ID, as stored by `generateBasicHandlers` */ +export type MockItem = { id: string } & Record; + // eslint-disable-next-line @typescript-eslint/no-explicit-any const ENDPOINT_SIGNALS: HashMap> = {}; @@ -57,12 +60,10 @@ const STORAGE_PREFIX = 'PLACEOS.mocks.'; * @param key Storage key (without prefix) * @param fallback Fallback data if nothing in storage */ -export function loadFromSession(key: string, fallback: T[]): T[] { +export function loadFromSession(key: string, fallback: T): T { try { const stored = sessionStorage.getItem(`${STORAGE_PREFIX}${key}`); - if (stored) { - return JSON.parse(stored); - } + if (stored) return JSON.parse(stored); } catch (e) { console.warn(`Failed to load mock data from session: ${key}`, e); } @@ -74,13 +75,27 @@ export function loadFromSession(key: string, fallback: T[]): T[] { * @param key Storage key (without prefix) * @param data Data to save */ -export function saveToSession(key: string, data: T[]): void { +export function saveToSession(key: string, data: T): void { try { sessionStorage.setItem(`${STORAGE_PREFIX}${key}`, JSON.stringify(data)); } catch (e) { console.warn(`Failed to save mock data to session: ${key}`, e); } } + +/** + * Make a signal that keeps its value in session storage. + * The seed is saved on first use, so random seed values stay the same + * after a reload. Every `set` and `update` saves the new value. + * @param key Storage key (without prefix) + * @param seed Value used when session storage has none + */ +export function createMockStore(key: string, seed: T): MockChangeSignal { + const store = createMockChangeSignal(loadFromSession(key, seed)); + store.subscribe((value) => saveToSession(key, value)); + return store; +} + /** List of available characters for IDs */ const AVAILABLE_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~'.split(''); @@ -99,11 +114,27 @@ export function generateID(length = 12, chars: string[] = AVAILABLE_CHARS) { return id; } +/** Current time in seconds, which is what the API uses for timestamps */ +export function now() { + return Math.floor(Date.now() / 1000); +} + +/** Error the handlers throw for an item that does not exist */ +export function notFound(name = 'Item'): never { + throw { status: 404, message: `${name} not found` }; +} + +/** Filter that matches `q` against the item name */ +export function nameFilter(item: Record, q: HashMap) { + if (!q?.q) return true; + return `${item.name || ''}`.toLowerCase().includes(`${q.q}`.toLowerCase()); +} + /** * Get signal for changes to data on endpoint * @param endpoint Endpoint to listen to */ -export function listenToHandlerChanges( +export function listenToHandlerChanges( endpoint: string, ): MockChangeSignal { return ENDPOINT_SIGNALS[endpoint] as MockChangeSignal; @@ -115,140 +146,137 @@ export function listenToHandlerChanges( */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export function endpointData(endpoint: string): any[] { - return ( - (ENDPOINT_SIGNALS[endpoint] ? ENDPOINT_SIGNALS[endpoint]() : null) || [] - ); + return ENDPOINT_SIGNALS[endpoint]?.() || []; } /** - * Derive a storage key from an endpoint path + * Change fields of an item made by `generateBasicHandlers` and save it + * @param endpoint Endpoint of the item + * @param id ID of the item + * @param changes Fields to change + * @returns The changed item */ -function endpointToStorageKey(endpoint: string): string { +export function updateItem( + endpoint: string, + id: string, + changes: Partial, +): T { + const store = listenToHandlerChanges(endpoint); + const list = store?.() || []; + const index = list.findIndex((item) => item.id === id); + if (index < 0) return notFound(); + const item = { ...list[index], ...changes, updated_at: now() }; + store.set(list.map((old, idx) => (idx === index ? item : old))); + return item; +} + +/** Storage key of an endpoint, e.g. `api_engine_v2_zones` */ +export function endpointToStorageKey(endpoint: string): string { return endpoint.replace(/\//g, '_').replace(/^_/, ''); } +export interface BasicHandlerOptions { + /** Selects the items for the query parameters of a request */ + filter?: FilterFn; + /** + * Fills in server-side fields of created and updated items. + * Updated items keep their old fields, so use + * `{ field: makeValue(), ...item }` for fields made only on create + */ + prepare?: (item: T) => T; + /** Prefix of new IDs, e.g. `sys-`. Defaults to `item-` */ + id_prefix?: string; +} + /** - * Function to generate basic CRUD handlers with session persistence + * Register index, show, create, update and remove handlers for an endpoint. + * Items persist in session storage under `endpointToStorageKey(endpoint)`. + * The mock router uses the first handler that matches, so register fixed + * paths such as `zones/tags` before you call this * @param endpoint API endpoint path - * @param data Initial data (used as fallback if no session data) - * @param filter Filter function for queries - * @param prepare Fills in server-side fields of created or updated items + * @param data Initial data (used when session storage has none) */ -export function generateBasicHandlers( +export function generateBasicHandlers( endpoint: string, data: T[], - filter: FilterFn = (_: T, _q: HashMap) => true, - prepare: (item: T) => T = (item) => item, + { + filter = () => true, + prepare = (item) => item, + id_prefix = 'item-', + }: BasicHandlerOptions = {}, ): MockChangeSignal { - const storage_key = endpointToStorageKey(endpoint); - - if (ENDPOINT_SIGNALS[endpoint]) { - ENDPOINT_SIGNALS[endpoint].dispose(); - delete ENDPOINT_SIGNALS[endpoint]; - } - - // Load from session storage if available, otherwise use provided data - const initial_data = loadFromSession(storage_key, data); - ENDPOINT_SIGNALS[endpoint] = createMockChangeSignal(initial_data); + ENDPOINT_SIGNALS[endpoint]?.dispose(); + const store = createMockStore(endpointToStorageKey(endpoint), data); + ENDPOINT_SIGNALS[endpoint] = store; + type Item = T & MockItem; + const list = () => store() as Item[]; + const indexOf = (event: MockHttpRequest) => { + const index = list().findIndex((i) => i.id === event.route_params.id); + return index >= 0 ? index : notFound(); + }; - /** Add GET for index */ registerMockEndpoint({ - path: `${endpoint}`, - metadata: data, + path: endpoint, method: 'GET', - callback: (event) => { - const list = [...(ENDPOINT_SIGNALS[endpoint]() || [])]; - list.sort((a, b) => (a.name || '').localeCompare(b.name || '')); - return list.filter((item) => filter(item, event.query_params)); - }, - } as MockHttpRequestHandler); + callback: (event) => + [...list()] + .sort((a, b) => + `${a.name || ''}`.localeCompare(`${b.name || ''}`), + ) + .filter((item) => filter(item, event.query_params)), + }); - /** Add GET for show */ registerMockEndpoint({ path: `${endpoint}/:id`, - metadata: data, method: 'GET', - callback: (event) => { - const list = ENDPOINT_SIGNALS[endpoint]() || []; - return list.find( - (item) => - item.id === event.route_params.id && - filter(item, event.query_params), - ); - }, - } as MockHttpRequestHandler); + callback: (event) => list()[indexOf(event)], + }); - /** Add POST for item */ registerMockEndpoint({ - path: `${endpoint}`, - metadata: data, + path: endpoint, method: 'POST', callback: (event) => { const item = prepare({ ...event.body, - id: `item-${generateID()}`, - created_at: Date.now() / 1000, - updated_at: Date.now() / 1000, + id: `${id_prefix}${generateID()}`, + created_at: now(), + updated_at: now(), }); - const list = [...(ENDPOINT_SIGNALS[endpoint]() || [])]; - list.push(item); - ENDPOINT_SIGNALS[endpoint].set(list); - saveToSession(storage_key, list); + store.set([...store(), item]); return item; }, - } as MockHttpRequestHandler); + }); - /** Add PATCH/PUT for item */ - const action = { - path: `${endpoint}/:id`, - metadata: data, - method: 'PATCH', - callback: (event) => { - const item = event.body; - const list = [...(ENDPOINT_SIGNALS[endpoint]() || [])]; - const index = list.findIndex( - (an_item) => an_item.id === event.route_params.id, - ); - if (index >= 0) { - const old_item = list[index]; - const updated_item = prepare({ - ...old_item, - ...item, - updated_at: Date.now() / 1000, + for (const method of ['PATCH', 'PUT'] as const) { + registerMockEndpoint({ + path: `${endpoint}/:id`, + method, + callback: (event) => { + const index = indexOf(event); + const item = prepare({ + ...list()[index], + ...event.body, + id: event.route_params.id, + updated_at: now(), }); - list.splice(index, 1, updated_item); - ENDPOINT_SIGNALS[endpoint].set(list); - saveToSession(storage_key, list); - return updated_item; - } else { - throw { status: 404, message: 'Not found' }; - } - }, - } as MockHttpRequestHandler; - registerMockEndpoint(action); - registerMockEndpoint({ ...action, method: 'PUT' }); + store.set( + list().map((old, idx) => (idx === index ? item : old)), + ); + return item; + }, + }); + } - /** Add DELETE for item */ registerMockEndpoint({ path: `${endpoint}/:id`, - metadata: data, method: 'DELETE', callback: (event) => { - const list = [...(ENDPOINT_SIGNALS[endpoint]() || [])]; - const index = list.findIndex( - (an_item) => an_item.id === event.route_params.id, - ); - if (index >= 0) { - const deleted_item = list[index]; - list.splice(index, 1); - ENDPOINT_SIGNALS[endpoint].set(list); - saveToSession(storage_key, list); - return deleted_item; - } else { - throw { status: 404, message: 'Not found' }; - } + const index = indexOf(event); + const item = list()[index]; + store.set(list().filter((_, idx) => idx !== index)); + return item; }, - } as MockHttpRequestHandler); + }); - return ENDPOINT_SIGNALS[endpoint]; + return store; } diff --git a/src/app/mocks/index.ts b/src/app/mocks/index.ts index 781ab98c8..0f0aab5b5 100644 --- a/src/app/mocks/index.ts +++ b/src/app/mocks/index.ts @@ -1 +1,10 @@ +import { setMockNotFoundHandler } from '@placeos/ts-client'; import './backend'; + +/** Show requests that have no mock, so gaps are easy to find */ +setMockNotFoundHandler((method, url) => { + console.warn(`[mock] No handler for ${method} ${url}`); + const error = new Error(`Mock endpoint not found: ${method} ${url}`); + (error as Error & { status: number }).status = 404; + return Promise.reject(error); +}); From 1178f80cf10c6456d00ec22a1961a888f9c50cf5 Mon Sep 17 00:00:00 2001 From: Alex Sorafumo Date: Tue, 10 Nov 2026 15:47:41 +1100 Subject: [PATCH 2/2] fix(mocks): make mock IDs and secrets with the crypto API CodeQL flagged mock API keys, OAuth secrets and webhook secrets made with Math.random(). Co-Authored-By: Claude Opus 5.5 --- src/app/mocks/common.mock.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/app/mocks/common.mock.ts b/src/app/mocks/common.mock.ts index 77a25a176..66cb458cc 100644 --- a/src/app/mocks/common.mock.ts +++ b/src/app/mocks/common.mock.ts @@ -103,15 +103,13 @@ const AVAILABLE_CHARS = export type FilterFn = (item: T, query: HashMap) => boolean; /** - * Generate an ID with length + * Generate an ID with length. Uses the crypto API, as mock keys and + * secrets are made with it too * @param length Length of the ID */ export function generateID(length = 12, chars: string[] = AVAILABLE_CHARS) { - let id = ''; - while (id.length < length) { - id += chars[Math.floor(Math.random() * chars.length)]; - } - return id; + const values = crypto.getRandomValues(new Uint32Array(length)); + return Array.from(values, (value) => chars[value % chars.length]).join(''); } /** Current time in seconds, which is what the API uses for timestamps */