Files
events-hub/backend/src/utils/billing/pdf.js
T
joshuaandClaude Opus 5.5 7478e84e9d 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>
2026-11-04 16:18:23 +02:00

326 lines
18 KiB
JavaScript

/**
* 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 { 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' };
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 Code 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 }],
]);
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));
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, 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, 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)})`;
};
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 ${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 },
{ 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 && 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.');
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 };