From e697564ff5e350f6fcdddf5d565db7265c579f42 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Thu, 5 Nov 2026 09:03:39 +0200 Subject: [PATCH] Hub 2.0 step 7: dashboard per product, revenue, linked products Dashboard: monthly recurring revenue after discounts, overdue invoices, per-product installs, latest version, behind, critical and licences. Install page: the church's other products and whether they're listed to this site. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++ backend/src/routes/admin.js | 32 ++++++++++++++++--- backend/src/utils/billing/compute.js | 20 +++++++++++- backend/tests/billing.test.js | 20 ++++++++++++ frontend/src/app/(hub)/installs/[id]/page.tsx | 25 ++++++++++++++- frontend/src/app/(hub)/page.tsx | 31 ++++++++++++++++-- 6 files changed, 125 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3dcb307..8ada73d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index 37aacee..9d1782c 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -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 })), }); })); diff --git a/backend/src/utils/billing/compute.js b/backend/src/utils/billing/compute.js index 3715aa0..6410f0a 100644 --- a/backend/src/utils/billing/compute.js +++ b/backend/src/utils/billing/compute.js @@ -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, }; diff --git a/backend/tests/billing.test.js b/backend/tests/billing.test.js index f0f4508..b301642 100644 --- a/backend/tests/billing.test.js +++ b/backend/tests/billing.test.js @@ -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); + }); +}); diff --git a/frontend/src/app/(hub)/installs/[id]/page.tsx b/frontend/src/app/(hub)/installs/[id]/page.tsx index e330fd4..2767599 100644 --- a/frontend/src/app/(hub)/installs/[id]/page.tsx +++ b/frontend/src/app/(hub)/installs/[id]/page.tsx @@ -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() { )} +
+

The church's other products

+ {d.siblings.length === 0 ?

None: this is the church's only product in use.

: ( + <> + + + {d.siblings.map(s => ( + + + + + + + ))} + +
{PRODUCT_NAMES[s.product]}{s.url}{s.version || "—"}{d.linkedProducts.some(l => l.installId === s.id) ? listed to this site : {s.hasPublicKey ? "not listed (licence revoked)" : `not listed (protocol ${s.protocolVersion}: no public key yet)`}}
+

{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."}

+ + )} +
+

Health

diff --git a/frontend/src/app/(hub)/page.tsx b/frontend/src/app/(hub)/page.tsx index 514c9bd..5aa54a0 100644 --- a/frontend/src/app/(hub)/page.tsx +++ b/frontend/src/app/(hub)/page.tsx @@ -12,10 +12,16 @@ import { Badge, Loading, PageTitle, Pager, SearchInput, Stat } from "@/component type Dashboard = { latestVersion: string | null; latestVersions: Partial>; - counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record }; + counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record; billedCustomers: number; overdueInvoices: number }; + // Hub 2.0: per product, and the money. + byProduct: Record }>; + 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() {
+
+ + + {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 ( +
+
{PRODUCT_NAMES[p]}
+
{b.installs} install{b.installs === 1 ? "" : "s"}
+
+ {data.latestVersions[p] ? `Latest ${data.latestVersions[p]}` : "No release yet"} + {b.behind ? · {b.behind} behind : null} + {b.critical ? · {b.critical} critical : null} +
+
{licences}
+
+ ); + })} +
+ {data.installs.length === 0 ? (
- No installs yet. Add a customer, generate a licence, and enter its key in the church's Cross Events setup. + No installs yet. Add a customer, generate a licence, and enter its key in the church's setup (Cross Events, Website, App or Accounts).
) : ( <>