Merge branch 'feat/hub2-products' into release/2.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,32 @@ versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`).
|
||||
|
||||
### Added
|
||||
|
||||
- **Products** (step 1): a licence and an install are for one product: Cross Events, Accounts,
|
||||
Church Website or Church App (existing ones are Cross Events). Generate a licence for a product
|
||||
on the customer's page; keys have the product's prefix (`CEH-` Events as before, `CCA-`
|
||||
Accounts, `CCW-` Website, `CCP-` App).
|
||||
- **One licence per product per customer** that isn't revoked (a revoked one can be replaced),
|
||||
enforced by the database. Un-revoking a licence whose product has another open licence is
|
||||
refused.
|
||||
- **Accounts licence** (free, never invoiced) created automatically with a customer's first other
|
||||
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`.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Cross Code Hub** in the dashboard, emails, PDFs and new two-factor set-ups (the `hel1.`
|
||||
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).
|
||||
- Migration `20261104132032_products`.
|
||||
|
||||
## [1.7.0] - 2026-11-03
|
||||
|
||||
### Added
|
||||
|
||||
Generated
+19
@@ -10,6 +10,7 @@
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^1.3.0",
|
||||
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.0.0.tgz",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"bcryptjs": "^2.4.3",
|
||||
@@ -607,6 +608,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@crosscode/contracts": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "file:vendor/crosscode-contracts-1.0.0.tgz",
|
||||
"integrity": "sha512-NcilXx9mVmHNsQvIBNNH5rPBmNKYKBSO8bLmC5czLNIlSiQQz95571qPYx+PMXvibAw7TX1LPpO8TKgz5f0dHA==",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@electric-sql/pglite": {
|
||||
"version": "0.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.3.tgz",
|
||||
@@ -7742,6 +7752,15 @@
|
||||
"grammex": "^3.1.11",
|
||||
"graphmatch": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "4.6.7",
|
||||
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
|
||||
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,10 +15,12 @@
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"create-admin": "node scripts/create-admin.js",
|
||||
"generate-keys": "node scripts/generate-keys.js"
|
||||
"generate-keys": "node scripts/generate-keys.js",
|
||||
"check:hub2": "node scripts/check-hub2.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^1.3.0",
|
||||
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.0.0.tgz",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"bcryptjs": "^2.4.3",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "Product" AS ENUM ('events', 'accounts', 'website', 'app');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Install" ADD COLUMN "product" "Product" NOT NULL DEFAULT 'events',
|
||||
ADD COLUMN "publicKey" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Licence" ADD COLUMN "product" "Product" NOT NULL DEFAULT 'events';
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Licence_customerId_product_idx" ON "Licence"("customerId", "product");
|
||||
|
||||
-- One licence per product per customer that isn't revoked (Hub 2.0; a revoked licence can be
|
||||
-- replaced). Prisma can't express a partial index, so it's only here. Every licence before 2.0 is
|
||||
-- an Events licence: a customer with two that aren't revoked stops the migration, named, so it can
|
||||
-- be sorted out (revoke one) before deploying — `npm run check:hub2` lists them in advance.
|
||||
DO $$
|
||||
DECLARE dupes TEXT;
|
||||
BEGIN
|
||||
SELECT string_agg(format('%s (%s licences)', c.name, n), ', ') INTO dupes
|
||||
FROM (SELECT "customerId", count(*) AS n FROM "Licence" WHERE status <> 'revoked' GROUP BY "customerId" HAVING count(*) > 1) d
|
||||
JOIN "Customer" c ON c.id = d."customerId";
|
||||
IF dupes IS NOT NULL THEN
|
||||
RAISE EXCEPTION 'Hub 2.0 allows one Events licence per customer that is not revoked. Revoke the extra licences first: %', dupes;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE UNIQUE INDEX "Licence_customerId_product_open_key" ON "Licence"("customerId", "product") WHERE status <> 'revoked';
|
||||
@@ -56,12 +56,25 @@ enum LicenceStatus {
|
||||
revoked
|
||||
}
|
||||
|
||||
// Hub 2.0: the Cross Code products a church can have (ROADMAP-v3 §5). Accounts comes free with
|
||||
// any other product.
|
||||
enum Product {
|
||||
events
|
||||
accounts
|
||||
website
|
||||
app
|
||||
}
|
||||
|
||||
model Licence {
|
||||
id String @id @default(uuid())
|
||||
customerId String
|
||||
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
|
||||
// CEH-XXXX-XXXX-XXXX-XXXX, generated by the Hub.
|
||||
// CEH-XXXX-XXXX-XXXX-XXXX (Events), CCA- (Accounts), CCW- (Website), CCP- (App).
|
||||
key String @unique
|
||||
// Hub 2.0. A customer has at most one licence per product that isn't revoked: enforced by the
|
||||
// partial unique index "Licence_customerId_product_open_key" (migration 20261104…_products),
|
||||
// which Prisma can't express here.
|
||||
product Product @default(events)
|
||||
plan String @default("standard")
|
||||
status LicenceStatus @default(active)
|
||||
// Null = no end date.
|
||||
@@ -90,6 +103,8 @@ model Licence {
|
||||
install Install?
|
||||
invoices Invoice[]
|
||||
licenceChanges LicenceChange[]
|
||||
|
||||
@@index([customerId, product])
|
||||
}
|
||||
|
||||
enum BillingCycle {
|
||||
@@ -104,8 +119,12 @@ model Install {
|
||||
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
|
||||
licenceId String? @unique
|
||||
licence Licence? @relation(fields: [licenceId], references: [id], onDelete: SetNull)
|
||||
// Hub 2.0: the licence's product, set when the install registers.
|
||||
product Product @default(events)
|
||||
name String
|
||||
url String
|
||||
// Protocol v2: the install's Ed25519 public key (PEM), shared with its linked products.
|
||||
publicKey String?
|
||||
// The install's HMAC secret, AES-GCM encrypted: the Hub needs it to check signatures.
|
||||
secret String
|
||||
version String?
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Before deploying Hub 2.0: checks the database can take the 2.0 migrations, and lists what to
|
||||
* sort out first. Changes nothing.
|
||||
*
|
||||
* npm run check:hub2
|
||||
*
|
||||
* Works before and after the 2.0 migrations (it reads the tables directly).
|
||||
* - Hub 2.0 allows one licence per product per customer that isn't revoked. Every licence before
|
||||
* 2.0 is an Events licence, so a customer with two open licences stops the migration: revoke
|
||||
* the one that isn't used (its install, if any, stops reporting).
|
||||
*/
|
||||
|
||||
require('dotenv').config();
|
||||
const prisma = require('../src/config/db');
|
||||
|
||||
async function main() {
|
||||
const columns = await prisma.$queryRaw`SELECT column_name FROM information_schema.columns WHERE table_name = 'Licence' AND column_name = 'product'`;
|
||||
const hasProduct = columns.length > 0;
|
||||
const rows = hasProduct
|
||||
? await prisma.$queryRawUnsafe(`SELECT c.name, l."customerId", l.product::text AS product, count(*)::int AS n,
|
||||
string_agg(l.key || ' (' || l.status::text || ')', ', ' ORDER BY l."createdAt") AS keys
|
||||
FROM "Licence" l JOIN "Customer" c ON c.id = l."customerId"
|
||||
WHERE l.status <> 'revoked' GROUP BY c.name, l."customerId", l.product HAVING count(*) > 1 ORDER BY c.name`)
|
||||
: await prisma.$queryRawUnsafe(`SELECT c.name, l."customerId", 'events' AS product, count(*)::int AS n,
|
||||
string_agg(l.key || ' (' || l.status::text || ')', ', ' ORDER BY l."createdAt") AS keys
|
||||
FROM "Licence" l JOIN "Customer" c ON c.id = l."customerId"
|
||||
WHERE l.status <> 'revoked' GROUP BY c.name, l."customerId" HAVING count(*) > 1 ORDER BY c.name`);
|
||||
|
||||
if (!rows.length) {
|
||||
console.log('OK: every customer has at most one open licence per product. Hub 2.0 can be deployed.');
|
||||
return 0;
|
||||
}
|
||||
console.log('Hub 2.0 allows one open (not revoked) licence per product per customer. Revoke the extra ones first:');
|
||||
for (const r of rows) console.log(` - ${r.name}: ${r.n} ${r.product} licences: ${r.keys}`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
main()
|
||||
.then(code => prisma.$disconnect().then(() => process.exit(code)))
|
||||
.catch(async e => {
|
||||
console.error('The check failed:', e.message);
|
||||
await prisma.$disconnect().catch(() => {});
|
||||
process.exit(2);
|
||||
});
|
||||
+19
-11
@@ -4,7 +4,8 @@ const express = require('express');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
const prisma = require('../config/db');
|
||||
const { protect } = require('../middleware/auth');
|
||||
const { licenceKey } = require('../utils/crypto');
|
||||
const { generateLicence, checkReopen } = require('../utils/licences');
|
||||
const { isProduct, PRODUCT_NAMES } = require('../utils/products');
|
||||
const { audit } = require('../utils/audit');
|
||||
const { getSettings, setSettings } = require('../utils/settings');
|
||||
const { problems, compareVersions } = require('../utils/alerts');
|
||||
@@ -24,7 +25,7 @@ const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardH
|
||||
const wrap = fn => (req, res) => fn(req, res).catch(e => {
|
||||
const status = e.status || 500;
|
||||
if (status >= 500) console.error('[admin]', e);
|
||||
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message });
|
||||
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message, ...(e.code && e.status ? { code: e.code } : {}) });
|
||||
});
|
||||
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
const text = (v, max = 500) => (v == null || String(v).trim() === '' ? null : String(v).trim().slice(0, max));
|
||||
@@ -42,6 +43,7 @@ function summary(install, settings, now = new Date()) {
|
||||
const worst = current.some(p => p.level === 'critical') ? 'critical' : current.some(p => p.level === 'warning') ? 'warning' : 'ok';
|
||||
return {
|
||||
id: install.id,
|
||||
product: install.product,
|
||||
name: install.name,
|
||||
url: install.url,
|
||||
customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null,
|
||||
@@ -87,7 +89,7 @@ router.get('/dashboard', wrap(async (req, res) => {
|
||||
router.get('/customers', wrap(async (req, res) => {
|
||||
const customers = await prisma.customer.findMany({
|
||||
orderBy: { name: 'asc' },
|
||||
include: { licences: { select: { id: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, url: true, lastHeartbeatAt: true } } },
|
||||
include: { licences: { select: { id: true, product: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, product: true, url: true, lastHeartbeatAt: true } } },
|
||||
});
|
||||
res.json(customers);
|
||||
}));
|
||||
@@ -153,23 +155,29 @@ function licenceData(body, { partial = false } = {}) {
|
||||
return data;
|
||||
}
|
||||
|
||||
// "Generate": a new licence with a fresh key for a customer.
|
||||
// "Generate": a new licence with a fresh key for a customer, for one product (Events unless
|
||||
// another is given). A customer has one open licence per product; its Accounts licence (free)
|
||||
// is created with its first other product.
|
||||
router.post('/customers/:id/licences', wrap(async (req, res) => {
|
||||
const customer = await prisma.customer.findUnique({ where: { id: req.params.id } });
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
let licence;
|
||||
for (let attempt = 0; !licence && attempt < 5; attempt++) {
|
||||
licence = await prisma.licence.create({ data: { ...licenceData(req.body), customerId: customer.id, key: licenceKey() } }).catch(e => (e.code === 'P2002' ? null : Promise.reject(e)));
|
||||
}
|
||||
await audit(req, 'licence_generated', licence.id, { customer: customer.name, expiresAt: licence.expiresAt });
|
||||
res.status(201).json(licence);
|
||||
const product = req.body?.product ?? 'events';
|
||||
if (!isProduct(product)) throw bad('Product must be events, accounts, website or app.');
|
||||
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data: licenceData(req.body) });
|
||||
await audit(req, 'licence_generated', licence.id, { customer: customer.name, product, expiresAt: licence.expiresAt });
|
||||
if (accounts) await audit(req, 'licence_generated', accounts.id, { customer: customer.name, product: 'accounts', automatic: true });
|
||||
res.status(201).json({ ...licence, accountsLicence: accounts });
|
||||
}));
|
||||
|
||||
router.put('/licences/:id', wrap(async (req, res) => {
|
||||
const existing = await prisma.licence.findUnique({ where: { id: req.params.id } });
|
||||
if (!existing) throw bad('Licence not found', 404);
|
||||
const data = licenceData(req.body, { partial: true });
|
||||
const licence = await prisma.licence.update({ where: { id: existing.id }, data });
|
||||
await checkReopen(prisma, existing, data.status);
|
||||
const licence = await prisma.licence.update({ where: { id: existing.id }, data }).catch(e => {
|
||||
if (e.code === 'P2002') throw Object.assign(bad(`This customer already has an open ${PRODUCT_NAMES[existing.product]} licence.`, 409), { code: 'PRODUCT_LICENCE_EXISTS' });
|
||||
throw e;
|
||||
});
|
||||
await audit(req, 'licence_updated', licence.id, { changed: Object.keys(data), status: licence.status, expiresAt: licence.expiresAt });
|
||||
res.json(licence);
|
||||
}));
|
||||
|
||||
@@ -12,6 +12,7 @@ const billing = require('../utils/billing');
|
||||
const compute = require('../utils/billing/compute');
|
||||
const { ymd, day, today } = require('../utils/billing/dates');
|
||||
const { TIERS } = require('../utils/billing/tiers');
|
||||
const { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(protect);
|
||||
@@ -279,6 +280,10 @@ router.put('/licences/:id', wrap(async (req, res) => {
|
||||
}
|
||||
}
|
||||
const merged = { ...existing, ...data };
|
||||
// Until billing per customer (Hub 2.0 step 4) only Events has prices; Accounts is never invoiced.
|
||||
if (merged.billingCycle !== 'none' && !BILLABLE.includes(existing.product)) {
|
||||
throw bad(`${PRODUCT_NAMES[existing.product]} licences can't be invoiced yet.`);
|
||||
}
|
||||
if (merged.billingCycle !== 'none') {
|
||||
if (!merged.billingStart) throw bad('Set the date billing starts.');
|
||||
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
|
||||
|
||||
@@ -17,6 +17,7 @@ const { sendMail } = require('../utils/mail');
|
||||
const { releasesForInstall } = require('../utils/releases');
|
||||
const { noticesForInstall } = require('../utils/notices');
|
||||
const ai = require('../utils/ai');
|
||||
const { PRODUCT_NAMES } = require('../utils/products');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -91,6 +92,11 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
const licence = await prisma.licence.findUnique({ where: { key: normaliseLicenceKey(body.licenceKey) }, include: { install: true, customer: true } });
|
||||
if (!licence) return fail(res, 404, 'LICENCE_NOT_FOUND', 'That licence key was not found. Check it, or ask your provider for your key.');
|
||||
if (licence.status === 'revoked') return fail(res, 403, 'LICENCE_REVOKED', 'This licence has been revoked.');
|
||||
// Protocol v1 is Cross Events only; other products register with v2 (Hub 2.0 step 2).
|
||||
const product = 'events';
|
||||
if (licence.product !== product) {
|
||||
return fail(res, 409, 'WRONG_PRODUCT', `This is a ${PRODUCT_NAMES[licence.product]} licence key, not a ${PRODUCT_NAMES[product]} one. Check you copied the right key.`);
|
||||
}
|
||||
if (licence.install && licence.install.url !== url) {
|
||||
return fail(res, 409, 'LICENCE_IN_USE', 'This licence is already used by another site. Ask your provider to release it if you have moved.');
|
||||
}
|
||||
@@ -111,7 +117,7 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
// Same licence, same site → re-register (new secret, same id).
|
||||
const install = licence.install
|
||||
? await prisma.install.update({ where: { id: licence.install.id }, data })
|
||||
: await prisma.install.create({ data: { ...data, customerId: licence.customerId, licenceId: licence.id } });
|
||||
: 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();
|
||||
@@ -197,7 +203,7 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
|
||||
const name = await customerName();
|
||||
await sendMail({
|
||||
to: settings.alert_email,
|
||||
subject: `Cross Events Hub: update request changed by ${name}`,
|
||||
subject: `Cross Code Hub: update request changed by ${name}`,
|
||||
text: `${name} (${install.url}) now asks to be updated from ${current} to ${latest}${previous ? ` instead of ${previous}` : ''}.\n\n${link}`,
|
||||
}).catch(e => console.warn('[update-request] email failed:', e?.message));
|
||||
}
|
||||
@@ -209,7 +215,7 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
|
||||
const name = await customerName();
|
||||
await sendMail({
|
||||
to: settings.alert_email,
|
||||
subject: `Cross Events Hub: update requested by ${name}`,
|
||||
subject: `Cross Code Hub: update requested by ${name}`,
|
||||
text: `${name} (${install.url}) would like to be updated from ${current} to ${latest}.\n\n${link}`,
|
||||
}).catch(e => console.warn('[update-request] email failed:', e?.message));
|
||||
}
|
||||
@@ -238,7 +244,7 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req,
|
||||
const customer = await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } });
|
||||
await sendMail({
|
||||
to: settings.alert_email,
|
||||
subject: `Cross Events Hub: update request withdrawn by ${customer?.name || install.name}`,
|
||||
subject: `Cross Code Hub: update request withdrawn by ${customer?.name || install.name}`,
|
||||
text: `${customer?.name || install.name} (${install.url}) withdrew their update request. No need to update the site for now.\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`,
|
||||
}).catch(e => console.warn('[update-request] email failed:', e?.message));
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ async function runAlerts(now = new Date()) {
|
||||
if (newAlerts.length && settings.alert_email) {
|
||||
await sendMail({
|
||||
to: settings.alert_email,
|
||||
subject: `Cross Events Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`,
|
||||
subject: `Cross Code Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`,
|
||||
text: `${newAlerts.join('\n')}\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/`,
|
||||
}).catch(e => console.warn('[alerts] email failed:', e?.message));
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ const pdf = require('./pdf');
|
||||
const { layout, sendBillingEmail } = require('./email');
|
||||
const { ymd, day, today, saHour, addDays, longDate, periodLabel, money } = require('./dates');
|
||||
const { planPrice, tierNamed } = require('./tiers');
|
||||
const { BILLABLE } = require('../products');
|
||||
|
||||
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
const hubLink = p => `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}${p}`;
|
||||
@@ -97,7 +98,7 @@ async function createDueDrafts(now, settings) {
|
||||
const days = parseInt(settings.billing_draft_days, 10) || 14;
|
||||
const horizon = addDays(today(now), days);
|
||||
const licences = await prisma.licence.findMany({
|
||||
where: { status: 'active', billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } },
|
||||
where: { status: 'active', product: { in: BILLABLE }, billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } },
|
||||
select: { id: true },
|
||||
});
|
||||
let made = 0;
|
||||
|
||||
@@ -18,7 +18,7 @@ const W = 595.28 - M * 2; // content width
|
||||
/** Renders `draw(doc)` into a PDF and resolves with its bytes. */
|
||||
function render(draw, { title, draft = false } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const doc = new PDFDocument({ size: 'A4', margins: { top: M, bottom: 70, left: M, right: M }, bufferPages: true, info: { Title: title, Author: 'Cross Code', Creator: 'Cross Events Hub' } });
|
||||
const doc = new PDFDocument({ size: 'A4', margins: { top: M, bottom: 70, left: M, right: M }, bufferPages: true, info: { Title: title, Author: 'Cross Code', Creator: 'Cross Code Hub' } });
|
||||
const chunks = [];
|
||||
doc.on('data', c => chunks.push(c));
|
||||
doc.on('end', () => resolve(Buffer.concat(chunks)));
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
const { KEY_PREFIXES } = require('./products');
|
||||
|
||||
let cachedKey = null;
|
||||
function key() {
|
||||
@@ -35,11 +36,16 @@ function decrypt(stored) {
|
||||
// No 0/O, 1/I/L, 5/S, 8/B — easy to read out over the phone.
|
||||
const KEY_ALPHABET = 'ACDEFGHJKMNPQRTUVWXY234679';
|
||||
|
||||
/** A licence key: CEH-XXXX-XXXX-XXXX-XXXX (16 characters from 26, ~75 bits of randomness). */
|
||||
function licenceKey() {
|
||||
/**
|
||||
* A licence key for a product: CEH-XXXX-XXXX-XXXX-XXXX for Events, CCA-/CCW-/CCP- for Accounts,
|
||||
* Website and App (16 characters from 26, ~75 bits of randomness).
|
||||
*/
|
||||
function licenceKey(product = 'events') {
|
||||
const prefix = KEY_PREFIXES[product];
|
||||
if (!prefix) throw new Error(`Unknown product: ${product}`);
|
||||
const bytes = crypto.randomBytes(20);
|
||||
const chars = Array.from(bytes, b => KEY_ALPHABET[b % KEY_ALPHABET.length]).join('');
|
||||
return `CEH-${chars.slice(0, 4)}-${chars.slice(4, 8)}-${chars.slice(8, 12)}-${chars.slice(12, 16)}`;
|
||||
return `${prefix}-${chars.slice(0, 4)}-${chars.slice(4, 8)}-${chars.slice(8, 12)}-${chars.slice(12, 16)}`;
|
||||
}
|
||||
|
||||
/** Tidy what someone typed: upper case, no spaces. */
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Creating licences (Hub 2.0): one licence per product per customer that isn't revoked, a key
|
||||
* with the product's prefix, and the free Accounts licence that comes with any other product.
|
||||
*/
|
||||
|
||||
const { licenceKey } = require('./crypto');
|
||||
const { PRODUCT_NAMES, isProduct } = require('./products');
|
||||
|
||||
const conflict = (message, code) => Object.assign(new Error(message), { status: 409, code });
|
||||
|
||||
/** The customer's licence for a product that isn't revoked, or null. */
|
||||
function openLicence(db, customerId, product) {
|
||||
return db.licence.findFirst({ where: { customerId, product, status: { not: 'revoked' } } });
|
||||
}
|
||||
|
||||
const productTaken = product =>
|
||||
conflict(`This customer already has a ${PRODUCT_NAMES[product]} licence. Revoke it first to issue a new one (a customer has one of each product).`, 'PRODUCT_LICENCE_EXISTS');
|
||||
|
||||
/**
|
||||
* A new licence for `product`, with a fresh key. A key collision (vanishingly rare) is retried; a
|
||||
* second open licence for the product is refused with 409 PRODUCT_LICENCE_EXISTS, also when two
|
||||
* requests race (the partial unique index catches the second).
|
||||
*/
|
||||
async function createLicence(db, { customerId, product = 'events', data = {} }) {
|
||||
if (!isProduct(product)) throw Object.assign(new Error('Unknown product.'), { status: 400 });
|
||||
if (await openLicence(db, customerId, product)) throw productTaken(product);
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
try {
|
||||
return await db.licence.create({ data: { ...data, customerId, product, key: licenceKey(product) } });
|
||||
} catch (e) {
|
||||
if (e?.code !== 'P2002') throw e;
|
||||
if (await openLicence(db, customerId, product)) throw productTaken(product);
|
||||
// Otherwise the key collided: try another.
|
||||
}
|
||||
}
|
||||
throw new Error('Could not generate a unique licence key.');
|
||||
}
|
||||
|
||||
/**
|
||||
* The customer's Accounts licence, created (free, never invoiced) if it has none that isn't
|
||||
* revoked. Returns { licence, created }.
|
||||
*/
|
||||
async function ensureAccountsLicence(db, customerId) {
|
||||
const existing = await openLicence(db, customerId, 'accounts');
|
||||
if (existing) return { licence: existing, created: false };
|
||||
try {
|
||||
const licence = await createLicence(db, { customerId, product: 'accounts', data: { plan: 'included', status: 'active', notes: 'Comes with the church\'s other products (free).' } });
|
||||
return { licence, created: true };
|
||||
} catch (e) {
|
||||
// Created by a request running at the same time.
|
||||
if (e.code === 'PRODUCT_LICENCE_EXISTS') return { licence: await openLicence(db, customerId, 'accounts'), created: false };
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a licence for a customer, plus its Accounts licence when this is a product other than
|
||||
* Accounts and it has none yet. Returns { licence, accounts } (accounts: the licence if created now).
|
||||
*/
|
||||
async function generateLicence(db, { customerId, product = 'events', data = {} }) {
|
||||
const licence = await createLicence(db, { customerId, product, data });
|
||||
if (product === 'accounts') return { licence, accounts: null };
|
||||
const { licence: accounts, created } = await ensureAccountsLicence(db, customerId);
|
||||
return { licence, accounts: created ? accounts : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Changing a licence's status back from revoked would give the customer two open licences for the
|
||||
* product: refused with 409 PRODUCT_LICENCE_EXISTS.
|
||||
*/
|
||||
async function checkReopen(db, licence, nextStatus) {
|
||||
if (licence.status !== 'revoked' || !nextStatus || nextStatus === 'revoked') return;
|
||||
const other = await openLicence(db, licence.customerId, licence.product);
|
||||
if (other && other.id !== licence.id) throw productTaken(licence.product);
|
||||
}
|
||||
|
||||
module.exports = { openLicence, createLicence, ensureAccountsLicence, generateLicence, checkReopen };
|
||||
@@ -61,8 +61,8 @@ async function testSmtp(overrides, to) {
|
||||
await t.sendMail({
|
||||
from: fromAddress(smtp),
|
||||
to,
|
||||
subject: 'Cross Events Hub: test email',
|
||||
text: `This is a test email from the Cross Events Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`,
|
||||
subject: 'Cross Code Hub: test email',
|
||||
text: `This is a test email from the Cross Code Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`,
|
||||
});
|
||||
} finally {
|
||||
t.close();
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The Cross Code products a church can have (Hub 2.0, ROADMAP-v3 §5). The same names as the
|
||||
* `Product` enum in schema.prisma and `productSchema` in @crosscode/contracts.
|
||||
*
|
||||
* - A customer has at most one licence per product that isn't revoked (a partial unique index).
|
||||
* - Accounts is free and comes with any other product: its licence is created with the first one.
|
||||
*/
|
||||
|
||||
const PRODUCTS = ['events', 'accounts', 'website', 'app'];
|
||||
|
||||
const PRODUCT_NAMES = {
|
||||
events: 'Cross Events',
|
||||
accounts: 'Accounts',
|
||||
website: 'Church Website',
|
||||
app: 'Church App',
|
||||
};
|
||||
|
||||
/** Licence key prefixes. CEH- (Cross Events Hub) predates 2.0 and stays for Events. */
|
||||
const KEY_PREFIXES = {
|
||||
events: 'CEH',
|
||||
accounts: 'CCA',
|
||||
website: 'CCW',
|
||||
app: 'CCP',
|
||||
};
|
||||
|
||||
/** The product a licence key is for, from its prefix, or null. */
|
||||
function productOfKey(key) {
|
||||
const prefix = String(key || '').slice(0, 3).toUpperCase();
|
||||
return PRODUCTS.find(p => KEY_PREFIXES[p] === prefix) || null;
|
||||
}
|
||||
|
||||
const isProduct = p => PRODUCTS.includes(p);
|
||||
|
||||
/**
|
||||
* Products that can be invoiced. Until billing per customer (Hub 2.0 step 4) only Events has
|
||||
* prices; Accounts is never invoiced.
|
||||
*/
|
||||
const BILLABLE = ['events'];
|
||||
|
||||
module.exports = { PRODUCTS, PRODUCT_NAMES, KEY_PREFIXES, BILLABLE, productOfKey, isProduct };
|
||||
@@ -67,7 +67,7 @@ function verifyCode(secret, code, now = Date.now()) {
|
||||
}
|
||||
|
||||
/** The otpauth:// link an authenticator app scans (as a QR code). */
|
||||
function otpauthUrl(secret, account, issuer = 'Cross Events Hub') {
|
||||
function otpauthUrl(secret, account, issuer = 'Cross Code Hub') {
|
||||
return `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
// Hub 2.0 step 1: products, licence keys per product, one open licence per product per customer
|
||||
// (with the partial unique index simulated), the free Accounts licence, and protocol v1
|
||||
// registering Events licences only. In-memory database.
|
||||
|
||||
const mockLicences = [];
|
||||
const mockInstalls = [];
|
||||
const isOpen = l => l.status !== 'revoked';
|
||||
const mockDb = {
|
||||
licence: {
|
||||
findFirst: jest.fn(async ({ where }) => mockLicences.find(l => l.customerId === where.customerId && l.product === where.product && (!where.status?.not || l.status !== where.status.not)) || null),
|
||||
findUnique: jest.fn(async ({ where, include }) => {
|
||||
const l = mockLicences.find(x => (where.key ? x.key === where.key : x.id === where.id));
|
||||
if (!l) return null;
|
||||
return include ? { ...l, install: mockInstalls.find(i => i.licenceId === l.id) || null, customer: { id: l.customerId, name: 'Hope Church' } } : l;
|
||||
}),
|
||||
create: jest.fn(async ({ data }) => {
|
||||
// The unique key and the partial unique index on (customerId, product) WHERE status <> 'revoked'.
|
||||
if (mockLicences.some(l => l.key === data.key)) throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
|
||||
const status = data.status || 'active';
|
||||
if (status !== 'revoked' && mockLicences.some(l => isOpen(l) && l.customerId === data.customerId && l.product === data.product)) {
|
||||
throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
|
||||
}
|
||||
const row = { id: `lic_${mockLicences.length + 1}`, status, plan: 'standard', createdAt: new Date(), ...data };
|
||||
mockLicences.push(row);
|
||||
return row;
|
||||
}),
|
||||
},
|
||||
install: {
|
||||
create: jest.fn(async ({ data }) => { const row = { id: `inst_${mockInstalls.length + 1}`, ...data }; mockInstalls.push(row); return row; }),
|
||||
update: jest.fn(),
|
||||
},
|
||||
installEvent: { create: jest.fn(async () => ({})) },
|
||||
};
|
||||
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/notices', () => ({ noticesForInstall: jest.fn(async () => []) }));
|
||||
jest.mock('../src/utils/licenceToken', () => ({ sign: jest.fn(() => 'hel1.token.sig'), buildPayload: jest.fn(() => ({})) }));
|
||||
|
||||
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123';
|
||||
|
||||
const express = require('express');
|
||||
const { licenceKey } = require('../src/utils/crypto');
|
||||
const { PRODUCTS, KEY_PREFIXES, productOfKey } = require('../src/utils/products');
|
||||
const { generateLicence, createLicence, checkReopen } = require('../src/utils/licences');
|
||||
const { productSchema } = require('@crosscode/contracts');
|
||||
|
||||
beforeEach(() => { mockLicences.length = 0; mockInstalls.length = 0; });
|
||||
|
||||
describe('products', () => {
|
||||
test('the Hub has the same products as the contracts', () => {
|
||||
expect([...PRODUCTS].sort()).toEqual([...productSchema.options].sort());
|
||||
});
|
||||
|
||||
test.each(PRODUCTS)('%s keys have their own prefix and are recognised', product => {
|
||||
const key = licenceKey(product);
|
||||
expect(key).toMatch(new RegExp(`^${KEY_PREFIXES[product]}(-[ACDEFGHJKMNPQRTUVWXY234679]{4}){4}$`));
|
||||
expect(productOfKey(key)).toBe(product);
|
||||
});
|
||||
|
||||
test('Events keys keep CEH-, and the default is Events', () => {
|
||||
expect(licenceKey()).toMatch(/^CEH-/);
|
||||
expect(() => licenceKey('nope')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('licences', () => {
|
||||
test('the first product licence comes with a free Accounts licence', async () => {
|
||||
const { licence, accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'website', data: { status: 'active' } });
|
||||
expect(licence).toMatchObject({ product: 'website', key: expect.stringMatching(/^CCW-/) });
|
||||
expect(accounts).toMatchObject({ product: 'accounts', plan: 'included', key: expect.stringMatching(/^CCA-/) });
|
||||
});
|
||||
|
||||
test('a later product licence does not make a second Accounts licence', async () => {
|
||||
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
|
||||
const { accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'app', data: {} });
|
||||
expect(accounts).toBeNull();
|
||||
expect(mockLicences.filter(l => l.product === 'accounts')).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('a second open licence for the same product is refused', async () => {
|
||||
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
|
||||
await expect(generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} })).rejects.toMatchObject({ status: 409, code: 'PRODUCT_LICENCE_EXISTS' });
|
||||
});
|
||||
|
||||
test('another customer can have the same product', async () => {
|
||||
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
|
||||
await expect(generateLicence(mockDb, { customerId: 'c2', product: 'events', data: {} })).resolves.toBeTruthy();
|
||||
});
|
||||
|
||||
test('a revoked licence can be replaced', async () => {
|
||||
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
|
||||
licence.status = 'revoked';
|
||||
await expect(generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} })).resolves.toBeTruthy();
|
||||
});
|
||||
|
||||
test('a race is caught by the unique index', async () => {
|
||||
// Both requests pass the check before either inserts: the second insert hits the index.
|
||||
mockDb.licence.findFirst.mockResolvedValueOnce(null);
|
||||
await createLicence(mockDb, { customerId: 'c1', product: 'app', data: {} });
|
||||
mockDb.licence.findFirst.mockResolvedValueOnce(null);
|
||||
await expect(createLicence(mockDb, { customerId: 'c1', product: 'app', data: {} })).rejects.toMatchObject({ code: 'PRODUCT_LICENCE_EXISTS' });
|
||||
});
|
||||
|
||||
test('un-revoking is refused when the product has another open licence', async () => {
|
||||
const { licence: old } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
|
||||
old.status = 'revoked';
|
||||
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
|
||||
await expect(checkReopen(mockDb, old, 'active')).rejects.toMatchObject({ code: 'PRODUCT_LICENCE_EXISTS' });
|
||||
await expect(checkReopen(mockDb, old, 'revoked')).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('unknown products are refused', async () => {
|
||||
await expect(createLicence(mockDb, { customerId: 'c1', product: 'shop' })).rejects.toMatchObject({ status: 400 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('register (protocol v1)', () => {
|
||||
let server;
|
||||
let base;
|
||||
beforeAll(async () => {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api', require('../src/routes/installApi'));
|
||||
await new Promise(resolve => { server = app.listen(0, '127.0.0.1', resolve); });
|
||||
base = `http://127.0.0.1:${server.address().port}/api`;
|
||||
});
|
||||
afterAll(() => new Promise(resolve => server.close(resolve)));
|
||||
|
||||
const register = key => fetch(`${base}/installs/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ protocolVersion: 1, licenceKey: key, install: { name: 'Hope Church', url: 'https://events.hope.test', version: '2.1.1' } }),
|
||||
});
|
||||
|
||||
test('an Events licence registers, and the install is an Events install', async () => {
|
||||
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
|
||||
const res = await register(licence.key);
|
||||
expect(res.status).toBe(201);
|
||||
expect(mockInstalls[0]).toMatchObject({ product: 'events', licenceId: licence.id });
|
||||
});
|
||||
|
||||
test('another product\'s licence is refused with WRONG_PRODUCT', async () => {
|
||||
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'website', data: {} });
|
||||
const res = await register(licence.key);
|
||||
expect(res.status).toBe(409);
|
||||
expect(await res.json()).toMatchObject({ code: 'WRONG_PRODUCT' });
|
||||
expect(mockInstalls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
BIN
Binary file not shown.
@@ -2,8 +2,10 @@
|
||||
|
||||
Cross Events Hub becomes **Cross Code Hub**: every product's customers, licences, stats, AI and
|
||||
billing in one place (ROADMAP-v3 §5, phase 1, in `hope-events/docs/ROADMAP-v3.md`). Planned
|
||||
2026-11-04. Each step is its own branch, merged into `main` with its tests when it's done; only the
|
||||
finished set is tagged and deployed as **2.0.0** (as Cross Events 2.0 was built).
|
||||
2026-11-04. Each step is its own branch (`feat/hub2-<step>`), merged with its tests into
|
||||
**`release/2.0`** when it's done; `release/2.0` is merged into `main` and tagged **2.0.0** only when
|
||||
every step is in (as Cross Events 2.0 was built). `main` stays at 1.7.x until then, so
|
||||
`scripts/deploy.sh` (which deploys the latest `main` by default) never ships half of 2.0.
|
||||
|
||||
**Cross Events 2.1.x installs keep working unchanged:** protocol v1 replies stay identical. Events
|
||||
moves to protocol v2 in Events 2.4.0.
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ArrowLeft, Copy, KeyRound } from "lucide-react";
|
||||
import { api, errorText } from "@/lib/api";
|
||||
import { ago, fmtDate } from "@/lib/format";
|
||||
import { PLANS } from "@/lib/tiers";
|
||||
import { KEY_WHERE, PRODUCTS, PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
|
||||
import type { Customer, Licence, LicenceStatus } from "@/lib/types";
|
||||
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
|
||||
import { CustomerBilling } from "@/components/billing/CustomerBilling";
|
||||
@@ -62,6 +63,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
||||
<div className="card space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<KeyRound className="h-4 w-4 text-slate-400" />
|
||||
<span className="font-semibold">{PRODUCT_NAMES[licence.product]}</span>
|
||||
<code className="text-sm font-semibold tracking-wide">{licence.key}</code>
|
||||
<button className="text-xs text-indigo-600 hover:underline" onClick={() => navigator.clipboard?.writeText(licence.key)} aria-label="Copy key"><Copy className="inline h-3.5 w-3.5" /> Copy</button>
|
||||
<span className="ml-auto"><Badge value={licence.status} /></span>
|
||||
@@ -69,16 +71,26 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
|
||||
<div className="text-sm text-slate-600">
|
||||
{licence.install
|
||||
? <>Used by <Link href={`/installs/${licence.install.id}`} className="text-indigo-600 hover:underline">{licence.install.url}</Link> · last heartbeat {ago(licence.install.lastHeartbeatAt)}</>
|
||||
: "Not used yet — enter this key in the church's Cross Events setup (or Site settings → Licence)."}
|
||||
: `Not used yet — enter this key in ${KEY_WHERE[licence.product]}.`}
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-6">
|
||||
<div>
|
||||
<label className="label" htmlFor={`plan-${licence.id}`}>Plan</label>
|
||||
<select id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })}>
|
||||
{!PLANS.includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
|
||||
{PLANS.map(p => <option key={p} value={p}>{p}</option>)}
|
||||
</select>
|
||||
<p className="mt-1 text-xs text-slate-500">Shown on the church's Licence page. Billing and founding status are under Billing below.</p>
|
||||
{licence.product === "events" ? (
|
||||
<select id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })}>
|
||||
{!PLANS.includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
|
||||
{PLANS.map(p => <option key={p} value={p}>{p}</option>)}
|
||||
</select>
|
||||
) : licence.product === "accounts" ? (
|
||||
<input id={`plan-${licence.id}`} className="input" value="Included" disabled />
|
||||
) : (
|
||||
<input id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })} />
|
||||
)}
|
||||
<p className="mt-1 text-xs text-slate-500">
|
||||
{licence.product === "accounts"
|
||||
? "Free: comes with the church's other products."
|
||||
: "Shown on the church's Licence page. Billing and founding status are under Billing below."}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Status</label>
|
||||
@@ -125,7 +137,7 @@ export default function CustomerPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [c, setC] = useState<Customer | null>(null);
|
||||
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "" });
|
||||
const [newLicence, setNewLicence] = useState({ expiresAt: "", graceDays: "14" });
|
||||
const [newLicence, setNewLicence] = useState<{ product: Product | ""; expiresAt: string; graceDays: string }>({ product: "", expiresAt: "", graceDays: "14" });
|
||||
const [msg, setMsg] = useState<Msg>(null);
|
||||
|
||||
const load = useCallback(() => api<Customer>(`/api/admin/customers/${id}`).then(x => {
|
||||
@@ -136,6 +148,12 @@ export default function CustomerPage() {
|
||||
|
||||
if (!c) return msg ? <Message msg={msg} /> : <Loading />;
|
||||
|
||||
// One open (not revoked) licence per product; Accounts comes with the first other product.
|
||||
const taken = new Set(c.licences.filter(l => l.status !== "revoked").map(l => l.product));
|
||||
const available = PRODUCTS.filter(p => !taken.has(p));
|
||||
const product: Product | undefined = newLicence.product && available.includes(newLicence.product) ? newLicence.product : available.find(p => p !== "accounts") || available[0];
|
||||
const licences = [...c.licences].sort((a, b) => byProduct(a, b) || (a.status === "revoked" ? 1 : 0) - (b.status === "revoked" ? 1 : 0));
|
||||
|
||||
const saveDetails = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
@@ -148,11 +166,15 @@ export default function CustomerPage() {
|
||||
const generate = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const l = await api<Licence>(`/api/admin/customers/${id}/licences`, {
|
||||
const l = await api<Licence & { accountsLicence: Licence | null }>(`/api/admin/customers/${id}/licences`, {
|
||||
method: "POST",
|
||||
body: { expiresAt: newLicence.expiresAt ? `${newLicence.expiresAt}T23:59:59+02:00` : null, graceDays: newLicence.graceDays },
|
||||
body: { product, expiresAt: newLicence.expiresAt ? `${newLicence.expiresAt}T23:59:59+02:00` : null, graceDays: newLicence.graceDays },
|
||||
});
|
||||
setMsg({
|
||||
type: "ok",
|
||||
text: `${PRODUCT_NAMES[l.product]} licence ${l.key} created. Send it to the church for their setup.`
|
||||
+ (l.accountsLicence ? ` Their Accounts licence (free) was created too: ${l.accountsLicence.key}.` : ""),
|
||||
});
|
||||
setMsg({ type: "ok", text: `Licence ${l.key} created. Send it to the church for their setup.` });
|
||||
load();
|
||||
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
|
||||
};
|
||||
@@ -176,12 +198,21 @@ export default function CustomerPage() {
|
||||
|
||||
<div className="space-y-4">
|
||||
<h2 className="font-semibold">Licences</h2>
|
||||
{c.licences.map(l => <LicenceCard key={`${l.id}-${l.status}-${l.expiresAt}`} licence={l} onSaved={load} setMsg={setMsg} />)}
|
||||
{licences.map(l => <LicenceCard key={`${l.id}-${l.status}-${l.expiresAt}`} licence={l} onSaved={load} setMsg={setMsg} />)}
|
||||
{product ? (
|
||||
<form onSubmit={generate} className="card flex flex-wrap items-end gap-3">
|
||||
<div>
|
||||
<label className="label" htmlFor="new-product">Product</label>
|
||||
<select id="new-product" className="input" value={product} onChange={e => setNewLicence({ ...newLicence, product: e.target.value as Product })}>
|
||||
{available.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div><label className="label">Expires (optional)</label><input type="date" className="input" value={newLicence.expiresAt} onChange={e => setNewLicence({ ...newLicence, expiresAt: e.target.value })} /></div>
|
||||
<div><label className="label">Grace (days)</label><input type="number" min={0} max={90} className="input w-24" value={newLicence.graceDays} onChange={e => setNewLicence({ ...newLicence, graceDays: e.target.value })} /></div>
|
||||
<button className="btn-primary"><KeyRound className="h-4 w-4" /> Generate licence</button>
|
||||
<p className="w-full text-xs text-slate-500">One licence per product (revoke one to replace it). Accounts is free and is created with the first other product.</p>
|
||||
</form>
|
||||
) : <p className="text-sm text-slate-500">This customer has a licence for every product.</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { api, errorText } from "@/lib/api";
|
||||
import { ago } from "@/lib/format";
|
||||
import { matches, usePaged } from "@/lib/paging";
|
||||
import type { Customer } from "@/lib/types";
|
||||
import { PRODUCT_NAMES, byProduct } from "@/lib/products";
|
||||
import { Badge, Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
|
||||
|
||||
export default function CustomersPage() {
|
||||
@@ -56,8 +57,8 @@ export default function CustomersPage() {
|
||||
{paged.rows.map(c => (
|
||||
<tr key={c.id} className="border-t hover:bg-slate-50">
|
||||
<td className="p-3"><Link href={`/customers/${c.id}`} className="font-medium text-indigo-700 hover:underline">{c.name}</Link><div className="text-xs text-slate-500">{[c.contactName, c.email].filter(Boolean).join(" · ")}</div></td>
|
||||
<td className="p-3">{c.licences.length ? c.licences.map(l => <span key={l.id} className="mr-1"><Badge value={l.status} /></span>) : <span className="text-xs text-slate-400">none</span>}</td>
|
||||
<td className="p-3">{c.installs.length ? c.installs.map(i => <div key={i.id} className="text-xs">{i.url} <span className="text-slate-400">· {ago(i.lastHeartbeatAt)}</span></div>) : <span className="text-xs text-slate-400">not connected</span>}</td>
|
||||
<td className="p-3">{c.licences.length ? [...c.licences].sort(byProduct).map(l => <span key={l.id} className="mr-2 inline-flex items-center gap-1 text-xs">{PRODUCT_NAMES[l.product]} <Badge value={l.status} /></span>) : <span className="text-xs text-slate-400">none</span>}</td>
|
||||
<td className="p-3">{c.installs.length ? c.installs.map(i => <div key={i.id} className="text-xs"><span className="text-slate-500">{PRODUCT_NAMES[i.product]}:</span> {i.url} <span className="text-slate-400">· {ago(i.lastHeartbeatAt)}</span></div>) : <span className="text-xs text-slate-400">not connected</span>}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { api, errorText } from "@/lib/api";
|
||||
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 { Badge, Loading, Message, PageTitle, Pager } from "@/components/ui";
|
||||
|
||||
@@ -63,7 +64,7 @@ export default function InstallPage() {
|
||||
<>
|
||||
<Link href="/" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Installs</Link>
|
||||
<PageTitle
|
||||
title={d.customer.name}
|
||||
title={`${d.customer.name}: ${PRODUCT_NAMES[d.summary.product]}`}
|
||||
subtitle={<a href={d.url} target="_blank" rel="noopener noreferrer" className="text-indigo-600 hover:underline">{d.url}</a>}
|
||||
actions={<Badge value={d.summary.status} />}
|
||||
/>
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 { Badge, Loading, PageTitle, Pager, SearchInput, Stat } from "@/components/ui";
|
||||
|
||||
type Dashboard = {
|
||||
@@ -81,7 +82,7 @@ export default function OverviewPage() {
|
||||
<tr key={i.id} className="border-t align-top hover:bg-slate-50">
|
||||
<td className="p-3">
|
||||
<Link href={`/installs/${i.id}`} className="font-medium text-indigo-700 hover:underline">{i.customer?.name || i.name}</Link>
|
||||
<div className="text-xs text-slate-500">{i.url}</div>
|
||||
<div className="text-xs text-slate-500">{PRODUCT_NAMES[i.product]} · {i.url}</div>
|
||||
</td>
|
||||
<td className="p-3">
|
||||
<Badge value={i.status} />
|
||||
|
||||
@@ -290,7 +290,7 @@ export default function SettingsPage() {
|
||||
<label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={smtpPass.clear} onChange={e => setSmtpPass({ value: "", clear: e.target.checked })} /> Remove the saved password</label>
|
||||
)}
|
||||
</div>
|
||||
<div><label className="label" htmlFor="smtp_from">From address</label><input id="smtp_from" className="input" placeholder="Cross Events Hub <hub@crosscode.co.za>" value={settings.smtp_from ?? ""} onChange={e => setSettings({ ...settings, smtp_from: e.target.value })} /><p className="mt-1 text-xs text-slate-500">Blank uses the username.</p></div>
|
||||
<div><label className="label" htmlFor="smtp_from">From address</label><input id="smtp_from" className="input" placeholder="Cross Code Hub <hub@crosscode.co.za>" value={settings.smtp_from ?? ""} onChange={e => setSettings({ ...settings, smtp_from: e.target.value })} /><p className="mt-1 text-xs text-slate-500">Blank uses the username.</p></div>
|
||||
<button className="btn-primary">Save email settings</button>
|
||||
<div className="border-t border-slate-100 pt-3">
|
||||
<label className="label" htmlFor="smtp_test_to">Send a test email to</label>
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Cross Events Hub",
|
||||
title: "Cross Code Hub",
|
||||
description: "Installs, licences and health for Cross Events",
|
||||
robots: { index: false, follow: false },
|
||||
};
|
||||
|
||||
@@ -57,7 +57,7 @@ export default function LoginPage() {
|
||||
<div className="flex min-h-screen items-center justify-center p-4">
|
||||
<div className="card w-full max-w-sm">
|
||||
<Logo markOnly className="mb-3 h-10 w-10" />
|
||||
<h1 className="text-xl font-semibold">Cross Events Hub</h1>
|
||||
<h1 className="text-xl font-semibold">Cross Code Hub</h1>
|
||||
{step === "password" && (
|
||||
<form onSubmit={submitPassword} className="mt-5 space-y-4">
|
||||
<div>
|
||||
|
||||
@@ -13,7 +13,7 @@ const STATUS_TONE: Record<string, string> = {
|
||||
};
|
||||
const STATUS_LABEL: Record<string, string> = { ok: "Healthy", warning: "Warning", critical: "Critical", info: "Info" };
|
||||
|
||||
/** The Cross Events Hub mark (same artwork as app/icon.svg), with the name beside it unless markOnly. */
|
||||
/** The Cross Code Hub mark (same artwork as app/icon.svg), with the name beside it unless markOnly. */
|
||||
export function Logo({ className = "h-8 w-8", markOnly }: { className?: string; markOnly?: boolean }) {
|
||||
const mark = (
|
||||
<svg viewBox="0 0 64 64" className={`${className} shrink-0`} aria-hidden="true">
|
||||
@@ -25,7 +25,7 @@ export function Logo({ className = "h-8 w-8", markOnly }: { className?: string;
|
||||
return (
|
||||
<span className="flex items-center gap-2.5">
|
||||
{mark}
|
||||
<span className="font-semibold leading-tight">Cross Events Hub</span>
|
||||
<span className="font-semibold leading-tight">Cross Code Hub</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// The Cross Code products (Hub 2.0). The same list as backend/src/utils/products.js.
|
||||
|
||||
export type Product = "events" | "accounts" | "website" | "app";
|
||||
|
||||
export const PRODUCTS: Product[] = ["events", "accounts", "website", "app"];
|
||||
|
||||
export const PRODUCT_NAMES: Record<Product, string> = {
|
||||
events: "Cross Events",
|
||||
accounts: "Accounts",
|
||||
website: "Church Website",
|
||||
app: "Church App",
|
||||
};
|
||||
|
||||
/** Where the church enters a licence key, per product. */
|
||||
export const KEY_WHERE: Record<Product, string> = {
|
||||
events: "the church's Cross Events setup (or Site settings → Licence)",
|
||||
accounts: "the church's Accounts setup",
|
||||
website: "the church's Website setup",
|
||||
app: "the church's App setup",
|
||||
};
|
||||
|
||||
/** Product order for lists: Events, Accounts, Website, App. */
|
||||
export const byProduct = <T extends { product: Product }>(a: T, b: T) => PRODUCTS.indexOf(a.product) - PRODUCTS.indexOf(b.product);
|
||||
@@ -1,8 +1,11 @@
|
||||
import type { Product } from "./products";
|
||||
|
||||
export type Problem = { type: string; level: "info" | "warning" | "critical"; message: string };
|
||||
export type LicenceStatus = "active" | "suspended" | "revoked";
|
||||
|
||||
export type InstallSummary = {
|
||||
id: string;
|
||||
product: Product;
|
||||
name: string;
|
||||
url: string;
|
||||
customer: { id: string; name: string } | null;
|
||||
@@ -18,6 +21,7 @@ export type InstallSummary = {
|
||||
export type Licence = {
|
||||
id: string;
|
||||
key: string;
|
||||
product: Product;
|
||||
plan: string;
|
||||
status: LicenceStatus;
|
||||
expiresAt: string | null;
|
||||
@@ -38,7 +42,7 @@ export type Customer = {
|
||||
notes: string | null;
|
||||
createdAt: string;
|
||||
licences: Licence[];
|
||||
installs: { id: string; url: string; name?: string; lastHeartbeatAt: string | null; releasedAt?: string | null; version?: string | null }[];
|
||||
installs: { id: string; product: Product; url: string; name?: string; lastHeartbeatAt: string | null; releasedAt?: string | null; version?: string | null }[];
|
||||
};
|
||||
|
||||
export type Health = {
|
||||
|
||||
Reference in New Issue
Block a user