Hub 2.0 step 4: billing per customer

- One invoice per customer per period for all its products; the schedule
  moves from Licence to Customer (migration copies it, so billing carries
  on unchanged); licences get billedFrom / billedUntil
- Website (R99, 5 GB) and App (on active members) prices next to the
  Events tiers; founding prices per product, then bundles (15% two, 25%
  three); extra website storage R20 per 5 GB, never discounted
- A product added to a billed customer starts after its free month; days
  before its first full period are prorated, never charged twice
- Annual review per product (Events income, App members), one notice of
  licence change per product; invoices, PDFs and emails name products
- Customer page: schedule, per-product billing, next-invoice preview
- Invoices from before 2.0 kept as they were (still recalculable)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 16:18:23 +02:00
co-authored by Claude Opus 5.5
parent 937c1fa38e
commit 7478e84e9d
21 changed files with 1081 additions and 316 deletions
+202 -53
View File
@@ -2,19 +2,34 @@
* Billing calculations, pure (no database): what an invoice for a period contains, totals and
* VAT, where an invoice stands with its payments, and a statement.
*
* Rules (decided 2026-11-03):
* - Invoices are in advance: the invoice dated the 1st covers the period starting that day.
* - The tier is reviewed once a year: the first invoice for a period starting on or after the
* licence's reviewDate uses the 12-month event-income band; invoices in between keep the tier.
* Rules (decided 2026-11-03 and 2026-11-04, Hub 2.0):
* - One invoice per customer per period, for all its products. Invoices are in advance: the
* invoice dated the 1st covers the period starting that day.
* - Each product is priced on its own plan (prices in tiers.js). Tiers are reviewed once a year:
* the first invoice for a period starting on or after the customer's reviewDate uses what each
* product reports (Events: 12-month event income; App: active members); invoices in between keep
* the tier.
* - Yearly billing is 10 months' price for 12 months. Founding churches pay the founding price.
* - Bundles: 15% off two products, 25% off three, on the products after founding (Accounts is free
* and never counts).
* - Add-ons (extra website storage) are never discounted: no founding, bundle or yearly discount.
* - A product that starts part-way through a period (after its free month, decision 3) is charged
* by the day for the days before its first full period: on the invoice for the period it starts
* in, or the next one if that was already invoiced.
* - Not VAT registered: no VAT. Once registered, prices are VAT-inclusive (totals unchanged).
*/
const { tierNamed, tierForBand, planPrice, YEARLY_MONTHS, FOUNDING_PERCENT } = require('./tiers');
const { ymd, day, addDays, addMonths, periodLabel } = require('./dates');
const {
tierNamed, reviewTier, planPrice, extraStorageBlocks, STORAGE, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
} = require('./tiers');
const { ymd, day, addDays, addMonths, periodLabel, shortDate } = require('./dates');
const { PRODUCTS, PRODUCT_NAMES, BILLABLE } = require('../products');
const anchorDayOf = licence => day(licence.billingStart || licence.nextInvoiceDate).getUTCDate();
const anchorDayOf = schedule => day(schedule.billingStart || schedule.nextInvoiceDate).getUTCDate();
const monthsIn = cycle => (cycle === 'yearly' ? 12 : 1);
const DAY = 864e5;
const daysBetween = (a, b) => Math.round((day(b) - day(a)) / DAY) + 1;
const later = (a, b) => (ymd(a) >= ymd(b) ? day(a) : day(b));
/** Who an invoice goes to: the customer's billing email, the site's admin contact, the customer's email. */
function recipientFor(customer, install) {
@@ -22,6 +37,12 @@ function recipientFor(customer, install) {
return customer?.billingEmail || contact || customer?.email || null;
}
/** The install whose admin contact invoices fall back on: Events first, then any in use. */
function contactInstall(licences) {
const installs = licences.map(l => l.install).filter(i => i && !i.releasedAt);
return installs.find(i => i.product === 'events' && i.adminContact?.email) || installs.find(i => i.adminContact?.email) || installs[0] || null;
}
/** Cleans invoice lines from the form: [{ description, quantity, unitCents, amountCents }]. */
function cleanLines(lines) {
if (!Array.isArray(lines)) throw Object.assign(new Error('Lines must be a list.'), { status: 400 });
@@ -48,8 +69,8 @@ function totals(lines, settings = {}) {
}
/**
* The lines for a plan over a period: the tier's price (×10 for a year) and, for a founding
* church, the founding discount as its own line. Returns { lines, warning? }.
* Before Hub 2.0: the lines for one Cross Events licence's plan over a period. Kept to recalculate
* drafts made by Hub 1.7 (licenceId set). Returns { lines, warning? }.
*/
function planLines({ plan, customMonthlyCents, cycle, periodStart, periodEnd, founding }) {
const price = planPrice(plan, customMonthlyCents);
@@ -70,73 +91,198 @@ function planLines({ plan, customMonthlyCents, cycle, periodStart, periodEnd, fo
return { lines };
}
/**
* The draft invoice for a licence's next period (licence.nextInvoiceDate), and how the licence
* moves on. `install` gives the income band (stats.income.eventIncome12m) and admin contact.
* Returns { invoice, licenceUpdate }.
*/
function draftInvoice({ licence, customer, install, settings = {} }) {
const cycle = licence.billingCycle;
if (cycle !== 'monthly' && cycle !== 'yearly') throw new Error('This licence isn\'t billed.');
const anchor = anchorDayOf(licence);
const periodStart = day(licence.nextInvoiceDate);
const nextStart = addMonths(periodStart, monthsIn(cycle), anchor);
const periodEnd = addDays(nextStart, -1);
const warnings = [];
/** "Cross Events, Grow tier" · "Church Website" · "Church App, Small Group tier". */
function productLabel(product, plan) {
const name = PRODUCT_NAMES[product];
if (product === 'website' && tierNamed(plan, 'website')) return name;
const tier = tierNamed(plan, product);
return `${name}, ${tier ? `${tier.name} tier` : plan}`;
}
// The yearly review: the first period starting on or after reviewDate.
const reviewed = !!licence.reviewDate && ymd(periodStart) >= ymd(licence.reviewDate);
const band = install?.stats?.income?.eventIncome12m || null;
let plan = licence.plan;
let planChange = null;
if (reviewed) {
const tier = tierForBand(band);
if (!tier) {
warnings.push(band
? `The site reports its income as "${band}", which can't be placed in a tier (Cross Events before 2.0.2). The tier stays ${plan}.`
: `The site hasn't reported its 12-month event income (it needs Cross Events 2.0.2 or later). The tier stays ${plan}.`);
} else if (licence.customMonthlyCents != null) {
if (tier.name !== plan) warnings.push(`Its income (${band}) is in the ${tier.name} tier, but the licence has a custom price, so it's kept. Change it by hand if needed.`);
} else if (tier.name !== plan) {
const from = planPrice(plan);
const to = planPrice(tier.name);
planChange = { from: plan, to: tier.name, fromMonthlyCents: from?.monthlyCents ?? null, toMonthlyCents: to?.monthlyCents ?? null, band };
plan = tier.name;
/** The tier review for one licence: { plan, planChange, warning }. */
function reviewLicence(licence, product) {
const { tier, band } = reviewTier(product, licence.install);
const plan = licence.plan;
if (tier === undefined) return { plan, planChange: null, warning: null, band };
const what = product === 'events' ? '12-month event income' : 'active members (last 90 days)';
if (!tier) {
const needs = product === 'events' ? ' (it needs Cross Events 2.0.2 or later)' : '';
return {
plan, planChange: null, band,
warning: band
? `${PRODUCT_NAMES[product]} reports its ${what} as "${band}", which can't be placed in a tier. The tier stays ${plan}.`
: `${PRODUCT_NAMES[product]} hasn't reported its ${what}${needs}. The tier stays ${plan}.`,
};
}
if (licence.customMonthlyCents != null) {
return { plan, planChange: null, band, warning: tier.name !== plan ? `${PRODUCT_NAMES[product]}: its ${what} (${band}) is in the ${tier.name} tier, but the licence has a custom price, so it's kept. Change it by hand if needed.` : null };
}
if (tier.name === plan) return { plan, planChange: null, warning: null, band };
const from = planPrice(plan, null, product);
const to = planPrice(tier.name, null, product);
return {
plan: tier.name, band, warning: null,
planChange: { licenceId: licence.id, product, from: plan, to: tier.name, fromMonthlyCents: from?.monthlyCents ?? null, toMonthlyCents: to?.monthlyCents ?? null, band },
};
}
/**
* A customer's invoice lines for a period: each billed product (with a prorated line for days
* owed before the period), its founding discount, the bundle discount, then add-ons. Pure.
*
* `licences` are the customer's licences with their install (`billedUntil` as it was before this
* period was invoiced). Returns { lines, plan, planChanges, warnings, licenceUpdates, products,
* eventsBand }.
*/
function customerInvoiceLines({ customer, licences, period, reviewed }) {
const { start, end, cycle } = period;
const months = cycle === 'yearly' ? YEARLY_MONTHS : 1;
// By the day: a year's price over 365 days (10 months' for yearly billing).
const perDay = cents => (cents * (cycle === 'yearly' ? YEARLY_MONTHS : 12)) / 365;
const founding = !!customer.founding;
const productLines = [];
const addOns = [];
const warnings = [];
const planChanges = [];
const licenceUpdates = [];
const products = [];
const plans = [];
let eventsBand = null;
const billed = licences
.filter(l => l.status === 'active' && BILLABLE.includes(l.product) && l.billedFrom && ymd(l.billedFrom) <= ymd(end))
.sort((a, b) => PRODUCTS.indexOf(a.product) - PRODUCTS.indexOf(b.product));
for (const licence of billed) {
const product = licence.product;
let plan = licence.plan;
if (reviewed) {
const r = reviewLicence(licence, product);
plan = r.plan;
if (r.warning) warnings.push(r.warning);
if (r.planChange) planChanges.push(r.planChange);
if (product === 'events') eventsBand = r.band;
}
const price = planPrice(plan, licence.customMonthlyCents, product);
if (!price) {
warnings.push(`${PRODUCT_NAMES[product]}: there's no price for the "${plan}" plan. Set a custom monthly price on the licence, or add the lines yourself.`);
continue;
}
const label = productLabel(product, plan);
const off = founding && price.foundingCents < price.monthlyCents ? price.foundingCents - price.monthlyCents : 0;
const add = (description, quantity, unitCents) => {
productLines.push({ description, quantity, unitCents, amountCents: Math.round(quantity * unitCents) });
if (off) {
const unitOff = unitCents === price.monthlyCents ? off : Math.round((unitCents * off) / price.monthlyCents);
productLines.push({ description: `Founding church discount (${FOUNDING_PERCENT}%)`, quantity, unitCents: unitOff, amountCents: Math.round(quantity * unitOff) });
}
};
// Days owed from before this period: it started after the last invoice was made.
const owedFrom = licence.billedUntil ? later(licence.billedFrom, addDays(licence.billedUntil, 1)) : day(licence.billedFrom);
if (ymd(owedFrom) < ymd(start)) {
const to = addDays(start, -1);
const days = daysBetween(owedFrom, to);
add(`${label}, ${shortDate(owedFrom)} – ${shortDate(to)} (${days} day${days === 1 ? '' : 's'} before this period)`, 1, Math.round(perDay(price.monthlyCents) * days));
}
// This period: all of it, or from the day it starts.
if (ymd(licence.billedFrom) <= ymd(start)) {
const range = periodLabel(start, end);
add(cycle === 'yearly' ? `${label}, 12 months (${range}), paid yearly: 2 months free` : `${label}, ${range}`, months, price.monthlyCents);
} else {
const days = daysBetween(licence.billedFrom, end);
add(`${label}, ${shortDate(licence.billedFrom)} – ${shortDate(end)} (${days} day${days === 1 ? '' : 's'}, from its start)`, 1, Math.round(perDay(price.monthlyCents) * days));
}
// Add-ons for the whole period only (measured now), never discounted.
if (product === 'website' && ymd(licence.billedFrom) <= ymd(start)) {
const blocks = extraStorageBlocks(licence.install?.stats?.storage);
if (blocks) {
const m = monthsIn(cycle);
addOns.push({
description: `Extra website storage: ${blocks} × 5 GB, ${m === 12 ? '12 months' : periodLabel(start, end)}`,
quantity: blocks * m, unitCents: STORAGE.monthly * 100, amountCents: blocks * m * STORAGE.monthly * 100,
});
}
}
products.push(product);
plans.push({ product, plan });
licenceUpdates.push({ id: licence.id, data: { billedUntil: day(end) } });
}
const { lines, warning } = planLines({ plan, customMonthlyCents: licence.customMonthlyCents, cycle, periodStart, periodEnd, founding: !!customer.founding });
if (warning) warnings.push(warning);
const recipientEmail = recipientFor(customer, install);
const lines = [...productLines];
const pct = BUNDLE_PERCENT[Math.min(products.length, 3)];
if (pct) {
const base = productLines.reduce((s, l) => s + l.amountCents, 0);
const cut = -Math.round((base * pct) / 100);
lines.push({ description: `Bundle discount (${pct}%: ${products.map(p => PRODUCT_NAMES[p]).join(', ').replace(/, ([^,]*)$/, ' and $1')})`, quantity: 1, unitCents: cut, amountCents: cut });
}
lines.push(...addOns);
const plan = plans.length === 1 && plans[0].product === 'events'
? plans[0].plan
: plans.map(p => (p.product === 'website' ? PRODUCT_NAMES.website : `${PRODUCT_NAMES[p.product]} ${p.plan}`)).join(' · ') || null;
return { lines, plan, planChanges, warnings, licenceUpdates, products, eventsBand };
}
/**
* The draft invoice for a customer's next period (customer.nextInvoiceDate), and how the
* customer and its licences move on. Returns { invoice, customerUpdate, licenceUpdates, empty }:
* `empty` when no product was billed and there's nothing to warn about (no invoice is made).
*/
function draftCustomerInvoice({ customer, licences, settings = {} }) {
const cycle = customer.billingCycle;
if (cycle !== 'monthly' && cycle !== 'yearly') throw new Error('This customer isn\'t billed.');
const anchor = anchorDayOf(customer);
const periodStart = day(customer.nextInvoiceDate);
const nextStart = addMonths(periodStart, monthsIn(cycle), anchor);
const periodEnd = addDays(nextStart, -1);
const reviewed = !!customer.reviewDate && ymd(periodStart) >= ymd(customer.reviewDate);
const r = customerInvoiceLines({ customer, licences, period: { start: periodStart, end: periodEnd, cycle }, reviewed });
const warnings = [...r.warnings];
const recipientEmail = recipientFor(customer, contactInstall(licences));
if (!recipientEmail) warnings.push('No email address to send it to: add a billing email on the customer.');
const terms = parseInt(settings.payment_terms_days, 10);
let reviewDate = licence.reviewDate ? day(licence.reviewDate) : null;
let reviewDate = customer.reviewDate ? day(customer.reviewDate) : null;
if (reviewed) while (ymd(reviewDate) <= ymd(periodStart)) reviewDate = addMonths(reviewDate, 12);
return {
empty: r.products.length === 0 && r.warnings.length === 0,
invoice: {
customerId: customer.id,
licenceId: licence.id,
licenceId: null,
issueDate: periodStart,
dueDate: addDays(periodStart, Number.isFinite(terms) && terms >= 0 ? terms : 7),
periodStart,
periodEnd,
cycle,
plan,
incomeBand: reviewed ? band : null,
plan: r.plan,
incomeBand: reviewed ? r.eventsBand : null,
reviewed,
founding: !!customer.founding,
planChange,
lines,
...totals(lines, settings),
planChange: r.planChanges.length ? r.planChanges : null,
lines: r.lines,
...totals(r.lines, settings),
warnings,
recipientEmail,
basis: { licences: licences.map(l => ({ id: l.id, billedUntil: ymd(l.billedUntil) })), planChangeDropped: false },
},
licenceUpdate: { nextInvoiceDate: nextStart, reviewDate },
customerUpdate: { nextInvoiceDate: nextStart, reviewDate },
licenceUpdates: r.licenceUpdates,
};
}
/** An invoice's tier changes as a list (Hub 1.7 stored one object). */
function planChangesOf(invoice) {
const pc = invoice?.planChange;
if (!pc) return [];
return Array.isArray(pc) ? pc : [{ licenceId: invoice.licenceId || null, product: 'events', ...pc }];
}
/** What's been paid on an invoice and where it stands. `todayYmd` decides "overdue". */
function invoiceState(invoice, todayYmd) {
const paidCents = (invoice.payments || []).reduce((s, p) => s + p.amountCents, 0);
@@ -151,7 +297,7 @@ function invoiceState(invoice, todayYmd) {
}
function invoiceDescription(invoice) {
if (invoice.periodStart && invoice.periodEnd) return `Cross Events licence, ${periodLabel(invoice.periodStart, invoice.periodEnd)}`;
if (invoice.periodStart && invoice.periodEnd) return `${invoice.licenceId ? 'Cross Events licence' : 'Licences'}, ${periodLabel(invoice.periodStart, invoice.periodEnd)}`;
return (invoice.lines?.[0]?.description || 'Invoice').slice(0, 80);
}
@@ -187,4 +333,7 @@ function statement({ invoices, payments, from, to }) {
return { from: f, to: t, openingCents: opening, entries, closingCents: balance, outstanding };
}
module.exports = { recipientFor, cleanLines, totals, planLines, draftInvoice, invoiceState, statement, invoiceDescription, anchorDayOf };
module.exports = {
recipientFor, contactInstall, cleanLines, totals, planLines, productLabel, customerInvoiceLines, draftCustomerInvoice,
planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn,
};