/** * 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 customer whose next period starts within billing_draft_days, make * the draft invoice for all its products (Hub 2.0) and email it to alert_email for approval * (the customer moves on to the next period at once, so a period is drafted once). * 2. Sends approved invoices on their date, from billing_send_hour (South African time). * 3. Emails Joshua once when an invoice's date has come and it still isn't approved. * 4. Applies tier changes on their effective date (the licence's plan). * 5. Hub 2.0: reminds Joshua 30 days before a domain he registered for a church (address * "domain included") is due for renewal, once per renewal date. */ const { Prisma } = require('@prisma/client'); const prisma = require('../../config/db'); const { getSettings } = require('../settings'); const { sendMail } = require('../mail'); const { render } = require('../emailLayout'); 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 { PRODUCT_NAMES } = require('../products'); const bad = (message, status = 400) => Object.assign(new Error(message), { status }); /** The install whose admin contact a customer's documents fall back on (Events first). */ const contactOf = customer => compute.contactInstall((customer.installs || []).map(install => ({ install }))); const hubLink = p => `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}${p}`; const EDITABLE = ['draft', 'approved']; /** 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 ──────────────────────────────────────────────────────────────── /** The products on a customer invoice, by name ("Cross Events and Church Website"). */ function productsText(invoice) { const products = invoice.basis?.products || (invoice.licenceId ? ['events'] : []); const names = products.map(p => PRODUCT_NAMES[p]); return names.length ? names.join(', ').replace(/, ([^,]*)$/, ' and $1') : 'Cross Code'; } /** * Makes the draft for one customer's next period (Hub 2.0: all its products on one invoice). * Returns the invoice, `{ empty: true }` when nothing was billed (the customer still moves on), or * null if the period was invoiced already. */ async function draftForCustomer(customerId, settings) { return prisma.$transaction(async (tx) => { // Lock the customer row: two runs never draft the same period. await tx.$executeRaw`SELECT 1 FROM "Customer" WHERE id = ${customerId} FOR UPDATE`; const customer = await tx.customer.findUnique({ where: { id: customerId }, include: { licences: { include: { install: true } } } }); if (!customer || customer.billingCycle === 'none' || !customer.nextInvoiceDate) return null; const { invoice, customerUpdate, licenceUpdates, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings }); await tx.customer.update({ where: { id: customer.id }, data: customerUpdate }); if (empty) return { empty: true }; const exists = await tx.invoice.findFirst({ where: { customerId: customer.id, licenceId: null, periodStart: invoice.periodStart, status: { not: 'void' } } }); if (exists) return null; for (const u of licenceUpdates) await tx.licence.update({ where: { id: u.id }, data: u.data }); const products = [...new Set(licenceUpdates.map(u => customer.licences.find(l => l.id === u.id)?.product).filter(Boolean))]; const number = await nextNumber(settings.invoice_prefix || 'INV', invoice.issueDate, tx); return tx.invoice.create({ data: { ...invoice, basis: { ...invoice.basis, products }, 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], ['Products', `${invoice.plan || '—'}${invoice.founding ? ' (founding)' : ''}`], ...(invoice.reviewed ? [['12-month event income', invoice.incomeBand || 'not reported']] : []), ...compute.planChangesOf(invoice).map(pc => [`Tier change (${PRODUCT_NAMES[pc.product] || 'Cross Events'})`, `${pc.from} → ${pc.to}`, true]), ['Total', money(invoice.totalCents), true], ['Goes out', longDate(invoice.issueDate)], ], 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 customers = await prisma.customer.findMany({ where: { billingCycle: { not: 'none' }, nextInvoiceDate: { lte: horizon } }, select: { id: true }, }); let made = 0; for (const { id } of customers) { // Catch up a customer that's behind (at most a year's worth in one run). for (let i = 0; i < 12; i++) { const invoice = await draftForCustomer(id, settings); if (!invoice) break; if (!invoice.empty) { made += 1; await emailApproval(invoice, settings).catch(e => console.warn('[billing] approval email failed:', e?.message || e)); } const c = await prisma.customer.findUnique({ where: { id }, select: { nextInvoiceDate: true } }); if (!c?.nextInvoiceDate || ymd(c.nextInvoiceDate) > ymd(horizon)) break; } } return made; } // ─── Sending ───────────────────────────────────────────────────────────────── /** The email note for an invoice's tier changes, or null. */ function tierChangeNote(invoice) { const changes = compute.planChangesOf(invoice); if (!changes.length) return null; const why = pc => (pc.product === 'app' ? 'your active members over the last 90 days' : 'your event income over the last 12 months'); const one = pc => `${PRODUCT_NAMES[pc.product] || 'Cross Events'} moves from the ${pc.from} tier to the ${pc.to} tier, based on ${why(pc)}.`; return { title: changes.length === 1 ? `Your ${PRODUCT_NAMES[changes[0].product] || 'Cross Events'} tier is now ${changes[0].to}` : 'Your tiers have changed', text: `At your annual review: ${changes.map(one).join(' ')}`, }; } async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) { const state = compute.invoiceState(invoice, ymd(today())); const tax = String(settings.vat_registered) === 'true'; 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 ${productsText(invoice)}${invoice.periodStart ? `, ${periodLabel(invoice.periodStart, invoice.periodEnd)}` : ''}. The PDF is attached.`, 'Please pay by EFT using the invoice number as the reference. The banking details are on the invoice.', ], rows: [ ['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: tierChangeNote(invoice), }); 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) { const email = render({ heading: `Invoice ${invoice.number} couldn't be sent`, blocks: [ { note: { kind: 'danger', title: 'The email server said', text: res.error } }, { rows: [['Invoice', invoice.number], ['Customer', invoice.customer.name], ['To', invoice.recipientEmail]] }, { p: 'It will be tried again.' }, { button: { label: 'Open the invoice', url: hubLink(`/billing/invoices/${id}`) } }, ], footer: 'Sent by the Cross Code Hub to the alert address in Settings.', }); await sendMail({ to: settings.alert_email, subject: `Invoice ${invoice.number} couldn't be sent`, ...email }).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' } } }] }, include: { licence: { select: { product: true } } }, }); for (const c of due) { const tier = tierNamed(c.toPlan, c.licence?.product || 'events'); const data = { plan: c.toPlan }; // A custom price comes with a change to an unpriced plan; a priced tier uses its own price. if (tier?.monthly != null) data.customMonthlyCents = null; 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; } const DOMAIN_REMINDER_DAYS = 30; /** * Emails Joshua about included domains due for renewal within 30 days (or overdue), once per * renewal date. "Renewed" on the customer page moves the date on a year. */ async function remindDomainRenewals(now, settings) { if (!settings.alert_email) return 0; const due = (await prisma.customer.findMany({ where: { addressType: 'included', domainRenewsOn: { lte: addDays(today(now), DOMAIN_REMINDER_DAYS) } }, })).filter(c => !c.domainRemindedFor || ymd(c.domainRemindedFor) !== ymd(c.domainRenewsOn)); if (!due.length) return 0; const content = layout(settings, { heading: due.length === 1 ? 'A church\'s domain is due for renewal' : `${due.length} churches' domains are due for renewal`, paragraphs: ['You registered these domains for the churches (address: domain included). Renew them, then press Renewed on the church\'s page so the date moves on a year.'], rows: due.map(c => [`${c.name}`, `${c.domain || '(no domain recorded)'}: ${longDate(c.domainRenewsOn)}${ymd(c.domainRenewsOn) < ymd(today(now)) ? ' (overdue)' : ''}`]), button: { label: 'Open billing', url: hubLink('/billing') }, signoff: false, }); const res = await sendBillingEmail(settings, { kind: 'reminder', to: settings.alert_email, subject: `Domain renewal${due.length === 1 ? '' : 's'} due: ${due.map(c => c.domain || c.name).join(', ')}`, content }); if (res.ok) for (const c of due) await prisma.customer.update({ where: { id: c.id }, data: { domainRemindedFor: c.domainRenewsOn } }); return due.length; } /** The background job. */ async function runBilling(now = new Date()) { const settings = await getSettings(); // Domain renewals matter even while invoicing is switched off. const domains = await remindDomainRenewals(now, settings).catch(e => { console.warn('[billing] domain reminder failed:', e?.message || e); return 0; }); if (String(settings.billing_enabled) !== 'true') return { drafted: 0, sent: 0, reminded: 0, applied: 0, domains }; 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, domains }; } // ─── 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 } }); // One notice per tier change (Hub 2.0: per product), unless it was made already. const notices = []; for (const pc of compute.planChangesOf(invoice)) { if (!pc.licenceId) continue; const existing = await prisma.licenceChange.findFirst({ where: { invoiceId: id, licenceId: pc.licenceId } }); if (existing) continue; notices.push(await createLicenceChange({ customerId: invoice.customerId, licenceId: pc.licenceId, invoiceId: id, fromPlan: pc.from, toPlan: pc.to, fromMonthlyCents: pc.fromMonthlyCents, toMonthlyCents: pc.toMonthlyCents, effectiveDate: invoice.periodStart || invoice.issueDate, incomeBand: pc.band || (pc.product === 'events' ? invoice.incomeBand : null), reason: 'Your annual tier review.', }, settings)); } return { invoice: await loadInvoice(id), notice: notices[0] || null, notices }; } 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; } let reprice = false; if (body.dropPlanChange === true) { if (await prisma.licenceChange.findFirst({ where: { invoiceId: id, sentAt: { not: null } } })) throw bad('The church has already been sent the notice of this tier change.', 409); data.planChange = Prisma.DbNull; if (invoice.licenceId) data.plan = invoice.licence?.plan || invoice.plan; else { // A customer invoice keeps the tiers it had: a draft is repriced at them below. data.basis = { ...(invoice.basis || {}), planChangeDropped: true }; reprice = invoice.status === 'draft' && body.lines === undefined; } } // Editing an approved invoice keeps it approved; editing clears the "waiting" reminder. data.overdueEmailedAt = null; await prisma.invoice.update({ where: { id }, data }); return reprice ? recalculateInvoice(id) : loadInvoice(id); } /** * Rebuilds a draft's lines from the customer and its licences as they are now (e.g. after changing * founding, a price or a product's start), for the same period. */ async function recalculateInvoice(id) { const settings = await getSettings(); const invoice = await loadInvoice(id); if (invoice.status !== 'draft') throw bad('Only a draft can be recalculated.', 409); if (!invoice.licenceId && invoice.periodStart && invoice.cycle !== 'none') return recalculateCustomerInvoice(invoice, settings); if (!invoice.licence || !invoice.periodStart) throw bad('Only an invoice for a period can be recalculated.', 409); const plan = invoice.planChange?.to || invoice.plan || invoice.licence.plan; const { lines, warning } = compute.planLines({ plan, customMonthlyCents: invoice.licence.customMonthlyCents, cycle: invoice.cycle, 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); } /** * Hub 2.0 customer invoice: the lines worked out again for its period, from each licence's * billedUntil as it was before the draft (invoice.basis), so days owed are counted once. */ async function recalculateCustomerInvoice(invoice, settings) { const customer = await prisma.customer.findUnique({ where: { id: invoice.customerId }, include: { licences: { include: { install: true } } } }); const before = new Map((invoice.basis?.licences || []).map(l => [l.id, l.billedUntil])); const licences = customer.licences.map(l => (before.has(l.id) ? { ...l, billedUntil: before.get(l.id) ? day(before.get(l.id)) : null } : l)); const reviewed = invoice.reviewed && !invoice.basis?.planChangeDropped; const r = compute.customerInvoiceLines({ customer, licences, period: { start: invoice.periodStart, end: invoice.periodEnd, cycle: invoice.cycle }, reviewed }); const recipientEmail = invoice.recipientEmail || compute.recipientFor(customer, compute.contactInstall(customer.licences)); await prisma.$transaction([ prisma.invoice.update({ where: { id: invoice.id }, data: { lines: r.lines, ...compute.totals(r.lines, settings), founding: !!customer.founding, plan: r.plan, recipientEmail, warnings: r.warnings, planChange: r.planChanges.length ? r.planChanges : Prisma.DbNull, basis: { ...(invoice.basis || {}), products: r.products }, }, }), // A product added or started since the draft was made is now covered up to the period's end. ...r.licenceUpdates.map(u => prisma.licence.update({ where: { id: u.id }, data: u.data })), ]); return loadInvoice(invoice.id); } async function voidInvoice(id, reason) { const invoice = await loadInvoice(id); if (invoice.status === 'void') throw bad('It\'s already void.', 409); // Refunded payments don't count: an invoice that was paid and refunded can be voided. if (invoice.payments.some(p => !p.refundedAt)) throw bad('It has payments that weren\'t refunded. Refund them (or remove a payment recorded by mistake) 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 } } } }); 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, contactOf(customer)), }, 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 } } } }, invoice: { include: { payments: true } } } }); if (!payment) throw bad('Payment not found', 404); const to = payment.invoice?.recipientEmail || compute.recipientFor(payment.customer, contactOf(payment.customer)); const state = payment.invoice ? compute.invoiceState(payment.invoice, ymd(today())) : null; const content = layout(settings, { preheader: `We received ${money(payment.amountCents)}. Thank you!`, 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; } /** * The money went back to the church: the payment stays on record (with its receipt) but no longer * counts as paid, so its invoice is owing again and can be voided. The statement shows the refund. */ async function refundPayment(id, { on, note } = {}) { const payment = await prisma.payment.findUnique({ where: { id } }); if (!payment) throw bad('Payment not found', 404); if (payment.refundedAt) throw bad('It was already refunded.', 409); const refundedAt = on ? day(on) : today(); if (Number.isNaN(refundedAt.getTime())) throw bad('Not a valid date.'); if (ymd(refundedAt) < ymd(payment.paidOn)) throw bad('A refund can\'t be before the payment.'); return prisma.payment.update({ where: { id }, data: { refundedAt, refundNote: note ? String(note).trim().slice(0, 300) || null : null }, include: { invoice: true } }); } 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 } } } }, 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, contactOf(payment.customer)) }) }; } // ─── Statements ────────────────────────────────────────────────────────────── async function customerStatement(customerId, from, to) { const customer = await prisma.customer.findUnique({ where: { id: customerId }, include: { installs: { where: { releasedAt: null } } } }); if (!customer) throw bad('Customer not found', 404); const t = to ? day(to) : today(); const f = from ? day(from) : addDays(t, -365); 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, contactOf(customer)), 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 Code statement', greeting: `Hi ${customer.contactName || customer.name},`, paragraphs: [`Here is your statement from ${longDate(statement.from)} to ${longDate(statement.to)}. The PDF is attached.`], rows: [ ['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 } } } }); const licence = change.licenceId ? await prisma.licence.findUnique({ where: { id: change.licenceId } }) : null; const product = licence?.product || 'events'; const name = PRODUCT_NAMES[product]; const to = compute.recipientFor(customer, contactOf(customer)); const up = change.fromMonthlyCents != null && change.toMonthlyCents != null ? change.toMonthlyCents > change.fromMonthlyCents : null; const content = layout(settings, { preheader: `From ${longDate(change.effectiveDate)}: the ${change.toPlan} tier`, heading: up === false ? `Good news: your ${name} tier moves down to ${change.toPlan}` : `Your ${name} tier changes to ${change.toPlan}`, greeting: `Hi ${customer.contactName || customer.name},`, paragraphs: [ `From ${longDate(change.effectiveDate)}, your ${name} licence moves from the ${change.fromPlan} tier to the ${change.toPlan} tier. The notice is attached.`, ...(change.reason ? [change.reason] : []), 'Every feature stays included, whatever your tier. If you have any questions, just reply to this email.', ], rows: [ ['Now', `${change.fromPlan}${change.fromMonthlyCents != null ? `, ${money(change.fromMonthlyCents)} a month` : ''}`], [`From ${longDate(change.effectiveDate)}`, `${change.toPlan}${change.toMonthlyCents != null ? `, ${money(change.toMonthlyCents)} a month` : ''}`, true], ...(change.incomeBand ? [[product === 'app' ? 'Active members (90 days)' : '12-month event income', change.incomeBand]] : []), ], note: customer.founding ? { title: 'Founding church', text: 'Your 35% founding discount carries on in your new tier.' } : null, }); const res = await sendBillingEmail(settings, { kind: 'licence_change', customerId: customer.id, refId: change.id, to, subject: `Notice of licence change: ${change.fromPlan} to ${change.toPlan} from ${longDate(change.effectiveDate)}`, content, pdfs: [{ filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer, settings, founding: customer.founding, recipientEmail: to, cycle: customer.billingCycle, product }) }], }); 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 || '') }, include: { customer: true } }); if (!licence) throw bad('Licence not found', 404); const toPlan = String(body.toPlan || '').trim(); if (!toPlan) throw bad('Choose the new tier.'); const fromPlan = body.fromPlan || licence.plan; if (toPlan === fromPlan && body.toMonthlyCents == null) throw bad('That\'s the tier it\'s on already.'); const priceOf = (plan, custom) => (custom != null ? Math.round(Number(custom)) : planPrice(plan, null, licence.product)?.monthlyCents ?? null); const effectiveDate = body.effectiveDate ? day(body.effectiveDate) : licence.customer.nextInvoiceDate ? day(licence.customer.nextInvoiceDate) : today(); const number = await nextNumber(settings.change_prefix || 'LC', new Date()); const change = await prisma.licenceChange.create({ data: { 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 } } } }, licence: true } }); if (change) change.product = change.licence?.product || 'events'; if (!change) throw bad('Notice not found', 404); return { filename: `${change.number}.pdf`, content: await pdf.licenceChangePdf({ change, customer: change.customer, settings, founding: change.customer.founding, recipientEmail: compute.recipientFor(change.customer, contactOf(change.customer)), cycle: change.customer.billingCycle, product: change.product }) }; } module.exports = { nextNumber, loadInvoice, invoicePdfFor, draftForCustomer, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved, applyDueLicenceChanges, runBilling, remindDomainRenewals, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice, refundPayment, resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement, statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval, };