Merge branch 'feat/hub2-billing' into release/2.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 16:18:25 +02:00
co-authored by Claude Opus 5.5
21 changed files with 1081 additions and 316 deletions
+17 -3
View File
@@ -43,15 +43,29 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`).
install of that product runs that version or later, counting every release the update would
bring. The install page shows what's missing; the Releases page shows each release's needs.
Protocol v2 replies carry them (`requires`, contracts 1.1.0); v1 replies are unchanged.
- **Billing per customer** (step 4): one invoice per church per period for all its products. The
billing schedule (cycle, start, next invoice, review) is the church's; each licence has the date
it's **charged from** and the day it's invoiced up to. Prices for the **Church Website** (R99, 5 GB
included) and the **Church App** (R99 to R999 on active members, Network priced per church), next to
the Cross Events tiers. **Bundles** 15% off two products and 25% off three, after the founding
prices; Accounts is free and never counts. **Extra website storage** R20 per 5 GB a month, never
discounted (12 months' price when billed yearly). A product added to a billed church gets its
**free month**, then the days before its first full period are charged by the day. The annual
review moves each product's tier (Cross Events on event income, the App on active members), with
a notice of licence change per product. Customer page → Billing: the schedule, each product's
billing and the **next invoice** as it would be drafted today (`GET …/customers/:id/preview`).
Invoices, PDFs and emails name the products. Invoices made before 2.0 (one per licence) stay as
they were, and their drafts can still be recalculated.
### Changed
- **Cross Code Hub** in the dashboard, emails, PDFs and new two-factor set-ups (the `hel1.`
licence-token prefix stays: it's part of the protocol).
- Installs register with protocol v1 only with a Cross Events licence (`409 WRONG_PRODUCT`
otherwise); the other products register with protocol v2 (step 2). Only Cross Events licences
can be invoiced until billing per customer (step 4).
- Migrations `20261104132032_products`, `20261104150000_releases_per_product`.
otherwise); the other products register with protocol v2 (step 2).
- Migrations `20261104132032_products`, `20261104150000_releases_per_product`,
`20261104170000_billing_per_customer` (moves each billed licence's schedule to its customer,
so billing carries on unchanged).
## [1.7.0] - 2026-11-03
+20 -11
View File
@@ -70,15 +70,24 @@ the emails, `index.js` the job and actions) and `backend/src/routes/billing.js`.
1. **Set up** Settings → **Billing**: business and banking details, VAT, timing and numbering. Set the
**alert email** (Settings → Alerts): approval requests go there. SMTP must work.
2. **Per church** (customer page → Billing): founding church (35% off every tier), billing email and
postal address, and for each licence: monthly or yearly (10 months' price for 12), the date billing
started (its day of the month is the billing day), the next invoice date, the next annual tier
review and an optional custom monthly price (e.g. the Network tier).
3. **The job** (every 15 minutes): **14 days** before a licence's next invoice date it drafts the
invoice and emails it to you with the draft PDF. At the yearly **review** the draft uses the site's
12-month event-income band (Cross Events 2.0.2+) and can move the tier up or down; drafts in between
keep the tier. **Approve** it on Billing (you can change its lines, dates, recipient and notes
first); a tier change sends the church a notice of licence change at once. Approved invoices go out
2. **Per church** (customer page → Billing; Hub 2.0: **one invoice per church for all its products**):
founding church (35% off every tier), billing email and postal address, the **billing schedule**
(monthly or yearly — 10 months' price for 12 —, the date billing started, whose day of the month
is the billing day, the next invoice date and the next annual tier review), and for each product
the date it's **charged from** (blank = not charged, e.g. a trial; Accounts is always free) and an
optional custom monthly price (e.g. a Network tier). **Next invoice** shows the next draft as it
would be made today.
3. **The job** (every 15 minutes): **14 days** before a church's next invoice date it drafts the
invoice and emails it to you with the draft PDF. Each product is a line at its price; a founding
church gets the founding price as a line under each; **bundles** take 15% off two products and 25%
off three (after founding); **extra website storage** (R20 per 5 GB above 5 GB, from the website's
heartbeat) is added last and never discounted (12 months' price on a yearly invoice). A product
added to a church that's billed already gets its **free month**, then the days before its first
full period are charged by the day (a year's price over 365 days). At the yearly **review** the
draft uses what each product reports — Cross Events its 12-month event-income band (2.0.2+), the
App its active-member band — and can move each tier up or down; drafts in between keep the tiers.
**Approve** it on Billing (you can change its lines, dates, recipient and notes first); each tier
change sends the church a notice of licence change at once. Approved invoices go out
**on their date from 08:00** (South African time) to the billing email, else the site's admin
contact, else the customer's email; the tier change takes effect when that invoice goes out. If a
date comes and it isn't approved, you're emailed once and it waits.
@@ -89,8 +98,8 @@ the emails, `index.js` the job and actions) and `backend/src/routes/billing.js`.
Invoices are **in advance** (the invoice dated the 1st covers that month). **VAT**: not registered →
plain invoices with no VAT; once registered, tick it in Settings → Billing: prices are then
VAT-inclusive (totals unchanged), documents become tax invoices with the VAT number and the VAT
included. The tiers are in `backend/src/utils/billing/tiers.js` and `frontend/src/lib/tiers.ts` (a test
checks they match) and on crosscode-site `src/data/pricing.mjs`. `node backend/scripts/sample-billing-pdfs.js <dir>`
included. The prices of every product are in `backend/src/utils/billing/tiers.js` and
`frontend/src/lib/tiers.ts` (a test checks they match) and on crosscode-site `src/data/pricing.mjs`. `node backend/scripts/sample-billing-pdfs.js <dir>`
writes sample PDFs (no database needed) to check the layout.
## The licence signing key
@@ -0,0 +1,47 @@
-- Hub 2.0: billing per customer. The schedule (cycle, start, next invoice, review) moves from the
-- licence to the customer, so one invoice covers all of a customer's products; each licence keeps
-- when it's charged from (billedFrom) and up to which day it has been invoiced (billedUntil).
-- Existing billing carries on unchanged: each billed licence's schedule becomes its customer's.
-- AlterTable: the customer's schedule, and the invoice's basis.
ALTER TABLE "Customer" ADD COLUMN "billingCycle" "BillingCycle" NOT NULL DEFAULT 'none',
ADD COLUMN "billingStart" DATE,
ADD COLUMN "nextInvoiceDate" DATE,
ADD COLUMN "reviewDate" DATE;
ALTER TABLE "Invoice" ADD COLUMN "basis" JSONB;
ALTER TABLE "Licence" ADD COLUMN "billedFrom" DATE,
ADD COLUMN "billedUntil" DATE;
-- Copy: a customer takes the schedule of its billed licence (Hub 1.7 billed one Events licence per
-- customer; if there were several, the one invoiced next).
UPDATE "Customer" c
SET "billingCycle" = l."billingCycle", "billingStart" = l."billingStart", "nextInvoiceDate" = l."nextInvoiceDate", "reviewDate" = l."reviewDate"
FROM (
SELECT DISTINCT ON ("customerId") "customerId", "billingCycle", "billingStart", "nextInvoiceDate", "reviewDate"
FROM "Licence"
WHERE "billingCycle" <> 'none' AND status <> 'revoked'
ORDER BY "customerId", "nextInvoiceDate" ASC NULLS LAST, "createdAt" ASC
) l
WHERE c.id = l."customerId";
-- A billed licence is charged from when its billing started, and has been invoiced up to the day
-- before its next invoice.
UPDATE "Licence"
SET "billedFrom" = COALESCE("billingStart", "nextInvoiceDate"),
"billedUntil" = CASE WHEN "nextInvoiceDate" IS NOT NULL THEN "nextInvoiceDate" - 1 END
WHERE "billingCycle" <> 'none';
-- The licence's own schedule is gone.
ALTER TABLE "Licence" DROP COLUMN "billingCycle",
DROP COLUMN "billingStart",
DROP COLUMN "nextInvoiceDate",
DROP COLUMN "reviewDate";
-- Invoices: one per licence and period before 2.0 (kept as history); one per customer and period
-- from 2.0 (licenceId null), not counting void ones.
DROP INDEX "Invoice_licenceId_periodStart_key";
CREATE INDEX "Invoice_licenceId_periodStart_idx" ON "Invoice"("licenceId", "periodStart");
CREATE UNIQUE INDEX "Invoice_customerId_periodStart_open_key" ON "Invoice"("customerId", "periodStart")
WHERE "licenceId" IS NULL AND "periodStart" IS NOT NULL AND status <> 'void';
+26 -12
View File
@@ -40,6 +40,16 @@ model Customer {
founding Boolean @default(false)
foundingSince DateTime? @db.Date
foundingNote String?
// Hub 2.0: one invoice per customer per period for all its products (moved from Licence).
// none = not invoiced. Invoices are in advance: each covers the period starting on its date.
billingCycle BillingCycle @default(none)
// The day billing started; its day of the month is the billing day.
billingStart DateTime? @db.Date
// The start of the next period to invoice (the draft is made 14 days before).
nextInvoiceDate DateTime? @db.Date
// The next annual tier review: the first invoice for a period starting on or after it uses
// what each product reports (Events: 12-month event income; App: active members).
reviewDate DateTime? @db.Date
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
@@ -85,16 +95,12 @@ model Licence {
// Markup on the real AI cost, in %. Null = the Hub default (Settings → AI).
aiMarkupPercent Int?
notes String?
// Billing (1.7.0). none = not invoiced (trial, free). Invoices are in advance: each covers
// the period starting on its date.
billingCycle BillingCycle @default(none)
// The day billing started; its day of the month is the billing day.
billingStart DateTime? @db.Date
// The start of the next period to invoice (the draft is made 14 days before).
nextInvoiceDate DateTime? @db.Date
// The next annual tier review: the first invoice for a period starting on or after it
// uses the last 12 months' event income.
reviewDate DateTime? @db.Date
// Billing (Hub 2.0: the schedule is the customer's). The licence is charged from billedFrom
// (null = not charged: a trial, free, or Accounts); a product added to a customer already
// billed starts after its free month. billedUntil is the last day an invoice has covered, so a
// product that starts mid-period gets a prorated line on the next invoice.
billedFrom DateTime? @db.Date
billedUntil DateTime? @db.Date
// A price per month instead of the tier's (e.g. the Network tier), in cents.
customMonthlyCents Int?
createdAt DateTime @default(now())
@@ -318,7 +324,9 @@ model Invoice {
incomeBand String?
reviewed Boolean @default(false)
founding Boolean @default(false)
// A tier change that comes with this invoice: { from, to, fromMonthlyCents, toMonthlyCents }.
// Tier changes that come with this invoice. Hub 2.0: a list, one per product,
// [{ licenceId, product, from, to, fromMonthlyCents, toMonthlyCents, band }]; before 2.0 one
// object { from, to, … } (read with compute.planChangesOf).
planChange Json?
// [{ description, quantity, unitCents, amountCents }]
lines Json
@@ -330,6 +338,9 @@ model Invoice {
// Things Joshua should check before approving (e.g. no income band reported).
warnings String[] @default([])
recipientEmail String?
// Hub 2.0: what a customer invoice was worked out from, so a draft can be recalculated:
// { licences: [{ id, billedUntil }], planChangeDropped }.
basis Json?
approvedAt DateTime?
approvedById String?
approvalEmailedAt DateTime?
@@ -344,7 +355,10 @@ model Invoice {
payments Payment[]
licenceChanges LicenceChange[]
@@unique([licenceId, periodStart])
// Before Hub 2.0 an invoice was for one licence's period. From 2.0 it's for the customer's
// period (licenceId null): one per customer per period that isn't void, enforced by the partial
// unique index "Invoice_customerId_periodStart_open_key" (migration …_billing_per_customer).
@@index([licenceId, periodStart])
@@index([status, issueDate])
@@index([customerId])
}
+15 -6
View File
@@ -7,17 +7,26 @@ const fs = require('fs');
const path = require('path');
const { DEFAULTS } = require('../src/utils/settings');
const pdf = require('../src/utils/billing/pdf');
const { draftInvoice, invoiceState, statement } = require('../src/utils/billing/compute');
const { draftCustomerInvoice, invoiceState, statement } = require('../src/utils/billing/compute');
const out = path.resolve(process.argv[2] || 'billing-samples');
fs.mkdirSync(out, { recursive: true });
const settings = { ...DEFAULTS, bank_name: 'Sample Bank', bank_account_name: 'Cross Code', bank_account_number: '1234 567 890', bank_branch_code: '250655', bank_account_type: 'Cheque' };
const customer = { id: 'c1', name: 'Cedarwood Community Church', contactName: 'Thandi Nkosi', billingAddress: '12 Oak Street, Meyerton, 1961', email: 'office@cedarwood.example', founding: true };
const install = { adminContact: { email: 'admin@cedarwood.example' }, stats: { income: { eventIncome12m: 'R250 001–R400 000' } } };
const licence = { id: 'l1', plan: 'Sprout', billingCycle: 'monthly', billingStart: new Date('2026-01-01'), nextInvoiceDate: new Date('2027-01-01'), reviewDate: new Date('2027-01-01'), customMonthlyCents: null };
// A founding church with all three products at its annual review: Events moves up a tier, the App
// joined part-way through December, and the website uses 7 GB.
const customer = {
id: 'c1', name: 'Cedarwood Community Church', contactName: 'Thandi Nkosi', billingAddress: '12 Oak Street, Meyerton, 1961', email: 'office@cedarwood.example', founding: true,
billingCycle: 'monthly', billingStart: new Date('2026-01-01'), nextInvoiceDate: new Date('2027-01-01'), reviewDate: new Date('2027-01-01'),
};
const GB = 1024 ** 3;
const licences = [
{ id: 'l1', product: 'events', status: 'active', plan: 'Sprout', customMonthlyCents: null, billedFrom: new Date('2026-01-01'), billedUntil: new Date('2026-12-31'), install: { product: 'events', adminContact: { email: 'admin@cedarwood.example' }, stats: { income: { eventIncome12m: 'R250 001–R400 000' } } } },
{ id: 'l2', product: 'website', status: 'active', plan: 'Website', customMonthlyCents: null, billedFrom: new Date('2026-06-01'), billedUntil: new Date('2026-12-31'), install: { product: 'website', stats: { storage: { usedBytes: 7 * GB, includedBytes: 5 * GB } } } },
{ id: 'l3', product: 'app', status: 'active', plan: 'Mustard Seed', customMonthlyCents: null, billedFrom: new Date('2026-12-15'), billedUntil: null, install: { product: 'app', stats: { activeMembers90d: '0–100' } } },
];
(async () => {
const { invoice: draft } = draftInvoice({ licence, customer, install, settings });
const { invoice: draft } = draftCustomerInvoice({ customer, licences, settings });
const invoice = { ...draft, id: 'i1', number: 'INV-2027-0001', status: 'sent', notes: null };
const payment = { id: 'p1', receiptNumber: 'REC-2027-0001', amountCents: 30000, paidOn: new Date('2027-01-05'), method: 'eft', reference: 'INV-2027-0001' };
const state = invoiceState({ ...invoice, payments: [payment] }, '2027-01-06');
@@ -28,6 +37,6 @@ const licence = { id: 'l1', plan: 'Sprout', billingCycle: 'monthly', billingStar
const st = statement({ invoices: [older, { ...invoice, payments: [payment] }], payments: [{ ...payment, invoice }], from: '2026-12-15', to: '2027-01-31' });
fs.writeFileSync(path.join(out, 'statement.pdf'), await pdf.statementPdf({ statement: st, customer, settings, recipientEmail: invoice.recipientEmail }));
const change = { number: 'LC-2026-0001', fromPlan: 'Sprout', toPlan: 'Grow', fromMonthlyCents: 55000, toMonthlyCents: 85000, effectiveDate: new Date('2027-01-01'), incomeBand: 'R250 001–R400 000', createdAt: new Date('2026-12-18') };
fs.writeFileSync(path.join(out, 'licence-change.pdf'), await pdf.licenceChangePdf({ change, customer, settings, founding: true, recipientEmail: invoice.recipientEmail, cycle: 'monthly' }));
fs.writeFileSync(path.join(out, 'licence-change.pdf'), await pdf.licenceChangePdf({ change, customer, settings, founding: true, recipientEmail: invoice.recipientEmail, cycle: 'monthly', product: 'events' }));
console.log(`samples in ${out}`);
})();
+3 -1
View File
@@ -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 });
+81 -31
View File
@@ -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 });
}));
+202 -53
View File
@@ -2,19 +2,34 @@
* Billing calculations, pure (no database): what an invoice for a period contains, totals and
* VAT, where an invoice stands with its payments, and a statement.
*
* Rules (decided 2026-11-03):
* - Invoices are in advance: the invoice dated the 1st covers the period starting that day.
* - The tier is reviewed once a year: the first invoice for a period starting on or after the
* licence's reviewDate uses the 12-month event-income band; invoices in between keep the tier.
* Rules (decided 2026-11-03 and 2026-11-04, Hub 2.0):
* - One invoice per customer per period, for all its products. Invoices are in advance: the
* invoice dated the 1st covers the period starting that day.
* - Each product is priced on its own plan (prices in tiers.js). Tiers are reviewed once a year:
* the first invoice for a period starting on or after the customer's reviewDate uses what each
* product reports (Events: 12-month event income; App: active members); invoices in between keep
* the tier.
* - Yearly billing is 10 months' price for 12 months. Founding churches pay the founding price.
* - Bundles: 15% off two products, 25% off three, on the products after founding (Accounts is free
* and never counts).
* - Add-ons (extra website storage) are never discounted: no founding, bundle or yearly discount.
* - A product that starts part-way through a period (after its free month, decision 3) is charged
* by the day for the days before its first full period: on the invoice for the period it starts
* in, or the next one if that was already invoiced.
* - Not VAT registered: no VAT. Once registered, prices are VAT-inclusive (totals unchanged).
*/
const { tierNamed, tierForBand, planPrice, YEARLY_MONTHS, FOUNDING_PERCENT } = require('./tiers');
const { ymd, day, addDays, addMonths, periodLabel } = require('./dates');
const {
tierNamed, reviewTier, planPrice, extraStorageBlocks, STORAGE, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
} = require('./tiers');
const { ymd, day, addDays, addMonths, periodLabel, shortDate } = require('./dates');
const { PRODUCTS, PRODUCT_NAMES, BILLABLE } = require('../products');
const anchorDayOf = licence => day(licence.billingStart || licence.nextInvoiceDate).getUTCDate();
const anchorDayOf = schedule => day(schedule.billingStart || schedule.nextInvoiceDate).getUTCDate();
const monthsIn = cycle => (cycle === 'yearly' ? 12 : 1);
const DAY = 864e5;
const daysBetween = (a, b) => Math.round((day(b) - day(a)) / DAY) + 1;
const later = (a, b) => (ymd(a) >= ymd(b) ? day(a) : day(b));
/** Who an invoice goes to: the customer's billing email, the site's admin contact, the customer's email. */
function recipientFor(customer, install) {
@@ -22,6 +37,12 @@ function recipientFor(customer, install) {
return customer?.billingEmail || contact || customer?.email || null;
}
/** The install whose admin contact invoices fall back on: Events first, then any in use. */
function contactInstall(licences) {
const installs = licences.map(l => l.install).filter(i => i && !i.releasedAt);
return installs.find(i => i.product === 'events' && i.adminContact?.email) || installs.find(i => i.adminContact?.email) || installs[0] || null;
}
/** Cleans invoice lines from the form: [{ description, quantity, unitCents, amountCents }]. */
function cleanLines(lines) {
if (!Array.isArray(lines)) throw Object.assign(new Error('Lines must be a list.'), { status: 400 });
@@ -48,8 +69,8 @@ function totals(lines, settings = {}) {
}
/**
* The lines for a plan over a period: the tier's price (×10 for a year) and, for a founding
* church, the founding discount as its own line. Returns { lines, warning? }.
* Before Hub 2.0: the lines for one Cross Events licence's plan over a period. Kept to recalculate
* drafts made by Hub 1.7 (licenceId set). Returns { lines, warning? }.
*/
function planLines({ plan, customMonthlyCents, cycle, periodStart, periodEnd, founding }) {
const price = planPrice(plan, customMonthlyCents);
@@ -70,73 +91,198 @@ function planLines({ plan, customMonthlyCents, cycle, periodStart, periodEnd, fo
return { lines };
}
/**
* The draft invoice for a licence's next period (licence.nextInvoiceDate), and how the licence
* moves on. `install` gives the income band (stats.income.eventIncome12m) and admin contact.
* Returns { invoice, licenceUpdate }.
*/
function draftInvoice({ licence, customer, install, settings = {} }) {
const cycle = licence.billingCycle;
if (cycle !== 'monthly' && cycle !== 'yearly') throw new Error('This licence isn\'t billed.');
const anchor = anchorDayOf(licence);
const periodStart = day(licence.nextInvoiceDate);
const nextStart = addMonths(periodStart, monthsIn(cycle), anchor);
const periodEnd = addDays(nextStart, -1);
const warnings = [];
/** "Cross Events, Grow tier" · "Church Website" · "Church App, Small Group tier". */
function productLabel(product, plan) {
const name = PRODUCT_NAMES[product];
if (product === 'website' && tierNamed(plan, 'website')) return name;
const tier = tierNamed(plan, product);
return `${name}, ${tier ? `${tier.name} tier` : plan}`;
}
// The yearly review: the first period starting on or after reviewDate.
const reviewed = !!licence.reviewDate && ymd(periodStart) >= ymd(licence.reviewDate);
const band = install?.stats?.income?.eventIncome12m || null;
let plan = licence.plan;
let planChange = null;
if (reviewed) {
const tier = tierForBand(band);
if (!tier) {
warnings.push(band
? `The site reports its income as "${band}", which can't be placed in a tier (Cross Events before 2.0.2). The tier stays ${plan}.`
: `The site hasn't reported its 12-month event income (it needs Cross Events 2.0.2 or later). The tier stays ${plan}.`);
} else if (licence.customMonthlyCents != null) {
if (tier.name !== plan) warnings.push(`Its income (${band}) is in the ${tier.name} tier, but the licence has a custom price, so it's kept. Change it by hand if needed.`);
} else if (tier.name !== plan) {
const from = planPrice(plan);
const to = planPrice(tier.name);
planChange = { from: plan, to: tier.name, fromMonthlyCents: from?.monthlyCents ?? null, toMonthlyCents: to?.monthlyCents ?? null, band };
plan = tier.name;
/** The tier review for one licence: { plan, planChange, warning }. */
function reviewLicence(licence, product) {
const { tier, band } = reviewTier(product, licence.install);
const plan = licence.plan;
if (tier === undefined) return { plan, planChange: null, warning: null, band };
const what = product === 'events' ? '12-month event income' : 'active members (last 90 days)';
if (!tier) {
const needs = product === 'events' ? ' (it needs Cross Events 2.0.2 or later)' : '';
return {
plan, planChange: null, band,
warning: band
? `${PRODUCT_NAMES[product]} reports its ${what} as "${band}", which can't be placed in a tier. The tier stays ${plan}.`
: `${PRODUCT_NAMES[product]} hasn't reported its ${what}${needs}. The tier stays ${plan}.`,
};
}
if (licence.customMonthlyCents != null) {
return { plan, planChange: null, band, warning: tier.name !== plan ? `${PRODUCT_NAMES[product]}: its ${what} (${band}) is in the ${tier.name} tier, but the licence has a custom price, so it's kept. Change it by hand if needed.` : null };
}
if (tier.name === plan) return { plan, planChange: null, warning: null, band };
const from = planPrice(plan, null, product);
const to = planPrice(tier.name, null, product);
return {
plan: tier.name, band, warning: null,
planChange: { licenceId: licence.id, product, from: plan, to: tier.name, fromMonthlyCents: from?.monthlyCents ?? null, toMonthlyCents: to?.monthlyCents ?? null, band },
};
}
/**
* A customer's invoice lines for a period: each billed product (with a prorated line for days
* owed before the period), its founding discount, the bundle discount, then add-ons. Pure.
*
* `licences` are the customer's licences with their install (`billedUntil` as it was before this
* period was invoiced). Returns { lines, plan, planChanges, warnings, licenceUpdates, products,
* eventsBand }.
*/
function customerInvoiceLines({ customer, licences, period, reviewed }) {
const { start, end, cycle } = period;
const months = cycle === 'yearly' ? YEARLY_MONTHS : 1;
// By the day: a year's price over 365 days (10 months' for yearly billing).
const perDay = cents => (cents * (cycle === 'yearly' ? YEARLY_MONTHS : 12)) / 365;
const founding = !!customer.founding;
const productLines = [];
const addOns = [];
const warnings = [];
const planChanges = [];
const licenceUpdates = [];
const products = [];
const plans = [];
let eventsBand = null;
const billed = licences
.filter(l => l.status === 'active' && BILLABLE.includes(l.product) && l.billedFrom && ymd(l.billedFrom) <= ymd(end))
.sort((a, b) => PRODUCTS.indexOf(a.product) - PRODUCTS.indexOf(b.product));
for (const licence of billed) {
const product = licence.product;
let plan = licence.plan;
if (reviewed) {
const r = reviewLicence(licence, product);
plan = r.plan;
if (r.warning) warnings.push(r.warning);
if (r.planChange) planChanges.push(r.planChange);
if (product === 'events') eventsBand = r.band;
}
const price = planPrice(plan, licence.customMonthlyCents, product);
if (!price) {
warnings.push(`${PRODUCT_NAMES[product]}: there's no price for the "${plan}" plan. Set a custom monthly price on the licence, or add the lines yourself.`);
continue;
}
const label = productLabel(product, plan);
const off = founding && price.foundingCents < price.monthlyCents ? price.foundingCents - price.monthlyCents : 0;
const add = (description, quantity, unitCents) => {
productLines.push({ description, quantity, unitCents, amountCents: Math.round(quantity * unitCents) });
if (off) {
const unitOff = unitCents === price.monthlyCents ? off : Math.round((unitCents * off) / price.monthlyCents);
productLines.push({ description: `Founding church discount (${FOUNDING_PERCENT}%)`, quantity, unitCents: unitOff, amountCents: Math.round(quantity * unitOff) });
}
};
// Days owed from before this period: it started after the last invoice was made.
const owedFrom = licence.billedUntil ? later(licence.billedFrom, addDays(licence.billedUntil, 1)) : day(licence.billedFrom);
if (ymd(owedFrom) < ymd(start)) {
const to = addDays(start, -1);
const days = daysBetween(owedFrom, to);
add(`${label}, ${shortDate(owedFrom)} – ${shortDate(to)} (${days} day${days === 1 ? '' : 's'} before this period)`, 1, Math.round(perDay(price.monthlyCents) * days));
}
// This period: all of it, or from the day it starts.
if (ymd(licence.billedFrom) <= ymd(start)) {
const range = periodLabel(start, end);
add(cycle === 'yearly' ? `${label}, 12 months (${range}), paid yearly: 2 months free` : `${label}, ${range}`, months, price.monthlyCents);
} else {
const days = daysBetween(licence.billedFrom, end);
add(`${label}, ${shortDate(licence.billedFrom)} – ${shortDate(end)} (${days} day${days === 1 ? '' : 's'}, from its start)`, 1, Math.round(perDay(price.monthlyCents) * days));
}
// Add-ons for the whole period only (measured now), never discounted.
if (product === 'website' && ymd(licence.billedFrom) <= ymd(start)) {
const blocks = extraStorageBlocks(licence.install?.stats?.storage);
if (blocks) {
const m = monthsIn(cycle);
addOns.push({
description: `Extra website storage: ${blocks} × 5 GB, ${m === 12 ? '12 months' : periodLabel(start, end)}`,
quantity: blocks * m, unitCents: STORAGE.monthly * 100, amountCents: blocks * m * STORAGE.monthly * 100,
});
}
}
products.push(product);
plans.push({ product, plan });
licenceUpdates.push({ id: licence.id, data: { billedUntil: day(end) } });
}
const { lines, warning } = planLines({ plan, customMonthlyCents: licence.customMonthlyCents, cycle, periodStart, periodEnd, founding: !!customer.founding });
if (warning) warnings.push(warning);
const recipientEmail = recipientFor(customer, install);
const lines = [...productLines];
const pct = BUNDLE_PERCENT[Math.min(products.length, 3)];
if (pct) {
const base = productLines.reduce((s, l) => s + l.amountCents, 0);
const cut = -Math.round((base * pct) / 100);
lines.push({ description: `Bundle discount (${pct}%: ${products.map(p => PRODUCT_NAMES[p]).join(', ').replace(/, ([^,]*)$/, ' and $1')})`, quantity: 1, unitCents: cut, amountCents: cut });
}
lines.push(...addOns);
const plan = plans.length === 1 && plans[0].product === 'events'
? plans[0].plan
: plans.map(p => (p.product === 'website' ? PRODUCT_NAMES.website : `${PRODUCT_NAMES[p.product]} ${p.plan}`)).join(' · ') || null;
return { lines, plan, planChanges, warnings, licenceUpdates, products, eventsBand };
}
/**
* The draft invoice for a customer's next period (customer.nextInvoiceDate), and how the
* customer and its licences move on. Returns { invoice, customerUpdate, licenceUpdates, empty }:
* `empty` when no product was billed and there's nothing to warn about (no invoice is made).
*/
function draftCustomerInvoice({ customer, licences, settings = {} }) {
const cycle = customer.billingCycle;
if (cycle !== 'monthly' && cycle !== 'yearly') throw new Error('This customer isn\'t billed.');
const anchor = anchorDayOf(customer);
const periodStart = day(customer.nextInvoiceDate);
const nextStart = addMonths(periodStart, monthsIn(cycle), anchor);
const periodEnd = addDays(nextStart, -1);
const reviewed = !!customer.reviewDate && ymd(periodStart) >= ymd(customer.reviewDate);
const r = customerInvoiceLines({ customer, licences, period: { start: periodStart, end: periodEnd, cycle }, reviewed });
const warnings = [...r.warnings];
const recipientEmail = recipientFor(customer, contactInstall(licences));
if (!recipientEmail) warnings.push('No email address to send it to: add a billing email on the customer.');
const terms = parseInt(settings.payment_terms_days, 10);
let reviewDate = licence.reviewDate ? day(licence.reviewDate) : null;
let reviewDate = customer.reviewDate ? day(customer.reviewDate) : null;
if (reviewed) while (ymd(reviewDate) <= ymd(periodStart)) reviewDate = addMonths(reviewDate, 12);
return {
empty: r.products.length === 0 && r.warnings.length === 0,
invoice: {
customerId: customer.id,
licenceId: licence.id,
licenceId: null,
issueDate: periodStart,
dueDate: addDays(periodStart, Number.isFinite(terms) && terms >= 0 ? terms : 7),
periodStart,
periodEnd,
cycle,
plan,
incomeBand: reviewed ? band : null,
plan: r.plan,
incomeBand: reviewed ? r.eventsBand : null,
reviewed,
founding: !!customer.founding,
planChange,
lines,
...totals(lines, settings),
planChange: r.planChanges.length ? r.planChanges : null,
lines: r.lines,
...totals(r.lines, settings),
warnings,
recipientEmail,
basis: { licences: licences.map(l => ({ id: l.id, billedUntil: ymd(l.billedUntil) })), planChangeDropped: false },
},
licenceUpdate: { nextInvoiceDate: nextStart, reviewDate },
customerUpdate: { nextInvoiceDate: nextStart, reviewDate },
licenceUpdates: r.licenceUpdates,
};
}
/** An invoice's tier changes as a list (Hub 1.7 stored one object). */
function planChangesOf(invoice) {
const pc = invoice?.planChange;
if (!pc) return [];
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". */
function invoiceState(invoice, todayYmd) {
const paidCents = (invoice.payments || []).reduce((s, p) => s + p.amountCents, 0);
@@ -151,7 +297,7 @@ function invoiceState(invoice, todayYmd) {
}
function invoiceDescription(invoice) {
if (invoice.periodStart && invoice.periodEnd) return `Cross Events licence, ${periodLabel(invoice.periodStart, invoice.periodEnd)}`;
if (invoice.periodStart && invoice.periodEnd) return `${invoice.licenceId ? 'Cross Events licence' : 'Licences'}, ${periodLabel(invoice.periodStart, invoice.periodEnd)}`;
return (invoice.lines?.[0]?.description || 'Invoice').slice(0, 80);
}
@@ -187,4 +333,7 @@ function statement({ invoices, payments, from, to }) {
return { from: f, to: t, openingCents: opening, entries, closingCents: balance, outstanding };
}
module.exports = { recipientFor, cleanLines, totals, planLines, draftInvoice, invoiceState, statement, invoiceDescription, anchorDayOf };
module.exports = {
recipientFor, contactInstall, cleanLines, totals, planLines, productLabel, customerInvoiceLines, draftCustomerInvoice,
planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn,
};
+136 -64
View File
@@ -4,9 +4,9 @@
* 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).
* 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).
@@ -21,9 +21,11 @@ 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 { 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'];
@@ -50,17 +52,33 @@ async function invoicePdfFor(invoice, settings) {
// ─── Drafting ────────────────────────────────────────────────────────────────
/** Makes the draft for one licence's next period. Returns the invoice, or null if it already exists. */
async function draftForLicence(licenceId, settings) {
/** 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) => {
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 } });
// 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, number, planChange: invoice.planChange ?? undefined }, include: invoiceInclude });
return tx.invoice.create({ data: { ...invoice, basis: { ...invoice.basis, products }, number, planChange: invoice.planChange ?? undefined }, include: invoiceInclude });
});
}
@@ -75,9 +93,9 @@ async function emailApproval(invoice, settings) {
],
rows: [
['Church', invoice.customer.name],
['Tier', `${invoice.plan || '—'}${invoice.founding ? ' (founding)' : ''}`],
['Products', `${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]] : []),
...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)],
],
@@ -97,20 +115,22 @@ async function emailApproval(invoice, settings) {
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 } },
const customers = await prisma.customer.findMany({
where: { 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 (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 draftForLicence(id, settings);
const invoice = await draftForCustomer(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;
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;
@@ -118,6 +138,18 @@ async function createDueDrafts(now, settings) {
// ─── 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';
@@ -127,7 +159,7 @@ async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
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.`,
`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: [
@@ -137,7 +169,7 @@ async function sendInvoiceEmail(invoice, settings, { copy = false } = {}) {
[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,
note: tierChangeNote(invoice),
});
return sendBillingEmail(settings, {
kind: 'invoice', customerId: invoice.customerId, refId: invoice.id, to: invoice.recipientEmail,
@@ -202,9 +234,10 @@ async function remindUnapproved(now, settings) {
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);
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;
@@ -238,20 +271,20 @@ async function approveInvoice(id, actorId) {
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);
}
// 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 };
return { invoice: await loadInvoice(id), notice: notices[0] || null, notices };
}
async function unapproveInvoice(id) {
@@ -281,23 +314,33 @@ async function updateInvoice(id, body) {
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;
data.plan = invoice.licence?.plan || invoice.plan;
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 loadInvoice(id);
return reprice ? recalculateInvoice(id) : loadInvoice(id);
}
/** Rebuilds a draft's lines from the licence as it is now (e.g. after changing founding or the price). */
/**
* 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.licence || !invoice.periodStart) throw bad('Only an invoice for a licence\'s period 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,
@@ -311,6 +354,32 @@ async function recalculateInvoice(id) {
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);
@@ -333,7 +402,7 @@ async function resendInvoice(id) {
/** 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 } } });
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.');
@@ -345,7 +414,7 @@ async function createManualInvoice(body) {
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]),
recipientEmail: body.recipientEmail || compute.recipientFor(customer, contactOf(customer)),
},
include: invoiceInclude,
});
@@ -354,9 +423,9 @@ async function createManualInvoice(body) {
// ─── 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 } } } });
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, payment.customer.installs[0]);
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!`,
@@ -419,16 +488,16 @@ async function resendReceipt(id) {
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 } } } });
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, payment.customer.installs[0]) }) };
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 }, take: 1 } } });
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);
@@ -437,7 +506,7 @@ async function customerStatement(customerId, from, to) {
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 }) };
return { customer, recipientEmail: compute.recipientFor(customer, contactOf(customer)), statement: compute.statement({ invoices, payments, from: f, to: t }) };
}
async function statementPdfFor(customerId, from, to) {
@@ -452,7 +521,7 @@ async function emailStatement(customerId, { from, to, email } = {}) {
const sendTo = email || recipientEmail;
const content = layout(settings, {
preheader: `Balance ${money(statement.closingCents)} on ${longDate(statement.to)}`,
heading: 'Your Cross Events statement',
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: [
@@ -474,30 +543,32 @@ async function emailStatement(customerId, { from, to, email } = {}) {
// ─── 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 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 to = compute.recipientFor(customer, customer.installs[0]);
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 tier moves down to ${change.toPlan}` : `Your Cross Events tier changes to ${change.toPlan}`,
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 Cross Events licence moves from the ${change.fromPlan} tier to the ${change.toPlan} tier. The notice is attached.`,
`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 ? [['12-month event income', change.incomeBand]] : []),
...(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: licence?.billingCycle }) }],
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;
@@ -509,14 +580,14 @@ async function sendLicenceChange(change, settings) {
*/
async function createLicenceChange(body, settings = null, { send = true } = {}) {
settings = settings || await getSettings();
const licence = await prisma.licence.findUnique({ where: { id: String(body.licenceId || '') } });
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)?.monthlyCents ?? null);
const effectiveDate = body.effectiveDate ? day(body.effectiveDate) : licence.nextInvoiceDate ? day(licence.nextInvoiceDate) : today();
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: {
@@ -543,13 +614,14 @@ async function resendLicenceChange(id) {
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 } });
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, change.customer.installs[0]), cycle: change.licence?.billingCycle }) };
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, draftForLicence, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
nextNumber, loadInvoice, invoicePdfFor, draftForCustomer, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
applyDueLicenceChanges, runBilling, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice,
resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement,
statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval,
+22 -9
View File
@@ -9,6 +9,14 @@ const path = require('path');
const PDFDocument = require('pdfkit');
const { longDate, shortDate, money, periodLabel } = require('./dates');
const { planPrice, FOUNDING_PERCENT } = require('./tiers');
const { PRODUCT_NAMES } = require('../products');
/** An invoice's tier changes as a list (Hub 1.7 stored one object). Same as compute.planChangesOf. */
const planChangesOf = invoice => {
const pc = invoice?.planChange;
if (!pc) return [];
return Array.isArray(pc) ? pc : [{ product: 'events', ...pc }];
};
const LOGO = path.join(__dirname, '..', '..', '..', 'assets', 'logo.png');
const C = { navy: '#11111f', sky: '#62b5e5', skyDark: '#1d6a9c', skyPale: '#e8f4fb', text: '#2b3044', muted: '#6b7184', line: '#e1e5ee', surface: '#f5f7fb', green: '#12734a', red: '#b42318' };
@@ -199,11 +207,14 @@ function invoicePdf({ invoice, customer, settings: s, state }) {
...(paid ? [['Total', money(invoice.totalCents)], ['Paid', money(-paid), { color: C.green }]] : []),
[paid ? 'Balance due' : 'Total due', money(paid ? state.balanceCents : invoice.totalCents), { big: true }],
]);
if (invoice.planChange) {
const pc = invoice.planChange;
y = box(doc, y, `Your tier changes to ${pc.to}`, [
`From this period your licence moves from the ${pc.from} tier to the ${pc.to} tier${pc.band ? `, based on your event income over the last 12 months (${pc.band})` : ''}.`,
'Tiers are reviewed once a year. Donations and sponsored places are never counted.',
const changes = planChangesOf(invoice);
if (changes.length) {
const basis = pc => (pc.product === 'app'
? `, based on your active members over the last 90 days (${pc.band})`
: `, based on your event income over the last 12 months (${pc.band})`);
y = box(doc, y, changes.length === 1 ? `Your ${PRODUCT_NAMES[changes[0].product] || 'Cross Events'} tier changes to ${changes[0].to}` : 'Your tiers change', [
...changes.map(pc => `From this period ${PRODUCT_NAMES[pc.product] || 'Cross Events'} moves from the ${pc.from} tier to the ${pc.to} tier${pc.band ? basis(pc) : ''}.`),
`Tiers are reviewed once a year.${changes.some(pc => pc.product !== 'app') ? ' Donations and sponsored places are never counted.' : ''}`,
], { tone: 'sky' });
}
if (invoice.status !== 'void') y = box(doc, y, 'How to pay', paymentLines(s, invoice.number));
@@ -270,13 +281,14 @@ function statementPdf({ statement: st, customer, settings: s, recipientEmail })
}
/** A notice of licence change (tier up or down). */
function licenceChangePdf({ change, customer, settings: s, founding, recipientEmail, cycle }) {
function licenceChangePdf({ change, customer, settings: s, founding, recipientEmail, cycle, product = 'events' }) {
const name = PRODUCT_NAMES[product] || 'Cross Events';
const up = change.fromMonthlyCents != null && change.toMonthlyCents != null ? change.toMonthlyCents > change.fromMonthlyCents : null;
// The monthly price, and for a founding church its founding price (the tier's, or 35% off).
const priceText = (plan, cents) => {
if (cents == null) return 'priced for your church';
if (!founding) return `${money(cents)} a month`;
const p = planPrice(plan);
const p = planPrice(plan, null, product);
const f = p && p.monthlyCents === cents ? p.foundingCents : Math.round((cents * (100 - FOUNDING_PERCENT)) / 100);
return `${money(f)} a month (founding price; normally ${money(cents)})`;
};
@@ -288,7 +300,7 @@ function licenceChangePdf({ change, customer, settings: s, founding, recipientEm
]);
y = party(doc, y, 'Notice to', customer, recipientEmail);
doc.font('Helvetica-Bold').fontSize(14).fillColor(C.navy).text(
up == null ? `Your Cross Events tier changes to ${change.toPlan}` : up ? `Your Cross Events tier moves up to ${change.toPlan}` : `Good news: your Cross Events tier moves down to ${change.toPlan}`, M, y, { width: W });
up == null ? `Your ${name} tier changes to ${change.toPlan}` : up ? `Your ${name} tier moves up to ${change.toPlan}` : `Good news: your ${name} tier moves down to ${change.toPlan}`, M, y, { width: W });
y = doc.y + 10;
y = table(doc, y, [
{ label: '', width: 150 },
@@ -300,7 +312,8 @@ function licenceChangePdf({ change, customer, settings: s, founding, recipientEm
]);
const why = [];
if (change.reason) why.push(change.reason);
if (change.incomeBand) why.push(`Your event income over the last 12 months was in the range ${change.incomeBand}. Tiers are based on ticket sales and other payments through Cross Events, less refunds; donations and sponsored places are never counted.`);
if (change.incomeBand && product === 'app') why.push(`Your church had ${change.incomeBand} active members over the last 90 days (people who used the app; visitors who don't sign in never count).`);
else if (change.incomeBand) why.push(`Your event income over the last 12 months was in the range ${change.incomeBand}. Tiers are based on ticket sales and other payments through Cross Events, less refunds; donations and sponsored places are never counted.`);
why.push('We review tiers once a year when your licence renews, never in the middle of the year.');
if (founding) why.push('As a founding church, your 35% founding discount carries on in your new tier.');
if (cycle === 'yearly') why.push('You pay yearly, so you still get two months free on the new price.');
+72 -11
View File
@@ -1,8 +1,17 @@
/**
* Cross Events licence tiers, billed on a site's event income over the last 12 months
* (`income.eventIncome12m`, Cross Events 2.0.2+). The same tiers are in
* frontend/src/lib/tiers.ts (a test checks they match) and the public prices in crosscode-site
* src/data/pricing.mjs. Prices are rand per month.
* Prices per product (Hub 2.0, ROADMAP-v3 §10), rand per month. The same prices are in
* frontend/src/lib/tiers.ts (a test checks they match) and the public ones in crosscode-site
* src/data/pricing.mjs.
*
* - Cross Events: tiers on a site's event income over the last 12 months (`income.eventIncome12m`,
* Cross Events 2.0.2+).
* - Church Website: one price, 5 GB of uploads included; extra storage is an add-on.
* - Church App: tiers on active members in the last 90 days (`activeMembers90d`, a band).
* - Accounts: free, never invoiced.
*
* The same rules for every product: yearly billing is 10 months' price, founding churches pay the
* founding price, bundles take 15% off two products and 25% off three, and add-ons are never
* discounted (compute.js).
*/
const TIERS = [
@@ -16,12 +25,34 @@ const TIERS = [
{ name: 'Network', upTo: null, monthly: null, founding: null }, // priced per church, from R7 500
];
/** Yearly billing: this many months' price for 12 months (two months free). */
/** Church Website: one plan. */
const WEBSITE_PLANS = [{ name: 'Website', monthly: 99, founding: 64 }];
/** Church App tiers, one per active-member band (contracts ACTIVE_MEMBER_BANDS, in order). */
const APP_TIERS = [
{ name: 'Mustard Seed', band: '0–100', monthly: 99, founding: 64 },
{ name: 'Small Group', band: '101–300', monthly: 249, founding: 162 },
{ name: 'Congregation', band: '301–750', monthly: 399, founding: 259 },
{ name: 'Gathering', band: '751–2 000', monthly: 649, founding: 422 },
{ name: 'Multitude', band: '2 001–5 000', monthly: 999, founding: 649 },
{ name: 'Network', band: 'over 5 000', monthly: null, founding: null }, // from R1 500, priced per church
];
/** Extra website storage: R20 a month per 5 GB above the 5 GB included. */
const STORAGE = { includedBytes: 5 * 1024 ** 3, stepBytes: 5 * 1024 ** 3, monthly: 20 };
/** Bundles: % off the products (not the add-ons) by how many are billed. Accounts doesn't count. */
const BUNDLE_PERCENT = { 2: 15, 3: 25 };
/** Yearly billing: this many months' price for 12 months (two months free). Products only. */
const YEARLY_MONTHS = 10;
/** Founding churches: this much off a price that has no published founding price. */
const FOUNDING_PERCENT = 35;
const tierNamed = name => TIERS.find(t => t.name.toLowerCase() === String(name || '').toLowerCase()) || null;
const PLANS = { events: TIERS, website: WEBSITE_PLANS, app: APP_TIERS, accounts: [] };
const tierNamed = (name, product = 'events') =>
(PLANS[product] || []).find(t => t.name.toLowerCase() === String(name || '').toLowerCase()) || null;
/** The highest rand amount in a band label ("R100 001–R150 000" → 150000; "over R10 000 000" → Infinity). */
function bandTop(band) {
@@ -32,7 +63,7 @@ function bandTop(band) {
return Number.isFinite(n) ? n : null;
}
/** The tier a band falls in, or null (no band, or an old install's "over R100 000"). */
/** The Cross Events tier an income band falls in, or null (no band, or an old install's "over R100 000"). */
function tierForBand(band) {
if (!band || band === 'over R100 000') return null;
const top = bandTop(band);
@@ -40,12 +71,31 @@ function tierForBand(band) {
return TIERS.find(t => t.upTo == null || top <= t.upTo) || null;
}
/** The Church App tier for an active-member band, or null. */
const appTierForBand = band => APP_TIERS.find(t => t.band === band) || null;
/**
* The monthly price of a plan in cents, normal and founding: { monthlyCents, foundingCents },
* The tier a product's install should be on from what it reports: { tier, band }. `tier` is
* undefined for a product without tiers (Website), null when it can't tell (no band reported).
*/
function reviewTier(product, install) {
if (product === 'events') {
const band = install?.stats?.income?.eventIncome12m || null;
return { tier: tierForBand(band), band };
}
if (product === 'app') {
const band = install?.stats?.activeMembers90d || null;
return { tier: appTierForBand(band), band };
}
return { tier: undefined, band: null };
}
/**
* The monthly price of a plan in cents, normal and founding: { monthlyCents, foundingCents, custom },
* or null when the plan has no price (Network, Trial, an old "standard") and no custom price.
*/
function planPrice(plan, customMonthlyCents = null) {
const tier = tierNamed(plan);
function planPrice(plan, customMonthlyCents = null, product = 'events') {
const tier = tierNamed(plan, product);
if (customMonthlyCents != null && customMonthlyCents >= 0) {
return { monthlyCents: customMonthlyCents, foundingCents: Math.round((customMonthlyCents * (100 - FOUNDING_PERCENT)) / 100), custom: true };
}
@@ -53,4 +103,15 @@ function planPrice(plan, customMonthlyCents = null) {
return { monthlyCents: tier.monthly * 100, foundingCents: tier.founding * 100, custom: false };
}
module.exports = { TIERS, YEARLY_MONTHS, FOUNDING_PERCENT, tierNamed, tierForBand, planPrice };
/** How many extra 5 GB blocks a website uses (from its heartbeat's `storage`). */
function extraStorageBlocks(storage) {
const used = Number(storage?.usedBytes);
if (!Number.isFinite(used) || used <= 0) return 0;
const included = Number(storage?.includedBytes) > 0 ? Number(storage.includedBytes) : STORAGE.includedBytes;
return Math.max(0, Math.ceil((used - included) / STORAGE.stepBytes));
}
module.exports = {
TIERS, WEBSITE_PLANS, APP_TIERS, PLANS, STORAGE, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
tierNamed, tierForBand, appTierForBand, reviewTier, planPrice, extraStorageBlocks,
};
+7 -2
View File
@@ -4,7 +4,8 @@
*/
const { licenceKey } = require('./crypto');
const { PRODUCT_NAMES, isProduct } = require('./products');
const { PRODUCT_NAMES, BILLABLE, isProduct } = require('./products');
const { today, addMonths } = require('./billing/dates');
const conflict = (message, code) => Object.assign(new Error(message), { status: 409, code });
@@ -57,7 +58,11 @@ async function ensureAccountsLicence(db, customerId) {
* Generate a licence for a customer, plus its Accounts licence when this is a product other than
* Accounts and it has none yet. Returns { licence, accounts } (accounts: the licence if created now).
*/
async function generateLicence(db, { customerId, product = 'events', data = {} }) {
async function generateLicence(db, { customerId, product = 'events', data = {}, now = new Date() }) {
// Hub 2.0, decision 3: a product added to a customer that's already billed gets its free month,
// then joins the customer's invoices (the days before its first full period prorated).
const customer = BILLABLE.includes(product) && data.billedFrom === undefined ? await db.customer?.findUnique({ where: { id: customerId } }) : null;
if (customer && customer.billingCycle && customer.billingCycle !== 'none') data = { ...data, billedFrom: addMonths(today(now), 1) };
const licence = await createLicence(db, { customerId, product, data });
if (product === 'accounts') return { licence, accounts: null };
const { licence: accounts, created } = await ensureAccountsLicence(db, customerId);
+2 -5
View File
@@ -31,10 +31,7 @@ function productOfKey(key) {
const isProduct = p => PRODUCTS.includes(p);
/**
* Products that can be invoiced. Until billing per customer (Hub 2.0 step 4) only Events has
* prices; Accounts is never invoiced.
*/
const BILLABLE = ['events'];
/** Products that are invoiced (Accounts is free and never invoiced). */
const BILLABLE = ['events', 'website', 'app'];
module.exports = { PRODUCTS, PRODUCT_NAMES, KEY_PREFIXES, BILLABLE, productOfKey, isProduct };
+188 -40
View File
@@ -2,24 +2,48 @@ jest.mock('../src/config/db', () => ({}));
const fs = require('fs');
const path = require('path');
const { TIERS, tierForBand, planPrice } = require('../src/utils/billing/tiers');
const { hub } = require('@crosscode/contracts');
const { TIERS, WEBSITE_PLANS, APP_TIERS, tierForBand, appTierForBand, planPrice, extraStorageBlocks } = require('../src/utils/billing/tiers');
const { day, ymd, addMonths, addDays, today, saHour, periodLabel, money } = require('../src/utils/billing/dates');
const { draftInvoice, cleanLines, totals, invoiceState, statement, recipientFor } = require('../src/utils/billing/compute');
const { draftCustomerInvoice, customerInvoiceLines, planChangesOf, cleanLines, totals, invoiceState, statement, recipientFor } = require('../src/utils/billing/compute');
const customer = (extra = {}) => ({ id: 'c1', name: 'Hope Church', email: 'office@hope.example', founding: false, ...extra });
const install = (band, email = 'admin@hope.example') => ({ adminContact: { email }, stats: band ? { income: { eventIncome12m: band } } : {} });
const licence = (extra = {}) => ({
id: 'l1', plan: 'Sprout', billingCycle: 'monthly', billingStart: day('2026-01-01'), nextInvoiceDate: day('2026-12-01'),
reviewDate: day('2027-01-01'), customMonthlyCents: null, ...extra,
const GB = 1024 ** 3;
const customer = (extra = {}) => ({
id: 'c1', name: 'Hope Church', email: 'office@hope.example', founding: false,
billingCycle: 'monthly', billingStart: day('2026-01-01'), nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-01-01'), ...extra,
});
const install = (band, email = 'admin@hope.example') => ({ product: 'events', adminContact: { email }, stats: band ? { income: { eventIncome12m: band } } : {} });
const events = (extra = {}) => ({
id: 'l1', product: 'events', status: 'active', plan: 'Sprout', customMonthlyCents: null,
billedFrom: day('2026-01-01'), billedUntil: day('2026-11-30'), install: install('R100 001–R150 000'), ...extra,
});
const website = (extra = {}) => ({
id: 'l2', product: 'website', status: 'active', plan: 'Website', customMonthlyCents: null,
billedFrom: day('2026-06-01'), billedUntil: day('2026-11-30'), install: { product: 'website', stats: {} }, ...extra,
});
const app = (extra = {}) => ({
id: 'l3', product: 'app', status: 'active', plan: 'Mustard Seed', customMonthlyCents: null,
billedFrom: day('2026-06-01'), billedUntil: day('2026-11-30'), install: { product: 'app', stats: { activeMembers90d: '0–100' } }, ...extra,
});
const accounts = () => ({ id: 'l4', product: 'accounts', status: 'active', plan: 'included', billedFrom: null, billedUntil: null, install: null });
const settings = { payment_terms_days: '7' };
const draft = (c, licences) => draftCustomerInvoice({ customer: c, licences, settings });
const amounts = invoice => invoice.lines.map(l => [l.description, l.amountCents]);
describe('tiers', () => {
test('the server and the Hub screens have the same tiers', () => {
const ts = fs.readFileSync(path.join(__dirname, '..', '..', 'frontend', 'src', 'lib', 'tiers.ts'), 'utf8');
const front = [...ts.matchAll(/\{ name: "(\w+)", upTo: ([\d_]+|null), monthly: (\d+|null), founding: (\d+|null) \}/g)]
.map(m => [m[1], m[2] === 'null' ? null : Number(m[2].replace(/_/g, '')), m[3] === 'null' ? null : Number(m[3]), m[4] === 'null' ? null : Number(m[4])]);
expect(front).toEqual(TIERS.map(t => [t.name, t.upTo, t.monthly, t.founding]));
const front = fs.readFileSync(path.join(__dirname, '..', '..', 'frontend', 'src', 'lib', 'tiers.ts'), 'utf8');
const num = v => (v === 'null' ? null : Number(v.replace(/_/g, '')));
test('the server and the Hub screens have the same Cross Events tiers', () => {
const rows = [...front.matchAll(/\{ name: "(\w+)", upTo: ([\d_]+|null), monthly: (\d+|null), founding: (\d+|null) \}/g)].map(m => [m[1], num(m[2]), num(m[3]), num(m[4])]);
expect(rows).toEqual(TIERS.map(t => [t.name, t.upTo, t.monthly, t.founding]));
});
test('...and the same Church App tiers and Website price', () => {
const appRows = [...front.matchAll(/\{ name: "([\w ]+)", band: "([^"]+)", monthly: (\d+|null), founding: (\d+|null) \}/g)].map(m => [m[1], m[2], num(m[3]), num(m[4])]);
expect(appRows).toEqual(APP_TIERS.map(t => [t.name, t.band, t.monthly, t.founding]));
const site = /WEBSITE_PLAN = \{ name: "Website", monthly: (\d+), founding: (\d+) \}/.exec(front);
expect([num(site[1]), num(site[2])]).toEqual([WEBSITE_PLANS[0].monthly, WEBSITE_PLANS[0].founding]);
});
test('a band falls in the tier whose top it fits under', () => {
@@ -32,11 +56,27 @@ describe('tiers', () => {
expect(tierForBand(null)).toBeNull();
});
test('every App active-member band (contracts) has a tier', () => {
expect(APP_TIERS.map(t => t.band)).toEqual([...hub.ACTIVE_MEMBER_BANDS]);
expect(appTierForBand('101–300').name).toBe('Small Group');
expect(appTierForBand(null)).toBeNull();
});
test('prices: the tier\'s, or a custom one with 35% off for founding', () => {
expect(planPrice('Grow')).toEqual({ monthlyCents: 85000, foundingCents: 55000, custom: false });
expect(planPrice('Network')).toBeNull();
expect(planPrice('Network', 750000)).toEqual({ monthlyCents: 750000, foundingCents: 487500, custom: true });
expect(planPrice('standard')).toBeNull();
expect(planPrice('Website', null, 'website')).toEqual({ monthlyCents: 9900, foundingCents: 6400, custom: false });
expect(planPrice('Small Group', null, 'app')).toEqual({ monthlyCents: 24900, foundingCents: 16200, custom: false });
expect(planPrice('Grow', null, 'app')).toBeNull(); // another product's tier
});
test('extra storage: whole 5 GB blocks above what is included', () => {
expect(extraStorageBlocks({ usedBytes: 4 * GB, includedBytes: 5 * GB })).toBe(0);
expect(extraStorageBlocks({ usedBytes: 5 * GB + 1, includedBytes: 5 * GB })).toBe(1);
expect(extraStorageBlocks({ usedBytes: 11 * GB })).toBe(2);
expect(extraStorageBlocks(null)).toBe(0);
});
});
@@ -63,82 +103,190 @@ describe('dates', () => {
});
});
describe('drafting an invoice', () => {
describe('drafting an invoice (one product, as before Hub 2.0)', () => {
test('monthly, in advance: the period starting on its date, due after the payment terms', () => {
const { invoice, licenceUpdate } = draftInvoice({ licence: licence(), customer: customer(), install: install('R100 001–R150 000'), settings });
const { invoice, customerUpdate, licenceUpdates } = draft(customer(), [events(), accounts()]);
expect(ymd(invoice.issueDate)).toBe('2026-12-01');
expect(ymd(invoice.dueDate)).toBe('2026-12-08');
expect([ymd(invoice.periodStart), ymd(invoice.periodEnd)]).toEqual(['2026-12-01', '2026-12-31']);
expect(invoice.lines).toEqual([{ description: 'Cross Events licence: Sprout tier, December 2026', quantity: 1, unitCents: 55000, amountCents: 55000 }]);
expect(invoice).toMatchObject({ totalCents: 55000, vatCents: 0, reviewed: false, planChange: null, recipientEmail: 'admin@hope.example', warnings: [] });
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-01-01');
expect(ymd(licenceUpdate.reviewDate)).toBe('2027-01-01'); // not reviewed yet
expect(invoice.lines).toEqual([{ description: 'Cross Events, Sprout tier, December 2026', quantity: 1, unitCents: 55000, amountCents: 55000 }]);
expect(invoice).toMatchObject({ licenceId: null, plan: 'Sprout', totalCents: 55000, vatCents: 0, reviewed: false, planChange: null, recipientEmail: 'admin@hope.example', warnings: [] });
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-01-01');
expect(ymd(customerUpdate.reviewDate)).toBe('2027-01-01'); // not reviewed yet
expect(licenceUpdates.map(u => [u.id, ymd(u.data.billedUntil)])).toEqual([['l1', '2026-12-31']]);
expect(invoice.basis.licences).toEqual([{ id: 'l1', billedUntil: '2026-11-30' }, { id: 'l4', billedUntil: null }]);
});
test('between reviews the tier stays, whatever the income', () => {
const { invoice } = draftInvoice({ licence: licence(), customer: customer(), install: install('R1 000 001–R2 500 000'), settings });
const { invoice } = draft(customer(), [events({ install: install('R1 000 001–R2 500 000') })]);
expect(invoice.plan).toBe('Sprout');
expect(invoice.incomeBand).toBeNull();
});
test('at the yearly review the income moves the tier up, and the next review is a year on', () => {
const { invoice, licenceUpdate } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install('R250 001–R400 000'), settings });
const { invoice, customerUpdate } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install('R250 001–R400 000') })]);
expect(invoice).toMatchObject({ reviewed: true, plan: 'Grow', incomeBand: 'R250 001–R400 000', totalCents: 85000 });
expect(invoice.planChange).toEqual({ from: 'Sprout', to: 'Grow', fromMonthlyCents: 55000, toMonthlyCents: 85000, band: 'R250 001–R400 000' });
expect(ymd(licenceUpdate.reviewDate)).toBe('2028-01-01');
expect(invoice.planChange).toEqual([{ licenceId: 'l1', product: 'events', from: 'Sprout', to: 'Grow', fromMonthlyCents: 55000, toMonthlyCents: 85000, band: 'R250 001–R400 000' }]);
expect(ymd(customerUpdate.reviewDate)).toBe('2028-01-01');
});
test('...or down', () => {
const { invoice } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install('R5 001–R20 000'), settings });
expect(invoice.planChange).toMatchObject({ from: 'Sprout', to: 'Seed' });
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install('R5 001–R20 000') })]);
expect(invoice.planChange[0]).toMatchObject({ from: 'Sprout', to: 'Seed' });
expect(invoice.totalCents).toBe(35000);
});
test('no band at the review: the tier stays and Joshua is warned', () => {
const { invoice } = draftInvoice({ licence: licence({ nextInvoiceDate: day('2027-01-01') }), customer: customer(), install: install(null), settings });
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ billedUntil: day('2026-12-31'), install: install(null) })]);
expect(invoice.plan).toBe('Sprout');
expect(invoice.planChange).toBeNull();
expect(invoice.warnings[0]).toMatch(/hasn't reported its 12-month event income/);
});
test('a founding church gets the founding price as its own line', () => {
const { invoice } = draftInvoice({ licence: licence(), customer: customer({ founding: true }), install: install(null), settings });
const { invoice } = draft(customer({ founding: true }), [events()]);
expect(invoice.lines[1]).toEqual({ description: 'Founding church discount (35%)', quantity: 1, unitCents: -19000, amountCents: -19000 });
expect(invoice.totalCents).toBe(36000);
expect(invoice.founding).toBe(true);
});
test('yearly: 10 months\' price for 12 months, founding on all of it', () => {
const { invoice, licenceUpdate } = draftInvoice({
licence: licence({ plan: 'Grow', billingCycle: 'yearly', nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-12-01') }),
customer: customer({ founding: true }), install: install(null), settings,
});
const { invoice, customerUpdate } = draft(
customer({ founding: true, billingCycle: 'yearly', nextInvoiceDate: day('2026-12-01'), reviewDate: day('2027-12-01') }),
[events({ plan: 'Grow' })],
);
expect([ymd(invoice.periodStart), ymd(invoice.periodEnd)]).toEqual(['2026-12-01', '2027-11-30']);
expect(invoice.lines.map(l => [l.quantity, l.unitCents, l.amountCents])).toEqual([[10, 85000, 850000], [10, -30000, -300000]]);
expect(invoice.lines[0].description).toBe('Cross Events licence: Grow tier, 12 months (1 December 2026 – 30 November 2027), paid yearly: 2 months free');
expect(invoice.lines[0].description).toBe('Cross Events, Grow tier, 12 months (1 December 2026 – 30 November 2027), paid yearly: 2 months free');
expect(invoice.totalCents).toBe(550000);
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-12-01');
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-12-01');
});
test('a custom price is kept at the review, with a note if the income points elsewhere', () => {
const { invoice } = draftInvoice({
licence: licence({ plan: 'Network', customMonthlyCents: 750000, nextInvoiceDate: day('2027-01-01') }),
customer: customer(), install: install('R5 000 001–R10 000 000'), settings,
});
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [events({ plan: 'Network', customMonthlyCents: 750000, billedUntil: day('2026-12-31'), install: install('R5 000 001–R10 000 000') })]);
expect(invoice).toMatchObject({ plan: 'Network', totalCents: 750000, planChange: null });
expect(invoice.warnings[0]).toMatch(/Movement tier, but the licence has a custom price/);
});
test('an unpriced plan makes an empty draft with a warning', () => {
const { invoice } = draftInvoice({ licence: licence({ plan: 'standard' }), customer: customer(), install: install(null), settings });
test('an unpriced plan makes an empty draft with a warning (so it isn\'t skipped)', () => {
const { invoice, empty } = draft(customer(), [events({ plan: 'standard' })]);
expect(invoice.lines).toEqual([]);
expect(invoice.warnings[0]).toMatch(/no price for the "standard" plan/);
expect(empty).toBe(false);
});
test('month-end billing day stays on the last day', () => {
const { invoice, licenceUpdate } = draftInvoice({ licence: licence({ billingStart: day('2026-01-31'), nextInvoiceDate: day('2027-01-31'), reviewDate: day('2028-01-31') }), customer: customer(), install: install(null), settings });
const { invoice, customerUpdate } = draft(customer({ billingStart: day('2026-01-31'), nextInvoiceDate: day('2027-01-31'), reviewDate: day('2028-01-31') }), [events({ billedUntil: day('2027-01-30') })]);
expect(ymd(invoice.periodEnd)).toBe('2027-02-27');
expect(ymd(licenceUpdate.nextInvoiceDate)).toBe('2027-02-28');
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-02-28');
});
test('nothing billed (only Accounts, a trial or a suspended licence): no invoice, the customer still moves on', () => {
for (const licences of [[accounts()], [events({ billedFrom: null })], [events({ status: 'suspended' })], []]) {
const { empty, customerUpdate } = draft(customer(), licences);
expect(empty).toBe(true);
expect(ymd(customerUpdate.nextInvoiceDate)).toBe('2027-01-01');
}
});
});
describe('drafting an invoice (several products, Hub 2.0)', () => {
test('two products: each at its price, then 15% off them', () => {
const { invoice } = draft(customer(), [events(), website(), accounts()]);
expect(amounts(invoice)).toEqual([
['Cross Events, Sprout tier, December 2026', 55000],
['Church Website, December 2026', 9900],
['Bundle discount (15%: Cross Events and Church Website)', -9735],
]);
expect(invoice.totalCents).toBe(55165);
expect(invoice.plan).toBe('Cross Events Sprout · Church Website');
});
test('three products: 25% off, after the founding prices (decision 1)', () => {
const { invoice } = draft(customer({ founding: true }), [events(), website(), app()]);
// Founding: 360 + 64 + 64 = R488, less 25% = R366.
expect(invoice.totalCents).toBe(36600);
expect(invoice.lines.at(-1)).toMatchObject({ description: 'Bundle discount (25%: Cross Events, Church Website and Church App)', amountCents: -12200 });
});
test('Accounts never counts towards a bundle, and is never on the invoice', () => {
const { invoice } = draft(customer(), [events(), accounts()]);
expect(invoice.lines.some(l => /Bundle|Accounts/.test(l.description))).toBe(false);
});
test('extra website storage: R20 per 5 GB a month, never discounted', () => {
const { invoice } = draft(customer({ founding: true }), [events(), website({ install: { product: 'website', stats: { storage: { usedBytes: 12 * GB, includedBytes: 5 * GB } } } })]);
expect(invoice.lines.at(-1)).toEqual({ description: 'Extra website storage: 2 × 5 GB, December 2026', quantity: 2, unitCents: 2000, amountCents: 4000 });
// The bundle comes off the products only: (360 + 64) × 15% = R63.60.
expect(invoice.lines.find(l => /Bundle/.test(l.description)).amountCents).toBe(-6360);
});
test('yearly: add-ons are 12 months\' price (decision 2), products 10', () => {
const { invoice } = draft(customer({ billingCycle: 'yearly', reviewDate: day('2027-12-01') }), [website({ install: { product: 'website', stats: { storage: { usedBytes: 8 * GB } } } })]);
expect(invoice.lines.map(l => [l.quantity, l.unitCents])).toEqual([[10, 9900], [12, 2000]]);
});
test('the App is reviewed on its active members', () => {
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [app({ billedUntil: day('2026-12-31'), install: { product: 'app', stats: { activeMembers90d: '301–750' } } })]);
expect(invoice.planChange).toEqual([expect.objectContaining({ licenceId: 'l3', product: 'app', from: 'Mustard Seed', to: 'Congregation', toMonthlyCents: 39900, band: '301–750' })]);
expect(invoice.totalCents).toBe(39900);
});
test('several tier changes at one review: one per product', () => {
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01') }), [
events({ billedUntil: day('2026-12-31'), install: install('R250 001–R400 000') }),
app({ billedUntil: day('2026-12-31'), install: { product: 'app', stats: { activeMembers90d: '101–300' } } }),
]);
expect(invoice.planChange.map(pc => `${pc.product}:${pc.to}`)).toEqual(['events:Grow', 'app:Small Group']);
});
});
describe('a product added part-way (decision 3)', () => {
test('starting inside the period being drafted: charged from its first day', () => {
const { invoice, licenceUpdates } = draft(customer(), [events(), website({ billedFrom: day('2026-12-20'), billedUntil: null })]);
// R99 a month = R1 188 a year; 12 days of it.
expect(amounts(invoice)[1]).toEqual(['Church Website, 20 Dec 2026 – 31 Dec 2026 (12 days, from its start)', Math.round((9900 * 12 / 365) * 12)]);
expect(licenceUpdates.find(u => u.id === 'l2').data.billedUntil).toEqual(day('2026-12-31'));
// It counts for the bundle in that period.
expect(invoice.lines.some(l => /Bundle discount \(15%/.test(l.description))).toBe(true);
});
test('starting in a period invoiced already: those days on the next invoice, then the full period', () => {
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01'), reviewDate: day('2027-06-01') }), [
events({ billedUntil: day('2026-12-31') }),
app({ billedFrom: day('2026-12-15'), billedUntil: null }),
]);
expect(amounts(invoice).slice(1, 3)).toEqual([
['Church App, Mustard Seed tier, 15 Dec 2026 – 31 Dec 2026 (17 days before this period)', Math.round((9900 * 12 / 365) * 17)],
['Church App, Mustard Seed tier, January 2027', 9900],
]);
});
test('starting after the period: not on this invoice', () => {
const { invoice } = draft(customer(), [events(), website({ billedFrom: day('2027-01-05'), billedUntil: null })]);
expect(invoice.lines.map(l => l.description)).toEqual(['Cross Events, Sprout tier, December 2026']);
});
test('days are never charged twice', () => {
// Invoiced up to the end of December already: nothing owed from before January.
const { invoice } = draft(customer({ nextInvoiceDate: day('2027-01-01'), reviewDate: day('2027-06-01') }), [app({ billedFrom: day('2026-12-15'), billedUntil: day('2026-12-31') })]);
expect(invoice.lines.map(l => l.description)).toEqual(['Church App, Mustard Seed tier, January 2027']);
});
test('a founding church\'s founding price is prorated the same way', () => {
const { lines } = customerInvoiceLines({
customer: customer({ founding: true }), licences: [website({ billedFrom: day('2026-12-20'), billedUntil: null })],
period: { start: day('2026-12-01'), end: day('2026-12-31'), cycle: 'monthly' }, reviewed: false,
});
const full = Math.round((9900 * 12 / 365) * 12);
expect(lines.map(l => l.amountCents)).toEqual([full, Math.round((full * -3500) / 9900)]);
});
});
describe('tier changes stored before Hub 2.0', () => {
test('one object reads as a list of one Cross Events change', () => {
expect(planChangesOf({ licenceId: 'l1', planChange: { from: 'Seed', to: 'Sprout' } })).toEqual([{ licenceId: 'l1', product: 'events', from: 'Seed', to: 'Sprout' }]);
expect(planChangesOf({ planChange: null })).toEqual([]);
});
});
+22
View File
@@ -110,6 +110,28 @@ describe('licences', () => {
await expect(checkReopen(mockDb, old, 'revoked')).resolves.toBeUndefined();
});
test('a product added to a customer that is billed already starts after its free month', async () => {
mockDb.customer = { findUnique: jest.fn(async () => ({ id: 'c1', billingCycle: 'monthly' })) };
try {
const { licence, accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'app', data: {}, now: new Date('2026-11-04T10:00:00Z') });
expect(licence.billedFrom.toISOString().slice(0, 10)).toBe('2026-12-04');
// Accounts is free: never charged.
expect(accounts.billedFrom).toBeUndefined();
} finally {
delete mockDb.customer;
}
});
test('a customer not billed yet: the product waits until billing is set up', async () => {
mockDb.customer = { findUnique: jest.fn(async () => ({ id: 'c1', billingCycle: 'none' })) };
try {
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
expect(licence.billedFrom).toBeUndefined();
} finally {
delete mockDb.customer;
}
});
test('unknown products are refused', async () => {
await expect(createLicence(mockDb, { customerId: 'c1', product: 'shop' })).rejects.toMatchObject({ status: 400 });
});
@@ -10,6 +10,7 @@ import { Loading, Message, PageTitle } from "@/components/ui";
import { EMAIL_KIND, METHOD, StateBadge, day, money, todayYmd, type BillingEmail, type Invoice, type LicenceChange } from "@/lib/billing";
import { LinesEditor, editTotal, fromEdit, toEdit, type EditLine } from "@/components/billing/LinesEditor";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { PRODUCT_NAMES } from "@/lib/products";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = Invoice & { licenceChanges: LicenceChange[]; emails: BillingEmail[] };
@@ -102,8 +103,9 @@ function InvoiceDetail({ id }: { id: string }) {
const approve = () => {
if (dirty) { setMsg({ type: "err", text: "Save your changes first." }); return; }
const when = inv.issueDate <= todayYmd() ? "within the next 15 minutes (its date has come)" : `on ${day(inv.issueDate)}`;
if (!confirm(`Approve ${inv.number}? It goes to ${inv.recipientEmail} ${when}.${inv.planChange ? `\n\nThe church is also sent a notice of licence change (${inv.planChange.from} → ${inv.planChange.to}) now.` : ""}`)) return;
act("approve", "approve", {}, r => `Approved. It goes out ${when}.${r.notice ? (r.notice.email?.ok ? ` The notice of licence change ${r.notice.change.number} was emailed.` : ` The notice ${r.notice.change.number} couldn't be emailed: ${r.notice.email?.error}`) : ""}`);
const changes = inv.planChanges.map(pc => `${PRODUCT_NAMES[pc.product || "events"]}: ${pc.from} → ${pc.to}`).join(", ");
if (!confirm(`Approve ${inv.number}? It goes to ${inv.recipientEmail} ${when}.${changes ? `\n\nThe church is also sent a notice of licence change for each tier change (${changes}) now.` : ""}`)) return;
act("approve", "approve", {}, r => `Approved. It goes out ${when}.${r.notice ? (r.notice.email?.ok ? ` The notice of licence change ${r.notice.change.number}${inv.planChanges.length > 1 ? " (and the others)" : ""} was emailed.` : ` The notice ${r.notice.change.number} couldn't be emailed: ${r.notice.email?.error}`) : ""}`);
};
const voidIt = () => {
const reason = prompt(`Void ${inv.number}? It stays on record, marked void. Why (printed on it)?`, "");
@@ -111,11 +113,12 @@ function InvoiceDetail({ id }: { id: string }) {
act("void", "void", { reason }, () => `${inv.number} is void.`);
};
const dropChange = async () => {
if (!confirm("Remove the tier change from this invoice? The tier stays as it is; then press Recalculate to price it at that tier.")) return;
const many = inv.planChanges.length > 1;
if (!confirm(`Remove the tier change${many ? "s" : ""} from this invoice? The tier${many ? "s stay" : " stays"} as ${many ? "they are" : "it is"}${inv.licenceId ? "; then press Recalculate to price it at that tier" : ", and the draft is priced at them again"}.`)) return;
setBusy("drop");
try {
await api(`/api/admin/billing/invoices/${id}`, { method: "PUT", body: { dropPlanChange: true } });
setMsg({ type: "ok", text: "Tier change removed. Press Recalculate to price it at the current tier." });
setMsg({ type: "ok", text: inv.licenceId ? "Tier change removed. Press Recalculate to price it at the current tier." : `Tier change${many ? "s" : ""} removed, and the draft repriced.` });
await load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(null); }
};
@@ -141,7 +144,7 @@ function InvoiceDetail({ id }: { id: string }) {
<div className="mb-4 flex flex-wrap gap-2">
{inv.status === "draft" && <button className="btn-primary" onClick={approve} disabled={!!busy}><Check className="h-4 w-4" /> {busy === "approve" ? "Approving…" : "Approve"}</button>}
{inv.status === "draft" && inv.licenceId && inv.periodStart && <button className="btn-secondary" onClick={() => act("recalc", "recalculate", {}, () => "Recalculated from the licence and founding status as they are now.")} disabled={!!busy}><RefreshCw className="h-4 w-4" /> Recalculate</button>}
{inv.status === "draft" && inv.periodStart && inv.cycle !== "none" && <button className="btn-secondary" onClick={() => act("recalc", "recalculate", {}, () => "Recalculated from the church's products, prices and founding status as they are now.")} disabled={!!busy}><RefreshCw className="h-4 w-4" /> Recalculate</button>}
{inv.status === "approved" && <button className="btn-primary" onClick={() => confirm(`Send ${inv.number} to ${inv.recipientEmail} now?`) && act("send", "send", {}, () => `Sent to ${inv.recipientEmail}.`)} disabled={!!busy}><Send className="h-4 w-4" /> {busy === "send" ? "Sending…" : "Send now"}</button>}
{inv.status === "approved" && <button className="btn-secondary" onClick={() => act("unapprove", "unapprove", {}, () => "Back to draft: it won't go out until you approve it again.")} disabled={!!busy}><Undo2 className="h-4 w-4" /> Back to draft</button>}
{inv.status === "sent" && inv.balanceCents > 0 && <button className="btn-primary" onClick={() => setPaying(true)}>Record payment</button>}
@@ -157,10 +160,18 @@ function InvoiceDetail({ id }: { id: string }) {
<ul className="list-disc space-y-0.5 pl-5">{inv.warnings.map(w => <li key={w}>{w}</li>)}</ul>
</div>
)}
{inv.planChange && (
{inv.planChanges.length > 0 && (
<div className="mb-4 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-sky-200 bg-sky-50 p-3 text-sm text-sky-900">
<div><strong>Annual review: {inv.planChange.from} → {inv.planChange.to}</strong>{inv.planChange.band ? ` (12-month event income ${inv.planChange.band})` : ""}. {inv.status === "draft" ? "Approving sends the church a notice of licence change straight away; the tier changes when this invoice goes out." : inv.status === "approved" ? "The notice was sent; the tier changes when this invoice goes out." : ""}</div>
{inv.status === "draft" && <button className="btn-secondary" onClick={dropChange} disabled={!!busy}>Keep the tier</button>}
<div>
{inv.planChanges.map(pc => (
<div key={`${pc.product}-${pc.to}`}>
<strong>Annual review, {PRODUCT_NAMES[pc.product || "events"]}: {pc.from} → {pc.to}</strong>
{pc.band ? ` (${pc.product === "app" ? "active members" : "12-month event income"} ${pc.band})` : ""}
</div>
))}
<div className="mt-1">{inv.status === "draft" ? `Approving sends the church a notice of licence change for each straight away; the tier${inv.planChanges.length > 1 ? "s change" : " changes"} when this invoice goes out.` : inv.status === "approved" ? "The notices were sent; the tiers change when this invoice goes out." : ""}</div>
</div>
{inv.status === "draft" && <button className="btn-secondary" onClick={dropChange} disabled={!!busy}>Keep the tier{inv.planChanges.length > 1 ? "s" : ""}</button>}
</div>
)}
+17 -8
View File
@@ -6,15 +6,18 @@ import { FileText, Play, Plus, Star } from "lucide-react";
import { api, errorText, openPdf } from "@/lib/api";
import { matches, usePaged } from "@/lib/paging";
import { Loading, Message, PageTitle, Pager, SearchInput, Stat, Tabs } from "@/components/ui";
import { CYCLE, METHOD, StateBadge, day, money, type BillingCycle, type Invoice, type Payment } from "@/lib/billing";
import { CYCLE, METHOD, StateBadge, day, money, todayYmd, type BillingCycle, type Invoice, type Payment } from "@/lib/billing";
import { RecordPayment } from "@/components/billing/RecordPayment";
import { PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
type Msg = { type: "ok" | "err"; text: string } | null;
type Overview = { drafts: number; approved: number; owingCents: number; overdueCents: number; overdue: number; receivedThisMonthCents: number };
type Account = {
id: string; name: string; founding: boolean; foundingSince: string | null; foundingNote: string | null; billingEmail: string | null;
balanceCents: number; overdue: number;
licences: { id: string; key: string; plan: string; status: string; billingCycle: BillingCycle; nextInvoiceDate: string | null; reviewDate: string | null; customMonthlyCents: number | null; url: string | null }[];
// Hub 2.0: the schedule is the church's, for all its products.
billingCycle: BillingCycle; nextInvoiceDate: string | null; reviewDate: string | null;
licences: { id: string; key: string; product: Product; plan: string; status: string; billable: boolean; billedFrom: string | null; customMonthlyCents: number | null; url: string | null }[];
};
type Tab = "invoices" | "payments" | "churches";
const TABS: { key: Tab; label: string }[] = [
@@ -126,7 +129,7 @@ export default function BillingPage() {
<tbody>
{invPaged.rows.map(i => (
<tr key={i.id} className="border-t border-slate-100">
<td className="p-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link>{i.planChange && <div className="text-xs text-amber-700">{i.planChange.from} → {i.planChange.to}</div>}{i.warnings.length > 0 && i.status === "draft" && <div className="text-xs text-amber-700">Check {i.warnings.length === 1 ? "1 note" : `${i.warnings.length} notes`}</div>}</td>
<td className="p-3"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link>{i.planChanges.map(pc => <div key={`${pc.product}-${pc.to}`} className="text-xs text-amber-700">{pc.product && pc.product !== "events" ? `${PRODUCT_NAMES[pc.product]}: ` : ""}{pc.from} → {pc.to}</div>)}{i.warnings.length > 0 && i.status === "draft" && <div className="text-xs text-amber-700">Check {i.warnings.length === 1 ? "1 note" : `${i.warnings.length} notes`}</div>}</td>
<td className="p-3">{i.customer?.name}{i.customer?.founding && <Star className="ml-1 inline h-3.5 w-3.5 fill-amber-400 text-amber-400" aria-label="Founding church" />}<div className="text-xs text-slate-500">{i.plan || "One-off"}</div></td>
<td className="p-3 whitespace-nowrap">{day(i.issueDate)}<div className="text-xs text-slate-500">due {day(i.dueDate)}</div></td>
<td className="p-3 text-right tabular-nums">{money(i.totalCents)}</td>
@@ -167,10 +170,10 @@ export default function BillingPage() {
{tab === "churches" && (!accounts ? <Loading /> : (
<>
<p className="mb-3 text-sm text-slate-600">{founding} founding church{founding === 1 ? "" : "es"}. Founding churches pay the founding price (35% less) on every tier for as long as they stay. Set billing up for each licence on the church&apos;s page.</p>
<p className="mb-3 text-sm text-slate-600">{founding} founding church{founding === 1 ? "" : "es"}. Founding churches pay the founding price (35% less) on every tier for as long as they stay. Set billing up on the church&apos;s page: one invoice covers all its products.</p>
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Church</th><th className="p-3">Founding</th><th className="p-3">Tier and billing</th><th className="p-3">Next invoice</th><th className="p-3 text-right">Owing</th></tr></thead>
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Church</th><th className="p-3">Founding</th><th className="p-3">Products</th><th className="p-3">Billing</th><th className="p-3 text-right">Owing</th></tr></thead>
<tbody>
{shownAccounts.map(a => (
<tr key={a.id} className="border-t border-slate-100 align-top">
@@ -179,10 +182,16 @@ export default function BillingPage() {
<label className="inline-flex items-center gap-2"><input type="checkbox" checked={a.founding} onChange={() => toggleFounding(a)} /> {a.founding ? "Founding" : "No"}</label>
{a.founding && <div className="text-xs text-slate-500">{a.foundingSince ? `since ${day(a.foundingSince)}` : ""}{a.foundingNote ? ` · ${a.foundingNote}` : ""}</div>}
</td>
<td className="p-3">{a.licences.length === 0 ? <span className="text-slate-400">No licence</span> : a.licences.map(l => (
<div key={l.id}>{l.plan}{l.customMonthlyCents != null ? ` (${money(l.customMonthlyCents)}/month)` : ""} · <span className={l.billingCycle === "none" ? "text-slate-400" : ""}>{CYCLE[l.billingCycle]}</span>{l.status !== "active" && <span className="text-red-600"> · {l.status}</span>}</div>
<td className="p-3">{a.licences.filter(l => l.billable).length === 0 ? <span className="text-slate-400">No product licence</span> : [...a.licences].filter(l => l.billable).sort(byProduct).map(l => (
<div key={l.id}>
{PRODUCT_NAMES[l.product]}: {l.plan}{l.customMonthlyCents != null ? ` (${money(l.customMonthlyCents)}/month)` : ""}
{l.status !== "active" ? <span className="text-red-600"> · {l.status}</span> : !l.billedFrom ? <span className="text-slate-400"> · not charged</span> : l.billedFrom > todayYmd() ? <span className="text-xs text-slate-500"> · from {day(l.billedFrom)}</span> : null}
</div>
))}</td>
<td className="p-3">{a.licences.filter(l => l.billingCycle !== "none").map(l => <div key={l.id}>{day(l.nextInvoiceDate)}{l.reviewDate && <span className="text-xs text-slate-500"> · review {day(l.reviewDate)}</span>}</div>)}</td>
<td className="p-3">
<span className={a.billingCycle === "none" ? "text-slate-400" : ""}>{CYCLE[a.billingCycle]}</span>
{a.billingCycle !== "none" && <div className="text-xs text-slate-500">next {day(a.nextInvoiceDate)}{a.reviewDate ? ` · review ${day(a.reviewDate)}` : ""}</div>}
</td>
<td className={`p-3 text-right tabular-nums ${a.overdue ? "text-red-700" : ""}`}>{a.balanceCents ? money(a.balanceCents) : "—"}{a.overdue > 0 && <div className="text-xs">{a.overdue} overdue</div>}</td>
</tr>
))}
@@ -6,7 +6,7 @@ import { useParams } from "next/navigation";
import { ArrowLeft, Copy, KeyRound } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { PLANS } from "@/lib/tiers";
import { PLANS_BY_PRODUCT } from "@/lib/tiers";
import { KEY_WHERE, PRODUCTS, PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
import type { Customer, Licence, LicenceStatus } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
@@ -76,15 +76,13 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
<div className="grid gap-3 sm:grid-cols-6">
<div>
<label className="label" htmlFor={`plan-${licence.id}`}>Plan</label>
{licence.product === "events" ? (
<select id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })}>
{!PLANS.includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
{PLANS.map(p => <option key={p} value={p}>{p}</option>)}
</select>
) : licence.product === "accounts" ? (
{licence.product === "accounts" ? (
<input id={`plan-${licence.id}`} className="input" value="Included" disabled />
) : (
<input id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })} />
<select id={`plan-${licence.id}`} className="input" value={form.plan} onChange={e => setForm({ ...form, plan: e.target.value })}>
{!PLANS_BY_PRODUCT[licence.product].includes(form.plan) && <option value={form.plan}>{form.plan}</option>}
{PLANS_BY_PRODUCT[licence.product].map(p => <option key={p} value={p}>{p}</option>)}
</select>
)}
<p className="mt-1 text-xs text-slate-500">
{licence.product === "accounts"
@@ -5,45 +5,103 @@ import Link from "next/link";
import { FileText, Mail, Plus, Star } from "lucide-react";
import { api, errorText, openPdf } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { CYCLE, EMAIL_KIND, METHOD, StateBadge, centsFrom, day, money, randInput, todayYmd, type BillingCycle, type BillingEmail, type BillingTier, type Invoice, type LicenceChange, type Payment } from "@/lib/billing";
import { CYCLE, EMAIL_KIND, METHOD, StateBadge, centsFrom, day, money, randInput, todayYmd, type BillingCycle, type BillingEmail, type Invoice, type LicenceChange, type Line, type Payment, type PlanChange } from "@/lib/billing";
import { PRODUCT_NAMES, byProduct, type Product } from "@/lib/products";
import { RecordPayment } from "./RecordPayment";
type Msg = { type: "ok" | "err"; text: string } | null;
type BillingLicence = { id: string; key: string; plan: string; status: string; billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null; customMonthlyCents: number | null; url: string | null; incomeBand: string | null };
/** A plan of a product: the Events tiers have an income ceiling (upTo), the App tiers a member band. */
type Plan = { name: string; monthly: number | null; founding: number | null; upTo?: number | null; band?: string };
type BillingLicence = {
id: string; key: string; product: Product; plan: string; status: string; customMonthlyCents: number | null;
billedFrom: string | null; billedUntil: string | null; billable: boolean; url: string | null;
incomeBand?: string | null; activeMembers?: string | null; storage?: { usedBytes: number; includedBytes: number } | null;
};
type CustomerBillingData = {
id: string; name: string; billingEmail: string | null; billingAddress: string | null; founding: boolean; foundingSince: string | null; foundingNote: string | null;
sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[]; tiers: BillingTier[];
billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null;
sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[];
plans: Record<Product, Plan[]>;
};
type Preview = { billed: false } | { billed: true; empty: boolean; invoice: { periodStart: string; periodEnd: string; issueDate: string; lines: Line[]; totalCents: number; warnings: string[]; planChanges: PlanChange[] } };
const yearAgo = () => { const d = new Date(`${todayYmd()}T00:00:00Z`); d.setUTCFullYear(d.getUTCFullYear() - 1); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); };
const gb = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GB`;
/** The tier a band ("R100 001–R150 000") falls in. */
function tierFor(tiers: BillingTier[], band: string | null) {
if (!band || band === "over R100 000") return null;
if (/^over /.test(band)) return tiers.find(t => t.upTo == null) || null;
/** The tier a product's report points to: an Events income band ("R100 001–R150 000") or an App member band. */
function suggestedTier(licence: BillingLicence, plans: Plan[]) {
if (licence.product === "app") return plans.find(p => p.band && p.band === licence.activeMembers) || null;
const band = licence.incomeBand;
if (licence.product !== "events" || !band || band === "over R100 000") return null;
if (/^over /.test(band)) return plans.find(t => t.upTo == null) || null;
const top = Number((band.split("–")[1] || "").replace(/[^\d]/g, ""));
return tiers.find(t => t.upTo == null || top <= t.upTo) || null;
return plans.find(t => t.upTo == null || top <= (t.upTo ?? Infinity)) || null;
}
/** One licence's billing set-up, and a notice of licence change for it. */
function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingLicence; tiers: BillingTier[]; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({
billingCycle: licence.billingCycle, billingStart: licence.billingStart || "", nextInvoiceDate: licence.nextInvoiceDate || "",
reviewDate: licence.reviewDate || "", custom: randInput(licence.customMonthlyCents),
});
/** What the product reports that its price depends on. */
function reportText(l: BillingLicence) {
if (l.product === "events") return l.incomeBand ? `12-month event income ${l.incomeBand}` : "No event income reported yet";
if (l.product === "app") return l.activeMembers ? `${l.activeMembers} active members (90 days)` : "No active members reported yet";
if (l.product === "website") return l.storage ? `${gb(l.storage.usedBytes)} of ${gb(l.storage.includedBytes)} storage used` : "No storage reported yet";
return "";
}
/** The church's billing schedule: one for all its products. */
function Schedule({ c, onSaved, setMsg }: { c: CustomerBillingData; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({ billingCycle: c.billingCycle, billingStart: c.billingStart || "", nextInvoiceDate: c.nextInvoiceDate || "", reviewDate: c.reviewDate || "" });
const [busy, setBusy] = useState(false);
const off = form.billingCycle === "none";
const save = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
try {
await api(`/api/admin/billing/customers/${c.id}`, { method: "PUT", body: { billingCycle: form.billingCycle, billingStart: form.billingStart || null, nextInvoiceDate: form.nextInvoiceDate || null, reviewDate: form.reviewDate || null } });
setMsg({ type: "ok", text: off ? "Saved: this church isn't billed." : "Billing saved. The next draft, for all the church's products, is made 14 days before the next invoice date." });
onSaved();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); } finally { setBusy(false); }
};
return (
<form onSubmit={save} className="space-y-3">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<div>
<label className="label" htmlFor="cycle">Billing</label>
<select id="cycle" className="input" value={form.billingCycle} onChange={e => setForm({ ...form, billingCycle: e.target.value as BillingCycle })}>
{(Object.keys(CYCLE) as BillingCycle[]).map(k => <option key={k} value={k}>{CYCLE[k]}</option>)}
</select>
</div>
<div><label className="label" htmlFor="start">Billing started</label><input id="start" type="date" className="input" value={form.billingStart} onChange={e => setForm({ ...form, billingStart: e.target.value })} disabled={off} /></div>
<div><label className="label" htmlFor="next">Next invoice</label><input id="next" type="date" className="input" value={form.nextInvoiceDate} onChange={e => setForm({ ...form, nextInvoiceDate: e.target.value })} disabled={off} /></div>
<div><label className="label" htmlFor="review">Next tier review</label><input id="review" type="date" className="input" value={form.reviewDate} onChange={e => setForm({ ...form, reviewDate: e.target.value })} disabled={off} /></div>
</div>
<p className="text-xs text-slate-500">One invoice covers all the church&apos;s products, in advance, on the same day of the month as billing started. Leave the next invoice and review blank to start from the billing date and review a year later. Starting billing charges the products that aren&apos;t charged yet from the billing date; a product added later starts after its free month.</p>
<button className="btn-primary" disabled={busy}>Save billing</button>
</form>
);
}
/** One licence's billing: when it's charged from, a custom price, and a notice of licence change. */
function LicenceBilling({ licence, plans, nextInvoiceDate, onSaved, setMsg }: { licence: BillingLicence; plans: Plan[]; nextInvoiceDate: string | null; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({ billedFrom: licence.billedFrom || "", custom: randInput(licence.customMonthlyCents) });
const [change, setChange] = useState<{ toPlan: string; effectiveDate: string; price: string; reason: string } | null>(null);
const [busy, setBusy] = useState(false);
const suggested = tierFor(tiers, licence.incomeBand);
const tier = tiers.find(t => t.name === licence.plan);
const suggested = suggestedTier(licence, plans);
const tier = plans.find(t => t.name === licence.plan);
const name = PRODUCT_NAMES[licence.product];
if (!licence.billable) {
return (
<div className="rounded-lg border border-slate-200 p-4 text-sm">
<span className="font-medium">{name}</span> <code className="ml-2 text-xs">{licence.key}</code>
<span className="ml-2 text-slate-500">Free: comes with the church&apos;s other products, never invoiced.</span>
</div>
);
}
const save = async () => {
setBusy(true);
try {
await api(`/api/admin/billing/licences/${licence.id}`, {
method: "PUT",
body: { billingCycle: form.billingCycle, billingStart: form.billingStart || null, nextInvoiceDate: form.nextInvoiceDate || null, reviewDate: form.reviewDate || null, customMonthlyCents: form.custom.trim() ? centsFrom(form.custom) : null },
});
setMsg({ type: "ok", text: form.billingCycle === "none" ? "Saved: this licence isn't billed." : "Billing saved. The next draft is made 14 days before the next invoice date." });
await api(`/api/admin/billing/licences/${licence.id}`, { method: "PUT", body: { billedFrom: form.billedFrom || null, customMonthlyCents: form.custom.trim() ? centsFrom(form.custom) : null } });
setMsg({ type: "ok", text: form.billedFrom ? `${name}: charged from ${day(form.billedFrom)}.` : `${name}: not charged.` });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
@@ -51,7 +109,7 @@ function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingL
const sendChange = async (e: React.FormEvent) => {
e.preventDefault();
if (!change) return;
if (!confirm(`Email ${licence.plan} → ${change.toPlan} from ${day(change.effectiveDate)} to the church now?`)) return;
if (!confirm(`Email ${name}: ${licence.plan} → ${change.toPlan} from ${day(change.effectiveDate)} to the church now?`)) return;
setBusy(true);
try {
const r = await api<{ change: LicenceChange; email: { ok: boolean; error: string | null } | null }>("/api/admin/billing/licence-changes", {
@@ -66,28 +124,25 @@ function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingL
return (
<div className="rounded-lg border border-slate-200 p-4">
<div className="mb-3 flex flex-wrap items-baseline justify-between gap-2">
<div><code className="text-xs">{licence.key}</code>{licence.url && <span className="ml-2 text-xs text-slate-500">{licence.url.replace(/^https?:\/\//, "")}</span>}</div>
<div><span className="font-medium">{name}</span> <code className="ml-2 text-xs">{licence.key}</code>{licence.url && <span className="ml-2 text-xs text-slate-500">{licence.url.replace(/^https?:\/\//, "")}</span>}</div>
<div className="text-sm">
Tier <strong>{licence.plan}</strong>{licence.customMonthlyCents != null ? ` at ${money(licence.customMonthlyCents)}/month` : tier?.monthly != null ? ` (R${tier.monthly}/month)` : ""}
{licence.incomeBand && <span className="ml-2 text-xs text-slate-500">12-month income {licence.incomeBand}{suggested && suggested.name !== licence.plan ? ` → ${suggested.name} at the next review` : ""}</span>}
{licence.product === "website" ? "Website" : <>Tier <strong>{licence.plan}</strong></>}
{licence.customMonthlyCents != null ? ` at ${money(licence.customMonthlyCents)}/month` : tier?.monthly != null ? ` (R${tier.monthly}/month)` : ""}
<span className="ml-2 text-xs text-slate-500">{reportText(licence)}{suggested && suggested.name !== licence.plan ? ` → ${suggested.name} at the next review` : ""}</span>
</div>
</div>
<div className="grid gap-3 sm:grid-cols-3 lg:grid-cols-5">
<div className="grid gap-3 sm:grid-cols-3">
<div>
<label className="label" htmlFor={`cycle-${licence.id}`}>Billing</label>
<select id={`cycle-${licence.id}`} className="input" value={form.billingCycle} onChange={e => setForm({ ...form, billingCycle: e.target.value as BillingCycle })}>
{(Object.keys(CYCLE) as BillingCycle[]).map(c => <option key={c} value={c}>{CYCLE[c]}</option>)}
</select>
<label className="label" htmlFor={`from-${licence.id}`}>Charged from</label>
<input id={`from-${licence.id}`} type="date" className="input" value={form.billedFrom} onChange={e => setForm({ ...form, billedFrom: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{licence.billedUntil ? `Invoiced up to ${day(licence.billedUntil)}.` : "Not invoiced yet."} Blank: not charged (e.g. a trial).</p>
</div>
<div><label className="label" htmlFor={`start-${licence.id}`}>Billing started</label><input id={`start-${licence.id}`} type="date" className="input" value={form.billingStart} onChange={e => setForm({ ...form, billingStart: e.target.value })} disabled={form.billingCycle === "none"} /></div>
<div><label className="label" htmlFor={`next-${licence.id}`}>Next invoice</label><input id={`next-${licence.id}`} type="date" className="input" value={form.nextInvoiceDate} onChange={e => setForm({ ...form, nextInvoiceDate: e.target.value })} disabled={form.billingCycle === "none"} /></div>
<div><label className="label" htmlFor={`review-${licence.id}`}>Next tier review</label><input id={`review-${licence.id}`} type="date" className="input" value={form.reviewDate} onChange={e => setForm({ ...form, reviewDate: e.target.value })} disabled={form.billingCycle === "none"} /></div>
<div><label className="label" htmlFor={`custom-${licence.id}`}>Custom price (R/month)</label><input id={`custom-${licence.id}`} className="input" inputMode="decimal" placeholder="Tier price" value={form.custom} onChange={e => setForm({ ...form, custom: e.target.value })} /></div>
</div>
<p className="mt-2 text-xs text-slate-500">Invoices are in advance: each covers the month (or year) starting on its date, on the same day of the month as billing started. Leave the next invoice and review blank to start from the billing date and review a year later. A custom price replaces the tier&apos;s (e.g. Network); founding churches get 35% off it.</p>
<p className="mt-2 text-xs text-slate-500">A product that starts part-way through a period is charged by the day up to the next period. A custom price replaces the tier&apos;s (e.g. Network); founding churches get 35% off it.</p>
<div className="mt-3 flex flex-wrap gap-2">
<button className="btn-primary" onClick={save} disabled={busy}>Save billing</button>
{!change && <button className="btn-secondary" onClick={() => setChange({ toPlan: suggested && suggested.name !== licence.plan ? suggested.name : "", effectiveDate: licence.nextInvoiceDate || todayYmd(), price: "", reason: "" })}>Notice of licence change…</button>}
<button className="btn-primary" onClick={save} disabled={busy}>Save</button>
{plans.length > 1 && !change && <button className="btn-secondary" onClick={() => setChange({ toPlan: suggested && suggested.name !== licence.plan ? suggested.name : "", effectiveDate: nextInvoiceDate || todayYmd(), price: "", reason: "" })}>Notice of licence change…</button>}
</div>
{change && (
<form onSubmit={sendChange} className="mt-4 space-y-3 rounded-lg bg-slate-50 p-3">
@@ -97,7 +152,7 @@ function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingL
<label className="label" htmlFor={`to-${licence.id}`}>New tier</label>
<select id={`to-${licence.id}`} className="input" value={change.toPlan} onChange={e => setChange({ ...change, toPlan: e.target.value })} required>
<option value="">Choose…</option>
{tiers.map(t => <option key={t.name} value={t.name} disabled={t.name === licence.plan}>{t.name}{t.monthly != null ? ` (R${t.monthly}/month)` : " (custom price)"}</option>)}
{plans.map(t => <option key={t.name} value={t.name} disabled={t.name === licence.plan}>{t.name}{t.monthly != null ? ` (R${t.monthly}/month)` : " (custom price)"}</option>)}
</select>
</div>
<div><label className="label" htmlFor={`eff-${licence.id}`}>Takes effect</label><input id={`eff-${licence.id}`} type="date" className="input" value={change.effectiveDate} onChange={e => setChange({ ...change, effectiveDate: e.target.value })} required /></div>
@@ -111,6 +166,38 @@ function LicenceBilling({ licence, tiers, onSaved, setMsg }: { licence: BillingL
);
}
/** The next invoice as it would be drafted now: nothing is saved. */
function NextInvoice({ customerId, version }: { customerId: string; version: string }) {
const [p, setP] = useState<Preview | null>(null);
const [err, setErr] = useState<string | null>(null);
useEffect(() => {
api<Preview>(`/api/admin/billing/customers/${customerId}/preview`).then(setP).catch(e => setErr(errorText(e)));
}, [customerId, version]);
if (err) return <p className="text-sm text-red-700">{err}</p>;
if (!p) return null;
if (!p.billed) return <p className="text-sm text-slate-500">Not billed: set the billing up above to see the next invoice.</p>;
if (p.empty) return <p className="text-sm text-slate-500">Nothing to charge for the period from {day(p.invoice.periodStart)}: no product is charged yet.</p>;
const inv = p.invoice;
return (
<div className="space-y-2 text-sm">
<p className="text-slate-600">For {day(inv.periodStart)} – {day(inv.periodEnd)}, drafted 14 days before {day(inv.issueDate)}. As it stands today (prices, founding, what each product reports):</p>
<table className="w-full">
<tbody>
{inv.lines.map((l, i) => (
<tr key={i} className="border-t border-slate-100 first:border-0">
<td className="py-1.5 pr-3">{l.description}{l.quantity !== 1 ? <span className="text-xs text-slate-500"> · {l.quantity} × {money(l.unitCents)}</span> : null}</td>
<td className={`py-1.5 text-right tabular-nums ${l.amountCents < 0 ? "text-green-700" : ""}`}>{money(l.amountCents)}</td>
</tr>
))}
<tr className="border-t border-slate-300 font-semibold"><td className="py-1.5">Total</td><td className="py-1.5 text-right tabular-nums">{money(inv.totalCents)}</td></tr>
</tbody>
</table>
{inv.planChanges.length > 0 && <p className="text-sky-800">At this review: {inv.planChanges.map(pc => `${PRODUCT_NAMES[pc.product || "events"]} ${pc.from} → ${pc.to}`).join(", ")}.</p>}
{inv.warnings.length > 0 && <ul className="list-disc pl-5 text-amber-800">{inv.warnings.map(w => <li key={w}>{w}</li>)}</ul>}
</div>
);
}
/** Customer page → Billing: founding, where invoices go, each licence's billing, statements, invoices, payments. */
export function CustomerBilling({ customerId }: { customerId: string }) {
const [c, setC] = useState<CustomerBillingData | null>(null);
@@ -168,9 +255,21 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
<button className="btn-secondary">Save billing details</button>
</form>
<div className="card space-y-3">
<h3 className="font-semibold">Licences</h3>
{c.licences.length === 0 ? <p className="text-sm text-slate-500">Generate a licence first.</p> : c.licences.map(l => <LicenceBilling key={`${l.id}-${l.plan}-${l.billingCycle}-${l.nextInvoiceDate}-${l.reviewDate}-${l.customMonthlyCents}`} licence={l} tiers={c.tiers} onSaved={load} setMsg={setMsg} />)}
<div className="space-y-4">
<div className="card space-y-3">
<h3 className="font-semibold">Billing schedule</h3>
<Schedule key={`${c.billingCycle}-${c.billingStart}-${c.nextInvoiceDate}-${c.reviewDate}`} c={c} onSaved={load} setMsg={setMsg} />
</div>
<div className="card space-y-3">
<h3 className="font-semibold">Products</h3>
{c.licences.length === 0 ? <p className="text-sm text-slate-500">Generate a licence first.</p> : [...c.licences].filter(l => l.status !== "revoked").sort(byProduct).map(l => (
<LicenceBilling key={`${l.id}-${l.plan}-${l.billedFrom}-${l.billedUntil}-${l.customMonthlyCents}`} licence={l} plans={c.plans[l.product] || []} nextInvoiceDate={c.nextInvoiceDate} onSaved={load} setMsg={setMsg} />
))}
</div>
<div className="card space-y-3">
<h3 className="font-semibold">Next invoice</h3>
<NextInvoice customerId={customerId} version={JSON.stringify([c.founding, c.billingCycle, c.nextInvoiceDate, c.licences.map(l => [l.plan, l.billedFrom, l.billedUntil, l.customMonthlyCents, l.status])])} />
</div>
</div>
</div>
@@ -199,7 +298,7 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
<tr key={i.id} className="border-t border-slate-100">
<td className="py-2"><Link className="font-medium text-indigo-700 hover:underline" href={`/billing/invoices/${i.id}`}>{i.number}</Link></td>
<td className="py-2">{day(i.issueDate)}</td>
<td className="py-2">{i.plan || "One-off"}{i.planChange ? ` (from ${i.planChange.from})` : ""}</td>
<td className="py-2">{i.plan || "One-off"}{i.planChanges.length ? ` (from ${i.planChanges.map(pc => pc.from).join(", ")})` : ""}</td>
<td className="py-2 text-right tabular-nums">{money(i.totalCents)}</td>
<td className="py-2 text-right tabular-nums">{i.status === "sent" ? money(i.balanceCents) : "—"}</td>
<td className="py-2"><StateBadge state={i.state} short /></td>
+8 -3
View File
@@ -1,4 +1,5 @@
import React from "react";
import type { Product } from "./products";
// Billing (1.7.0): the shapes the billing API returns, and how they're shown.
@@ -6,7 +7,8 @@ export type InvoiceStatus = "draft" | "approved" | "sent" | "void";
export type InvoiceState = InvoiceStatus | "unpaid" | "part_paid" | "overdue" | "paid";
export type BillingCycle = "none" | "monthly" | "yearly";
export type Line = { description: string; quantity: number; unitCents: number; amountCents: number };
export type PlanChange = { from: string; to: string; fromMonthlyCents: number | null; toMonthlyCents: number | null; band?: string | null };
/** A tier change at the annual review (Hub 2.0: one per product). */
export type PlanChange = { licenceId?: string | null; product?: Product; from: string; to: string; fromMonthlyCents: number | null; toMonthlyCents: number | null; band?: string | null };
export type BillingTier = { name: string; upTo: number | null; monthly: number | null; founding: number | null };
export type Payment = {
@@ -18,13 +20,16 @@ export type Payment = {
export type Invoice = {
id: string; number: string; customerId: string; licenceId: string | null; status: InvoiceStatus; state: InvoiceState;
issueDate: string; dueDate: string; periodStart: string | null; periodEnd: string | null; cycle: BillingCycle;
plan: string | null; incomeBand: string | null; reviewed: boolean; founding: boolean; planChange: PlanChange | null;
plan: string | null; incomeBand: string | null; reviewed: boolean; founding: boolean;
/** The tier changes on this invoice (the API reads Hub 1.7's single change as a list of one). */
planChanges: PlanChange[];
lines: Line[]; totalCents: number; vatCents: number; paidCents: number; balanceCents: number;
notes: string | null; warnings: string[]; recipientEmail: string | null;
approvedAt: string | null; approvalEmailedAt: string | null; sentAt: string | null; sendError: string | null; voidedAt: string | null; voidReason: string | null;
createdAt: string; payments: Payment[];
customer?: { id: string; name: string; founding: boolean };
licence?: { id: string; key: string; plan: string; billingCycle: BillingCycle; installUrl: string | null } | null;
/** Before Hub 2.0 an invoice was for one licence; from 2.0 it's for the customer (null). */
licence?: { id: string; key: string; product: Product; plan: string; installUrl: string | null } | null;
};
export type LicenceChange = {
+31
View File
@@ -19,6 +19,37 @@ export const TIERS: Tier[] = [
/** Licence plans offered on a licence: the tiers, plus a trial. */
export const PLANS = ["Trial", ...TIERS.map(t => t.name)];
// Hub 2.0: the other products' prices (ROADMAP-v3 §10), the same as backend/src/utils/billing/tiers.js.
/** Church Website: one price, 5 GB of uploads included. */
export const WEBSITE_PLAN = { name: "Website", monthly: 99, founding: 64 };
export type AppTier = { name: string; band: string; monthly: number | null; founding: number | null };
/** Church App tiers, on active members in the last 90 days. */
export const APP_TIERS: AppTier[] = [
{ name: "Mustard Seed", band: "0–100", monthly: 99, founding: 64 },
{ name: "Small Group", band: "101–300", monthly: 249, founding: 162 },
{ name: "Congregation", band: "301–750", monthly: 399, founding: 259 },
{ name: "Gathering", band: "751–2 000", monthly: 649, founding: 422 },
{ name: "Multitude", band: "2 001–5 000", monthly: 999, founding: 649 },
{ name: "Network", band: "over 5 000", monthly: null, founding: null },
];
/** Plans offered on a licence, per product (Accounts has none: it's free). */
export const PLANS_BY_PRODUCT = {
events: PLANS,
website: [WEBSITE_PLAN.name],
app: ["Trial", ...APP_TIERS.map(t => t.name)],
accounts: [] as string[],
};
/** Extra website storage: R20 a month per 5 GB above the 5 GB included. Never discounted. */
export const STORAGE_ADDON = { includedGb: 5, stepGb: 5, monthly: 20 };
/** Bundles: % off the products (not add-ons) by how many are billed. */
export const BUNDLE_PERCENT: Record<number, number> = { 2: 15, 3: 25 };
/** The highest rand amount in a band label ("R100 001–R150 000" → 150000; "over R10 000 000" → Infinity). */
function bandTop(band: string): number | null {
if (/^over /i.test(band)) return Infinity;