/** The Hub dashboard's API (admin login required). */ const express = require('express'); const rateLimit = require('express-rate-limit'); const prisma = require('../config/db'); const { protect } = require('../middleware/auth'); const { generateLicence, checkReopen } = require('../utils/licences'); const { PRODUCTS, isProduct, PRODUCT_NAMES } = require('../utils/products'); const compute = require('../utils/billing/compute'); const { ymd, today } = require('../utils/billing/dates'); const { linkedProductsFor } = require('../utils/protocol'); const { audit } = require('../utils/audit'); const { getSettings, setSettings } = require('../utils/settings'); const { problems, compareVersions } = require('../utils/alerts'); const licenceToken = require('../utils/licenceToken'); const { smtpConfigured, testSmtp } = require('../utils/mail'); const { VERSION_RE, sortReleases, syncLatestVersion, latestVersions, unmetRequirementsFor } = require('../utils/releases'); const { emailNotice } = require('../utils/notices'); const { parseRepoUrl, syncReleases, releaseSources, cleanSources } = require('../utils/releaseSync'); const ai = require('../utils/ai'); const { AI_MODELS } = require('../utils/aiModels'); const router = express.Router(); router.use(protect); const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many test emails — wait a few minutes.' } }); const wrap = fn => (req, res) => fn(req, res).catch(e => { const status = e.status || 500; if (status >= 500) console.error('[admin]', e); res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message, ...(e.code && e.status ? { code: e.code } : {}) }); }); const bad = (message, status = 400) => Object.assign(new Error(message), { status }); const text = (v, max = 500) => (v == null || String(v).trim() === '' ? null : String(v).trim().slice(0, max)); function dateOrNull(v) { if (v == null || v === '') return null; const d = new Date(v); if (Number.isNaN(d.getTime())) throw bad('Not a valid date.'); return d; } // The health of an install at a glance, for lists. `latest` is the latest version per product. function summary(install, settings, latest = {}, now = new Date()) { const current = problems(install, { ...settings, latest_versions: latest }, now); const latestForProduct = latest[install.product] || null; const worst = current.some(p => p.level === 'critical') ? 'critical' : current.some(p => p.level === 'warning') ? 'warning' : 'ok'; return { id: install.id, product: install.product, name: install.name, url: install.url, customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null, version: install.version, latestVersion: latestForProduct, behind: !!(latestForProduct && install.version && compareVersions(install.version, latestForProduct) < 0), licence: install.licence ? { id: install.licence.id, status: install.licence.status, expiresAt: install.licence.expiresAt } : null, lastHeartbeatAt: install.lastHeartbeatAt, status: worst, problems: current, releasedAt: install.releasedAt, }; } // ─── Dashboard ──────────────────────────────────────────────────────────────── router.get('/dashboard', wrap(async (req, res) => { const [settings, latest] = await Promise.all([getSettings(), latestVersions()]); const installs = await prisma.install.findMany({ where: { releasedAt: null }, include: { licence: true, customer: true }, orderBy: { name: 'asc' } }); const rows = installs.map(i => summary(i, settings, latest)); const [customers, licences, openAlerts, billed, sentInvoices] = await Promise.all([ prisma.customer.count(), prisma.licence.groupBy({ by: ['product', 'status'], _count: { _all: true } }), prisma.installEvent.count({ where: { resolvedAt: null, level: { not: 'info' } } }), prisma.customer.findMany({ where: { billingCycle: { not: 'none' } }, include: { licences: { include: { install: true } } } }), prisma.invoice.findMany({ where: { status: 'sent' }, include: { payments: true } }), ]); // Hub 2.0: per product, monthly recurring revenue (after discounts) and overdue invoices. const byProduct = Object.fromEntries(PRODUCTS.map(p => { const own = rows.filter(r => r.product === p); return [p, { installs: own.length, behind: own.filter(r => r.behind).length, critical: own.filter(r => r.status === 'critical').length, licences: Object.fromEntries(licences.filter(l => l.product === p).map(l => [l.status, l._count._all])), }]; })); const t = ymd(today()); const overdue = sentInvoices.map(i => compute.invoiceState(i, t)).filter(s => s.state === 'overdue'); res.json({ latestVersion: latest.events || null, latestVersions: latest, counts: { installs: rows.length, healthy: rows.filter(r => r.status === 'ok').length, warning: rows.filter(r => r.status === 'warning').length, critical: rows.filter(r => r.status === 'critical').length, behind: rows.filter(r => r.behind).length, customers, licences: licences.reduce((acc, l) => ({ ...acc, [l.status]: (acc[l.status] || 0) + l._count._all }), {}), openAlerts, billedCustomers: billed.length, overdueInvoices: overdue.length, }, byProduct, monthlyRecurringCents: billed.reduce((s, c) => s + compute.monthlyRecurringCents(c, c.licences), 0), overdueCents: overdue.reduce((s, x) => s + x.balanceCents, 0), installs: rows, }); })); // ─── Customers ──────────────────────────────────────────────────────────────── router.get('/customers', wrap(async (req, res) => { const customers = await prisma.customer.findMany({ orderBy: { name: 'asc' }, include: { licences: { select: { id: true, product: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, product: true, url: true, lastHeartbeatAt: true } } }, }); res.json(customers); })); function customerData(body, { partial = false } = {}) { const data = {}; for (const f of ['name', 'contactName', 'email', 'phone', 'notes']) if (body?.[f] !== undefined) data[f] = text(body[f], f === 'notes' ? 5000 : 200); // AI (Hub 2.0: the church's, for all its installs): the monthly cap and an optional markup. if (body?.aiMonthlyCapCents !== undefined) { const n = parseInt(body.aiMonthlyCapCents, 10); if (!Number.isInteger(n) || n < 0) throw bad('The AI cap must be 0 or more.'); data.aiMonthlyCapCents = n; } if (body?.aiMarkupPercent !== undefined) { if (body.aiMarkupPercent === null || body.aiMarkupPercent === '') data.aiMarkupPercent = null; else { const n = parseInt(body.aiMarkupPercent, 10); if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The AI markup is 0–500 %, or blank for the default.'); data.aiMarkupPercent = n; } } if ((!partial || 'name' in data) && !data.name) throw bad('Give the customer a name.'); return data; } router.post('/customers', wrap(async (req, res) => { const customer = await prisma.customer.create({ data: customerData(req.body) }); await audit(req, 'customer_created', customer.id, { name: customer.name }); res.status(201).json(customer); })); router.get('/customers/:id', wrap(async (req, res) => { const customer = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: { orderBy: { createdAt: 'desc' }, include: { install: { select: { id: true, name: true, url: true, lastHeartbeatAt: true } } } }, installs: { orderBy: { registeredAt: 'desc' } } }, }); if (!customer) throw bad('Customer not found', 404); res.json(customer); })); router.put('/customers/:id', wrap(async (req, res) => { const customer = await prisma.customer.update({ where: { id: req.params.id }, data: customerData(req.body, { partial: true }) }).catch(() => { throw bad('Customer not found', 404); }); await audit(req, 'customer_updated', customer.id, { name: customer.name }); res.json(customer); })); // ─── Licences ───────────────────────────────────────────────────────────────── function licenceData(body, { partial = false } = {}) { const data = {}; if (body?.plan !== undefined) data.plan = text(body.plan, 50) || 'standard'; if (body?.expiresAt !== undefined) data.expiresAt = dateOrNull(body.expiresAt); if (body?.graceDays !== undefined) { const n = parseInt(body.graceDays, 10); if (!Number.isInteger(n) || n < 0 || n > 90) throw bad('Grace period: 0–90 days.'); data.graceDays = n; } if (body?.status !== undefined) { if (!['active', 'suspended', 'revoked'].includes(body.status)) throw bad('Status must be active, suspended or revoked.'); data.status = body.status; } if (body?.notes !== undefined) data.notes = text(body.notes, 5000); if (!partial && data.status === undefined) data.status = 'active'; return data; } // "Generate": a new licence with a fresh key for a customer, for one product (Events unless // another is given). A customer has one open licence per product; its Accounts licence (free) // is created with its first other product. router.post('/customers/:id/licences', wrap(async (req, res) => { const customer = await prisma.customer.findUnique({ where: { id: req.params.id } }); if (!customer) throw bad('Customer not found', 404); const product = req.body?.product ?? 'events'; if (!isProduct(product)) throw bad('Product must be events, accounts, website or app.'); // A new Website licence is on its one plan, an App licence on the first tier (the review moves it). const data = { ...(product === 'website' ? { plan: 'Website' } : product === 'app' ? { plan: 'Mustard Seed' } : {}), ...licenceData(req.body) }; const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data }); await audit(req, 'licence_generated', licence.id, { customer: customer.name, product, expiresAt: licence.expiresAt }); if (accounts) await audit(req, 'licence_generated', accounts.id, { customer: customer.name, product: 'accounts', automatic: true }); res.status(201).json({ ...licence, accountsLicence: accounts }); })); router.put('/licences/:id', wrap(async (req, res) => { const existing = await prisma.licence.findUnique({ where: { id: req.params.id } }); if (!existing) throw bad('Licence not found', 404); const data = licenceData(req.body, { partial: true }); await checkReopen(prisma, existing, data.status); const licence = await prisma.licence.update({ where: { id: existing.id }, data }).catch(e => { if (e.code === 'P2002') throw Object.assign(bad(`This customer already has an open ${PRODUCT_NAMES[existing.product]} licence.`, 409), { code: 'PRODUCT_LICENCE_EXISTS' }); throw e; }); await audit(req, 'licence_updated', licence.id, { changed: Object.keys(data), status: licence.status, expiresAt: licence.expiresAt }); res.json(licence); })); // Free the licence from its install (e.g. the church moved to a new address): the old install's // heartbeats are refused, and the licence can be registered again from the new site. router.post('/licences/:id/release', wrap(async (req, res) => { const licence = await prisma.licence.findUnique({ where: { id: req.params.id }, include: { install: true } }); if (!licence) throw bad('Licence not found', 404); if (!licence.install) throw bad('This licence is not in use.'); await prisma.install.update({ where: { id: licence.install.id }, data: { licenceId: null, releasedAt: new Date() } }); await prisma.installEvent.create({ data: { installId: licence.install.id, type: 'released', level: 'info', message: 'Licence released from this install', resolvedAt: new Date() } }); await audit(req, 'licence_released', licence.id, { install: licence.install.url }); res.json({ message: 'Released.' }); })); // ─── Installs ───────────────────────────────────────────────────────────────── router.get('/installs', wrap(async (req, res) => { const [settings, latest] = await Promise.all([getSettings(), latestVersions()]); const installs = await prisma.install.findMany({ include: { licence: true, customer: true }, orderBy: { name: 'asc' } }); res.json(installs.map(i => summary(i, settings, latest))); })); router.get('/installs/:id', wrap(async (req, res) => { const [settings, latest] = await Promise.all([getSettings(), latestVersions()]); const install = await prisma.install.findUnique({ where: { id: req.params.id }, include: { licence: true, customer: true, events: { orderBy: { createdAt: 'desc' }, take: 100 } }, }); if (!install) throw bad('Install not found', 404); const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); const heartbeats = await prisma.heartbeat.findMany({ where: { installId: install.id, receivedAt: { gte: since } }, orderBy: { receivedAt: 'asc' }, select: { receivedAt: true, version: true, health: true, stats: true }, }); const { secret, ...safe } = install; let licence = null; if (install.licence) { // What the install would be told right now, for checking. licence = { ...install.licence, tokenPreview: licenceToken.buildPayload({ ...install.licence, aiMonthlyCapCents: install.customer.aiMonthlyCapCents }, install, install.customer.name) }; } const target = latest[install.product] || null; const behind = !!(target && install.version && compareVersions(install.version, target) < 0); const [aiStatus, aiMonths, aiHelpers, unmet] = await Promise.all([ ai.statusFor(install), ai.usageByMonth(install.id), ai.usageByHelper(install.id), behind ? unmetRequirementsFor(install, target) : [], ]); res.json({ ...safe, licence, summary: summary(install, settings, latest), heartbeats, ai: { status: aiStatus, months: aiMonths, helpers: aiHelpers }, // What updating to the latest version needs from the church's other products (Hub 2.0). update: { latestVersion: target, behind, unmetRequirements: unmet }, // The church's other installs this one is told about (protocol v2), and the ones it isn't. linkedProducts: await linkedProductsFor(install), siblings: (await prisma.install.findMany({ where: { customerId: install.customerId, id: { not: install.id }, releasedAt: null }, select: { id: true, product: true, url: true, version: true, protocolVersion: true, publicKey: true, lastHeartbeatAt: true } })) .map(({ publicKey, ...s }) => ({ ...s, hasPublicKey: !!publicKey })), }); })); router.put('/installs/:id', wrap(async (req, res) => { const install = await prisma.install.update({ where: { id: req.params.id }, data: { notes: text(req.body?.notes, 5000) } }).catch(() => { throw bad('Install not found', 404); }); await audit(req, 'install_notes_updated', install.id); res.json({ id: install.id, notes: install.notes }); })); // ─── Alerts and history ─────────────────────────────────────────────────────── router.get('/events', wrap(async (req, res) => { const where = req.query.open === 'true' ? { resolvedAt: null, level: { not: 'info' } } : {}; const events = await prisma.installEvent.findMany({ where, orderBy: { createdAt: 'desc' }, take: 200, include: { install: { select: { id: true, name: true, url: true } } }, }); res.json(events); })); router.get('/audit', wrap(async (req, res) => { res.json(await prisma.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 300, include: { actor: { select: { name: true } } } })); })); // ─── Releases ───────────────────────────────────────────────────────────────── // What's new in each version of each product (Hub 2.0). Installs on an older version see the // notes; a product's highest version is its latest, so a new one tells its installs an update is // out. A product with release sources (Releases page) gets its releases from git only; one with // none is managed by hand. router.get('/releases', wrap(async (req, res) => { const [releases, installs] = await Promise.all([ prisma.release.findMany(), prisma.install.findMany({ where: { releasedAt: null }, select: { product: true, version: true } }), ]); const onVersion = {}; for (const i of installs) if (i.version) onVersion[`${i.product}@${i.version}`] = (onVersion[`${i.product}@${i.version}`] || 0) + 1; const latest = await latestVersions(); res.json(sortReleases(releases).map(r => ({ ...r, latest: latest[r.product] === r.version, installs: onVersion[`${r.product}@${r.version}`] || 0 }))); })); // The release sources in use (the saved list or the defaults). router.get('/releases/sources', wrap(async (req, res) => { const settings = await getSettings(); res.json({ sources: releaseSources(settings), saved: !!String(settings.release_sources || '').trim() }); })); function releaseData(body, { partial = false } = {}) { const data = {}; if (!partial) { const product = body?.product ?? 'events'; if (!isProduct(product)) throw bad('Choose a product.'); data.product = product; } if (body?.version !== undefined) { const v = String(body.version || '').trim().replace(/^v/i, ''); if (!VERSION_RE.test(v)) throw bad('The version looks like 1.47.0.'); data.version = v; } else if (!partial) throw bad('The version looks like 1.47.0.'); if (body?.notes !== undefined) data.notes = String(body.notes || '').trim().slice(0, 20000); if (body?.urgent !== undefined) data.urgent = !!body.urgent; if (body?.releasedAt !== undefined) data.releasedAt = dateOrNull(body.releasedAt) || new Date(); return data; } // A product with release sources gets its releases from git only. async function manualReleases(product) { if (releaseSources(await getSettings()).some(s => s.product === product)) { throw bad(`${PRODUCT_NAMES[product]} releases come from git: tag the version and edit its notes file, then Sync now.`); } } router.post('/releases/sync', wrap(async (req, res) => { if (!releaseSources(await getSettings()).length) throw bad('Add a release source first.'); let result; try { result = await syncReleases(); } catch (e) { throw bad(e.message, 502); } await audit(req, 'releases_synced', null, result); res.json(result); })); const releaseError = e => { if (e.code === 'P2002') throw bad('This product already has a release with that version.', 409); if (e.code === 'P2025') throw bad('Release not found', 404); throw e; }; router.post('/releases', wrap(async (req, res) => { const data = releaseData(req.body); await manualReleases(data.product); const release = await prisma.release.create({ data }).catch(releaseError); const latest = await syncLatestVersion(); await audit(req, 'release_added', release.id, { product: release.product, version: release.version, urgent: release.urgent }); res.status(201).json({ release, latestVersion: latest[release.product] || null }); })); router.put('/releases/:id', wrap(async (req, res) => { const existing = await prisma.release.findUnique({ where: { id: req.params.id } }); if (!existing) throw bad('Release not found', 404); await manualReleases(existing.product); const data = releaseData(req.body, { partial: true }); const release = await prisma.release.update({ where: { id: existing.id }, data }).catch(releaseError); const latest = await syncLatestVersion(); await audit(req, 'release_updated', release.id, { product: release.product, version: release.version, changed: Object.keys(data) }); res.json({ release, latestVersion: latest[release.product] || null }); })); router.delete('/releases/:id', wrap(async (req, res) => { const existing = await prisma.release.findUnique({ where: { id: req.params.id } }); if (!existing) throw bad('Release not found', 404); await manualReleases(existing.product); const release = await prisma.release.delete({ where: { id: existing.id } }).catch(releaseError); const latest = await syncLatestVersion(); await audit(req, 'release_deleted', release.id, { product: release.product, version: release.version }); res.json({ latestVersion: latest[release.product] || null }); })); // ─── Notices ────────────────────────────────────────────────────────────────── // Messages to churches: a banner on their site (site admins and supervisors) and/or one email. router.get('/notices', wrap(async (req, res) => { res.json(await prisma.notice.findMany({ orderBy: { createdAt: 'desc' }, take: 200 })); })); const NOTICE_LEVELS = ['info', 'maintenance', 'warning']; async function noticeData(body, { partial = false } = {}) { const data = {}; if (body?.title !== undefined) data.title = text(body.title, 120); if (body?.message !== undefined) data.message = text(body.message, 2000); if ((!partial || 'title' in data) && !data.title) throw bad('Give the notice a title.'); if ((!partial || 'message' in data) && !data.message) throw bad('Write the message.'); if (body?.level !== undefined) { if (!NOTICE_LEVELS.includes(body.level)) throw bad('Level must be info, maintenance or warning.'); data.level = body.level; } if (body?.allInstalls !== undefined) data.allInstalls = !!body.allInstalls; if (body?.installIds !== undefined) { const ids = [...new Set((Array.isArray(body.installIds) ? body.installIds : []).map(String))]; const found = ids.length ? await prisma.install.count({ where: { id: { in: ids } } }) : 0; if (found !== ids.length) throw bad('One of the chosen installs no longer exists.'); data.installIds = ids; } if (body?.showBanner !== undefined) data.showBanner = !!body.showBanner; if (body?.startsAt !== undefined) data.startsAt = dateOrNull(body.startsAt); if (body?.endsAt !== undefined) data.endsAt = dateOrNull(body.endsAt); return data; } function checkNotice(notice) { if (notice.allInstalls === false && !(notice.installIds || []).length) throw bad('Choose at least one install, or send it to every install.'); if (notice.startsAt && notice.endsAt && new Date(notice.endsAt) <= new Date(notice.startsAt)) throw bad('The end has to be after the start.'); } // Create, and email it straight away when asked. Email only (no banner) is fine too. router.post('/notices', wrap(async (req, res) => { const data = await noticeData(req.body); const sendEmail = !!req.body?.sendEmail; if (data.showBanner === false && !sendEmail) throw bad('Show it as a banner, email it, or both.'); checkNotice(data); let notice = await prisma.notice.create({ data }); if (sendEmail) { const sent = await emailNotice(notice); notice = await prisma.notice.update({ where: { id: notice.id }, data: { emailedAt: new Date(), emailedTo: sent } }); } await audit(req, 'notice_created', notice.id, { title: notice.title, allInstalls: notice.allInstalls, installs: notice.installIds.length, banner: notice.showBanner, emailedTo: sendEmail ? notice.emailedTo : null }); res.status(201).json(notice); })); // Edit the banner (the email isn't sent again). "End now" is { endsAt: now }. router.put('/notices/:id', wrap(async (req, res) => { const existing = await prisma.notice.findUnique({ where: { id: req.params.id } }); if (!existing) throw bad('Notice not found', 404); const data = await noticeData(req.body, { partial: true }); checkNotice({ ...existing, ...data }); const notice = await prisma.notice.update({ where: { id: existing.id }, data }); await audit(req, 'notice_updated', notice.id, { title: notice.title, changed: Object.keys(data) }); res.json(notice); })); router.delete('/notices/:id', wrap(async (req, res) => { const notice = await prisma.notice.delete({ where: { id: req.params.id } }).catch(() => { throw bad('Notice not found', 404); }); await audit(req, 'notice_deleted', notice.id, { title: notice.title }); res.json({ message: 'Deleted.' }); })); // ─── Settings ───────────────────────────────────────────────────────────────── router.get('/settings', wrap(async (req, res) => { const settings = await getSettings(); res.json({ settings, releaseSources: releaseSources(settings), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured(), aiModels: AI_MODELS }); })); const SMTP_FIELDS = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_pass_clear', 'smtp_from']; function checkSmtp(values) { if (values.smtp_port != null && values.smtp_port !== '' && !/^\d{1,5}$/.test(String(values.smtp_port))) throw bad('SMTP port is a number, usually 587 or 465.'); if (values.smtp_host && /[\s/]/.test(String(values.smtp_host).trim())) throw bad('SMTP server is a host name like mail.example.com, without https:// or a path.'); } // What the audit log records: never the password, only that it changed. function auditValues(values) { const { smtp_pass, smtp_pass_clear, release_repo_token, release_repo_token_clear, ai_api_key, ai_api_key_clear, ...rest } = values; if (smtp_pass_clear) rest.smtp_pass = '(removed)'; else if (smtp_pass) rest.smtp_pass = '(changed)'; if (release_repo_token_clear) rest.release_repo_token = '(removed)'; else if (release_repo_token) rest.release_repo_token = '(changed)'; if (ai_api_key_clear) rest.ai_api_key = '(removed)'; else if (ai_api_key) rest.ai_api_key = '(changed)'; return rest; } function checkAi(values) { for (const [key, label] of [['ai_input_usd_per_mtok', 'Input price'], ['ai_output_usd_per_mtok', 'Output price'], ['ai_usd_zar', 'Exchange rate']]) { if (values[key] != null && values[key] !== '' && !(parseFloat(values[key]) >= 0)) throw bad(`${label} is a number.`); } if (values.ai_markup_percent != null && values.ai_markup_percent !== '') { const n = Number(values.ai_markup_percent); if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The default markup is a whole number of % (0–500).'); } if (values.ai_model != null && !/^[a-z0-9][a-z0-9.-]{2,60}$/.test(String(values.ai_model).trim())) throw bad('The model looks like claude-haiku-5-5.'); } router.put('/settings', wrap(async (req, res) => { // The latest version follows the Releases page; the sync writes its own status. // eslint-disable-next-line no-unused-vars const { latest_version, release_synced_at, release_sync_error, ...values } = req.body?.settings || {}; if (values.release_repo_url && !parseRepoUrl(values.release_repo_url)) throw bad('The repository address looks like https://git.example.com/owner/repo.'); if (values.release_notes_path != null && !String(values.release_notes_path).trim()) values.release_notes_path = 'WHATS-NEW.md'; // Hub 2.0: the release sources per product. A list is checked and saved as JSON; null goes back // to the defaults. if (values.release_sources !== undefined) { values.release_sources = values.release_sources === null ? '' : JSON.stringify(cleanSources(values.release_sources)); } checkSmtp(values); checkAi(values); if (values.ai_model != null) values.ai_model = String(values.ai_model).trim(); const settings = await setSettings(values); await audit(req, 'settings_updated', null, auditValues(values)); res.json({ settings, smtp: await smtpConfigured() }); })); // Tries the SMTP settings in the form (unsaved is fine): logs in and sends a test email. router.post('/settings/smtp-test', smtpTestLimiter, wrap(async (req, res) => { const values = Object.fromEntries(SMTP_FIELDS.filter(k => req.body?.settings?.[k] != null).map(k => [k, req.body.settings[k]])); checkSmtp(values); const to = text(req.body?.to, 200) || (await getSettings()).alert_email || req.admin.email; if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(to)) throw bad('Send the test to a valid email address.'); try { await testSmtp(values, to); } catch (e) { await audit(req, 'smtp_test_failed', null, { to, error: String(e.message).slice(0, 300) }); throw bad(`The test failed: ${e.message}`); } await audit(req, 'smtp_test_sent', null, { to }); res.json({ to }); })); // ─── AI ─────────────────────────────────────────────────────────────────────── // A tiny call with the saved key and model, to check they work. Not metered to any install. router.post('/settings/ai-test', smtpTestLimiter, wrap(async (req, res) => { try { const result = await ai.testCall(await getSettings()); await audit(req, 'ai_test_ok', null, { model: result.model }); res.json(result); } catch (e) { await audit(req, 'ai_test_failed', null, { error: String(e.message).slice(0, 300) }); throw bad(e.message, e.status || 502); } })); // Every install's AI use in a month (YYYY-MM, default this month): real cost, charged, profit. router.get('/ai-usage', wrap(async (req, res) => { const month = /^\d{4}-\d{2}$/.test(String(req.query.month || '')) ? String(req.query.month) : ai.monthOf(); const installs = await ai.usageForMonth(month); const sum = key => Math.round(installs.reduce((n, i) => n + i[key], 0) * 100) / 100; res.json({ month, installs, totals: { calls: installs.reduce((n, i) => n + i.calls, 0), realCents: sum('realCents'), chargedCents: sum('chargedCents'), profitCents: sum('profitCents') } }); })); module.exports = router; module.exports.summary = summary;