- Product enum (events, accounts, website, app) on Licence and Install, Install.publicKey; existing rows are events - One open licence per product per customer: partial unique index, with a migration guard that names customers with duplicates (npm run check:hub2 lists them beforehand) - Licence keys per product (CEH-, CCA-, CCW-, CCP-); free Accounts licence created with the first other product licence - Protocol v1 registers Events licences only (409 WRONG_PRODUCT); only Events licences can be invoiced until billing per customer - Cross Code Hub in the UI, emails and PDFs - @crosscode/contracts 1.0.0 vendored (backend/vendor) - Steps merge into release/2.0, not main (plan updated) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
315 lines
17 KiB
JavaScript
315 lines
17 KiB
JavaScript
/**
|
|
* 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 { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
|
|
|
|
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 };
|
|
// Until billing per customer (Hub 2.0 step 4) only Events has prices; Accounts is never invoiced.
|
|
if (merged.billingCycle !== 'none' && !BILLABLE.includes(existing.product)) {
|
|
throw bad(`${PRODUCT_NAMES[existing.product]} licences can't be invoiced yet.`);
|
|
}
|
|
if (merged.billingCycle !== 'none') {
|
|
if (!merged.billingStart) throw bad('Set the date billing starts.');
|
|
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
|
|
// The first review is a year after billing starts.
|
|
if (!merged.reviewDate && b.reviewDate === undefined) data.reviewDate = require('../utils/billing/dates').addMonths(merged.billingStart, 12);
|
|
}
|
|
const licence = await prisma.licence.update({ where: { id: existing.id }, data });
|
|
await audit(req, 'licence_billing_updated', licence.id, { changed: Object.keys(data), billingCycle: licence.billingCycle });
|
|
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;
|