Billing: invoices, approval, receipts, statements, licence changes (1.7.0)

- Invoices drafted 14 days before each licence's invoice date and emailed
  to the alert email for approval; approved ones go out on their date from
  08:00 SA time. Drafts can be edited, recalculated, sent early, put back
  to draft or voided; one-off invoices too.
- Annual tier review from the 12-month event-income band; approving a tier
  change emails a notice of licence change, applied when the invoice goes out.
  Notices can also be sent by hand.
- Founding churches (35% off as its own line), payments with receipts,
  statements for any dates.
- Every billing email is styled HTML with a PDF (invoice / tax invoice,
  receipt, statement, licence change) and logged per customer.
- Settings -> Billing: business and bank details, VAT (off: plain invoices;
  on: VAT-inclusive tax invoices), timing and numbering.
- Migration 20261103111645_invoicing; pdfkit 0.17.2; tests/billing.test.js;
  scripts/sample-billing-pdfs.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-03 13:42:45 +02:00
co-authored by Claude Opus 5.5
parent cc7d62690b
commit 6fce0fe90e
33 changed files with 3579 additions and 53 deletions
@@ -0,0 +1,169 @@
-- CreateEnum
CREATE TYPE "BillingCycle" AS ENUM ('none', 'monthly', 'yearly');
-- CreateEnum
CREATE TYPE "InvoiceStatus" AS ENUM ('draft', 'approved', 'sent', 'void');
-- AlterTable
ALTER TABLE "Customer" ADD COLUMN "billingAddress" TEXT,
ADD COLUMN "billingEmail" TEXT,
ADD COLUMN "founding" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "foundingNote" TEXT,
ADD COLUMN "foundingSince" DATE;
-- AlterTable
ALTER TABLE "Licence" ADD COLUMN "billingCycle" "BillingCycle" NOT NULL DEFAULT 'none',
ADD COLUMN "billingStart" DATE,
ADD COLUMN "customMonthlyCents" INTEGER,
ADD COLUMN "nextInvoiceDate" DATE,
ADD COLUMN "reviewDate" DATE;
-- CreateTable
CREATE TABLE "Invoice" (
"id" TEXT NOT NULL,
"number" TEXT NOT NULL,
"customerId" TEXT NOT NULL,
"licenceId" TEXT,
"status" "InvoiceStatus" NOT NULL DEFAULT 'draft',
"issueDate" DATE NOT NULL,
"dueDate" DATE NOT NULL,
"periodStart" DATE,
"periodEnd" DATE,
"cycle" "BillingCycle" NOT NULL DEFAULT 'monthly',
"plan" TEXT,
"incomeBand" TEXT,
"reviewed" BOOLEAN NOT NULL DEFAULT false,
"founding" BOOLEAN NOT NULL DEFAULT false,
"planChange" JSONB,
"lines" JSONB NOT NULL,
"totalCents" INTEGER NOT NULL,
"vatCents" INTEGER NOT NULL DEFAULT 0,
"vatRate" DOUBLE PRECISION,
"notes" TEXT,
"warnings" TEXT[] DEFAULT ARRAY[]::TEXT[],
"recipientEmail" TEXT,
"approvedAt" TIMESTAMP(3),
"approvedById" TEXT,
"approvalEmailedAt" TIMESTAMP(3),
"overdueEmailedAt" TIMESTAMP(3),
"sentAt" TIMESTAMP(3),
"sendError" TEXT,
"voidedAt" TIMESTAMP(3),
"voidReason" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Invoice_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Payment" (
"id" TEXT NOT NULL,
"receiptNumber" TEXT NOT NULL,
"customerId" TEXT NOT NULL,
"invoiceId" TEXT,
"amountCents" INTEGER NOT NULL,
"paidOn" DATE NOT NULL,
"method" TEXT NOT NULL DEFAULT 'eft',
"reference" TEXT,
"notes" TEXT,
"receiptSentAt" TIMESTAMP(3),
"createdById" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "Payment_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "LicenceChange" (
"id" TEXT NOT NULL,
"number" TEXT NOT NULL,
"customerId" TEXT NOT NULL,
"licenceId" TEXT,
"invoiceId" TEXT,
"fromPlan" TEXT NOT NULL,
"toPlan" TEXT NOT NULL,
"fromMonthlyCents" INTEGER,
"toMonthlyCents" INTEGER,
"effectiveDate" DATE NOT NULL,
"reason" TEXT,
"incomeBand" TEXT,
"appliedAt" TIMESTAMP(3),
"sentAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "LicenceChange_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BillingEmail" (
"id" TEXT NOT NULL,
"customerId" TEXT,
"kind" TEXT NOT NULL,
"refId" TEXT,
"to" TEXT NOT NULL,
"subject" TEXT NOT NULL,
"error" TEXT,
"sentAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "BillingEmail_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "DocumentCounter" (
"key" TEXT NOT NULL,
"value" INTEGER NOT NULL DEFAULT 0,
CONSTRAINT "DocumentCounter_pkey" PRIMARY KEY ("key")
);
-- CreateIndex
CREATE UNIQUE INDEX "Invoice_number_key" ON "Invoice"("number");
-- CreateIndex
CREATE INDEX "Invoice_status_issueDate_idx" ON "Invoice"("status", "issueDate");
-- CreateIndex
CREATE INDEX "Invoice_customerId_idx" ON "Invoice"("customerId");
-- CreateIndex
CREATE UNIQUE INDEX "Invoice_licenceId_periodStart_key" ON "Invoice"("licenceId", "periodStart");
-- CreateIndex
CREATE UNIQUE INDEX "Payment_receiptNumber_key" ON "Payment"("receiptNumber");
-- CreateIndex
CREATE INDEX "Payment_customerId_paidOn_idx" ON "Payment"("customerId", "paidOn");
-- CreateIndex
CREATE UNIQUE INDEX "LicenceChange_number_key" ON "LicenceChange"("number");
-- CreateIndex
CREATE INDEX "LicenceChange_licenceId_appliedAt_idx" ON "LicenceChange"("licenceId", "appliedAt");
-- CreateIndex
CREATE INDEX "BillingEmail_customerId_sentAt_idx" ON "BillingEmail"("customerId", "sentAt");
-- AddForeignKey
ALTER TABLE "Invoice" ADD CONSTRAINT "Invoice_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Invoice" ADD CONSTRAINT "Invoice_licenceId_fkey" FOREIGN KEY ("licenceId") REFERENCES "Licence"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_invoiceId_fkey" FOREIGN KEY ("invoiceId") REFERENCES "Invoice"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "LicenceChange" ADD CONSTRAINT "LicenceChange_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "LicenceChange" ADD CONSTRAINT "LicenceChange_licenceId_fkey" FOREIGN KEY ("licenceId") REFERENCES "Licence"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "LicenceChange" ADD CONSTRAINT "LicenceChange_invoiceId_fkey" FOREIGN KEY ("invoiceId") REFERENCES "Invoice"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "BillingEmail" ADD CONSTRAINT "BillingEmail_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "Customer"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+198 -34
View File
@@ -11,31 +11,43 @@ datasource db {
// Someone who logs in to the Hub (Joshua, later support staff). Two-factor (authenticator
// app) is required: totpSecret is set up on first login.
model AdminUser {
id String @id @default(uuid())
email String @unique
name String
password String
id String @id @default(uuid())
email String @unique
name String
password String
// AES-GCM encrypted (utils/crypto.js); null until two-factor is set up.
totpSecret String?
totpEnabled Boolean @default(false)
totpSecret String?
totpEnabled Boolean @default(false)
// Bumped to sign out everywhere.
tokenVersion Int @default(0)
lastLoginAt DateTime?
createdAt DateTime @default(now())
auditLogs AuditLog[]
tokenVersion Int @default(0)
lastLoginAt DateTime?
createdAt DateTime @default(now())
auditLogs AuditLog[]
}
model Customer {
id String @id @default(uuid())
name String
contactName String?
email String?
phone String?
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
installs Install[]
id String @id @default(uuid())
name String
contactName String?
email String?
phone String?
notes String?
// Billing (1.7.0). Invoices go to billingEmail, else the site's admin contact, else email.
billingEmail String?
// The postal address printed on invoices and statements.
billingAddress String?
// A founding church pays the founding price on every tier (35% less) while it stays.
founding Boolean @default(false)
foundingSince DateTime? @db.Date
foundingNote String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
installs Install[]
invoices Invoice[]
payments Payment[]
licenceChanges LicenceChange[]
billingEmails BillingEmail[]
}
enum LicenceStatus {
@@ -45,25 +57,45 @@ enum LicenceStatus {
}
model Licence {
id String @id @default(uuid())
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
id String @id @default(uuid())
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
// CEH-XXXX-XXXX-XXXX-XXXX, generated by the Hub.
key String @unique
plan String @default("standard")
status LicenceStatus @default(active)
key String @unique
plan String @default("standard")
status LicenceStatus @default(active)
// Null = no end date.
expiresAt DateTime?
graceDays Int @default(14)
expiresAt DateTime?
graceDays Int @default(14)
// Cross Events 2.0: monthly AI spend cap (in cents, rand), counted in charged rand. 0 = AI off.
aiMonthlyCapCents Int @default(0)
aiMonthlyCapCents Int @default(0)
// Markup on the real AI cost, in %. Null = the Hub default (Settings → AI).
aiMarkupPercent Int?
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
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
// A price per month instead of the tier's (e.g. the Network tier), in cents.
customMonthlyCents Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// One licence = one install.
install Install?
install Install?
invoices Invoice[]
licenceChanges LicenceChange[]
}
enum BillingCycle {
none
monthly
yearly
}
model Install {
@@ -227,3 +259,135 @@ model Notice {
@@index([endsAt])
}
// ─── Billing (1.7.0) ───────────────────────────────────────────────────────────
enum InvoiceStatus {
// Made 14 days before its date and emailed to Joshua for approval. Can be edited.
draft
// Goes out automatically on its date. Can still be edited until then.
approved
sent
void
}
// One invoice for one licence's period, in cents (rand). Payment state comes from its payments.
model Invoice {
id String @id @default(uuid())
number String @unique
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
licenceId String?
licence Licence? @relation(fields: [licenceId], references: [id], onDelete: SetNull)
status InvoiceStatus @default(draft)
// The day it's sent (and dated), and when payment is due.
issueDate DateTime @db.Date
dueDate DateTime @db.Date
periodStart DateTime? @db.Date
periodEnd DateTime? @db.Date
cycle BillingCycle @default(monthly)
// The tier billed, and how it was chosen (the income band at a review).
plan String?
incomeBand String?
reviewed Boolean @default(false)
founding Boolean @default(false)
// A tier change that comes with this invoice: { from, to, fromMonthlyCents, toMonthlyCents }.
planChange Json?
// [{ description, quantity, unitCents, amountCents }]
lines Json
totalCents Int
// VAT included in the total (0 unless VAT registered).
vatCents Int @default(0)
vatRate Float?
notes String?
// Things Joshua should check before approving (e.g. no income band reported).
warnings String[] @default([])
recipientEmail String?
approvedAt DateTime?
approvedById String?
approvalEmailedAt DateTime?
// Emailed to Joshua when its date came and it still wasn't approved.
overdueEmailedAt DateTime?
sentAt DateTime?
sendError String?
voidedAt DateTime?
voidReason String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
payments Payment[]
licenceChanges LicenceChange[]
@@unique([licenceId, periodStart])
@@index([status, issueDate])
@@index([customerId])
}
// Money received from a church, optionally against one invoice. Each gets a receipt number.
model Payment {
id String @id @default(uuid())
receiptNumber String @unique
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
invoiceId String?
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: SetNull)
amountCents Int
paidOn DateTime @db.Date
// eft, card, cash, other
method String @default("eft")
reference String?
notes String?
receiptSentAt DateTime?
createdById String?
createdAt DateTime @default(now())
@@index([customerId, paidOn])
}
// A notice to a church that its tier (and price) changes from a date. Sent when the invoice
// that brings the change is approved, or by hand from the customer page.
model LicenceChange {
id String @id @default(uuid())
number String @unique
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
licenceId String?
licence Licence? @relation(fields: [licenceId], references: [id], onDelete: SetNull)
invoiceId String?
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: SetNull)
fromPlan String
toPlan String
fromMonthlyCents Int?
toMonthlyCents Int?
effectiveDate DateTime @db.Date
reason String?
incomeBand String?
// Set once the plan has been changed on the licence (on the effective date).
appliedAt DateTime?
sentAt DateTime?
createdAt DateTime @default(now())
@@index([licenceId, appliedAt])
}
// Every billing email: invoices, receipts, statements, licence-change notices and approval
// requests to Joshua.
model BillingEmail {
id String @id @default(uuid())
customerId String?
customer Customer? @relation(fields: [customerId], references: [id], onDelete: SetNull)
// invoice, receipt, statement, licence_change, approval, reminder
kind String
refId String?
to String
subject String
error String?
sentAt DateTime @default(now())
@@index([customerId, sentAt])
}
// Document numbers (INV-2026-0001…): one counter per prefix and year, incremented atomically.
model DocumentCounter {
key String @id
value Int @default(0)
}