Hub 2.0 step 5: the church's address

Own domain R0, Cross Code address R10, domain included R25 (custom price
for other endings), once per invoice and never discounted; renewal date
with a reminder 30 days before, once per renewal, and Renewed to move it on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-04 16:24:10 +02:00
co-authored by Claude Opus 5.5
parent fff1c6f4ef
commit fbbf72dcd8
9 changed files with 229 additions and 11 deletions
+6 -1
View File
@@ -56,6 +56,11 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`).
billing and the **next invoice** as it would be drafted today (`GET …/customers/:id/preview`). 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 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. they were, and their drafts can still be recalculated.
- **The church's address** (step 5), one for all its products: own domain (R0), Cross Code address
(`<church>.crosscode.co.za`, R10 a month) or domain included (R25 a month; other endings at cost
as a custom price). Charged once per invoice and never discounted (12 months' price when yearly).
For a domain included: its renewal date, an email to the alert address 30 days before (once per
renewal), and **Renewed** on the customer page to move it on a year.
### Changed ### Changed
@@ -65,7 +70,7 @@ Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`).
otherwise); the other products register with protocol v2 (step 2). otherwise); the other products register with protocol v2 (step 2).
- Migrations `20261104132032_products`, `20261104150000_releases_per_product`, - Migrations `20261104132032_products`, `20261104150000_releases_per_product`,
`20261104170000_billing_per_customer` (moves each billed licence's schedule to its customer, `20261104170000_billing_per_customer` (moves each billed licence's schedule to its customer,
so billing carries on unchanged). so billing carries on unchanged), `20261104190000_customer_address`.
## [1.7.0] - 2026-11-03 ## [1.7.0] - 2026-11-03
@@ -0,0 +1,13 @@
-- Hub 2.0: the church's address (own domain R0, Cross Code address R10, domain included R25), one per
-- customer. Existing churches use their own domain.
-- CreateEnum
CREATE TYPE "AddressType" AS ENUM ('own_domain', 'crosscode', 'included');
-- AlterTable
ALTER TABLE "Customer" ADD COLUMN "addressCustomCents" INTEGER,
ADD COLUMN "addressType" "AddressType" NOT NULL DEFAULT 'own_domain',
ADD COLUMN "domain" TEXT,
ADD COLUMN "domainRemindedFor" DATE,
ADD COLUMN "domainRenewsOn" DATE;
+18
View File
@@ -50,6 +50,18 @@ model Customer {
// The next annual tier review: the first invoice for a period starting on or after it uses // 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). // what each product reports (Events: 12-month event income; App: active members).
reviewDate DateTime? @db.Date reviewDate DateTime? @db.Date
// Hub 2.0: the church's address, one for all its products (ROADMAP-v3 §10), billed once per
// invoice and never discounted. own_domain R0 · crosscode (<church>.crosscode.co.za) R10 ·
// included (a domain registered in the church's name and renewed by Cross Code) R25.
addressType AddressType @default(own_domain)
// The domain: hopefamily.co.za, or hopefamily.crosscode.co.za for a Cross Code address.
domain String?
// A price per month instead of the option's (e.g. a .com charged at cost), in cents.
addressCustomCents Int?
// Domain included: when it's next due for renewal, and the renewal date Joshua was last
// reminded about (30 days before), so he's reminded once per renewal.
domainRenewsOn DateTime? @db.Date
domainRemindedFor DateTime? @db.Date
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
licences Licence[] licences Licence[]
@@ -113,6 +125,12 @@ model Licence {
@@index([customerId, product]) @@index([customerId, product])
} }
enum AddressType {
own_domain
crosscode
included
}
enum BillingCycle { enum BillingCycle {
none none
monthly monthly
+44 -3
View File
@@ -12,7 +12,7 @@ const { audit } = require('../utils/audit');
const billing = require('../utils/billing'); const billing = require('../utils/billing');
const compute = require('../utils/billing/compute'); const compute = require('../utils/billing/compute');
const { ymd, day, today } = require('../utils/billing/dates'); const { ymd, day, today } = require('../utils/billing/dates');
const { TIERS, PLANS, BUNDLE_PERCENT, STORAGE } = require('../utils/billing/tiers'); const { TIERS, PLANS, BUNDLE_PERCENT, STORAGE, ADDRESS } = require('../utils/billing/tiers');
const { addMonths } = require('../utils/billing/dates'); const { addMonths } = require('../utils/billing/dates');
const { BILLABLE, PRODUCT_NAMES } = require('../utils/products'); const { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
@@ -194,8 +194,14 @@ const billingLicence = l => ({
url: l.install?.url || null, ...reported(l), url: l.install?.url || null, ...reported(l),
}); });
/** A customer's schedule for the billing screens. */ /** A customer's schedule and address for the billing screens. */
const schedule = c => ({ billingCycle: c.billingCycle, billingStart: ymd(c.billingStart), nextInvoiceDate: ymd(c.nextInvoiceDate), reviewDate: ymd(c.reviewDate) }); const schedule = c => ({
billingCycle: c.billingCycle, billingStart: ymd(c.billingStart), nextInvoiceDate: ymd(c.nextInvoiceDate), reviewDate: ymd(c.reviewDate),
addressType: c.addressType, domain: c.domain, addressCustomCents: c.addressCustomCents, addressMonthlyCents: compute.addressMonthlyCents(c), domainRenewsOn: ymd(c.domainRenewsOn),
});
// A domain name: letters, digits and hyphens in dot-separated labels, at least one dot.
const DOMAIN_RE = /^(?=.{3,253}$)(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))+$/;
/** Every customer's billing at a glance: founding, schedule, licences' plans, balance. */ /** Every customer's billing at a glance: founding, schedule, licences' plans, balance. */
router.get('/customers', wrap(async (req, res) => { router.get('/customers', wrap(async (req, res) => {
@@ -246,9 +252,21 @@ router.get('/customers/:id', wrap(async (req, res) => {
plans: PLANS, plans: PLANS,
bundlePercent: BUNDLE_PERCENT, bundlePercent: BUNDLE_PERCENT,
storage: STORAGE, storage: STORAGE,
address: ADDRESS,
}); });
})); }));
// Domain included: Joshua renewed it, so the renewal date moves on a year.
router.post('/customers/:id/domain-renewed', wrap(async (req, res) => {
const c = await prisma.customer.findUnique({ where: { id: req.params.id } });
if (!c) throw bad('Customer not found', 404);
if (c.addressType !== 'included' || !c.domainRenewsOn) throw bad('This church has no domain of ours with a renewal date.');
const next = addMonths(c.domainRenewsOn, 12);
await prisma.customer.update({ where: { id: c.id }, data: { domainRenewsOn: next } });
await audit(req, 'domain_renewed', c.id, { domain: c.domain, until: ymd(next) });
res.json({ domainRenewsOn: ymd(next), message: `Renewed: next due ${ymd(next)}.` });
}));
// The next invoice as it would be drafted now (nothing is saved): its lines, discounts and total. // 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) => { router.get('/customers/:id/preview', wrap(async (req, res) => {
const { getSettings } = require('../utils/settings'); const { getSettings } = require('../utils/settings');
@@ -283,9 +301,32 @@ router.put('/customers/:id', wrap(async (req, res) => {
data.billingCycle = b.billingCycle; data.billingCycle = b.billingCycle;
} }
for (const f of ['billingStart', 'nextInvoiceDate', 'reviewDate']) if (b[f] !== undefined) data[f] = dayOrNull(b[f]); for (const f of ['billingStart', 'nextInvoiceDate', 'reviewDate']) if (b[f] !== undefined) data[f] = dayOrNull(b[f]);
// The address (Hub 2.0): one per church, for all its products.
if (b.addressType !== undefined) {
if (!Object.keys(ADDRESS).includes(b.addressType)) throw bad('Choose own domain, Cross Code address or domain included.');
data.addressType = b.addressType;
}
if (b.domain !== undefined) {
const d = text(b.domain, 253)?.toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '').replace(/^www\./, '') || null;
if (d && !DOMAIN_RE.test(d)) throw bad('The domain looks like hopefamily.co.za.');
data.domain = d;
}
if (b.addressCustomCents !== undefined) {
if (b.addressCustomCents === null || b.addressCustomCents === '') data.addressCustomCents = null;
else {
const n = Math.round(Number(b.addressCustomCents));
if (!Number.isInteger(n) || n < 0 || n > 1e7) throw bad('Enter the address price a month.');
data.addressCustomCents = n;
}
}
if (b.domainRenewsOn !== undefined) data.domainRenewsOn = dayOrNull(b.domainRenewsOn);
const existing = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: true } }); const existing = await prisma.customer.findUnique({ where: { id: req.params.id }, include: { licences: true } });
if (!existing) throw bad('Customer not found', 404); if (!existing) throw bad('Customer not found', 404);
const merged = { ...existing, ...data }; const merged = { ...existing, ...data };
if (merged.addressType === 'crosscode' && merged.domain && !merged.domain.endsWith('.crosscode.co.za')) throw bad('A Cross Code address ends in .crosscode.co.za, e.g. hopefamily.crosscode.co.za.');
if (merged.addressType === 'included' && !merged.domainRenewsOn && data.domainRenewsOn === undefined && b.addressType === 'included') {
throw bad('Give the date the domain is next due for renewal, so you\'re reminded in time.');
}
if (merged.billingCycle !== 'none') { if (merged.billingCycle !== 'none') {
if (!merged.billingStart) throw bad('Set the date billing starts.'); if (!merged.billingStart) throw bad('Set the date billing starts.');
if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart; if (!merged.nextInvoiceDate) data.nextInvoiceDate = merged.billingStart;
+24 -2
View File
@@ -20,7 +20,7 @@
*/ */
const { const {
tierNamed, reviewTier, planPrice, extraStorageBlocks, STORAGE, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT, tierNamed, reviewTier, planPrice, extraStorageBlocks, STORAGE, ADDRESS, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
} = require('./tiers'); } = require('./tiers');
const { ymd, day, addDays, addMonths, periodLabel, shortDate } = require('./dates'); const { ymd, day, addDays, addMonths, periodLabel, shortDate } = require('./dates');
const { PRODUCTS, PRODUCT_NAMES, BILLABLE } = require('../products'); const { PRODUCTS, PRODUCT_NAMES, BILLABLE } = require('../products');
@@ -126,6 +126,24 @@ function reviewLicence(licence, product) {
}; };
} }
/** The monthly price of the customer's address in cents (a custom price wins). */
function addressMonthlyCents(customer) {
if (customer.addressCustomCents != null && customer.addressCustomCents >= 0) return customer.addressCustomCents;
return (ADDRESS[customer.addressType || 'own_domain']?.monthly || 0) * 100;
}
/** The address line for a period, or null (own domain, or free). 12 months' price when yearly. */
function addressLine(customer, { start, end, cycle }) {
const cents = addressMonthlyCents(customer);
if (!cents) return null;
const option = ADDRESS[customer.addressType] || ADDRESS.own_domain;
const m = monthsIn(cycle);
return {
description: `${option.label}${customer.domain ? ` (${customer.domain})` : ''}, ${m === 12 ? '12 months' : periodLabel(start, end)}`,
quantity: m, unitCents: cents, amountCents: m * cents,
};
}
/** /**
* A customer's invoice lines for a period: each billed product (with a prorated line for days * 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. * owed before the period), its founding discount, the bundle discount, then add-ons. Pure.
@@ -221,6 +239,10 @@ function customerInvoiceLines({ customer, licences, period, reviewed }) {
} }
lines.push(...addOns); lines.push(...addOns);
// The church's address: once per invoice with any product on it, never discounted.
const address = addressLine(customer, { start, end, cycle });
if (address && products.length) lines.push(address);
const plan = plans.length === 1 && plans[0].product === 'events' const plan = plans.length === 1 && plans[0].product === 'events'
? plans[0].plan ? plans[0].plan
: plans.map(p => (p.product === 'website' ? PRODUCT_NAMES.website : `${PRODUCT_NAMES[p.product]} ${p.plan}`)).join(' · ') || null; : plans.map(p => (p.product === 'website' ? PRODUCT_NAMES.website : `${PRODUCT_NAMES[p.product]} ${p.plan}`)).join(' · ') || null;
@@ -334,6 +356,6 @@ function statement({ invoices, payments, from, to }) {
} }
module.exports = { module.exports = {
recipientFor, contactInstall, cleanLines, totals, planLines, productLabel, customerInvoiceLines, draftCustomerInvoice, recipientFor, contactInstall, cleanLines, totals, planLines, productLabel, customerInvoiceLines, draftCustomerInvoice, addressMonthlyCents,
planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn, planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn,
}; };
+31 -3
View File
@@ -10,6 +10,8 @@
* 2. Sends approved invoices on their date, from billing_send_hour (South African time). * 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. * 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). * 4. Applies tier changes on their effective date (the licence's plan).
* 5. Hub 2.0: reminds Joshua 30 days before a domain he registered for a church (address
* "domain included") is due for renewal, once per renewal date.
*/ */
const { Prisma } = require('@prisma/client'); const { Prisma } = require('@prisma/client');
@@ -250,15 +252,41 @@ async function applyDueLicenceChanges(now = new Date()) {
return due.length; return due.length;
} }
const DOMAIN_REMINDER_DAYS = 30;
/**
* Emails Joshua about included domains due for renewal within 30 days (or overdue), once per
* renewal date. "Renewed" on the customer page moves the date on a year.
*/
async function remindDomainRenewals(now, settings) {
if (!settings.alert_email) return 0;
const due = (await prisma.customer.findMany({
where: { addressType: 'included', domainRenewsOn: { lte: addDays(today(now), DOMAIN_REMINDER_DAYS) } },
})).filter(c => !c.domainRemindedFor || ymd(c.domainRemindedFor) !== ymd(c.domainRenewsOn));
if (!due.length) return 0;
const content = layout(settings, {
heading: due.length === 1 ? 'A church\'s domain is due for renewal' : `${due.length} churches' domains are due for renewal`,
paragraphs: ['You registered these domains for the churches (address: domain included). Renew them, then press Renewed on the church\'s page so the date moves on a year.'],
rows: due.map(c => [`${c.name}`, `${c.domain || '(no domain recorded)'}: ${longDate(c.domainRenewsOn)}${ymd(c.domainRenewsOn) < ymd(today(now)) ? ' (overdue)' : ''}`]),
button: { label: 'Open billing', url: hubLink('/billing') },
signoff: false,
});
const res = await sendBillingEmail(settings, { kind: 'reminder', to: settings.alert_email, subject: `Domain renewal${due.length === 1 ? '' : 's'} due: ${due.map(c => c.domain || c.name).join(', ')}`, content });
if (res.ok) for (const c of due) await prisma.customer.update({ where: { id: c.id }, data: { domainRemindedFor: c.domainRenewsOn } });
return due.length;
}
/** The background job. */ /** The background job. */
async function runBilling(now = new Date()) { async function runBilling(now = new Date()) {
const settings = await getSettings(); const settings = await getSettings();
if (String(settings.billing_enabled) !== 'true') return { drafted: 0, sent: 0, reminded: 0, applied: 0 }; // Domain renewals matter even while invoicing is switched off.
const domains = await remindDomainRenewals(now, settings).catch(e => { console.warn('[billing] domain reminder failed:', e?.message || e); return 0; });
if (String(settings.billing_enabled) !== 'true') return { drafted: 0, sent: 0, reminded: 0, applied: 0, domains };
const drafted = await createDueDrafts(now, settings); const drafted = await createDueDrafts(now, settings);
const sent = await sendDueInvoices(now, settings); const sent = await sendDueInvoices(now, settings);
const reminded = await remindUnapproved(now, settings); const reminded = await remindUnapproved(now, settings);
const applied = await applyDueLicenceChanges(now); const applied = await applyDueLicenceChanges(now);
return { drafted, sent, reminded, applied }; return { drafted, sent, reminded, applied, domains };
} }
// ─── Invoice actions ───────────────────────────────────────────────────────── // ─── Invoice actions ─────────────────────────────────────────────────────────
@@ -622,7 +650,7 @@ async function licenceChangePdfFor(id) {
module.exports = { module.exports = {
nextNumber, loadInvoice, invoicePdfFor, draftForCustomer, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved, nextNumber, loadInvoice, invoicePdfFor, draftForCustomer, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
applyDueLicenceChanges, runBilling, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice, applyDueLicenceChanges, runBilling, remindDomainRenewals, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice,
resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement, resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement,
statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval, statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval,
}; };
+11 -1
View File
@@ -41,6 +41,16 @@ const APP_TIERS = [
/** Extra website storage: R20 a month per 5 GB above the 5 GB included. */ /** 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 }; const STORAGE = { includedBytes: 5 * 1024 ** 3, stepBytes: 5 * 1024 ** 3, monthly: 20 };
/**
* The church's address, one for all its products, charged once per invoice and never discounted.
* Other domain endings (.com, .church) are charged at cost: a custom price on the customer.
*/
const ADDRESS = {
own_domain: { label: 'Own domain', monthly: 0 },
crosscode: { label: 'Cross Code address', monthly: 10 },
included: { label: 'Domain included', monthly: 25 },
};
/** Bundles: % off the products (not the add-ons) by how many are billed. Accounts doesn't count. */ /** Bundles: % off the products (not the add-ons) by how many are billed. Accounts doesn't count. */
const BUNDLE_PERCENT = { 2: 15, 3: 25 }; const BUNDLE_PERCENT = { 2: 15, 3: 25 };
@@ -112,6 +122,6 @@ function extraStorageBlocks(storage) {
} }
module.exports = { module.exports = {
TIERS, WEBSITE_PLANS, APP_TIERS, PLANS, STORAGE, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT, TIERS, WEBSITE_PLANS, APP_TIERS, PLANS, STORAGE, ADDRESS, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
tierNamed, tierForBand, appTierForBand, reviewTier, planPrice, extraStorageBlocks, tierNamed, tierForBand, appTierForBand, reviewTier, planPrice, extraStorageBlocks,
}; };
+24
View File
@@ -347,3 +347,27 @@ describe('payments and statements', () => {
expect(later.closingCents).toBe(90000); expect(later.closingCents).toBe(90000);
}); });
}); });
describe('the church\'s address (one per church, never discounted)', () => {
test('own domain: nothing to charge', () => {
const { invoice } = draft(customer({ addressType: 'own_domain', domain: 'hope.co.za' }), [events()]);
expect(invoice.lines.some(l => /domain|address/i.test(l.description))).toBe(false);
});
test('Cross Code address R10 and domain included R25 a month, after the bundle, not discounted', () => {
const { invoice } = draft(customer({ founding: true, addressType: 'crosscode', domain: 'hope.crosscode.co.za' }), [events(), website()]);
expect(invoice.lines.at(-1)).toEqual({ description: 'Cross Code address (hope.crosscode.co.za), December 2026', quantity: 1, unitCents: 1000, amountCents: 1000 });
const { invoice: inc } = draft(customer({ addressType: 'included', domain: 'hope.co.za' }), [events()]);
expect(inc.lines.at(-1)).toMatchObject({ description: 'Domain included (hope.co.za), December 2026', amountCents: 2500 });
});
test('yearly: 12 months\' price; a custom price (e.g. a .com at cost) wins', () => {
const { invoice } = draft(customer({ billingCycle: 'yearly', reviewDate: day('2027-12-01'), addressType: 'included', domain: 'hope.church', addressCustomCents: 4500 }), [events()]);
expect(invoice.lines.at(-1)).toMatchObject({ description: 'Domain included (hope.church), 12 months', quantity: 12, unitCents: 4500, amountCents: 54000 });
});
test('a church with no product charged gets no invoice just for its address', () => {
const { empty } = draft(customer({ addressType: 'crosscode' }), [events({ billedFrom: null })]);
expect(empty).toBe(true);
});
});
@@ -20,6 +20,7 @@ type BillingLicence = {
type CustomerBillingData = { type CustomerBillingData = {
id: string; name: string; billingEmail: string | null; billingAddress: string | null; founding: boolean; foundingSince: string | null; foundingNote: string | null; id: string; name: string; billingEmail: string | null; billingAddress: string | null; founding: boolean; foundingSince: string | null; foundingNote: string | null;
billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null; billingCycle: BillingCycle; billingStart: string | null; nextInvoiceDate: string | null; reviewDate: string | null;
addressType: AddressType; domain: string | null; addressCustomCents: number | null; addressMonthlyCents: number; domainRenewsOn: string | null;
sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[]; sendsTo: string | null; balanceCents: number; licences: BillingLicence[]; invoices: Invoice[]; payments: Payment[]; licenceChanges: LicenceChange[]; emails: BillingEmail[];
plans: Record<Product, Plan[]>; plans: Record<Product, Plan[]>;
}; };
@@ -79,6 +80,58 @@ function Schedule({ c, onSaved, setMsg }: { c: CustomerBillingData; onSaved: ()
); );
} }
type AddressType = "own_domain" | "crosscode" | "included";
const ADDRESS_OPTIONS: Record<AddressType, { label: string; price: string; help: string }> = {
own_domain: { label: "Own domain", price: "R0", help: "The church (or whoever manages its domain) adds the DNS records we send. We look after the certificates." },
crosscode: { label: "Cross Code address", price: "R10/month", help: "<church>.crosscode.co.za, with events., app. and so on in front. Free during a trial." },
included: { label: "Domain included", price: "R25/month", help: "A .co.za or .org.za registered in the church's name; we renew it and manage the DNS. Other endings at cost: set a custom price." },
};
/** The church's address: one for all its products, billed once per invoice and never discounted. */
function Address({ c, onSaved, setMsg }: { c: CustomerBillingData; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({ addressType: c.addressType, domain: c.domain || "", custom: randInput(c.addressCustomCents), domainRenewsOn: c.domainRenewsOn || "" });
const [busy, setBusy] = useState(false);
const save = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
try {
await api(`/api/admin/billing/customers/${c.id}`, { method: "PUT", body: { addressType: form.addressType, domain: form.domain || null, addressCustomCents: form.custom.trim() ? centsFrom(form.custom) : null, domainRenewsOn: form.domainRenewsOn || null } });
setMsg({ type: "ok", text: `Address saved: ${ADDRESS_OPTIONS[form.addressType].label}.` });
onSaved();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); } finally { setBusy(false); }
};
const renewed = async () => {
if (!confirm(`Mark ${c.domain || "the domain"} as renewed? The renewal date moves on a year.`)) return;
try {
const r = await api<{ message: string }>(`/api/admin/billing/customers/${c.id}/domain-renewed`, { method: "POST" });
setMsg({ type: "ok", text: r.message });
onSaved();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const due = c.addressType === "included" && c.domainRenewsOn && c.domainRenewsOn <= new Date(Date.now() + 30 * 864e5).toISOString().slice(0, 10);
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="addr-type">Address</label>
<select id="addr-type" className="input" value={form.addressType} onChange={e => setForm({ ...form, addressType: e.target.value as AddressType })}>
{(Object.keys(ADDRESS_OPTIONS) as AddressType[]).map(k => <option key={k} value={k}>{ADDRESS_OPTIONS[k].label} ({ADDRESS_OPTIONS[k].price})</option>)}
</select>
</div>
<div><label className="label" htmlFor="addr-domain">Domain</label><input id="addr-domain" className="input" value={form.domain} onChange={e => setForm({ ...form, domain: e.target.value })} placeholder={form.addressType === "crosscode" ? "hopefamily.crosscode.co.za" : "hopefamily.co.za"} /></div>
{form.addressType !== "own_domain" && <div><label className="label" htmlFor="addr-price">Custom price (R/month)</label><input id="addr-price" className="input" inputMode="decimal" placeholder={ADDRESS_OPTIONS[form.addressType].price} value={form.custom} onChange={e => setForm({ ...form, custom: e.target.value })} /></div>}
{form.addressType === "included" && <div><label className="label" htmlFor="addr-renews">Domain renews on</label><input id="addr-renews" type="date" className="input" value={form.domainRenewsOn} onChange={e => setForm({ ...form, domainRenewsOn: e.target.value })} /></div>}
</div>
<p className="text-xs text-slate-500">{ADDRESS_OPTIONS[form.addressType].help} Charged once per invoice for all the church&apos;s products, never discounted.{form.addressType === "included" ? " You're emailed 30 days before the renewal date." : ""}</p>
{due && <p className="rounded-lg bg-amber-50 p-2 text-sm text-amber-900">{c.domain || "The domain"} is due for renewal on {day(c.domainRenewsOn)}.</p>}
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>Save address</button>
{c.addressType === "included" && c.domainRenewsOn && <button type="button" className="btn-secondary" onClick={renewed}>Renewed</button>}
</div>
</form>
);
}
/** One licence's billing: when it's charged from, a custom price, and a notice of licence change. */ /** 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 }) { 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 [form, setForm] = useState({ billedFrom: licence.billedFrom || "", custom: randInput(licence.customMonthlyCents) });
@@ -260,6 +313,10 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
<h3 className="font-semibold">Billing schedule</h3> <h3 className="font-semibold">Billing schedule</h3>
<Schedule key={`${c.billingCycle}-${c.billingStart}-${c.nextInvoiceDate}-${c.reviewDate}`} c={c} onSaved={load} setMsg={setMsg} /> <Schedule key={`${c.billingCycle}-${c.billingStart}-${c.nextInvoiceDate}-${c.reviewDate}`} c={c} onSaved={load} setMsg={setMsg} />
</div> </div>
<div className="card space-y-3">
<h3 className="font-semibold">Address</h3>
<Address key={`${c.addressType}-${c.domain}-${c.addressCustomCents}-${c.domainRenewsOn}`} c={c} onSaved={load} setMsg={setMsg} />
</div>
<div className="card space-y-3"> <div className="card space-y-3">
<h3 className="font-semibold">Products</h3> <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 => ( {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 => (
@@ -268,7 +325,7 @@ export function CustomerBilling({ customerId }: { customerId: string }) {
</div> </div>
<div className="card space-y-3"> <div className="card space-y-3">
<h3 className="font-semibold">Next invoice</h3> <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])])} /> <NextInvoice customerId={customerId} version={JSON.stringify([c.founding, c.billingCycle, c.nextInvoiceDate, c.addressType, c.addressCustomCents, c.licences.map(l => [l.plan, l.billedFrom, l.billedUntil, l.customMonthlyCents, l.status])])} />
</div> </div>
</div> </div>
</div> </div>