Merge branch 'feat/hub2-dashboard' into release/2.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 09:03:40 +02:00
co-authored by Claude Opus 5.5
6 changed files with 125 additions and 8 deletions
+5
View File
@@ -65,6 +65,11 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`).
Details), shared by all its sites: a call from any of them counts what all of them used this month,
under one lock so two calls at once can't both take the last of it. The licence token carries the
church's cap. Settings → AI shows each site's use with its product and the church's cap.
- **Dashboard** (step 7): monthly recurring revenue (each billed church's full month after
discounts, add-ons included, yearly divided by 12), overdue invoices, and per product: installs,
latest version, how many are behind or critical, and licences by status. The install page lists
the church's other products and whether this site is told about them (Linked products, protocol
v2), next to what an update needs (step 3).
### Changed
+28 -4
View File
@@ -5,7 +5,10 @@ const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { protect } = require('../middleware/auth');
const { generateLicence, checkReopen } = require('../utils/licences');
const { isProduct, PRODUCT_NAMES } = require('../utils/products');
const { PRODUCTS, isProduct, PRODUCT_NAMES } = require('../utils/products');
const compute = require('../utils/billing/compute');
const { ymd, today } = require('../utils/billing/dates');
const { linkedProductsFor } = require('../utils/protocol');
const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const { problems, compareVersions } = require('../utils/alerts');
@@ -65,11 +68,23 @@ router.get('/dashboard', wrap(async (req, res) => {
const [settings, latest] = await Promise.all([getSettings(), latestVersions()]);
const installs = await prisma.install.findMany({ where: { releasedAt: null }, include: { licence: true, customer: true }, orderBy: { name: 'asc' } });
const rows = installs.map(i => summary(i, settings, latest));
const [customers, licences, openAlerts] = await Promise.all([
const [customers, licences, openAlerts, billed, sentInvoices] = await Promise.all([
prisma.customer.count(),
prisma.licence.groupBy({ by: ['status'], _count: { _all: true } }),
prisma.licence.groupBy({ by: ['product', 'status'], _count: { _all: true } }),
prisma.installEvent.count({ where: { resolvedAt: null, level: { not: 'info' } } }),
prisma.customer.findMany({ where: { billingCycle: { not: 'none' } }, include: { licences: { include: { install: true } } } }),
prisma.invoice.findMany({ where: { status: 'sent' }, include: { payments: true } }),
]);
// Hub 2.0: per product, monthly recurring revenue (after discounts) and overdue invoices.
const byProduct = Object.fromEntries(PRODUCTS.map(p => {
const own = rows.filter(r => r.product === p);
return [p, {
installs: own.length, behind: own.filter(r => r.behind).length, critical: own.filter(r => r.status === 'critical').length,
licences: Object.fromEntries(licences.filter(l => l.product === p).map(l => [l.status, l._count._all])),
}];
}));
const t = ymd(today());
const overdue = sentInvoices.map(i => compute.invoiceState(i, t)).filter(s => s.state === 'overdue');
res.json({
latestVersion: latest.events || null,
latestVersions: latest,
@@ -80,9 +95,14 @@ router.get('/dashboard', wrap(async (req, res) => {
critical: rows.filter(r => r.status === 'critical').length,
behind: rows.filter(r => r.behind).length,
customers,
licences: Object.fromEntries(licences.map(l => [l.status, l._count._all])),
licences: licences.reduce((acc, l) => ({ ...acc, [l.status]: (acc[l.status] || 0) + l._count._all }), {}),
openAlerts,
billedCustomers: billed.length,
overdueInvoices: overdue.length,
},
byProduct,
monthlyRecurringCents: billed.reduce((s, c) => s + compute.monthlyRecurringCents(c, c.licences), 0),
overdueCents: overdue.reduce((s, x) => s + x.balanceCents, 0),
installs: rows,
});
}));
@@ -237,6 +257,10 @@ router.get('/installs/:id', wrap(async (req, res) => {
...safe, licence, summary: summary(install, settings, latest), heartbeats, ai: { status: aiStatus, months: aiMonths, helpers: aiHelpers },
// What updating to the latest version needs from the church's other products (Hub 2.0).
update: { latestVersion: target, behind, unmetRequirements: unmet },
// The church's other installs this one is told about (protocol v2), and the ones it isn't.
linkedProducts: await linkedProductsFor(install),
siblings: (await prisma.install.findMany({ where: { customerId: install.customerId, id: { not: install.id }, releasedAt: null }, select: { id: true, product: true, url: true, version: true, protocolVersion: true, publicKey: true, lastHeartbeatAt: true } }))
.map(({ publicKey, ...s }) => ({ ...s, hasPublicKey: !!publicKey })),
});
}));
+19 -1
View File
@@ -298,6 +298,24 @@ function draftCustomerInvoice({ customer, licences, settings = {} }) {
};
}
/**
* What a billed customer pays a month as things stand (Hub 2.0 dashboard): a full period of every
* product charged by now, after founding and bundle discounts, plus add-ons; a yearly invoice
* divided by 12. Days owed from before a period aren't recurring, so they're left out. Cents.
*/
function monthlyRecurringCents(customer, licences, now = new Date()) {
if (customer.billingCycle !== 'monthly' && customer.billingCycle !== 'yearly') return 0;
const start = day(customer.nextInvoiceDate || now);
const end = addDays(addMonths(start, monthsIn(customer.billingCycle), anchorDayOf({ billingStart: customer.billingStart, nextInvoiceDate: start })), -1);
const charged = licences
.filter(l => l.billedFrom && ymd(l.billedFrom) <= ymd(now))
// As if invoiced up to this period, and charged for all of it.
.map(l => ({ ...l, billedFrom: ymd(l.billedFrom) < ymd(start) ? l.billedFrom : start, billedUntil: addDays(start, -1) }));
const { lines } = customerInvoiceLines({ customer, licences: charged, period: { start, end, cycle: customer.billingCycle }, reviewed: false });
const total = lines.reduce((s, l) => s + l.amountCents, 0);
return Math.round(customer.billingCycle === 'yearly' ? total / 12 : total);
}
/** An invoice's tier changes as a list (Hub 1.7 stored one object). */
function planChangesOf(invoice) {
const pc = invoice?.planChange;
@@ -357,5 +375,5 @@ function statement({ invoices, payments, from, to }) {
module.exports = {
recipientFor, contactInstall, cleanLines, totals, planLines, productLabel, customerInvoiceLines, draftCustomerInvoice, addressMonthlyCents,
planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn,
planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn, monthlyRecurringCents,
};
+20
View File
@@ -371,3 +371,23 @@ describe('the church\'s address (one per church, never discounted)', () => {
expect(empty).toBe(true);
});
});
describe('monthly recurring revenue (dashboard)', () => {
const { monthlyRecurringCents } = require('../src/utils/billing/compute');
const now = new Date('2026-11-20T10:00:00Z');
test('a full month of each product charged now, after founding and bundle, plus add-ons', () => {
// Founding: 360 + 64 = R424, less 15% = R360.40, plus a Cross Code address R10.
expect(monthlyRecurringCents(customer({ founding: true, addressType: 'crosscode' }), [events(), website(), accounts()], now)).toBe(37040);
});
test('days owed from before a period aren\'t recurring; a product not charged yet doesn\'t count', () => {
expect(monthlyRecurringCents(customer(), [events(), app({ billedFrom: day('2026-11-10'), billedUntil: null })], now)).toBe(Math.round((55000 + 9900) * 0.85));
expect(monthlyRecurringCents(customer(), [events(), app({ billedFrom: day('2026-12-15'), billedUntil: null })], now)).toBe(55000);
});
test('yearly is a twelfth of the year\'s invoice; not billed is 0', () => {
expect(monthlyRecurringCents(customer({ billingCycle: 'yearly' }), [events()], now)).toBe(Math.round((55000 * 10) / 12));
expect(monthlyRecurringCents(customer({ billingCycle: 'none' }), [events()], now)).toBe(0);
});
});
+24 -1
View File
@@ -8,7 +8,7 @@ import { api, errorText } from "@/lib/api";
import { ago, bytes, fmtDate, rand, randFine } from "@/lib/format";
import { usePaged } from "@/lib/paging";
import { tierForBand, tierPrice } from "@/lib/tiers";
import { PRODUCT_NAMES } from "@/lib/products";
import { PRODUCT_NAMES, type Product } from "@/lib/products";
import type { AiHelperUse, AiMonth, AiStatus, Health, InstallEvent, InstallSummary, Licence, Stats, UnmetRequirement } from "@/lib/types";
import { Badge, Loading, Message, PageTitle, Pager } from "@/components/ui";
@@ -24,6 +24,8 @@ type Detail = {
heartbeats: { receivedAt: string; version: string | null; stats: Stats | null }[];
ai: { status: AiStatus; months: AiMonth[]; helpers: AiHelperUse[] };
update: { latestVersion: string | null; behind: boolean; unmetRequirements: UnmetRequirement[] };
linkedProducts: { product: Product; installId: string; url: string }[];
siblings: { id: string; product: Product; url: string; version: string | null; protocolVersion: number; hasPublicKey: boolean; lastHeartbeatAt: string | null }[];
};
const NO_EVENTS: InstallEvent[] = [];
@@ -86,6 +88,27 @@ export default function InstallPage() {
</div>
)}
<div className="card mb-6 text-sm">
<h2 className="mb-2 font-semibold">The church&apos;s other products</h2>
{d.siblings.length === 0 ? <p className="text-slate-500">None: this is the church&apos;s only product in use.</p> : (
<>
<table className="w-full">
<tbody>
{d.siblings.map(s => (
<tr key={s.id} className="border-t border-slate-100 first:border-0">
<td className="py-1.5 pr-3"><Link href={`/installs/${s.id}`} className="text-indigo-700 hover:underline">{PRODUCT_NAMES[s.product]}</Link></td>
<td className="py-1.5 pr-3 text-slate-600">{s.url}</td>
<td className="py-1.5 pr-3">{s.version || "—"}</td>
<td className="py-1.5 text-right text-xs">{d.linkedProducts.some(l => l.installId === s.id) ? <span className="text-green-700">listed to this site</span> : <span className="text-slate-500">{s.hasPublicKey ? "not listed (licence revoked)" : `not listed (protocol ${s.protocolVersion}: no public key yet)`}</span>}</td>
</tr>
))}
</tbody>
</table>
<p className="mt-2 text-xs text-slate-500">{d.protocolVersion >= 2 ? "This site is told about the products listed to it in each heartbeat reply (Linked products), so it can connect to them." : "This site uses protocol 1 (Cross Events before 2.4), so it isn't told about the others yet."}</p>
</>
)}
</div>
<div className="grid gap-6 md:grid-cols-2">
<div className="card">
<h2 className="mb-2 font-semibold">Health</h2>
+29 -2
View File
@@ -12,10 +12,16 @@ import { Badge, Loading, PageTitle, Pager, SearchInput, Stat } from "@/component
type Dashboard = {
latestVersion: string | null;
latestVersions: Partial<Record<Product, string>>;
counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record<string, number> };
counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record<string, number>; billedCustomers: number; overdueInvoices: number };
// Hub 2.0: per product, and the money.
byProduct: Record<Product, { installs: number; behind: number; critical: number; licences: Record<string, number> }>;
monthlyRecurringCents: number;
overdueCents: number;
installs: InstallSummary[];
};
const rands = (cents: number) => `R${Math.round(cents / 100).toLocaleString("en-ZA")}`;
type Health = "all" | InstallSummary["status"] | "behind";
const HEALTH: { key: Health; label: string }[] = [
{ key: "all", label: "All health" },
@@ -65,9 +71,30 @@ export default function OverviewPage() {
<Stat label="Behind latest" value={c.behind} tone={c.behind ? "amber" : undefined} />
</div>
<div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-6">
<Link href="/billing" className="col-span-2 md:col-span-1"><Stat label="Monthly recurring" value={rands(data.monthlyRecurringCents)} /></Link>
<Link href="/billing" className="col-span-2 md:col-span-1"><Stat label="Overdue" value={c.overdueInvoices ? `${rands(data.overdueCents)} (${c.overdueInvoices})` : "None"} tone={c.overdueInvoices ? "red" : undefined} /></Link>
{PRODUCTS.map(p => {
const b = data.byProduct[p];
const licences = Object.entries(b.licences).filter(([, n]) => n).map(([s, n]) => `${n} ${s}`).join(", ") || "no licences";
return (
<div key={p} className="card">
<div className="text-sm text-slate-500">{PRODUCT_NAMES[p]}</div>
<div className="mt-1 text-2xl font-semibold tabular-nums">{b.installs} <span className="text-sm font-normal text-slate-500">install{b.installs === 1 ? "" : "s"}</span></div>
<div className="mt-1 text-xs text-slate-500">
{data.latestVersions[p] ? `Latest ${data.latestVersions[p]}` : "No release yet"}
{b.behind ? <span className="text-amber-700"> · {b.behind} behind</span> : null}
{b.critical ? <span className="text-red-700"> · {b.critical} critical</span> : null}
</div>
<div className="text-xs text-slate-400">{licences}</div>
</div>
);
})}
</div>
{data.installs.length === 0 ? (
<div className="card text-sm text-slate-600">
No installs yet. Add a <Link href="/customers" className="text-indigo-600 hover:underline">customer</Link>, generate a licence, and enter its key in the church&apos;s Cross Events setup.
No installs yet. Add a <Link href="/customers" className="text-indigo-600 hover:underline">customer</Link>, generate a licence, and enter its key in the church&apos;s setup (Cross Events, Website, App or Accounts).
</div>
) : (
<>