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
+188 -40
View File
@@ -2,24 +2,48 @@ jest.mock('../src/config/db', () => ({}));
const fs = require('fs');
const path = require('path');
const { TIERS, tierForBand, planPrice } = require('../src/utils/billing/tiers');
const { hub } = require('@crosscode/contracts');
const { TIERS, WEBSITE_PLANS, APP_TIERS, tierForBand, appTierForBand, planPrice, extraStorageBlocks } = require('../src/utils/billing/tiers');
const { day, ymd, addMonths, addDays, today, saHour, periodLabel, money } = require('../src/utils/billing/dates');
const { draftInvoice, cleanLines, totals, invoiceState, statement, recipientFor } = require('../src/utils/billing/compute');
const { draftCustomerInvoice, customerInvoiceLines, planChangesOf, cleanLines, totals, invoiceState, statement, recipientFor } = require('../src/utils/billing/compute');
const customer = (extra = {}) => ({ id: 'c1', name: 'Hope Church', email: 'office@hope.example', founding: false, ...extra });
const install = (band, email = 'admin@hope.example') => ({ adminContact: { email }, stats: band ? { income: { eventIncome12m: band } } : {} });
const licence = (extra = {}) => ({
id: 'l1', plan: 'Sprout', billingCycle: 'monthly', billingStart: day('2026-01-01'), nextInvoiceDate: day('2026-12-01'),
reviewDate: day('2027-01-01'), customMonthlyCents: null, ...extra,
const GB = 1024 ** 3;
const customer = (extra = {}) => ({
id: 'c1', name: 'Hope Church', email: 'office@hope.example', founding: false,
billingCycle: 'monthly', billingStart: day('2026-01-01'), nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-01-01'), ...extra,
});
const install = (band, email = 'admin@hope.example') => ({ product: 'events', adminContact: { email }, stats: band ? { income: { eventIncome12m: band } } : {} });
const events = (extra = {}) => ({
id: 'l1', product: 'events', status: 'active', plan: 'Sprout', customMonthlyCents: null,
billedFrom: day('2026-01-01'), billedUntil: day('2026-11-30'), install: install('R100 001–R150 000'), ...extra,
});
const website = (extra = {}) => ({
id: 'l2', product: 'website', status: 'active', plan: 'Website', customMonthlyCents: null,
billedFrom: day('2026-06-01'), billedUntil: day('2026-11-30'), install: { product: 'website', stats: {} }, ...extra,
});
const app = (extra = {}) => ({
id: 'l3', product: 'app', status: 'active', plan: 'Mustard Seed', customMonthlyCents: null,
billedFrom: day('2026-06-01'), billedUntil: day('2026-11-30'), install: { product: 'app', stats: { activeMembers90d: '0–100' } }, ...extra,
});
const accounts = () => ({ id: 'l4', product: 'accounts', status: 'active', plan: 'included', billedFrom: null, billedUntil: null, install: null });
const settings = { payment_terms_days: '7' };
const draft = (c, licences) => draftCustomerInvoice({ customer: c, licences, settings });
const amounts = invoice => invoice.lines.map(l => [l.description, l.amountCents]);
describe('tiers', () => {
test('the server and the Hub screens have the same tiers', () => {
const ts = fs.readFileSync(path.join(__dirname, '..', '..', 'frontend', 'src', 'lib', 'tiers.ts'), 'utf8');
const front = [...ts.matchAll(/\{ name: "(\w+)", upTo: ([\d_]+|null), monthly: (\d+|null), founding: (\d+|null) \}/g)]
.map(m => [m[1], m[2] === 'null' ? null : Number(m[2].replace(/_/g, '')), m[3] === 'null' ? null : Number(m[3]), m[4] === 'null' ? null : Number(m[4])]);
expect(front).toEqual(TIERS.map(t => [t.name, t.upTo, t.monthly, t.founding]));
const front = fs.readFileSync(path.join(__dirname, '..', '..', 'frontend', 'src', 'lib', 'tiers.ts'), 'utf8');
const num = v => (v === 'null' ? null : Number(v.replace(/_/g, '')));
test('the server and the Hub screens have the same Cross Events tiers', () => {
const rows = [...front.matchAll(/\{ name: "(\w+)", upTo: ([\d_]+|null), monthly: (\d+|null), founding: (\d+|null) \}/g)].map(m => [m[1], num(m[2]), num(m[3]), num(m[4])]);
expect(rows).toEqual(TIERS.map(t => [t.name, t.upTo, t.monthly, t.founding]));
});
test('...and the same Church App tiers and Website price', () => {
const appRows = [...front.matchAll(/\{ name: "([\w ]+)", band: "([^"]+)", monthly: (\d+|null), founding: (\d+|null) \}/g)].map(m => [m[1], m[2], num(m[3]), num(m[4])]);
expect(appRows).toEqual(APP_TIERS.map(t => [t.name, t.band, t.monthly, t.founding]));
const site = /WEBSITE_PLAN = \{ name: "Website", monthly: (\d+), founding: (\d+) \}/.exec(front);
expect([num(site[1]), num(site[2])]).toEqual([WEBSITE_PLANS[0].monthly, WEBSITE_PLANS[0].founding]);
});
test('a band falls in the tier whose top it fits under', () => {
@@ -32,11 +56,27 @@ describe('tiers', () => {
expect(tierForBand(null)).toBeNull();
});
test('every App active-member band (contracts) has a tier', () => {
expect(APP_TIERS.map(t => t.band)).toEqual([...hub.ACTIVE_MEMBER_BANDS]);
expect(appTierForBand('101–300').name).toBe('Small Group');
expect(appTierForBand(null)).toBeNull();
});
test('prices: the tier\'s, or a custom one with 35% off for founding', () => {
expect(planPrice('Grow')).toEqual({ monthlyCents: 85000, foundingCents: 55000, custom: false });
expect(planPrice('Network')).toBeNull();
expect(planPrice('Network', 750000)).toEqual({ monthlyCents: 750000, foundingCents: 487500, custom: true });
expect(planPrice('standard')).toBeNull();
expect(planPrice('Website', null, 'website')).toEqual({ monthlyCents: 9900, foundingCents: 6400, custom: false });
expect(planPrice('Small Group', null, 'app')).toEqual({ monthlyCents: 24900, foundingCents: 16200, custom: false });
expect(planPrice('Grow', null, 'app')).toBeNull(); // another product's tier
});
test('extra storage: whole 5 GB blocks above what is included', () => {
expect(extraStorageBlocks({ usedBytes: 4 * GB, includedBytes: 5 * GB })).toBe(0);
expect(extraStorageBlocks({ usedBytes: 5 * GB + 1, includedBytes: 5 * GB })).toBe(1);
expect(extraStorageBlocks({ usedBytes: 11 * GB })).toBe(2);
expect(extraStorageBlocks(null)).toBe(0);
});
});
@@ -63,82 +103,190 @@ describe('dates', () => {
});
});
describe('drafting an invoice', () => {
describe('drafting an invoice (one product, as before Hub 2.0)', () => {
test('monthly, in advance: the period starting on its date, due after the payment terms', () => {
const { invoice, licenceUpdate } = draftInvoice({ licence: licence(), customer: customer(), install: install('R100 001–R150 000'), settings });
const { invoice, customerUpdate, licenceUpdates } = draft(customer(), [events(), accounts()]);
expect(ymd(invoice.issueDate)).toBe('2026-12-01');
expect(ymd(invoice.dueDate)).toBe('2026-12-08');
expect([ymd(invoice.periodStart), ymd(invoice.periodEnd)]).toEqual(['2026-12-01', '2026-12-31']);
expect(invoice.lines).toEqual([{ description: 'Cross Events licence: Sprout tier, December 2026', quantity: 1, unitCents: 55000, amountCents: 55000 }]);
expect(invoice).toMatchObject({ totalCents: 55000, vatCents: 0, reviewed: false, planChange: null, recipientEmail: 'admin@hope.example', warnings: [] });
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-01-01');
expect(ymd(licenceUpdate.reviewDate)).toBe('2027-01-01'); // not reviewed yet
expect(invoice.lines).toEqual([{ description: 'Cross Events, Sprout tier, December 2026', quantity: 1, unitCents: 55000, amountCents: 55000 }]);
expect(invoice).toMatchObject({ licenceId: null, plan: 'Sprout', totalCents: 55000, vatCents: 0, reviewed: false, planChange: null, recipientEmail: 'admin@hope.example', warnings: [] });
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-01-01');
expect(ymd(customerUpdate.reviewDate)).toBe('2027-01-01'); // not reviewed yet
expect(licenceUpdates.map(u => [u.id, ymd(u.data.billedUntil)])).toEqual([['l1', '2026-12-31']]);
expect(invoice.basis.licences).toEqual([{ id: 'l1', billedUntil: '2026-11-30' }, { id: 'l4', billedUntil: null }]);
});
test('between reviews the tier stays, whatever the income', () => {
const { invoice } = draftInvoice({ licence: licence(), customer: customer(), install: install('R1 000 001–R2 500 000'), settings });
const { invoice } = draft(customer(), [events({ install: install('R1 000 001–R2 500 000') })]);
expect(invoice.plan).toBe('Sprout');
expect(invoice.incomeBand).toBeNull();
});
test('at the yearly review the income moves the tier up, and the next review is a year on', () => {
const { invoice, licenceUpdate } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install('R250 001–R400 000'), settings });
const { invoice, customerUpdate } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install('R250 001–R400 000') })]);
expect(invoice).toMatchObject({ reviewed: true, plan: 'Grow', incomeBand: 'R250 001–R400 000', totalCents: 85000 });
expect(invoice.planChange).toEqual({ from: 'Sprout', to: 'Grow', fromMonthlyCents: 55000, toMonthlyCents: 85000, band: 'R250 001–R400 000' });
expect(ymd(licenceUpdate.reviewDate)).toBe('2028-01-01');
expect(invoice.planChange).toEqual([{ licenceId: 'l1', product: 'events', from: 'Sprout', to: 'Grow', fromMonthlyCents: 55000, toMonthlyCents: 85000, band: 'R250 001–R400 000' }]);
expect(ymd(customerUpdate.reviewDate)).toBe('2028-01-01');
});
test('...or down', () => {
const { invoice } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install('R5 001–R20 000'), settings });
expect(invoice.planChange).toMatchObject({ from: 'Sprout', to: 'Seed' });
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install('R5 001–R20 000') })]);
expect(invoice.planChange[0]).toMatchObject({ from: 'Sprout', to: 'Seed' });
expect(invoice.totalCents).toBe(35000);
});
test('no band at the review: the tier stays and Joshua is warned', () => {
const { invoice } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install(null), settings });
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install(null) })]);
expect(invoice.plan).toBe('Sprout');
expect(invoice.planChange).toBeNull();
expect(invoice.warnings[0]).toMatch(/hasn't reported its 12-month event income/);
});
test('a founding church gets the founding price as its own line', () => {
const { invoice } = draftInvoice({ licence: licence(), customer: customer({ founding: true }), install: install(null), settings });
const { invoice } = draft(customer({ founding: true }), [events()]);
expect(invoice.lines[1]).toEqual({ description: 'Founding church discount (35%)', quantity: 1, unitCents: -19000, amountCents: -19000 });
expect(invoice.totalCents).toBe(36000);
expect(invoice.founding).toBe(true);
});
test('yearly: 10 months\' price for 12 months, founding on all of it', () => {
const { invoice, licenceUpdate } = draftInvoice({
licence: licence({ plan: 'Grow', billingCycle: 'yearly', nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-12-01') }),
customer: customer({ founding: true }), install: install(null), settings,
});
const { invoice, customerUpdate } = draft(
customer({ founding: true, billingCycle: 'yearly', nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-12-01') }),
[events({ plan: 'Grow' })],
);
expect([ymd(invoice.periodStart), ymd(invoice.periodEnd)]).toEqual(['2026-12-01', '2027-11-30']);
expect(invoice.lines.map(l => [l.quantity, l.unitCents, l.amountCents])).toEqual([[10, 85000, 850000], [10, -30000, -300000]]);
expect(invoice.lines[0].description).toBe('Cross Events licence: Grow tier, 12 months (1 December 2026 – 30 November 2027), paid yearly: 2 months free');
expect(invoice.lines[0].description).toBe('Cross Events, Grow tier, 12 months (1 December 2026 – 30 November 2027), paid yearly: 2 months free');
expect(invoice.totalCents).toBe(550000);
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-12-01');
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-12-01');
});
test('a custom price is kept at the review, with a note if the income points elsewhere', () => {
const { invoice } = draftInvoice({
licence: licence({ plan: 'Network', customMonthlyCents: 750000, nextInvoiceDate: day('2027-01-01') }),
customer: customer(), install: install('R5 000 001–R10 000 000'), settings,
});
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ plan: 'Network', customMonthlyCents: 750000, billedUntil: day('2026-12-31'), install: install('R5 000 001–R10 000 000') })]);
expect(invoice).toMatchObject({ plan: 'Network', totalCents: 750000, planChange: null });
expect(invoice.warnings[0]).toMatch(/Movement tier, but the licence has a custom price/);
});
test('an unpriced plan makes an empty draft with a warning', () => {
const { invoice } = draftInvoice({ licence: licence({ plan: 'standard' }), customer: customer(), install: install(null), settings });
test('an unpriced plan makes an empty draft with a warning (so it isn\'t skipped)', () => {
const { invoice, empty } = draft(customer(), [events({ plan: 'standard' })]);
expect(invoice.lines).toEqual([]);
expect(invoice.warnings[0]).toMatch(/no price for the "standard" plan/);
expect(empty).toBe(false);
});
test('month-end billing day stays on the last day', () => {
const { invoice, licenceUpdate } = draftInvoice({ licence: licence({ billingStart: day('2026-01-31'), nextInvoiceDate: day('2027-01-31'), reviewDate: day('2028-01-31') }), customer: customer(), install: install(null), settings });
const { invoice, customerUpdate } = draft(customer({ billingStart: day('2026-01-31'), nextInvoiceDate: day('2027-01-31'), reviewDate: day('2028-01-31') }), [events({ billedUntil: day('2027-01-30') })]);
expect(ymd(invoice.periodEnd)).toBe('2027-02-27');
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-02-28');
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-02-28');
});
test('nothing billed (only Accounts, a trial or a suspended licence): no invoice, the customer still moves on', () => {
for (const licences of [[accounts()], [events({ billedFrom: null })], [events({ status: 'suspended' })], []]) {
const { empty, customerUpdate } = draft(customer(), licences);
expect(empty).toBe(true);
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-01-01');
}
});
});
describe('drafting an invoice (several products, Hub 2.0)', () => {
test('two products: each at its price, then 15% off them', () => {
const { invoice } = draft(customer(), [events(), website(), accounts()]);
expect(amounts(invoice)).toEqual([
['Cross Events, Sprout tier, December 2026', 55000],
['Church Website, December 2026', 9900],
['Bundle discount (15%: Cross Events and Church Website)', -9735],
]);
expect(invoice.totalCents).toBe(55165);
expect(invoice.plan).toBe('Cross Events Sprout · Church Website');
});
test('three products: 25% off, after the founding prices (decision 1)', () => {
const { invoice } = draft(customer({ founding: true }), [events(), website(), app()]);
// Founding: 360 + 64 + 64 = R488, less 25% = R366.
expect(invoice.totalCents).toBe(36600);
expect(invoice.lines.at(-1)).toMatchObject({ description: 'Bundle discount (25%: Cross Events, Church Website and Church App)', amountCents: -12200 });
});
test('Accounts never counts towards a bundle, and is never on the invoice', () => {
const { invoice } = draft(customer(), [events(), accounts()]);
expect(invoice.lines.some(l => /Bundle|Accounts/.test(l.description))).toBe(false);
});
test('extra website storage: R20 per 5 GB a month, never discounted', () => {
const { invoice } = draft(customer({ founding: true }), [events(), website({ install: { product: 'website', stats: { storage: { usedBytes: 12 * GB, includedBytes: 5 * GB } } } })]);
expect(invoice.lines.at(-1)).toEqual({ description: 'Extra website storage: 2 × 5 GB, December 2026', quantity: 2, unitCents: 2000, amountCents: 4000 });
// The bundle comes off the products only: (360 + 64) × 15% = R63.60.
expect(invoice.lines.find(l => /Bundle/.test(l.description)).amountCents).toBe(-6360);
});
test('yearly: add-ons are 12 months\' price (decision 2), products 10', () => {
const { invoice } = draft(customer({ billingCycle: 'yearly', reviewDate: day('2027-12-01') }), [website({ install: { product: 'website', stats: { storage: { usedBytes: 8 * GB } } } })]);
expect(invoice.lines.map(l => [l.quantity, l.unitCents])).toEqual([[10, 9900], [12, 2000]]);
});
test('the App is reviewed on its active members', () => {
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [app({ billedUntil: day('2026-12-31'), install: { product: 'app', stats: { activeMembers90d: '301–750' } } })]);
expect(invoice.planChange).toEqual([expect.objectContaining({ licenceId: 'l3', product: 'app', from: 'Mustard Seed', to: 'Congregation', toMonthlyCents: 39900, band: '301–750' })]);
expect(invoice.totalCents).toBe(39900);
});
test('several tier changes at one review: one per product', () => {
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [
events({ billedUntil: day('2026-12-31'), install: install('R250 001–R400 000') }),
app({ billedUntil: day('2026-12-31'), install: { product: 'app', stats: { activeMembers90d: '101–300' } } }),
]);
expect(invoice.planChange.map(pc => `${pc.product}:${pc.to}`)).toEqual(['events:Grow', 'app:Small Group']);
});
});
describe('a product added part-way (decision 3)', () => {
test('starting inside the period being drafted: charged from its first day', () => {
const { invoice, licenceUpdates } = draft(customer(), [events(), website({ billedFrom: day('2026-12-20'), billedUntil: null })]);
// R99 a month = R1 188 a year; 12 days of it.
expect(amounts(invoice)[1]).toEqual(['Church Website, 20 Dec 2026 – 31 Dec 2026 (12 days, from its start)', Math.round((9900 * 12 / 365) * 12)]);
expect(licenceUpdates.find(u => u.id === 'l2').data.billedUntil).toEqual(day('2026-12-31'));
// It counts for the bundle in that period.
expect(invoice.lines.some(l => /Bundle discount \(15%/.test(l.description))).toBe(true);
});
test('starting in a period invoiced already: those days on the next invoice, then the full period', () => {
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01'), reviewDate: day('2027-06-01') }), [
events({ billedUntil: day('2026-12-31') }),
app({ billedFrom: day('2026-12-15'), billedUntil: null }),
]);
expect(amounts(invoice).slice(1, 3)).toEqual([
['Church App, Mustard Seed tier, 15 Dec 2026 – 31 Dec 2026 (17 days before this period)', Math.round((9900 * 12 / 365) * 17)],
['Church App, Mustard Seed tier, January 2027', 9900],
]);
});
test('starting after the period: not on this invoice', () => {
const { invoice } = draft(customer(), [events(), website({ billedFrom: day('2027-01-05'), billedUntil: null })]);
expect(invoice.lines.map(l => l.description)).toEqual(['Cross Events, Sprout tier, December 2026']);
});
test('days are never charged twice', () => {
// Invoiced up to the end of December already: nothing owed from before January.
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01'), reviewDate: day('2027-06-01') }), [app({ billedFrom: day('2026-12-15'), billedUntil: day('2026-12-31') })]);
expect(invoice.lines.map(l => l.description)).toEqual(['Church App, Mustard Seed tier, January 2027']);
});
test('a founding church\'s founding price is prorated the same way', () => {
const { lines } = customerInvoiceLines({
customer: customer({ founding: true }), licences: [website({ billedFrom: day('2026-12-20'), billedUntil: null })],
period: { start: day('2026-12-01'), end: day('2026-12-31'), cycle: 'monthly' }, reviewed: false,
});
const full = Math.round((9900 * 12 / 365) * 12);
expect(lines.map(l => l.amountCents)).toEqual([full, Math.round((full * -3500) / 9900)]);
});
});
describe('tier changes stored before Hub 2.0', () => {
test('one object reads as a list of one Cross Events change', () => {
expect(planChangesOf({ licenceId: 'l1', planChange: { from: 'Seed', to: 'Sprout' } })).toEqual([{ licenceId: 'l1', product: 'events', from: 'Seed', to: 'Sprout' }]);
expect(planChangesOf({ planChange: null })).toEqual([]);
});
});