Files
events-hub/backend/src/utils/billing/index.js
T
joshuaandClaude Opus 5.5 ad602b2846 Hub 2.0 step 1: products foundation
- 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>
2026-11-04 15:28:06 +02:00

557 lines
33 KiB
JavaScript

/**
* 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 { BILLABLE } = require('../products');
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', product: { in: BILLABLE }, 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,
};