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:
Generated
+6
-6
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"name": "events-hub-backend",
|
||||
"version": "2.24.1",
|
||||
"version": "2.25.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "events-hub-backend",
|
||||
"version": "2.24.1",
|
||||
"version": "2.25.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@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/client": "^7.10.1",
|
||||
"bcryptjs": "^2.4.3",
|
||||
@@ -609,9 +609,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@crosscode/contracts": {
|
||||
"version": "1.18.0",
|
||||
"resolved": "file:vendor/crosscode-contracts-1.18.0.tgz",
|
||||
"integrity": "sha512-3rcu08JRg+yL5xdRI5IV0RBjQ2NWTr0EG1oM0X6ISAVtyOWjxAsWtUWpmkwG/wlhgcvdOWGvv/katB+F9P8EqQ==",
|
||||
"version": "1.19.0",
|
||||
"resolved": "file:vendor/crosscode-contracts-1.19.0.tgz",
|
||||
"integrity": "sha512-s6gXVYT6FmoABS0ozcLVhavC/AeD7cGBngvDVl1WkZb0NB8qRYaK42JR/HD5IM79x4WOZcsfUXZGeuDbYUULrA==",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "events-hub-backend",
|
||||
"version": "2.24.1",
|
||||
"version": "2.25.0",
|
||||
"private": true,
|
||||
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
|
||||
"main": "src/index.js",
|
||||
@@ -20,7 +20,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^1.3.0",
|
||||
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.18.0.tgz",
|
||||
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.19.0.tgz",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"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);
|
||||
@@ -69,6 +69,11 @@ model Customer {
|
||||
aiMarkupPercent Int?
|
||||
// Hub 2.12.0: archived (left out of the customer list until restored). Nothing else changes.
|
||||
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())
|
||||
updatedAt DateTime @updatedAt
|
||||
licences Licence[]
|
||||
|
||||
@@ -204,7 +204,7 @@ const billingLicence = l => ({
|
||||
|
||||
/** A customer's schedule and address for the billing screens. */
|
||||
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),
|
||||
});
|
||||
|
||||
@@ -280,6 +280,7 @@ router.get('/customers/:id/preview', wrap(async (req, res) => {
|
||||
const { getSettings } = require('../utils/settings');
|
||||
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.isDemo) return res.json({ billed: false, demo: true });
|
||||
if (customer.billingCycle === 'none' || !customer.nextInvoiceDate) return res.json({ billed: false });
|
||||
const { invoice, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings: await getSettings() });
|
||||
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 } });
|
||||
if (!existing) throw bad('Customer not found', 404);
|
||||
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 === '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.');
|
||||
|
||||
@@ -216,7 +216,7 @@ router.post('/deployments/link', 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);
|
||||
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 });
|
||||
}));
|
||||
|
||||
// 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.
|
||||
router.get('/deployments/:id/env', wrap(async (req, res) => {
|
||||
res.json(await jobs.envState(req.params.id));
|
||||
|
||||
@@ -72,7 +72,8 @@ async function draftForCustomer(customerId, settings) {
|
||||
// Lock the customer row: two runs never draft the same period.
|
||||
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 } } } });
|
||||
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 });
|
||||
await tx.customer.update({ where: { id: customer.id }, data: customerUpdate });
|
||||
if (empty) return { empty: true };
|
||||
@@ -119,7 +120,7 @@ async function createDueDrafts(now, settings) {
|
||||
const days = parseInt(settings.billing_draft_days, 10) || 14;
|
||||
const horizon = addDays(today(now), days);
|
||||
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 },
|
||||
});
|
||||
let made = 0;
|
||||
@@ -185,6 +186,7 @@ async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
|
||||
async function sendInvoice(id, settings, now = new Date()) {
|
||||
const invoice = await loadInvoice(id);
|
||||
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);
|
||||
// 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 } });
|
||||
@@ -444,6 +446,7 @@ async function createManualInvoice(body) {
|
||||
const settings = await getSettings();
|
||||
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.isDemo) throw bad(`${customer.name} is a demo client, so it isn't billed.`, 409);
|
||||
const lines = compute.cleanLines(body.lines || []);
|
||||
if (!lines.length) throw bad('Add at least one line.');
|
||||
const issueDate = body.issueDate ? day(body.issueDate) : today();
|
||||
|
||||
+66
-17
@@ -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;
|
||||
const ports = await portsFor();
|
||||
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 } });
|
||||
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 d = await prisma.$transaction(async tx => {
|
||||
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']]) {
|
||||
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) licence = (await generateLicence(tx, { customerId: d.customerId, product: 'accounts', now })).licence;
|
||||
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 } });
|
||||
const o = next();
|
||||
const job = await makeJob(tx, {
|
||||
@@ -1620,7 +1620,7 @@ async function linkDeployment(input, admin) {
|
||||
const domain = new URL(install.url).hostname;
|
||||
return prisma.$transaction(async tx => {
|
||||
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']]) {
|
||||
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 });
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
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 (d.product !== 'events') throw fail(400, 'NOT_EVENTS', 'Only Cross Events installs have demo data.');
|
||||
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 } });
|
||||
/** Whether a customer is a demo client (2.25.0): its new installs start as demo sites. */
|
||||
async function customerIsDemo(db, customerId) {
|
||||
if (!customerId) return false;
|
||||
const c = await db.customer.findUnique({ where: { id: customerId } });
|
||||
return !!c?.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
|
||||
* 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()) {
|
||||
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { server: true } });
|
||||
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.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 (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 (compareVersions(d.server.agentVersion || '0.0.0', agent.SEED_DEMO_MIN_AGENT) < 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).`);
|
||||
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'}; ${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' } });
|
||||
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;
|
||||
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) ─────────────────
|
||||
|
||||
const ENV_PRODUCTS = ['events', 'accounts'];
|
||||
@@ -1765,7 +1814,7 @@ async function setEnv(deploymentId, { file, set, unset, restart }, admin, now =
|
||||
|
||||
module.exports = {
|
||||
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,
|
||||
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,
|
||||
|
||||
@@ -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') });
|
||||
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)', () => {
|
||||
const statusResult = (domain = 'accounts.found.co.za') => ({ churches: [{ church: 'found', address: 'found.co.za', products: [
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
Reference in New Issue
Block a user