Billing: refund a payment; void invoices that aren't paid (none, or all refunded)
Void was refused while any payment was recorded, so a paid-then-refunded invoice could only be voided by deleting the payment and losing the record. A payment can now be marked refunded: kept with its receipt, no longer counted as paid, shown on the statement as money going back out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user