diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f585e4..c189d61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,24 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.22.0] - 2026-11-25 + +"Get more storage" for the Church Website (crosscode-platform docs/WEBSITE-1.0-PLAN.md §10, decision +12). Vendors `@crosscode/contracts` 1.18.0 (was 1.17.0). No migration; no API is removed. + +### Added + +- **`POST /api/installs/storage-request`** (contracts 1.18.0, signed as the heartbeat): a Website's + Owner or Admin asks for more 5 GB steps. It shows on the install as an open `storage_requested` + event and Joshua is emailed once (with who asked and what the site uses); asking again only + changes the number of steps. It closes when the licence's extra storage steps go up (Edit → + Extra storage), and the site gets its new limit with the next heartbeat. Only a Website may ask + (`WRONG_PRODUCT`). +- **The church is emailed when its website's storage passes 80% and when it's full**, from the + Website's heartbeat (`stats.storage`), to the customer's email and the install's admin contact, + once each (open `storage_80` / `storage_full` events), again only after it has dropped below. + The alert run leaves these events to the heartbeat, as it does update requests. + ## [2.21.0] - 2026-11-25 The Hub side of the Church Website 1.0.0 (crosscode-platform docs/WEBSITE-1.0-PLAN.md §11). diff --git a/backend/package-lock.json b/backend/package-lock.json index 2d98b81..2fab907 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,16 +1,16 @@ { "name": "events-hub-backend", - "version": "2.21.0", + "version": "2.22.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "2.21.0", + "version": "2.22.0", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.17.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.18.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.17.0", - "resolved": "file:vendor/crosscode-contracts-1.17.0.tgz", - "integrity": "sha512-mT/A1/NEkw3h3vRHZ546x2KJvqVRBkv+x4c0/Cb+xTE/mZKUpXRwbDyBsDxKzs7orKdAcPZQxLg91gnAObx2PQ==", + "version": "1.18.0", + "resolved": "file:vendor/crosscode-contracts-1.18.0.tgz", + "integrity": "sha512-3rcu08JRg+yL5xdRI5IV0RBjQ2NWTr0EG1oM0X6ISAVtyOWjxAsWtUWpmkwG/wlhgcvdOWGvv/katB+F9P8EqQ==", "license": "UNLICENSED", "dependencies": { "zod": "^4.6.7" diff --git a/backend/package.json b/backend/package.json index 741fa04..7240b14 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "2.21.0", + "version": "2.22.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", @@ -20,7 +20,7 @@ }, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", - "@crosscode/contracts": "file:vendor/crosscode-contracts-1.17.0.tgz", + "@crosscode/contracts": "file:vendor/crosscode-contracts-1.18.0.tgz", "@prisma/adapter-pg": "^7.10.1", "@prisma/client": "^7.10.1", "bcryptjs": "^2.4.3", diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index a54e1af..5b74c00 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -260,6 +260,11 @@ router.put('/licences/:id', wrap(async (req, res) => { throw e; }); await audit(req, 'licence_updated', licence.id, { changed: Object.keys(data), status: licence.status, expiresAt: licence.expiresAt }); + // 2.22.0: more storage added: the site's "Get more storage" request is done. + if (data.extraStorageSteps !== undefined && data.extraStorageSteps > (existing.extraStorageSteps || 0)) { + const install = await prisma.install.findFirst({ where: { licenceId: existing.id } }); + await require('../utils/storage').storageAdded(prisma, install?.id); + } res.json(licence); })); diff --git a/backend/src/routes/installApi.js b/backend/src/routes/installApi.js index 392e62e..9e21631 100644 --- a/backend/src/routes/installApi.js +++ b/backend/src/routes/installApi.js @@ -19,6 +19,7 @@ const { compareVersions } = require('../utils/alerts'); const { requestMessage, requestedVersionOf, isOutdated } = require('../utils/updateRequests'); const { sendMail } = require('../utils/mail'); const { render } = require('../utils/emailLayout'); +const storage = require('../utils/storage'); /** An update-request email to Joshua (2.10.0: laid out as the Hub's other emails). */ const updateRequestEmail = ({ heading, note, rows, link }) => render({ @@ -248,6 +249,15 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => { await prisma.installEvent.updateMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null }, data: { resolvedAt: now } }); } } + // Hub 2.22.0: a Website's storage at 80% or full emails the church once (decision 12). + if (install.product === 'website' && stats) { + try { + const withCustomer = await prisma.install.findUnique({ where: { id: install.id }, include: { customer: true } }); + await storage.storageLevels(prisma, withCustomer || install, stats, { sendMail, now }); + } catch (e) { + console.warn('[storage] checking the storage level failed:', e?.message || e); + } + } const publicKeyStatus = v2 && body.publicKey ? await acceptPublicKey(install, body.publicKey, now) : null; @@ -265,6 +275,25 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => { } }); +// Hub 2.22.0 (contracts 1.18.0): a Website's Owner or Admin pressed "Get more storage". Recorded on +// the install and emailed to Joshua once per request; it closes when the licence gets more steps. +router.post('/installs/storage-request', updateRequestLimiter, async (req, res) => { + try { + const install = await signedInstall(req, res); + if (!install) return; + if (install.product !== 'website') return fail(res, 409, 'WRONG_PRODUCT', 'Only a Church Website has storage to add.'); + const body = bodyFor(req, res, hub.storageRequestSchema); + if (!body) return; + const settings = await getSettings(); + const withCustomer = await prisma.install.findUnique({ where: { id: install.id }, include: { customer: true } }); + const reply = await storage.storageRequested(prisma, withCustomer || install, body, { alertEmail: settings.alert_email, sendMail }); + res.status(reply.alreadyRequested ? 200 : 201).json(reply); + } catch (e) { + console.error('[storage-request]', e); + fail(res, 500, 'SERVER_ERROR', 'The Hub could not record the request. Try again later.'); + } +}); + // A site admin pressed "Request update": open an alert (emailed once) until the install reports a // newer version. Asking again while a request is open doesn't email again. router.post('/installs/update-request', updateRequestLimiter, async (req, res) => { diff --git a/backend/src/utils/alerts.js b/backend/src/utils/alerts.js index 5f9e790..aaf4f44 100644 --- a/backend/src/utils/alerts.js +++ b/backend/src/utils/alerts.js @@ -150,8 +150,9 @@ async function runAlerts(now = new Date()) { const churches = churchesOf(installs); for (const install of installs) { const current = problems({ ...install, church: churches.get(install.customerId) }, 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', 'update_request_withdrawn'].includes(e.type)).map(e => [e.type, e])); + // Update requests are opened by the install and resolved by its heartbeat, not by these checks; + // so are a Website's storage request and levels (2.22.0, utils/storage.js). + const openByType = new Map(install.events.filter(e => !['registered', 'version', 'update_requested', 'update_request_withdrawn', 'storage_requested', 'storage_80', 'storage_full'].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 } }); diff --git a/backend/src/utils/storage.js b/backend/src/utils/storage.js new file mode 100644 index 0000000..95b0d95 --- /dev/null +++ b/backend/src/utils/storage.js @@ -0,0 +1,112 @@ +/** + * A Church Website's storage (Hub 2.22.0, contracts 1.18.0; WEBSITE-1.0-PLAN §10, decision 12). + * + * - "Get more storage": the site asks (`POST /api/installs/storage-request`). An open + * `storage_requested` event shows on the install, and Joshua is emailed once per request (asking + * again only changes the number of steps). It's resolved when the licence's extra storage steps go + * up (admin.js, PUT /licences/:id). + * - 80% and full: from the site's heartbeat (`stats.storage`: used and its limit), the church's + * contacts are emailed once when it passes 80% and once when it's full (open `storage_80` / + * `storage_full` events), again only after it has dropped below and come back. + */ + +const { render } = require('./emailLayout'); + +const STEP_BYTES = 5 * 1024 ** 3; +const TYPES = ['storage_requested', 'storage_80', 'storage_full']; + +const gb = n => `${(n / 1024 ** 3).toFixed(1)} GB`; +const hubLink = install => `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`; + +/** The church's contacts for its site: the customer's email and the install's admin contact, once each. */ +function churchRecipients(install) { + const seen = new Map(); + 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()]; +} + +/** The site asked for more storage. Returns the reply for the site. */ +async function storageRequested(db, install, body, { alertEmail, sendMail, now = new Date() }) { + const name = install.customer?.name || install.name; + const message = `Asked for ${body.steps * 5} GB more (${body.steps} step${body.steps === 1 ? '' : 's'}) by ${body.requestedBy || 'an admin'}; using ${gb(body.usedBytes)} of ${gb(body.limitBytes)}`; + const open = await db.installEvent.findFirst({ where: { installId: install.id, type: 'storage_requested', resolvedAt: null }, orderBy: { createdAt: 'desc' } }); + if (open) { + await db.installEvent.update({ where: { id: open.id }, data: { message } }); + return { requestedAt: open.createdAt.toISOString(), steps: body.steps, alreadyRequested: true }; + } + const event = await db.installEvent.create({ data: { installId: install.id, type: 'storage_requested', level: 'warning', message, createdAt: now } }); + if (alertEmail) { + await sendMail({ + to: alertEmail, + subject: `Cross Code Hub: ${name} would like more website storage`, + ...render({ + heading: `${name} would like more storage`, + blocks: [ + { note: { kind: 'info', text: `${body.requestedBy || 'An admin'} asked for ${body.steps * 5} GB more (R${body.steps * 20} a month). Add the steps to the Website licence (Edit → Extra storage); the site gets the new limit with its next heartbeat.` } }, + { rows: [['Church', name], ['Site', install.url], ['Using', `${gb(body.usedBytes)} of ${gb(body.limitBytes)}`], ['Asked for', `${body.steps} × 5 GB`]] }, + { button: { label: 'Open the install', url: hubLink(install) } }, + ], + footer: 'Sent by the Cross Code Hub to the alert address in Settings.', + }), + }).catch(e => console.warn('[storage] email failed:', e?.message)); + } + return { requestedAt: event.createdAt.toISOString(), steps: body.steps, alreadyRequested: false }; +} + +/** The licence's extra storage went up: the open request is done. */ +async function storageAdded(db, installId, now = new Date()) { + if (!installId) return 0; + const r = await db.installEvent.updateMany({ where: { installId, type: 'storage_requested', resolvedAt: null }, data: { resolvedAt: now } }); + return r.count; +} + +/** + * After a Website's heartbeat: email the church once when its storage passes 80%, and once when it's + * full; open events close when it drops back below. + */ +async function storageLevels(db, install, stats, { sendMail, now = new Date() }) { + if (install.product !== 'website') return null; + const used = Number(stats?.storage?.usedBytes); + const limit = Number(stats?.storage?.includedBytes); + if (!Number.isFinite(used) || !Number.isFinite(limit) || limit <= 0) return null; + const share = used / limit; + const open = await db.installEvent.findMany({ where: { installId: install.id, type: { in: ['storage_80', 'storage_full'] }, resolvedAt: null } }); + const isOpen = type => open.some(e => e.type === type); + const sent = []; + for (const [type, reached] of [['storage_80', share >= 0.8], ['storage_full', share >= 1]]) { + if (!reached) { + if (isOpen(type)) await db.installEvent.updateMany({ where: { installId: install.id, type, resolvedAt: null }, data: { resolvedAt: now } }); + continue; + } + if (isOpen(type)) continue; + const full = type === 'storage_full'; + await db.installEvent.create({ data: { installId: install.id, type, level: full ? 'warning' : 'info', message: `Website storage ${full ? 'full' : 'at 80%'}: ${gb(used)} of ${gb(limit)}`, createdAt: now } }); + sent.push(type); + const to = churchRecipients(install); + if (!to.length) continue; + const site = install.url.replace(/\/+$/, ''); + for (const address of to) { + await sendMail({ + to: address, + subject: full ? 'Your website\'s storage is full' : 'Your website\'s storage is nearly full', + ...render({ + heading: full ? 'Your website\'s storage is full' : 'Your website\'s storage is nearly full', + blocks: [ + { note: { kind: full ? 'warning' : 'info', text: full + ? `Your website uses ${gb(used)} of ${gb(limit)}, so new uploads have stopped. Everything already uploaded keeps showing.` + : `Your website uses ${gb(used)} of ${gb(limit)}. When it's full, new uploads stop (everything already uploaded keeps showing).` } }, + { p: 'Ask for more storage in your website\'s admin, under Media library: 5 GB at a time, R20 a month each. Or remove photos you no longer use.' }, + { button: { label: 'Open the media library', url: `${site}/admin/media` } }, + ], + footer: 'Sent by Cross Code about your church\'s website.', + }), + }).catch(e => console.warn('[storage] email failed:', e?.message)); + } + } + return sent; +} + +module.exports = { STEP_BYTES, TYPES, churchRecipients, storageRequested, storageAdded, storageLevels }; diff --git a/backend/tests/storage.test.js b/backend/tests/storage.test.js new file mode 100644 index 0000000..2b79041 --- /dev/null +++ b/backend/tests/storage.test.js @@ -0,0 +1,75 @@ +// A Church Website's storage (Hub 2.22.0): "Get more storage" requests and the 80% / full emails. +jest.mock('../src/config/db', () => require('./fakeDb').createFakeDb()); + +const { createFakeDb } = require('./fakeDb'); +const storage = require('../src/utils/storage'); + +const GB = 1024 ** 3; + +function setup() { + const db = createFakeDb(); + const mails = []; + const sendMail = async m => { mails.push(m); }; + const install = { + id: 'inst-1', name: 'Hope Website', product: 'website', url: 'https://www.hope.test', + adminContact: { name: 'Sam', email: 'sam@hope.test' }, customer: { name: 'Hope Family Church', email: 'office@hope.test' }, + }; + return { db, mails, sendMail, install }; +} + +describe('Get more storage', () => { + test('records the request and emails Joshua once; asking again only changes it', async () => { + const { db, mails, sendMail, install } = setup(); + const body = { protocolVersion: 2, steps: 1, usedBytes: 4.8 * GB, limitBytes: 5 * GB, requestedBy: 'Sam' }; + const first = await storage.storageRequested(db, install, body, { alertEmail: 'joshua@hub.test', sendMail }); + expect(first.alreadyRequested).toBe(false); + expect(mails).toHaveLength(1); + expect(mails[0].to).toBe('joshua@hub.test'); + expect(mails[0].subject).toMatch(/Hope Family Church would like more website storage/); + const again = await storage.storageRequested(db, install, { ...body, steps: 2 }, { alertEmail: 'joshua@hub.test', sendMail }); + expect(again).toMatchObject({ alreadyRequested: true, steps: 2 }); + expect(mails).toHaveLength(1); + const events = await db.installEvent.findMany({ where: { installId: 'inst-1', type: 'storage_requested' } }); + expect(events).toHaveLength(1); + expect(events[0].message).toMatch(/10 GB more/); + }); + + test('is done when the licence gets more steps', async () => { + const { db, sendMail, install } = setup(); + await storage.storageRequested(db, install, { protocolVersion: 2, steps: 1, usedBytes: 1, limitBytes: 5 * GB, requestedBy: null }, { alertEmail: null, sendMail }); + expect(await storage.storageAdded(db, 'inst-1')).toBe(1); + expect(await db.installEvent.count({ where: { installId: 'inst-1', type: 'storage_requested', resolvedAt: null } })).toBe(0); + }); +}); + +describe('80% and full', () => { + const at = share => ({ storage: { usedBytes: Math.round(share * 5 * GB), includedBytes: 5 * GB } }); + + test('emails the church once at 80% and once when full, to its two addresses', async () => { + const { db, mails, sendMail, install } = setup(); + expect(await storage.storageLevels(db, install, at(0.5), { sendMail })).toEqual([]); + expect(await storage.storageLevels(db, install, at(0.85), { sendMail })).toEqual(['storage_80']); + expect(mails.map(m => m.to).sort()).toEqual(['office@hope.test', 'sam@hope.test']); + expect(mails[0].subject).toBe("Your website's storage is nearly full"); + expect(await storage.storageLevels(db, install, at(0.9), { sendMail })).toEqual([]); + expect(await storage.storageLevels(db, install, at(1), { sendMail })).toEqual(['storage_full']); + expect(mails).toHaveLength(4); + expect(mails[3].subject).toBe("Your website's storage is full"); + expect(mails[3].text).toMatch(/admin\/media/); + }); + + test('again only after it dropped back below', async () => { + const { db, mails, sendMail, install } = setup(); + await storage.storageLevels(db, install, at(0.85), { sendMail }); + await storage.storageLevels(db, install, at(0.4), { sendMail }); + expect(await db.installEvent.count({ where: { installId: 'inst-1', type: 'storage_80', resolvedAt: null } })).toBe(0); + await storage.storageLevels(db, install, at(0.85), { sendMail }); + expect(mails).toHaveLength(4); + }); + + test('leaves other products and odd stats alone', async () => { + const { db, sendMail, install } = setup(); + expect(await storage.storageLevels(db, { ...install, product: 'events' }, at(1), { sendMail })).toBeNull(); + expect(await storage.storageLevels(db, install, { storage: { usedBytes: 5, includedBytes: 0 } }, { sendMail })).toBeNull(); + }); +}); diff --git a/backend/vendor/crosscode-contracts-1.17.0.tgz b/backend/vendor/crosscode-contracts-1.17.0.tgz deleted file mode 100644 index 709170f..0000000 Binary files a/backend/vendor/crosscode-contracts-1.17.0.tgz and /dev/null differ diff --git a/backend/vendor/crosscode-contracts-1.18.0.tgz b/backend/vendor/crosscode-contracts-1.18.0.tgz new file mode 100644 index 0000000..b21e5a3 Binary files /dev/null and b/backend/vendor/crosscode-contracts-1.18.0.tgz differ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index aea5c5b..69cecf9 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "2.21.0", + "version": "2.22.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "2.21.0", + "version": "2.22.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index 192c78f..5b28595 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "2.21.0", + "version": "2.22.0", "private": true, "scripts": { "dev": "next dev -p 3200",