Merge branch 'chore/releases-notices'

This commit is contained in:
2026-10-28 09:13:30 +02:00
27 changed files with 1260 additions and 30 deletions
+25
View File
@@ -5,6 +5,31 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [1.4.0] - 2026-10-28
### Added
- **Releases from git** — every `v1.2.3` tag of the Cross Events repository is a release, and the
newest tag is the latest version: no more setting it by hand. What's new in each version comes
from the repo's `WHATS-NEW.md` (written for churches; `urgent` or `security` in a version's heading
marks a security or serious bug fix). Synced every 15 minutes and with **Sync now** on the new
**Releases** page, which shows each version, its notes and how many installs run it. Installs on an
older version get the notes for every version they'd get, so the church can decide whether to ask
for the update; urgent ones can't be put off. Set to the hope-events repository by default; a
token is only needed if it becomes private. With the repository cleared, releases are added by
hand on the same page.
- **Notices page** — write a message for every install or chosen ones: a **banner** on their site for
site admins and supervisors (from and until a time, e.g. planned maintenance), an **email** to the
customer and the site's admin contact, or both. Banners can be edited or ended early.
- **Withdrawn update requests** — when a church withdraws its update request, the alert is resolved
and you're emailed, so you don't update the site after all.
### Changed
- Settings → "Releases and alerts" is now "Alerts"; the latest version follows the Releases page.
Cross Events 1.46.2 shows the notes and notices; older installs keep working and ignore them.
## [1.3.0] - 2026-10-28
### Added
+10
View File
@@ -39,6 +39,16 @@ The first login sets up two-factor with an authenticator app (required).
To try it with Cross Events locally, point the install at the Hub with `HUB_URL=http://localhost:5200`
and `HUB_PUBLIC_KEY` (the public key shown in Hub → Settings) in Cross Events' `backend/.env`.
## Releases and notices
- **Releases** come from git: every `v1.2.3` tag of `joshua/hope-events` is a release, the newest is
the latest version, and the notes churches see come from `WHATS-NEW.md` in that repo as of the
newest tag. The Hub checks every 15 minutes (and on **Sync now**, Releases page). So releasing
Cross Events is: write the version's section in `WHATS-NEW.md`, tag, push — installs see the
update with their next heartbeat.
- **Notices** (Notices page) are banners on churches' sites for their admins and supervisors, emails
to them, or both — e.g. planned maintenance.
## The licence signing key
Licences are tokens signed with an Ed25519 key. **The private key exists only on the Hub server**;
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "1.3.0",
"version": "1.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "1.3.0",
"version": "1.4.0",
"hasInstallScript": true,
"dependencies": {
"@prisma/adapter-pg": "^7.10.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "1.3.0",
"version": "1.4.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
@@ -0,0 +1,45 @@
-- CreateEnum
CREATE TYPE "NoticeLevel" AS ENUM ('info', 'maintenance', 'warning');
-- CreateTable
CREATE TABLE "Release" (
"id" TEXT NOT NULL,
"version" TEXT NOT NULL,
"notes" TEXT NOT NULL DEFAULT '',
"urgent" BOOLEAN NOT NULL DEFAULT false,
"releasedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Release_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Notice" (
"id" TEXT NOT NULL,
"title" TEXT NOT NULL,
"message" TEXT NOT NULL,
"level" "NoticeLevel" NOT NULL DEFAULT 'info',
"allInstalls" BOOLEAN NOT NULL DEFAULT true,
"installIds" TEXT[] DEFAULT ARRAY[]::TEXT[],
"showBanner" BOOLEAN NOT NULL DEFAULT true,
"startsAt" TIMESTAMP(3),
"endsAt" TIMESTAMP(3),
"emailedAt" TIMESTAMP(3),
"emailedTo" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Notice_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "Release_version_key" ON "Release"("version");
-- CreateIndex
CREATE INDEX "Notice_endsAt_idx" ON "Notice"("endsAt");
-- The latest version set on the Settings page becomes the first release (no notes yet).
INSERT INTO "Release" ("id", "version", "notes", "urgent", "releasedAt", "createdAt", "updatedAt")
SELECT gen_random_uuid()::text, "value", '', false, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
FROM "Setting" WHERE "key" = 'latest_version' AND "value" <> '';
+43
View File
@@ -147,3 +147,46 @@ model Setting {
key String @id
value String
}
// A Cross Events version and what's new in it, shown to installs on an older version so the church
// can decide whether to ask for the update. The highest version is the latest (kept in the
// latest_version setting). Urgent releases (security or serious bug fixes) can't be put off.
model Release {
id String @id @default(uuid())
version String @unique
// Plain text; lines starting with "- " show as a list.
notes String @default("")
urgent Boolean @default(false)
releasedAt DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
enum NoticeLevel {
info
maintenance
warning
}
// A message from Joshua to churches: a banner on their site for site admins and supervisors
// (between startsAt and endsAt), an email to the customer and the install's admin contact, or both.
model Notice {
id String @id @default(uuid())
title String
message String
level NoticeLevel @default(info)
// Every install, or only the ones listed.
allInstalls Boolean @default(true)
installIds String[] @default([])
showBanner Boolean @default(true)
// Null = straight away / until ended.
startsAt DateTime?
endsAt DateTime?
// Set when the email went out (sent once, when the notice is created).
emailedAt DateTime?
emailedTo Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([endsAt])
}
+4 -1
View File
@@ -11,6 +11,7 @@ const app = require('./app');
const { keyPair } = require('./utils/licenceToken');
const { runAlerts, rollupHeartbeats } = require('./utils/alerts');
const { importSmtpFromEnv } = require('./utils/settings');
const { syncReleases } = require('./utils/releaseSync');
// Fail early if the licence signing key is missing or wrong.
try {
@@ -28,11 +29,13 @@ importSmtpFromEnv()
const PORT = parseInt(process.env.PORT || '5200', 10);
app.listen(PORT, () => console.log(`[hub] Listening on ${PORT}`));
// Background checks: alerts every 5 minutes, heartbeat roll-up once a day. The Hub runs as a
// Background checks: alerts every 5 minutes, releases from git every 15, heartbeat roll-up once a day. The Hub runs as a
// single process, so plain timers are enough.
if (String(process.env.JOBS_ENABLED || 'true').toLowerCase() !== 'false') {
const every = (ms, name, fn) => setInterval(() => fn().catch(e => console.warn(`[hub] ${name} failed:`, e?.message || e)), ms);
every(5 * 60 * 1000, 'alerts', () => runAlerts());
every(15 * 60 * 1000, 'release sync', () => syncReleases());
every(24 * 60 * 60 * 1000, 'heartbeat roll-up', () => rollupHeartbeats());
setTimeout(() => runAlerts().catch(() => {}), 30 * 1000);
setTimeout(() => syncReleases().catch(e => console.warn('[hub] release sync failed:', e?.message || e)), 20 * 1000);
}
+156 -4
View File
@@ -10,6 +10,9 @@ 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 } = require('../utils/releases');
const { emailNotice } = require('../utils/notices');
const { parseRepoUrl, syncReleases } = require('../utils/releaseSync');
const router = express.Router();
router.use(protect);
@@ -19,7 +22,7 @@ const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardH
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 ? 'Something went wrong.' : e.message });
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message });
});
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));
@@ -224,6 +227,150 @@ 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 Cross Events version. Installs on an older version see the notes; the highest
// version is the latest (latest_version), so adding one tells installs an update is out. With a git
// repository set (Releases page), releases come from its tags and WHATS-NEW.md only.
router.get('/releases', wrap(async (req, res) => {
const [releases, installs] = await Promise.all([
prisma.release.findMany(),
prisma.install.findMany({ where: { releasedAt: null }, select: { version: true } }),
]);
const onVersion = {};
for (const i of installs) if (i.version) onVersion[i.version] = (onVersion[i.version] || 0) + 1;
res.json(sortReleases(releases).map(r => ({ ...r, installs: onVersion[r.version] || 0 })));
}));
function releaseData(body, { partial = false } = {}) {
const data = {};
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;
}
async function manualReleases() {
if (parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Releases come from git: tag the version and edit WHATS-NEW.md, then Sync now.');
}
router.post('/releases/sync', wrap(async (req, res) => {
if (!parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Set the git repository 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('There is already 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) => {
await manualReleases();
const release = await prisma.release.create({ data: releaseData(req.body) }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_added', release.id, { version: release.version, urgent: release.urgent });
res.status(201).json({ release, latestVersion: latest || null });
}));
router.put('/releases/:id', wrap(async (req, res) => {
await manualReleases();
const data = releaseData(req.body, { partial: true });
const release = await prisma.release.update({ where: { id: req.params.id }, data }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_updated', release.id, { version: release.version, changed: Object.keys(data) });
res.json({ release, latestVersion: latest || null });
}));
router.delete('/releases/:id', wrap(async (req, res) => {
await manualReleases();
const release = await prisma.release.delete({ where: { id: req.params.id } }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_deleted', release.id, { version: release.version });
res.json({ latestVersion: latest || 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) => {
@@ -239,15 +386,20 @@ function checkSmtp(values) {
// What the audit log records: never the password, only that it changed.
function auditValues(values) {
const { smtp_pass, smtp_pass_clear, ...rest } = values;
const { smtp_pass, smtp_pass_clear, release_repo_token, release_repo_token_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)';
return rest;
}
router.put('/settings', wrap(async (req, res) => {
const values = req.body?.settings || {};
if (values.latest_version && !/^\d+\.\d+\.\d+$/.test(String(values.latest_version))) throw bad('Latest version looks like 1.41.0.');
// 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';
checkSmtp(values);
const settings = await setSettings(values);
await audit(req, 'settings_updated', null, auditValues(values));
+42 -2
View File
@@ -1,5 +1,6 @@
/**
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request.
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request
* (and withdrawing it).
* Install → Hub only; these are the only endpoints that aren't behind an admin login.
*/
@@ -12,6 +13,8 @@ const { checkSignature } = require('../utils/signing');
const { getSettings } = require('../utils/settings');
const { compareVersions } = require('../utils/alerts');
const { sendMail } = require('../utils/mail');
const { releasesForInstall } = require('../utils/releases');
const { noticesForInstall } = require('../utils/notices');
const router = express.Router();
@@ -114,6 +117,8 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
licence: await tokenFor(install),
heartbeatIntervalMinutes: HEARTBEAT_MINUTES,
latestVersion: settings.latest_version || null,
releases: await releasesForInstall(install.version),
notices: await noticesForInstall(install.id),
});
} catch (e) {
console.error('[register]', e);
@@ -144,7 +149,13 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
}
const settings = await getSettings();
res.json({ licence: await tokenFor(install), latestVersion: settings.latest_version || null, serverTime: now.toISOString() });
res.json({
licence: await tokenFor(install),
latestVersion: settings.latest_version || null,
releases: await releasesForInstall(version || install.version),
notices: await noticesForInstall(install.id, now),
serverTime: now.toISOString(),
});
} catch (e) {
console.error('[heartbeat]', e);
fail(res, 500, 'SERVER_ERROR', 'The Hub could not record this heartbeat.');
@@ -184,5 +195,34 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
}
});
// A site admin withdrew their update request: resolve the open request, and tell Joshua if he was
// emailed about it, so he doesn't update the site after all.
router.post('/installs/update-request/cancel', updateRequestLimiter, async (req, res) => {
try {
const install = await signedInstall(req, res);
if (!install) return;
const now = new Date();
const open = await prisma.installEvent.findMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null } });
if (!open.length) return res.json({ cancelled: false });
await prisma.installEvent.updateMany({ where: { id: { in: open.map(e => e.id) } }, data: { resolvedAt: now } });
await prisma.installEvent.create({ data: { installId: install.id, type: 'update_request_withdrawn', level: 'info', message: 'Update request withdrawn by the site', resolvedAt: now } });
const settings = await getSettings();
if (settings.alert_email) {
const customer = await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } });
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: update request withdrawn by ${customer?.name || install.name}`,
text: `${customer?.name || install.name} (${install.url}) withdrew their update request. No need to update the site for now.\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`,
}).catch(e => console.warn('[update-request] email failed:', e?.message));
}
res.json({ cancelled: true });
} catch (e) {
console.error('[update-request/cancel]', e);
fail(res, 500, 'SERVER_ERROR', 'The Hub could not withdraw the update request. Try again later.');
}
});
module.exports = router;
module.exports.PROTOCOL_VERSIONS = PROTOCOL_VERSIONS;
+1 -1
View File
@@ -89,7 +89,7 @@ async function runAlerts(now = new Date()) {
for (const install of installs) {
const current = problems(install, settings, now);
// Update requests are opened by the install and resolved by its heartbeat, not by these checks.
const openByType = new Map(install.events.filter(e => !['registered', 'version', 'update_requested'].includes(e.type)).map(e => [e.type, e]));
const openByType = new Map(install.events.filter(e => !['registered', 'version', 'update_requested', 'update_request_withdrawn'].includes(e.type)).map(e => [e.type, e]));
for (const p of current) {
if (openByType.has(p.type)) continue;
await prisma.installEvent.create({ data: { installId: install.id, type: p.type, level: p.level, message: p.message, createdAt: now } });
+84
View File
@@ -0,0 +1,84 @@
/**
* Notices from Joshua to churches (Notices page): a banner on the site for site admins and
* supervisors, sent with every heartbeat until it ends, and/or one email to the customer and the
* install's admin contact.
*/
const prisma = require('../config/db');
const { sendMail } = require('./mail');
function forInstall(notice, installId) {
return notice.allInstalls || (notice.installIds || []).includes(installId);
}
/**
* The banners an install is sent (§3): for it, banner on, and not ended. Ones that start later are
* included so the site shows them on time without waiting for a heartbeat; the site checks the dates.
*/
function noticesFor(notices, installId, now = new Date()) {
return notices
.filter(n => n.showBanner && forInstall(n, installId) && (!n.endsAt || new Date(n.endsAt) > now))
.map(n => ({
id: n.id,
level: n.level,
title: n.title,
message: n.message,
startsAt: n.startsAt ? new Date(n.startsAt).toISOString() : null,
endsAt: n.endsAt ? new Date(n.endsAt).toISOString() : null,
updatedAt: new Date(n.updatedAt).toISOString(),
}));
}
async function noticesForInstall(installId, now = new Date()) {
const notices = await prisma.notice.findMany({
where: { showBanner: true, OR: [{ endsAt: null }, { endsAt: { gt: now } }] },
orderBy: { createdAt: 'desc' },
});
return noticesFor(notices, installId, now);
}
/** Who a notice is emailed to: each install's customer email and admin contact, once each. */
function recipients(installs) {
const seen = new Map();
for (const install of installs) {
for (const email of [install.customer?.email, install.adminContact?.email]) {
const e = String(email || '').trim();
if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e) && !seen.has(e.toLowerCase())) seen.set(e.toLowerCase(), e);
}
}
return [...seen.values()];
}
const when = d => new Date(d).toLocaleString('en-ZA', { timeZone: 'Africa/Johannesburg', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' });
function emailText(notice) {
const lines = [notice.message.trim()];
if (notice.startsAt || notice.endsAt) {
lines.push('', [notice.startsAt && `From: ${when(notice.startsAt)}`, notice.endsAt && `Until: ${when(notice.endsAt)}`].filter(Boolean).join('\n'));
}
lines.push('', '— Cross Events');
return lines.join('\n');
}
/**
* Email a notice to the installs it's for (one email per address, so churches don't see each
* other). Returns how many were sent.
*/
async function emailNotice(notice) {
const installs = await prisma.install.findMany({
where: { releasedAt: null, ...(notice.allInstalls ? {} : { id: { in: notice.installIds } }) },
include: { customer: { select: { email: true } } },
});
let sent = 0;
for (const to of recipients(installs)) {
try {
await sendMail({ to, subject: `Cross Events: ${notice.title}`, text: emailText(notice) });
sent++;
} catch (e) {
console.warn(`[notices] email to ${to} failed:`, e?.message);
}
}
return sent;
}
module.exports = { noticesFor, noticesForInstall, recipients, emailText, emailNotice };
+149
View File
@@ -0,0 +1,149 @@
/**
* Releases from git (Gitea): every v1.2.3 tag of the Cross Events repo is a release, dated by its
* commit, and the notes come from the repo's WHATS-NEW.md as of the newest tag ("## 1.2.3" sections;
* "urgent" or "security" in the heading marks an urgent release). Runs every 15 minutes and from
* "Sync now" on the Releases page, when a repo is set; git is then the only source of releases.
*/
const prisma = require('../config/db');
const { compareVersions } = require('./alerts');
const { getSettings, setSettings, releaseRepoToken } = require('./settings');
const { syncLatestVersion } = require('./releases');
const TIMEOUT_MS = 20000;
const TAG_RE = /^v?(\d+\.\d+\.\d+)$/;
/** https://git.example.com/owner/repo(.git) → { api, owner, repo }, or null. */
function parseRepoUrl(url) {
try {
const u = new URL(String(url || '').trim());
if (!/^https?:$/.test(u.protocol)) return null;
const [owner, repo] = u.pathname.replace(/\/+$/, '').replace(/\.git$/, '').split('/').filter(Boolean);
if (!owner || !repo) return null;
return { api: `${u.origin}/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`, owner, repo };
} catch {
return null;
}
}
/** Markdown to the plain notes installs show: list lines stay "- ", the rest loses its markup. */
function plainNotes(lines) {
const out = [];
for (const raw of lines) {
let line = raw.replace(/\s+$/, '');
if (!line.trim()) { out.push(''); continue; }
const indent = /^\s{2,}[-*]\s/.test(line);
line = line.trim()
.replace(/^#{1,6}\s+/, '')
.replace(/^[*+]\s+/, '- ')
.replace(/\*\*(.+?)\*\*/g, '$1')
.replace(/__(.+?)__/g, '$1')
.replace(/`([^`]+)`/g, '$1')
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
// A wrapped line continues the line above: an indented one after a list item, any one in a paragraph.
const prev = out[out.length - 1];
const continues = prev && !line.startsWith('- ') && !indent && (prev.startsWith('- ') ? /^\s/.test(raw) : true);
if (continues) out[out.length - 1] = `${prev} ${line}`;
else out.push(line);
}
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
/**
* The sections of WHATS-NEW.md: { "1.46.2": { notes, urgent } }. A section is a "## 1.46.2" heading
* (optionally "[1.46.2]", "v1.46.2", a date or "— urgent" after it) up to the next "## ".
*/
function parseNotes(markdown) {
const text = String(markdown || '').replace(/<!--[\s\S]*?-->/g, '');
const sections = {};
let current = null;
for (const line of text.split(/\r?\n/)) {
const heading = /^##\s+(.*)$/.exec(line);
if (heading) {
const v = /\[?v?(\d+\.\d+\.\d+)\]?/.exec(heading[1]);
current = v ? { version: v[1], urgent: /\b(urgent|security)\b/i.test(heading[1]), lines: [] } : null;
if (current) sections[current.version] = current;
continue;
}
if (/^#\s/.test(line)) { current = null; continue; }
if (current) current.lines.push(line);
}
return Object.fromEntries(Object.values(sections).map(s => [s.version, { notes: plainNotes(s.lines), urgent: s.urgent }]));
}
async function get(url, token, { raw = false } = {}) {
let res;
try {
res = await fetch(url, { headers: token ? { Authorization: `token ${token}` } : {}, signal: AbortSignal.timeout(TIMEOUT_MS) });
} catch (e) {
throw new Error(`Git could not be reached: ${e?.message || e}`);
}
if (res.status === 404) return null;
if (res.status === 401 || res.status === 403) throw new Error('Git refused access — check the access token (or that the repository is public).');
if (!res.ok) throw new Error(`Git answered ${res.status} for ${url}`);
return raw ? res.text() : res.json();
}
/** Every v1.2.3 tag: [{ version, date }]. */
async function fetchTags(repo, token) {
const tags = [];
for (let page = 1; page <= 20; page++) {
const batch = await get(`${repo.api}/tags?limit=50&page=${page}`, token);
if (batch === null) throw new Error('The repository was not found. Check its address (and the token if it is private).');
for (const t of batch) {
const m = TAG_RE.exec(t.name || '');
if (m) tags.push({ version: m[1], date: t.commit?.created || null });
}
if (batch.length < 50) break;
}
return tags;
}
/**
* Bring the releases in line with git: add new tags, update notes and urgency from WHATS-NEW.md, and
* remove releases that have no tag. Returns { tags, added, updated, removed, latest }.
*/
async function syncReleases() {
const settings = await getSettings();
const repo = parseRepoUrl(settings.release_repo_url);
if (!repo) return { skipped: 'no repository set' };
try {
const token = await releaseRepoToken();
const tags = await fetchTags(repo, token);
if (!tags.length) throw new Error('The repository has no version tags (v1.2.3) yet.');
const newest = tags.reduce((a, b) => (compareVersions(b.version, a.version) > 0 ? b : a));
const path = (settings.release_notes_path || 'WHATS-NEW.md').replace(/^\/+/, '').split('/').map(encodeURIComponent).join('/');
const markdown = await get(`${repo.api}/raw/${path}?ref=v${newest.version}`, token, { raw: true });
const notes = parseNotes(markdown || '');
const existing = new Map((await prisma.release.findMany()).map(r => [r.version, r]));
const tagged = new Set(tags.map(t => t.version));
let added = 0;
let updated = 0;
for (const tag of tags) {
const n = notes[tag.version] || { notes: '', urgent: false };
const had = existing.get(tag.version);
if (!had) {
await prisma.release.create({ data: { version: tag.version, notes: n.notes, urgent: n.urgent, releasedAt: tag.date ? new Date(tag.date) : new Date() } });
added++;
} else {
// Releases added by hand (or from the old latest_version setting) take the tag's date.
const date = tag.date ? new Date(tag.date) : had.releasedAt;
if (had.notes !== n.notes || had.urgent !== n.urgent || date.getTime() !== new Date(had.releasedAt).getTime()) {
await prisma.release.update({ where: { id: had.id }, data: { notes: n.notes, urgent: n.urgent, releasedAt: date } });
updated++;
}
}
}
const gone = [...existing.values()].filter(r => !tagged.has(r.version)).map(r => r.id);
if (gone.length) await prisma.release.deleteMany({ where: { id: { in: gone } } });
const latest = await syncLatestVersion();
await setSettings({ release_synced_at: new Date().toISOString(), release_sync_error: markdown === null ? `${settings.release_notes_path} was not found at v${newest.version}, so there are no notes.` : '' });
return { tags: tags.length, added, updated, removed: gone.length, latest };
} catch (e) {
await setSettings({ release_sync_error: `${new Date().toISOString()} ${e.message}`.slice(0, 500) });
throw e;
}
}
module.exports = { parseRepoUrl, parseNotes, plainNotes, syncReleases };
+41
View File
@@ -0,0 +1,41 @@
/**
* Cross Events releases and their notes (Releases page). The highest version is the latest one,
* kept in the latest_version setting so alerts and the install API read it as before.
*/
const prisma = require('../config/db');
const { compareVersions } = require('./alerts');
const { setSettings } = require('./settings');
const VERSION_RE = /^\d+\.\d+\.\d+$/;
const MAX_SENT = 20;
/** Newest first. */
function sortReleases(releases) {
return [...releases].sort((a, b) => compareVersions(b.version, a.version));
}
/**
* What an install on `version` is told (§3): every release newer than it, newest first — at most
* 20, so a long-neglected install still gets a reply of sensible size.
*/
function releasesFor(releases, version) {
return sortReleases(releases)
.filter(r => !version || compareVersions(r.version, version) > 0)
.slice(0, MAX_SENT)
.map(r => ({ version: r.version, releasedAt: new Date(r.releasedAt).toISOString(), urgent: !!r.urgent, notes: r.notes || '' }));
}
/** Point latest_version at the highest release (blank when there are none). */
async function syncLatestVersion() {
const releases = await prisma.release.findMany({ select: { version: true } });
const latest = sortReleases(releases)[0]?.version || '';
await setSettings({ latest_version: latest });
return latest;
}
async function releasesForInstall(version) {
return releasesFor(await prisma.release.findMany(), version);
}
module.exports = { VERSION_RE, sortReleases, releasesFor, releasesForInstall, syncLatestVersion };
+31 -9
View File
@@ -17,29 +17,45 @@ const DEFAULTS = {
smtp_user: '',
smtp_pass: '',
smtp_from: '',
// Releases and their notes are read from git (utils/releaseSync.js) when a repo is set.
release_repo_url: 'https://c-git.crosscode.co.za/joshua/hope-events',
release_notes_path: 'WHATS-NEW.md',
release_repo_token: '',
// Written by the sync, not the Settings page.
release_synced_at: '',
release_sync_error: '',
};
// Stored encrypted and never sent to the browser: only "is one saved" (<key>_set).
const SECRETS = ['smtp_pass', 'release_repo_token'];
async function rawSettings() {
const rows = await prisma.setting.findMany();
const saved = Object.fromEntries(rows.map(r => [r.key, r.value]));
return { ...DEFAULTS, ...saved };
}
/** Settings for the Settings page: the SMTP password only as "is one saved". */
/** Settings for the Settings page: secrets (SMTP password, repo token) only as "is one saved". */
async function getSettings() {
const { smtp_pass, ...settings } = await rawSettings();
return { ...settings, smtp_pass_set: smtp_pass ? 'true' : '' };
const settings = await rawSettings();
for (const key of SECRETS) {
settings[`${key}_set`] = settings[key] ? 'true' : '';
delete settings[key];
}
return settings;
}
/**
* Save settings. A blank smtp_pass keeps the saved password (the page never has it);
* smtp_pass_clear removes it.
* Save settings. A blank secret keeps the saved one (the page never has it); <key>_clear
* removes it.
*/
async function setSettings(values) {
const input = { ...(values || {}) };
if (input.smtp_pass_clear) input.smtp_pass = '';
else if (input.smtp_pass) input.smtp_pass = encrypt(input.smtp_pass);
else delete input.smtp_pass;
for (const key of SECRETS) {
if (input[`${key}_clear`]) input[key] = '';
else if (input[key]) input[key] = encrypt(input[key]);
else delete input[key];
}
const updates = Object.entries(input).filter(([k]) => k in DEFAULTS);
for (const [key, value] of updates) {
await prisma.setting.upsert({ where: { key }, update: { value: String(value ?? '') }, create: { key, value: String(value ?? '') } });
@@ -83,4 +99,10 @@ async function importSmtpFromEnv() {
return true;
}
module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv };
/** The saved repo token, decrypted ('' when none). */
async function releaseRepoToken() {
const { release_repo_token } = await rawSettings();
return release_repo_token ? decrypt(release_repo_token) : '';
}
module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv, releaseRepoToken };
+63
View File
@@ -0,0 +1,63 @@
// Releases from git: reading the repo address and WHATS-NEW.md.
jest.mock('../src/config/db', () => ({}));
const { parseRepoUrl, parseNotes } = require('../src/utils/releaseSync');
test('the repository address becomes the Gitea API', () => {
expect(parseRepoUrl('https://c-git.crosscode.co.za/joshua/hope-events')).toEqual({ api: 'https://c-git.crosscode.co.za/api/v1/repos/joshua/hope-events', owner: 'joshua', repo: 'hope-events' });
expect(parseRepoUrl('https://c-git.crosscode.co.za/joshua/hope-events.git/').api).toBe('https://c-git.crosscode.co.za/api/v1/repos/joshua/hope-events');
expect(parseRepoUrl('https://c-git.crosscode.co.za/joshua')).toBeNull();
expect(parseRepoUrl('ftp://x/y/z')).toBeNull();
expect(parseRepoUrl('')).toBeNull();
});
describe('WHATS-NEW.md', () => {
const md = `# What's new in Cross Events
Intro text that isn't a release.
<!--
## 9.9.9
Hidden instructions are not a release.
-->
## 1.46.2 — urgent
- **See what's new** before you update, on the
Licence page.
- Uses \`code\` and [a link](https://example.com).
## [1.46.1] - 2026-10-28
Behind-the-scenes maintenance.
Nothing changes for you.
## v1.46.0 (security fix)
### Volunteers
- Rosters
- Swaps
`;
const notes = parseNotes(md);
test('one section per version; comments and the title are skipped', () => {
expect(Object.keys(notes).sort()).toEqual(['1.46.0', '1.46.1', '1.46.2']);
});
test('"urgent" or "security" in the heading marks it urgent', () => {
expect(notes['1.46.2'].urgent).toBe(true);
expect(notes['1.46.1'].urgent).toBe(false);
expect(notes['1.46.0'].urgent).toBe(true);
});
test('markup is removed, wrapped lines joined, list items kept', () => {
expect(notes['1.46.2'].notes).toBe("- See what's new before you update, on the Licence page.\n- Uses code and a link.");
expect(notes['1.46.1'].notes).toBe('Behind-the-scenes maintenance. Nothing changes for you.');
expect(notes['1.46.0'].notes).toBe('Volunteers\n- Rosters\n- Swaps');
});
test('no file means no notes', () => {
expect(parseNotes('')).toEqual({});
expect(parseNotes(null)).toEqual({});
});
});
+72
View File
@@ -0,0 +1,72 @@
// What installs are told about releases and notices (docs/hub-protocol.md §3).
jest.mock('../src/config/db', () => ({}));
const { releasesFor } = require('../src/utils/releases');
const { noticesFor, recipients, emailText } = require('../src/utils/notices');
const NOW = new Date('2026-10-28T10:00:00Z');
const at = '2026-10-20T08:00:00.000Z';
describe('releases for an install', () => {
const releases = [
{ version: '1.9.0', notes: 'Old', urgent: false, releasedAt: at },
{ version: '1.10.1', notes: '- Security fix', urgent: true, releasedAt: at },
{ version: '1.10.0', notes: '- Rosters', urgent: false, releasedAt: at },
];
test('only newer versions, newest first, compared as numbers (1.10 > 1.9)', () => {
expect(releasesFor(releases, '1.9.0').map(r => r.version)).toEqual(['1.10.1', '1.10.0']);
expect(releasesFor(releases, '1.10.1')).toEqual([]);
});
test('sends the notes and the urgent flag, nothing else', () => {
expect(releasesFor(releases, '1.10.0')).toEqual([{ version: '1.10.1', releasedAt: at, urgent: true, notes: '- Security fix' }]);
});
test('at most 20', () => {
const many = Array.from({ length: 30 }, (_, i) => ({ version: `1.${i + 1}.0`, notes: '', urgent: false, releasedAt: at }));
const sent = releasesFor(many, '1.0.0');
expect(sent).toHaveLength(20);
expect(sent[0].version).toBe('1.30.0');
});
});
describe('notices for an install', () => {
const base = { level: 'info', title: 'T', message: 'M', showBanner: true, allInstalls: true, installIds: [], startsAt: null, endsAt: null, updatedAt: at };
test('every install, or only the chosen ones', () => {
const notices = [{ ...base, id: 'all' }, { ...base, id: 'some', allInstalls: false, installIds: ['inst_2'] }];
expect(noticesFor(notices, 'inst_1', NOW).map(n => n.id)).toEqual(['all']);
expect(noticesFor(notices, 'inst_2', NOW).map(n => n.id)).toEqual(['all', 'some']);
});
test('ended and email-only notices are not sent; ones starting later are', () => {
const notices = [
{ ...base, id: 'ended', endsAt: '2026-10-28T09:00:00Z' },
{ ...base, id: 'email-only', showBanner: false },
{ ...base, id: 'later', startsAt: '2026-11-01T18:00:00Z', endsAt: '2026-11-01T20:00:00Z' },
];
expect(noticesFor(notices, 'inst_1', NOW)).toEqual([
{ id: 'later', level: 'info', title: 'T', message: 'M', startsAt: '2026-11-01T18:00:00.000Z', endsAt: '2026-11-01T20:00:00.000Z', updatedAt: at },
]);
});
});
describe('notice emails', () => {
test('to each customer email and admin contact once, skipping blanks and nonsense', () => {
const installs = [
{ customer: { email: 'office@hope.org' }, adminContact: { email: 'Jane@hope.org' } },
{ customer: { email: 'OFFICE@hope.org' }, adminContact: { email: 'jane@hope.org' } },
{ customer: { email: null }, adminContact: { email: 'not an email' } },
{ customer: { email: 'grace@grace.org' }, adminContact: null },
];
expect(recipients(installs)).toEqual(['office@hope.org', 'Jane@hope.org', 'grace@grace.org']);
});
test('the message, with the dates when there are any', () => {
expect(emailText({ message: 'Hello ' })).toBe('Hello\n\n— Cross Events');
const text = emailText({ message: 'Down for maintenance.', startsAt: '2026-11-01T18:00:00Z', endsAt: '2026-11-01T20:00:00Z' });
expect(text).toContain('From: 1 November 2026');
expect(text).toContain('Until: 1 November 2026');
});
});
+41 -2
View File
@@ -55,7 +55,9 @@ POST /api/installs/register
"installSecret": "…", // shown once; the install stores it encrypted
"licence": "<licence token>",
"heartbeatIntervalMinutes": 15,
"latestVersion": "1.41.0"
"latestVersion": "1.41.0",
"releases": [ … ], // as in the heartbeat reply (§3); Hub 1.4.0+
"notices": [ … ]
}
```
@@ -101,9 +103,30 @@ X-Hub-Signature: <hex HMAC-SHA256(installSecret, timestamp + "." + rawBody)>
"income": { "last30d": "R5 001–R20 000", "allTime": "over R100 000" }
}
}
→ 200 { "licence": "<fresh licence token>", "latestVersion": "1.42.0", "serverTime": "…" }
→ 200 {
"licence": "<fresh licence token>",
"latestVersion": "1.42.0",
"releases": [ // Hub 1.4.0+: newer than the version sent, newest first, at most 20
{ "version": "1.42.0", "releasedAt": "2026-10-27T10:00:00.000Z", "urgent": false, "notes": "- Event series\n- Fixed: …" }
],
"notices": [ // Hub 1.4.0+: the provider's banners for this install
{ "id": "…", "level": "maintenance", "title": "Planned maintenance", "message": "…",
"startsAt": "2026-11-01T16:00:00.000Z", "endsAt": "2026-11-01T16:30:00.000Z", "updatedAt": "…" }
],
"serverTime": "…"
}
```
- **`releases`** — what's new in each version, so the church can decide whether to ask for the
update. The Hub takes the versions from the Cross Events repository's `v*` tags and the notes from
its `WHATS-NEW.md`. `notes` is plain text; lines starting with `- ` are
a list. `urgent` marks security or serious bug fixes: the install shows those in red and doesn't let
admins put them off. The highest release is `latestVersion`.
- **`notices`** — banners Joshua posts on the Hub's Notices page (`level`: `info`, `maintenance` or
`warning`). Sent until `endsAt`, including ones that haven't started, so the install shows each one
from `startsAt` without waiting for a heartbeat. The install shows them to site admins and
supervisors. Notices can also be emailed; that happens on the Hub, not through the install.
- A Hub older than 1.4.0 sends neither field; the install then shows no notes and no notices.
- The signature covers the exact bytes sent. Requests more than **5 minutes** off the Hub's
clock are refused (`401 STALE_REQUEST`); a bad signature is `401 BAD_SIGNATURE`; an unknown or
released install is `404 INSTALL_NOT_FOUND` (the install should show "Reconnect to Hub").
@@ -132,6 +155,22 @@ X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3)
hour per IP). A Hub older than this section answers `404 NOT_FOUND`.
- No personal information: not who pressed the button (the Hub already has the admin contact).
### Withdrawing it
Sent when a site admin presses **Withdraw request**. Signed like the heartbeat.
```
POST /api/installs/update-request/cancel
X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3)
{ "protocolVersion": 1 }
→ 200 { "cancelled": true } // the open request was resolved, and Joshua is emailed
→ 200 { "cancelled": false } // there was no open request
```
- The Hub resolves the `update_requested` alert and records `update_request_withdrawn` in the install's
history. Rate-limited with update requests. A Hub older than 1.4.0 answers `404 NOT_FOUND`.
- **"Not now"** (no reminders until the next version) stays on the install; the Hub isn't told.
## 4. Licence token
`hel1.<payload>.<signature>` — `payload` is base64url JSON, `signature` is the base64url
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "1.3.0",
"version": "1.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "1.3.0",
"version": "1.4.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "1.3.0",
"version": "1.4.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+1 -1
View File
@@ -25,7 +25,7 @@ export default function AlertsPage() {
return (
<>
<PageTitle title="Alerts" subtitle="Checked every 5 minutes. New warnings and critical alerts are emailed once (Settings → Releases and alerts → Alert email)." />
<PageTitle title="Alerts" subtitle="Checked every 5 minutes. New warnings and critical alerts are emailed once (Settings → Alerts → Alert email)." />
<div className="mb-4 flex flex-wrap gap-2">
<button className={openOnly ? "btn-primary" : "btn-secondary"} onClick={() => setOpenOnly(true)}>Open</button>
<button className={!openOnly ? "btn-primary" : "btn-secondary"} onClick={() => setOpenOnly(false)}>Everything</button>
+3 -1
View File
@@ -3,7 +3,7 @@
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut } from "lucide-react";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone } from "lucide-react";
import { api, getToken, setToken } from "@/lib/api";
import { Logo } from "@/components/ui";
@@ -13,6 +13,8 @@ const NAV = [
{ href: "/", label: "Installs", icon: LayoutDashboard },
{ href: "/customers", label: "Customers", icon: Building2 },
{ href: "/alerts", label: "Alerts", icon: BellRing },
{ href: "/releases", label: "Releases", icon: Rocket },
{ href: "/notices", label: "Notices", icon: Megaphone },
{ href: "/settings", label: "Settings", icon: Settings },
];
+215
View File
@@ -0,0 +1,215 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { Mail, Megaphone } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { matches } from "@/lib/paging";
import type { InstallSummary, Notice, NoticeLevel } from "@/lib/types";
import { Badge, Loading, Message, PageTitle, SearchInput } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
const LEVELS: { key: NoticeLevel; label: string; hint: string }[] = [
{ key: "info", label: "Information", hint: "Blue banner" },
{ key: "maintenance", label: "Planned maintenance", hint: "Amber banner" },
{ key: "warning", label: "Important", hint: "Red banner" },
];
const LEVEL_LABEL = Object.fromEntries(LEVELS.map(l => [l.key, l.label])) as Record<NoticeLevel, string>;
// <input type="datetime-local"> works in the browser's time; the API takes ISO.
const toInput = (d: string | null) => {
if (!d) return "";
const x = new Date(d);
return new Date(x.getTime() - x.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
};
const fromInput = (v: string) => (v ? new Date(v).toISOString() : null);
type Form = { title: string; message: string; level: NoticeLevel; allInstalls: boolean; installIds: string[]; showBanner: boolean; sendEmail: boolean; startsAt: string; endsAt: string };
const empty = (): Form => ({ title: "", message: "", level: "info", allInstalls: true, installIds: [], showBanner: true, sendEmail: false, startsAt: "", endsAt: "" });
function state(n: Notice, now = Date.now()) {
if (!n.showBanner) return { label: "Email only", value: "info" as const };
if (n.endsAt && new Date(n.endsAt).getTime() <= now) return { label: "Ended", value: "info" as const };
if (n.startsAt && new Date(n.startsAt).getTime() > now) return { label: "Scheduled", value: "warning" as const };
return { label: "Showing", value: "ok" as const };
}
/** Pick every install or some of them. */
function Audience({ installs, form, setForm }: { installs: InstallSummary[]; form: Form; setForm: (f: Form) => void }) {
const [query, setQuery] = useState("");
const shown = useMemo(() => installs.filter(i => matches(query, i.name, i.url, i.customer?.name)), [installs, query]);
const toggle = (id: string) => setForm({ ...form, installIds: form.installIds.includes(id) ? form.installIds.filter(x => x !== id) : [...form.installIds, id] });
return (
<fieldset className="space-y-2">
<legend className="label">Who gets it</legend>
<div className="flex flex-wrap gap-4 text-sm">
<label className="flex items-center gap-2"><input type="radio" checked={form.allInstalls} onChange={() => setForm({ ...form, allInstalls: true })} /> Every install</label>
<label className="flex items-center gap-2"><input type="radio" checked={!form.allInstalls} onChange={() => setForm({ ...form, allInstalls: false })} /> Chosen installs ({form.installIds.length})</label>
</div>
{!form.allInstalls && (
<div className="rounded-lg border border-slate-200 p-3">
<SearchInput className="mb-2" value={query} onChange={setQuery} placeholder="Search installs" />
<div className="max-h-56 space-y-1 overflow-y-auto">
{shown.length === 0 && <p className="text-sm text-slate-500">No installs match.</p>}
{shown.map(i => (
<label key={i.id} className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={form.installIds.includes(i.id)} onChange={() => toggle(i.id)} />
<span className="font-medium">{i.customer?.name || i.name}</span>
<span className="truncate text-xs text-slate-500">{i.url}</span>
</label>
))}
</div>
</div>
)}
</fieldset>
);
}
function NoticeForm({ initial, installs, editing, busy, onSave, onCancel }: { initial: Form; installs: InstallSummary[]; editing: boolean; busy: boolean; onSave: (f: Form) => void; onCancel: () => void }) {
const [form, setForm] = useState(initial);
return (
<form onSubmit={e => { e.preventDefault(); onSave(form); }} className="space-y-4">
<div className="grid gap-3 sm:grid-cols-3">
<div className="sm:col-span-2">
<label className="label" htmlFor="n_title">Title</label>
<input id="n_title" className="input" maxLength={120} placeholder="Planned maintenance on Saturday evening" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} required />
</div>
<div>
<label className="label" htmlFor="n_level">Kind</label>
<select id="n_level" className="input" value={form.level} onChange={e => setForm({ ...form, level: e.target.value as NoticeLevel })}>
{LEVELS.map(l => <option key={l.key} value={l.key}>{l.label} — {l.hint}</option>)}
</select>
</div>
</div>
<div>
<label className="label" htmlFor="n_message">Message</label>
<textarea id="n_message" className="input min-h-28" maxLength={2000} value={form.message} onChange={e => setForm({ ...form, message: e.target.value })} required placeholder="The site will be unavailable for about 30 minutes while we update the server." />
</div>
<Audience installs={installs} form={form} setForm={setForm} />
<fieldset className="space-y-2">
<legend className="label">How</legend>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.showBanner} onChange={e => setForm({ ...form, showBanner: e.target.checked })} /> <Megaphone className="h-4 w-4 text-slate-400" /> Banner on the site for site admins and supervisors</label>
{!editing && <label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={form.sendEmail} onChange={e => setForm({ ...form, sendEmail: e.target.checked })} /> <Mail className="h-4 w-4 text-slate-400" /> Email the church now (customer email and the site&apos;s admin contact)</label>}
</fieldset>
{form.showBanner && (
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="n_starts">Show from</label>
<input id="n_starts" type="datetime-local" className="input" value={form.startsAt} onChange={e => setForm({ ...form, startsAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">Blank: straight away (within 15 minutes, at the site&apos;s next heartbeat).</p>
</div>
<div>
<label className="label" htmlFor="n_ends">Until</label>
<input id="n_ends" type="datetime-local" className="input" value={form.endsAt} onChange={e => setForm({ ...form, endsAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">Blank: until you end it.</p>
</div>
</div>
)}
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : editing ? "Save notice" : form.sendEmail ? "Create and email" : "Create notice"}</button>
<button type="button" className="btn-secondary" onClick={onCancel}>Cancel</button>
</div>
</form>
);
}
/** Messages to churches: a banner on their site and/or an email. */
export default function NoticesPage() {
const [notices, setNotices] = useState<Notice[] | null>(null);
const [installs, setInstalls] = useState<InstallSummary[]>([]);
const [msg, setMsg] = useState<Msg>(null);
const [adding, setAdding] = useState(false);
const [editing, setEditing] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(() => api<Notice[]>("/api/admin/notices").then(setNotices).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
useEffect(() => {
load();
api<InstallSummary[]>("/api/admin/installs").then(rows => setInstalls(rows.filter(i => !i.releasedAt))).catch(() => {});
}, [load]);
const installName = (id: string) => { const i = installs.find(x => x.id === id); return i ? i.customer?.name || i.name : "(removed install)"; };
const save = async (f: Form, id?: string) => {
if (!id && f.sendEmail && !confirm(`Email "${f.title}" to ${f.allInstalls ? "every church" : `${f.installIds.length} church${f.installIds.length === 1 ? "" : "es"}`} now?`)) return;
setBusy(true);
setMsg(null);
try {
const body = { title: f.title, message: f.message, level: f.level, allInstalls: f.allInstalls, installIds: f.allInstalls ? [] : f.installIds, showBanner: f.showBanner, startsAt: fromInput(f.startsAt), endsAt: fromInput(f.endsAt), ...(id ? {} : { sendEmail: f.sendEmail }) };
const n = await api<Notice>(id ? `/api/admin/notices/${id}` : "/api/admin/notices", { method: id ? "PUT" : "POST", body });
const parts = [id ? "Saved." : "Created."];
if (!id && f.sendEmail) parts.push(`Emailed ${n.emailedTo} address${n.emailedTo === 1 ? "" : "es"}.`);
if (n.showBanner) parts.push("Sites show the banner after their next heartbeat (within 15 minutes).");
setMsg({ type: "ok", text: parts.join(" ") });
setAdding(false);
setEditing(null);
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const endNow = async (n: Notice) => {
try {
await api(`/api/admin/notices/${n.id}`, { method: "PUT", body: { endsAt: new Date().toISOString() } });
setMsg({ type: "ok", text: "Ended. Sites take the banner down after their next heartbeat (within 15 minutes)." });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const remove = async (n: Notice) => {
if (!confirm(`Delete "${n.title}"?`)) return;
try {
await api(`/api/admin/notices/${n.id}`, { method: "DELETE" });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<>
<PageTitle
title="Notices"
subtitle="Tell churches about maintenance or anything else: a banner on their site for site admins and supervisors, an email, or both."
actions={!adding && <button className="btn-primary" onClick={() => { setAdding(true); setEditing(null); }}>New notice</button>}
/>
{msg && <div className="mb-4"><Message msg={msg} /></div>}
{adding && <div className="card mb-6"><h2 className="mb-3 font-semibold">New notice</h2><NoticeForm initial={empty()} installs={installs} editing={false} busy={busy} onSave={f => save(f)} onCancel={() => setAdding(false)} /></div>}
{!notices ? <Loading /> : notices.length === 0 ? <p className="text-sm text-slate-500">No notices yet.</p> : (
<div className="space-y-4">
{notices.map(n => {
const st = state(n);
return (
<div key={n.id} className="card">
{editing === n.id ? (
<NoticeForm
initial={{ title: n.title, message: n.message, level: n.level, allInstalls: n.allInstalls, installIds: n.installIds, showBanner: n.showBanner, sendEmail: false, startsAt: toInput(n.startsAt), endsAt: toInput(n.endsAt) }}
installs={installs} editing busy={busy} onSave={f => save(f, n.id)} onCancel={() => setEditing(null)}
/>
) : (
<>
<div className="mb-1 flex flex-wrap items-center gap-2">
<h2 className="font-semibold">{n.title}</h2>
<Badge value={st.value} label={st.label} />
<span className="text-xs text-slate-500">{LEVEL_LABEL[n.level]}</span>
<span className="ml-auto flex gap-2">
{st.label === "Showing" || st.label === "Scheduled" ? <button className="btn-secondary px-2 py-1 text-xs" onClick={() => endNow(n)}>End now</button> : null}
<button className="btn-secondary px-2 py-1 text-xs" onClick={() => { setEditing(n.id); setAdding(false); }}>Edit</button>
<button className="btn-danger px-2 py-1 text-xs" onClick={() => remove(n)}>Delete</button>
</span>
</div>
<p className="whitespace-pre-line text-sm text-slate-700">{n.message}</p>
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-500">
<span>To: {n.allInstalls ? "every install" : n.installIds.map(installName).join(", ")}</span>
{n.showBanner && <span>Banner: {n.startsAt ? fmtDate(n.startsAt) : "from creation"} → {n.endsAt ? fmtDate(n.endsAt) : "until ended"}</span>}
{n.emailedAt && <span>Emailed {fmtDate(n.emailedAt)} to {n.emailedTo} address{n.emailedTo === 1 ? "" : "es"}</span>}
</div>
</>
)}
</div>
);
})}
</div>
)}
</>
);
}
+1 -1
View File
@@ -49,7 +49,7 @@ export default function OverviewPage() {
return (
<>
<PageTitle title="Installs" subtitle={data.latestVersion ? `Latest release: ${data.latestVersion}` : "Set the latest release in Settings to see who is behind."} />
<PageTitle title="Installs" subtitle={data.latestVersion ? `Latest release: ${data.latestVersion}` : "Add the latest release on the Releases page to see who is behind."} />
<div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-5">
<Stat label="Installs" value={c.installs} />
<Stat label="Healthy" value={c.healthy} tone="green" />
+183
View File
@@ -0,0 +1,183 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { GitBranch, RefreshCw, ShieldAlert } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import type { Release } from "@/lib/types";
import { Badge, Loading, Message, PageTitle, ReleaseNotes } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
type Form = { version: string; notes: string; urgent: boolean; releasedAt: string };
const today = () => new Date().toISOString().slice(0, 10);
const empty = (): Form => ({ version: "", notes: "", urgent: false, releasedAt: today() });
/** Add or edit one release. */
function ReleaseForm({ initial, onSave, onCancel, busy }: { initial: Form; onSave: (f: Form) => void; onCancel?: () => void; busy: boolean }) {
const [form, setForm] = useState(initial);
return (
<form onSubmit={e => { e.preventDefault(); onSave(form); }} className="space-y-3">
<div className="grid gap-3 sm:grid-cols-3">
<div>
<label className="label" htmlFor="rel_version">Version</label>
<input id="rel_version" className="input" placeholder="1.47.0" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })} required />
</div>
<div>
<label className="label" htmlFor="rel_date">Released</label>
<input id="rel_date" type="date" className="input" value={form.releasedAt} onChange={e => setForm({ ...form, releasedAt: e.target.value })} />
</div>
<label className="flex items-center gap-2 self-end pb-2 text-sm">
<input type="checkbox" checked={form.urgent} onChange={e => setForm({ ...form, urgent: e.target.checked })} />
Urgent (security or serious bug fix)
</label>
</div>
<div>
<label className="label" htmlFor="rel_notes">What&apos;s new</label>
<textarea id="rel_notes" className="input min-h-40 font-mono" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder={"Written for the church, not for developers.\n- Volunteer rosters: plan who serves where\n- Fixed: kids tickets were offered publicly"} />
<p className="mt-1 text-xs text-slate-500">Lines starting with &quot;- &quot; show as a list. Churches see this on Site settings → Licence before they ask for the update.{form.urgent && " Urgent releases can't be put off with \"Not now\"."}</p>
</div>
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save release"}</button>
{onCancel && <button type="button" className="btn-secondary" onClick={onCancel}>Cancel</button>}
</div>
</form>
);
}
type Source = { release_repo_url: string; release_notes_path: string; release_repo_token_set: string; release_synced_at: string; release_sync_error: string };
/** Where releases come from: the git repository's tags and WHATS-NEW.md (synced every 15 minutes). */
function GitSource({ source, onSaved, setMsg }: { source: Source; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({ url: source.release_repo_url, path: source.release_notes_path || "WHATS-NEW.md", token: "", clearToken: false });
const [busy, setBusy] = useState(false);
const syncNow = async (saved = false) => {
try {
const r = await api<{ tags: number; added: number; updated: number; removed: number; latest: string | null }>("/api/admin/releases/sync", { method: "POST" });
setMsg({ type: "ok", text: `${saved ? "Saved and synced" : "Synced"}: ${r.tags} version tags, ${r.added} new, ${r.updated} updated, ${r.removed} removed. Latest is ${r.latest || "not set"}.` });
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
onSaved();
};
const save = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setMsg(null);
try {
await api("/api/admin/settings", { method: "PUT", body: { settings: { release_repo_url: form.url.trim(), release_notes_path: form.path.trim(), release_repo_token: form.token, release_repo_token_clear: form.clearToken } } });
setForm({ ...form, token: "", clearToken: false });
if (form.url.trim()) await syncNow(true);
else { setMsg({ type: "ok", text: "Saved. Releases are added by hand now." }); onSaved(); }
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setBusy(false);
};
return (
<form onSubmit={save} className="card mb-6 space-y-3">
<div className="flex flex-wrap items-center gap-2">
<GitBranch className="h-4 w-4 text-slate-400" />
<h2 className="font-semibold">From git</h2>
{source.release_repo_url && <span className="text-xs text-slate-500">Last synced {ago(source.release_synced_at || null)}</span>}
{source.release_repo_url && (
<button type="button" className="btn-secondary ml-auto px-2 py-1 text-xs" disabled={busy} onClick={async () => { setBusy(true); setMsg(null); await syncNow(); setBusy(false); }}>
<RefreshCw className={`mr-1 inline h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} /> Sync now
</button>
)}
</div>
<p className="text-sm text-slate-600">Every <code>v1.2.3</code> tag is a release, and the newest tag is the latest version. The notes come from the file below as of that tag: a <code>## 1.2.3</code> heading per version, with <code>urgent</code> or <code>security</code> in the heading for an urgent release. Checked every 15 minutes. Leave the address blank to add releases by hand.</p>
<div className="grid gap-3 sm:grid-cols-3">
<div className="sm:col-span-2"><label className="label" htmlFor="repo_url">Repository</label><input id="repo_url" className="input" placeholder="https://c-git.crosscode.co.za/joshua/hope-events" value={form.url} onChange={e => setForm({ ...form, url: e.target.value })} /></div>
<div><label className="label" htmlFor="notes_path">Notes file</label><input id="notes_path" className="input" value={form.path} onChange={e => setForm({ ...form, path: e.target.value })} /></div>
</div>
<div>
<label className="label" htmlFor="repo_token">Access token (private repositories only)</label>
<input id="repo_token" className="input" type="password" autoComplete="new-password" disabled={form.clearToken} placeholder={source.release_repo_token_set ? "Saved — leave blank to keep it" : "Not needed for a public repository"} value={form.token} onChange={e => setForm({ ...form, token: e.target.value })} />
{source.release_repo_token_set && <label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={form.clearToken} onChange={e => setForm({ ...form, token: "", clearToken: e.target.checked })} /> Remove the saved token</label>}
</div>
{source.release_sync_error && <p className="rounded-lg bg-amber-50 p-3 text-sm text-amber-900">{source.release_sync_error}</p>}
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save"}</button>
</form>
);
}
/** Cross Events versions and what's new in each. The newest is the latest version installs are offered. */
export default function ReleasesPage() {
const [releases, setReleases] = useState<Release[] | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [adding, setAdding] = useState(false);
const [editing, setEditing] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [source, setSource] = useState<Source | null>(null);
const load = useCallback(() => {
api<Release[]>("/api/admin/releases").then(setReleases).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ settings: Source }>("/api/admin/settings").then(r => setSource(r.settings)).catch(() => {});
}, []);
const fromGit = !!source?.release_repo_url;
useEffect(() => { load(); }, [load]);
const body = (f: Form) => ({ version: f.version, notes: f.notes, urgent: f.urgent, releasedAt: f.releasedAt ? `${f.releasedAt}T12:00:00+02:00` : null });
const save = async (f: Form, id?: string) => {
setBusy(true);
setMsg(null);
try {
const r = await api<{ latestVersion: string | null }>(id ? `/api/admin/releases/${id}` : "/api/admin/releases", { method: id ? "PUT" : "POST", body: body(f) });
setMsg({ type: "ok", text: `Saved. The latest version is ${r.latestVersion || "not set"}; installs see it with their next heartbeat (within 15 minutes).` });
setAdding(false);
setEditing(null);
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const remove = async (r: Release) => {
if (!confirm(`Delete release ${r.version}? Installs stop being offered it${releases?.[0]?.id === r.id ? ", and the version before it becomes the latest" : ""}.`)) return;
try {
const res = await api<{ latestVersion: string | null }>(`/api/admin/releases/${r.id}`, { method: "DELETE" });
setMsg({ type: "ok", text: `Deleted. The latest version is ${res.latestVersion || "not set"}.` });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<>
<PageTitle
title="Releases"
subtitle="Each Cross Events version and what's new in it. The newest is the latest version: installs on an older one see “Update available” with the notes for every version they'd get."
actions={!adding && !fromGit && source && <button className="btn-primary" onClick={() => { setAdding(true); setEditing(null); }}>Add release</button>}
/>
{msg && <div className="mb-4"><Message msg={msg} /></div>}
{source && <GitSource key={source.release_synced_at + source.release_repo_url} source={source} onSaved={load} setMsg={setMsg} />}
{adding && <div className="card mb-6"><h2 className="mb-3 font-semibold">New release</h2><ReleaseForm initial={empty()} busy={busy} onSave={f => save(f)} onCancel={() => setAdding(false)} /></div>}
{!releases ? <Loading /> : releases.length === 0 ? <p className="text-sm text-slate-500">No releases yet. Add the version installs should be on.</p> : (
<div className="space-y-4">
{releases.map((r, i) => (
<div key={r.id} className="card">
{editing === r.id ? (
<ReleaseForm initial={{ version: r.version, notes: r.notes, urgent: r.urgent, releasedAt: r.releasedAt.slice(0, 10) }} busy={busy} onSave={f => save(f, r.id)} onCancel={() => setEditing(null)} />
) : (
<>
<div className="mb-2 flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold">{r.version}</h2>
{i === 0 && <Badge value="ok" label="Latest" />}
{r.urgent && <span className="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 ring-1 ring-inset ring-red-200"><ShieldAlert className="h-3 w-3" /> Urgent</span>}
<span className="text-xs text-slate-500">{fmtDate(r.releasedAt, false)} · {r.installs} install{r.installs === 1 ? "" : "s"} on it</span>
{!fromGit && (
<span className="ml-auto flex gap-2">
<button className="btn-secondary px-2 py-1 text-xs" onClick={() => { setEditing(r.id); setAdding(false); }}>Edit</button>
<button className="btn-danger px-2 py-1 text-xs" onClick={() => remove(r)}>Delete</button>
</span>
)}
</div>
<ReleaseNotes notes={r.notes} />
</>
)}
</div>
))}
</div>
)}
</>
);
}
+3 -2
View File
@@ -1,6 +1,7 @@
"use client";
import React, { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { api, errorText, setToken } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
@@ -11,7 +12,6 @@ type AuditRow = { id: string; action: string; target: string | null; metadata: u
type Msg = { type: "ok" | "err"; text: string } | null;
const FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "latest_version", label: "Latest Cross Events release", hint: "e.g. 1.41.0 — installs on an older version show as behind, and see \"Update available\"." },
{ key: "alert_email", label: "Alert email", hint: "Where new alerts are sent.", type: "email" },
{ key: "offline_minutes", label: "Offline after (minutes without a heartbeat)", hint: "Default 60.", type: "number" },
{ key: "backup_max_age_hours", label: "Backup too old after (hours)", hint: "Default 48.", type: "number" },
@@ -22,7 +22,7 @@ const FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
type Tab = "alerts" | "email" | "security" | "audit";
const TABS: { key: Tab; label: string }[] = [
{ key: "alerts", label: "Releases and alerts" },
{ key: "alerts", label: "Alerts" },
{ key: "email", label: "Email" },
{ key: "security", label: "Login and security" },
{ key: "audit", label: "Audit log" },
@@ -122,6 +122,7 @@ export default function SettingsPage() {
<div role="tabpanel" id={`panel-${tab}`} aria-labelledby={`tab-${tab}`}>
{tab === "alerts" && (
<form onSubmit={save} className="card max-w-2xl space-y-4">
<p className="text-sm text-slate-600">The latest Cross Events version is the newest one on the <Link href="/releases" className="text-indigo-700 hover:underline">Releases</Link> page{settings.latest_version ? ` (now ${settings.latest_version})` : ""}.</p>
{FIELDS.map(f => (
<div key={f.key}>
<label className="label" htmlFor={f.key}>{f.label}</label>
+23
View File
@@ -119,3 +119,26 @@ export function Tabs<K extends string>({ tabs, active, onChange }: { tabs: { key
</div>
);
}
/** Release notes as the installs show them: lines starting with "- " are a list, the rest paragraphs. */
export function ReleaseNotes({ notes, className = "" }: { notes: string; className?: string }) {
const blocks: ({ list: false; text: string } | { list: true; items: string[] })[] = [];
for (const raw of notes.split(/\r?\n/)) {
const line = raw.trim();
if (!line) continue;
const item = /^[-*•]\s+(.*)$/.exec(line);
const last = blocks[blocks.length - 1];
if (item) {
if (last?.list) last.items.push(item[1]);
else blocks.push({ list: true, items: [item[1]] });
} else blocks.push({ list: false, text: line });
}
if (!blocks.length) return <p className={`text-sm italic text-slate-400 ${className}`}>No notes.</p>;
return (
<div className={`space-y-2 text-sm text-slate-700 ${className}`}>
{blocks.map((b, i) => (b.list
? <ul key={i} className="list-disc space-y-0.5 pl-5">{b.items.map((t, j) => <li key={j}>{t}</li>)}</ul>
: <p key={i}>{b.text}</p>))}
</div>
);
}
+18
View File
@@ -64,3 +64,21 @@ export type Stats = {
};
export type InstallEvent = { id: string; type: string; level: Problem["level"]; message: string; createdAt: string; resolvedAt: string | null; install?: { id: string; name: string; url: string } };
export type Release = { id: string; version: string; notes: string; urgent: boolean; releasedAt: string; installs: number };
export type NoticeLevel = "info" | "maintenance" | "warning";
export type Notice = {
id: string;
title: string;
message: string;
level: NoticeLevel;
allInstalls: boolean;
installIds: string[];
showBanner: boolean;
startsAt: string | null;
endsAt: string | null;
emailedAt: string | null;
emailedTo: number;
createdAt: string;
};