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:
2026-11-03 13:42:45 +02:00
co-authored by Claude Opus 5.5
parent cc7d62690b
commit 6fce0fe90e
33 changed files with 3579 additions and 53 deletions
+1
View File
@@ -15,6 +15,7 @@ app.use(express.json({ limit: '300kb', verify: (req, res, buf) => { req.rawBody
app.get('/api/health', (req, res) => res.json({ ok: true }));
app.use('/api', require('./routes/installApi'));
app.use('/api/auth', require('./routes/auth'));
app.use('/api/admin/billing', require('./routes/billing'));
app.use('/api/admin', require('./routes/admin'));
app.use((req, res) => res.status(404).json({ message: 'Not found', code: 'NOT_FOUND' }));
+4 -1
View File
@@ -12,6 +12,7 @@ const { keyPair } = require('./utils/licenceToken');
const { runAlerts, rollupHeartbeats } = require('./utils/alerts');
const { importSmtpFromEnv } = require('./utils/settings');
const { syncReleases } = require('./utils/releaseSync');
const { runBilling } = require('./utils/billing');
// Fail early if the licence signing key is missing or wrong.
try {
@@ -29,13 +30,15 @@ importSmtpFromEnv()
const PORT = parseInt(process.env.PORT || '5200', 10);
app.listen(PORT, () => console.log(`[hub] Listening on ${PORT}`));
// Background checks: alerts every 5 minutes, releases from git every 15, heartbeat roll-up once a day. The Hub runs as a
// Background checks: alerts every 5 minutes, releases from git and billing every 15, heartbeat roll-up once a day. The Hub runs as a
// single process, so plain timers are enough.
if (String(process.env.JOBS_ENABLED || 'true').toLowerCase() !== 'false') {
const every = (ms, name, fn) => setInterval(() => fn().catch(e => console.warn(`[hub] ${name} failed:`, e?.message || e)), ms);
every(5 * 60 * 1000, 'alerts', () => runAlerts());
every(15 * 60 * 1000, 'release sync', () => syncReleases());
every(24 * 60 * 60 * 1000, 'heartbeat roll-up', () => rollupHeartbeats());
every(15 * 60 * 1000, 'billing', () => runBilling());
setTimeout(() => runBilling().catch(e => console.warn('[hub] billing failed:', e?.message || e)), 60 * 1000);
setTimeout(() => runAlerts().catch(() => {}), 30 * 1000);
setTimeout(() => syncReleases().catch(e => console.warn('[hub] release sync failed:', e?.message || e)), 20 * 1000);
}
+309
View File
@@ -0,0 +1,309 @@
/**
* 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/.
*/
const express = require('express');
const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { protect } = require('../middleware/auth');
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 router = express.Router();
router.use(protect);
// Emails to churches: generous for normal use, a brake on a runaway script.
const emailLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 60, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many emails — wait a few minutes.' } });
const wrap = fn => (req, res) => fn(req, res).catch(e => {
const status = e.status || 500;
if (status >= 500) console.error('[billing]', e);
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message });
});
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
const text = (v, max = 500) => (v == null || String(v).trim() === '' ? null : String(v).trim().slice(0, max));
const dayOrNull = v => (v == null || v === '' ? null : day(v));
const sendPdf = (res, { filename, content }) => {
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `inline; filename="${filename.replace(/[^\w .()-]/g, '_')}"`);
res.send(content);
};
/** An invoice for lists and the invoice page, with where it stands. */
function invoiceRow(invoice, todayYmd = ymd(today())) {
const { licence, ...rest } = invoice;
return {
...rest,
issueDate: ymd(invoice.issueDate), dueDate: ymd(invoice.dueDate),
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,
...compute.invoiceState(invoice, todayYmd),
};
}
const PAYMENT_STATES = ['unpaid', 'part_paid', 'overdue', 'paid'];
// ─── Overview ─────────────────────────────────────────────────────────────────
router.get('/overview', wrap(async (req, res) => {
const t = ymd(today());
const [invoices, payments] = await Promise.all([
prisma.invoice.findMany({ where: { status: { not: 'void' } }, include: { customer: true, payments: true } }),
prisma.payment.findMany({ where: { paidOn: { gte: day(`${t.slice(0, 7)}-01`) } } }),
]);
const rows = invoices.map(i => invoiceRow(i, t));
const sum = list => list.reduce((s, i) => s + i.balanceCents, 0);
res.json({
drafts: rows.filter(i => i.state === 'draft').length,
approved: rows.filter(i => i.state === 'approved').length,
owingCents: sum(rows.filter(i => i.status === 'sent' && i.balanceCents > 0)),
overdueCents: sum(rows.filter(i => i.state === 'overdue')),
overdue: rows.filter(i => i.state === 'overdue').length,
receivedThisMonthCents: payments.reduce((s, p) => s + p.amountCents, 0),
tiers: TIERS,
});
}));
router.post('/run', wrap(async (req, res) => {
const out = await billing.runBilling();
await audit(req, 'billing_run', null, out);
res.json(out);
}));
// ─── Invoices ─────────────────────────────────────────────────────────────────
router.get('/invoices', wrap(async (req, res) => {
const { status, customerId } = req.query;
const where = {};
if (customerId) where.customerId = String(customerId);
if (['draft', 'approved', 'sent', 'void'].includes(status)) where.status = status;
else if (PAYMENT_STATES.includes(status)) where.status = 'sent';
const invoices = await prisma.invoice.findMany({ where, include: { customer: true, payments: true, licence: { include: { install: true } } }, orderBy: [{ issueDate: 'desc' }, { number: 'desc' }], take: 500 });
let rows = invoices.map(i => invoiceRow(i));
if (PAYMENT_STATES.includes(status)) rows = rows.filter(i => (status === 'unpaid' ? ['unpaid', 'part_paid', 'overdue'].includes(i.state) : i.state === status));
res.json(rows);
}));
router.post('/invoices', wrap(async (req, res) => {
const invoice = await billing.createManualInvoice(req.body || {});
await audit(req, 'invoice_created', invoice.id, { number: invoice.number });
res.status(201).json(invoiceRow(invoice));
}));
router.get('/invoices/:id', wrap(async (req, res) => {
const invoice = await billing.loadInvoice(req.params.id);
const [changes, emails] = await Promise.all([
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 });
}));
router.put('/invoices/:id', wrap(async (req, res) => {
const invoice = await billing.updateInvoice(req.params.id, req.body || {});
await audit(req, 'invoice_updated', invoice.id, { number: invoice.number, changed: Object.keys(req.body || {}) });
res.json(invoiceRow(invoice));
}));
for (const [action, fn, auditName] of [
['approve', (req) => billing.approveInvoice(req.params.id, req.admin?.id).then(r => ({ invoice: r.invoice, notice: r.notice })), 'invoice_approved'],
['unapprove', (req) => billing.unapproveInvoice(req.params.id).then(invoice => ({ invoice })), 'invoice_unapproved'],
['recalculate', (req) => billing.recalculateInvoice(req.params.id).then(invoice => ({ invoice })), 'invoice_recalculated'],
['void', (req) => billing.voidInvoice(req.params.id, req.body?.reason).then(invoice => ({ invoice })), 'invoice_voided'],
]) {
router.post(`/invoices/:id/${action}`, wrap(async (req, res) => {
const out = await fn(req);
await audit(req, auditName, req.params.id, { number: out.invoice.number });
res.json({ invoice: invoiceRow(out.invoice), notice: out.notice || null });
}));
}
router.post('/invoices/:id/send', emailLimiter, wrap(async (req, res) => {
const { getSettings } = require('../utils/settings');
const invoice = await billing.sendInvoice(req.params.id, await getSettings());
await audit(req, 'invoice_sent', invoice.id, { number: invoice.number, to: invoice.recipientEmail });
res.json({ invoice: invoiceRow(invoice) });
}));
router.post('/invoices/:id/resend', emailLimiter, wrap(async (req, res) => {
const invoice = await billing.resendInvoice(req.params.id);
await audit(req, 'invoice_resent', invoice.id, { number: invoice.number, to: invoice.recipientEmail });
res.json({ message: `Sent again to ${invoice.recipientEmail}.` });
}));
router.get('/invoices/:id/pdf', wrap(async (req, res) => {
const { getSettings } = require('../utils/settings');
const invoice = await billing.loadInvoice(req.params.id);
sendPdf(res, { filename: `${invoice.number}${invoice.status === 'draft' || invoice.status === 'approved' ? ' (draft)' : ''}.pdf`, content: await billing.invoicePdfFor(invoice, await getSettings()) });
}));
// ─── Payments ─────────────────────────────────────────────────────────────────
router.get('/payments', wrap(async (req, res) => {
const where = req.query.customerId ? { customerId: String(req.query.customerId) } : {};
const payments = await prisma.payment.findMany({ where, include: { customer: { select: { id: true, name: true } }, invoice: { select: { id: true, number: true } } }, orderBy: [{ paidOn: 'desc' }, { createdAt: 'desc' }], take: 500 });
res.json(payments.map(p => ({ ...p, paidOn: ymd(p.paidOn) })));
}));
router.post('/payments', emailLimiter, wrap(async (req, res) => {
const { payment, receipt } = await billing.recordPayment(req.body || {}, req.admin?.id);
await audit(req, 'payment_recorded', payment.id, { receipt: payment.receiptNumber, amountCents: payment.amountCents, invoice: payment.invoice?.number || null });
res.status(201).json({ payment: { ...payment, paidOn: ymd(payment.paidOn) }, receipt });
}));
router.delete('/payments/:id', wrap(async (req, res) => {
const payment = await billing.deletePayment(req.params.id);
await audit(req, 'payment_deleted', payment.id, { receipt: payment.receiptNumber, amountCents: payment.amountCents });
res.json({ message: `Payment ${payment.receiptNumber} removed.` });
}));
router.post('/payments/:id/resend', emailLimiter, wrap(async (req, res) => {
await billing.resendReceipt(req.params.id);
await audit(req, 'receipt_resent', req.params.id);
res.json({ message: 'Receipt sent again.' });
}));
router.get('/payments/:id/pdf', wrap(async (req, res) => sendPdf(res, await billing.receiptPdfFor(req.params.id))));
// ─── Customers: founding, billing details, statements ─────────────────────────
/** Every customer's billing at a glance: founding, licences' plans and next invoice, balance. */
router.get('/customers', wrap(async (req, res) => {
const t = ymd(today());
const customers = await prisma.customer.findMany({
orderBy: { name: 'asc' },
include: { licences: { include: { install: { select: { url: true } } } }, invoices: { where: { status: 'sent' }, include: { payments: true } } },
});
res.json(customers.map(c => {
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,
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 })),
};
}));
}));
router.get('/customers/:id', wrap(async (req, res) => {
const t = ymd(today());
const customer = await prisma.customer.findUnique({
where: { id: req.params.id },
include: {
licences: { include: { install: true }, orderBy: { createdAt: 'desc' } },
invoices: { include: { payments: true }, orderBy: [{ issueDate: 'desc' }, { number: 'desc' }] },
payments: { include: { invoice: { select: { id: true, number: true } } }, orderBy: [{ paidOn: 'desc' }, { createdAt: 'desc' }] },
licenceChanges: { orderBy: { createdAt: 'desc' } },
billingEmails: { orderBy: { sentAt: 'desc' }, take: 50 },
},
});
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),
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,
})),
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,
});
}));
router.put('/customers/:id', wrap(async (req, res) => {
const b = req.body || {};
const data = {};
if (b.founding !== undefined) {
data.founding = b.founding === true;
if (data.founding && b.foundingSince === undefined) data.foundingSince = today();
}
if (b.foundingSince !== undefined) data.foundingSince = dayOrNull(b.foundingSince);
if (b.foundingNote !== undefined) data.foundingNote = text(b.foundingNote, 500);
if (b.billingAddress !== undefined) data.billingAddress = text(b.billingAddress, 500);
if (b.billingEmail !== undefined) {
const e = text(b.billingEmail, 200);
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 });
res.json({ ok: true });
}));
router.get('/customers/:id/statement', wrap(async (req, res) => {
const { statement, recipientEmail } = await billing.customerStatement(req.params.id, req.query.from, req.query.to);
res.json({ ...statement, recipientEmail });
}));
router.get('/customers/:id/statement.pdf', wrap(async (req, res) => sendPdf(res, await billing.statementPdfFor(req.params.id, req.query.from, req.query.to))));
router.post('/customers/:id/statement/email', emailLimiter, wrap(async (req, res) => {
const out = await billing.emailStatement(req.params.id, req.body || {});
await audit(req, 'statement_sent', req.params.id, { to: out.to, from: out.statement.from, until: out.statement.to });
res.json({ message: `Statement sent to ${out.to}.` });
}));
// ─── Licence billing set-up ───────────────────────────────────────────────────
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;
}
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 {
const n = Math.round(Number(b.customMonthlyCents));
if (!Number.isInteger(n) || n < 0 || n > 1e8) throw bad('Enter a monthly price.');
data.customMonthlyCents = n;
}
}
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 = 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 });
res.json({ ok: true });
}));
// ─── Licence changes ──────────────────────────────────────────────────────────
router.post('/licence-changes', emailLimiter, wrap(async (req, res) => {
const { change, email } = await billing.createLicenceChange(req.body || {}, null, { send: req.body?.send !== false });
await audit(req, 'licence_change_created', change.id, { number: change.number, from: change.fromPlan, to: change.toPlan, effective: ymd(change.effectiveDate) });
res.status(201).json({ change: { ...change, effectiveDate: ymd(change.effectiveDate) }, email });
}));
router.post('/licence-changes/:id/resend', emailLimiter, wrap(async (req, res) => {
await billing.resendLicenceChange(req.params.id);
await audit(req, 'licence_change_resent', req.params.id);
res.json({ message: 'Notice sent again.' });
}));
router.get('/licence-changes/:id/pdf', wrap(async (req, res) => sendPdf(res, await billing.licenceChangePdfFor(req.params.id))));
module.exports = router;
+190
View File
@@ -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 };
+79
View File
@@ -0,0 +1,79 @@
/**
* Calendar dates and money for billing. Date-only columns (@db.Date) come back as JavaScript
* Dates at UTC midnight, so dates here are UTC-midnight Dates and 'YYYY-MM-DD' strings. "Today"
* is today in South Africa.
*/
const TZ = 'Africa/Johannesburg';
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/** 'YYYY-MM-DD' of a date-only value (a UTC-midnight Date or a string). */
function ymd(d) {
if (!d) return null;
if (typeof d === 'string') return d.slice(0, 10);
return d.toISOString().slice(0, 10);
}
/** A date-only value as a UTC-midnight Date. Throws on nonsense. */
function day(v) {
const s = ymd(v instanceof Date ? v : String(v || ''));
if (!s || !/^\d{4}-\d{2}-\d{2}$/.test(s)) throw Object.assign(new Error('Not a valid date.'), { status: 400 });
const d = new Date(`${s}T00:00:00Z`);
if (Number.isNaN(d.getTime()) || ymd(d) !== s) throw Object.assign(new Error('Not a valid date.'), { status: 400 });
return d;
}
/** Today's date in South Africa, as a UTC-midnight Date. */
function today(now = new Date()) {
return day(new Intl.DateTimeFormat('en-CA', { timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit' }).format(now));
}
/** The hour (0–23) in South Africa. */
function saHour(now = new Date()) {
return Number(new Intl.DateTimeFormat('en-GB', { timeZone: TZ, hour: '2-digit', hourCycle: 'h23' }).format(now));
}
const addDays = (d, n) => new Date(day(d).getTime() + n * 864e5);
/**
* `n` months after `d`, on `anchorDay` (the billing day) or the month's last day when the month
* is shorter: 31 Jan + 1 month on day 31 → 28/29 Feb; then + 1 → 31 Mar.
*/
function addMonths(d, n, anchorDay = day(d).getUTCDate()) {
const base = day(d);
const y = base.getUTCFullYear();
const m = base.getUTCMonth() + n;
const last = new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
return new Date(Date.UTC(y, m, Math.min(anchorDay, last)));
}
/** "1 December 2026". */
function longDate(d) {
if (!d) return '';
const x = day(d);
return `${x.getUTCDate()} ${MONTHS[x.getUTCMonth()]} ${x.getUTCFullYear()}`;
}
/** "15 Dec 2026". */
function shortDate(d) {
if (!d) return '';
const x = day(d);
return `${x.getUTCDate()} ${MONTHS[x.getUTCMonth()].slice(0, 3)} ${x.getUTCFullYear()}`;
}
/** "December 2026" (a monthly period), or "1 December 2026 – 30 November 2027". */
function periodLabel(start, end) {
const s = day(start);
const e = day(end);
const wholeMonth = s.getUTCDate() === 1 && ymd(addDays(e, 1)) === ymd(addMonths(s, 1, 1));
return wholeMonth ? `${MONTHS[s.getUTCMonth()]} ${s.getUTCFullYear()}` : `${longDate(s)} – ${longDate(e)}`;
}
/** R1 350.00 (cents in, South African style with a space between thousands). */
function money(cents) {
const neg = cents < 0;
const [r, c] = (Math.abs(Math.round(cents)) / 100).toFixed(2).split('.');
return `${neg ? '-' : ''}R${r.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')}.${c}`;
}
module.exports = { TZ, ymd, day, today, saHour, addDays, addMonths, longDate, shortDate, periodLabel, money };
+99
View File
@@ -0,0 +1,99 @@
/**
* Billing emails: one styled layout (HTML with a plain-text twin) and a sender that records every
* email in BillingEmail. The logo is embedded (cid:logo); the documents go as PDF attachments.
*/
const fs = require('fs');
const path = require('path');
const prisma = require('../../config/db');
const { sendMail } = require('../mail');
const LOGO = path.join(__dirname, '..', '..', '..', 'assets', 'logo.png');
let logoBytes = null;
const logo = () => {
if (logoBytes === null) {
try { logoBytes = fs.readFileSync(LOGO); } catch { logoBytes = false; }
}
return logoBytes || null;
};
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
const FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif";
/**
* The email. `paragraphs` are plain text (escaped); `rows` a summary table [[label, value, bold?]];
* `note` a highlighted box { title, text }; `button` { label, url }.
*/
function layout(settings, { preheader = '', heading, greeting, paragraphs = [], rows = [], note, button, signoff = true }) {
const s = settings || {};
const business = s.business_name || 'Cross Code';
const footer = [business, s.business_website, s.business_email, s.business_phone].filter(Boolean).map(esc).join(' &nbsp;·&nbsp; ');
const p = t => `<p style="margin:0 0 14px 0;font-family:${FONT};font-size:15px;line-height:1.6;color:#2b3044">${esc(t)}</p>`;
const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(heading)}</title></head>
<body style="margin:0;padding:0;background:#f5f7fb">
<div style="display:none;max-height:0;overflow:hidden;opacity:0">${esc(preheader)}</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f5f7fb;padding:24px 12px"><tr><td align="center">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px;background:#ffffff;border-radius:14px;overflow:hidden;border:1px solid #e1e5ee">
<tr><td style="background:#11111f;padding:22px 28px">
<table role="presentation" cellpadding="0" cellspacing="0"><tr>
${logo() ? '<td style="padding-right:12px"><img src="cid:logo" width="40" height="40" alt="" style="display:block;border:0"></td>' : ''}
<td style="font-family:${FONT};font-size:15px;letter-spacing:4px;text-transform:uppercase;color:#ffffff"><span style="color:#62b5e5">${esc(business.split(' ')[0])}</span> ${esc(business.split(' ').slice(1).join(' '))}</td>
</tr></table>
</td></tr>
<tr><td style="height:4px;background:#62b5e5;line-height:4px;font-size:0">&nbsp;</td></tr>
<tr><td style="padding:30px 28px 10px 28px">
<h1 style="margin:0 0 18px 0;font-family:${FONT};font-size:22px;line-height:1.3;color:#11111f">${esc(heading)}</h1>
${greeting ? p(greeting) : ''}
${paragraphs.map(p).join('')}
${rows.length ? `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:6px 0 20px 0;background:#f5f7fb;border-radius:10px">
${rows.map(([k, v, bold], i) => `<tr><td style="padding:${i ? 8 : 14}px 16px ${i === rows.length - 1 ? 14 : 8}px 16px;font-family:${FONT};font-size:14px;color:#6b7184">${esc(k)}</td><td align="right" style="padding:${i ? 8 : 14}px 16px ${i === rows.length - 1 ? 14 : 8}px 16px;font-family:${FONT};font-size:14px;color:#11111f;${bold ? 'font-weight:700' : ''}">${esc(v)}</td></tr>`).join('')}
</table>` : ''}
${note ? `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 20px 0;background:#e8f4fb;border-left:4px solid #62b5e5;border-radius:6px"><tr><td style="padding:14px 16px;font-family:${FONT};font-size:14px;line-height:1.55;color:#2b3044">${note.title ? `<strong style="color:#11111f">${esc(note.title)}</strong><br>` : ''}${esc(note.text).replace(/\n/g, '<br>')}</td></tr></table>` : ''}
${button ? `<table role="presentation" cellpadding="0" cellspacing="0" style="margin:4px 0 22px 0"><tr><td style="border-radius:8px;background:#1d6a9c"><a href="${esc(button.url)}" style="display:inline-block;padding:12px 22px;font-family:${FONT};font-size:15px;font-weight:600;color:#ffffff;text-decoration:none;border-radius:8px">${esc(button.label)}</a></td></tr></table>` : ''}
${signoff ? p(`Kind regards,\n${s.business_owner || ''}${s.business_owner ? ', ' : ''}${business}`).replace('\n', '<br>') : ''}
</td></tr>
<tr><td style="padding:18px 28px 24px 28px;border-top:1px solid #e1e5ee;font-family:${FONT};font-size:12px;line-height:1.5;color:#6b7184">${footer}</td></tr>
</table>
</td></tr></table>
</body></html>`;
const text = [
heading,
'',
greeting,
...paragraphs,
rows.length ? rows.map(([k, v]) => `${k}: ${v}`).join('\n') : null,
note ? `${note.title ? `${note.title}\n` : ''}${note.text}` : null,
button ? `${button.label}: ${button.url}` : null,
signoff ? `Kind regards,\n${s.business_owner ? `${s.business_owner}, ` : ''}${business}` : null,
'',
[business, s.business_website, s.business_email, s.business_phone].filter(Boolean).join(' · '),
].filter(x => x != null).join('\n\n').replace(/\n{3,}/g, '\n\n');
return { html, text };
}
/**
* Sends a billing email and records it. Returns { ok, error }; never throws for a mail failure
* (the caller decides what to do).
*/
async function sendBillingEmail(settings, { kind, customerId = null, refId = null, to, subject, content, pdfs = [] }) {
const attachments = [
...(logo() ? [{ filename: 'logo.png', content: logo(), contentType: 'image/png', cid: 'logo' }] : []),
...pdfs.map(f => ({ filename: f.filename, content: f.content, contentType: 'application/pdf' })),
];
let error = null;
try {
if (!to) throw new Error('No email address.');
await sendMail({
to, subject, text: content.text, html: content.html, attachments,
replyTo: settings.billing_reply_to || settings.business_email || undefined,
fromName: settings.business_name || 'Cross Code',
});
} catch (e) {
error = e?.message || String(e);
}
await prisma.billingEmail.create({ data: { kind, customerId, refId, to: to || '(none)', subject, error } }).catch(e => console.warn('[billing] could not log email:', e?.message || e));
return { ok: !error, error };
}
module.exports = { layout, sendBillingEmail, esc };
+555
View File
@@ -0,0 +1,555 @@
/**
* Billing (1.7.0): invoices drafted automatically, approved by Joshua, sent on their date;
* payments with receipts; statements; notices of licence change. Calculations are in compute.js,
* 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).
* 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).
*/
const { Prisma } = require('@prisma/client');
const prisma = require('../../config/db');
const { getSettings } = require('../settings');
const { sendMail } = require('../mail');
const compute = require('./compute');
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 bad = (message, status = 400) => Object.assign(new Error(message), { status });
const hubLink = p => `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}${p}`;
const EDITABLE = ['draft', 'approved'];
/** The next number for a prefix in a year: INV-2026-0001. Atomic (one row per prefix and year). */
async function nextNumber(prefix, date = new Date(), db = prisma) {
const year = ymd(date).slice(0, 4);
const key = `${prefix}-${year}`;
const row = await db.documentCounter.upsert({ where: { key }, create: { key, value: 1 }, update: { value: { increment: 1 } } });
return `${key}-${String(row.value).padStart(4, '0')}`;
}
const invoiceInclude = { customer: true, payments: { orderBy: { paidOn: 'asc' } }, licence: { include: { install: true } } };
async function loadInvoice(id) {
const invoice = await prisma.invoice.findUnique({ where: { id }, include: invoiceInclude });
if (!invoice) throw bad('Invoice not found', 404);
return invoice;
}
async function invoicePdfFor(invoice, settings) {
const state = compute.invoiceState(invoice, ymd(today()));
return pdf.invoicePdf({ invoice, customer: invoice.customer, settings, state });
}
// ─── Drafting ────────────────────────────────────────────────────────────────
/** Makes the draft for one licence's next period. Returns the invoice, or null if it already exists. */
async function draftForLicence(licenceId, 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 } });
if (exists) return null;
const number = await nextNumber(settings.invoice_prefix || 'INV', invoice.issueDate, tx);
return tx.invoice.create({ data: { ...invoice, number, planChange: invoice.planChange ?? undefined }, include: invoiceInclude });
});
}
async function emailApproval(invoice, settings) {
const to = settings.alert_email;
if (!to) return;
const content = layout(settings, {
preheader: `${invoice.customer.name}: ${money(invoice.totalCents)}, goes out ${longDate(invoice.issueDate)}`,
heading: `Invoice ${invoice.number} is ready for approval`,
paragraphs: [
`The draft for ${invoice.customer.name}${invoice.periodStart ? ` (${periodLabel(invoice.periodStart, invoice.periodEnd)})` : ''} is attached. Once you approve it, it goes out to ${invoice.recipientEmail || '(no email address yet)'} on ${longDate(invoice.issueDate)}.`,
],
rows: [
['Church', invoice.customer.name],
['Tier', `${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]] : []),
['Total', money(invoice.totalCents), true],
['Goes out', longDate(invoice.issueDate)],
],
note: invoice.warnings?.length ? { title: 'Check before approving', text: invoice.warnings.join('\n') } : invoice.planChange ? { title: 'Tier change', text: 'Approving also sends the church a notice of licence change straight away.' } : null,
button: { label: 'Review and approve', url: hubLink(`/billing/invoices/${invoice.id}`) },
signoff: false,
});
const res = await sendBillingEmail(settings, {
kind: 'approval', customerId: invoice.customerId, refId: invoice.id, to,
subject: `Approve invoice ${invoice.number} for ${invoice.customer.name}: ${money(invoice.totalCents)}`,
content, pdfs: [{ filename: `${invoice.number} (draft).pdf`, content: await invoicePdfFor(invoice, settings) }],
});
if (res.ok) await prisma.invoice.update({ where: { id: invoice.id }, data: { approvalEmailedAt: new Date() } });
}
/** Drafts every invoice that's due within billing_draft_days. Returns how many. */
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', 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 (let i = 0; i < 12; i++) {
const invoice = await draftForLicence(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;
}
}
return made;
}
// ─── Sending ─────────────────────────────────────────────────────────────────
async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
const state = compute.invoiceState(invoice, ymd(today()));
const tax = String(settings.vat_registered) === 'true';
const title = tax ? 'Tax invoice' : 'Invoice';
const content = layout(settings, {
preheader: `${title} ${invoice.number}: ${money(state.balanceCents)} due ${longDate(invoice.dueDate)}`,
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.`,
'Please pay by EFT using the invoice number as the reference. The banking details are on the invoice.',
],
rows: [
['Invoice', invoice.number],
...(invoice.periodStart ? [['Period', periodLabel(invoice.periodStart, invoice.periodEnd)]] : []),
...(state.paidCents ? [['Total', money(invoice.totalCents)], ['Paid', money(state.paidCents)]] : []),
[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,
});
return sendBillingEmail(settings, {
kind: 'invoice', customerId: invoice.customerId, refId: invoice.id, to: invoice.recipientEmail,
subject: `${title} ${invoice.number} from ${settings.business_name || 'Cross Code'}: ${money(state.balanceCents)} due ${longDate(invoice.dueDate)}`,
content, pdfs: [{ filename: `${invoice.number}.pdf`, content: await pdf.invoicePdf({ invoice: { ...invoice, status: 'sent' }, customer: invoice.customer, settings, state }) }],
});
}
/** Sends an approved invoice now. Marks it sent, or records why it couldn't go. */
async function sendInvoice(id, settings, now = new Date()) {
const invoice = await loadInvoice(id);
if (invoice.status !== 'approved') throw bad('Only an approved invoice can be sent.', 409);
if (!invoice.recipientEmail) throw bad('There\'s no email address to send it to.', 409);
// Claim it so two runs never both send it.
const claimed = await prisma.invoice.updateMany({ where: { id, status: 'approved' }, data: { status: 'sent', sentAt: now, sendError: null } });
if (claimed.count !== 1) throw bad('It was sent already.', 409);
const res = await sendInvoiceEmail({ ...invoice, status: 'sent' }, settings);
if (!res.ok) {
await prisma.invoice.update({ where: { id }, data: { status: 'approved', sentAt: null, sendError: res.error } });
if (!invoice.sendError && settings.alert_email) {
await sendMail({ to: settings.alert_email, subject: `Invoice ${invoice.number} couldn't be sent`, text: `Invoice ${invoice.number} for ${invoice.customer.name} couldn't be emailed to ${invoice.recipientEmail}: ${res.error}\n\nIt will be tried again. ${hubLink(`/billing/invoices/${id}`)}` }).catch(() => {});
}
throw bad(`It couldn't be emailed: ${res.error}`, 502);
}
await applyDueLicenceChanges(now);
return loadInvoice(id);
}
async function sendDueInvoices(now, settings) {
if (saHour(now) < (parseInt(settings.billing_send_hour, 10) || 0)) return 0;
const due = await prisma.invoice.findMany({ where: { status: 'approved', issueDate: { lte: today(now) } }, select: { id: true } });
let sent = 0;
for (const { id } of due) {
try {
await sendInvoice(id, settings, now);
sent += 1;
} catch (e) {
console.warn(`[billing] invoice ${id} not sent:`, e?.message || e);
}
}
return sent;
}
/** Emails Joshua once about drafts whose date has come without approval. */
async function remindUnapproved(now, settings) {
if (!settings.alert_email) return 0;
const late = await prisma.invoice.findMany({ where: { status: 'draft', issueDate: { lte: today(now) }, overdueEmailedAt: null }, include: { customer: true } });
if (!late.length) return 0;
const content = layout(settings, {
heading: late.length === 1 ? 'An invoice is waiting for your approval' : `${late.length} invoices are waiting for your approval`,
paragraphs: ['Their date has come, but they won\'t go out until you approve them.'],
rows: late.map(i => [`${i.number}, ${i.customer.name}`, `${money(i.totalCents)}, ${longDate(i.issueDate)}`]),
button: { label: 'Open billing', url: hubLink('/billing') },
signoff: false,
});
const res = await sendBillingEmail(settings, { kind: 'reminder', to: settings.alert_email, subject: `${late.length} invoice${late.length === 1 ? '' : 's'} waiting for approval`, content });
if (res.ok) await prisma.invoice.updateMany({ where: { id: { in: late.map(i => i.id) } }, data: { overdueEmailedAt: now } });
return late.length;
}
/** Puts tier changes into effect on their date (once the invoice that brings one has gone out). */
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' } } }] },
});
for (const c of due) {
const tier = tierNamed(c.toPlan);
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;
else if (c.toMonthlyCents != null) data.customMonthlyCents = c.toMonthlyCents;
await prisma.$transaction([
prisma.licence.update({ where: { id: c.licenceId }, data }),
prisma.licenceChange.update({ where: { id: c.id }, data: { appliedAt: now } }),
]);
}
return due.length;
}
/** The background job. */
async function runBilling(now = new Date()) {
const settings = await getSettings();
if (String(settings.billing_enabled) !== 'true') return { drafted: 0, sent: 0, reminded: 0, applied: 0 };
const drafted = await createDueDrafts(now, settings);
const sent = await sendDueInvoices(now, settings);
const reminded = await remindUnapproved(now, settings);
const applied = await applyDueLicenceChanges(now);
return { drafted, sent, reminded, applied };
}
// ─── Invoice actions ─────────────────────────────────────────────────────────
/** Approves a draft. A tier change with it sends the church its notice now. */
async function approveInvoice(id, actorId) {
const settings = await getSettings();
const invoice = await loadInvoice(id);
if (invoice.status !== 'draft') throw bad('Only a draft can be approved.', 409);
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);
}
}
return { invoice: await loadInvoice(id), notice };
}
async function unapproveInvoice(id) {
const res = await prisma.invoice.updateMany({ where: { id, status: 'approved' }, data: { status: 'draft', approvedAt: null, approvedById: null } });
if (res.count !== 1) throw bad('Only an approved invoice that hasn\'t gone out can go back to draft.', 409);
return loadInvoice(id);
}
/** Changes a draft or approved invoice: dates, lines, notes, recipient, the tier change. */
async function updateInvoice(id, body) {
const settings = await getSettings();
const invoice = await loadInvoice(id);
if (!EDITABLE.includes(invoice.status)) throw bad('A sent or void invoice can\'t be changed. Void it and make a new one instead.', 409);
const data = {};
if (body.issueDate !== undefined) data.issueDate = day(body.issueDate);
if (body.dueDate !== undefined) data.dueDate = day(body.dueDate);
const issue = data.issueDate || invoice.issueDate;
const due = data.dueDate || invoice.dueDate;
if (ymd(due) < ymd(issue)) throw bad('The due date can\'t be before the invoice date.');
if (body.lines !== undefined) {
const lines = compute.cleanLines(body.lines);
Object.assign(data, { lines }, compute.totals(lines, settings));
}
if (body.notes !== undefined) data.notes = body.notes ? String(body.notes).slice(0, 2000) : null;
if (body.recipientEmail !== undefined) {
const e = String(body.recipientEmail || '').trim();
if (e && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) throw bad('That email address doesn\'t look right.');
data.recipientEmail = e || null;
}
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;
}
// 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);
}
/** Rebuilds a draft's lines from the licence as it is now (e.g. after changing founding or the price). */
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);
const plan = invoice.planChange?.to || invoice.plan || invoice.licence.plan;
const { lines, warning } = compute.planLines({
plan, customMonthlyCents: invoice.licence.customMonthlyCents, cycle: invoice.cycle,
periodStart: invoice.periodStart, periodEnd: invoice.periodEnd, founding: !!invoice.customer.founding,
});
const recipientEmail = invoice.recipientEmail || compute.recipientFor(invoice.customer, invoice.licence.install);
await prisma.invoice.update({
where: { id },
data: { lines, ...compute.totals(lines, settings), founding: !!invoice.customer.founding, plan, recipientEmail, warnings: warning ? [warning] : [] },
});
return loadInvoice(id);
}
async function voidInvoice(id, reason) {
const invoice = await loadInvoice(id);
if (invoice.status === 'void') throw bad('It\'s already void.', 409);
if (invoice.payments.length) throw bad('It has payments recorded against it. Remove them (or move them) first.', 409);
await prisma.invoice.update({ where: { id }, data: { status: 'void', voidedAt: new Date(), voidReason: reason ? String(reason).slice(0, 500) : null } });
// A tier change that hasn't happened yet goes with it.
await prisma.licenceChange.deleteMany({ where: { invoiceId: id, appliedAt: null, sentAt: null } });
return loadInvoice(id);
}
async function resendInvoice(id) {
const settings = await getSettings();
const invoice = await loadInvoice(id);
if (invoice.status !== 'sent') throw bad('Only a sent invoice can be sent again.', 409);
const res = await sendInvoiceEmail(invoice, settings, { copy: true });
if (!res.ok) throw bad(`It couldn't be emailed: ${res.error}`, 502);
return invoice;
}
/** 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 } } });
if (!customer) throw bad('Customer not found', 404);
const lines = compute.cleanLines(body.lines || []);
if (!lines.length) throw bad('Add at least one line.');
const issueDate = body.issueDate ? day(body.issueDate) : today();
const terms = parseInt(settings.payment_terms_days, 10);
const dueDate = body.dueDate ? day(body.dueDate) : addDays(issueDate, Number.isFinite(terms) ? terms : 7);
const number = await nextNumber(settings.invoice_prefix || 'INV', issueDate);
return prisma.invoice.create({
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]),
},
include: invoiceInclude,
});
}
// ─── 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 } } } });
if (!payment) throw bad('Payment not found', 404);
const to = payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, payment.customer.installs[0]);
const state = payment.invoice ? compute.invoiceState(payment.invoice, ymd(today())) : null;
const content = layout(settings, {
preheader: `We received ${money(payment.amountCents)}. Thank you!`,
heading: 'Thank you for your payment',
greeting: `Hi ${payment.customer.contactName || payment.customer.name},`,
paragraphs: [`We received your payment of ${money(payment.amountCents)} on ${longDate(payment.paidOn)}. Your receipt is attached.`],
rows: [
['Receipt', payment.receiptNumber],
['Amount', money(payment.amountCents), true],
...(payment.invoice ? [['For invoice', payment.invoice.number], ['Still owing on it', money(Math.max(0, state.balanceCents)), true]] : []),
],
note: state && state.balanceCents <= 0 ? { title: 'Paid in full', text: `Invoice ${payment.invoice.number} is now paid in full.` } : null,
});
const res = await sendBillingEmail(settings, {
kind: 'receipt', customerId: payment.customerId, refId: payment.id, to,
subject: `Receipt ${payment.receiptNumber} from ${settings.business_name || 'Cross Code'}: ${money(payment.amountCents)} received`,
content, pdfs: [{ filename: `${payment.receiptNumber}.pdf`, content: await pdf.receiptPdf({ payment, customer: payment.customer, invoice: payment.invoice, state, settings, recipientEmail: to }) }],
});
if (res.ok) await prisma.payment.update({ where: { id: paymentId }, data: { receiptSentAt: new Date() } });
return res;
}
/** Records a payment (and emails the receipt unless sendReceipt is false). */
async function recordPayment(body, actorId) {
const settings = await getSettings();
const customer = await prisma.customer.findUnique({ where: { id: String(body.customerId || '') } });
if (!customer) throw bad('Customer not found', 404);
const amountCents = Math.round(Number(body.amountCents));
if (!Number.isInteger(amountCents) || amountCents <= 0 || amountCents > 1e9) throw bad('Enter the amount received.');
let invoiceId = null;
if (body.invoiceId) {
const inv = await prisma.invoice.findUnique({ where: { id: String(body.invoiceId) } });
if (!inv || inv.customerId !== customer.id) throw bad('That invoice isn\'t this customer\'s.');
if (inv.status === 'void') throw bad('That invoice is void.');
invoiceId = inv.id;
}
const method = ['eft', 'card', 'cash', 'other'].includes(body.method) ? body.method : 'eft';
const paidOn = body.paidOn ? day(body.paidOn) : today();
const receiptNumber = await nextNumber(settings.receipt_prefix || 'REC', paidOn);
const payment = await prisma.payment.create({
data: { receiptNumber, customerId: customer.id, invoiceId, amountCents, paidOn, method, reference: body.reference ? String(body.reference).slice(0, 200) : null, notes: body.notes ? String(body.notes).slice(0, 1000) : null, createdById: actorId || null },
});
let receipt = null;
if (body.sendReceipt !== false) receipt = await sendReceipt(payment.id, settings);
return { payment: await prisma.payment.findUnique({ where: { id: payment.id }, include: { invoice: true } }), receipt };
}
async function deletePayment(id) {
const payment = await prisma.payment.findUnique({ where: { id } });
if (!payment) throw bad('Payment not found', 404);
await prisma.payment.delete({ where: { id } });
return payment;
}
async function resendReceipt(id) {
const res = await sendReceipt(id, await getSettings());
if (!res.ok) throw bad(`It couldn't be emailed: ${res.error}`, 502);
return res;
}
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 } } } });
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]) }) };
}
// ─── Statements ──────────────────────────────────────────────────────────────
async function customerStatement(customerId, from, to) {
const customer = await prisma.customer.findUnique({ where: { id: customerId }, include: { installs: { where: { releasedAt: null }, take: 1 } } });
if (!customer) throw bad('Customer not found', 404);
const t = to ? day(to) : today();
const f = from ? day(from) : addDays(t, -365);
if (ymd(f) > ymd(t)) throw bad('The start date is after the end date.');
const [invoices, payments] = await Promise.all([
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 }) };
}
async function statementPdfFor(customerId, from, to) {
const settings = await getSettings();
const { customer, recipientEmail, statement } = await customerStatement(customerId, from, to);
return { filename: `Statement ${customer.name} ${statement.to}.pdf`, content: await pdf.statementPdf({ statement, customer, settings, recipientEmail }) };
}
async function emailStatement(customerId, { from, to, email } = {}) {
const settings = await getSettings();
const { customer, recipientEmail, statement } = await customerStatement(customerId, from, to);
const sendTo = email || recipientEmail;
const content = layout(settings, {
preheader: `Balance ${money(statement.closingCents)} on ${longDate(statement.to)}`,
heading: 'Your Cross Events 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: [
['Balance brought forward', money(statement.openingCents)],
[statement.closingCents > 0 ? 'Amount owing' : statement.closingCents < 0 ? 'In credit' : 'Balance', money(Math.abs(statement.closingCents)), true],
...(statement.outstanding.length ? [['Invoices still owing', statement.outstanding.map(o => o.number).join(', ')]] : []),
],
note: statement.closingCents <= 0 ? { title: 'All paid up', text: 'Nothing is owing. Thank you!' } : null,
});
const res = await sendBillingEmail(settings, {
kind: 'statement', customerId, to: sendTo,
subject: `Statement from ${settings.business_name || 'Cross Code'}: ${statement.closingCents > 0 ? `${money(statement.closingCents)} owing` : 'all paid up'}`,
content, pdfs: [{ filename: `Statement ${statement.to}.pdf`, content: await pdf.statementPdf({ statement, customer, settings, recipientEmail: sendTo }) }],
});
if (!res.ok) throw bad(`It couldn't be emailed: ${res.error}`, 502);
return { to: sendTo, statement };
}
// ─── 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 licence = change.licenceId ? await prisma.licence.findUnique({ where: { id: change.licenceId } }) : null;
const to = compute.recipientFor(customer, customer.installs[0]);
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}`,
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.`,
...(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]] : []),
],
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 }) }],
});
if (res.ok) await prisma.licenceChange.update({ where: { id: change.id }, data: { sentAt: new Date() } });
return res;
}
/**
* A notice of licence change, sent now (`send` false to only record it). It takes effect on
* effectiveDate (the job changes the licence's plan then; at once if that's today or earlier).
*/
async function createLicenceChange(body, settings = null, { send = true } = {}) {
settings = settings || await getSettings();
const licence = await prisma.licence.findUnique({ where: { id: String(body.licenceId || '') } });
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 number = await nextNumber(settings.change_prefix || 'LC', new Date());
const change = await prisma.licenceChange.create({
data: {
number, customerId: licence.customerId, licenceId: licence.id, invoiceId: body.invoiceId || null,
fromPlan, toPlan,
fromMonthlyCents: body.fromMonthlyCents !== undefined ? body.fromMonthlyCents : priceOf(fromPlan, licence.customMonthlyCents),
toMonthlyCents: priceOf(toPlan, body.toMonthlyCents),
effectiveDate, reason: body.reason ? String(body.reason).slice(0, 1000) : null, incomeBand: body.incomeBand || null,
},
});
let email = null;
if (send) email = await sendLicenceChange(change, settings);
if (!body.invoiceId) await applyDueLicenceChanges();
return { change: await prisma.licenceChange.findUnique({ where: { id: change.id } }), email };
}
async function resendLicenceChange(id) {
const change = await prisma.licenceChange.findUnique({ where: { id } });
if (!change) throw bad('Notice not found', 404);
const res = await sendLicenceChange(change, await getSettings());
if (!res.ok) throw bad(`It couldn't be emailed: ${res.error}`, 502);
return res;
}
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 } });
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 }) };
}
module.exports = {
nextNumber, loadInvoice, invoicePdfFor, draftForLicence, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
applyDueLicenceChanges, runBilling, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice,
resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement,
statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval,
};
+312
View File
@@ -0,0 +1,312 @@
/**
* Billing PDFs (A4, pdfkit): invoices (tax invoices once VAT registered), receipts, statements
* and notices of licence change. One shared layout: the Cross Code logo and business details,
* the document's title and reference box, the church's details, a table, totals, how to pay,
* and a footer on every page. Drafts carry a DRAFT watermark.
*/
const path = require('path');
const PDFDocument = require('pdfkit');
const { longDate, shortDate, money, periodLabel } = require('./dates');
const { planPrice, FOUNDING_PERCENT } = require('./tiers');
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' };
const M = 48; // page margin
const W = 595.28 - M * 2; // content width
/** Renders `draw(doc)` into a PDF and resolves with its bytes. */
function render(draw, { title, draft = false } = {}) {
return new Promise((resolve, reject) => {
const doc = new PDFDocument({ size: 'A4', margins: { top: M, bottom: 70, left: M, right: M }, bufferPages: true, info: { Title: title, Author: 'Cross Code', Creator: 'Cross Events Hub' } });
const chunks = [];
doc.on('data', c => chunks.push(c));
doc.on('end', () => resolve(Buffer.concat(chunks)));
doc.on('error', reject);
try {
draw(doc);
const range = doc.bufferedPageRange();
for (let i = range.start; i < range.start + range.count; i++) {
doc.switchToPage(i);
if (draft) watermark(doc);
footer(doc, i - range.start + 1, range.count);
}
doc.end();
} catch (e) {
reject(e);
}
});
}
function watermark(doc) {
doc.save();
doc.rotate(-30, { origin: [297, 420] });
doc.font('Helvetica-Bold').fontSize(110).fillColor(C.sky).fillOpacity(0.12).text('DRAFT', 60, 360, { width: 480, align: 'center', lineBreak: false });
doc.restore();
doc.fillOpacity(1);
}
let footerText = '';
function footer(doc, n, of) {
const y = 841.89 - 46;
const bottom = doc.page.margins.bottom;
doc.page.margins.bottom = 0;
doc.moveTo(M, y - 8).lineTo(M + W, y - 8).lineWidth(0.5).strokeColor(C.line).stroke();
doc.font('Helvetica').fontSize(7.5).fillColor(C.muted).text(footerText, M, y, { width: W - 60, lineBreak: false });
doc.text(`Page ${n} of ${of}`, M + W - 60, y, { width: 60, align: 'right', lineBreak: false });
doc.page.margins.bottom = bottom;
}
/** The logo and business details (left), the title and reference rows (right). Returns the y below. */
function header(doc, s, title, refRows) {
footerText = [s.business_name, s.business_website, s.business_email, s.business_phone].filter(Boolean).join(' · ');
try { doc.image(LOGO, M, M - 4, { width: 46, height: 46 }); } catch { /* no logo file */ }
doc.font('Helvetica-Bold').fontSize(15).fillColor(C.navy).text(s.business_name || 'Cross Code', M + 56, M + 2);
const details = [
s.business_owner && s.business_registration ? `${s.business_owner} · ${s.business_registration}` : s.business_owner || s.business_registration,
s.business_address,
[s.business_email, s.business_phone].filter(Boolean).join(' · '),
String(s.vat_registered) === 'true' && s.vat_number ? `VAT number ${s.vat_number}` : null,
].filter(Boolean);
doc.font('Helvetica').fontSize(8).fillColor(C.muted).text(details.join('\n'), M + 56, M + 21, { width: 250, lineGap: 1.5 });
const rx = M + W - 210;
doc.font('Helvetica-Bold').fontSize(20).fillColor(C.navy).text(title, rx, M, { width: 210, align: 'right' });
let y = M + 30;
doc.roundedRect(rx, y, 210, 14 + refRows.length * 15, 6).fillColor(C.surface).fill();
y += 8;
for (const [k, v, bold] of refRows) {
doc.font('Helvetica').fontSize(8.5).fillColor(C.muted).text(k, rx + 10, y, { width: 90 });
doc.font(bold ? 'Helvetica-Bold' : 'Helvetica').fillColor(C.text).text(v, rx + 95, y, { width: 105, align: 'right' });
y += 15;
}
const bottom = Math.max(y + 8, M + 21 + details.length * 11 + 10);
doc.moveTo(M, bottom + 6).lineTo(M + W, bottom + 6).lineWidth(2).strokeColor(C.sky).stroke();
return bottom + 22;
}
/** "Billed to" (or another label) with the church's details. Returns the y below. */
function party(doc, y, label, customer, email) {
doc.font('Helvetica-Bold').fontSize(8).fillColor(C.skyDark).text(label.toUpperCase(), M, y, { characterSpacing: 1 });
const lines = [customer.contactName ? `Attention: ${customer.contactName}` : null, customer.billingAddress, email].filter(Boolean);
doc.font('Helvetica-Bold').fontSize(11).fillColor(C.navy).text(customer.name, M, y + 13, { width: 300 });
doc.font('Helvetica').fontSize(9).fillColor(C.text).text(lines.join('\n'), M, doc.y + 2, { width: 300, lineGap: 1.5 });
return doc.y + 16;
}
/**
* A table. `cols`: [{ label, width, align }]; `rows`: arrays of cell text (or { text, bold, color }).
* Breaks onto new pages, repeating the heading. Returns the y below.
*/
function table(doc, y, cols, rows) {
const head = yy => {
doc.rect(M, yy, W, 20).fillColor(C.navy).fill();
let x = M;
for (const c of cols) {
doc.font('Helvetica-Bold').fontSize(8).fillColor('#ffffff').text(c.label, x + 8, yy + 6.5, { width: c.width - 16, align: c.align || 'left', lineBreak: false });
x += c.width;
}
return yy + 20;
};
y = head(y);
rows.forEach((row, ri) => {
const cells = row.map(c => (typeof c === 'object' && c !== null ? c : { text: String(c ?? '') }));
doc.font('Helvetica').fontSize(9);
const h = Math.max(20, ...cells.map((c, i) => doc.heightOfString(c.text, { width: cols[i].width - 16 }) + 11));
if (y + h > 841.89 - 90) {
doc.addPage();
y = head(M);
}
if (ri % 2 === 1) doc.rect(M, y, W, h).fillColor(C.surface).fill();
let x = M;
cells.forEach((c, i) => {
doc.font(c.bold ? 'Helvetica-Bold' : 'Helvetica').fontSize(9).fillColor(c.color || C.text).text(c.text, x + 8, y + 6, { width: cols[i].width - 16, align: cols[i].align || 'left' });
x += cols[i].width;
});
y += h;
});
doc.moveTo(M, y).lineTo(M + W, y).lineWidth(0.5).strokeColor(C.line).stroke();
return y + 10;
}
/** Right-hand totals: [[label, value, { bold, big, color }]]. Returns the y below. */
function totalsBlock(doc, y, rows) {
const x = M + W - 230;
for (const [k, v, o = {}] of rows) {
if (y > 841.89 - 110) { doc.addPage(); y = M; }
if (o.big) {
doc.roundedRect(x, y - 3, 230, 26, 5).fillColor(C.skyPale).fill();
doc.font('Helvetica-Bold').fontSize(11).fillColor(C.navy).text(k, x + 10, y + 4, { width: 120 });
doc.fillColor(o.color || C.navy).text(v, x + 120, y + 4, { width: 100, align: 'right' });
y += 30;
} else {
doc.font(o.bold ? 'Helvetica-Bold' : 'Helvetica').fontSize(9).fillColor(C.muted).text(k, x + 10, y, { width: 130 });
doc.fillColor(o.color || C.text).text(v, x + 120, y, { width: 100, align: 'right' });
y += 15;
}
}
return y + 8;
}
/** A shaded box with a heading and lines of text. Returns the y below. */
function box(doc, y, heading, lines, { tone = 'surface' } = {}) {
doc.font('Helvetica').fontSize(9);
const textH = doc.heightOfString(lines.join('\n'), { width: W - 28, lineGap: 2 });
const h = textH + 34;
if (y + h > 841.89 - 90) { doc.addPage(); y = M; }
doc.roundedRect(M, y, W, h, 6).fillColor(tone === 'sky' ? C.skyPale : C.surface).fill();
doc.font('Helvetica-Bold').fontSize(9.5).fillColor(C.navy).text(heading, M + 14, y + 11);
doc.font('Helvetica').fontSize(9).fillColor(C.text).text(lines.join('\n'), M + 14, y + 26, { width: W - 28, lineGap: 2 });
return y + h + 12;
}
function paymentLines(s, reference) {
const bank = [
s.bank_account_name && `Account name: ${s.bank_account_name}`,
s.bank_name && `Bank: ${s.bank_name}`,
s.bank_account_number && `Account number: ${s.bank_account_number}`,
s.bank_branch_code && `Branch code: ${s.bank_branch_code}`,
s.bank_account_type && `Account type: ${s.bank_account_type}`,
].filter(Boolean);
if (!bank.length) return [`Please contact us at ${s.business_email || 'admin@crosscode.co.za'} for our banking details.`, `Reference: ${reference}`];
return [...bank, `Reference: ${reference}`, 'Please use the reference so we can match your payment.'];
}
const isTax = s => String(s.vat_registered) === 'true';
const vatRow = (s, vatCents) => (isTax(s) ? [[`Includes VAT (${parseFloat(s.vat_rate) || 15}%)`, money(vatCents)]] : []);
/** An invoice (a tax invoice once VAT registered). `state` gives paid and balance. */
function invoicePdf({ invoice, customer, settings: s, state }) {
const title = isTax(s) ? 'Tax invoice' : 'Invoice';
const draft = invoice.status === 'draft' || invoice.status === 'approved';
return render(doc => {
let y = header(doc, s, invoice.status === 'void' ? `${title} (void)` : title, [
['Invoice number', invoice.number, true],
['Date', longDate(invoice.issueDate)],
['Due', longDate(invoice.dueDate)],
...(invoice.periodStart ? [['Period', periodLabel(invoice.periodStart, invoice.periodEnd)]] : []),
]);
y = party(doc, y, 'Billed to', customer, invoice.recipientEmail);
y = table(doc, y, [
{ label: 'Description', width: W - 250 },
{ label: 'Qty', width: 50, align: 'right' },
{ label: 'Unit price', width: 100, align: 'right' },
{ label: 'Amount', width: 100, align: 'right' },
], (invoice.lines || []).map(l => [l.description, String(l.quantity), money(l.unitCents), { text: money(l.amountCents), bold: true }]));
const paid = state?.paidCents || 0;
y = totalsBlock(doc, y, [
...vatRow(s, invoice.vatCents),
...(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.',
], { tone: 'sky' });
}
if (invoice.status !== 'void') y = box(doc, y, 'How to pay', paymentLines(s, invoice.number));
if (invoice.notes) y = box(doc, y, 'Notes', [invoice.notes]);
if (invoice.status === 'void' && invoice.voidReason) y = box(doc, y, 'This invoice is void', [invoice.voidReason]);
if (s.invoice_footer) doc.font('Helvetica-Oblique').fontSize(9).fillColor(C.muted).text(s.invoice_footer, M, y + 4, { width: W, align: 'center' });
}, { title: `${title} ${invoice.number}`, draft });
}
/** A receipt for one payment. `invoice` (optional) with its state after the payment. */
function receiptPdf({ payment, customer, invoice, state, settings: s, recipientEmail }) {
const METHOD = { eft: 'EFT', card: 'Card', cash: 'Cash', other: 'Other' };
return render(doc => {
let y = header(doc, s, 'Receipt', [
['Receipt number', payment.receiptNumber, true],
['Date received', longDate(payment.paidOn)],
['Method', METHOD[payment.method] || payment.method],
...(payment.reference ? [['Reference', payment.reference]] : []),
]);
y = party(doc, y, 'Received from', customer, recipientEmail);
y = table(doc, y, [
{ label: 'Description', width: W - 120 },
{ label: 'Amount', width: 120, align: 'right' },
], [[invoice ? `Payment for invoice ${invoice.number}` : 'Payment on account', { text: money(payment.amountCents), bold: true }]]);
y = totalsBlock(doc, y, [
['Amount received', money(payment.amountCents), { big: true, color: C.green }],
...(invoice && state ? [[`Invoice ${invoice.number} balance`, money(Math.max(0, state.balanceCents)), { bold: true }]] : []),
]);
if (invoice && state && state.balanceCents <= 0) y = box(doc, y, 'Paid in full', [`Invoice ${invoice.number} is now paid in full. Thank you!`], { tone: 'sky' });
if (payment.notes) y = box(doc, y, 'Notes', [payment.notes]);
doc.font('Helvetica-Oblique').fontSize(9).fillColor(C.muted).text('Thank you for your payment.', M, y + 4, { width: W, align: 'center' });
}, { title: `Receipt ${payment.receiptNumber}` });
}
/** A statement (from compute.statement). */
function statementPdf({ statement: st, customer, settings: s, recipientEmail }) {
return render(doc => {
let y = header(doc, s, 'Statement', [
['From', longDate(st.from)],
['To', longDate(st.to)],
['Balance', money(st.closingCents), true],
]);
y = party(doc, y, 'Statement for', customer, recipientEmail);
const rows = [
[shortDate(st.from), '', { text: 'Balance brought forward', bold: true }, '', '', { text: money(st.openingCents), bold: true }],
...st.entries.map(e => [shortDate(e.date), e.reference, e.description, e.debitCents ? money(e.debitCents) : '', e.creditCents ? money(e.creditCents) : '', money(e.balanceCents)]),
];
y = table(doc, y, [
{ label: 'Date', width: 72 },
{ label: 'Reference', width: 82 },
{ label: 'Description', width: W - 72 - 82 - 70 - 70 - 75 },
{ label: 'Charged', width: 70, align: 'right' },
{ label: 'Paid', width: 70, align: 'right' },
{ label: 'Balance', width: 75, align: 'right' },
], rows);
y = totalsBlock(doc, y, [[st.closingCents > 0 ? 'Amount owing' : st.closingCents < 0 ? 'In credit' : 'Balance', money(Math.abs(st.closingCents)), { big: true, color: st.closingCents > 0 ? C.navy : C.green }]]);
if (st.outstanding.length) {
y = box(doc, y, 'Invoices still owing', st.outstanding.map(o => `${o.number}: ${money(o.balanceCents)} of ${money(o.totalCents)}, due ${longDate(o.dueDate)}${o.overdue ? ' (overdue)' : ''}`));
y = box(doc, y, 'How to pay', paymentLines(s, st.outstanding.map(o => o.number).join(', ')));
} else {
y = box(doc, y, 'All paid up', ['Nothing is owing. Thank you!'], { tone: 'sky' });
}
}, { title: `Statement ${customer.name}` });
}
/** A notice of licence change (tier up or down). */
function licenceChangePdf({ change, customer, settings: s, founding, recipientEmail, cycle }) {
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 f = p && p.monthlyCents === cents ? p.foundingCents : Math.round((cents * (100 - FOUNDING_PERCENT)) / 100);
return `${money(f)} a month (founding price; normally ${money(cents)})`;
};
return render(doc => {
let y = header(doc, s, 'Licence change', [
['Notice number', change.number, true],
['Date', longDate(change.createdAt || new Date())],
['Takes effect', longDate(change.effectiveDate), true],
]);
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 });
y = doc.y + 10;
y = table(doc, y, [
{ label: '', width: 150 },
{ label: 'Now', width: (W - 150) / 2 },
{ label: `From ${longDate(change.effectiveDate)}`, width: (W - 150) / 2 },
], [
[{ text: 'Tier', bold: true }, change.fromPlan, { text: change.toPlan, bold: true }],
[{ text: 'Price', bold: true }, priceText(change.fromPlan, change.fromMonthlyCents), { text: priceText(change.toPlan, change.toMonthlyCents), bold: true }],
]);
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.`);
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.');
y = box(doc, y, 'Why it changes', why, { tone: 'sky' });
y = box(doc, y, 'Questions?', [`Reply to this email or contact us at ${s.business_email || 'admin@crosscode.co.za'}${s.business_phone ? ` or ${s.business_phone}` : ''}. Every feature stays included, whatever your tier.`]);
}, { title: `Licence change ${change.number}` });
}
module.exports = { invoicePdf, receiptPdf, statementPdf, licenceChangePdf };
+56
View File
@@ -0,0 +1,56 @@
/**
* 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.
*/
const TIERS = [
{ name: 'Seed', upTo: 50_000, monthly: 350, founding: 230 },
{ name: 'Sprout', upTo: 150_000, monthly: 550, founding: 360 },
{ name: 'Grow', upTo: 400_000, monthly: 850, founding: 550 },
{ name: 'Flourish', upTo: 1_000_000, monthly: 1350, founding: 880 },
{ name: 'Harvest', upTo: 2_500_000, monthly: 2100, founding: 1370 },
{ name: 'Abundance', upTo: 5_000_000, monthly: 3200, founding: 2080 },
{ name: 'Movement', upTo: 10_000_000, monthly: 4800, founding: 3120 },
{ 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). */
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;
/** The highest rand amount in a band label ("R100 001–R150 000" → 150000; "over R10 000 000" → Infinity). */
function bandTop(band) {
if (/^over /i.test(band)) return Infinity;
const parts = String(band).split('–');
if (parts.length !== 2 || !parts[1].trim()) return null;
const n = Number(parts[1].replace(/[^\d]/g, ''));
return Number.isFinite(n) ? n : null;
}
/** The tier a 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);
if (top == null) return null;
return TIERS.find(t => t.upTo == null || top <= t.upTo) || null;
}
/**
* The monthly price of a plan in cents, normal and founding: { monthlyCents, foundingCents },
* 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);
if (customMonthlyCents != null && customMonthlyCents >= 0) {
return { monthlyCents: customMonthlyCents, foundingCents: Math.round((customMonthlyCents * (100 - FOUNDING_PERCENT)) / 100), custom: true };
}
if (!tier || tier.monthly == null) return null;
return { monthlyCents: tier.monthly * 100, foundingCents: tier.founding * 100, custom: false };
}
module.exports = { TIERS, YEARLY_MONTHS, FOUNDING_PERCENT, tierNamed, tierForBand, planPrice };
+11 -4
View File
@@ -25,12 +25,17 @@ async function smtpConfigured() {
return !!(await smtpSettings()).host;
}
/** Send an email; without SMTP it's logged instead (development). */
async function sendMail({ to, subject, text }) {
/**
* Send an email; without SMTP it's logged instead (development). Billing emails (1.7.0) add
* `html`, `attachments` (nodemailer's: { filename, content, contentType, cid? }), `replyTo` and
* `fromName` (shown as the sender's name).
*/
async function sendMail({ to, subject, text, html, attachments, replyTo, fromName }) {
if (!to) return;
const smtp = await smtpSettings();
if (!smtp.host) {
console.info(`[mail] (SMTP not set up) to=${to} subject="${subject}"\n${text}`);
const files = (attachments || []).filter(a => !a.cid).map(a => a.filename).join(', ');
console.info(`[mail] (SMTP not set up) to=${to} subject="${subject}"${files ? ` attachments=${files}` : ''}\n${text}`);
return;
}
const key = JSON.stringify(smtp);
@@ -38,7 +43,9 @@ async function sendMail({ to, subject, text }) {
transporter = createTransport(smtp);
transporterFor = key;
}
await transporter.sendMail({ from: fromAddress(smtp), to, subject, text });
const address = fromAddress(smtp);
const from = fromName ? { name: fromName, address: address.replace(/^.*<([^>]+)>.*$/, '$1') } : address;
await transporter.sendMail({ from, to, subject, text, html, attachments, replyTo });
}
/**
+31
View File
@@ -37,6 +37,37 @@ const DEFAULTS = {
ai_usd_zar: '',
// Default markup on the real cost, in %; a licence can override it.
ai_markup_percent: '40',
// Billing (1.7.0, utils/billing/). Drafts are made billing_draft_days before an invoice's date
// and emailed to alert_email for approval; approved invoices go out on their date at
// billing_send_hour (South African time).
billing_enabled: 'true',
billing_draft_days: '14',
billing_send_hour: '8',
payment_terms_days: '7',
invoice_prefix: 'INV',
receipt_prefix: 'REC',
change_prefix: 'LC',
// Printed on every document.
business_name: 'Cross Code',
business_owner: 'Joshua Oosthuizen',
business_address: '44 Gordon Road, Henley on Klip, Gauteng, South Africa',
business_email: 'admin@crosscode.co.za',
business_phone: '+27 68 903 8075',
business_website: 'crosscode.co.za',
business_registration: '',
// Not VAT registered: no VAT on documents. Once registered, prices are VAT-inclusive: the
// totals stay the same, documents become tax invoices and show the VAT included.
vat_registered: '',
vat_number: '',
vat_rate: '15',
bank_name: '',
bank_account_name: '',
bank_account_number: '',
bank_branch_code: '',
bank_account_type: '',
invoice_footer: 'Thank you for using Cross Events.',
// Replies to billing emails go here (blank: business_email).
billing_reply_to: '',
};
// Stored encrypted and never sent to the browser: only "is one saved" (<key>_set).