diff --git a/CHANGELOG.md b/CHANGELOG.md index 41ee437..2984f7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,7 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`). product licence. - `npm run check:hub2`: before deploying 2.0, lists customers with two open licences (the 2.0 migration stops on them, naming them). Run it against production first. -- `@crosscode/contracts` 1.0.0, committed as `backend/vendor/crosscode-contracts-1.0.0.tgz`. +- `@crosscode/contracts`, committed as `backend/vendor/crosscode-contracts-.tgz` (1.1.0). - **Protocol v2** (step 2) next to v1 (`utils/protocol.js`; `/api/public-key` lists `[1, 2]`): register and heartbeat say which `product` they are (it must match the licence, else `409 WRONG_PRODUCT`), register sends the install's public key, the heartbeat's stats are per @@ -30,6 +30,19 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`). as before. Tests put every contract sample through the routes and check the replies against the contract. - Licence tokens carry `customerId` and `product` (Cross Events 2.1 ignores them). +- **Releases per product** (step 3): each product has its own releases and latest version (an + install is offered its own product's releases and shows as behind against its own latest). + **Release sources** on the Releases page: per product, one or more repositories with a tag prefix + and a notes file. The defaults: every product from `crosscode-platform` (`events@1.2.3`, + `accounts@…`, `website@…`, `app@…`, notes in `apps//WHATS-NEW.md`) plus Cross Events + before the move from the repository set until now (`v1.2.3` tags). `contracts@` tags are ignored. + A product's releases are only removed when every one of its sources was read and found tags, so + an unreachable source never wipes releases; a product with no source is managed by hand. +- **Requirements between products**: `— requires accounts 1.2.0` in a release's notes heading. + Request update answers `409 REQUIREMENT_NOT_MET` (saying what's needed) until the church's + install of that product runs that version or later, counting every release the update would + bring. The install page shows what's missing; the Releases page shows each release's needs. + Protocol v2 replies carry them (`requires`, contracts 1.1.0); v1 replies are unchanged. ### Changed @@ -37,9 +50,8 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`). licence-token prefix stays: it's part of the protocol). - Installs register with protocol v1 only with a Cross Events licence (`409 WRONG_PRODUCT` otherwise); the other products register with protocol v2 (step 2). Only Cross Events licences - can be invoiced until billing per customer (step 4). Until releases per product (step 3), only - Cross Events installs are told about releases or shown as behind. -- Migration `20261104132032_products`. + can be invoiced until billing per customer (step 4). +- Migrations `20261104132032_products`, `20261104150000_releases_per_product`. ## [1.7.0] - 2026-11-03 diff --git a/backend/package-lock.json b/backend/package-lock.json index cc008c8..0940b26 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -10,7 +10,7 @@ "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.0.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.1.0.tgz", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", @@ -609,9 +609,9 @@ "license": "MIT" }, "node_modules/@crosscode/contracts": { - "version": "1.0.0", - "resolved": "file:vendor/crosscode-contracts-1.0.0.tgz", - "integrity": "sha512-NcilXx9mVmHNsQvIBNNH5rPBmNKYKBSO8bLmC5czLNIlSiQQz95571qPYx+PMXvibAw7TX1LPpO8TKgz5f0dHA==", + "version": "1.1.0", + "resolved": "file:vendor/crosscode-contracts-1.1.0.tgz", + "integrity": "sha512-k/7fFcjNh79B4la+GUxzh/buFtnM6G+5JPxxKvhXNdlIXvon/45VErzEKYsnDnL8pF3fQHldJcfeFtLm52Q47A==", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/backend/package.json b/backend/package.json index c65936d..3eb3597 100644 --- a/backend/package.json +++ b/backend/package.json @@ -20,7 +20,7 @@ }, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.0.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.1.0.tgz", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", diff --git a/backend/prisma/migrations/20261104150000_releases_per_product/migration.sql b/backend/prisma/migrations/20261104150000_releases_per_product/migration.sql new file mode 100644 index 0000000..7d6b19e --- /dev/null +++ b/backend/prisma/migrations/20261104150000_releases_per_product/migration.sql @@ -0,0 +1,12 @@ +-- Hub 2.0: releases per product. Every release before 2.0 is a Cross Events release; the version is +-- now unique per product. + +-- DropIndex +DROP INDEX "Release_version_key"; + +-- AlterTable +ALTER TABLE "Release" ADD COLUMN "product" "Product" NOT NULL DEFAULT 'events', +ADD COLUMN "requires" JSONB NOT NULL DEFAULT '[]'; + +-- CreateIndex +CREATE UNIQUE INDEX "Release_product_version_key" ON "Release"("product", "version"); diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index f610831..e03ab42 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -241,13 +241,21 @@ model Setting { // 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 + // Hub 2.0: releases are per product (existing ones are Cross Events), from the product's release + // sources (Releases page; utils/releaseSync.js). + product Product @default(events) + version String // Plain text; lines starting with "- " show as a list. notes String @default("") urgent Boolean @default(false) + // Hub 2.0: sibling versions this release needs, from "— requires accounts 1.2.0" in its + // WHATS-NEW.md heading: [{ product, version }]. Request update is refused until they're met. + requires Json @default("[]") releasedAt DateTime @default(now()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt + + @@unique([product, version]) } enum NoticeLevel { diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index 36b375b..cbfab4a 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -11,9 +11,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 { VERSION_RE, sortReleases, syncLatestVersion, latestVersions, unmetRequirementsFor } = require('../utils/releases'); const { emailNotice } = require('../utils/notices'); -const { parseRepoUrl, syncReleases } = require('../utils/releaseSync'); +const { parseRepoUrl, syncReleases, releaseSources, cleanSources } = require('../utils/releaseSync'); const ai = require('../utils/ai'); const { AI_MODELS } = require('../utils/aiModels'); @@ -37,9 +37,10 @@ function dateOrNull(v) { return d; } -// The health of an install at a glance, for lists. -function summary(install, settings, now = new Date()) { - const current = problems(install, settings, now); +// 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, @@ -48,8 +49,8 @@ function summary(install, settings, now = new Date()) { url: install.url, customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null, version: install.version, - // Releases are Cross Events' until releases per product (Hub 2.0 step 3). - behind: !!(install.product === 'events' && settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0), + 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, @@ -61,16 +62,17 @@ function summary(install, settings, now = new Date()) { // ─── Dashboard ──────────────────────────────────────────────────────────────── router.get('/dashboard', wrap(async (req, res) => { - const settings = await getSettings(); + 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)); + const rows = installs.map(i => summary(i, settings, latest)); const [customers, licences, openAlerts] = await Promise.all([ prisma.customer.count(), prisma.licence.groupBy({ by: ['status'], _count: { _all: true } }), prisma.installEvent.count({ where: { resolvedAt: null, level: { not: 'info' } } }), ]); res.json({ - latestVersion: settings.latest_version || null, + latestVersion: latest.events || null, + latestVersions: latest, counts: { installs: rows.length, healthy: rows.filter(r => r.status === 'ok').length, @@ -198,13 +200,13 @@ router.post('/licences/:id/release', wrap(async (req, res) => { // ─── Installs ───────────────────────────────────────────────────────────────── router.get('/installs', wrap(async (req, res) => { - const settings = await getSettings(); + 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))); + res.json(installs.map(i => summary(i, settings, latest))); })); router.get('/installs/:id', wrap(async (req, res) => { - const settings = await getSettings(); + 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 } }, @@ -222,8 +224,17 @@ router.get('/installs/:id', wrap(async (req, res) => { // What the install would be told right now, for checking. licence = { ...install.licence, tokenPreview: licenceToken.buildPayload(install.licence, install, install.customer.name) }; } - const [aiStatus, aiMonths, aiHelpers] = await Promise.all([ai.statusFor(install), ai.usageByMonth(install.id), ai.usageByHelper(install.id)]); - res.json({ ...safe, licence, summary: summary(install, settings), heartbeats, ai: { status: aiStatus, months: aiMonths, helpers: aiHelpers } }); + 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 }, + }); })); router.put('/installs/:id', wrap(async (req, res) => { @@ -248,22 +259,35 @@ router.get('/audit', wrap(async (req, res) => { })); // ─── 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. +// 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: { version: true } }), + prisma.install.findMany({ where: { releasedAt: null }, select: { product: true, 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 }))); + 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.'); @@ -275,12 +299,15 @@ function releaseData(body, { partial = false } = {}) { 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.'); +// 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 (!parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Set the git repository first.'); + if (!releaseSources(await getSettings()).length) throw bad('Add a release source first.'); let result; try { result = await syncReleases(); @@ -292,34 +319,39 @@ router.post('/releases/sync', wrap(async (req, res) => { })); const releaseError = e => { - if (e.code === 'P2002') throw bad('There is already a release with that version.', 409); + 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) => { - await manualReleases(); - const release = await prisma.release.create({ data: releaseData(req.body) }).catch(releaseError); + 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, { version: release.version, urgent: release.urgent }); - res.status(201).json({ release, latestVersion: latest || null }); + 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) => { - await manualReleases(); + 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: req.params.id }, data }).catch(releaseError); + const release = await prisma.release.update({ where: { id: existing.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 }); + 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) => { - await manualReleases(); - const release = await prisma.release.delete({ where: { id: req.params.id } }).catch(releaseError); + 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, { version: release.version }); - res.json({ latestVersion: latest || null }); + await audit(req, 'release_deleted', release.id, { product: release.product, version: release.version }); + res.json({ latestVersion: latest[release.product] || null }); })); // ─── Notices ────────────────────────────────────────────────────────────────── @@ -394,7 +426,8 @@ router.delete('/notices/:id', wrap(async (req, res) => { // ─── Settings ───────────────────────────────────────────────────────────────── router.get('/settings', wrap(async (req, res) => { - res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured(), aiModels: AI_MODELS }); + 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']; @@ -433,6 +466,11 @@ router.put('/settings', wrap(async (req, res) => { 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(); diff --git a/backend/src/routes/installApi.js b/backend/src/routes/installApi.js index 18d46cf..7448504 100644 --- a/backend/src/routes/installApi.js +++ b/backend/src/routes/installApi.js @@ -18,7 +18,7 @@ const { getSettings } = require('../utils/settings'); const { compareVersions } = require('../utils/alerts'); const { requestMessage, requestedVersionOf, isOutdated } = require('../utils/updateRequests'); const { sendMail } = require('../utils/mail'); -const { releasesForInstall } = require('../utils/releases'); +const { releasesForInstall, latestVersions, unmetRequirementsFor, requirementMessage } = require('../utils/releases'); const { noticesForInstall } = require('../utils/notices'); const ai = require('../utils/ai'); const { PRODUCT_NAMES } = require('../utils/products'); @@ -55,12 +55,12 @@ function cleanUrl(url) { } /** - * Releases and the latest version are Cross Events' until releases per product (Hub 2.0 step 3): - * other products are told nothing rather than Events versions. + * The install's product's latest version and the releases newer than `version` (Hub 2.0: per + * product). v2 replies carry each release's requirements; v1 replies are as before. */ -async function releaseInfo(install, version, settings) { - if (install.product !== 'events') return { latestVersion: null, releases: [] }; - return { latestVersion: settings.latest_version || null, releases: await releasesForInstall(version) }; +async function releaseInfo(install, version, { v2 = false } = {}) { + const latest = (await latestVersions())[install.product] || null; + return { latestVersion: latest, releases: await releasesForInstall(install.product, version, { withRequires: v2 }) }; } async function tokenFor(install) { @@ -152,13 +152,12 @@ router.post('/installs/register', registerLimiter, async (req, res) => { : await prisma.install.create({ data: { ...data, product: licence.product, customerId: licence.customerId, licenceId: licence.id } }); await prisma.installEvent.create({ data: { installId: install.id, type: 'registered', level: 'info', message: `${licence.install ? 'Re-registered' : 'Registered'} from ${url} (version ${install.version || '?'})`, resolvedAt: new Date() } }); - const settings = await getSettings(); res.status(201).json({ installId: install.id, installSecret: secret, licence: await tokenFor(install), heartbeatIntervalMinutes: HEARTBEAT_MINUTES, - ...(await releaseInfo(install, install.version, settings)), + ...(await releaseInfo(install, install.version, { v2 })), notices: await noticesForInstall(install.id), ...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}), }); @@ -193,10 +192,9 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => { } } - const settings = await getSettings(); res.json({ licence: await tokenFor(install), - ...(await releaseInfo(install, version || install.version, settings)), + ...(await releaseInfo(install, version || install.version, { v2 })), notices: await noticesForInstall(install.id, now), ...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}), serverTime: now.toISOString(), @@ -217,11 +215,16 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) = if (!body) return; const settings = await getSettings(); - const latest = (await releaseInfo(install, null, settings)).latestVersion; + const latest = (await latestVersions())[install.product] || null; const current = str(body.version, 40) || install.version; if (!latest || compareVersions(current, latest) >= 0) { return fail(res, 409, 'UP_TO_DATE', 'This site already runs the latest version.'); } + // Hub 2.0: the update may need the church's other products updated first. + const unmet = await unmetRequirementsFor({ ...install, version: current }, latest); + if (unmet.length) { + return res.status(409).json({ code: 'REQUIREMENT_NOT_MET', message: `This update needs another product first. ${requirementMessage(unmet)}`, requirements: unmet }); + } const customerName = async () => (await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } }))?.name || install.name; const link = `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`; diff --git a/backend/src/utils/alerts.js b/backend/src/utils/alerts.js index c33bd07..77a0f75 100644 --- a/backend/src/utils/alerts.js +++ b/backend/src/utils/alerts.js @@ -70,15 +70,27 @@ function problems(install, settings, now = new Date()) { else if (left <= s.expiryDays * DAY) out.push({ type: 'licence_expiring', level: 'warning', message: `Licence expires ${new Date(lic.expiresAt).toISOString().slice(0, 10)}` }); } - if (settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0) { - out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${settings.latest_version}` }); + // Hub 2.0: the latest version of the install's product (settings.latest_versions, a map); before + // that, latest_version was Cross Events'. + const latest = settings.latest_versions ? settings.latest_versions[install.product || 'events'] : settings.latest_version; + if (latest && install.version && compareVersions(install.version, latest) < 0) { + out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${latest}` }); } return out; } /** Run the checks for every install: open new alerts (emailed unless info), resolve cleared ones. */ +/** The latest version of each product ({ events: '2.1.1', … }), read here rather than from releases.js (which needs this file). */ +async function latestVersionsNow() { + const out = {}; + for (const r of await prisma.release.findMany({ select: { product: true, version: true } })) { + if (!out[r.product] || compareVersions(r.version, out[r.product]) > 0) out[r.product] = r.version; + } + return out; +} + async function runAlerts(now = new Date()) { - const settings = await getSettings(); + const settings = { ...(await getSettings()), latest_versions: await latestVersionsNow() }; const installs = await prisma.install.findMany({ where: { releasedAt: null }, include: { licence: true, customer: { select: { name: true } }, events: { where: { resolvedAt: null } } }, diff --git a/backend/src/utils/releaseSync.js b/backend/src/utils/releaseSync.js index 46ba5aa..daa5640 100644 --- a/backend/src/utils/releaseSync.js +++ b/backend/src/utils/releaseSync.js @@ -1,18 +1,24 @@ /** - * 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 on its default branch ("## 1.2.3" sections; - * "urgent" or "security" in the heading marks an urgent release). Notes only attach to tagged - * versions, so a section written ahead of a release stays hidden until it's tagged, and a note can be - * corrected after release without a new version. 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. + * Releases from git (Gitea), per product (Hub 2.0). Each product has one or more release sources + * (Releases page): a repository, a tag prefix and a notes file. Every tag `1.2.3` is a + * release of that product, dated by its commit; the notes come from the notes file on the + * repository's default branch ("## 1.2.3" sections; "urgent" or "security" in the heading marks an + * urgent release, "requires accounts 1.2.0" a requirement). Notes only attach to tagged versions, + * so a section written ahead of a release stays hidden until it's tagged, and a note can be + * corrected after release without a new version. Runs every 15 minutes and from "Sync now". + * + * A product's releases are the tags of all its sources. Releases of a product are only removed + * when every one of its sources was read and at least one tag was found, so an unreachable git + * server (or a mistyped address) never wipes releases. A product with no source is managed by hand. */ const prisma = require('../config/db'); const { getSettings, setSettings, releaseRepoToken } = require('./settings'); const { syncLatestVersion } = require('./releases'); +const { PRODUCTS, PRODUCT_NAMES, isProduct } = require('./products'); const TIMEOUT_MS = 20000; -const TAG_RE = /^v?(\d+\.\d+\.\d+)$/; +const PLATFORM_REPO = 'https://c-git.crosscode.co.za/joshua/crosscode-platform'; /** https://git.example.com/owner/repo(.git) → { api, owner, repo }, or null. */ function parseRepoUrl(url) { @@ -27,6 +33,61 @@ function parseRepoUrl(url) { } } +/** + * The default sources: every product from the platform monorepo (`events@1.2.3`, `accounts@…`, + * with notes in `apps//WHATS-NEW.md`), plus Cross Events before the move, from the + * repository set before Hub 2.0 (`release_repo_url`, `v1.2.3` tags). + */ +function defaultSources(settings = {}) { + const platform = product => ({ product, repo: PLATFORM_REPO, tagPrefix: `${product}@`, notesPath: `apps/${product}/WHATS-NEW.md` }); + const legacy = parseRepoUrl(settings.release_repo_url) + ? [{ product: 'events', repo: String(settings.release_repo_url).trim(), tagPrefix: 'v', notesPath: settings.release_notes_path || 'WHATS-NEW.md' }] + : []; + return [platform('events'), ...legacy, platform('accounts'), platform('website'), platform('app')]; +} + +const bad = message => Object.assign(new Error(message), { status: 400 }); + +/** Checked and tidied sources from the Releases page. Throws (status 400) on a bad one. */ +function cleanSources(list) { + if (!Array.isArray(list)) throw bad('Release sources must be a list.'); + if (list.length > 20) throw bad('At most 20 release sources.'); + const seen = new Set(); + return list.map((s, i) => { + const n = `Source ${i + 1}`; + if (!isProduct(s?.product)) throw bad(`${n}: choose a product.`); + const repo = String(s.repo || '').trim(); + if (!parseRepoUrl(repo)) throw bad(`${n}: the repository address looks like https://git.example.com/owner/repo.`); + const tagPrefix = String(s.tagPrefix ?? '').trim(); + if (!/^[A-Za-z0-9._@/-]{0,40}$/.test(tagPrefix)) throw bad(`${n}: the tag prefix can only have letters, digits and . _ @ / -.`); + const notesPath = String(s.notesPath || 'WHATS-NEW.md').trim().replace(/^\/+/, ''); + if (!notesPath || notesPath.includes('..') || notesPath.length > 200) throw bad(`${n}: give the notes file's path in the repository.`); + const key = `${parseRepoUrl(repo).api}#${tagPrefix}`; + if (seen.has(key)) throw bad(`${n}: the same repository and tag prefix are listed twice.`); + seen.add(key); + return { product: s.product, repo, tagPrefix, notesPath }; + }); +} + +/** The sources in use: the saved list (release_sources), or the defaults when none is saved. */ +function releaseSources(settings = {}) { + const raw = String(settings.release_sources || '').trim(); + if (!raw) return defaultSources(settings); + try { + return cleanSources(JSON.parse(raw)); + } catch { + return defaultSources(settings); + } +} + +const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/** The tag pattern for a prefix: `v` also accepts a bare 1.2.3 (as before Hub 2.0). */ +function tagPattern(prefix) { + if (prefix === 'v') return /^v?(\d+\.\d+\.\d+)$/; + return new RegExp(`^${escapeRegExp(prefix)}(\\d+\\.\\d+\\.\\d+)$`); +} + /** Markdown to the plain notes installs show: list lines stay "- ", the rest loses its markup. */ function plainNotes(lines) { const out = []; @@ -50,9 +111,27 @@ function plainNotes(lines) { return out.join('\n').replace(/\n{3,}/g, '\n\n').trim(); } +const REQUIREMENT_RE = new RegExp(`\\b(${PRODUCTS.join('|')})\\s+v?(\\d+\\.\\d+\\.\\d+)`, 'gi'); + /** - * 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 "## ". + * What a heading needs: "— requires accounts 1.2.0, website 1.1.0 — urgent" → + * [{ product: 'accounts', version: '1.2.0' }, { product: 'website', version: '1.1.0' }]. + */ +function parseRequirements(heading) { + const at = String(heading || '').search(/\brequires?\b/i); + if (at < 0) return []; + const out = []; + for (const m of heading.slice(at).matchAll(REQUIREMENT_RE)) { + const product = m[1].toLowerCase(); + if (!out.some(r => r.product === product)) out.push({ product, version: m[2] }); + } + return out; +} + +/** + * The sections of a notes file: { "1.46.2": { notes, urgent, requires } }. A section is a + * "## 1.46.2" heading (optionally "[1.46.2]", "v1.46.2", a date, "— urgent" or "— requires + * accounts 1.2.0" after it) up to the next "## ". */ function parseNotes(markdown) { const text = String(markdown || '').replace(//g, ''); @@ -62,14 +141,16 @@ function parseNotes(markdown) { 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; + current = v + ? { version: v[1], urgent: /\b(urgent|security)\b/i.test(heading[1]), requires: parseRequirements(heading[1].slice(v.index + v[0].length)), 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 }])); + return Object.fromEntries(Object.values(sections).map(s => [s.version, { notes: plainNotes(s.lines), urgent: s.urgent, requires: s.requires }])); } async function get(url, token, { raw = false } = {}) { @@ -85,65 +166,114 @@ async function get(url, token, { raw = false } = {}) { return raw ? res.text() : res.json(); } -/** Every v1.2.3 tag: [{ version, date }]. */ +/** Every tag of a repository: [{ name, 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 }); - } + for (const t of batch) if (t?.name) tags.push({ name: t.name, date: t.commit?.created || null }); if (batch.length < 50) break; } return tags; } +const sameRequires = (a, b) => JSON.stringify(a || []) === JSON.stringify(b || []); +const sourceLabel = s => `${PRODUCT_NAMES[s.product]} (${parseRepoUrl(s.repo)?.repo || s.repo}, ${s.tagPrefix || 'no prefix'}1.2.3)`; + /** - * 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 }. + * Read every source: { found: { product: Map(version → { date, notes, urgent, requires }) }, + * failed: Set(product), problems: [message], counts: [{ source, tags }] }. A repository's tags and + * notes files are fetched once per sync, however many sources use them. + */ +async function readSources(sources, token) { + const found = {}; + const failed = new Set(); + const problems = []; + const counts = []; + const tagCache = new Map(); + const notesCache = new Map(); + for (const source of sources) { + try { + const repo = parseRepoUrl(source.repo); + if (!tagCache.has(repo.api)) tagCache.set(repo.api, fetchTags(repo, token)); + const pattern = tagPattern(source.tagPrefix); + const tags = (await tagCache.get(repo.api)).map(t => ({ ...t, m: pattern.exec(t.name) })).filter(t => t.m); + let notes = {}; + if (tags.length) { + const url = `${repo.api}/raw/${source.notesPath.split('/').map(encodeURIComponent).join('/')}`; + if (!notesCache.has(url)) notesCache.set(url, get(url, token, { raw: true })); + const markdown = await notesCache.get(url); + if (markdown === null) problems.push(`${sourceLabel(source)}: ${source.notesPath} was not found on the default branch, so there are no notes.`); + notes = parseNotes(markdown || ''); + } + const map = found[source.product] || (found[source.product] = new Map()); + for (const t of tags) { + const version = t.m[1]; + // The first source listed wins if two tag the same version. + if (map.has(version)) continue; + const n = notes[version] || { notes: '', urgent: false, requires: [] }; + map.set(version, { date: t.date, notes: n.notes, urgent: n.urgent, requires: n.requires.filter(r => r.product !== source.product) }); + } + counts.push({ source: sourceLabel(source), tags: tags.length }); + } catch (e) { + failed.add(source.product); + problems.push(`${sourceLabel(source)}: ${e.message}`); + } + } + return { found, failed, problems, counts }; +} + +/** + * Bring each product's releases in line with its sources: add new tags, update notes, urgency and + * requirements, and remove releases that have no tag (only when all the product's sources were + * read and found tags). Returns { sources, added, updated, removed, latest, problems }; throws when + * no source could be read at all. */ 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 path = (settings.release_notes_path || 'WHATS-NEW.md').replace(/^\/+/, '').split('/').map(encodeURIComponent).join('/'); - const markdown = await get(`${repo.api}/raw/${path}`, token, { raw: true }); - const notes = parseNotes(markdown || ''); + const sources = releaseSources(settings); + if (!sources.length) return { skipped: 'no release sources' }; + const { found, failed, problems, counts } = await readSources(sources, await releaseRepoToken()); + if (counts.length === 0) { + await setSettings({ release_sync_error: `${new Date().toISOString()} ${problems.join(' · ')}`.slice(0, 2000) }); + throw new Error(problems.join(' · ')); + } - 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); + let added = 0; + let updated = 0; + let removed = 0; + for (const product of new Set(sources.map(s => s.product))) { + const tagged = found[product] || new Map(); + const existing = new Map((await prisma.release.findMany({ where: { product } })).map(r => [r.version, r])); + for (const [version, t] of tagged) { + const had = existing.get(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() } }); + await prisma.release.create({ data: { product, version, notes: t.notes, urgent: t.urgent, requires: t.requires, releasedAt: t.date ? new Date(t.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 } }); + const date = t.date ? new Date(t.date) : had.releasedAt; + if (had.notes !== t.notes || had.urgent !== t.urgent || !sameRequires(had.requires, t.requires) || date.getTime() !== new Date(had.releasedAt).getTime()) { + await prisma.release.update({ where: { id: had.id }, data: { notes: t.notes, urgent: t.urgent, requires: t.requires, releasedAt: date } }); updated++; } } } + if (failed.has(product)) continue; + if (!tagged.size) { + if (existing.size) problems.push(`${PRODUCT_NAMES[product]}: no version tags found in its sources, so its ${existing.size} release(s) were kept. Check the sources.`); + continue; + } 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 on the default branch, 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; + if (gone.length) { + await prisma.release.deleteMany({ where: { id: { in: gone } } }); + removed += gone.length; + } } + const latest = await syncLatestVersion(); + await setSettings({ release_synced_at: new Date().toISOString(), release_sync_error: problems.join('\n').slice(0, 2000) }); + return { sources: counts, added, updated, removed, latest, problems }; } -module.exports = { parseRepoUrl, parseNotes, plainNotes, syncReleases }; +module.exports = { PLATFORM_REPO, parseRepoUrl, parseNotes, parseRequirements, plainNotes, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases }; diff --git a/backend/src/utils/releases.js b/backend/src/utils/releases.js index e7b79b8..c3b7aaf 100644 --- a/backend/src/utils/releases.js +++ b/backend/src/utils/releases.js @@ -1,11 +1,17 @@ /** - * 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. + * Releases per product (Hub 2.0) and their notes (Releases page). The highest version of a product + * is its latest. `latest_version` keeps the Cross Events latest for older code paths and the + * Settings page. + * + * Requirements: a release can need a minimum version of a sibling product (`requires`, from + * "— requires accounts 1.2.0" in WHATS-NEW.md). An install can't ask for an update until the + * church's install of each required product runs that version or later. */ const prisma = require('../config/db'); const { compareVersions } = require('./alerts'); const { setSettings } = require('./settings'); +const { PRODUCT_NAMES } = require('./products'); const VERSION_RE = /^\d+\.\d+\.\d+$/; const MAX_SENT = 20; @@ -15,27 +21,90 @@ function sortReleases(releases) { return [...releases].sort((a, b) => compareVersions(b.version, a.version)); } +const requirementsOf = r => (Array.isArray(r.requires) ? r.requires.filter(q => q && q.product && VERSION_RE.test(q.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. + * 20, so a long-neglected install still gets a reply of sensible size. `withRequires` (protocol v2) + * adds each release's requirements (contracts 1.1.0); v1 replies stay as they were. */ -function releasesFor(releases, version) { +function releasesFor(releases, version, { withRequires = false } = {}) { 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 || '' })); + .map(r => { + const out = { version: r.version, releasedAt: new Date(r.releasedAt).toISOString(), urgent: !!r.urgent, notes: r.notes || '' }; + const requires = requirementsOf(r); + return withRequires && requires.length ? { ...out, requires } : out; + }); } -/** 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 }); +/** { events: '2.1.1', website: '1.0.0', … } — the highest release of each product that has any. */ +function latestByProduct(releases) { + const out = {}; + for (const r of releases) { + const p = r.product || 'events'; + if (!out[p] || compareVersions(r.version, out[p]) > 0) out[p] = r.version; + } + return out; +} + +async function latestVersions(db = prisma) { + return latestByProduct(await db.release.findMany({ select: { product: true, version: true } })); +} + +/** Keep latest_version on the Cross Events latest (blank when there are none). Returns the map. */ +async function syncLatestVersion(db = prisma) { + const latest = await latestVersions(db); + await setSettings({ latest_version: latest.events || '' }); return latest; } -async function releasesForInstall(version) { - return releasesFor(await prisma.release.findMany(), version); +async function releasesForInstall(product, version, options = {}, db = prisma) { + return releasesFor(await db.release.findMany({ where: { product } }), version, options); } -module.exports = { VERSION_RE, sortReleases, releasesFor, releasesForInstall, syncLatestVersion }; +/** + * What updating `install` from its version to `target` needs from its siblings: the highest + * required version per product over every release it would get (so a requirement in a skipped + * release still counts). `siblings` are the church's other installs in use: [{ product, version }]. + * Returns [{ product, version, current }] for the ones not met (current: null = not installed). + */ +function unmetRequirements({ releases, from, target, siblings }) { + const needed = {}; + for (const r of releases) { + if (from && compareVersions(r.version, from) <= 0) continue; + if (compareVersions(r.version, target) > 0) continue; + for (const q of requirementsOf(r)) { + if (!needed[q.product] || compareVersions(q.version, needed[q.product]) > 0) needed[q.product] = q.version; + } + } + const out = []; + for (const [product, version] of Object.entries(needed)) { + const running = siblings.filter(s => s.product === product && s.version).map(s => s.version).sort((a, b) => compareVersions(b, a))[0] || null; + if (!running || compareVersions(running, version) < 0) out.push({ product, version, current: running }); + } + return out; +} + +/** "Accounts must be updated to 1.2.0 first (it runs 1.1.0)." for each unmet requirement. */ +function requirementMessage(unmet) { + return unmet.map(u => (u.current + ? `${PRODUCT_NAMES[u.product] || u.product} must be updated to ${u.version} first (it runs ${u.current}).` + : `${PRODUCT_NAMES[u.product] || u.product} ${u.version} or later must be installed first.`)).join(' '); +} + +/** The requirements `install` hasn't met for updating to `target` (database version). */ +async function unmetRequirementsFor(install, target, db = prisma) { + if (!target) return []; + const [releases, siblings] = await Promise.all([ + db.release.findMany({ where: { product: install.product } }), + db.install.findMany({ where: { customerId: install.customerId, id: { not: install.id }, releasedAt: null }, select: { product: true, version: true } }), + ]); + return unmetRequirements({ releases, from: install.version, target, siblings }); +} + +module.exports = { + VERSION_RE, sortReleases, releasesFor, releasesForInstall, latestByProduct, latestVersions, syncLatestVersion, + unmetRequirements, unmetRequirementsFor, requirementMessage, +}; diff --git a/backend/src/utils/settings.js b/backend/src/utils/settings.js index b9cada7..d392c53 100644 --- a/backend/src/utils/settings.js +++ b/backend/src/utils/settings.js @@ -18,7 +18,10 @@ const DEFAULTS = { smtp_user: '', smtp_pass: '', smtp_from: '', - // Releases and their notes are read from git (utils/releaseSync.js) when a repo is set. + // Releases and their notes are read from git (utils/releaseSync.js). Hub 2.0: release_sources + // is the list of sources per product (JSON, Releases page); blank = the defaults, which include + // release_repo_url (Cross Events before the monorepo, v1.2.3 tags) and release_notes_path. + release_sources: '', release_repo_url: 'https://c-git.crosscode.co.za/joshua/hope-events', release_notes_path: 'WHATS-NEW.md', release_repo_token: '', diff --git a/backend/tests/products.test.js b/backend/tests/products.test.js index d5c1f5e..879aac0 100644 --- a/backend/tests/products.test.js +++ b/backend/tests/products.test.js @@ -33,7 +33,7 @@ const mockDb = { }; jest.mock('../src/config/db', () => mockDb); jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => ({ latest_version: '2.1.1' })) })); -jest.mock('../src/utils/releases', () => ({ releasesForInstall: jest.fn(async () => []) })); +jest.mock('../src/utils/releases', () => ({ releasesForInstall: jest.fn(async () => []), latestVersions: jest.fn(async () => ({ events: '2.1.1' })) })); jest.mock('../src/utils/notices', () => ({ noticesForInstall: jest.fn(async () => []) })); jest.mock('../src/utils/licenceToken', () => ({ sign: jest.fn(() => 'hel1.token.sig'), buildPayload: jest.fn(() => ({})) })); diff --git a/backend/tests/protocol.test.js b/backend/tests/protocol.test.js index e9c208e..92346cb 100644 --- a/backend/tests/protocol.test.js +++ b/backend/tests/protocol.test.js @@ -12,7 +12,7 @@ const mockL_EVENTS = '2d0b5e4c-7f6a-4b8c-9d9e-3f4a5b6c7d8e'; const mockL_WEBSITE = '3e1c6f5d-8a7b-4c9d-8eaf-4a5b6c7d8e9f'; const mockL_OTHER = '4f2d7a6e-9b8c-4dae-9fb0-5b6c7d8e9fa0'; const mockDb = (() => { - const t = { licences: [], installs: [], events: [], heartbeats: [] }; + const t = { licences: [], installs: [], events: [], heartbeats: [], releases: [] }; const id = p => `${p}_${crypto.randomUUID()}`; const customers = { [mockC1]: { id: mockC1, name: 'Hope Family Church' }, [mockC2]: { id: mockC2, name: 'Grace Church' } }; const withLicence = l => l && { ...l, install: t.installs.find(i => i.licenceId === l.id) || null, customer: customers[l.customerId] }; @@ -26,8 +26,9 @@ const mockDb = (() => { create: jest.fn(async ({ data }) => { const row = { id: crypto.randomUUID(), registeredAt: new Date(Date.now() + t.installs.length), releasedAt: null, ...data }; t.installs.push(row); return row; }), update: jest.fn(async ({ where, data }) => Object.assign(t.installs.find(i => i.id === where.id), Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined)))), findMany: jest.fn(async ({ where, select }) => t.installs - .filter(i => i.customerId === where.customerId && i.id !== where.id.not && i.releasedAt === null && i.publicKey != null) - .filter(i => t.licences.find(l => l.id === i.licenceId)?.status !== 'revoked') + .filter(i => i.customerId === where.customerId && i.id !== where.id.not && i.releasedAt === null) + .filter(i => !where.publicKey || i.publicKey != null) + .filter(i => !where.licence || t.licences.find(l => l.id === i.licenceId)?.status !== 'revoked') .sort((a, b) => a.registeredAt - b.registeredAt) .map(i => Object.fromEntries(Object.keys(select).map(k => [k, i[k]])))), }, @@ -38,6 +39,7 @@ const mockDb = (() => { findMany: jest.fn(async () => []), }, heartbeat: { create: jest.fn(async ({ data }) => { t.heartbeats.push(data); return data; }) }, + release: { findMany: jest.fn(async ({ where } = {}) => t.releases.filter(r => !where?.product || r.product === where.product)) }, customer: { findUnique: jest.fn(async ({ where }) => customers[where.id]) }, $transaction: jest.fn(async ops => Promise.all(ops)), }; @@ -45,10 +47,7 @@ const mockDb = (() => { jest.mock('../src/config/db', () => mockDb); // Every test registers: the hourly register limit would cut in part-way through the file. jest.mock('express-rate-limit', () => () => (req, res, next) => next()); -jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => ({ latest_version: '2.4.0' })) })); -jest.mock('../src/utils/releases', () => ({ - releasesForInstall: jest.fn(async () => [{ version: '2.4.0', releasedAt: '2026-11-20T08:00:00.000Z', urgent: false, notes: '- Event feed' }]), -})); +jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => ({})), setSettings: jest.fn(async () => ({})) })); jest.mock('../src/utils/notices', () => ({ noticesForInstall: jest.fn(async () => []) })); process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123'; @@ -80,6 +79,12 @@ afterAll(() => new Promise(resolve => server.close(resolve))); beforeEach(() => { const { t } = mockDb; t.installs.length = 0; t.events.length = 0; t.heartbeats.length = 0; + t.releases.splice(0, t.releases.length, + { product: 'events', version: '2.4.0', releasedAt: new Date('2026-11-20T08:00:00Z'), urgent: false, notes: '- Event feed', requires: [] }, + { product: 'events', version: '3.0.0', releasedAt: new Date('2026-12-01T08:00:00Z'), urgent: false, notes: '- Sign in with your church account', requires: [{ product: 'accounts', version: '1.2.0' }] }, + { product: 'website', version: '1.0.0', releasedAt: new Date('2026-11-25T08:00:00Z'), urgent: false, notes: '- First release', requires: [] }, + { product: 'website', version: '1.1.0', releasedAt: new Date('2026-12-05T08:00:00Z'), urgent: false, notes: '- Sermon series', requires: [] }, + ); t.licences.splice(0, t.licences.length, { id: mockL_EVENTS, customerId: mockC1, product: 'events', key: KEYS.events, status: 'active', plan: 'Grow', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 0 }, { id: mockL_WEBSITE, customerId: mockC1, product: 'website', key: KEYS.website, status: 'active', plan: 'Website', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 0 }, @@ -191,11 +196,22 @@ describe('heartbeat', () => { expect(json.linkedProducts.map(l => [l.product, l.installId])).toEqual([['website', website.installId]]); }); - test('releases are Cross Events\' only until releases per product', async () => { + test('each product is told its own releases', async () => { const { json: website } = await register(websiteRegistration()); - expect(website).toMatchObject({ latestVersion: null, releases: [] }); + expect(website.latestVersion).toBe('1.1.0'); + expect(website.releases.map(r => r.version)).toEqual(['1.1.0']); const { json: events } = await register(eventsRegistration()); - expect(events.latestVersion).toBe('2.4.0'); + expect(events.latestVersion).toBe('3.0.0'); + expect(events.releases.map(r => r.version)).toEqual(['3.0.0', '2.4.0']); + }); + + test('v2 replies carry requirements; v1 replies are as before', async () => { + const { json: v2 } = await register(eventsRegistration()); + expect(v2.releases[0].requires).toEqual([{ product: 'accounts', version: '1.2.0' }]); + expect(v2.releases[1]).not.toHaveProperty('requires'); + const r = eventsRegistration(); + const { json: v1 } = await register({ protocolVersion: 1, licenceKey: r.licenceKey, install: { name: r.install.name, url: r.install.url, version: '2.1.1' } }); + expect(v1.releases.every(x => !('requires' in x))).toBe(true); }); test('a heartbeat for another product is refused', async () => { @@ -238,11 +254,38 @@ describe('update requests (v2)', () => { expect((await res.json()).code).toBe('INVALID_REQUEST'); }); - test('a v2 request is recorded', async () => { + test('an update that needs Accounts first is refused until Accounts is new enough', async () => { const { json: reg } = await register(eventsRegistration()); - const res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' }); - const json = await res.json(); + let res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' }); + let json = await res.json(); + expect(res.status).toBe(409); + expect(json).toMatchObject({ code: 'REQUIREMENT_NOT_MET', requirements: [{ product: 'accounts', version: '1.2.0', current: null }] }); + expect(json.message).toContain('Accounts 1.2.0 or later must be installed first'); + + // The church's Accounts install, on 1.1.0: still refused, and the message says what it runs. + mockDb.t.installs.push({ id: crypto.randomUUID(), customerId: mockC1, product: 'accounts', version: '1.1.0', releasedAt: null, registeredAt: new Date() }); + json = await (await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' })).json(); + expect(json.message).toContain('Accounts must be updated to 1.2.0 first (it runs 1.1.0)'); + + // On 1.2.0: the request goes through, and fits the contract. + mockDb.t.installs.find(i => i.product === 'accounts').version = '1.2.0'; + res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' }); + json = await res.json(); expect(res.status).toBe(201); + expect(json.version).toBe('3.0.0'); expect(hub.updateRequestResponseSchema.safeParse(json).error?.issues ?? []).toEqual([]); }); + + test('another church\'s Accounts doesn\'t count', async () => { + mockDb.t.installs.push({ id: crypto.randomUUID(), customerId: mockC2, product: 'accounts', version: '9.0.0', releasedAt: null, registeredAt: new Date() }); + const { json: reg } = await register(eventsRegistration()); + const res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' }); + expect(res.status).toBe(409); + }); + + test('a product with no requirements updates as before', async () => { + const { json: reg } = await register(websiteRegistration()); + const res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '1.0.0' }); + expect(res.status).toBe(201); + }); }); diff --git a/backend/tests/releaseSources.test.js b/backend/tests/releaseSources.test.js new file mode 100644 index 0000000..1a52f1e --- /dev/null +++ b/backend/tests/releaseSources.test.js @@ -0,0 +1,210 @@ +// Hub 2.0 step 3: releases per product from several git sources, requirements in the notes, and +// the rules that keep an unreachable source from wiping releases. Gitea is faked with a fetch +// stub; the database is in memory. + +const mockReleases = []; +const mockSettings = { values: {} }; +const mockDb = { + release: { + findMany: jest.fn(async ({ where, select } = {}) => { + const rows = mockReleases.filter(r => !where?.product || r.product === where.product); + return select ? rows.map(r => Object.fromEntries(Object.keys(select).map(k => [k, r[k]]))) : rows; + }), + create: jest.fn(async ({ data }) => { const row = { id: `r${mockReleases.length + 1}_${data.product}_${data.version}`, requires: [], ...data }; mockReleases.push(row); return row; }), + update: jest.fn(async ({ where, data }) => Object.assign(mockReleases.find(r => r.id === where.id), data)), + deleteMany: jest.fn(async ({ where }) => { + const ids = new Set(where.id.in); + for (let i = mockReleases.length - 1; i >= 0; i--) if (ids.has(mockReleases[i].id)) mockReleases.splice(i, 1); + return { count: ids.size }; + }), + }, +}; +jest.mock('../src/config/db', () => mockDb); +jest.mock('../src/utils/settings', () => ({ + getSettings: jest.fn(async () => ({ ...mockSettings.values })), + setSettings: jest.fn(async v => { Object.assign(mockSettings.values, v); return mockSettings.values; }), + releaseRepoToken: jest.fn(async () => ''), +})); + +const { parseNotes, parseRequirements, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases, PLATFORM_REPO } = require('../src/utils/releaseSync'); +const { unmetRequirements, latestByProduct } = require('../src/utils/releases'); + +const LEGACY = 'https://c-git.crosscode.co.za/joshua/hope-events'; +const api = repo => `https://c-git.crosscode.co.za/api/v1/repos/joshua/${repo}`; + +/** A fake Gitea: { 'hope-events': { tags: [...], files: { 'WHATS-NEW.md': '...' } } }; a repo set to 'down' fails. */ +let gitea; +global.fetch = jest.fn(async url => { + const m = /\/repos\/joshua\/([^/]+)\/(tags|raw\/(.+))/.exec(url); + const repo = m && gitea[m[1]]; + if (repo === 'down') throw new Error('connect ECONNREFUSED'); + if (!repo) return { ok: false, status: 404 }; + if (m[2].startsWith('tags')) { + const page = Number(new URL(url).searchParams.get('page')); + return { ok: true, status: 200, json: async () => (page === 1 ? repo.tags.map(name => ({ name, commit: { created: '2026-11-01T10:00:00Z' } })) : []) }; + } + const file = repo.files?.[decodeURIComponent(m[3])]; + return file == null ? { ok: false, status: 404 } : { ok: true, status: 200, text: async () => file }; +}); + +beforeEach(() => { + mockReleases.length = 0; + mockSettings.values = { release_repo_url: LEGACY, release_notes_path: 'WHATS-NEW.md' }; + gitea = { + 'hope-events': { tags: ['v2.0.0', 'v2.1.0', 'v2.1.1', 'not-a-version'], files: { 'WHATS-NEW.md': '## 2.1.1\n- Feedback in the background\n## 2.1.0\n- Feedback page' } }, + 'crosscode-platform': { + tags: ['contracts@1.0.0', 'contracts@1.1.0', 'events@2.2.0', 'events@3.0.0', 'accounts@1.2.0', 'website@1.0.0'], + files: { + 'apps/events/WHATS-NEW.md': '## 3.0.0 — requires accounts 1.2.0\n- Sign in with your church account\n## 2.2.0\n- Moved into the monorepo', + 'apps/accounts/WHATS-NEW.md': '## 1.2.0\n- Authenticator app', + 'apps/website/WHATS-NEW.md': '## 1.0.0 — requires events 2.4.0\n- First release', + }, + }, + }; +}); + +const versions = product => mockReleases.filter(r => r.product === product).map(r => r.version).sort(); + +describe('sources', () => { + test('the defaults: every product from the monorepo, plus Cross Events from the repo set before 2.0', () => { + expect(defaultSources(mockSettings.values)).toEqual([ + { product: 'events', repo: PLATFORM_REPO, tagPrefix: 'events@', notesPath: 'apps/events/WHATS-NEW.md' }, + { product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' }, + { product: 'accounts', repo: PLATFORM_REPO, tagPrefix: 'accounts@', notesPath: 'apps/accounts/WHATS-NEW.md' }, + { product: 'website', repo: PLATFORM_REPO, tagPrefix: 'website@', notesPath: 'apps/website/WHATS-NEW.md' }, + { product: 'app', repo: PLATFORM_REPO, tagPrefix: 'app@', notesPath: 'apps/app/WHATS-NEW.md' }, + ]); + }); + + test('a saved list replaces the defaults', () => { + const saved = [{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' }]; + expect(releaseSources({ release_sources: JSON.stringify(saved) })).toEqual(saved); + }); + + test('bad sources are refused with what is wrong', () => { + expect(() => cleanSources([{ product: 'shop', repo: LEGACY }])).toThrow(/product/); + expect(() => cleanSources([{ product: 'events', repo: 'not a url' }])).toThrow(/repository/); + expect(() => cleanSources([{ product: 'events', repo: LEGACY, tagPrefix: 'a b' }])).toThrow(/prefix/); + expect(() => cleanSources([{ product: 'events', repo: LEGACY, notesPath: '../x' }])).toThrow(/notes/); + expect(() => cleanSources([{ product: 'events', repo: LEGACY, tagPrefix: 'v' }, { product: 'events', repo: `${LEGACY}.git`, tagPrefix: 'v' }])).toThrow(/twice/); + }); + + test('tag patterns: a prefix, and v (also bare versions, as before 2.0)', () => { + expect(tagPattern('events@').exec('events@2.2.0')[1]).toBe('2.2.0'); + expect(tagPattern('events@').exec('website@2.2.0')).toBeNull(); + expect(tagPattern('events@').exec('events@2.2.0-rc1')).toBeNull(); + expect(tagPattern('v').exec('v2.1.1')[1]).toBe('2.1.1'); + expect(tagPattern('v').exec('2.1.1')[1]).toBe('2.1.1'); + }); +}); + +describe('requirements in the notes', () => { + test('"— requires accounts 1.2.0, website v1.1.0 — urgent"', () => { + expect(parseNotes('## 3.0.0 — requires accounts 1.2.0, website v1.1.0 — urgent\n- x')['3.0.0']).toEqual({ + notes: '- x', urgent: true, requires: [{ product: 'accounts', version: '1.2.0' }, { product: 'website', version: '1.1.0' }], + }); + }); + + test('no "requires" means no requirements, even if a product is named', () => { + expect(parseRequirements(' — works with the website 1.0.0')).toEqual([]); + expect(parseNotes('## 2.4.0\n- x')['2.4.0'].requires).toEqual([]); + }); +}); + +describe('sync', () => { + test('every product gets the tags of its sources, with notes and requirements', async () => { + const result = await syncReleases(); + expect(versions('events')).toEqual(['2.0.0', '2.1.0', '2.1.1', '2.2.0', '3.0.0']); + expect(versions('accounts')).toEqual(['1.2.0']); + expect(versions('website')).toEqual(['1.0.0']); + expect(versions('app')).toEqual([]); + expect(mockReleases.find(r => r.product === 'events' && r.version === '3.0.0').requires).toEqual([{ product: 'accounts', version: '1.2.0' }]); + expect(mockReleases.find(r => r.product === 'events' && r.version === '2.1.1').notes).toBe('- Feedback in the background'); + expect(result.latest).toEqual({ events: '3.0.0', accounts: '1.2.0', website: '1.0.0' }); + expect(mockSettings.values.latest_version).toBe('3.0.0'); + }); + + test('contracts@ tags are nobody\'s release', async () => { + await syncReleases(); + expect(mockReleases.some(r => r.version === '1.1.0')).toBe(false); + }); + + test('a removed tag removes its release', async () => { + await syncReleases(); + gitea['hope-events'].tags = ['v2.1.0', 'v2.1.1']; + const result = await syncReleases(); + expect(versions('events')).toEqual(['2.1.0', '2.1.1', '2.2.0', '3.0.0']); + expect(result.removed).toBe(1); + }); + + test('a source that can\'t be reached keeps its product\'s releases', async () => { + await syncReleases(); + gitea['hope-events'] = 'down'; + const result = await syncReleases(); + expect(versions('events')).toEqual(['2.0.0', '2.1.0', '2.1.1', '2.2.0', '3.0.0']); + expect(result.problems.join(' ')).toMatch(/hope-events.*ECONNREFUSED/); + // The other products still sync. + gitea['crosscode-platform'].tags.push('accounts@1.3.0'); + await syncReleases(); + expect(versions('accounts')).toEqual(['1.2.0', '1.3.0']); + }); + + test('a product whose sources have no tags any more keeps its releases (and says so)', async () => { + mockSettings.values.release_sources = JSON.stringify([{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' }]); + await syncReleases(); + gitea['hope-events'].tags = []; + const result = await syncReleases(); + expect(versions('events')).toEqual(['2.0.0', '2.1.0', '2.1.1']); + expect(result.problems.join(' ')).toMatch(/kept/); + }); + + test('when nothing can be read, the sync fails and changes nothing', async () => { + await syncReleases(); + gitea['hope-events'] = 'down'; + gitea['crosscode-platform'] = 'down'; + await expect(syncReleases()).rejects.toThrow(/ECONNREFUSED/); + expect(versions('events')).toHaveLength(5); + }); + + test('a product with no source is left alone (managed by hand)', async () => { + mockReleases.push({ id: 'manual', product: 'app', version: '0.9.0', notes: '', urgent: false, requires: [], releasedAt: new Date() }); + mockSettings.values.release_sources = JSON.stringify([{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' }]); + await syncReleases(); + expect(versions('app')).toEqual(['0.9.0']); + }); + + test('a requirement can\'t be on the product itself', async () => { + gitea['crosscode-platform'].files['apps/events/WHATS-NEW.md'] = '## 3.0.0 — requires events 2.9.0, accounts 1.2.0\n- x'; + await syncReleases(); + expect(mockReleases.find(r => r.product === 'events' && r.version === '3.0.0').requires).toEqual([{ product: 'accounts', version: '1.2.0' }]); + }); +}); + +describe('unmet requirements', () => { + const releases = [ + { version: '2.4.0', requires: [] }, + { version: '2.5.0', requires: [{ product: 'accounts', version: '1.1.0' }] }, + { version: '3.0.0', requires: [{ product: 'accounts', version: '1.2.0' }, { product: 'website', version: '1.0.0' }] }, + { version: '3.1.0', requires: [{ product: 'accounts', version: '1.5.0' }] }, + ]; + + test('the highest requirement over every release up to the target counts', () => { + expect(unmetRequirements({ releases, from: '2.4.0', target: '3.0.0', siblings: [{ product: 'accounts', version: '1.1.0' }] })).toEqual([ + { product: 'accounts', version: '1.2.0', current: '1.1.0' }, + { product: 'website', version: '1.0.0', current: null }, + ]); + }); + + test('releases already installed, or beyond the target, don\'t count', () => { + expect(unmetRequirements({ releases, from: '2.5.0', target: '2.5.0', siblings: [] })).toEqual([]); + expect(unmetRequirements({ releases, from: '3.0.0', target: '3.1.0', siblings: [{ product: 'accounts', version: '1.5.0' }] })).toEqual([]); + }); + + test('met when the sibling runs that version or later', () => { + expect(unmetRequirements({ releases, from: '2.4.0', target: '3.0.0', siblings: [{ product: 'accounts', version: '1.2.1' }, { product: 'website', version: '1.0.0' }] })).toEqual([]); + }); + + test('latest per product', () => { + expect(latestByProduct([{ product: 'events', version: '2.10.0' }, { product: 'events', version: '2.9.0' }, { product: 'app', version: '1.0.0' }])).toEqual({ events: '2.10.0', app: '1.0.0' }); + }); +}); diff --git a/backend/vendor/crosscode-contracts-1.0.0.tgz b/backend/vendor/crosscode-contracts-1.0.0.tgz deleted file mode 100644 index 632a913..0000000 Binary files a/backend/vendor/crosscode-contracts-1.0.0.tgz and /dev/null differ diff --git a/backend/vendor/crosscode-contracts-1.1.0.tgz b/backend/vendor/crosscode-contracts-1.1.0.tgz new file mode 100644 index 0000000..1aade2a Binary files /dev/null and b/backend/vendor/crosscode-contracts-1.1.0.tgz differ diff --git a/frontend/src/app/(hub)/installs/[id]/page.tsx b/frontend/src/app/(hub)/installs/[id]/page.tsx index 44aa16a..5ce3f58 100644 --- a/frontend/src/app/(hub)/installs/[id]/page.tsx +++ b/frontend/src/app/(hub)/installs/[id]/page.tsx @@ -9,7 +9,7 @@ import { ago, bytes, fmtDate, rand, randFine } from "@/lib/format"; import { usePaged } from "@/lib/paging"; import { tierForBand, tierPrice } from "@/lib/tiers"; import { PRODUCT_NAMES } from "@/lib/products"; -import type { AiHelperUse, AiMonth, AiStatus, Health, InstallEvent, InstallSummary, Licence, Stats } from "@/lib/types"; +import type { AiHelperUse, AiMonth, AiStatus, Health, InstallEvent, InstallSummary, Licence, Stats, UnmetRequirement } from "@/lib/types"; import { Badge, Loading, Message, PageTitle, Pager } from "@/components/ui"; type Detail = { @@ -23,6 +23,7 @@ type Detail = { events: InstallEvent[]; heartbeats: { receivedAt: string; version: string | null; stats: Stats | null }[]; ai: { status: AiStatus; months: AiMonth[]; helpers: AiHelperUse[] }; + update: { latestVersion: string | null; behind: boolean; unmetRequirements: UnmetRequirement[] }; }; const NO_EVENTS: InstallEvent[] = []; @@ -74,12 +75,22 @@ export default function InstallPage() { {d.summary.problems.map(p =>
{p.message}
)} )} + {d.update.unmetRequirements.length > 0 && ( +
+

Updating to {d.update.latestVersion} needs the church's other products first, so Request update is refused until then:

+
    + {d.update.unmetRequirements.map(u => ( +
  • {PRODUCT_NAMES[u.product]} {u.version} or later{u.current ? ` (it runs ${u.current})` : " (not installed)"}
  • + ))} +
+
+ )}

Health

- + diff --git a/frontend/src/app/(hub)/page.tsx b/frontend/src/app/(hub)/page.tsx index 10109e1..514c9bd 100644 --- a/frontend/src/app/(hub)/page.tsx +++ b/frontend/src/app/(hub)/page.tsx @@ -6,11 +6,12 @@ import { api, errorText } from "@/lib/api"; import { ago, fmtDate } from "@/lib/format"; import { matches, usePaged } from "@/lib/paging"; import type { InstallSummary } from "@/lib/types"; -import { PRODUCT_NAMES } from "@/lib/products"; +import { PRODUCTS, PRODUCT_NAMES, type Product } from "@/lib/products"; import { Badge, Loading, PageTitle, Pager, SearchInput, Stat } from "@/components/ui"; type Dashboard = { latestVersion: string | null; + latestVersions: Partial>; counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record }; installs: InstallSummary[]; }; @@ -50,7 +51,12 @@ export default function OverviewPage() { return ( <> - + data.latestVersions[p]) + ? `Latest releases: ${PRODUCTS.filter(p => data.latestVersions[p]).map(p => `${PRODUCT_NAMES[p]} ${data.latestVersions[p]}`).join(" · ")}` + : "Releases appear on the Releases page once they're tagged; then you can see who is behind."} + />
@@ -88,7 +94,7 @@ export default function OverviewPage() { {i.problems.filter(p => p.level !== "info").map(p =>
{p.message}
)} - {i.version || "—"}{i.behind && (behind)} + {i.version || "—"}{i.behind && (latest {i.latestVersion})} {i.licence ? <>{i.licence.expiresAt &&
to {fmtDate(i.licence.expiresAt, false)}
} : none} diff --git a/frontend/src/app/(hub)/releases/page.tsx b/frontend/src/app/(hub)/releases/page.tsx index 254ad70..2e1bfc6 100644 --- a/frontend/src/app/(hub)/releases/page.tsx +++ b/frontend/src/app/(hub)/releases/page.tsx @@ -1,24 +1,32 @@ "use client"; -import React, { useCallback, useEffect, useState } from "react"; -import { GitBranch, RefreshCw, ShieldAlert } from "lucide-react"; +import React, { useCallback, useEffect, useMemo, useState } from "react"; +import { GitBranch, Link2, Plus, RefreshCw, ShieldAlert, Trash2 } from "lucide-react"; import { api, errorText } from "@/lib/api"; import { ago, fmtDate } from "@/lib/format"; -import type { Release } from "@/lib/types"; +import { PRODUCTS, PRODUCT_NAMES, type Product } from "@/lib/products"; +import type { Release, ReleaseSource } 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 }; +type Form = { product: Product; 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 }) { +/** Add or edit one release (only for a product with no release source). */ +function ReleaseForm({ initial, products, onSave, onCancel, busy }: { initial: Form; products: Product[] | null; onSave: (f: Form) => void; onCancel?: () => void; busy: boolean }) { const [form, setForm] = useState(initial); return (
{ e.preventDefault(); onSave(form); }} className="space-y-3"> -
+
+ {products && ( +
+ + +
+ )}
setForm({ ...form, version: e.target.value })} required /> @@ -35,7 +43,7 @@ function ReleaseForm({ initial, onSave, onCancel, busy }: { initial: Form; onSav