/** * 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 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, reviewTier, planPrice, extraStorageBlocks, STORAGE, ADDRESS, 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 = 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) { const contact = install?.adminContact && typeof install.adminContact === 'object' ? install.adminContact.email : null; 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 }); 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 }; } /** * 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); 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 }; } /** "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 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 }, }; } /** The monthly price of the customer's address in cents (a custom price wins). */ function addressMonthlyCents(customer) { if (customer.addressCustomCents != null && customer.addressCustomCents >= 0) return customer.addressCustomCents; return (ADDRESS[customer.addressType || 'own_domain']?.monthly || 0) * 100; } /** The address line for a period, or null (own domain, or free). 12 months' price when yearly. */ function addressLine(customer, { start, end, cycle }) { const cents = addressMonthlyCents(customer); if (!cents) return null; const option = ADDRESS[customer.addressType] || ADDRESS.own_domain; const m = monthsIn(cycle); return { description: `${option.label}${customer.domain ? ` (${customer.domain})` : ''}, ${m === 12 ? '12 months' : periodLabel(start, end)}`, quantity: m, unitCents: cents, amountCents: m * cents, }; } /** * 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 = [...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); // The church's address: once per invoice with any product on it, never discounted. const address = addressLine(customer, { start, end, cycle }); if (address && products.length) lines.push(address); 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 = 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: null, issueDate: periodStart, dueDate: addDays(periodStart, Number.isFinite(terms) && terms >= 0 ? terms : 7), periodStart, periodEnd, cycle, plan: r.plan, incomeBand: reviewed ? r.eventsBand : null, reviewed, founding: !!customer.founding, 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 }, }, customerUpdate: { nextInvoiceDate: nextStart, reviewDate }, licenceUpdates: r.licenceUpdates, }; } /** * 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; 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); 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 `${invoice.licenceId ? 'Cross Events licence' : 'Licences'}, ${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, contactInstall, cleanLines, totals, planLines, productLabel, customerInvoiceLines, draftCustomerInvoice, addressMonthlyCents, planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn, monthlyRecurringCents, };