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
+3 -1
View File
@@ -166,7 +166,9 @@ router.post('/customers/:id/licences', wrap(async (req, res) => {
if (!customer) throw bad('Customer not found', 404);
const product = req.body?.product ?? 'events';
if (!isProduct(product)) throw bad('Product must be events, accounts, website or app.');
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data: licenceData(req.body) });
// A new Website licence is on its one plan, an App licence on the first tier (the review moves it).
const data = { ...(product === 'website' ? { plan: 'Website' } : product === 'app' ? { plan: 'Mustard Seed' } : {}), ...licenceData(req.body) };
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data });
await audit(req, 'licence_generated', licence.id, { customer: customer.name, product, expiresAt: licence.expiresAt });
if (accounts) await audit(req, 'licence_generated', accounts.id, { customer: customer.name, product: 'accounts', automatic: true });
res.status(201).json({ ...licence, accountsLicence: accounts });
+81 -31
View File
@@ -1,6 +1,7 @@
/**
* Billing API (1.7.0, admin login required): invoices, payments, statements, licence changes,
* founding churches and each licence's billing set-up. The work is in utils/billing/.
* founding churches, each customer's billing schedule and each licence's billing (Hub 2.0: one
* invoice per customer for all its products). The work is in utils/billing/.
*/
const express = require('express');
@@ -11,7 +12,8 @@ const { audit } = require('../utils/audit');
const billing = require('../utils/billing');
const compute = require('../utils/billing/compute');
const { ymd, day, today } = require('../utils/billing/dates');
const { TIERS } = require('../utils/billing/tiers');
const { TIERS, PLANS, BUNDLE_PERCENT, STORAGE } = require('../utils/billing/tiers');
const { addMonths } = require('../utils/billing/dates');
const { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
const router = express.Router();
@@ -43,7 +45,8 @@ function invoiceRow(invoice, todayYmd = ymd(today())) {
periodStart: ymd(invoice.periodStart), periodEnd: ymd(invoice.periodEnd),
customer: invoice.customer ? { id: invoice.customer.id, name: invoice.customer.name, founding: invoice.customer.founding } : undefined,
payments: (invoice.payments || []).map(p => ({ ...p, paidOn: ymd(p.paidOn) })),
licence: licence ? { id: licence.id, key: licence.key, plan: licence.plan, billingCycle: licence.billingCycle, installUrl: licence.install?.url || null } : null,
licence: licence ? { id: licence.id, key: licence.key, product: licence.product, plan: licence.plan, installUrl: licence.install?.url || null } : null,
planChanges: compute.planChangesOf(invoice),
...compute.invoiceState(invoice, todayYmd),
};
}
@@ -68,6 +71,7 @@ router.get('/overview', wrap(async (req, res) => {
overdue: rows.filter(i => i.state === 'overdue').length,
receivedThisMonthCents: payments.reduce((s, p) => s + p.amountCents, 0),
tiers: TIERS,
plans: PLANS,
});
}));
@@ -103,7 +107,7 @@ router.get('/invoices/:id', wrap(async (req, res) => {
prisma.licenceChange.findMany({ where: { invoiceId: invoice.id }, orderBy: { createdAt: 'desc' } }),
prisma.billingEmail.findMany({ where: { refId: invoice.id }, orderBy: { sentAt: 'desc' } }),
]);
res.json({ ...invoiceRow(invoice), licenceChanges: changes.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })), emails, tiers: TIERS });
res.json({ ...invoiceRow(invoice), licenceChanges: changes.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })), emails, tiers: TIERS, plans: PLANS });
}));
router.put('/invoices/:id', wrap(async (req, res) => {
@@ -174,7 +178,26 @@ router.get('/payments/:id/pdf', wrap(async (req, res) => sendPdf(res, await bill
// ─── Customers: founding, billing details, statements ─────────────────────────
/** Every customer's billing at a glance: founding, licences' plans and next invoice, balance. */
/** What a licence's product reports that its price depends on, for the billing screens. */
function reported(l) {
const stats = l.install?.stats || {};
if (l.product === 'events') return { incomeBand: stats.income?.eventIncome12m || null };
if (l.product === 'app') return { activeMembers: stats.activeMembers90d || null };
if (l.product === 'website') return { storage: stats.storage || null };
return {};
}
/** A licence for the billing screens. */
const billingLicence = l => ({
id: l.id, key: l.key, product: l.product, plan: l.plan, status: l.status, customMonthlyCents: l.customMonthlyCents,
billedFrom: ymd(l.billedFrom), billedUntil: ymd(l.billedUntil), billable: BILLABLE.includes(l.product),
url: l.install?.url || null, ...reported(l),
});
/** A customer's schedule for the billing screens. */
const schedule = c => ({ billingCycle: c.billingCycle, billingStart: ymd(c.billingStart), nextInvoiceDate: ymd(c.nextInvoiceDate), reviewDate: ymd(c.reviewDate) });
/** Every customer's billing at a glance: founding, schedule, licences' plans, balance. */
router.get('/customers', wrap(async (req, res) => {
const t = ymd(today());
const customers = await prisma.customer.findMany({
@@ -185,9 +208,10 @@ router.get('/customers', wrap(async (req, res) => {
const states = c.invoices.map(i => compute.invoiceState(i, t));
return {
id: c.id, name: c.name, founding: c.founding, foundingSince: ymd(c.foundingSince), foundingNote: c.foundingNote, billingEmail: c.billingEmail,
...schedule(c),
balanceCents: states.reduce((s, x) => s + Math.max(0, x.balanceCents), 0),
overdue: states.filter(x => x.state === 'overdue').length,
licences: c.licences.map(l => ({ id: l.id, key: l.key, plan: l.plan, status: l.status, billingCycle: l.billingCycle, nextInvoiceDate: ymd(l.nextInvoiceDate), reviewDate: ymd(l.reviewDate), customMonthlyCents: l.customMonthlyCents, url: l.install?.url || null })),
licences: c.licences.map(billingLicence),
};
}));
}));
@@ -206,23 +230,35 @@ router.get('/customers/:id', wrap(async (req, res) => {
});
if (!customer) throw bad('Customer not found', 404);
const invoices = customer.invoices.map(i => invoiceRow(i, t));
const install = customer.licences.find(l => l.install && !l.install.releasedAt)?.install || null;
res.json({
id: customer.id, name: customer.name, contactName: customer.contactName, email: customer.email,
billingEmail: customer.billingEmail, billingAddress: customer.billingAddress,
founding: customer.founding, foundingSince: ymd(customer.foundingSince), foundingNote: customer.foundingNote,
sendsTo: compute.recipientFor(customer, install),
...schedule(customer),
sendsTo: compute.recipientFor(customer, compute.contactInstall(customer.licences)),
balanceCents: invoices.filter(i => i.status === 'sent').reduce((s, i) => s + Math.max(0, i.balanceCents), 0),
licences: customer.licences.map(l => ({
id: l.id, key: l.key, plan: l.plan, status: l.status, billingCycle: l.billingCycle, billingStart: ymd(l.billingStart),
nextInvoiceDate: ymd(l.nextInvoiceDate), reviewDate: ymd(l.reviewDate), customMonthlyCents: l.customMonthlyCents,
url: l.install?.url || null, incomeBand: l.install?.stats?.income?.eventIncome12m || null,
})),
licences: customer.licences.map(billingLicence),
invoices,
payments: customer.payments.map(p => ({ ...p, paidOn: ymd(p.paidOn) })),
licenceChanges: customer.licenceChanges.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })),
emails: customer.billingEmails,
tiers: TIERS,
plans: PLANS,
bundlePercent: BUNDLE_PERCENT,
storage: STORAGE,
});
}));
// The next invoice as it would be drafted now (nothing is saved): its lines, discounts and total.
router.get('/customers/:id/preview', wrap(async (req, res) => {
const { getSettings } = require('../utils/settings');
const customer = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: { include: { install: true } } } });
if (!customer) throw bad('Customer not found', 404);
if (customer.billingCycle === 'none' || !customer.nextInvoiceDate) return res.json({ billed: false });
const { invoice, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings: await getSettings() });
res.json({
billed: true, empty,
invoice: { ...invoice, issueDate: ymd(invoice.issueDate), dueDate: ymd(invoice.dueDate), periodStart: ymd(invoice.periodStart), periodEnd: ymd(invoice.periodEnd), planChanges: invoice.planChange || [] },
});
}));
@@ -241,8 +277,29 @@ router.put('/customers/:id', wrap(async (req, res) => {
if (e && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) throw bad('That email address doesn\'t look right.');
data.billingEmail = e;
}
const customer = await prisma.customer.update({ where: { id: req.params.id }, data }).catch(() => { throw bad('Customer not found', 404); });
await audit(req, 'customer_billing_updated', customer.id, { changed: Object.keys(data), founding: customer.founding });
// The schedule (Hub 2.0: per customer, for all its products).
if (b.billingCycle !== undefined) {
if (!['none', 'monthly', 'yearly'].includes(b.billingCycle)) throw bad('Choose monthly, yearly or not billed.');
data.billingCycle = b.billingCycle;
}
for (const f of ['billingStart', 'nextInvoiceDate', 'reviewDate']) if (b[f] !== undefined) data[f] = dayOrNull(b[f]);
const existing = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: true } });
if (!existing) throw bad('Customer not found', 404);
const merged = { ...existing, ...data };
if (merged.billingCycle !== 'none') {
if (!merged.billingStart) throw bad('Set the date billing starts.');
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
// The first review is a year after billing starts.
if (!merged.reviewDate && b.reviewDate === undefined) data.reviewDate = addMonths(merged.billingStart, 12);
}
// Starting billing: the products not charged yet are charged from the billing start.
const start = existing.billingCycle === 'none' && merged.billingCycle !== 'none' ? merged.billingStart : null;
const startLicences = start ? existing.licences.filter(l => BILLABLE.includes(l.product) && l.status === 'active' && !l.billedFrom) : [];
const [customer] = await prisma.$transaction([
prisma.customer.update({ where: { id: existing.id }, data }),
...startLicences.map(l => prisma.licence.update({ where: { id: l.id }, data: { billedFrom: day(start) } })),
]);
await audit(req, 'customer_billing_updated', customer.id, { changed: Object.keys(data), founding: customer.founding, billingCycle: customer.billingCycle, licencesStarted: startLicences.length });
res.json({ ok: true });
}));
@@ -261,16 +318,20 @@ router.post('/customers/:id/statement/email', emailLimiter, wrap(async (req, res
// ─── Licence billing set-up ───────────────────────────────────────────────────
// Hub 2.0: when a licence is charged from (blank = not charged), and an optional custom price.
// The schedule is the customer's.
router.put('/licences/:id', wrap(async (req, res) => {
const b = req.body || {};
const existing = await prisma.licence.findUnique({ where: { id: req.params.id } });
if (!existing) throw bad('Licence not found', 404);
const data = {};
if (b.billingCycle !== undefined) {
if (!['none', 'monthly', 'yearly'].includes(b.billingCycle)) throw bad('Choose monthly, yearly or not billed.');
data.billingCycle = b.billingCycle;
if (b.billedFrom !== undefined) {
data.billedFrom = dayOrNull(b.billedFrom);
if (data.billedFrom && !BILLABLE.includes(existing.product)) throw bad(`${PRODUCT_NAMES[existing.product]} is free: it's never invoiced.`);
if (data.billedFrom && existing.billedUntil && ymd(data.billedFrom) <= ymd(existing.billedUntil)) {
throw bad(`It's invoiced up to ${ymd(existing.billedUntil)} already: choose a later date, or correct the invoices by hand.`);
}
}
for (const f of ['billingStart', 'nextInvoiceDate', 'reviewDate']) if (b[f] !== undefined) data[f] = dayOrNull(b[f]);
if (b.customMonthlyCents !== undefined) {
if (b.customMonthlyCents === null || b.customMonthlyCents === '') data.customMonthlyCents = null;
else {
@@ -279,19 +340,8 @@ router.put('/licences/:id', wrap(async (req, res) => {
data.customMonthlyCents = n;
}
}
const merged = { ...existing, ...data };
// Until billing per customer (Hub 2.0 step 4) only Events has prices; Accounts is never invoiced.
if (merged.billingCycle !== 'none' && !BILLABLE.includes(existing.product)) {
throw bad(`${PRODUCT_NAMES[existing.product]} licences can't be invoiced yet.`);
}
if (merged.billingCycle !== 'none') {
if (!merged.billingStart) throw bad('Set the date billing starts.');
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
// The first review is a year after billing starts.
if (!merged.reviewDate && b.reviewDate === undefined) data.reviewDate = require('../utils/billing/dates').addMonths(merged.billingStart, 12);
}
const licence = await prisma.licence.update({ where: { id: existing.id }, data });
await audit(req, 'licence_billing_updated', licence.id, { changed: Object.keys(data), billingCycle: licence.billingCycle });
await audit(req, 'licence_billing_updated', licence.id, { changed: Object.keys(data), billedFrom: ymd(licence.billedFrom) });
res.json({ ok: true });
}));
+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,
};
+136 -64
View File
@@ -4,9 +4,9 @@
* PDFs in pdf.js, emails in email.js.
*
* The job (runBilling, every 15 minutes):
* 1. Drafts: for each billed, active licence whose next period starts within billing_draft_days,
* make the draft invoice and email it to alert_email for approval (the licence moves on to
* the next period at once, so a period is drafted once).
* 1. Drafts: for each billed customer whose next period starts within billing_draft_days, make
* the draft invoice for all its products (Hub 2.0) and email it to alert_email for approval
* (the customer moves on to the next period at once, so a period is drafted once).
* 2. Sends approved invoices on their date, from billing_send_hour (South African time).
* 3. Emails Joshua once when an invoice's date has come and it still isn't approved.
* 4. Applies tier changes on their effective date (the licence's plan).
@@ -21,9 +21,11 @@ const pdf = require('./pdf');
const { layout, sendBillingEmail } = require('./email');
const { ymd, day, today, saHour, addDays, longDate, periodLabel, money } = require('./dates');
const { planPrice, tierNamed } = require('./tiers');
const { BILLABLE } = require('../products');
const { PRODUCT_NAMES } = require('../products');
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
/** The install whose admin contact a customer's documents fall back on (Events first). */
const contactOf = customer => compute.contactInstall((customer.installs || []).map(install => ({ install })));
const hubLink = p => `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}${p}`;
const EDITABLE = ['draft', 'approved'];
@@ -50,17 +52,33 @@ async function invoicePdfFor(invoice, settings) {
// ─── Drafting ────────────────────────────────────────────────────────────────
/** Makes the draft for one licence's next period. Returns the invoice, or null if it already exists. */
async function draftForLicence(licenceId, settings) {
/** The products on a customer invoice, by name ("Cross Events and Church Website"). */
function productsText(invoice) {
const products = invoice.basis?.products || (invoice.licenceId ? ['events'] : []);
const names = products.map(p => PRODUCT_NAMES[p]);
return names.length ? names.join(', ').replace(/, ([^,]*)$/, ' and $1') : 'Cross Code';
}
/**
* Makes the draft for one customer's next period (Hub 2.0: all its products on one invoice).
* Returns the invoice, `{ empty: true }` when nothing was billed (the customer still moves on), or
* null if the period was invoiced already.
*/
async function draftForCustomer(customerId, settings) {
return prisma.$transaction(async (tx) => {
const licence = await tx.licence.findUnique({ where: { id: licenceId }, include: { customer: true, install: true } });
if (!licence || !licence.nextInvoiceDate) return null;
const { invoice, licenceUpdate } = compute.draftInvoice({ licence, customer: licence.customer, install: licence.install, settings });
await tx.licence.update({ where: { id: licence.id }, data: licenceUpdate });
const exists = await tx.invoice.findFirst({ where: { licenceId: licence.id, periodStart: invoice.periodStart } });
// Lock the customer row: two runs never draft the same period.
await tx.$executeRaw`SELECT 1 FROM "Customer" WHERE id = ${customerId} FOR UPDATE`;
const customer = await tx.customer.findUnique({ where: { id: customerId }, include: { licences: { include: { install: true } } } });
if (!customer || customer.billingCycle === 'none' || !customer.nextInvoiceDate) return null;
const { invoice, customerUpdate, licenceUpdates, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings });
await tx.customer.update({ where: { id: customer.id }, data: customerUpdate });
if (empty) return { empty: true };
const exists = await tx.invoice.findFirst({ where: { customerId: customer.id, licenceId: null, periodStart: invoice.periodStart, status: { not: 'void' } } });
if (exists) return null;
for (const u of licenceUpdates) await tx.licence.update({ where: { id: u.id }, data: u.data });
const products = [...new Set(licenceUpdates.map(u => customer.licences.find(l => l.id === u.id)?.product).filter(Boolean))];
const number = await nextNumber(settings.invoice_prefix || 'INV', invoice.issueDate, tx);
return tx.invoice.create({ data: { ...invoice, number, planChange: invoice.planChange ?? undefined }, include: invoiceInclude });
return tx.invoice.create({ data: { ...invoice, basis: { ...invoice.basis, products }, number, planChange: invoice.planChange ?? undefined }, include: invoiceInclude });
});
}
@@ -75,9 +93,9 @@ async function emailApproval(invoice, settings) {
],
rows: [
['Church', invoice.customer.name],
['Tier', `${invoice.plan || '—'}${invoice.founding ? ' (founding)' : ''}`],
['Products', `${invoice.plan || '—'}${invoice.founding ? ' (founding)' : ''}`],
...(invoice.reviewed ? [['12-month event income', invoice.incomeBand || 'not reported']] : []),
...(invoice.planChange ? [['Tier change', `${invoice.planChange.from} → ${invoice.planChange.to}`, true]] : []),
...compute.planChangesOf(invoice).map(pc => [`Tier change (${PRODUCT_NAMES[pc.product] || 'Cross Events'})`, `${pc.from} → ${pc.to}`, true]),
['Total', money(invoice.totalCents), true],
['Goes out', longDate(invoice.issueDate)],
],
@@ -97,20 +115,22 @@ async function emailApproval(invoice, settings) {
async function createDueDrafts(now, settings) {
const days = parseInt(settings.billing_draft_days, 10) || 14;
const horizon = addDays(today(now), days);
const licences = await prisma.licence.findMany({
where: { status: 'active', product: { in: BILLABLE }, billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } },
const customers = await prisma.customer.findMany({
where: { billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } },
select: { id: true },
});
let made = 0;
for (const { id } of licences) {
// Catch up a licence that's behind (at most a year's worth in one run).
for (const { id } of customers) {
// Catch up a customer that's behind (at most a year's worth in one run).
for (let i = 0; i < 12; i++) {
const invoice = await draftForLicence(id, settings);
const invoice = await draftForCustomer(id, settings);
if (!invoice) break;
made += 1;
await emailApproval(invoice, settings).catch(e => console.warn('[billing] approval email failed:', e?.message || e));
const lic = await prisma.licence.findUnique({ where: { id }, select: { nextInvoiceDate: true } });
if (!lic?.nextInvoiceDate || ymd(lic.nextInvoiceDate) > ymd(horizon)) break;
if (!invoice.empty) {
made += 1;
await emailApproval(invoice, settings).catch(e => console.warn('[billing] approval email failed:', e?.message || e));
}
const c = await prisma.customer.findUnique({ where: { id }, select: { nextInvoiceDate: true } });
if (!c?.nextInvoiceDate || ymd(c.nextInvoiceDate) > ymd(horizon)) break;
}
}
return made;
@@ -118,6 +138,18 @@ async function createDueDrafts(now, settings) {
// ─── Sending ─────────────────────────────────────────────────────────────────
/** The email note for an invoice's tier changes, or null. */
function tierChangeNote(invoice) {
const changes = compute.planChangesOf(invoice);
if (!changes.length) return null;
const why = pc => (pc.product === 'app' ? 'your active members over the last 90 days' : 'your event income over the last 12 months');
const one = pc => `${PRODUCT_NAMES[pc.product] || 'Cross Events'} moves from the ${pc.from} tier to the ${pc.to} tier, based on ${why(pc)}.`;
return {
title: changes.length === 1 ? `Your ${PRODUCT_NAMES[changes[0].product] || 'Cross Events'} tier is now ${changes[0].to}` : 'Your tiers have changed',
text: `At your annual review: ${changes.map(one).join(' ')}`,
};
}
async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
const state = compute.invoiceState(invoice, ymd(today()));
const tax = String(settings.vat_registered) === 'true';
@@ -127,7 +159,7 @@ async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
heading: `${title} ${invoice.number}${copy ? ' (copy)' : ''}`,
greeting: `Hi ${invoice.customer.contactName || invoice.customer.name},`,
paragraphs: [
`Here is your ${title.toLowerCase()} for Cross Events${invoice.periodStart ? `, ${periodLabel(invoice.periodStart, invoice.periodEnd)}` : ''}. The PDF is attached.`,
`Here is your ${title.toLowerCase()} for ${productsText(invoice)}${invoice.periodStart ? `, ${periodLabel(invoice.periodStart, invoice.periodEnd)}` : ''}. The PDF is attached.`,
'Please pay by EFT using the invoice number as the reference. The banking details are on the invoice.',
],
rows: [
@@ -137,7 +169,7 @@ async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
[state.paidCents ? 'Balance due' : 'Amount due', money(state.balanceCents), true],
['Due by', longDate(invoice.dueDate), true],
],
note: invoice.planChange ? { title: `Your tier is now ${invoice.planChange.to}`, text: `Your annual review moved your licence from the ${invoice.planChange.from} tier to the ${invoice.planChange.to} tier, based on your event income over the last 12 months.` } : null,
note: tierChangeNote(invoice),
});
return sendBillingEmail(settings, {
kind: 'invoice', customerId: invoice.customerId, refId: invoice.id, to: invoice.recipientEmail,
@@ -202,9 +234,10 @@ async function remindUnapproved(now, settings) {
async function applyDueLicenceChanges(now = new Date()) {
const due = await prisma.licenceChange.findMany({
where: { appliedAt: null, effectiveDate: { lte: today(now) }, licenceId: { not: null }, OR: [{ invoiceId: null }, { invoice: { is: { status: 'sent' } } }] },
include: { licence: { select: { product: true } } },
});
for (const c of due) {
const tier = tierNamed(c.toPlan);
const tier = tierNamed(c.toPlan, c.licence?.product || 'events');
const data = { plan: c.toPlan };
// A custom price comes with a change to an unpriced plan; a priced tier uses its own price.
if (tier?.monthly != null) data.customMonthlyCents = null;
@@ -238,20 +271,20 @@ async function approveInvoice(id, actorId) {
if (!invoice.recipientEmail) throw bad('Add an email address to send it to first.', 409);
if (!invoice.lines?.length) throw bad('Add at least one line first.', 409);
await prisma.invoice.update({ where: { id }, data: { status: 'approved', approvedAt: new Date(), approvedById: actorId || null } });
let notice = null;
if (invoice.planChange && invoice.licenceId) {
const existing = await prisma.licenceChange.findFirst({ where: { invoiceId: id } });
if (!existing) {
const pc = invoice.planChange;
notice = await createLicenceChange({
customerId: invoice.customerId, licenceId: invoice.licenceId, invoiceId: id,
fromPlan: pc.from, toPlan: pc.to, fromMonthlyCents: pc.fromMonthlyCents, toMonthlyCents: pc.toMonthlyCents,
effectiveDate: invoice.periodStart || invoice.issueDate, incomeBand: pc.band || invoice.incomeBand,
reason: 'Your annual tier review.',
}, settings);
}
// One notice per tier change (Hub 2.0: per product), unless it was made already.
const notices = [];
for (const pc of compute.planChangesOf(invoice)) {
if (!pc.licenceId) continue;
const existing = await prisma.licenceChange.findFirst({ where: { invoiceId: id, licenceId: pc.licenceId } });
if (existing) continue;
notices.push(await createLicenceChange({
customerId: invoice.customerId, licenceId: pc.licenceId, invoiceId: id,
fromPlan: pc.from, toPlan: pc.to, fromMonthlyCents: pc.fromMonthlyCents, toMonthlyCents: pc.toMonthlyCents,
effectiveDate: invoice.periodStart || invoice.issueDate, incomeBand: pc.band || (pc.product === 'events' ? invoice.incomeBand : null),
reason: 'Your annual tier review.',
}, settings));
}
return { invoice: await loadInvoice(id), notice };
return { invoice: await loadInvoice(id), notice: notices[0] || null, notices };
}
async function unapproveInvoice(id) {
@@ -281,23 +314,33 @@ async function updateInvoice(id, body) {
if (e && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) throw bad('That email address doesn\'t look right.');
data.recipientEmail = e || null;
}
let reprice = false;
if (body.dropPlanChange === true) {
if (await prisma.licenceChange.findFirst({ where: { invoiceId: id, sentAt: { not: null } } })) throw bad('The church has already been sent the notice of this tier change.', 409);
data.planChange = Prisma.DbNull;
data.plan = invoice.licence?.plan || invoice.plan;
if (invoice.licenceId) data.plan = invoice.licence?.plan || invoice.plan;
else {
// A customer invoice keeps the tiers it had: a draft is repriced at them below.
data.basis = { ...(invoice.basis || {}), planChangeDropped: true };
reprice = invoice.status === 'draft' && body.lines === undefined;
}
}
// Editing an approved invoice keeps it approved; editing clears the "waiting" reminder.
data.overdueEmailedAt = null;
await prisma.invoice.update({ where: { id }, data });
return loadInvoice(id);
return reprice ? recalculateInvoice(id) : loadInvoice(id);
}
/** Rebuilds a draft's lines from the licence as it is now (e.g. after changing founding or the price). */
/**
* Rebuilds a draft's lines from the customer and its licences as they are now (e.g. after changing
* founding, a price or a product's start), for the same period.
*/
async function recalculateInvoice(id) {
const settings = await getSettings();
const invoice = await loadInvoice(id);
if (invoice.status !== 'draft') throw bad('Only a draft can be recalculated.', 409);
if (!invoice.licence || !invoice.periodStart) throw bad('Only an invoice for a licence\'s period can be recalculated.', 409);
if (!invoice.licenceId && invoice.periodStart && invoice.cycle !== 'none') return recalculateCustomerInvoice(invoice, settings);
if (!invoice.licence || !invoice.periodStart) throw bad('Only an invoice for a period can be recalculated.', 409);
const plan = invoice.planChange?.to || invoice.plan || invoice.licence.plan;
const { lines, warning } = compute.planLines({
plan, customMonthlyCents: invoice.licence.customMonthlyCents, cycle: invoice.cycle,
@@ -311,6 +354,32 @@ async function recalculateInvoice(id) {
return loadInvoice(id);
}
/**
* Hub 2.0 customer invoice: the lines worked out again for its period, from each licence's
* billedUntil as it was before the draft (invoice.basis), so days owed are counted once.
*/
async function recalculateCustomerInvoice(invoice, settings) {
const customer = await prisma.customer.findUnique({ where: { id: invoice.customerId }, include: { licences: { include: { install: true } } } });
const before = new Map((invoice.basis?.licences || []).map(l => [l.id, l.billedUntil]));
const licences = customer.licences.map(l => (before.has(l.id) ? { ...l, billedUntil: before.get(l.id) ? day(before.get(l.id)) : null } : l));
const reviewed = invoice.reviewed && !invoice.basis?.planChangeDropped;
const r = compute.customerInvoiceLines({ customer, licences, period: { start: invoice.periodStart, end: invoice.periodEnd, cycle: invoice.cycle }, reviewed });
const recipientEmail = invoice.recipientEmail || compute.recipientFor(customer, compute.contactInstall(customer.licences));
await prisma.$transaction([
prisma.invoice.update({
where: { id: invoice.id },
data: {
lines: r.lines, ...compute.totals(r.lines, settings), founding: !!customer.founding, plan: r.plan, recipientEmail, warnings: r.warnings,
planChange: r.planChanges.length ? r.planChanges : Prisma.DbNull,
basis: { ...(invoice.basis || {}), products: r.products },
},
}),
// A product added or started since the draft was made is now covered up to the period's end.
...r.licenceUpdates.map(u => prisma.licence.update({ where: { id: u.id }, data: u.data })),
]);
return loadInvoice(invoice.id);
}
async function voidInvoice(id, reason) {
const invoice = await loadInvoice(id);
if (invoice.status === 'void') throw bad('It\'s already void.', 409);
@@ -333,7 +402,7 @@ async function resendInvoice(id) {
/** A one-off invoice (e.g. standby support), as a draft. */
async function createManualInvoice(body) {
const settings = await getSettings();
const customer = await prisma.customer.findUnique({ where: { id: String(body.customerId || '') }, include: { installs: { where: { releasedAt: null }, take: 1 } } });
const customer = await prisma.customer.findUnique({ where: { id: String(body.customerId || '') }, include: { installs: { where: { releasedAt: null } } } });
if (!customer) throw bad('Customer not found', 404);
const lines = compute.cleanLines(body.lines || []);
if (!lines.length) throw bad('Add at least one line.');
@@ -345,7 +414,7 @@ async function createManualInvoice(body) {
data: {
number, customerId: customer.id, licenceId: body.licenceId || null, status: 'draft', issueDate, dueDate,
cycle: 'none', lines, ...compute.totals(lines, settings), notes: body.notes || null, founding: customer.founding,
recipientEmail: body.recipientEmail || compute.recipientFor(customer, customer.installs[0]),
recipientEmail: body.recipientEmail || compute.recipientFor(customer, contactOf(customer)),
},
include: invoiceInclude,
});
@@ -354,9 +423,9 @@ async function createManualInvoice(body) {
// ─── Payments and receipts ───────────────────────────────────────────────────
async function sendReceipt(paymentId, settings) {
const payment = await prisma.payment.findUnique({ where: { id: paymentId }, include: { customer: { include: { installs: { where: { releasedAt: null }, take: 1 } } }, invoice: { include: { payments: true } } } });
const payment = await prisma.payment.findUnique({ where: { id: paymentId }, include: { customer: { include: { installs: { where: { releasedAt: null } } } }, invoice: { include: { payments: true } } } });
if (!payment) throw bad('Payment not found', 404);
const to = payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, payment.customer.installs[0]);
const to = payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, contactOf(payment.customer));
const state = payment.invoice ? compute.invoiceState(payment.invoice, ymd(today())) : null;
const content = layout(settings, {
preheader: `We received ${money(payment.amountCents)}. Thank you!`,
@@ -419,16 +488,16 @@ async function resendReceipt(id) {
async function receiptPdfFor(id) {
const settings = await getSettings();
const payment = await prisma.payment.findUnique({ where: { id }, include: { customer: { include: { installs: { where: { releasedAt: null }, take: 1 } } }, invoice: { include: { payments: true } } } });
const payment = await prisma.payment.findUnique({ where: { id }, include: { customer: { include: { installs: { where: { releasedAt: null } } } }, invoice: { include: { payments: true } } } });
if (!payment) throw bad('Payment not found', 404);
const state = payment.invoice ? compute.invoiceState(payment.invoice, ymd(today())) : null;
return { filename: `${payment.receiptNumber}.pdf`, content: await pdf.receiptPdf({ payment, customer: payment.customer, invoice: payment.invoice, state, settings, recipientEmail: payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, payment.customer.installs[0]) }) };
return { filename: `${payment.receiptNumber}.pdf`, content: await pdf.receiptPdf({ payment, customer: payment.customer, invoice: payment.invoice, state, settings, recipientEmail: payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, contactOf(payment.customer)) }) };
}
// ─── Statements ──────────────────────────────────────────────────────────────
async function customerStatement(customerId, from, to) {
const customer = await prisma.customer.findUnique({ where: { id: customerId }, include: { installs: { where: { releasedAt: null }, take: 1 } } });
const customer = await prisma.customer.findUnique({ where: { id: customerId }, include: { installs: { where: { releasedAt: null } } } });
if (!customer) throw bad('Customer not found', 404);
const t = to ? day(to) : today();
const f = from ? day(from) : addDays(t, -365);
@@ -437,7 +506,7 @@ async function customerStatement(customerId, from, to) {
prisma.invoice.findMany({ where: { customerId, status: 'sent' }, include: { payments: true } }),
prisma.payment.findMany({ where: { customerId }, include: { invoice: { select: { number: true } } } }),
]);
return { customer, recipientEmail: compute.recipientFor(customer, customer.installs[0]), statement: compute.statement({ invoices, payments, from: f, to: t }) };
return { customer, recipientEmail: compute.recipientFor(customer, contactOf(customer)), statement: compute.statement({ invoices, payments, from: f, to: t }) };
}
async function statementPdfFor(customerId, from, to) {
@@ -452,7 +521,7 @@ async function emailStatement(customerId, { from, to, email } = {}) {
const sendTo = email || recipientEmail;
const content = layout(settings, {
preheader: `Balance ${money(statement.closingCents)} on ${longDate(statement.to)}`,
heading: 'Your Cross Events statement',
heading: 'Your Cross Code statement',
greeting: `Hi ${customer.contactName || customer.name},`,
paragraphs: [`Here is your statement from ${longDate(statement.from)} to ${longDate(statement.to)}. The PDF is attached.`],
rows: [
@@ -474,30 +543,32 @@ async function emailStatement(customerId, { from, to, email } = {}) {
// ─── Licence changes ─────────────────────────────────────────────────────────
async function sendLicenceChange(change, settings) {
const customer = await prisma.customer.findUnique({ where: { id: change.customerId }, include: { installs: { where: { releasedAt: null }, take: 1 } } });
const customer = await prisma.customer.findUnique({ where: { id: change.customerId }, include: { installs: { where: { releasedAt: null } } } });
const licence = change.licenceId ? await prisma.licence.findUnique({ where: { id: change.licenceId } }) : null;
const to = compute.recipientFor(customer, customer.installs[0]);
const product = licence?.product || 'events';
const name = PRODUCT_NAMES[product];
const to = compute.recipientFor(customer, contactOf(customer));
const up = change.fromMonthlyCents != null && change.toMonthlyCents != null ? change.toMonthlyCents > change.fromMonthlyCents : null;
const content = layout(settings, {
preheader: `From ${longDate(change.effectiveDate)}: the ${change.toPlan} tier`,
heading: up === false ? `Good news: your tier moves down to ${change.toPlan}` : `Your Cross Events tier changes to ${change.toPlan}`,
heading: up === false ? `Good news: your ${name} tier moves down to ${change.toPlan}` : `Your ${name} tier changes to ${change.toPlan}`,
greeting: `Hi ${customer.contactName || customer.name},`,
paragraphs: [
`From ${longDate(change.effectiveDate)}, your Cross Events licence moves from the ${change.fromPlan} tier to the ${change.toPlan} tier. The notice is attached.`,
`From ${longDate(change.effectiveDate)}, your ${name} licence moves from the ${change.fromPlan} tier to the ${change.toPlan} tier. The notice is attached.`,
...(change.reason ? [change.reason] : []),
'Every feature stays included, whatever your tier. If you have any questions, just reply to this email.',
],
rows: [
['Now', `${change.fromPlan}${change.fromMonthlyCents != null ? `, ${money(change.fromMonthlyCents)} a month` : ''}`],
[`From ${longDate(change.effectiveDate)}`, `${change.toPlan}${change.toMonthlyCents != null ? `, ${money(change.toMonthlyCents)} a month` : ''}`, true],
...(change.incomeBand ? [['12-month event income', change.incomeBand]] : []),
...(change.incomeBand ? [[product === 'app' ? 'Active members (90 days)' : '12-month event income', change.incomeBand]] : []),
],
note: customer.founding ? { title: 'Founding church', text: 'Your 35% founding discount carries on in your new tier.' } : null,
});
const res = await sendBillingEmail(settings, {
kind: 'licence_change', customerId: customer.id, refId: change.id, to,
subject: `Notice of licence change: ${change.fromPlan} to ${change.toPlan} from ${longDate(change.effectiveDate)}`,
content, pdfs: [{ filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer, settings, founding: customer.founding, recipientEmail: to, cycle: licence?.billingCycle }) }],
content, pdfs: [{ filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer, settings, founding: customer.founding, recipientEmail: to, cycle: customer.billingCycle, product }) }],
});
if (res.ok) await prisma.licenceChange.update({ where: { id: change.id }, data: { sentAt: new Date() } });
return res;
@@ -509,14 +580,14 @@ async function sendLicenceChange(change, settings) {
*/
async function createLicenceChange(body, settings = null, { send = true } = {}) {
settings = settings || await getSettings();
const licence = await prisma.licence.findUnique({ where: { id: String(body.licenceId || '') } });
const licence = await prisma.licence.findUnique({ where: { id: String(body.licenceId || '') }, include: { customer: true } });
if (!licence) throw bad('Licence not found', 404);
const toPlan = String(body.toPlan || '').trim();
if (!toPlan) throw bad('Choose the new tier.');
const fromPlan = body.fromPlan || licence.plan;
if (toPlan === fromPlan && body.toMonthlyCents == null) throw bad('That\'s the tier it\'s on already.');
const priceOf = (plan, custom) => (custom != null ? Math.round(Number(custom)) : planPrice(plan)?.monthlyCents ?? null);
const effectiveDate = body.effectiveDate ? day(body.effectiveDate) : licence.nextInvoiceDate ? day(licence.nextInvoiceDate) : today();
const priceOf = (plan, custom) => (custom != null ? Math.round(Number(custom)) : planPrice(plan, null, licence.product)?.monthlyCents ?? null);
const effectiveDate = body.effectiveDate ? day(body.effectiveDate) : licence.customer.nextInvoiceDate ? day(licence.customer.nextInvoiceDate) : today();
const number = await nextNumber(settings.change_prefix || 'LC', new Date());
const change = await prisma.licenceChange.create({
data: {
@@ -543,13 +614,14 @@ async function resendLicenceChange(id) {
async function licenceChangePdfFor(id) {
const settings = await getSettings();
const change = await prisma.licenceChange.findUnique({ where: { id }, include: { customer: { include: { installs: { where: { releasedAt: null }, take: 1 } } }, licence: true } });
const change = await prisma.licenceChange.findUnique({ where: { id }, include: { customer: { include: { installs: { where: { releasedAt: null } } } }, licence: true } });
if (change) change.product = change.licence?.product || 'events';
if (!change) throw bad('Notice not found', 404);
return { filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer: change.customer, settings, founding: change.customer.founding, recipientEmail: compute.recipientFor(change.customer, change.customer.installs[0]), cycle: change.licence?.billingCycle }) };
return { filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer: change.customer, settings, founding: change.customer.founding, recipientEmail: compute.recipientFor(change.customer, contactOf(change.customer)), cycle: change.customer.billingCycle, product: change.product }) };
}
module.exports = {
nextNumber, loadInvoice, invoicePdfFor, draftForLicence, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
nextNumber, loadInvoice, invoicePdfFor, draftForCustomer, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
applyDueLicenceChanges, runBilling, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice,
resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement,
statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval,
+22 -9
View File
@@ -9,6 +9,14 @@ const path = require('path');
const PDFDocument = require('pdfkit');
const { longDate, shortDate, money, periodLabel } = require('./dates');
const { planPrice, FOUNDING_PERCENT } = require('./tiers');
const { PRODUCT_NAMES } = require('../products');
/** An invoice's tier changes as a list (Hub 1.7 stored one object). Same as compute.planChangesOf. */
const planChangesOf = invoice => {
const pc = invoice?.planChange;
if (!pc) return [];
return Array.isArray(pc) ? pc : [{ product: 'events', ...pc }];
};
const LOGO = path.join(__dirname, '..', '..', '..', 'assets', 'logo.png');
const C = { navy: '#11111f', sky: '#62b5e5', skyDark: '#1d6a9c', skyPale: '#e8f4fb', text: '#2b3044', muted: '#6b7184', line: '#e1e5ee', surface: '#f5f7fb', green: '#12734a', red: '#b42318' };
@@ -199,11 +207,14 @@ function invoicePdf({ invoice, customer, settings: s, state }) {
...(paid ? [['Total', money(invoice.totalCents)], ['Paid', money(-paid), { color: C.green }]] : []),
[paid ? 'Balance due' : 'Total due', money(paid ? state.balanceCents : invoice.totalCents), { big: true }],
]);
if (invoice.planChange) {
const pc = invoice.planChange;
y = box(doc, y, `Your tier changes to ${pc.to}`, [
`From this period your licence moves from the ${pc.from} tier to the ${pc.to} tier${pc.band ? `, based on your event income over the last 12 months (${pc.band})` : ''}.`,
'Tiers are reviewed once a year. Donations and sponsored places are never counted.',
const changes = planChangesOf(invoice);
if (changes.length) {
const basis = pc => (pc.product === 'app'
? `, based on your active members over the last 90 days (${pc.band})`
: `, based on your event income over the last 12 months (${pc.band})`);
y = box(doc, y, changes.length === 1 ? `Your ${PRODUCT_NAMES[changes[0].product] || 'Cross Events'} tier changes to ${changes[0].to}` : 'Your tiers change', [
...changes.map(pc => `From this period ${PRODUCT_NAMES[pc.product] || 'Cross Events'} moves from the ${pc.from} tier to the ${pc.to} tier${pc.band ? basis(pc) : ''}.`),
`Tiers are reviewed once a year.${changes.some(pc => pc.product !== 'app') ? ' Donations and sponsored places are never counted.' : ''}`,
], { tone: 'sky' });
}
if (invoice.status !== 'void') y = box(doc, y, 'How to pay', paymentLines(s, invoice.number));
@@ -270,13 +281,14 @@ function statementPdf({ statement: st, customer, settings: s, recipientEmail })
}
/** A notice of licence change (tier up or down). */
function licenceChangePdf({ change, customer, settings: s, founding, recipientEmail, cycle }) {
function licenceChangePdf({ change, customer, settings: s, founding, recipientEmail, cycle, product = 'events' }) {
const name = PRODUCT_NAMES[product] || 'Cross Events';
const up = change.fromMonthlyCents != null && change.toMonthlyCents != null ? change.toMonthlyCents > change.fromMonthlyCents : null;
// The monthly price, and for a founding church its founding price (the tier's, or 35% off).
const priceText = (plan, cents) => {
if (cents == null) return 'priced for your church';
if (!founding) return `${money(cents)} a month`;
const p = planPrice(plan);
const p = planPrice(plan, null, product);
const f = p && p.monthlyCents === cents ? p.foundingCents : Math.round((cents * (100 - FOUNDING_PERCENT)) / 100);
return `${money(f)} a month (founding price; normally ${money(cents)})`;
};
@@ -288,7 +300,7 @@ function licenceChangePdf({ change, customer, settings: s, founding, recipientEm
]);
y = party(doc, y, 'Notice to', customer, recipientEmail);
doc.font('Helvetica-Bold').fontSize(14).fillColor(C.navy).text(
up == null ? `Your Cross Events tier changes to ${change.toPlan}` : up ? `Your Cross Events tier moves up to ${change.toPlan}` : `Good news: your Cross Events tier moves down to ${change.toPlan}`, M, y, { width: W });
up == null ? `Your ${name} tier changes to ${change.toPlan}` : up ? `Your ${name} tier moves up to ${change.toPlan}` : `Good news: your ${name} tier moves down to ${change.toPlan}`, M, y, { width: W });
y = doc.y + 10;
y = table(doc, y, [
{ label: '', width: 150 },
@@ -300,7 +312,8 @@ function licenceChangePdf({ change, customer, settings: s, founding, recipientEm
]);
const why = [];
if (change.reason) why.push(change.reason);
if (change.incomeBand) why.push(`Your event income over the last 12 months was in the range ${change.incomeBand}. Tiers are based on ticket sales and other payments through Cross Events, less refunds; donations and sponsored places are never counted.`);
if (change.incomeBand && product === 'app') why.push(`Your church had ${change.incomeBand} active members over the last 90 days (people who used the app; visitors who don't sign in never count).`);
else if (change.incomeBand) why.push(`Your event income over the last 12 months was in the range ${change.incomeBand}. Tiers are based on ticket sales and other payments through Cross Events, less refunds; donations and sponsored places are never counted.`);
why.push('We review tiers once a year when your licence renews, never in the middle of the year.');
if (founding) why.push('As a founding church, your 35% founding discount carries on in your new tier.');
if (cycle === 'yearly') why.push('You pay yearly, so you still get two months free on the new price.');
+72 -11
View File
@@ -1,8 +1,17 @@
/**
* Cross Events licence tiers, billed on a site's event income over the last 12 months
* (`income.eventIncome12m`, Cross Events 2.0.2+). The same tiers are in
* frontend/src/lib/tiers.ts (a test checks they match) and the public prices in crosscode-site
* src/data/pricing.mjs. Prices are rand per month.
* Prices per product (Hub 2.0, ROADMAP-v3 §10), rand per month. The same prices are in
* frontend/src/lib/tiers.ts (a test checks they match) and the public ones in crosscode-site
* src/data/pricing.mjs.
*
* - Cross Events: tiers on a site's event income over the last 12 months (`income.eventIncome12m`,
* Cross Events 2.0.2+).
* - Church Website: one price, 5 GB of uploads included; extra storage is an add-on.
* - Church App: tiers on active members in the last 90 days (`activeMembers90d`, a band).
* - Accounts: free, never invoiced.
*
* The same rules for every product: yearly billing is 10 months' price, founding churches pay the
* founding price, bundles take 15% off two products and 25% off three, and add-ons are never
* discounted (compute.js).
*/
const TIERS = [
@@ -16,12 +25,34 @@ const TIERS = [
{ name: 'Network', upTo: null, monthly: null, founding: null }, // priced per church, from R7 500
];
/** Yearly billing: this many months' price for 12 months (two months free). */
/** Church Website: one plan. */
const WEBSITE_PLANS = [{ name: 'Website', monthly: 99, founding: 64 }];
/** Church App tiers, one per active-member band (contracts ACTIVE_MEMBER_BANDS, in order). */
const APP_TIERS = [
{ name: 'Mustard Seed', band: '0–100', monthly: 99, founding: 64 },
{ name: 'Small Group', band: '101–300', monthly: 249, founding: 162 },
{ name: 'Congregation', band: '301–750', monthly: 399, founding: 259 },
{ name: 'Gathering', band: '751–2 000', monthly: 649, founding: 422 },
{ name: 'Multitude', band: '2 001–5 000', monthly: 999, founding: 649 },
{ name: 'Network', band: 'over 5 000', monthly: null, founding: null }, // from R1 500, priced per church
];
/** Extra website storage: R20 a month per 5 GB above the 5 GB included. */
const STORAGE = { includedBytes: 5 * 1024 ** 3, stepBytes: 5 * 1024 ** 3, monthly: 20 };
/** Bundles: % off the products (not the add-ons) by how many are billed. Accounts doesn't count. */
const BUNDLE_PERCENT = { 2: 15, 3: 25 };
/** Yearly billing: this many months' price for 12 months (two months free). Products only. */
const YEARLY_MONTHS = 10;
/** Founding churches: this much off a price that has no published founding price. */
const FOUNDING_PERCENT = 35;
const tierNamed = name => TIERS.find(t => t.name.toLowerCase() === String(name || '').toLowerCase()) || null;
const PLANS = { events: TIERS, website: WEBSITE_PLANS, app: APP_TIERS, accounts: [] };
const tierNamed = (name, product = 'events') =>
(PLANS[product] || []).find(t => t.name.toLowerCase() === String(name || '').toLowerCase()) || null;
/** The highest rand amount in a band label ("R100 001–R150 000" → 150000; "over R10 000 000" → Infinity). */
function bandTop(band) {
@@ -32,7 +63,7 @@ function bandTop(band) {
return Number.isFinite(n) ? n : null;
}
/** The tier a band falls in, or null (no band, or an old install's "over R100 000"). */
/** The Cross Events tier an income band falls in, or null (no band, or an old install's "over R100 000"). */
function tierForBand(band) {
if (!band || band === 'over R100 000') return null;
const top = bandTop(band);
@@ -40,12 +71,31 @@ function tierForBand(band) {
return TIERS.find(t => t.upTo == null || top <= t.upTo) || null;
}
/** The Church App tier for an active-member band, or null. */
const appTierForBand = band => APP_TIERS.find(t => t.band === band) || null;
/**
* The monthly price of a plan in cents, normal and founding: { monthlyCents, foundingCents },
* The tier a product's install should be on from what it reports: { tier, band }. `tier` is
* undefined for a product without tiers (Website), null when it can't tell (no band reported).
*/
function reviewTier(product, install) {
if (product === 'events') {
const band = install?.stats?.income?.eventIncome12m || null;
return { tier: tierForBand(band), band };
}
if (product === 'app') {
const band = install?.stats?.activeMembers90d || null;
return { tier: appTierForBand(band), band };
}
return { tier: undefined, band: null };
}
/**
* The monthly price of a plan in cents, normal and founding: { monthlyCents, foundingCents, custom },
* or null when the plan has no price (Network, Trial, an old "standard") and no custom price.
*/
function planPrice(plan, customMonthlyCents = null) {
const tier = tierNamed(plan);
function planPrice(plan, customMonthlyCents = null, product = 'events') {
const tier = tierNamed(plan, product);
if (customMonthlyCents != null && customMonthlyCents >= 0) {
return { monthlyCents: customMonthlyCents, foundingCents: Math.round((customMonthlyCents * (100 - FOUNDING_PERCENT)) / 100), custom: true };
}
@@ -53,4 +103,15 @@ function planPrice(plan, customMonthlyCents = null) {
return { monthlyCents: tier.monthly * 100, foundingCents: tier.founding * 100, custom: false };
}
module.exports = { TIERS, YEARLY_MONTHS, FOUNDING_PERCENT, tierNamed, tierForBand, planPrice };
/** How many extra 5 GB blocks a website uses (from its heartbeat's `storage`). */
function extraStorageBlocks(storage) {
const used = Number(storage?.usedBytes);
if (!Number.isFinite(used) || used <= 0) return 0;
const included = Number(storage?.includedBytes) > 0 ? Number(storage.includedBytes) : STORAGE.includedBytes;
return Math.max(0, Math.ceil((used - included) / STORAGE.stepBytes));
}
module.exports = {
TIERS, WEBSITE_PLANS, APP_TIERS, PLANS, STORAGE, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
tierNamed, tierForBand, appTierForBand, reviewTier, planPrice, extraStorageBlocks,
};
+7 -2
View File
@@ -4,7 +4,8 @@
*/
const { licenceKey } = require('./crypto');
const { PRODUCT_NAMES, isProduct } = require('./products');
const { PRODUCT_NAMES, BILLABLE, isProduct } = require('./products');
const { today, addMonths } = require('./billing/dates');
const conflict = (message, code) => Object.assign(new Error(message), { status: 409, code });
@@ -57,7 +58,11 @@ async function ensureAccountsLicence(db, customerId) {
* Generate a licence for a customer, plus its Accounts licence when this is a product other than
* Accounts and it has none yet. Returns { licence, accounts } (accounts: the licence if created now).
*/
async function generateLicence(db, { customerId, product = 'events', data = {} }) {
async function generateLicence(db, { customerId, product = 'events', data = {}, now = new Date() }) {
// Hub 2.0, decision 3: a product added to a customer that's already billed gets its free month,
// then joins the customer's invoices (the days before its first full period prorated).
const customer = BILLABLE.includes(product) && data.billedFrom === undefined ? await db.customer?.findUnique({ where: { id: customerId } }) : null;
if (customer && customer.billingCycle && customer.billingCycle !== 'none') data = { ...data, billedFrom: addMonths(today(now), 1) };
const licence = await createLicence(db, { customerId, product, data });
if (product === 'accounts') return { licence, accounts: null };
const { licence: accounts, created } = await ensureAccountsLicence(db, customerId);
+2 -5
View File
@@ -31,10 +31,7 @@ function productOfKey(key) {
const isProduct = p => PRODUCTS.includes(p);
/**
* Products that can be invoiced. Until billing per customer (Hub 2.0 step 4) only Events has
* prices; Accounts is never invoiced.
*/
const BILLABLE = ['events'];
/** Products that are invoiced (Accounts is free and never invoiced). */
const BILLABLE = ['events', 'website', 'app'];
module.exports = { PRODUCTS, PRODUCT_NAMES, KEY_PREFIXES, BILLABLE, productOfKey, isProduct };