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>
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
/**
|
||||
* 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.
|
||||
* - Yearly billing is 10 months' price for 12 months. Founding churches pay the founding price.
|
||||
* - 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 anchorDayOf = licence => day(licence.billingStart || licence.nextInvoiceDate).getUTCDate();
|
||||
const monthsIn = cycle => (cycle === 'yearly' ? 12 : 1);
|
||||
|
||||
/** Who an invoice goes to: the customer's billing email, the site's admin contact, the customer's email. */
|
||||
function recipientFor(customer, install) {
|
||||
const contact = install?.adminContact && typeof install.adminContact === 'object' ? install.adminContact.email : null;
|
||||
return customer?.billingEmail || contact || customer?.email || 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 });
|
||||
const out = lines
|
||||
.filter(l => l && String(l.description || '').trim())
|
||||
.map((l, i) => {
|
||||
const quantity = Number(l.quantity ?? 1);
|
||||
const unitCents = Math.round(Number(l.unitCents));
|
||||
if (!Number.isFinite(quantity) || quantity <= 0 || quantity > 10000) throw Object.assign(new Error(`Line ${i + 1}: enter a quantity above 0.`), { status: 400 });
|
||||
if (!Number.isInteger(unitCents) || Math.abs(unitCents) > 1e9) throw Object.assign(new Error(`Line ${i + 1}: enter a price.`), { status: 400 });
|
||||
return { description: String(l.description).trim().slice(0, 300), quantity, unitCents, amountCents: Math.round(quantity * unitCents) };
|
||||
});
|
||||
if (out.length > 50) throw Object.assign(new Error('An invoice can have at most 50 lines.'), { status: 400 });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Total and VAT included in it. `settings.vat_registered` 'true' → VAT-inclusive at vat_rate %. */
|
||||
function totals(lines, settings = {}) {
|
||||
const totalCents = lines.reduce((s, l) => s + l.amountCents, 0);
|
||||
const registered = String(settings.vat_registered) === 'true';
|
||||
const rate = registered ? (parseFloat(settings.vat_rate) || 15) / 100 : null;
|
||||
const vatCents = registered && totalCents > 0 ? Math.round((totalCents * rate) / (1 + rate)) : 0;
|
||||
return { totalCents, vatCents, vatRate: rate };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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? }.
|
||||
*/
|
||||
function planLines({ plan, customMonthlyCents, cycle, periodStart, periodEnd, founding }) {
|
||||
const price = planPrice(plan, customMonthlyCents);
|
||||
if (!price) return { lines: [], warning: `There's no price for the "${plan}" plan. Set a custom monthly price on the licence, or add the lines yourself.` };
|
||||
const months = cycle === 'yearly' ? YEARLY_MONTHS : 1;
|
||||
const label = periodLabel(periodStart, periodEnd);
|
||||
const what = tierNamed(plan) ? `${tierNamed(plan).name} tier` : plan;
|
||||
const lines = [{
|
||||
description: cycle === 'yearly'
|
||||
? `Cross Events licence: ${what}, 12 months (${label}), paid yearly: 2 months free`
|
||||
: `Cross Events licence: ${what}, ${label}`,
|
||||
quantity: months, unitCents: price.monthlyCents, amountCents: months * price.monthlyCents,
|
||||
}];
|
||||
if (founding && price.foundingCents < price.monthlyCents) {
|
||||
const off = price.foundingCents - price.monthlyCents;
|
||||
lines.push({ description: `Founding church discount (${FOUNDING_PERCENT}%)`, quantity: months, unitCents: off, amountCents: months * off });
|
||||
}
|
||||
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 = [];
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
const { lines, warning } = planLines({ plan, customMonthlyCents: licence.customMonthlyCents, cycle, periodStart, periodEnd, founding: !!customer.founding });
|
||||
if (warning) warnings.push(warning);
|
||||
const recipientEmail = recipientFor(customer, install);
|
||||
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;
|
||||
if (reviewed) while (ymd(reviewDate) <= ymd(periodStart)) reviewDate = addMonths(reviewDate, 12);
|
||||
|
||||
return {
|
||||
invoice: {
|
||||
customerId: customer.id,
|
||||
licenceId: licence.id,
|
||||
issueDate: periodStart,
|
||||
dueDate: addDays(periodStart, Number.isFinite(terms) && terms >= 0 ? terms : 7),
|
||||
periodStart,
|
||||
periodEnd,
|
||||
cycle,
|
||||
plan,
|
||||
incomeBand: reviewed ? band : null,
|
||||
reviewed,
|
||||
founding: !!customer.founding,
|
||||
planChange,
|
||||
lines,
|
||||
...totals(lines, settings),
|
||||
warnings,
|
||||
recipientEmail,
|
||||
},
|
||||
licenceUpdate: { nextInvoiceDate: nextStart, reviewDate },
|
||||
};
|
||||
}
|
||||
|
||||
/** 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);
|
||||
const balanceCents = invoice.totalCents - paidCents;
|
||||
let state = invoice.status;
|
||||
if (invoice.status === 'sent') {
|
||||
if (balanceCents <= 0) state = 'paid';
|
||||
else if (ymd(invoice.dueDate) < todayYmd) state = 'overdue';
|
||||
else state = paidCents > 0 ? 'part_paid' : 'unpaid';
|
||||
}
|
||||
return { paidCents, balanceCents, state };
|
||||
}
|
||||
|
||||
function invoiceDescription(invoice) {
|
||||
if (invoice.periodStart && invoice.periodEnd) return `Cross Events licence, ${periodLabel(invoice.periodStart, invoice.periodEnd)}`;
|
||||
return (invoice.lines?.[0]?.description || 'Invoice').slice(0, 80);
|
||||
}
|
||||
|
||||
/**
|
||||
* A statement from `from` to `to` (inclusive): the balance brought forward, each sent invoice
|
||||
* (debit) and payment (credit) in date order with a running balance, the closing balance, and
|
||||
* invoices still owing. Drafts, approved-but-unsent and void invoices aren't on it.
|
||||
*/
|
||||
function statement({ invoices, payments, from, to }) {
|
||||
const f = ymd(from);
|
||||
const t = ymd(to);
|
||||
const live = invoices.filter(i => i.status === 'sent');
|
||||
const before = d => ymd(d) < f;
|
||||
const within = d => ymd(d) >= f && ymd(d) <= t;
|
||||
const opening = live.filter(i => before(i.issueDate)).reduce((s, i) => s + i.totalCents, 0)
|
||||
- payments.filter(p => before(p.paidOn)).reduce((s, p) => s + p.amountCents, 0);
|
||||
const entries = [
|
||||
...live.filter(i => within(i.issueDate)).map(i => ({ date: ymd(i.issueDate), kind: 'invoice', reference: i.number, description: invoiceDescription(i), debitCents: i.totalCents, creditCents: 0 })),
|
||||
...payments.filter(p => within(p.paidOn)).map(p => ({ date: ymd(p.paidOn), kind: 'payment', reference: p.receiptNumber, description: `Payment received${p.invoice?.number ? ` for ${p.invoice.number}` : ''}${p.reference ? ` (ref ${p.reference})` : ''}`, debitCents: 0, creditCents: p.amountCents })),
|
||||
].sort((a, b) => a.date.localeCompare(b.date) || (a.kind === 'invoice' ? -1 : 1));
|
||||
let balance = opening;
|
||||
for (const e of entries) {
|
||||
balance += e.debitCents - e.creditCents;
|
||||
e.balanceCents = balance;
|
||||
}
|
||||
// Payments up to the statement date only.
|
||||
const paidBy = p => ymd(p.paidOn) <= t;
|
||||
const outstanding = live
|
||||
.filter(i => ymd(i.issueDate) <= t)
|
||||
.map(i => ({ ...i, ...invoiceState({ ...i, payments: (i.payments || []).filter(paidBy) }, t) }))
|
||||
.filter(i => i.balanceCents > 0)
|
||||
.map(i => ({ number: i.number, issueDate: ymd(i.issueDate), dueDate: ymd(i.dueDate), totalCents: i.totalCents, balanceCents: i.balanceCents, overdue: ymd(i.dueDate) < t }));
|
||||
return { from: f, to: t, openingCents: opening, entries, closingCents: balance, outstanding };
|
||||
}
|
||||
|
||||
module.exports = { recipientFor, cleanLines, totals, planLines, draftInvoice, invoiceState, statement, invoiceDescription, anchorDayOf };
|
||||
Reference in New Issue
Block a user