diff --git a/CHANGELOG.md b/CHANGELOG.md index 814ca07..6dc15fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- **An invoice that was paid and then refunded can be voided** (planned as 2.0.2). Before, Void + was refused while any payment was recorded against the invoice, and the only way round it was to + remove the payment, which lost the record that money came in and went back. A payment now has + **Refund** (invoice page → Payments): it stays on record with its receipt, no longer counts as + paid, and the statement shows the refund going back out. Void is allowed when no payment on the + invoice is left unrefunded. Migration `20261118120000_payment_refunds` (two new columns). + ## [2.0.1] - 2026-11-17 ### Added diff --git a/backend/prisma/migrations/20261118120000_payment_refunds/migration.sql b/backend/prisma/migrations/20261118120000_payment_refunds/migration.sql new file mode 100644 index 0000000..0c1834e --- /dev/null +++ b/backend/prisma/migrations/20261118120000_payment_refunds/migration.sql @@ -0,0 +1,3 @@ +-- 2.0.2: refunds. A refunded payment stays on record but no longer counts as paid. +ALTER TABLE "Payment" ADD COLUMN "refundedAt" DATE; +ALTER TABLE "Payment" ADD COLUMN "refundNote" TEXT; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 208909f..c414fce 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -397,6 +397,10 @@ model Payment { reference String? notes String? receiptSentAt DateTime? + // A refund: the money went back to the church. The payment stays on record (and its receipt), but + // no longer counts as paid, so the invoice can be voided or paid again. + refundedAt DateTime? @db.Date + refundNote String? createdById String? createdAt DateTime @default(now()) diff --git a/backend/src/routes/billing.js b/backend/src/routes/billing.js index 0828286..2e59683 100644 --- a/backend/src/routes/billing.js +++ b/backend/src/routes/billing.js @@ -168,6 +168,13 @@ router.delete('/payments/:id', wrap(async (req, res) => { res.json({ message: `Payment ${payment.receiptNumber} removed.` }); })); +// The money went back to the church (2.0.2): kept on record, no longer counts as paid. +router.post('/payments/:id/refund', wrap(async (req, res) => { + const payment = await billing.refundPayment(req.params.id, { on: req.body?.on, note: req.body?.note }); + await audit(req, 'payment_refunded', payment.id, { receipt: payment.receiptNumber, amountCents: payment.amountCents, invoice: payment.invoice?.number || null, note: payment.refundNote }); + res.json({ message: `Payment ${payment.receiptNumber} marked as refunded.${payment.invoice ? ` ${payment.invoice.number} is owing again; you can void it now.` : ''}` }); +})); + router.post('/payments/:id/resend', emailLimiter, wrap(async (req, res) => { await billing.resendReceipt(req.params.id); await audit(req, 'receipt_resent', req.params.id); diff --git a/backend/src/utils/billing/compute.js b/backend/src/utils/billing/compute.js index 6410f0a..286e18f 100644 --- a/backend/src/utils/billing/compute.js +++ b/backend/src/utils/billing/compute.js @@ -323,9 +323,15 @@ function planChangesOf(invoice) { return Array.isArray(pc) ? pc : [{ licenceId: invoice.licenceId || null, product: 'events', ...pc }]; } -/** What's been paid on an invoice and where it stands. `todayYmd` decides "overdue". */ +/** A payment still counts on `asOfYmd` unless it was refunded by then. */ +const notRefunded = asOfYmd => p => !p.refundedAt || ymd(p.refundedAt) > asOfYmd; + +/** + * What's been paid on an invoice and where it stands. `todayYmd` decides "overdue", and which + * refunds have happened (a refunded payment doesn't count as paid). + */ function invoiceState(invoice, todayYmd) { - const paidCents = (invoice.payments || []).reduce((s, p) => s + p.amountCents, 0); + const paidCents = (invoice.payments || []).filter(notRefunded(todayYmd)).reduce((s, p) => s + p.amountCents, 0); const balanceCents = invoice.totalCents - paidCents; let state = invoice.status; if (invoice.status === 'sent') { @@ -343,8 +349,9 @@ function invoiceDescription(invoice) { /** * A statement from `from` to `to` (inclusive): the balance brought forward, each sent invoice - * (debit) and payment (credit) in date order with a running balance, the closing balance, and - * invoices still owing. Drafts, approved-but-unsent and void invoices aren't on it. + * (debit), payment (credit) and refund (debit: the money went back) in date order with a running + * balance, the closing balance, and invoices still owing. Drafts, approved-but-unsent and void + * invoices aren't on it. */ function statement({ invoices, payments, from, to }) { const f = ymd(from); @@ -352,18 +359,21 @@ function statement({ invoices, payments, from, to }) { const live = invoices.filter(i => i.status === 'sent'); const before = d => ymd(d) < f; const within = d => ymd(d) >= f && ymd(d) <= t; + const refunds = payments.filter(p => p.refundedAt); const opening = live.filter(i => before(i.issueDate)).reduce((s, i) => s + i.totalCents, 0) - - payments.filter(p => before(p.paidOn)).reduce((s, p) => s + p.amountCents, 0); + - payments.filter(p => before(p.paidOn)).reduce((s, p) => s + p.amountCents, 0) + + refunds.filter(p => before(p.refundedAt)).reduce((s, p) => s + p.amountCents, 0); const entries = [ ...live.filter(i => within(i.issueDate)).map(i => ({ date: ymd(i.issueDate), kind: 'invoice', reference: i.number, description: invoiceDescription(i), debitCents: i.totalCents, creditCents: 0 })), ...payments.filter(p => within(p.paidOn)).map(p => ({ date: ymd(p.paidOn), kind: 'payment', reference: p.receiptNumber, description: `Payment received${p.invoice?.number ? ` for ${p.invoice.number}` : ''}${p.reference ? ` (ref ${p.reference})` : ''}`, debitCents: 0, creditCents: p.amountCents })), - ].sort((a, b) => a.date.localeCompare(b.date) || (a.kind === 'invoice' ? -1 : 1)); + ...refunds.filter(p => within(p.refundedAt)).map(p => ({ date: ymd(p.refundedAt), kind: 'refund', reference: p.receiptNumber, description: `Refund of ${p.receiptNumber}${p.refundNote ? ` (${p.refundNote})` : ''}`, debitCents: p.amountCents, creditCents: 0 })), + ].sort((a, b) => a.date.localeCompare(b.date) || (a.kind === 'invoice' ? -1 : b.kind === 'invoice' ? 1 : 0)); let balance = opening; for (const e of entries) { balance += e.debitCents - e.creditCents; e.balanceCents = balance; } - // Payments up to the statement date only. + // Payments up to the statement date only (invoiceState leaves out those refunded by then). const paidBy = p => ymd(p.paidOn) <= t; const outstanding = live .filter(i => ymd(i.issueDate) <= t) diff --git a/backend/src/utils/billing/index.js b/backend/src/utils/billing/index.js index b48e63a..e92c8d0 100644 --- a/backend/src/utils/billing/index.js +++ b/backend/src/utils/billing/index.js @@ -411,7 +411,8 @@ async function recalculateCustomerInvoice(invoice, settings) { 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); + // 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 } }); @@ -508,6 +509,20 @@ async function deletePayment(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); @@ -650,7 +665,7 @@ async function licenceChangePdfFor(id) { module.exports = { nextNumber, loadInvoice, invoicePdfFor, draftForCustomer, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved, - applyDueLicenceChanges, runBilling, remindDomainRenewals, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice, + applyDueLicenceChanges, runBilling, remindDomainRenewals, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice, refundPayment, resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement, statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval, }; diff --git a/backend/tests/billing.test.js b/backend/tests/billing.test.js index b301642..263f36c 100644 --- a/backend/tests/billing.test.js +++ b/backend/tests/billing.test.js @@ -346,6 +346,27 @@ describe('payments and statements', () => { expect(later.openingCents).toBe(35000); expect(later.closingCents).toBe(90000); }); + + test('a refunded payment no longer counts as paid, from the day it was refunded (2.0.2)', () => { + const refunded = { amountCents: 55000, paidOn: day('2026-12-02'), refundedAt: day('2026-12-10') }; + expect(invoiceState(inv('A', '2026-12-01', 55000, [refunded]), '2026-12-05').state).toBe('paid'); + expect(invoiceState(inv('A', '2026-12-01', 55000, [refunded]), '2026-12-10')).toMatchObject({ paidCents: 0, balanceCents: 55000 }); + }); + + test('a statement shows the refund going back out', () => { + const p = { receiptNumber: 'REC-9', amountCents: 55000, paidOn: day('2026-12-02'), refundedAt: day('2026-12-10'), refundNote: 'EFT back', invoice: { number: 'INV-9' } }; + const invoices = [inv('INV-9', '2026-12-01', 55000, [p])]; + const st = statement({ invoices, payments: [p], from: '2026-12-01', to: '2026-12-31' }); + expect(st.entries.map(e => [e.date, e.kind, e.debitCents, e.creditCents, e.balanceCents])).toEqual([ + ['2026-12-01', 'invoice', 55000, 0, 55000], + ['2026-12-02', 'payment', 0, 55000, 0], + ['2026-12-10', 'refund', 55000, 0, 55000], + ]); + expect(st.entries[2].description).toBe('Refund of REC-9 (EFT back)'); + expect(st.outstanding.map(o => o.balanceCents)).toEqual([55000]); + // The month after: brought forward includes the refund. + expect(statement({ invoices, payments: [p], from: '2027-01-01', to: '2027-01-31' }).openingCents).toBe(55000); + }); }); describe('the church\'s address (one per church, never discounted)', () => { diff --git a/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx b/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx index 9c0c3f9..c2bcbf7 100644 --- a/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx +++ b/frontend/src/app/(hub)/billing/invoices/[id]/page.tsx @@ -123,6 +123,15 @@ function InvoiceDetail({ id }: { id: string }) { } catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(null); } }; const pdf = (path: string) => openPdf(path).catch(e => setMsg({ type: "err", text: errorText(e) })); + const refund = async (p: Invoice["payments"][number]) => { + const note = prompt(`Mark ${p.receiptNumber} (${money(p.amountCents)}) as refunded to the church? It stays on record, no longer counts as paid, and the statement shows the refund. Note (optional, e.g. the EFT reference):`, ""); + if (note === null) return; + try { + const r = await api<{ message: string }>(`/api/admin/billing/payments/${p.id}/refund`, { method: "POST", body: { note } }); + setMsg({ type: "ok", text: r.message }); + load(); + } catch (e) { setMsg({ type: "err", text: errorText(e) }); } + }; const paymentAction = async (pid: string, what: "resend" | "delete") => { if (what === "delete" && !confirm("Remove this payment? Its receipt number won't be used again.")) return; try { @@ -150,7 +159,7 @@ function InvoiceDetail({ id }: { id: string }) { {inv.status === "sent" && inv.balanceCents > 0 && } {inv.status === "sent" && } - {inv.status !== "void" && inv.payments.length === 0 && } + {inv.status !== "void" && inv.payments.every(p => p.refundedAt) && } {inv.sendError &&
The last attempt to send it failed: {inv.sendError}. It's tried again every 15 minutes.
} @@ -227,11 +236,13 @@ function InvoiceDetail({ id }: { id: string }) {

Payments

{inv.payments.map(p => (
-
{p.receiptNumber} · {day(p.paidOn)}{money(p.amountCents)}
+
{p.receiptNumber} · {day(p.paidOn)}{money(p.amountCents)}
{METHOD[p.method] || p.method}{p.reference && p.reference !== inv.number ? ` · ${p.reference}` : ""}{p.receiptSentAt ? " · receipt sent" : ""}
+ {p.refundedAt &&
Refunded {day(p.refundedAt)}{p.refundNote ? ` · ${p.refundNote}` : ""}
}
+ {!p.refundedAt && }
diff --git a/frontend/src/lib/billing.tsx b/frontend/src/lib/billing.tsx index afd2a26..2f3d1e8 100644 --- a/frontend/src/lib/billing.tsx +++ b/frontend/src/lib/billing.tsx @@ -14,6 +14,7 @@ export type BillingTier = { name: string; upTo: number | null; monthly: number | export type Payment = { id: string; receiptNumber: string; customerId: string; invoiceId: string | null; amountCents: number; paidOn: string; method: string; reference: string | null; notes: string | null; receiptSentAt: string | null; createdAt: string; + refundedAt?: string | null; refundNote?: string | null; invoice?: { id: string; number: string } | null; customer?: { id: string; name: string }; };