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 <noreply@anthropic.com>
This commit is contained in:
@@ -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 })),
|
||||
});
|
||||
}));
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user