Files
events-hub/backend/tests/billing.test.js
T
joshuaandClaude Opus 5.5 6fce0fe90e Billing: invoices, approval, receipts, statements, licence changes (1.7.0)
- Invoices drafted 14 days before each licence's invoice date and emailed
  to the alert email for approval; approved ones go out on their date from
  08:00 SA time. Drafts can be edited, recalculated, sent early, put back
  to draft or voided; one-off invoices too.
- Annual tier review from the 12-month event-income band; approving a tier
  change emails a notice of licence change, applied when the invoice goes out.
  Notices can also be sent by hand.
- Founding churches (35% off as its own line), payments with receipts,
  statements for any dates.
- Every billing email is styled HTML with a PDF (invoice / tax invoice,
  receipt, statement, licence change) and logged per customer.
- Settings -> Billing: business and bank details, VAT (off: plain invoices;
  on: VAT-inclusive tax invoices), timing and numbering.
- Migration 20261103111645_invoicing; pdfkit 0.17.2; tests/billing.test.js;
  scripts/sample-billing-pdfs.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:42:45 +02:00

202 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
jest.mock('../src/config/db', () => ({}));
const fs = require('fs');
const path = require('path');
const { TIERS, tierForBand, planPrice } = 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 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 settings = { payment_terms_days: '7' };
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]));
});
test('a band falls in the tier whose top it fits under', () => {
expect(tierForBand('R0–R1 000').name).toBe('Seed');
expect(tierForBand('R20 001–R50 000').name).toBe('Seed');
expect(tierForBand('R100 001–R150 000').name).toBe('Sprout');
expect(tierForBand('R700 001–R1 000 000').name).toBe('Flourish');
expect(tierForBand('over R10 000 000').name).toBe('Network');
expect(tierForBand('over R100 000')).toBeNull(); // an old install
expect(tierForBand(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();
});
});
describe('dates', () => {
test('months keep the billing day, or the month\'s last day', () => {
expect(ymd(addMonths(day('2026-01-31'), 1, 31))).toBe('2026-02-28');
expect(ymd(addMonths(day('2026-02-28'), 1, 31))).toBe('2026-03-31');
expect(ymd(addMonths(day('2028-01-31'), 1, 31))).toBe('2028-02-29');
expect(ymd(addMonths(day('2026-12-15'), 12))).toBe('2027-12-15');
});
test('today and the hour are South African', () => {
const late = new Date('2026-11-30T23:30:00Z'); // 01:30 on 1 December in South Africa
expect(ymd(today(late))).toBe('2026-12-01');
expect(saHour(late)).toBe(1);
});
test('labels and money', () => {
expect(periodLabel(day('2026-12-01'), day('2026-12-31'))).toBe('December 2026');
expect(periodLabel(day('2026-12-15'), day('2027-01-14'))).toBe('15 December 2026 – 14 January 2027');
expect(money(135000)).toBe('R1 350.00');
expect(money(-30000)).toBe('-R300.00');
expect(() => day('2026-02-30')).toThrow('Not a valid date.');
});
});
describe('drafting an invoice', () => {
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 });
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
});
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 });
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 });
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');
});
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' });
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 });
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 });
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,
});
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.totalCents).toBe(550000);
expect(ymd(licenceUpdate.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,
});
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 });
expect(invoice.lines).toEqual([]);
expect(invoice.warnings[0]).toMatch(/no price for the "standard" plan/);
});
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 });
expect(ymd(invoice.periodEnd)).toBe('2027-02-27');
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-02-28');
});
});
describe('who it goes to', () => {
test('billing email, then the site\'s admin contact, then the customer\'s email', () => {
expect(recipientFor(customer({ billingEmail: 'accounts@hope.example' }), install(null))).toBe('accounts@hope.example');
expect(recipientFor(customer(), install(null))).toBe('admin@hope.example');
expect(recipientFor(customer(), null)).toBe('office@hope.example');
});
});
describe('lines and VAT', () => {
test('lines are checked and their amounts worked out', () => {
expect(cleanLines([{ description: ' Standby support ', quantity: 2, unitCents: 50000 }, { description: '' }])).toEqual([{ description: 'Standby support', quantity: 2, unitCents: 50000, amountCents: 100000 }]);
expect(() => cleanLines([{ description: 'x', quantity: 0, unitCents: 1 }])).toThrow('quantity');
});
test('not VAT registered: no VAT; registered: the same total, VAT included', () => {
const lines = [{ amountCents: 85000 }, { amountCents: -30000 }];
expect(totals(lines, {})).toEqual({ totalCents: 55000, vatCents: 0, vatRate: null });
expect(totals(lines, { vat_registered: 'true', vat_rate: '15' })).toEqual({ totalCents: 55000, vatCents: 7174, vatRate: 0.15 });
});
});
describe('payments and statements', () => {
const inv = (number, issue, total, payments = [], status = 'sent') => ({ number, status, issueDate: day(issue), dueDate: addDays(day(issue), 7), periodStart: day(issue), periodEnd: addDays(addMonths(day(issue), 1), -1), totalCents: total, payments });
test('where an invoice stands', () => {
expect(invoiceState(inv('A', '2026-12-01', 55000), '2026-12-05')).toMatchObject({ state: 'unpaid', balanceCents: 55000 });
expect(invoiceState(inv('A', '2026-12-01', 55000, [{ amountCents: 20000 }]), '2026-12-05')).toMatchObject({ state: 'part_paid', paidCents: 20000, balanceCents: 35000 });
expect(invoiceState(inv('A', '2026-12-01', 55000, [{ amountCents: 20000 }]), '2026-12-09').state).toBe('overdue');
expect(invoiceState(inv('A', '2026-12-01', 55000, [{ amountCents: 55000 }]), '2026-12-20').state).toBe('paid');
expect(invoiceState(inv('A', '2026-12-01', 55000, [], 'draft'), '2026-12-20').state).toBe('draft');
});
test('a statement: brought forward, running balance, what\'s still owing', () => {
const p1 = { receiptNumber: 'REC-1', amountCents: 55000, paidOn: day('2026-11-05'), invoice: { number: 'INV-1' } };
const p2 = { receiptNumber: 'REC-2', amountCents: 20000, paidOn: day('2026-12-10'), reference: 'EFT 123', invoice: { number: 'INV-2' } };
const invoices = [
inv('INV-1', '2026-11-01', 55000, [p1]),
inv('INV-2', '2026-12-01', 55000, [p2]),
inv('INV-3', '2027-01-01', 55000, []),
inv('INV-X', '2026-12-15', 99900, [], 'void'),
inv('INV-D', '2026-12-20', 55000, [], 'draft'),
];
const st = statement({ invoices, payments: [p1, p2], from: '2026-12-01', to: '2026-12-31' });
expect(st.openingCents).toBe(0);
expect(st.entries.map(e => [e.date, e.reference, e.debitCents, e.creditCents, e.balanceCents])).toEqual([
['2026-12-01', 'INV-2', 55000, 0, 55000],
['2026-12-10', 'REC-2', 0, 20000, 35000],
]);
expect(st.entries[1].description).toBe('Payment received for INV-2 (ref EFT 123)');
expect(st.closingCents).toBe(35000);
expect(st.outstanding).toEqual([{ number: 'INV-2', issueDate: '2026-12-01', dueDate: '2026-12-08', totalCents: 55000, balanceCents: 35000, overdue: true }]);
const later = statement({ invoices, payments: [p1, p2], from: '2027-01-01', to: '2027-01-05' });
expect(later.openingCents).toBe(35000);
expect(later.closingCents).toBe(90000);
});
});