Hub 2.22.0: Get more storage for the Church Website

POST /api/installs/storage-request (contracts 1.18.0): recorded on the
install, Joshua emailed once, closed when the licence gets more extra
storage steps. The church is emailed once when its website's storage
passes 80% and once when it's full (from the heartbeat). Vendors
contracts 1.18.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 15:41:31 +02:00
co-authored by Claude Opus 5.5
parent f23f40392e
commit 43eb634199
12 changed files with 253 additions and 13 deletions
+5
View File
@@ -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);
}));
+29
View File
@@ -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) => {
+3 -2
View File
@@ -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 } });
+112
View File
@@ -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 };