Hub 2.25.0: demo clients, and demo data for the Church Website

- A customer can be a demo client: every install a demo site (Accounts
  included, and any later install), never billed (billing off, no invoice
  drafted, sent or made by hand). Migration: Customer.isDemo, demoSince.
- Any install can be marked as a demo site; Events and the Website have
  demo data. The Website's eight demo churches need agent 1.6.0.
- Contracts 1.19.0 vendored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 09:20:10 +02:00
co-authored by Claude Opus 5.5
parent 7850de51ec
commit 8448babb08
24 changed files with 297 additions and 58 deletions
+29
View File
@@ -5,6 +5,35 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased] ## [Unreleased]
## [2.25.0] - 2026-11-27
One migration (`20261127120000_customer_demo`: `Customer.isDemo`, `Customer.demoSince`). No
API is removed. Contracts 1.19.0 (vendored).
### Added
- **Demo clients** (customer → More actions → "Make it a demo client…", typing its name). Every
install of the customer becomes a demo site, Accounts included, and so does any install it gets
later (new installs, Accounts added next to a product, sites found on a server or linked). It
isn't billed: its billing is set to "not invoiced" and can't be switched on while it's a demo
client, no invoice of it is drafted, sent or made by hand ("One-off invoice" is hidden), and the
next-invoice preview says so. Invoices it has that haven't gone out are left alone and named in
the message, to void. A demo client's installs can't be unmarked one by one; "Not a demo client
any more…" unmarks them all and leaves billing off until it's set up again. A "Demo client" badge
on the customer and "demo" in the customer list. `POST /api/admin/customers/:id/demo`
`{ isDemo, confirm }`, audited as `customer_marked_demo` / `customer_unmarked_demo`.
- **Demo data for the Church Website** (install → Load demo data…): eight demo churches, two per
template, each its own kind of church; the second of each starts on the template's other
recommended layouts. They replace the site's content and publish it, keeping the church's
profile, the site settings, the site icon and the admins. Needs agent 1.6.0 (refused before,
`AGENT_TOO_OLD`) and Website 1.3.0 on the site. The job is `seed-demo` with
`product: "website"`; Events' jobs keep their old form.
### Changed
- **Any install can be marked as a demo site**, not only Cross Events. Accounts and the App are a
tag only: "Load demo data…" is offered for Events and the Website (`NO_DEMO_DATA` otherwise).
## [2.24.1] - 2026-11-27 ## [2.24.1] - 2026-11-27
No migration; no API is removed. Frontend only, apart from one error message. No migration; no API is removed. Frontend only, apart from one error message.
+6 -6
View File
@@ -1,16 +1,16 @@
{ {
"name": "events-hub-backend", "name": "events-hub-backend",
"version": "2.24.1", "version": "2.25.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "events-hub-backend", "name": "events-hub-backend",
"version": "2.24.1", "version": "2.25.0",
"hasInstallScript": true, "hasInstallScript": true,
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^1.3.0", "@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.18.0.tgz", "@crosscode/contracts": "file:vendor/crosscode-contracts-1.19.0.tgz",
"@prisma/adapter-pg": "^7.10.1", "@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1", "@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
@@ -609,9 +609,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@crosscode/contracts": { "node_modules/@crosscode/contracts": {
"version": "1.18.0", "version": "1.19.0",
"resolved": "file:vendor/crosscode-contracts-1.18.0.tgz", "resolved": "file:vendor/crosscode-contracts-1.19.0.tgz",
"integrity": "sha512-3rcu08JRg+yL5xdRI5IV0RBjQ2NWTr0EG1oM0X6ISAVtyOWjxAsWtUWpmkwG/wlhgcvdOWGvv/katB+F9P8EqQ==", "integrity": "sha512-s6gXVYT6FmoABS0ozcLVhavC/AeD7cGBngvDVl1WkZb0NB8qRYaK42JR/HD5IM79x4WOZcsfUXZGeuDbYUULrA==",
"license": "UNLICENSED", "license": "UNLICENSED",
"dependencies": { "dependencies": {
"zod": "^4.6.7" "zod": "^4.6.7"
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "events-hub-backend", "name": "events-hub-backend",
"version": "2.24.1", "version": "2.25.0",
"private": true, "private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js", "main": "src/index.js",
@@ -20,7 +20,7 @@
}, },
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^1.3.0", "@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.18.0.tgz", "@crosscode/contracts": "file:vendor/crosscode-contracts-1.19.0.tgz",
"@prisma/adapter-pg": "^7.10.1", "@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1", "@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
@@ -0,0 +1,3 @@
-- Hub 2.25.0: a demo client. All its installs are demo sites and it's never billed.
ALTER TABLE "Customer" ADD COLUMN "isDemo" BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE "Customer" ADD COLUMN "demoSince" TIMESTAMP(3);
+5
View File
@@ -69,6 +69,11 @@ model Customer {
aiMarkupPercent Int? aiMarkupPercent Int?
// Hub 2.12.0: archived (left out of the customer list until restored). Nothing else changes. // Hub 2.12.0: archived (left out of the customer list until restored). Nothing else changes.
archivedAt DateTime? archivedAt DateTime?
// Hub 2.25.0: a demo client (a church used for showing Cross Code). Every install of it is a demo
// site (Accounts too), it's never billed (billingCycle stays none, no invoices are made) and its
// installs can have demo data loaded.
isDemo Boolean @default(false)
demoSince DateTime?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
licences Licence[] licences Licence[]
+4 -1
View File
@@ -204,7 +204,7 @@ const billingLicence = l => ({
/** A customer's schedule and address for the billing screens. */ /** A customer's schedule and address for the billing screens. */
const schedule = c => ({ const schedule = c => ({
billingCycle: c.billingCycle, billingStart: ymd(c.billingStart), nextInvoiceDate: ymd(c.nextInvoiceDate), reviewDate: ymd(c.reviewDate), isDemo: !!c.isDemo, billingCycle: c.billingCycle, billingStart: ymd(c.billingStart), nextInvoiceDate: ymd(c.nextInvoiceDate), reviewDate: ymd(c.reviewDate),
addressType: c.addressType, domain: c.domain, addressCustomCents: c.addressCustomCents, addressMonthlyCents: compute.addressMonthlyCents(c), domainRenewsOn: ymd(c.domainRenewsOn), addressType: c.addressType, domain: c.domain, addressCustomCents: c.addressCustomCents, addressMonthlyCents: compute.addressMonthlyCents(c), domainRenewsOn: ymd(c.domainRenewsOn),
}); });
@@ -280,6 +280,7 @@ router.get('/customers/:id/preview', wrap(async (req, res) => {
const { getSettings } = require('../utils/settings'); const { getSettings } = require('../utils/settings');
const customer = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: { include: { install: true } } } }); const customer = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: { include: { install: true } } } });
if (!customer) throw bad('Customer not found', 404); if (!customer) throw bad('Customer not found', 404);
if (customer.isDemo) return res.json({ billed: false, demo: true });
if (customer.billingCycle === 'none' || !customer.nextInvoiceDate) return res.json({ billed: false }); if (customer.billingCycle === 'none' || !customer.nextInvoiceDate) return res.json({ billed: false });
const { invoice, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings: await getSettings() }); const { invoice, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings: await getSettings() });
res.json({ res.json({
@@ -330,6 +331,8 @@ router.put('/customers/:id', wrap(async (req, res) => {
const existing = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: true } }); const existing = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: true } });
if (!existing) throw bad('Customer not found', 404); if (!existing) throw bad('Customer not found', 404);
const merged = { ...existing, ...data }; const merged = { ...existing, ...data };
// 2.25.0: a demo client isn't billed.
if (existing.isDemo && merged.billingCycle !== 'none') throw bad(`${existing.name} is a demo client, so it isn't billed. Make it an ordinary customer first.`, 409);
if (merged.addressType === 'crosscode' && merged.domain && !merged.domain.endsWith('.crosscode.co.za')) throw bad('A Cross Code address ends in .crosscode.co.za, e.g. hopefamily.crosscode.co.za.'); if (merged.addressType === 'crosscode' && merged.domain && !merged.domain.endsWith('.crosscode.co.za')) throw bad('A Cross Code address ends in .crosscode.co.za, e.g. hopefamily.crosscode.co.za.');
if (merged.addressType === 'included' && !merged.domainRenewsOn && data.domainRenewsOn === undefined && b.addressType === 'included') { if (merged.addressType === 'included' && !merged.domainRenewsOn && data.domainRenewsOn === undefined && b.addressType === 'included') {
throw bad('Give the date the domain is next due for renewal, so you\'re reminded in time.'); throw bad('Give the date the domain is next due for renewal, so you\'re reminded in time.');
+9 -1
View File
@@ -216,7 +216,7 @@ router.post('/deployments/link', wrap(async (req, res) => {
})); }));
router.get('/deployments/:id', wrap(async (req, res) => { router.get('/deployments/:id', wrap(async (req, res) => {
const d = await prisma.deployment.findUnique({ where: { id: req.params.id }, include: { server: true, customer: { select: { id: true, name: true } }, install: true, jobs: { orderBy: { createdAt: 'desc' }, take: 50 }, exports: { select: { id: true, bytes: true, expiresAt: true, downloadedAt: true, deletedAt: true, createdAt: true } } } }); const d = await prisma.deployment.findUnique({ where: { id: req.params.id }, include: { server: true, customer: { select: { id: true, name: true, isDemo: true } }, install: true, jobs: { orderBy: { createdAt: 'desc' }, take: 50 }, exports: { select: { id: true, bytes: true, expiresAt: true, downloadedAt: true, deletedAt: true, createdAt: true } } } });
if (!d) throw bad('Not found.', 404); if (!d) throw bad('Not found.', 404);
res.json({ deployment: { ...d, server: serverSummary(d.server) }, fastPanel: await jobs.fastPanelText(d), canRemoveRecord: await jobs.neverInstalled(d), stale: jobs.staleness(d), uninstall: await jobs.uninstallPlan(d) }); res.json({ deployment: { ...d, server: serverSummary(d.server) }, fastPanel: await jobs.fastPanelText(d), canRemoveRecord: await jobs.neverInstalled(d), stale: jobs.staleness(d), uninstall: await jobs.uninstallPlan(d) });
})); }));
@@ -255,6 +255,14 @@ router.post('/deployments/:id/demo', wrap(async (req, res) => {
res.json({ isDemo: d.isDemo }); res.json({ isDemo: d.isDemo });
})); }));
// Demo clients (2.25.0): every install a demo site, Accounts included, and never billed.
router.post('/customers/:id/demo', wrap(async (req, res) => {
const isDemo = req.body?.isDemo === true;
const { customer, sites, warnings } = await jobs.setCustomerDemo(req.params.id, { isDemo, confirm: req.body?.confirm });
await audit(req, isDemo ? 'customer_marked_demo' : 'customer_unmarked_demo', customer.id, { name: customer.name, sites });
res.json({ isDemo: customer.isDemo, sites, warnings });
}));
// An install's .env (2.8.0): the last read (secrets only as set or not), read it again, change values. // An install's .env (2.8.0): the last read (secrets only as set or not), read it again, change values.
router.get('/deployments/:id/env', wrap(async (req, res) => { router.get('/deployments/:id/env', wrap(async (req, res) => {
res.json(await jobs.envState(req.params.id)); res.json(await jobs.envState(req.params.id));
+5 -2
View File
@@ -72,7 +72,8 @@ async function draftForCustomer(customerId, settings) {
// Lock the customer row: two runs never draft the same period. // Lock the customer row: two runs never draft the same period.
await tx.$executeRaw`SELECT 1 FROM "Customer" WHERE id = ${customerId} FOR UPDATE`; await tx.$executeRaw`SELECT 1 FROM "Customer" WHERE id = ${customerId} FOR UPDATE`;
const customer = await tx.customer.findUnique({ where: { id: customerId }, include: { licences: { include: { install: true } } } }); const customer = await tx.customer.findUnique({ where: { id: customerId }, include: { licences: { include: { install: true } } } });
if (!customer || customer.billingCycle === 'none' || !customer.nextInvoiceDate) return null; // 2.25.0: a demo client is never billed.
if (!customer || customer.isDemo || customer.billingCycle === 'none' || !customer.nextInvoiceDate) return null;
const { invoice, customerUpdate, licenceUpdates, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings }); const { invoice, customerUpdate, licenceUpdates, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings });
await tx.customer.update({ where: { id: customer.id }, data: customerUpdate }); await tx.customer.update({ where: { id: customer.id }, data: customerUpdate });
if (empty) return { empty: true }; if (empty) return { empty: true };
@@ -119,7 +120,7 @@ async function createDueDrafts(now, settings) {
const days = parseInt(settings.billing_draft_days, 10) || 14; const days = parseInt(settings.billing_draft_days, 10) || 14;
const horizon = addDays(today(now), days); const horizon = addDays(today(now), days);
const customers = await prisma.customer.findMany({ const customers = await prisma.customer.findMany({
where: { billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } }, where: { billingCycle: { not: 'none' }, isDemo: false, nextInvoiceDate: { lte: horizon } },
select: { id: true }, select: { id: true },
}); });
let made = 0; let made = 0;
@@ -185,6 +186,7 @@ async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
async function sendInvoice(id, settings, now = new Date()) { async function sendInvoice(id, settings, now = new Date()) {
const invoice = await loadInvoice(id); const invoice = await loadInvoice(id);
if (invoice.status !== 'approved') throw bad('Only an approved invoice can be sent.', 409); if (invoice.status !== 'approved') throw bad('Only an approved invoice can be sent.', 409);
if (invoice.customer?.isDemo) throw bad(`${invoice.customer.name} is a demo client, so it isn't billed: void the invoice instead.`, 409);
if (!invoice.recipientEmail) throw bad('There\'s no email address to send it to.', 409); if (!invoice.recipientEmail) throw bad('There\'s no email address to send it to.', 409);
// Claim it so two runs never both send it. // Claim it so two runs never both send it.
const claimed = await prisma.invoice.updateMany({ where: { id, status: 'approved' }, data: { status: 'sent', sentAt: now, sendError: null } }); const claimed = await prisma.invoice.updateMany({ where: { id, status: 'approved' }, data: { status: 'sent', sentAt: now, sendError: null } });
@@ -444,6 +446,7 @@ async function createManualInvoice(body) {
const settings = await getSettings(); const settings = await getSettings();
const customer = await prisma.customer.findUnique({ where: { id: String(body.customerId || '') }, include: { installs: { where: { releasedAt: null } } } }); const customer = await prisma.customer.findUnique({ where: { id: String(body.customerId || '') }, include: { installs: { where: { releasedAt: null } } } });
if (!customer) throw bad('Customer not found', 404); if (!customer) throw bad('Customer not found', 404);
if (customer.isDemo) throw bad(`${customer.name} is a demo client, so it isn't billed.`, 409);
const lines = compute.cleanLines(body.lines || []); const lines = compute.cleanLines(body.lines || []);
if (!lines.length) throw bad('Add at least one line.'); if (!lines.length) throw bad('Add at least one line.');
const issueDate = body.issueDate ? day(body.issueDate) : today(); const issueDate = body.issueDate ? day(body.issueDate) : today();
+66 -17
View File
@@ -719,7 +719,7 @@ async function newInstall(input, admin, now = new Date()) {
if (!licence) licence = (await generateLicence(tx, { customerId: customer.id, product: p, now })).licence; if (!licence) licence = (await generateLicence(tx, { customerId: customer.id, product: p, now })).licence;
const ports = await portsFor(); const ports = await portsFor();
const d = await tx.deployment.create({ const d = await tx.deployment.create({
data: { serverId: server.id, customerId: customer.id, licenceId: licence.id, product: p, shortName, domain: dom, webPort: ports.web, apiPort: ports.api, timezone: input.timezone || null, adminName: input.adminName || null, adminEmail: adminEmail || null, status: 'installing' }, data: { serverId: server.id, customerId: customer.id, licenceId: licence.id, product: p, shortName, domain: dom, webPort: ports.web, apiPort: ports.api, timezone: input.timezone || null, adminName: input.adminName || null, adminEmail: adminEmail || null, isDemo: !!customer.isDemo, status: 'installing' },
}); });
await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: d.id } }); await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: d.id } });
return { d, ports }; return { d, ports };
@@ -991,7 +991,7 @@ async function linkFromStatus(job, now = new Date()) {
const version = /@(\d+\.\d+\.\d+.*)$/.exec(String(p.ref || ''))?.[1] || install?.version || null; const version = /@(\d+\.\d+\.\d+.*)$/.exec(String(p.ref || ''))?.[1] || install?.version || null;
const d = await prisma.$transaction(async tx => { const d = await prisma.$transaction(async tx => {
const made = await tx.deployment.create({ const made = await tx.deployment.create({
data: { serverId: job.serverId, customerId, licenceId: install?.licenceId || null, installId: install?.id || null, product, shortName: c.church, domain, webPort: web, apiPort: api, version, timezone: install?.timezone || sibling?.timezone || null, status: 'live', liveAt: now, adminName: install?.adminContact?.name || sibling?.adminName || null, adminEmail: install?.adminContact?.email || sibling?.adminEmail || null }, data: { serverId: job.serverId, customerId, licenceId: install?.licenceId || null, installId: install?.id || null, product, shortName: c.church, domain, webPort: web, apiPort: api, version, timezone: install?.timezone || sibling?.timezone || null, isDemo: await customerIsDemo(tx, customerId), status: 'live', liveAt: now, adminName: install?.adminContact?.name || sibling?.adminName || null, adminEmail: install?.adminContact?.email || sibling?.adminEmail || null },
}); });
for (const [port, role] of [[web, 'web'], [api, 'api']]) { for (const [port, role] of [[web, 'web'], [api, 'api']]) {
await tx.port.upsert({ where: { port }, update: { serverId: job.serverId, deploymentId: made.id, role, releasedAt: null, note: 'found on the server' }, create: { port, serverId: job.serverId, deploymentId: made.id, role, note: 'found on the server' } }); await tx.port.upsert({ where: { port }, update: { serverId: job.serverId, deploymentId: made.id, role, releasedAt: null, note: 'found on the server' }, create: { port, serverId: job.serverId, deploymentId: made.id, role, note: 'found on the server' } });
@@ -1265,7 +1265,7 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version,
if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${d.shortName}: its Accounts licence is already used by ${licence.install.url}. Link that install (Installs → Link existing) instead.`); if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${d.shortName}: its Accounts licence is already used by ${licence.install.url}. Link that install (Installs → Link existing) instead.`);
if (!licence) licence = (await generateLicence(tx, { customerId: d.customerId, product: 'accounts', now })).licence; if (!licence) licence = (await generateLicence(tx, { customerId: d.customerId, product: 'accounts', now })).licence;
const ports = await servers.allocatePorts(tx, d.serverId, now); const ports = await servers.allocatePorts(tx, d.serverId, now);
const a = await tx.deployment.create({ data: { serverId: d.serverId, customerId: d.customerId, licenceId: licence.id, product: 'accounts', shortName: d.shortName, domain: plan.install.domain, webPort: ports.web, apiPort: ports.api, timezone: d.timezone, adminName: d.adminName, adminEmail: d.adminEmail, status: 'installing' } }); const a = await tx.deployment.create({ data: { serverId: d.serverId, customerId: d.customerId, licenceId: licence.id, product: 'accounts', shortName: d.shortName, domain: plan.install.domain, webPort: ports.web, apiPort: ports.api, timezone: d.timezone, adminName: d.adminName, adminEmail: d.adminEmail, isDemo: await customerIsDemo(tx, d.customerId), status: 'installing' } });
await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: a.id } }); await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: a.id } });
const o = next(); const o = next();
const job = await makeJob(tx, { const job = await makeJob(tx, {
@@ -1620,7 +1620,7 @@ async function linkDeployment(input, admin) {
const domain = new URL(install.url).hostname; const domain = new URL(install.url).hostname;
return prisma.$transaction(async tx => { return prisma.$transaction(async tx => {
const d = await tx.deployment.create({ const d = await tx.deployment.create({
data: { serverId: server.id, customerId: install.customerId, licenceId: install.licenceId, installId: install.id, product: install.product, shortName, domain, webPort: web, apiPort: api, version: install.version, timezone: install.timezone, status: 'live', liveAt: new Date(), adminName: install.adminContact?.name || null, adminEmail: install.adminContact?.email || null }, data: { serverId: server.id, customerId: install.customerId, licenceId: install.licenceId, installId: install.id, product: install.product, shortName, domain, webPort: web, apiPort: api, version: install.version, timezone: install.timezone, isDemo: await customerIsDemo(tx, install.customerId), status: 'live', liveAt: new Date(), adminName: install.adminContact?.name || null, adminEmail: install.adminContact?.email || null },
}); });
for (const [port, role] of [[web, 'web'], [api, 'api']]) { for (const [port, role] of [[web, 'web'], [api, 'api']]) {
await tx.port.upsert({ where: { port }, update: { serverId: server.id, deploymentId: d.id, role, releasedAt: null, note: 'existing install' }, create: { port, serverId: server.id, deploymentId: d.id, role, note: 'existing install' } }); await tx.port.upsert({ where: { port }, update: { serverId: server.id, deploymentId: d.id, role, releasedAt: null, note: 'existing install' }, create: { port, serverId: server.id, deploymentId: d.id, role, note: 'existing install' } });
@@ -1669,37 +1669,86 @@ async function runNow({ serverId, type, args, deploymentId = null }, admin, now
return makeJob(prisma, { serverId, type, args, deploymentId, createdById: admin?.id || null, notBefore: now }); return makeJob(prisma, { serverId, type, args, deploymentId, createdById: admin?.id || null, notBefore: now });
} }
/** Mark or unmark an install as a demo site. Marking it asks for its short name, since a demo site's data can be replaced. */ /** Whether a customer is a demo client (2.25.0): its new installs start as demo sites. */
async function setDemo(deploymentId, { isDemo, confirm }) { async function customerIsDemo(db, customerId) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId } }); if (!customerId) return false;
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); const c = await db.customer.findUnique({ where: { id: customerId } });
if (d.product !== 'events') throw fail(400, 'NOT_EVENTS', 'Only Cross Events installs have demo data.'); return !!c?.isDemo;
if (isDemo && confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to mark it as a demo site.`);
return prisma.deployment.update({ where: { id: d.id }, data: { isDemo: !!isDemo } });
} }
/**
* Mark or unmark an install as a demo site. Marking it asks for its short name, since a demo site's
* data can be replaced. 2.25.0: any product (Accounts and the App as a tag only; Events and the
* Website can then have demo data loaded); a demo client's installs stay demo sites.
*/
async function setDemo(deploymentId, { isDemo, confirm }) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (isDemo && confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to mark it as a demo site.`);
if (!isDemo && await customerIsDemo(prisma, d.customerId)) throw fail(409, 'DEMO_CLIENT', 'Its customer is a demo client, so all its sites are demo sites. Change that on the customer.');
return prisma.deployment.update({ where: { id: d.id }, data: { isDemo: !!isDemo } });
}
/** The products with demo data, their profiles (from the contracts) and the agent each needs. */
const DEMO_DATA = {
events: { profiles: agent.DEMO_PROFILES, minAgent: agent.SEED_DEMO_MIN_AGENT },
website: { profiles: agent.WEBSITE_DEMO_PROFILES, minAgent: agent.SEED_WEBSITE_DEMO_MIN_AGENT },
};
/** /**
* Replace a demo site's data with a demo set (`crosscode demo`, a backup is taken first). Only for * Replace a demo site's data with a demo set (`crosscode demo`, a backup is taken first). Only for
* installs marked as demo sites, typing the short name, on an agent that knows the job (1.2.0+). * installs marked as demo sites, typing the short name, on an agent that knows the job (1.2.0+;
* 2.25.0: the Website's, on 1.6.0+). Events keeps its admin; the Website keeps every admin, the
* church's profile and the site settings.
*/ */
async function seedDemo({ deploymentId, profile, confirm }, admin, now = new Date()) { async function seedDemo({ deploymentId, profile, confirm }, admin, now = new Date()) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { server: true } }); const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { server: true } });
if (!d) throw fail(404, 'NOT_FOUND', 'Not found.'); if (!d) throw fail(404, 'NOT_FOUND', 'Not found.');
if (!d.isDemo) throw fail(409, 'NOT_DEMO', `${d.shortName} isn't marked as a demo site.`); if (!d.isDemo) throw fail(409, 'NOT_DEMO', `${d.shortName} isn't marked as a demo site.`);
if (d.product !== 'events') throw fail(400, 'NOT_EVENTS', 'Only Cross Events installs have demo data.'); const data = DEMO_DATA[d.product];
if (!data) throw fail(400, 'NO_DEMO_DATA', `${PRODUCT_NAMES[d.product] || d.product} has no demo data (only Cross Events and the Church Website).`);
if (!['live', 'waiting_for_proxy'].includes(d.status)) throw fail(409, 'NOT_LIVE', `It's ${d.status.replace(/_/g, ' ')}; demo data goes on an installed site.`); if (!['live', 'waiting_for_proxy'].includes(d.status)) throw fail(409, 'NOT_LIVE', `It's ${d.status.replace(/_/g, ' ')}; demo data goes on an installed site.`);
if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to replace its data.`); if (confirm !== d.shortName) throw fail(400, 'CONFIRM', `Type ${d.shortName} to replace its data.`);
if (!agent.DEMO_PROFILES.includes(profile)) throw fail(400, 'BAD_REQUEST', `Choose one of: ${agent.DEMO_PROFILES.join(', ')}.`); if (!data.profiles.includes(profile)) throw fail(400, 'BAD_REQUEST', `Choose one of: ${data.profiles.join(', ')}.`);
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.'); if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', 'That server was removed.');
if (compareVersions(d.server.agentVersion || '0.0.0', agent.SEED_DEMO_MIN_AGENT) < 0) { if (compareVersions(d.server.agentVersion || '0.0.0', data.minAgent) < 0) {
throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; demo data needs ${agent.SEED_DEMO_MIN_AGENT} or later (update the agent first).`); throw fail(409, 'AGENT_TOO_OLD', `The agent on ${d.server.name} is ${d.server.agentVersion || 'an unknown version'}; ${d.product === 'website' ? 'the Website\'s ' : ''}demo data needs ${data.minAgent} or later (update the agent first).`);
} }
const running = await prisma.job.findFirst({ where: { serverId: d.serverId, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } }); const running = await prisma.job.findFirst({ where: { serverId: d.serverId, status: 'delivered' }, orderBy: { deliveredAt: 'desc' } });
if (!agentOnline(d.server, now, running)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${d.server.name} isn't online.`); if (!agentOnline(d.server, now, running)) throw fail(409, 'AGENT_OFFLINE', `The agent on ${d.server.name} isn't online.`);
// Events' jobs keep their old form (no product), so they mean the same to any agent.
if (d.product === 'website') {
return makeJob(prisma, { serverId: d.serverId, type: 'seed-demo', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, args: { church: d.shortName, product: 'website', profile } });
}
const adminEmail = d.adminEmail && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.adminEmail) ? d.adminEmail.toLowerCase() : undefined; const adminEmail = d.adminEmail && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.adminEmail) ? d.adminEmail.toLowerCase() : undefined;
return makeJob(prisma, { serverId: d.serverId, type: 'seed-demo', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, args: { church: d.shortName, profile, ...(adminEmail ? { adminEmail } : {}) } }); return makeJob(prisma, { serverId: d.serverId, type: 'seed-demo', deploymentId: d.id, createdById: admin?.id || null, notBefore: now, args: { church: d.shortName, profile, ...(adminEmail ? { adminEmail } : {}) } });
} }
/**
* Hub 2.25.0: make a customer a demo client (typing its name), or an ordinary one again. A demo
* client's installs are all demo sites, Accounts included (and any it gets later), and it isn't
* billed: its billing is set to not invoiced and stays so while it's a demo client, and no invoice
* of it is drafted or sent. Invoices it has that haven't gone out are left alone, but named in the
* warnings. Unmarking unmarks its installs; billing stays off until it's set up again.
*/
async function setCustomerDemo(customerId, { isDemo, confirm }, now = new Date()) {
const c = await prisma.customer.findUnique({ where: { id: customerId } });
if (!c) throw fail(404, 'NOT_FOUND', 'Customer not found.');
if (isDemo && (confirm || '').trim() !== c.name.trim()) throw fail(400, 'CONFIRM', `Type ${c.name} to make it a demo client.`);
const waiting = isDemo ? await prisma.invoice.count({ where: { customerId: c.id, status: { in: ['draft', 'approved'] } } }) : 0;
const [customer, sites] = await prisma.$transaction([
prisma.customer.update({
where: { id: c.id },
data: isDemo
? { isDemo: true, demoSince: c.isDemo ? c.demoSince : now, billingCycle: 'none', nextInvoiceDate: null }
: { isDemo: false, demoSince: null },
}),
prisma.deployment.updateMany({ where: { customerId: c.id, removedAt: null }, data: { isDemo: !!isDemo } }),
]);
const warnings = waiting ? [`${waiting} invoice${waiting === 1 ? '' : 's'} not sent yet won't go out while it's a demo client; void ${waiting === 1 ? 'it' : 'them'} under Invoices and payments.`] : [];
return { customer, sites: sites.count, warnings };
}
// ─── An install's .env (2.8.0, contracts 1.12.0, agent 1.3.0) ───────────────── // ─── An install's .env (2.8.0, contracts 1.12.0, agent 1.3.0) ─────────────────
const ENV_PRODUCTS = ['events', 'accounts']; const ENV_PRODUCTS = ['events', 'accounts'];
@@ -1765,7 +1814,7 @@ async function setEnv(deploymentId, { file, set, unset, restart }, admin, now =
module.exports = { module.exports = {
readEnv, setEnv, envState, readFrp, writeFrp, listFrpcTunnels, portsProbed, probeServers, PROBE_SPARE, readEnv, setEnv, envState, readFrp, writeFrp, listFrpcTunnels, portsProbed, probeServers, PROBE_SPARE,
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, churchUpdatePlan, scheduleChurchUpdate, WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, setCustomerDemo, customerIsDemo, churchUpdatePlan, scheduleChurchUpdate,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch, makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, staleness, forgetStale, uninstallPlan, STALE_MS, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow, JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, staleness, forgetStale, uninstallPlan, STALE_MS, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
fastPanelText, fastPanelSteps, notesBlocks, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail, fastPanelText, fastPanelSteps, notesBlocks, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
+48
View File
@@ -706,6 +706,54 @@ describe('demo sites (2.4.0)', () => {
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.2.0') }); await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.2.0') });
expect(await db.job.findMany({})).toEqual([]); expect(await db.job.findMany({})).toEqual([]);
}); });
test('2.25.0: a Website demo site gets a Website profile, on an agent of 1.6.0 or later', async () => {
const { server, d } = await liveDemo({ agentVersion: '1.6.0' });
await db.deployment.update({ where: { id: d.id }, data: { product: 'website' } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'BAD_REQUEST', message: expect.stringContaining('heritage-parish') });
const job = await jobs.seedDemo({ deploymentId: d.id, profile: 'community-town', confirm: 'demo2' }, admin, NOW);
expect(job.args).toEqual({ church: 'demo2', product: 'website', profile: 'community-town' });
const polled = await jobs.poll(server, { agentApiVersion: 1, agentVersion: '1.6.0', mode: 'church', runningJobId: null }, NOW);
expect(agent.agentJobSchema.safeParse(polled.jobs[0]).success).toBe(true);
await db.server.update({ where: { id: server.id }, data: { agentVersion: '1.5.0' } });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'bold-plant', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'AGENT_TOO_OLD', message: expect.stringContaining('1.6.0') });
});
test('2.25.0: any product can be a demo site, but only Events and the Website have demo data', async () => {
const { d } = await liveDemo({ agentVersion: '1.6.0', isDemo: false });
await db.deployment.update({ where: { id: d.id }, data: { product: 'accounts' } });
expect(await jobs.setDemo(d.id, { isDemo: true, confirm: 'demo2' })).toMatchObject({ isDemo: true });
await expect(jobs.seedDemo({ deploymentId: d.id, profile: 'small', confirm: 'demo2' }, admin, NOW)).rejects.toMatchObject({ code: 'NO_DEMO_DATA' });
});
test('2.25.0: a demo client: all its installs demo sites (Accounts too), billing off, new installs demo too', async () => {
const { server } = await joinServer();
await db.customer.update({ where: { id: 'cust-1' }, data: { billingCycle: 'monthly', nextInvoiceDate: new Date('2026-12-01') } });
for (const [id, product, port] of [['dep-ev', 'events', 20000], ['dep-acc', 'accounts', 20002]]) {
await db.deployment.create({ data: { id, serverId: server.id, customerId: 'cust-1', product, shortName: 'hope', domain: `${product}.hope.test`, webPort: port, apiPort: port + 1, status: 'live', isDemo: false, removedAt: null } });
}
await db.invoice.create({ data: { id: 'inv-1', customerId: 'cust-1', status: 'approved' } });
await expect(jobs.setCustomerDemo('cust-1', { isDemo: true, confirm: 'Hope' })).rejects.toMatchObject({ code: 'CONFIRM' });
const out = await jobs.setCustomerDemo('cust-1', { isDemo: true, confirm: 'Hope Church' }, NOW);
expect(out).toMatchObject({ sites: 2, warnings: [expect.stringContaining('1 invoice')] });
expect(await db.customer.findUnique({ where: { id: 'cust-1' } })).toMatchObject({ isDemo: true, billingCycle: 'none', nextInvoiceDate: null, demoSince: NOW });
expect((await db.deployment.findMany({ where: { customerId: 'cust-1' } })).map(x => x.isDemo)).toEqual([true, true]);
await expect(jobs.setDemo('dep-acc', { isDemo: false })).rejects.toMatchObject({ code: 'DEMO_CLIENT' });
expect(await jobs.customerIsDemo(db, 'cust-1')).toBe(true);
await jobs.setCustomerDemo('cust-1', { isDemo: false });
expect(await db.customer.findUnique({ where: { id: 'cust-1' } })).toMatchObject({ isDemo: false, billingCycle: 'none', demoSince: null });
expect((await db.deployment.findMany({ where: { customerId: 'cust-1' } })).map(x => x.isDemo)).toEqual([false, false]);
});
test('2.25.0: a demo client\'s new install starts as a demo site', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback', DB_ADMIN_URL: 'postgresql://admin:pw@10.0.0.5/postgres' });
await db.customer.update({ where: { id: 'cust-1' }, data: { isDemo: true } });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za' }, admin, NOW);
expect(deployment.isDemo).toBe(true);
});
}); });
describe('sites added on a server are found and tied to their registration (2.6.0)', () => { describe('sites added on a server are found and tied to their registration (2.6.0)', () => {
const statusResult = (domain = 'accounts.found.co.za') => ({ churches: [{ church: 'found', address: 'found.co.za', products: [ const statusResult = (domain = 'accounts.found.co.za') => ({ churches: [{ church: 'found', address: 'found.co.za', products: [
Binary file not shown.
Binary file not shown.
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "events-hub-frontend", "name": "events-hub-frontend",
"version": "2.24.1", "version": "2.25.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "events-hub-frontend", "name": "events-hub-frontend",
"version": "2.24.1", "version": "2.25.0",
"dependencies": { "dependencies": {
"lucide-react": "^0.536.0", "lucide-react": "^0.536.0",
"next": "^15.5.24", "next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "events-hub-frontend", "name": "events-hub-frontend",
"version": "2.24.1", "version": "2.25.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev -p 3200", "dev": "next dev -p 3200",
@@ -17,6 +17,7 @@ import { AddressCard, AddressModal } from "@/components/customer/AddressCard";
import { AiCard, AiModal } from "@/components/customer/AiCard"; import { AiCard, AiModal } from "@/components/customer/AiCard";
import { SitesCard } from "@/components/customer/SitesCard"; import { SitesCard } from "@/components/customer/SitesCard";
import { ChurchUpdateModal } from "@/components/customer/ChurchUpdateModal"; import { ChurchUpdateModal } from "@/components/customer/ChurchUpdateModal";
import { DemoClientModal } from "@/components/customer/DemoClientModal";
import { ProductCard } from "@/components/customer/ProductCard"; import { ProductCard } from "@/components/customer/ProductCard";
import { AddProductModal } from "@/components/customer/AddProductModal"; import { AddProductModal } from "@/components/customer/AddProductModal";
import { NextInvoiceModal } from "@/components/customer/NextInvoice"; import { NextInvoiceModal } from "@/components/customer/NextInvoice";
@@ -145,6 +146,7 @@ export default function CustomerPage() {
{popup === "schedule" && b && <ScheduleModal b={b} onClose={close} onDone={done} />} {popup === "schedule" && b && <ScheduleModal b={b} onClose={close} onDone={done} />}
{popup === "address" && b && <AddressModal b={b} onClose={close} onDone={done} />} {popup === "address" && b && <AddressModal b={b} onClose={close} onDone={done} />}
{popup === "ai" && <AiModal c={c} onClose={close} onDone={done} />} {popup === "ai" && <AiModal c={c} onClose={close} onDone={done} />}
{popup === "demo" && <DemoClientModal c={c} onClose={close} onDone={done} />}
{popup === "update" && <ChurchUpdateModal customerId={id} name={c.name} onClose={close} onDone={done} />} {popup === "update" && <ChurchUpdateModal customerId={id} name={c.name} onClose={close} onDone={done} />}
</> </>
); );
+1 -1
View File
@@ -78,7 +78,7 @@ export default function CustomersPage() {
{paged.rows.length === 0 && <tr><td colSpan={3} className="p-3 text-slate-500">No customers match.</td></tr>} {paged.rows.length === 0 && <tr><td colSpan={3} className="p-3 text-slate-500">No customers match.</td></tr>}
{paged.rows.map(c => ( {paged.rows.map(c => (
<tr key={c.id} className="border-t hover:bg-slate-50"> <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"><Link href={`/customers/${c.id}`} className="font-medium text-indigo-700 hover:underline">{c.name}</Link>{c.isDemo && <span className="ml-1 rounded bg-sky-100 px-1.5 text-xs text-sky-800">demo</span>}<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].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.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> <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> </tr>
@@ -11,7 +11,7 @@ import { Menu, Stat } from "@/components/ui";
import { ADDRESS_OPTIONS, type CustomerBillingData, type Preview } from "./shared"; import { ADDRESS_OPTIONS, type CustomerBillingData, type Preview } from "./shared";
/** What the header's tiles open, and its buttons. */ /** What the header's tiles open, and its buttons. */
export type HeaderAction = "payment" | "oneoff" | "add" | "preview" | "address" | "ai" | "history"; export type HeaderAction = "payment" | "oneoff" | "add" | "preview" | "address" | "ai" | "history" | "demo";
/** /**
* Hub 2.14.0: always at the top of the customer page: who the church is, what it has, what it * Hub 2.14.0: always at the top of the customer page: who the church is, what it has, what it
@@ -37,15 +37,17 @@ export function CustomerHeader({ c, b, preview, canAdd, onAction, onArchive }: {
<h1 className="flex flex-wrap items-center gap-2 text-2xl font-semibold"> <h1 className="flex flex-wrap items-center gap-2 text-2xl font-semibold">
<span className="break-words">{c.name}</span> <span className="break-words">{c.name}</span>
{b?.founding && <span title="Founding church (35% off)" className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-800 ring-1 ring-inset ring-amber-200"><Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" /> Founding</span>} {b?.founding && <span title="Founding church (35% off)" className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-800 ring-1 ring-inset ring-amber-200"><Star className="h-3.5 w-3.5 fill-amber-400 text-amber-400" /> Founding</span>}
{c.isDemo && <span title="Every install is a demo site, and it isn't billed" className="rounded-full bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700 ring-1 ring-inset ring-indigo-200">Demo client</span>}
{c.archivedAt && <span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600 ring-1 ring-inset ring-slate-200">Archived {fmtDate(c.archivedAt, false)}</span>} {c.archivedAt && <span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-600 ring-1 ring-inset ring-slate-200">Archived {fmtDate(c.archivedAt, false)}</span>}
</h1> </h1>
<p className="mt-1 text-sm text-slate-500">Customer since {fmtDate(c.createdAt, false)}</p> <p className="mt-1 text-sm text-slate-500">Customer since {fmtDate(c.createdAt, false)}</p>
</div> </div>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
<button type="button" className="btn-primary" onClick={() => onAction("payment")}><Plus className="h-4 w-4" /> Record payment</button> <button type="button" className="btn-primary" onClick={() => onAction("payment")}><Plus className="h-4 w-4" /> Record payment</button>
<button type="button" className="btn-secondary" onClick={() => onAction("oneoff")}><FilePlus className="h-4 w-4" /> One-off invoice</button> {!c.isDemo && <button type="button" className="btn-secondary" onClick={() => onAction("oneoff")}><FilePlus className="h-4 w-4" /> One-off invoice</button>}
{canAdd && <button type="button" className="btn-secondary" onClick={() => onAction("add")}><KeyRound className="h-4 w-4" /> Add product</button>} {canAdd && <button type="button" className="btn-secondary" onClick={() => onAction("add")}><KeyRound className="h-4 w-4" /> Add product</button>}
<Menu label="More actions for this customer" items={[ <Menu label="More actions for this customer" items={[
c.isDemo ? { label: "Not a demo client any more…", onClick: () => onAction("demo") } : { label: "Make it a demo client…", onClick: () => onAction("demo") },
c.archivedAt ? { label: "Restore", onClick: () => onArchive(false) } : { label: "Archive…", onClick: () => onArchive(true) }, c.archivedAt ? { label: "Restore", onClick: () => onArchive(false) } : { label: "Archive…", onClick: () => onArchive(true) },
]} /> ]} />
</div> </div>
@@ -59,8 +61,8 @@ export function CustomerHeader({ c, b, preview, canAdd, onAction, onArchive }: {
value={b ? money(b.balanceCents) : "…"} value={b ? money(b.balanceCents) : "…"}
sub={overdue.length ? `${overdue.length} overdue` : b && b.balanceCents <= 0 ? "Nothing owing" : undefined} /> sub={overdue.length ? `${overdue.length} overdue` : b && b.balanceCents <= 0 ? "Nothing owing" : undefined} />
<Stat label="Next invoice" small onClick={() => onAction("preview")} <Stat label="Next invoice" small onClick={() => onAction("preview")}
value={!b ? "…" : b.billingCycle === "none" ? "Not billed" : b.nextInvoiceDate ? day(b.nextInvoiceDate) : "Not set"} value={!b ? "…" : b.isDemo ? "Not billed (demo)" : b.billingCycle === "none" ? "Not billed" : b.nextInvoiceDate ? day(b.nextInvoiceDate) : "Not set"}
sub={b && b.billingCycle !== "none" ? (estimate != null ? `About ${money(estimate)} · see it` : preview?.billed && preview.empty ? "Nothing to charge yet" : "See it") : "Set up billing"} /> sub={b?.isDemo ? "A demo client" : b && b.billingCycle !== "none" ? (estimate != null ? `About ${money(estimate)} · see it` : preview?.billed && preview.empty ? "Nothing to charge yet" : "See it") : "Set up billing"} />
<Stat label="Address" small onClick={() => onAction("address")} <Stat label="Address" small onClick={() => onAction("address")}
value={b ? ADDRESS_OPTIONS[b.addressType].label : "…"} value={b ? ADDRESS_OPTIONS[b.addressType].label : "…"}
sub={b?.domain || "No domain yet"} /> sub={b?.domain || "No domain yet"} />
@@ -0,0 +1,52 @@
"use client";
import React, { useState } from "react";
import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { post, withWarnings } from "@/components/install/shared";
import type { Customer } from "@/lib/types";
import type { Done } from "./shared";
/**
* Hub 2.25.0: make a customer a demo client (a church used for showing Cross Code), or an ordinary
* one again. A demo client's installs are all demo sites, Accounts included, and it isn't billed.
*/
export function DemoClientModal({ c, onClose, onDone }: { c: Customer; onClose: () => void; onDone: Done }) {
const [confirmName, setConfirmName] = useState("");
const { busy, error, run } = useSubmit();
const submit = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await post<{ sites: number; warnings?: string[] }>(`/api/admin/customers/${c.id}/demo`, { isDemo: !c.isDemo, confirm: confirmName });
const sites = `${r.sites} install${r.sites === 1 ? "" : "s"}`;
onDone({ type: "ok", text: withWarnings(c.isDemo
? `${c.name} is an ordinary customer again: ${sites} no longer demo sites. Billing stays off until you set it up.`
: `${c.name} is a demo client: ${sites} marked as demo sites, and it isn't billed.`, r) });
});
};
if (c.isDemo) return (
<Modal title="Make it an ordinary customer" onClose={onClose}>
<form onSubmit={submit} className="space-y-4">
<p className="text-sm text-slate-500">Its installs stop being demo sites, so no more demo data can be loaded on them. Billing stays &quot;not invoiced&quot; until you set up its schedule.</p>
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Not a demo client any more" />
</form>
</Modal>
);
return (
<Modal title="Make it a demo client" onClose={onClose} dirty={!!confirmName}>
<form onSubmit={submit} className="space-y-4">
<ul className="list-disc space-y-1 pl-5 text-sm text-slate-500">
<li>Every install of {c.name} becomes a demo site, Accounts included, and so does any it gets later. Demo data can then be loaded on its Events and Website.</li>
<li>It isn&apos;t billed: billing is set to &quot;not invoiced&quot;, and no invoice of it is drafted or sent.</li>
<li>Only for churches used for showing Cross Code, never a real customer.</li>
</ul>
<div><label className="label" htmlFor="dc-c">Type {c.name}</label><input id="dc-c" className="input" autoComplete="off" value={confirmName} onChange={e => setConfirmName(e.target.value)} /></div>
<FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Make it a demo client" danger disabled={confirmName.trim() !== c.name.trim()} />
</form>
</Modal>
);
}
@@ -10,9 +10,9 @@ import { changed, type CustomerBillingData, type Done } from "./shared";
export function ScheduleCard({ b, onEdit }: { b: CustomerBillingData; onEdit: () => void }) { export function ScheduleCard({ b, onEdit }: { b: CustomerBillingData; onEdit: () => void }) {
const off = b.billingCycle === "none"; const off = b.billingCycle === "none";
return ( return (
<ReadCard title="Billing schedule" onEdit={onEdit}> <ReadCard title="Billing schedule" onEdit={b.isDemo ? undefined : onEdit}>
<Fields> <Fields>
<Field label="Billing">{CYCLE[b.billingCycle]}</Field> <Field label="Billing">{b.isDemo ? "Not billed: a demo client" : CYCLE[b.billingCycle]}</Field>
{!off && <Field label="Billing started">{b.billingStart && day(b.billingStart)}</Field>} {!off && <Field label="Billing started">{b.billingStart && day(b.billingStart)}</Field>}
{!off && <Field label="Next invoice">{b.nextInvoiceDate && day(b.nextInvoiceDate)}</Field>} {!off && <Field label="Next invoice">{b.nextInvoiceDate && day(b.nextInvoiceDate)}</Field>}
{!off && <Field label="Next tier review">{b.reviewDate && day(b.reviewDate)}</Field>} {!off && <Field label="Next tier review">{b.reviewDate && day(b.reviewDate)}</Field>}
@@ -20,6 +20,8 @@ export type AddressType = "own_domain" | "crosscode" | "included";
export type CustomerBillingData = { export type CustomerBillingData = {
id: string; name: string; billingEmail: string | null; billingAddress: string | null; founding: boolean; foundingSince: string | null; foundingNote: string | null; id: string; name: string; billingEmail: string | null; billingAddress: string | null; founding: boolean; foundingSince: string | null; foundingNote: string | null;
/** Hub 2.25.0: a demo client (never billed). */
isDemo?: boolean;
billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null; billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null;
addressType: AddressType; domain: string | null; addressCustomCents: number | null; addressMonthlyCents: number; domainRenewsOn: string | null; addressType: AddressType; domain: string | null; addressCustomCents: number | null; addressMonthlyCents: number; domainRenewsOn: string | null;
sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[]; sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[];
+43 -14
View File
@@ -4,22 +4,41 @@ import React, { useState } from "react";
import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui"; import { FormError, Modal, ModalButtons, useSubmit } from "@/components/ui";
import { post, withWarnings, type Done, type Install } from "./shared"; import { post, withWarnings, type Done, type Install } from "./shared";
const PROFILES = [ /** Each product's demo data sets (contracts `DEMO_PROFILES` and, 2.25.0, `WEBSITE_DEMO_PROFILES`). */
{ key: "small", label: "Small church: the essentials" }, const PROFILES: Record<string, { key: string; label: string }[]> = {
{ key: "events", label: "Events and conferences" }, events: [
{ key: "ministry", label: "Weekly ministry: courses, kids, volunteers" }, { key: "small", label: "Small church: the essentials" },
{ key: "multicampus", label: "Three campuses" }, { key: "events", label: "Events and conferences" },
]; { key: "ministry", label: "Weekly ministry: courses, kids, volunteers" },
{ key: "multicampus", label: "Three campuses" },
],
website: [
{ key: "heritage-parish", label: "Heritage: a parish church with a long history" },
{ key: "heritage-city", label: "Heritage: a city-centre church (other layouts)" },
{ key: "bold-youth", label: "Bold: a young, music-led church" },
{ key: "bold-plant", label: "Bold: a new church plant (other layouts)" },
{ key: "community-family", label: "Community: a family church" },
{ key: "community-town", label: "Community: a country-town church (other layouts)" },
{ key: "clean-modern", label: "Clean: a contemporary church" },
{ key: "clean-campus", label: "Clean: a church near the university (other layouts)" },
],
};
/** Whether a product has demo data to load (Accounts and the App are only tagged). */
export const hasDemoData = (product: string) => product in PROFILES;
/** /**
* An Events site used for showing Cross Events: mark it as a demo site, or (once it is one) replace * An install used for showing Cross Code: mark it as a demo site, or (once it is one) replace its
* its data with a demo set. Unmarking is a menu item on the page. * data with a demo set. Unmarking is a menu item on the page. 2.25.0: the Website's eight demo
* churches; Accounts and the App can be marked (a tag) but have no demo data.
*/ */
export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => void; onDone: Done }) { export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => void; onDone: Done }) {
const [profile, setProfile] = useState("events"); const profiles = PROFILES[x.product] || [];
const [profile, setProfile] = useState(profiles[0]?.key || "");
const [confirmName, setConfirmName] = useState(""); const [confirmName, setConfirmName] = useState("");
const { busy, error, run } = useSubmit(); const { busy, error, run } = useSubmit();
const typed = confirmName === x.shortName; const typed = confirmName === x.shortName;
const website = x.product === "website";
const mark = (e: React.FormEvent) => { const mark = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
@@ -30,7 +49,8 @@ export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => v
}; };
const seed = (e: React.FormEvent) => { const seed = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
if (!window.confirm(`Replace ALL of ${x.shortName}'s data with the "${profile}" demo? A backup is taken first; one admin account is kept.`)) return; const what = website ? "content (pages, ministries, messages, events, pictures)" : "data";
if (!window.confirm(`Replace ALL of ${x.shortName}'s ${what} with the "${profile}" demo? A backup is taken first.`)) return;
run(async () => { run(async () => {
const r = await post(`/api/admin/deployments/${x.id}/seed-demo`, { profile, confirm: confirmName }); const r = await post(`/api/admin/deployments/${x.id}/seed-demo`, { profile, confirm: confirmName });
onDone({ type: "ok", text: withWarnings("Queued: the agent loads the demo data on its next poll (see Jobs). You get an email when it's done.", r) }); onDone({ type: "ok", text: withWarnings("Queued: the agent loads the demo data on its next poll (see Jobs). You get an email when it's done.", r) });
@@ -44,7 +64,12 @@ export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => v
if (!x.isDemo) return ( if (!x.isDemo) return (
<Modal title="Mark as a demo site" onClose={onClose} dirty={!!confirmName}> <Modal title="Mark as a demo site" onClose={onClose} dirty={!!confirmName}>
<form onSubmit={mark} className="space-y-4"> <form onSubmit={mark} className="space-y-4">
<p className="text-sm text-slate-500">A demo site&apos;s data can be replaced with demo data from the Hub. Only mark sites used for showing Cross Events, never a church&apos;s real site.</p> <p className="text-sm text-slate-500">
{hasDemoData(x.product)
? "A demo site's data can be replaced with demo data from the Hub. "
: "This product has no demo data: marking it only tags it as a demo site. "}
Only mark sites used for showing Cross Code, never a church&apos;s real site.
</p>
{confirmField} {confirmField}
<FormError error={error} /> <FormError error={error} />
<ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Mark as a demo site" disabled={!typed} /> <ModalButtons busy={busy} busyLabel="Working…" onCancel={onClose} label="Mark as a demo site" disabled={!typed} />
@@ -53,14 +78,18 @@ export function DemoModal({ x, onClose, onDone }: { x: Install; onClose: () => v
); );
return ( return (
<Modal title="Load demo data" onClose={onClose} dirty={!!confirmName || profile !== "events"}> <Modal title="Load demo data" onClose={onClose} dirty={!!confirmName || profile !== profiles[0]?.key}>
<form onSubmit={seed} className="space-y-4"> <form onSubmit={seed} className="space-y-4">
<p className="text-sm text-slate-500">Replaces everything (events, people, payments) with a demo set, keeping the site settings and {x.adminEmail || "the site's first admin"}. Demo logins use the password Demo@1234.</p> <p className="text-sm text-slate-500">
{website
? "Replaces the site's content with a demo church on its template, and publishes it. The church's profile (name, logo, colours, service times, contact), the site settings, the site icon and the admins stay, and the demo's text uses the church's name. Needs agent 1.6.0 and Website 1.3.0."
: <>Replaces everything (events, people, payments) with a demo set, keeping the site settings and {x.adminEmail || "the site's first admin"}. Demo logins use the password Demo@1234.</>}
</p>
<div className="grid gap-3 sm:grid-cols-2"> <div className="grid gap-3 sm:grid-cols-2">
<div> <div>
<label className="label" htmlFor="d-p">Demo</label> <label className="label" htmlFor="d-p">Demo</label>
<select id="d-p" className="input" value={profile} onChange={e => setProfile(e.target.value)}> <select id="d-p" className="input" value={profile} onChange={e => setProfile(e.target.value)}>
{PROFILES.map(p => <option key={p.key} value={p.key}>{p.label}</option>)} {profiles.map(p => <option key={p.key} value={p.key}>{p.label}</option>)}
</select> </select>
</div> </div>
{confirmField} {confirmField}
@@ -8,6 +8,7 @@ import { ago } from "@/lib/format";
import { Menu, Stat } from "@/components/ui"; import { Menu, Stat } from "@/components/ui";
import { StatusPill } from "@/components/servers"; import { StatusPill } from "@/components/servers";
import { productName, running, type Detail } from "./shared"; import { productName, running, type Detail } from "./shared";
import { hasDemoData } from "./DemoModal";
/** What the header's buttons, menu and tiles open. */ /** What the header's buttons, menu and tiles open. */
export type InstallAction = "update" | "adopt" | "demo" | "undemo" | "uninstall" | "record" | "forget"; export type InstallAction = "update" | "adopt" | "demo" | "undemo" | "uninstall" | "record" | "forget";
@@ -41,10 +42,10 @@ export function InstallHeader({ d, onAction }: { d: Detail; onAction: (a: Instal
{live && <button type="button" className="btn-primary" onClick={() => onAction("update")}><RefreshCw className="h-4 w-4" /> Schedule update</button>} {live && <button type="button" className="btn-primary" onClick={() => onAction("update")}><RefreshCw className="h-4 w-4" /> Schedule update</button>}
<Menu label="More actions for this install" items={[ <Menu label="More actions for this install" items={[
live && x.install?.version?.startsWith("2.1.") && { label: "Move onto the monorepo…", onClick: () => onAction("adopt") }, live && x.install?.version?.startsWith("2.1.") && { label: "Move onto the monorepo…", onClick: () => onAction("adopt") },
x.product === "events" && running(x) && (x.isDemo // 2.25.0: any product can be a demo site; Events and the Website have demo data.
? { label: "Load demo data…", onClick: () => onAction("demo") } running(x) && !x.isDemo && { label: "Mark as a demo site…", onClick: () => onAction("demo") },
: { label: "Mark as a demo site…", onClick: () => onAction("demo") }), running(x) && x.isDemo && hasDemoData(x.product) && { label: "Load demo data…", onClick: () => onAction("demo") },
x.product === "events" && running(x) && x.isDemo && { label: "It isn't a demo site any more", onClick: () => onAction("undemo") }, running(x) && x.isDemo && !x.customer?.isDemo && { label: "It isn't a demo site any more", onClick: () => onAction("undemo") },
running(x) && { label: `Uninstall ${productName(x.product)}…`, onClick: () => onAction("uninstall"), danger: true }, running(x) && { label: `Uninstall ${productName(x.product)}…`, onClick: () => onAction("uninstall"), danger: true },
d.stale.stale && { label: "Remove from the Hub…", onClick: () => onAction("forget"), danger: true }, d.stale.stale && { label: "Remove from the Hub…", onClick: () => onAction("forget"), danger: true },
d.canRemoveRecord && { label: "Remove the record…", onClick: () => onAction("record"), danger: true }, d.canRemoveRecord && { label: "Remove the record…", onClick: () => onAction("record"), danger: true },
+1 -1
View File
@@ -28,7 +28,7 @@ export type Deployment = {
id: string; serverId: string; customerId: string; installId: string | null; product: string; shortName: string; domain: string; id: string; serverId: string; customerId: string; installId: string | null; product: string; shortName: string; domain: string;
webPort: number; apiPort: number; status: string; version: string | null; adminName: string | null; adminEmail: string | null; isDemo?: boolean; webPort: number; apiPort: number; status: string; version: string | null; adminName: string | null; adminEmail: string | null; isDemo?: boolean;
liveAt: string | null; createdAt: string; liveAt: string | null; createdAt: string;
server?: { id: string; name: string }; customer?: { id: string; name: string }; server?: { id: string; name: string }; customer?: { id: string; name: string; isDemo?: boolean };
install?: { id: string; version: string | null; lastHeartbeatAt: string | null; url: string } | null; install?: { id: string; version: string | null; lastHeartbeatAt: string | null; url: string } | null;
}; };
+3
View File
@@ -44,6 +44,9 @@ export type Customer = {
createdAt: string; createdAt: string;
/** Hub 2.12.0: archived (left out of the customer list until restored). */ /** Hub 2.12.0: archived (left out of the customer list until restored). */
archivedAt?: string | null; archivedAt?: string | null;
/** Hub 2.25.0: a demo client: all its installs are demo sites, and it isn't billed. */
isDemo?: boolean;
demoSince?: string | null;
/** Hub 2.0: the church's AI allowance, shared by all its installs. */ /** Hub 2.0: the church's AI allowance, shared by all its installs. */
aiMonthlyCapCents: number; aiMonthlyCapCents: number;
aiMarkupPercent: number | null; aiMarkupPercent: number | null;