Hub 2.0 step 4: billing per customer
- One invoice per customer per period for all its products; the schedule moves from Licence to Customer (migration copies it, so billing carries on unchanged); licences get billedFrom / billedUntil - Website (R99, 5 GB) and App (on active members) prices next to the Events tiers; founding prices per product, then bundles (15% two, 25% three); extra website storage R20 per 5 GB, never discounted - A product added to a billed customer starts after its free month; days before its first full period are prorated, never charged twice - Annual review per product (Events income, App members), one notice of licence change per product; invoices, PDFs and emails name products - Customer page: schedule, per-product billing, next-invoice preview - Invoices from before 2.0 kept as they were (still recalculable) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -166,7 +166,9 @@ router.post('/customers/:id/licences', wrap(async (req, res) => {
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
const product = req.body?.product ?? 'events';
|
||||
if (!isProduct(product)) throw bad('Product must be events, accounts, website or app.');
|
||||
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data: licenceData(req.body) });
|
||||
// A new Website licence is on its one plan, an App licence on the first tier (the review moves it).
|
||||
const data = { ...(product === 'website' ? { plan: 'Website' } : product === 'app' ? { plan: 'Mustard Seed' } : {}), ...licenceData(req.body) };
|
||||
const { licence, accounts } = await generateLicence(prisma, { customerId: customer.id, product, data });
|
||||
await audit(req, 'licence_generated', licence.id, { customer: customer.name, product, expiresAt: licence.expiresAt });
|
||||
if (accounts) await audit(req, 'licence_generated', accounts.id, { customer: customer.name, product: 'accounts', automatic: true });
|
||||
res.status(201).json({ ...licence, accountsLicence: accounts });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Billing API (1.7.0, admin login required): invoices, payments, statements, licence changes,
|
||||
* founding churches and each licence's billing set-up. The work is in utils/billing/.
|
||||
* founding churches, each customer's billing schedule and each licence's billing (Hub 2.0: one
|
||||
* invoice per customer for all its products). The work is in utils/billing/.
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
@@ -11,7 +12,8 @@ const { audit } = require('../utils/audit');
|
||||
const billing = require('../utils/billing');
|
||||
const compute = require('../utils/billing/compute');
|
||||
const { ymd, day, today } = require('../utils/billing/dates');
|
||||
const { TIERS } = require('../utils/billing/tiers');
|
||||
const { TIERS, PLANS, BUNDLE_PERCENT, STORAGE } = require('../utils/billing/tiers');
|
||||
const { addMonths } = require('../utils/billing/dates');
|
||||
const { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -43,7 +45,8 @@ function invoiceRow(invoice, todayYmd = ymd(today())) {
|
||||
periodStart: ymd(invoice.periodStart), periodEnd: ymd(invoice.periodEnd),
|
||||
customer: invoice.customer ? { id: invoice.customer.id, name: invoice.customer.name, founding: invoice.customer.founding } : undefined,
|
||||
payments: (invoice.payments || []).map(p => ({ ...p, paidOn: ymd(p.paidOn) })),
|
||||
licence: licence ? { id: licence.id, key: licence.key, plan: licence.plan, billingCycle: licence.billingCycle, installUrl: licence.install?.url || null } : null,
|
||||
licence: licence ? { id: licence.id, key: licence.key, product: licence.product, plan: licence.plan, installUrl: licence.install?.url || null } : null,
|
||||
planChanges: compute.planChangesOf(invoice),
|
||||
...compute.invoiceState(invoice, todayYmd),
|
||||
};
|
||||
}
|
||||
@@ -68,6 +71,7 @@ router.get('/overview', wrap(async (req, res) => {
|
||||
overdue: rows.filter(i => i.state === 'overdue').length,
|
||||
receivedThisMonthCents: payments.reduce((s, p) => s + p.amountCents, 0),
|
||||
tiers: TIERS,
|
||||
plans: PLANS,
|
||||
});
|
||||
}));
|
||||
|
||||
@@ -103,7 +107,7 @@ router.get('/invoices/:id', wrap(async (req, res) => {
|
||||
prisma.licenceChange.findMany({ where: { invoiceId: invoice.id }, orderBy: { createdAt: 'desc' } }),
|
||||
prisma.billingEmail.findMany({ where: { refId: invoice.id }, orderBy: { sentAt: 'desc' } }),
|
||||
]);
|
||||
res.json({ ...invoiceRow(invoice), licenceChanges: changes.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })), emails, tiers: TIERS });
|
||||
res.json({ ...invoiceRow(invoice), licenceChanges: changes.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })), emails, tiers: TIERS, plans: PLANS });
|
||||
}));
|
||||
|
||||
router.put('/invoices/:id', wrap(async (req, res) => {
|
||||
@@ -174,7 +178,26 @@ router.get('/payments/:id/pdf', wrap(async (req, res) => sendPdf(res, await bill
|
||||
|
||||
// ─── Customers: founding, billing details, statements ─────────────────────────
|
||||
|
||||
/** Every customer's billing at a glance: founding, licences' plans and next invoice, balance. */
|
||||
/** What a licence's product reports that its price depends on, for the billing screens. */
|
||||
function reported(l) {
|
||||
const stats = l.install?.stats || {};
|
||||
if (l.product === 'events') return { incomeBand: stats.income?.eventIncome12m || null };
|
||||
if (l.product === 'app') return { activeMembers: stats.activeMembers90d || null };
|
||||
if (l.product === 'website') return { storage: stats.storage || null };
|
||||
return {};
|
||||
}
|
||||
|
||||
/** A licence for the billing screens. */
|
||||
const billingLicence = l => ({
|
||||
id: l.id, key: l.key, product: l.product, plan: l.plan, status: l.status, customMonthlyCents: l.customMonthlyCents,
|
||||
billedFrom: ymd(l.billedFrom), billedUntil: ymd(l.billedUntil), billable: BILLABLE.includes(l.product),
|
||||
url: l.install?.url || null, ...reported(l),
|
||||
});
|
||||
|
||||
/** A customer's schedule for the billing screens. */
|
||||
const schedule = c => ({ billingCycle: c.billingCycle, billingStart: ymd(c.billingStart), nextInvoiceDate: ymd(c.nextInvoiceDate), reviewDate: ymd(c.reviewDate) });
|
||||
|
||||
/** Every customer's billing at a glance: founding, schedule, licences' plans, balance. */
|
||||
router.get('/customers', wrap(async (req, res) => {
|
||||
const t = ymd(today());
|
||||
const customers = await prisma.customer.findMany({
|
||||
@@ -185,9 +208,10 @@ router.get('/customers', wrap(async (req, res) => {
|
||||
const states = c.invoices.map(i => compute.invoiceState(i, t));
|
||||
return {
|
||||
id: c.id, name: c.name, founding: c.founding, foundingSince: ymd(c.foundingSince), foundingNote: c.foundingNote, billingEmail: c.billingEmail,
|
||||
...schedule(c),
|
||||
balanceCents: states.reduce((s, x) => s + Math.max(0, x.balanceCents), 0),
|
||||
overdue: states.filter(x => x.state === 'overdue').length,
|
||||
licences: c.licences.map(l => ({ id: l.id, key: l.key, plan: l.plan, status: l.status, billingCycle: l.billingCycle, nextInvoiceDate: ymd(l.nextInvoiceDate), reviewDate: ymd(l.reviewDate), customMonthlyCents: l.customMonthlyCents, url: l.install?.url || null })),
|
||||
licences: c.licences.map(billingLicence),
|
||||
};
|
||||
}));
|
||||
}));
|
||||
@@ -206,23 +230,35 @@ router.get('/customers/:id', wrap(async (req, res) => {
|
||||
});
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
const invoices = customer.invoices.map(i => invoiceRow(i, t));
|
||||
const install = customer.licences.find(l => l.install && !l.install.releasedAt)?.install || null;
|
||||
res.json({
|
||||
id: customer.id, name: customer.name, contactName: customer.contactName, email: customer.email,
|
||||
billingEmail: customer.billingEmail, billingAddress: customer.billingAddress,
|
||||
founding: customer.founding, foundingSince: ymd(customer.foundingSince), foundingNote: customer.foundingNote,
|
||||
sendsTo: compute.recipientFor(customer, install),
|
||||
...schedule(customer),
|
||||
sendsTo: compute.recipientFor(customer, compute.contactInstall(customer.licences)),
|
||||
balanceCents: invoices.filter(i => i.status === 'sent').reduce((s, i) => s + Math.max(0, i.balanceCents), 0),
|
||||
licences: customer.licences.map(l => ({
|
||||
id: l.id, key: l.key, plan: l.plan, status: l.status, billingCycle: l.billingCycle, billingStart: ymd(l.billingStart),
|
||||
nextInvoiceDate: ymd(l.nextInvoiceDate), reviewDate: ymd(l.reviewDate), customMonthlyCents: l.customMonthlyCents,
|
||||
url: l.install?.url || null, incomeBand: l.install?.stats?.income?.eventIncome12m || null,
|
||||
})),
|
||||
licences: customer.licences.map(billingLicence),
|
||||
invoices,
|
||||
payments: customer.payments.map(p => ({ ...p, paidOn: ymd(p.paidOn) })),
|
||||
licenceChanges: customer.licenceChanges.map(c => ({ ...c, effectiveDate: ymd(c.effectiveDate) })),
|
||||
emails: customer.billingEmails,
|
||||
tiers: TIERS,
|
||||
plans: PLANS,
|
||||
bundlePercent: BUNDLE_PERCENT,
|
||||
storage: STORAGE,
|
||||
});
|
||||
}));
|
||||
|
||||
// The next invoice as it would be drafted now (nothing is saved): its lines, discounts and total.
|
||||
router.get('/customers/:id/preview', wrap(async (req, res) => {
|
||||
const { getSettings } = require('../utils/settings');
|
||||
const customer = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: { include: { install: true } } } });
|
||||
if (!customer) throw bad('Customer not found', 404);
|
||||
if (customer.billingCycle === 'none' || !customer.nextInvoiceDate) return res.json({ billed: false });
|
||||
const { invoice, empty } = compute.draftCustomerInvoice({ customer, licences: customer.licences, settings: await getSettings() });
|
||||
res.json({
|
||||
billed: true, empty,
|
||||
invoice: { ...invoice, issueDate: ymd(invoice.issueDate), dueDate: ymd(invoice.dueDate), periodStart: ymd(invoice.periodStart), periodEnd: ymd(invoice.periodEnd), planChanges: invoice.planChange || [] },
|
||||
});
|
||||
}));
|
||||
|
||||
@@ -241,8 +277,29 @@ router.put('/customers/:id', wrap(async (req, res) => {
|
||||
if (e && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) throw bad('That email address doesn\'t look right.');
|
||||
data.billingEmail = e;
|
||||
}
|
||||
const customer = await prisma.customer.update({ where: { id: req.params.id }, data }).catch(() => { throw bad('Customer not found', 404); });
|
||||
await audit(req, 'customer_billing_updated', customer.id, { changed: Object.keys(data), founding: customer.founding });
|
||||
// The schedule (Hub 2.0: per customer, for all its products).
|
||||
if (b.billingCycle !== undefined) {
|
||||
if (!['none', 'monthly', 'yearly'].includes(b.billingCycle)) throw bad('Choose monthly, yearly or not billed.');
|
||||
data.billingCycle = b.billingCycle;
|
||||
}
|
||||
for (const f of ['billingStart', 'nextInvoiceDate', 'reviewDate']) if (b[f] !== undefined) data[f] = dayOrNull(b[f]);
|
||||
const existing = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: true } });
|
||||
if (!existing) throw bad('Customer not found', 404);
|
||||
const merged = { ...existing, ...data };
|
||||
if (merged.billingCycle !== 'none') {
|
||||
if (!merged.billingStart) throw bad('Set the date billing starts.');
|
||||
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
|
||||
// The first review is a year after billing starts.
|
||||
if (!merged.reviewDate && b.reviewDate === undefined) data.reviewDate = addMonths(merged.billingStart, 12);
|
||||
}
|
||||
// Starting billing: the products not charged yet are charged from the billing start.
|
||||
const start = existing.billingCycle === 'none' && merged.billingCycle !== 'none' ? merged.billingStart : null;
|
||||
const startLicences = start ? existing.licences.filter(l => BILLABLE.includes(l.product) && l.status === 'active' && !l.billedFrom) : [];
|
||||
const [customer] = await prisma.$transaction([
|
||||
prisma.customer.update({ where: { id: existing.id }, data }),
|
||||
...startLicences.map(l => prisma.licence.update({ where: { id: l.id }, data: { billedFrom: day(start) } })),
|
||||
]);
|
||||
await audit(req, 'customer_billing_updated', customer.id, { changed: Object.keys(data), founding: customer.founding, billingCycle: customer.billingCycle, licencesStarted: startLicences.length });
|
||||
res.json({ ok: true });
|
||||
}));
|
||||
|
||||
@@ -261,16 +318,20 @@ router.post('/customers/:id/statement/email', emailLimiter, wrap(async (req, res
|
||||
|
||||
// ─── Licence billing set-up ───────────────────────────────────────────────────
|
||||
|
||||
// Hub 2.0: when a licence is charged from (blank = not charged), and an optional custom price.
|
||||
// The schedule is the customer's.
|
||||
router.put('/licences/:id', wrap(async (req, res) => {
|
||||
const b = req.body || {};
|
||||
const existing = await prisma.licence.findUnique({ where: { id: req.params.id } });
|
||||
if (!existing) throw bad('Licence not found', 404);
|
||||
const data = {};
|
||||
if (b.billingCycle !== undefined) {
|
||||
if (!['none', 'monthly', 'yearly'].includes(b.billingCycle)) throw bad('Choose monthly, yearly or not billed.');
|
||||
data.billingCycle = b.billingCycle;
|
||||
if (b.billedFrom !== undefined) {
|
||||
data.billedFrom = dayOrNull(b.billedFrom);
|
||||
if (data.billedFrom && !BILLABLE.includes(existing.product)) throw bad(`${PRODUCT_NAMES[existing.product]} is free: it's never invoiced.`);
|
||||
if (data.billedFrom && existing.billedUntil && ymd(data.billedFrom) <= ymd(existing.billedUntil)) {
|
||||
throw bad(`It's invoiced up to ${ymd(existing.billedUntil)} already: choose a later date, or correct the invoices by hand.`);
|
||||
}
|
||||
}
|
||||
for (const f of ['billingStart', 'nextInvoiceDate', 'reviewDate']) if (b[f] !== undefined) data[f] = dayOrNull(b[f]);
|
||||
if (b.customMonthlyCents !== undefined) {
|
||||
if (b.customMonthlyCents === null || b.customMonthlyCents === '') data.customMonthlyCents = null;
|
||||
else {
|
||||
@@ -279,19 +340,8 @@ router.put('/licences/:id', wrap(async (req, res) => {
|
||||
data.customMonthlyCents = n;
|
||||
}
|
||||
}
|
||||
const merged = { ...existing, ...data };
|
||||
// Until billing per customer (Hub 2.0 step 4) only Events has prices; Accounts is never invoiced.
|
||||
if (merged.billingCycle !== 'none' && !BILLABLE.includes(existing.product)) {
|
||||
throw bad(`${PRODUCT_NAMES[existing.product]} licences can't be invoiced yet.`);
|
||||
}
|
||||
if (merged.billingCycle !== 'none') {
|
||||
if (!merged.billingStart) throw bad('Set the date billing starts.');
|
||||
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
|
||||
// The first review is a year after billing starts.
|
||||
if (!merged.reviewDate && b.reviewDate === undefined) data.reviewDate = require('../utils/billing/dates').addMonths(merged.billingStart, 12);
|
||||
}
|
||||
const licence = await prisma.licence.update({ where: { id: existing.id }, data });
|
||||
await audit(req, 'licence_billing_updated', licence.id, { changed: Object.keys(data), billingCycle: licence.billingCycle });
|
||||
await audit(req, 'licence_billing_updated', licence.id, { changed: Object.keys(data), billedFrom: ymd(licence.billedFrom) });
|
||||
res.json({ ok: true });
|
||||
}));
|
||||
|
||||
|
||||
Reference in New Issue
Block a user