Merge branch 'release/2.0' (2.0.0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-05 09:07:29 +02:00
co-authored by Claude Opus 5.5
54 changed files with 3240 additions and 600 deletions
+77
View File
@@ -5,6 +5,83 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
Hub 2.0.0, Cross Code Hub, in steps (`docs/HUB-2.0-PLAN.md`).
### Added
- **Products** (step 1): a licence and an install are for one product: Cross Events, Accounts,
Church Website or Church App (existing ones are Cross Events). Generate a licence for a product
on the customer's page; keys have the product's prefix (`CEH-` Events as before, `CCA-`
Accounts, `CCW-` Website, `CCP-` App).
- **One licence per product per customer** that isn't revoked (a revoked one can be replaced),
enforced by the database. Un-revoking a licence whose product has another open licence is
refused.
- **Accounts licence** (free, never invoiced) created automatically with a customer's first other
product licence.
- `npm run check:hub2`: before deploying 2.0, lists customers with two open licences (the 2.0
migration stops on them, naming them). Run it against production first.
- `@crosscode/contracts`, committed as `backend/vendor/crosscode-contracts-<version>.tgz` (1.1.0).
- **Protocol v2** (step 2) next to v1 (`utils/protocol.js`; `/api/public-key` lists `[1, 2]`):
register and heartbeat say which `product` they are (it must match the licence, else
`409 WRONG_PRODUCT`), register sends the install's public key, the heartbeat's stats are per
product, and the replies add `linkedProducts`: the church's other installs in use that have a
public key (product, id, address, key; nothing else). v2 bodies are checked against the
contracts' schemas (`400 INVALID_REQUEST` says what's wrong); v1 requests and replies are exactly
as before. Tests put every contract sample through the routes and check the replies against the
contract.
- Licence tokens carry `customerId` and `product` (Cross Events 2.1 ignores them).
- **Releases per product** (step 3): each product has its own releases and latest version (an
install is offered its own product's releases and shows as behind against its own latest).
**Release sources** on the Releases page: per product, one or more repositories with a tag prefix
and a notes file. The defaults: every product from `crosscode-platform` (`events@1.2.3`,
`accounts@…`, `website@…`, `app@…`, notes in `apps/<product>/WHATS-NEW.md`) plus Cross Events
before the move from the repository set until now (`v1.2.3` tags). `contracts@` tags are ignored.
A product's releases are only removed when every one of its sources was read and found tags, so
an unreachable source never wipes releases; a product with no source is managed by hand.
- **Requirements between products**: `— requires accounts 1.2.0` in a release's notes heading.
Request update answers `409 REQUIREMENT_NOT_MET` (saying what's needed) until the church's
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.
- **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.
- **AI per church** (step 6): the monthly AI cap and markup are the church's (customer page →
Details), shared by all its sites: a call from any of them counts what all of them used this month,
under one lock so two calls at once can't both take the last of it. The licence token carries the
church's cap. Settings → AI shows each site's use with its product and the church's cap.
- **Dashboard** (step 7): monthly recurring revenue (each billed church's full month after
discounts, add-ons included, yearly divided by 12), overdue invoices, and per product: installs,
latest version, how many are behind or critical, and licences by status. The install page lists
the church's other products and whether this site is told about them (Linked products, protocol
v2), next to what an update needs (step 3).
### 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).
- 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), `20261104190000_customer_address`,
`20261105080000_ai_per_customer` (each church takes its licence's AI cap and markup).
## [1.7.0] - 2026-11-03
### Added
+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
+19
View File
@@ -10,6 +10,7 @@
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.1.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -607,6 +608,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/@crosscode/contracts": {
"version": "1.1.0",
"resolved": "file:vendor/crosscode-contracts-1.1.0.tgz",
"integrity": "sha512-k/7fFcjNh79B4la+GUxzh/buFtnM6G+5JPxxKvhXNdlIXvon/45VErzEKYsnDnL8pF3fQHldJcfeFtLm52Q47A==",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
}
},
"node_modules/@electric-sql/pglite": {
"version": "0.4.3",
"resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.4.3.tgz",
@@ -7742,6 +7752,15 @@
"grammex": "^3.1.11",
"graphmatch": "^1.1.0"
}
},
"node_modules/zod": {
"version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
"integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}
+3 -1
View File
@@ -15,10 +15,12 @@
"prisma:generate": "prisma generate",
"prisma:deploy": "prisma migrate deploy && prisma generate",
"create-admin": "node scripts/create-admin.js",
"generate-keys": "node scripts/generate-keys.js"
"generate-keys": "node scripts/generate-keys.js",
"check:hub2": "node scripts/check-hub2.js"
},
"dependencies": {
"@anthropic-ai/sdk": "^1.3.0",
"@crosscode/contracts": "file:vendor/crosscode-contracts-1.1.0.tgz",
"@prisma/adapter-pg": "^7.10.1",
"@prisma/client": "^7.10.1",
"bcryptjs": "^2.4.3",
@@ -0,0 +1,29 @@
-- CreateEnum
CREATE TYPE "Product" AS ENUM ('events', 'accounts', 'website', 'app');
-- AlterTable
ALTER TABLE "Install" ADD COLUMN "product" "Product" NOT NULL DEFAULT 'events',
ADD COLUMN "publicKey" TEXT;
-- AlterTable
ALTER TABLE "Licence" ADD COLUMN "product" "Product" NOT NULL DEFAULT 'events';
-- CreateIndex
CREATE INDEX "Licence_customerId_product_idx" ON "Licence"("customerId", "product");
-- One licence per product per customer that isn't revoked (Hub 2.0; a revoked licence can be
-- replaced). Prisma can't express a partial index, so it's only here. Every licence before 2.0 is
-- an Events licence: a customer with two that aren't revoked stops the migration, named, so it can
-- be sorted out (revoke one) before deploying — `npm run check:hub2` lists them in advance.
DO $$
DECLARE dupes TEXT;
BEGIN
SELECT string_agg(format('%s (%s licences)', c.name, n), ', ') INTO dupes
FROM (SELECT "customerId", count(*) AS n FROM "Licence" WHERE status <> 'revoked' GROUP BY "customerId" HAVING count(*) > 1) d
JOIN "Customer" c ON c.id = d."customerId";
IF dupes IS NOT NULL THEN
RAISE EXCEPTION 'Hub 2.0 allows one Events licence per customer that is not revoked. Revoke the extra licences first: %', dupes;
END IF;
END $$;
CREATE UNIQUE INDEX "Licence_customerId_product_open_key" ON "Licence"("customerId", "product") WHERE status <> 'revoked';
@@ -0,0 +1,12 @@
-- Hub 2.0: releases per product. Every release before 2.0 is a Cross Events release; the version is
-- now unique per product.
-- DropIndex
DROP INDEX "Release_version_key";
-- AlterTable
ALTER TABLE "Release" ADD COLUMN "product" "Product" NOT NULL DEFAULT 'events',
ADD COLUMN "requires" JSONB NOT NULL DEFAULT '[]';
-- CreateIndex
CREATE UNIQUE INDEX "Release_product_version_key" ON "Release"("product", "version");
@@ -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';
@@ -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;
@@ -0,0 +1,19 @@
-- Hub 2.0: the AI cap and markup are the church's (counted over all its installs), moved from the
-- licence. Each church takes the cap of its open licence with the highest cap, and that licence's
-- markup override (Hub 1.7 had one Events licence per church, so this is that licence's).
ALTER TABLE "Customer" ADD COLUMN "aiMarkupPercent" INTEGER,
ADD COLUMN "aiMonthlyCapCents" INTEGER NOT NULL DEFAULT 0;
UPDATE "Customer" c
SET "aiMonthlyCapCents" = l."aiMonthlyCapCents", "aiMarkupPercent" = l."aiMarkupPercent"
FROM (
SELECT DISTINCT ON ("customerId") "customerId", "aiMonthlyCapCents", "aiMarkupPercent"
FROM "Licence"
WHERE status <> 'revoked'
ORDER BY "customerId", "aiMonthlyCapCents" DESC, "createdAt" ASC
) l
WHERE c.id = l."customerId";
ALTER TABLE "Licence" DROP COLUMN "aiMarkupPercent",
DROP COLUMN "aiMonthlyCapCents";
+78 -18
View File
@@ -40,6 +40,33 @@ 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
// 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
// Hub 2.0 (moved from Licence): the monthly AI spend cap in cents (rand), counted in charged
// rand over all the church's installs. 0 = AI off. And the markup on the real cost, in %; null =
// the Hub default (Settings → AI).
aiMonthlyCapCents Int @default(0)
aiMarkupPercent Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
@@ -56,32 +83,37 @@ enum LicenceStatus {
revoked
}
// Hub 2.0: the Cross Code products a church can have (ROADMAP-v3 §5). Accounts comes free with
// any other product.
enum Product {
events
accounts
website
app
}
model Licence {
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.
// CEH-XXXX-XXXX-XXXX-XXXX (Events), CCA- (Accounts), CCW- (Website), CCP- (App).
key String @unique
// Hub 2.0. A customer has at most one licence per product that isn't revoked: enforced by the
// partial unique index "Licence_customerId_product_open_key" (migration 20261104…_products),
// which Prisma can't express here.
product Product @default(events)
plan String @default("standard")
status LicenceStatus @default(active)
// Null = no end date.
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)
// 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())
@@ -90,6 +122,14 @@ model Licence {
install Install?
invoices Invoice[]
licenceChanges LicenceChange[]
@@index([customerId, product])
}
enum AddressType {
own_domain
crosscode
included
}
enum BillingCycle {
@@ -104,8 +144,12 @@ model Install {
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
licenceId String? @unique
licence Licence? @relation(fields: [licenceId], references: [id], onDelete: SetNull)
// Hub 2.0: the licence's product, set when the install registers.
product Product @default(events)
name String
url String
// Protocol v2: the install's Ed25519 public key (PEM), shared with its linked products.
publicKey String?
// The install's HMAC secret, AES-GCM encrypted: the Hub needs it to check signatures.
secret String
version String?
@@ -222,13 +266,21 @@ model Setting {
// latest_version setting). Urgent releases (security or serious bug fixes) can't be put off.
model Release {
id String @id @default(uuid())
version String @unique
// Hub 2.0: releases are per product (existing ones are Cross Events), from the product's release
// sources (Releases page; utils/releaseSync.js).
product Product @default(events)
version String
// Plain text; lines starting with "- " show as a list.
notes String @default("")
urgent Boolean @default(false)
// Hub 2.0: sibling versions this release needs, from "— requires accounts 1.2.0" in its
// WHATS-NEW.md heading: [{ product, version }]. Request update is refused until they're met.
requires Json @default("[]")
releasedAt DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([product, version])
}
enum NoticeLevel {
@@ -291,7 +343,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
@@ -303,6 +357,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?
@@ -317,7 +374,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])
}
+44
View File
@@ -0,0 +1,44 @@
/**
* Before deploying Hub 2.0: checks the database can take the 2.0 migrations, and lists what to
* sort out first. Changes nothing.
*
* npm run check:hub2
*
* Works before and after the 2.0 migrations (it reads the tables directly).
* - Hub 2.0 allows one licence per product per customer that isn't revoked. Every licence before
* 2.0 is an Events licence, so a customer with two open licences stops the migration: revoke
* the one that isn't used (its install, if any, stops reporting).
*/
require('dotenv').config();
const prisma = require('../src/config/db');
async function main() {
const columns = await prisma.$queryRaw`SELECT column_name FROM information_schema.columns WHERE table_name = 'Licence' AND column_name = 'product'`;
const hasProduct = columns.length > 0;
const rows = hasProduct
? await prisma.$queryRawUnsafe(`SELECT c.name, l."customerId", l.product::text AS product, count(*)::int AS n,
string_agg(l.key || ' (' || l.status::text || ')', ', ' ORDER BY l."createdAt") AS keys
FROM "Licence" l JOIN "Customer" c ON c.id = l."customerId"
WHERE l.status <> 'revoked' GROUP BY c.name, l."customerId", l.product HAVING count(*) > 1 ORDER BY c.name`)
: await prisma.$queryRawUnsafe(`SELECT c.name, l."customerId", 'events' AS product, count(*)::int AS n,
string_agg(l.key || ' (' || l.status::text || ')', ', ' ORDER BY l."createdAt") AS keys
FROM "Licence" l JOIN "Customer" c ON c.id = l."customerId"
WHERE l.status <> 'revoked' GROUP BY c.name, l."customerId" HAVING count(*) > 1 ORDER BY c.name`);
if (!rows.length) {
console.log('OK: every customer has at most one open licence per product. Hub 2.0 can be deployed.');
return 0;
}
console.log('Hub 2.0 allows one open (not revoked) licence per product per customer. Revoke the extra ones first:');
for (const r of rows) console.log(` - ${r.name}: ${r.n} ${r.product} licences: ${r.keys}`);
return 1;
}
main()
.then(code => prisma.$disconnect().then(() => process.exit(code)))
.catch(async e => {
console.error('The check failed:', e.message);
await prisma.$disconnect().catch(() => {});
process.exit(2);
});
+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}`);
})();
+139 -65
View File
@@ -4,15 +4,19 @@ const express = require('express');
const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { protect } = require('../middleware/auth');
const { licenceKey } = require('../utils/crypto');
const { generateLicence, checkReopen } = require('../utils/licences');
const { PRODUCTS, isProduct, PRODUCT_NAMES } = require('../utils/products');
const compute = require('../utils/billing/compute');
const { ymd, today } = require('../utils/billing/dates');
const { linkedProductsFor } = require('../utils/protocol');
const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const { problems, compareVersions } = require('../utils/alerts');
const licenceToken = require('../utils/licenceToken');
const { smtpConfigured, testSmtp } = require('../utils/mail');
const { VERSION_RE, sortReleases, syncLatestVersion } = require('../utils/releases');
const { VERSION_RE, sortReleases, syncLatestVersion, latestVersions, unmetRequirementsFor } = require('../utils/releases');
const { emailNotice } = require('../utils/notices');
const { parseRepoUrl, syncReleases } = require('../utils/releaseSync');
const { parseRepoUrl, syncReleases, releaseSources, cleanSources } = require('../utils/releaseSync');
const ai = require('../utils/ai');
const { AI_MODELS } = require('../utils/aiModels');
@@ -24,7 +28,7 @@ const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardH
const wrap = fn => (req, res) => fn(req, res).catch(e => {
const status = e.status || 500;
if (status >= 500) console.error('[admin]', e);
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message });
res.status(status).json({ message: status >= 500 && !e.status ? 'Something went wrong.' : e.message, ...(e.code && e.status ? { code: e.code } : {}) });
});
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
const text = (v, max = 500) => (v == null || String(v).trim() === '' ? null : String(v).trim().slice(0, max));
@@ -36,17 +40,20 @@ function dateOrNull(v) {
return d;
}
// The health of an install at a glance, for lists.
function summary(install, settings, now = new Date()) {
const current = problems(install, settings, now);
// The health of an install at a glance, for lists. `latest` is the latest version per product.
function summary(install, settings, latest = {}, now = new Date()) {
const current = problems(install, { ...settings, latest_versions: latest }, now);
const latestForProduct = latest[install.product] || null;
const worst = current.some(p => p.level === 'critical') ? 'critical' : current.some(p => p.level === 'warning') ? 'warning' : 'ok';
return {
id: install.id,
product: install.product,
name: install.name,
url: install.url,
customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null,
version: install.version,
behind: !!(settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0),
latestVersion: latestForProduct,
behind: !!(latestForProduct && install.version && compareVersions(install.version, latestForProduct) < 0),
licence: install.licence ? { id: install.licence.id, status: install.licence.status, expiresAt: install.licence.expiresAt } : null,
lastHeartbeatAt: install.lastHeartbeatAt,
status: worst,
@@ -58,16 +65,29 @@ function summary(install, settings, now = new Date()) {
// ─── Dashboard ────────────────────────────────────────────────────────────────
router.get('/dashboard', wrap(async (req, res) => {
const settings = await getSettings();
const [settings, latest] = await Promise.all([getSettings(), latestVersions()]);
const installs = await prisma.install.findMany({ where: { releasedAt: null }, include: { licence: true, customer: true }, orderBy: { name: 'asc' } });
const rows = installs.map(i => summary(i, settings));
const [customers, licences, openAlerts] = await Promise.all([
const rows = installs.map(i => summary(i, settings, latest));
const [customers, licences, openAlerts, billed, sentInvoices] = await Promise.all([
prisma.customer.count(),
prisma.licence.groupBy({ by: ['status'], _count: { _all: true } }),
prisma.licence.groupBy({ by: ['product', 'status'], _count: { _all: true } }),
prisma.installEvent.count({ where: { resolvedAt: null, level: { not: 'info' } } }),
prisma.customer.findMany({ where: { billingCycle: { not: 'none' } }, include: { licences: { include: { install: true } } } }),
prisma.invoice.findMany({ where: { status: 'sent' }, include: { payments: true } }),
]);
// Hub 2.0: per product, monthly recurring revenue (after discounts) and overdue invoices.
const byProduct = Object.fromEntries(PRODUCTS.map(p => {
const own = rows.filter(r => r.product === p);
return [p, {
installs: own.length, behind: own.filter(r => r.behind).length, critical: own.filter(r => r.status === 'critical').length,
licences: Object.fromEntries(licences.filter(l => l.product === p).map(l => [l.status, l._count._all])),
}];
}));
const t = ymd(today());
const overdue = sentInvoices.map(i => compute.invoiceState(i, t)).filter(s => s.state === 'overdue');
res.json({
latestVersion: settings.latest_version || null,
latestVersion: latest.events || null,
latestVersions: latest,
counts: {
installs: rows.length,
healthy: rows.filter(r => r.status === 'ok').length,
@@ -75,9 +95,14 @@ router.get('/dashboard', wrap(async (req, res) => {
critical: rows.filter(r => r.status === 'critical').length,
behind: rows.filter(r => r.behind).length,
customers,
licences: Object.fromEntries(licences.map(l => [l.status, l._count._all])),
licences: licences.reduce((acc, l) => ({ ...acc, [l.status]: (acc[l.status] || 0) + l._count._all }), {}),
openAlerts,
billedCustomers: billed.length,
overdueInvoices: overdue.length,
},
byProduct,
monthlyRecurringCents: billed.reduce((s, c) => s + compute.monthlyRecurringCents(c, c.licences), 0),
overdueCents: overdue.reduce((s, x) => s + x.balanceCents, 0),
installs: rows,
});
}));
@@ -87,7 +112,7 @@ router.get('/dashboard', wrap(async (req, res) => {
router.get('/customers', wrap(async (req, res) => {
const customers = await prisma.customer.findMany({
orderBy: { name: 'asc' },
include: { licences: { select: { id: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, url: true, lastHeartbeatAt: true } } },
include: { licences: { select: { id: true, product: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, product: true, url: true, lastHeartbeatAt: true } } },
});
res.json(customers);
}));
@@ -95,6 +120,20 @@ router.get('/customers', wrap(async (req, res) => {
function customerData(body, { partial = false } = {}) {
const data = {};
for (const f of ['name', 'contactName', 'email', 'phone', 'notes']) if (body?.[f] !== undefined) data[f] = text(body[f], f === 'notes' ? 5000 : 200);
// AI (Hub 2.0: the church's, for all its installs): the monthly cap and an optional markup.
if (body?.aiMonthlyCapCents !== undefined) {
const n = parseInt(body.aiMonthlyCapCents, 10);
if (!Number.isInteger(n) || n < 0) throw bad('The AI cap must be 0 or more.');
data.aiMonthlyCapCents = n;
}
if (body?.aiMarkupPercent !== undefined) {
if (body.aiMarkupPercent === null || body.aiMarkupPercent === '') data.aiMarkupPercent = null;
else {
const n = parseInt(body.aiMarkupPercent, 10);
if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The AI markup is 0–500 %, or blank for the default.');
data.aiMarkupPercent = n;
}
}
if ((!partial || 'name' in data) && !data.name) throw bad('Give the customer a name.');
return data;
}
@@ -131,19 +170,6 @@ function licenceData(body, { partial = false } = {}) {
if (!Number.isInteger(n) || n < 0 || n > 90) throw bad('Grace period: 0–90 days.');
data.graceDays = n;
}
if (body?.aiMonthlyCapCents !== undefined) {
const n = parseInt(body.aiMonthlyCapCents, 10);
if (!Number.isInteger(n) || n < 0) throw bad('The AI cap must be 0 or more.');
data.aiMonthlyCapCents = n;
}
if (body?.aiMarkupPercent !== undefined) {
if (body.aiMarkupPercent === null || body.aiMarkupPercent === '') data.aiMarkupPercent = null;
else {
const n = parseInt(body.aiMarkupPercent, 10);
if (!Number.isInteger(n) || n < 0 || n > 500) throw bad('The AI markup is 0–500 %, or blank for the default.');
data.aiMarkupPercent = n;
}
}
if (body?.status !== undefined) {
if (!['active', 'suspended', 'revoked'].includes(body.status)) throw bad('Status must be active, suspended or revoked.');
data.status = body.status;
@@ -153,23 +179,31 @@ function licenceData(body, { partial = false } = {}) {
return data;
}
// "Generate": a new licence with a fresh key for a customer.
// "Generate": a new licence with a fresh key for a customer, for one product (Events unless
// another is given). A customer has one open licence per product; its Accounts licence (free)
// is created with its first other product.
router.post('/customers/:id/licences', wrap(async (req, res) => {
const customer = await prisma.customer.findUnique({ where: { id: req.params.id } });
if (!customer) throw bad('Customer not found', 404);
let licence;
for (let attempt = 0; !licence && attempt < 5; attempt++) {
licence = await prisma.licence.create({ data: { ...licenceData(req.body), customerId: customer.id, key: licenceKey() } }).catch(e => (e.code === 'P2002' ? null : Promise.reject(e)));
}
await audit(req, 'licence_generated', licence.id, { customer: customer.name, expiresAt: licence.expiresAt });
res.status(201).json(licence);
const product = req.body?.product ?? 'events';
if (!isProduct(product)) throw bad('Product must be events, accounts, website or app.');
// 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 });
}));
router.put('/licences/:id', wrap(async (req, res) => {
const existing = await prisma.licence.findUnique({ where: { id: req.params.id } });
if (!existing) throw bad('Licence not found', 404);
const data = licenceData(req.body, { partial: true });
const licence = await prisma.licence.update({ where: { id: existing.id }, data });
await checkReopen(prisma, existing, data.status);
const licence = await prisma.licence.update({ where: { id: existing.id }, data }).catch(e => {
if (e.code === 'P2002') throw Object.assign(bad(`This customer already has an open ${PRODUCT_NAMES[existing.product]} licence.`, 409), { code: 'PRODUCT_LICENCE_EXISTS' });
throw e;
});
await audit(req, 'licence_updated', licence.id, { changed: Object.keys(data), status: licence.status, expiresAt: licence.expiresAt });
res.json(licence);
}));
@@ -189,13 +223,13 @@ router.post('/licences/:id/release', wrap(async (req, res) => {
// ─── Installs ─────────────────────────────────────────────────────────────────
router.get('/installs', wrap(async (req, res) => {
const settings = await getSettings();
const [settings, latest] = await Promise.all([getSettings(), latestVersions()]);
const installs = await prisma.install.findMany({ include: { licence: true, customer: true }, orderBy: { name: 'asc' } });
res.json(installs.map(i => summary(i, settings)));
res.json(installs.map(i => summary(i, settings, latest)));
}));
router.get('/installs/:id', wrap(async (req, res) => {
const settings = await getSettings();
const [settings, latest] = await Promise.all([getSettings(), latestVersions()]);
const install = await prisma.install.findUnique({
where: { id: req.params.id },
include: { licence: true, customer: true, events: { orderBy: { createdAt: 'desc' }, take: 100 } },
@@ -211,10 +245,23 @@ router.get('/installs/:id', wrap(async (req, res) => {
let licence = null;
if (install.licence) {
// What the install would be told right now, for checking.
licence = { ...install.licence, tokenPreview: licenceToken.buildPayload(install.licence, install, install.customer.name) };
licence = { ...install.licence, tokenPreview: licenceToken.buildPayload({ ...install.licence, aiMonthlyCapCents: install.customer.aiMonthlyCapCents }, install, install.customer.name) };
}
const [aiStatus, aiMonths, aiHelpers] = await Promise.all([ai.statusFor(install), ai.usageByMonth(install.id), ai.usageByHelper(install.id)]);
res.json({ ...safe, licence, summary: summary(install, settings), heartbeats, ai: { status: aiStatus, months: aiMonths, helpers: aiHelpers } });
const target = latest[install.product] || null;
const behind = !!(target && install.version && compareVersions(install.version, target) < 0);
const [aiStatus, aiMonths, aiHelpers, unmet] = await Promise.all([
ai.statusFor(install), ai.usageByMonth(install.id), ai.usageByHelper(install.id),
behind ? unmetRequirementsFor(install, target) : [],
]);
res.json({
...safe, licence, summary: summary(install, settings, latest), heartbeats, ai: { status: aiStatus, months: aiMonths, helpers: aiHelpers },
// What updating to the latest version needs from the church's other products (Hub 2.0).
update: { latestVersion: target, behind, unmetRequirements: unmet },
// The church's other installs this one is told about (protocol v2), and the ones it isn't.
linkedProducts: await linkedProductsFor(install),
siblings: (await prisma.install.findMany({ where: { customerId: install.customerId, id: { not: install.id }, releasedAt: null }, select: { id: true, product: true, url: true, version: true, protocolVersion: true, publicKey: true, lastHeartbeatAt: true } }))
.map(({ publicKey, ...s }) => ({ ...s, hasPublicKey: !!publicKey })),
});
}));
router.put('/installs/:id', wrap(async (req, res) => {
@@ -239,22 +286,35 @@ router.get('/audit', wrap(async (req, res) => {
}));
// ─── Releases ─────────────────────────────────────────────────────────────────
// What's new in each Cross Events version. Installs on an older version see the notes; the highest
// version is the latest (latest_version), so adding one tells installs an update is out. With a git
// repository set (Releases page), releases come from its tags and WHATS-NEW.md only.
// What's new in each version of each product (Hub 2.0). Installs on an older version see the
// notes; a product's highest version is its latest, so a new one tells its installs an update is
// out. A product with release sources (Releases page) gets its releases from git only; one with
// none is managed by hand.
router.get('/releases', wrap(async (req, res) => {
const [releases, installs] = await Promise.all([
prisma.release.findMany(),
prisma.install.findMany({ where: { releasedAt: null }, select: { version: true } }),
prisma.install.findMany({ where: { releasedAt: null }, select: { product: true, version: true } }),
]);
const onVersion = {};
for (const i of installs) if (i.version) onVersion[i.version] = (onVersion[i.version] || 0) + 1;
res.json(sortReleases(releases).map(r => ({ ...r, installs: onVersion[r.version] || 0 })));
for (const i of installs) if (i.version) onVersion[`${i.product}@${i.version}`] = (onVersion[`${i.product}@${i.version}`] || 0) + 1;
const latest = await latestVersions();
res.json(sortReleases(releases).map(r => ({ ...r, latest: latest[r.product] === r.version, installs: onVersion[`${r.product}@${r.version}`] || 0 })));
}));
// The release sources in use (the saved list or the defaults).
router.get('/releases/sources', wrap(async (req, res) => {
const settings = await getSettings();
res.json({ sources: releaseSources(settings), saved: !!String(settings.release_sources || '').trim() });
}));
function releaseData(body, { partial = false } = {}) {
const data = {};
if (!partial) {
const product = body?.product ?? 'events';
if (!isProduct(product)) throw bad('Choose a product.');
data.product = product;
}
if (body?.version !== undefined) {
const v = String(body.version || '').trim().replace(/^v/i, '');
if (!VERSION_RE.test(v)) throw bad('The version looks like 1.47.0.');
@@ -266,12 +326,15 @@ function releaseData(body, { partial = false } = {}) {
return data;
}
async function manualReleases() {
if (parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Releases come from git: tag the version and edit WHATS-NEW.md, then Sync now.');
// A product with release sources gets its releases from git only.
async function manualReleases(product) {
if (releaseSources(await getSettings()).some(s => s.product === product)) {
throw bad(`${PRODUCT_NAMES[product]} releases come from git: tag the version and edit its notes file, then Sync now.`);
}
}
router.post('/releases/sync', wrap(async (req, res) => {
if (!parseRepoUrl((await getSettings()).release_repo_url)) throw bad('Set the git repository first.');
if (!releaseSources(await getSettings()).length) throw bad('Add a release source first.');
let result;
try {
result = await syncReleases();
@@ -283,34 +346,39 @@ router.post('/releases/sync', wrap(async (req, res) => {
}));
const releaseError = e => {
if (e.code === 'P2002') throw bad('There is already a release with that version.', 409);
if (e.code === 'P2002') throw bad('This product already has a release with that version.', 409);
if (e.code === 'P2025') throw bad('Release not found', 404);
throw e;
};
router.post('/releases', wrap(async (req, res) => {
await manualReleases();
const release = await prisma.release.create({ data: releaseData(req.body) }).catch(releaseError);
const data = releaseData(req.body);
await manualReleases(data.product);
const release = await prisma.release.create({ data }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_added', release.id, { version: release.version, urgent: release.urgent });
res.status(201).json({ release, latestVersion: latest || null });
await audit(req, 'release_added', release.id, { product: release.product, version: release.version, urgent: release.urgent });
res.status(201).json({ release, latestVersion: latest[release.product] || null });
}));
router.put('/releases/:id', wrap(async (req, res) => {
await manualReleases();
const existing = await prisma.release.findUnique({ where: { id: req.params.id } });
if (!existing) throw bad('Release not found', 404);
await manualReleases(existing.product);
const data = releaseData(req.body, { partial: true });
const release = await prisma.release.update({ where: { id: req.params.id }, data }).catch(releaseError);
const release = await prisma.release.update({ where: { id: existing.id }, data }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_updated', release.id, { version: release.version, changed: Object.keys(data) });
res.json({ release, latestVersion: latest || null });
await audit(req, 'release_updated', release.id, { product: release.product, version: release.version, changed: Object.keys(data) });
res.json({ release, latestVersion: latest[release.product] || null });
}));
router.delete('/releases/:id', wrap(async (req, res) => {
await manualReleases();
const release = await prisma.release.delete({ where: { id: req.params.id } }).catch(releaseError);
const existing = await prisma.release.findUnique({ where: { id: req.params.id } });
if (!existing) throw bad('Release not found', 404);
await manualReleases(existing.product);
const release = await prisma.release.delete({ where: { id: existing.id } }).catch(releaseError);
const latest = await syncLatestVersion();
await audit(req, 'release_deleted', release.id, { version: release.version });
res.json({ latestVersion: latest || null });
await audit(req, 'release_deleted', release.id, { product: release.product, version: release.version });
res.json({ latestVersion: latest[release.product] || null });
}));
// ─── Notices ──────────────────────────────────────────────────────────────────
@@ -385,7 +453,8 @@ router.delete('/notices/:id', wrap(async (req, res) => {
// ─── Settings ─────────────────────────────────────────────────────────────────
router.get('/settings', wrap(async (req, res) => {
res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured(), aiModels: AI_MODELS });
const settings = await getSettings();
res.json({ settings, releaseSources: releaseSources(settings), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured(), aiModels: AI_MODELS });
}));
const SMTP_FIELDS = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_pass_clear', 'smtp_from'];
@@ -424,6 +493,11 @@ router.put('/settings', wrap(async (req, res) => {
const { latest_version, release_synced_at, release_sync_error, ...values } = req.body?.settings || {};
if (values.release_repo_url && !parseRepoUrl(values.release_repo_url)) throw bad('The repository address looks like https://git.example.com/owner/repo.');
if (values.release_notes_path != null && !String(values.release_notes_path).trim()) values.release_notes_path = 'WHATS-NEW.md';
// Hub 2.0: the release sources per product. A list is checked and saved as JSON; null goes back
// to the defaults.
if (values.release_sources !== undefined) {
values.release_sources = values.release_sources === null ? '' : JSON.stringify(cleanSources(values.release_sources));
}
checkSmtp(values);
checkAi(values);
if (values.ai_model != null) values.ai_model = String(values.ai_model).trim();
+123 -27
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,9 @@ 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, ADDRESS } = require('../utils/billing/tiers');
const { addMonths } = require('../utils/billing/dates');
const { BILLABLE, PRODUCT_NAMES } = require('../utils/products');
const router = express.Router();
router.use(protect);
@@ -42,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),
};
}
@@ -67,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,
});
}));
@@ -102,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) => {
@@ -173,7 +178,32 @@ 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 and address for the billing screens. */
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. */
router.get('/customers', wrap(async (req, res) => {
const t = ymd(today());
const customers = await prisma.customer.findMany({
@@ -184,9 +214,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),
};
}));
}));
@@ -205,23 +236,47 @@ 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,
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.
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 || [] },
});
}));
@@ -240,8 +295,52 @@ 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]);
// 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 } });
if (!existing) throw bad('Customer not found', 404);
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.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 });
}));
@@ -260,16 +359,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 {
@@ -278,15 +381,8 @@ router.put('/licences/:id', wrap(async (req, res) => {
data.customMonthlyCents = n;
}
}
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 = 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 });
}));
+72 -21
View File
@@ -1,7 +1,11 @@
/**
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request
* (and withdrawing it).
* (and withdrawing it), AI.
* Install → Hub only; these are the only endpoints that aren't behind an admin login.
*
* Protocol v1 (Cross Events 2.1) and v2 (every product, @crosscode/contracts `hub`) are both
* accepted (utils/protocol.js). v2 bodies are checked with the contract schemas, and v2 replies
* add `linkedProducts`; v1 is handled and answered exactly as before.
*/
const express = require('express');
@@ -14,13 +18,15 @@ const { getSettings } = require('../utils/settings');
const { compareVersions } = require('../utils/alerts');
const { requestMessage, requestedVersionOf, isOutdated } = require('../utils/updateRequests');
const { sendMail } = require('../utils/mail');
const { releasesForInstall } = require('../utils/releases');
const { releasesForInstall, latestVersions, unmetRequirementsFor, requirementMessage } = require('../utils/releases');
const { noticesForInstall } = require('../utils/notices');
const ai = require('../utils/ai');
const { PRODUCT_NAMES } = require('../utils/products');
const { hub } = require('@crosscode/contracts');
const { PROTOCOL_VERSIONS, isV2, parseV2, linkedProductsFor } = require('../utils/protocol');
const router = express.Router();
const PROTOCOL_VERSIONS = [1];
const HEARTBEAT_MINUTES = 15;
const registerLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts.', code: 'RATE_LIMITED' } });
const heartbeatLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } });
@@ -48,10 +54,20 @@ function cleanUrl(url) {
}
}
/**
* The install's product's latest version and the releases newer than `version` (Hub 2.0: per
* product). v2 replies carry each release's requirements; v1 replies are as before.
*/
async function releaseInfo(install, version, { v2 = false } = {}) {
const latest = (await latestVersions())[install.product] || null;
return { latestVersion: latest, releases: await releasesForInstall(install.product, version, { withRequires: v2 }) };
}
async function tokenFor(install) {
const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true } } } }) : null;
const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true, aiMonthlyCapCents: true } } } }) : null;
if (!licence) return null;
return licenceToken.sign(licenceToken.buildPayload(licence, install, licence.customer.name));
// The AI cap in the token is the church's (Hub 2.0).
return licenceToken.sign(licenceToken.buildPayload({ ...licence, aiMonthlyCapCents: licence.customer.aiMonthlyCapCents }, install, licence.customer.name));
}
/**
@@ -76,14 +92,32 @@ async function signedInstall(req, res) {
return install;
}
/**
* The request body: a v2 body checked against its contract schema (null once the 400 is sent),
* a v1 body as it came.
*/
function bodyFor(req, res, schema) {
if (!isV2(req.body)) return req.body || {};
const parsed = parseV2(schema, req.body);
if (!parsed.ok) { fail(res, parsed.status, parsed.code, parsed.message); return null; }
return parsed.data;
}
const wrongProduct = (res, got, want) =>
fail(res, 409, 'WRONG_PRODUCT', `This is a ${PRODUCT_NAMES[got]} licence, not a ${PRODUCT_NAMES[want]} one. Check you copied the right key.`);
router.get('/public-key', (req, res) => {
res.json({ protocolVersions: PROTOCOL_VERSIONS, keyId: 'k1', algorithm: 'Ed25519', publicKey: licenceToken.keyPair().publicKeyPem });
});
router.post('/installs/register', registerLimiter, async (req, res) => {
try {
const body = req.body || {};
if (!protocolOk(body)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${body.protocolVersion} is not supported; this Hub speaks ${PROTOCOL_VERSIONS.join(', ')}.`);
const raw = req.body || {};
if (!protocolOk(raw)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${raw.protocolVersion} is not supported; this Hub speaks ${PROTOCOL_VERSIONS.join(', ')}.`);
const v2 = isV2(raw);
// A key as typed (lower case, spaces) is tidied before the v2 schema checks its shape.
const body = bodyFor({ body: v2 ? { ...raw, licenceKey: normaliseLicenceKey(raw.licenceKey) } : raw }, res, hub.registerRequestSchema);
if (!body) return;
const info = body.install || {};
const url = cleanUrl(info.url);
if (!url) return fail(res, 400, 'BAD_URL', 'The install needs its public web address (https://…).');
@@ -91,6 +125,9 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
const licence = await prisma.licence.findUnique({ where: { key: normaliseLicenceKey(body.licenceKey) }, include: { install: true, customer: true } });
if (!licence) return fail(res, 404, 'LICENCE_NOT_FOUND', 'That licence key was not found. Check it, or ask your provider for your key.');
if (licence.status === 'revoked') return fail(res, 403, 'LICENCE_REVOKED', 'This licence has been revoked.');
// v2 says which product is registering; v1 is always Cross Events.
const product = v2 ? body.product : 'events';
if (licence.product !== product) return wrongProduct(res, licence.product, product);
if (licence.install && licence.install.url !== url) {
return fail(res, 409, 'LICENCE_IN_USE', 'This licence is already used by another site. Ask your provider to release it if you have moved.');
}
@@ -106,23 +143,24 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
server: info.server ? { node: str(info.server.node, 40), postgres: str(info.server.postgres, 40), os: str(info.server.os, 80) } : undefined,
timezone: str(info.timezone, 60),
features: info.features && typeof info.features === 'object' ? info.features : undefined,
// v2: shared with the church's other installs (linkedProducts). A v1 re-register keeps it.
publicKey: v2 ? info.publicKey : undefined,
releasedAt: null,
};
// Same licence, same site → re-register (new secret, same id).
const install = licence.install
? await prisma.install.update({ where: { id: licence.install.id }, data })
: await prisma.install.create({ data: { ...data, customerId: licence.customerId, licenceId: licence.id } });
: await prisma.install.create({ data: { ...data, product: licence.product, customerId: licence.customerId, licenceId: licence.id } });
await prisma.installEvent.create({ data: { installId: install.id, type: 'registered', level: 'info', message: `${licence.install ? 'Re-registered' : 'Registered'} from ${url} (version ${install.version || '?'})`, resolvedAt: new Date() } });
const settings = await getSettings();
res.status(201).json({
installId: install.id,
installSecret: secret,
licence: await tokenFor(install),
heartbeatIntervalMinutes: HEARTBEAT_MINUTES,
latestVersion: settings.latest_version || null,
releases: await releasesForInstall(install.version),
...(await releaseInfo(install, install.version, { v2 })),
notices: await noticesForInstall(install.id),
...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}),
});
} catch (e) {
console.error('[register]', e);
@@ -134,7 +172,10 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
try {
const install = await signedInstall(req, res);
if (!install) return;
const body = req.body;
const body = bodyFor(req, res, hub.heartbeatRequestSchema);
if (!body) return;
const v2 = isV2(body);
if (v2 && body.product !== install.product) return wrongProduct(res, install.product, body.product);
const now = new Date();
const version = str(body.version, 40);
@@ -152,12 +193,11 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
}
}
const settings = await getSettings();
res.json({
licence: await tokenFor(install),
latestVersion: settings.latest_version || null,
releases: await releasesForInstall(version || install.version),
...(await releaseInfo(install, version || install.version, { v2 })),
notices: await noticesForInstall(install.id, now),
...(v2 ? { linkedProducts: await linkedProductsFor(install) } : {}),
serverTime: now.toISOString(),
});
} catch (e) {
@@ -172,13 +212,20 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
try {
const install = await signedInstall(req, res);
if (!install) return;
const body = bodyFor(req, res, hub.updateRequestSchema);
if (!body) return;
const settings = await getSettings();
const latest = settings.latest_version || null;
const current = str(req.body.version, 40) || install.version;
const latest = (await latestVersions())[install.product] || null;
const current = str(body.version, 40) || install.version;
if (!latest || compareVersions(current, latest) >= 0) {
return fail(res, 409, 'UP_TO_DATE', 'This site already runs the latest version.');
}
// Hub 2.0: the update may need the church's other products updated first.
const unmet = await unmetRequirementsFor({ ...install, version: current }, latest);
if (unmet.length) {
return res.status(409).json({ code: 'REQUIREMENT_NOT_MET', message: `This update needs another product first. ${requirementMessage(unmet)}`, requirements: unmet });
}
const customerName = async () => (await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } }))?.name || install.name;
const link = `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`;
@@ -197,7 +244,7 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
const name = await customerName();
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: update request changed by ${name}`,
subject: `Cross Code Hub: update request changed by ${name}`,
text: `${name} (${install.url}) now asks to be updated from ${current} to ${latest}${previous ? ` instead of ${previous}` : ''}.\n\n${link}`,
}).catch(e => console.warn('[update-request] email failed:', e?.message));
}
@@ -209,7 +256,7 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
const name = await customerName();
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: update requested by ${name}`,
subject: `Cross Code Hub: update requested by ${name}`,
text: `${name} (${install.url}) would like to be updated from ${current} to ${latest}.\n\n${link}`,
}).catch(e => console.warn('[update-request] email failed:', e?.message));
}
@@ -226,6 +273,7 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req,
try {
const install = await signedInstall(req, res);
if (!install) return;
if (!bodyFor(req, res, hub.updateRequestCancelSchema)) return;
const now = new Date();
const open = await prisma.installEvent.findMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null } });
@@ -238,7 +286,7 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req,
const customer = await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } });
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: update request withdrawn by ${customer?.name || install.name}`,
subject: `Cross Code Hub: update request withdrawn by ${customer?.name || install.name}`,
text: `${customer?.name || install.name} (${install.url}) withdrew their update request. No need to update the site for now.\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`,
}).catch(e => console.warn('[update-request] email failed:', e?.message));
}
@@ -256,6 +304,7 @@ router.post('/installs/ai/status', aiLimiter, async (req, res) => {
try {
const install = await signedInstall(req, res);
if (!install) return;
if (!bodyFor(req, res, hub.aiStatusRequestSchema)) return;
res.json(await ai.statusFor(install));
} catch (e) {
console.error('[ai/status]', e);
@@ -269,7 +318,9 @@ router.post('/installs/ai/complete', aiLimiter, async (req, res) => {
try {
install = await signedInstall(req, res);
if (!install) return;
res.json(await ai.complete(install, req.body));
const body = bodyFor(req, res, hub.aiCompleteRequestSchema);
if (!body) return;
res.json(await ai.complete(install, body));
} catch (e) {
if (e.status && e.code) return res.status(e.status).json({ code: e.code, message: e.message, ...(e.aiStatus ? { status: e.aiStatus } : {}) });
console.error('[ai/complete]', e);
+33 -21
View File
@@ -50,7 +50,7 @@ function renewsOn(date = new Date()) {
* Prices for a call, or null when the Hub's AI isn't set up (no key or no exchange rate).
* Blank prices use the built-in ones for the model (utils/aiModels.js); cache reads always do,
* falling back to 0.1× the input price for a model the Hub doesn't know.
* `licence.aiMarkupPercent` overrides the Hub's default markup.
* `allowance.aiMarkupPercent` (the church's, Hub 2.0) overrides the Hub's default markup.
*/
function pricing(settings, licence, hasKey) {
const known = findModel(settings.ai_model);
@@ -131,11 +131,14 @@ function cleanRequest(body) {
// ─── Database ─────────────────────────────────────────────────────────────────
/** Charged so far this month (millicents): finished calls, and holds for calls still running. */
async function chargedThisMonth(db, installId, month, now = new Date()) {
/**
* Charged so far this month (millicents) over the church's installs (Hub 2.0: the cap is the
* church's): finished calls, and holds for calls still running.
*/
async function chargedThisMonth(db, installIds, month, now = new Date()) {
const rows = await db.aiUsage.aggregate({
where: {
installId, month,
installId: { in: installIds }, month,
OR: [{ status: { in: ['done', 'failed'] } }, { status: 'reserved', createdAt: { gt: new Date(now.getTime() - STALE_HOLD_MS) } }],
},
_sum: { chargedMillicents: true },
@@ -143,30 +146,38 @@ async function chargedThisMonth(db, installId, month, now = new Date()) {
return rows._sum.chargedMillicents || 0;
}
/**
* What a call is checked against: the install's licence (active, not expired) with the church's
* cap and markup (Hub 2.0), and the church's installs whose use counts towards the cap.
*/
async function setup(install) {
const [settings, key, licence] = await Promise.all([
const [settings, key, licence, customer, installs] = await Promise.all([
getSettings(),
aiApiKey(),
install.licenceId ? prisma.licence.findUnique({ where: { id: install.licenceId } }) : null,
install.customerId ? prisma.customer.findUnique({ where: { id: install.customerId }, select: { aiMonthlyCapCents: true, aiMarkupPercent: true } }) : null,
install.customerId ? prisma.install.findMany({ where: { customerId: install.customerId }, select: { id: true } }) : [],
]);
return { settings, key, licence, price: pricing(settings, licence, !!key) };
const allowance = licence ? { ...licence, aiMonthlyCapCents: customer?.aiMonthlyCapCents || 0, aiMarkupPercent: customer?.aiMarkupPercent ?? null } : null;
const installIds = [...new Set([install.id, ...installs.map(i => i.id)])];
return { settings, key, licence: allowance, installIds, price: pricing(settings, allowance, !!key) };
}
/** Status for one install (§3b). */
/** Status for one install (§3b): the church's allowance, used by all its installs. */
async function statusFor(install, now = new Date()) {
const { licence, price } = await setup(install);
return statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, install.id, monthOf(now), now), now });
const { licence, installIds, price } = await setup(install);
return statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, installIds, monthOf(now), now), now });
}
/**
* Hold the worst case against the cap, or refuse. One transaction with a lock per install, so two
* calls at once can't both take the last of the allowance.
* Hold the worst case against the cap, or refuse. One transaction with a lock per church (its
* installs share the cap), so two calls at once can't both take the last of the allowance.
*/
async function reserve({ install, licence, price, helper, worst, now }) {
async function reserve({ install, installIds, licence, price, helper, worst, now }) {
const month = monthOf(now);
return prisma.$transaction(async tx => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai:${install.id}`}))`;
const charged = await chargedThisMonth(tx, install.id, month, now);
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai:${install.customerId || install.id}`}))`;
const charged = await chargedThisMonth(tx, installIds, month, now);
if (charged + worst > licence.aiMonthlyCapCents * 1000) return null;
return tx.aiUsage.create({
data: { installId: install.id, helper, model: price.model, month, status: 'reserved', chargedMillicents: worst, markupPercent: price.markup, usdZar: price.usdZar },
@@ -231,15 +242,15 @@ function claudeError(e) {
*/
async function complete(install, body, now = new Date()) {
const req = cleanRequest(body);
const { key, licence, price } = await setup(install);
const status = async () => statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, install.id, monthOf(now), now), now });
const { key, licence, installIds, price } = await setup(install);
const status = async () => statusOf({ licence, price, chargedMillicents: await chargedThisMonth(prisma, installIds, monthOf(now), now), now });
if (!price) throw Object.assign(fail(503, 'AI_NOT_CONFIGURED', 'AI is not available.'), { aiStatus: await status() });
if (!licence || licence.aiMonthlyCapCents <= 0) throw Object.assign(fail(403, 'AI_OFF', 'AI is not part of this licence.'), { aiStatus: await status() });
if (!licence || licence.aiMonthlyCapCents <= 0) throw Object.assign(fail(403, 'AI_OFF', 'AI is not part of this church\'s plan.'), { aiStatus: await status() });
if (!licenceAllows(licence, now)) throw Object.assign(fail(403, 'LICENCE_INACTIVE', 'AI needs an active licence.'), { aiStatus: await status() });
const worst = worstCase(req.inputTokens, req.maxTokens, price);
const hold = await reserve({ install, licence, price, helper: req.helper, worst, now });
const hold = await reserve({ install, installIds, licence, price, helper: req.helper, worst, now });
if (!hold) throw Object.assign(fail(402, 'AI_CAP_REACHED', "This month's AI allowance is used up."), { aiStatus: await status() });
let message;
@@ -323,7 +334,7 @@ async function usageByHelper(installId, month = monthOf()) {
return rows.map(r => ({ helper: r.helper, calls: r._count._all, chargedCents: toCents(r._sum.chargedMillicents || 0) })).sort((a, b) => b.chargedCents - a.chargedCents);
}
/** Every install's use in a month, for the Settings → AI overview. */
/** Every install's use in a month, for the Settings → AI overview (with its product and the church's cap). */
async function usageForMonth(month = monthOf()) {
const rows = await prisma.aiUsage.groupBy({
by: ['installId'],
@@ -331,12 +342,13 @@ async function usageForMonth(month = monthOf()) {
_sum: { realMillicents: true, chargedMillicents: true },
_count: { _all: true },
});
const installs = await prisma.install.findMany({ where: { id: { in: rows.map(r => r.installId) } }, select: { id: true, name: true, url: true, licence: { select: { aiMonthlyCapCents: true } } } });
const installs = await prisma.install.findMany({ where: { id: { in: rows.map(r => r.installId) } }, select: { id: true, name: true, url: true, product: true, customer: { select: { id: true, name: true, aiMonthlyCapCents: true } } } });
const byId = new Map(installs.map(i => [i.id, i]));
return rows.map(r => {
const i = byId.get(r.installId);
return {
installId: r.installId, name: i?.name || '?', url: i?.url || '', capCents: i?.licence?.aiMonthlyCapCents || 0,
installId: r.installId, name: i?.name || '?', url: i?.url || '', product: i?.product || 'events',
customer: i?.customer ? { id: i.customer.id, name: i.customer.name } : null, capCents: i?.customer?.aiMonthlyCapCents || 0,
calls: r._count._all,
realCents: toCents(r._sum.realMillicents || 0),
chargedCents: toCents(r._sum.chargedMillicents || 0),
+16 -4
View File
@@ -70,15 +70,27 @@ function problems(install, settings, now = new Date()) {
else if (left <= s.expiryDays * DAY) out.push({ type: 'licence_expiring', level: 'warning', message: `Licence expires ${new Date(lic.expiresAt).toISOString().slice(0, 10)}` });
}
if (settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0) {
out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${settings.latest_version}` });
// Hub 2.0: the latest version of the install's product (settings.latest_versions, a map); before
// that, latest_version was Cross Events'.
const latest = settings.latest_versions ? settings.latest_versions[install.product || 'events'] : settings.latest_version;
if (latest && install.version && compareVersions(install.version, latest) < 0) {
out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${latest}` });
}
return out;
}
/** Run the checks for every install: open new alerts (emailed unless info), resolve cleared ones. */
/** The latest version of each product ({ events: '2.1.1', … }), read here rather than from releases.js (which needs this file). */
async function latestVersionsNow() {
const out = {};
for (const r of await prisma.release.findMany({ select: { product: true, version: true } })) {
if (!out[r.product] || compareVersions(r.version, out[r.product]) > 0) out[r.product] = r.version;
}
return out;
}
async function runAlerts(now = new Date()) {
const settings = await getSettings();
const settings = { ...(await getSettings()), latest_versions: await latestVersionsNow() };
const installs = await prisma.install.findMany({
where: { releasedAt: null },
include: { licence: true, customer: { select: { name: true } }, events: { where: { resolvedAt: null } } },
@@ -106,7 +118,7 @@ async function runAlerts(now = new Date()) {
if (newAlerts.length && settings.alert_email) {
await sendMail({
to: settings.alert_email,
subject: `Cross Events Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`,
subject: `Cross Code Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`,
text: `${newAlerts.join('\n')}\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/`,
}).catch(e => console.warn('[alerts] email failed:', e?.message));
}
+242 -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, ADDRESS, 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,238 @@ 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 },
};
}
/** 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
* 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);
// 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'
? 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,
};
}
/**
* What a billed customer pays a month as things stand (Hub 2.0 dashboard): a full period of every
* product charged by now, after founding and bundle discounts, plus add-ons; a yearly invoice
* divided by 12. Days owed from before a period aren't recurring, so they're left out. Cents.
*/
function monthlyRecurringCents(customer, licences, now = new Date()) {
if (customer.billingCycle !== 'monthly' && customer.billingCycle !== 'yearly') return 0;
const start = day(customer.nextInvoiceDate || now);
const end = addDays(addMonths(start, monthsIn(customer.billingCycle), anchorDayOf({ billingStart: customer.billingStart, nextInvoiceDate: start })), -1);
const charged = licences
.filter(l => l.billedFrom && ymd(l.billedFrom) <= ymd(now))
// As if invoiced up to this period, and charged for all of it.
.map(l => ({ ...l, billedFrom: ymd(l.billedFrom) < ymd(start) ? l.billedFrom : start, billedUntil: addDays(start, -1) }));
const { lines } = customerInvoiceLines({ customer, licences: charged, period: { start, end, cycle: customer.billingCycle }, reviewed: false });
const total = lines.reduce((s, l) => s + l.amountCents, 0);
return Math.round(customer.billingCycle === 'yearly' ? total / 12 : total);
}
/** 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 +337,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 +373,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, addressMonthlyCents,
planChangesOf, invoiceState, statement, invoiceDescription, anchorDayOf, monthsIn, monthlyRecurringCents,
};
+167 -66
View File
@@ -4,12 +4,14 @@
* 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).
* 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');
@@ -21,8 +23,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 { 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'];
@@ -49,17 +54,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 });
});
}
@@ -74,9 +95,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)],
],
@@ -96,20 +117,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', 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;
@@ -117,6 +140,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';
@@ -126,7 +161,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: [
@@ -136,7 +171,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,
@@ -201,9 +236,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;
@@ -216,15 +252,41 @@ async function applyDueLicenceChanges(now = new Date()) {
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. */
async function runBilling(now = new Date()) {
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 sent = await sendDueInvoices(now, settings);
const reminded = await remindUnapproved(now, settings);
const applied = await applyDueLicenceChanges(now);
return { drafted, sent, reminded, applied };
return { drafted, sent, reminded, applied, domains };
}
// ─── Invoice actions ─────────────────────────────────────────────────────────
@@ -237,20 +299,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) {
@@ -280,23 +342,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,
@@ -310,6 +382,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);
@@ -332,7 +430,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.');
@@ -344,7 +442,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,
});
@@ -353,9 +451,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!`,
@@ -418,16 +516,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);
@@ -436,7 +534,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) {
@@ -451,7 +549,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: [
@@ -473,30 +571,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;
@@ -508,14 +608,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: {
@@ -542,14 +642,15 @@ 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,
applyDueLicenceChanges, runBilling, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice,
nextNumber, loadInvoice, invoicePdfFor, draftForCustomer, createDueDrafts, sendInvoice, sendDueInvoices, remindUnapproved,
applyDueLicenceChanges, runBilling, remindDomainRenewals, approveInvoice, unapproveInvoice, updateInvoice, recalculateInvoice, voidInvoice,
resendInvoice, createManualInvoice, recordPayment, deletePayment, resendReceipt, receiptPdfFor, customerStatement,
statementPdfFor, emailStatement, createLicenceChange, resendLicenceChange, licenceChangePdfFor, emailApproval,
};
+23 -10
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' };
@@ -18,7 +26,7 @@ const W = 595.28 - M * 2; // content width
/** Renders `draw(doc)` into a PDF and resolves with its bytes. */
function render(draw, { title, draft = false } = {}) {
return new Promise((resolve, reject) => {
const doc = new PDFDocument({ size: 'A4', margins: { top: M, bottom: 70, left: M, right: M }, bufferPages: true, info: { Title: title, Author: 'Cross Code', Creator: 'Cross Events Hub' } });
const doc = new PDFDocument({ size: 'A4', margins: { top: M, bottom: 70, left: M, right: M }, bufferPages: true, info: { Title: title, Author: 'Cross Code', Creator: 'Cross Code Hub' } });
const chunks = [];
doc.on('data', c => chunks.push(c));
doc.on('end', () => resolve(Buffer.concat(chunks)));
@@ -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.');
+82 -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,44 @@ 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 };
/**
* 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. */
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 +73,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 +81,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 +113,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, ADDRESS, BUNDLE_PERCENT, YEARLY_MONTHS, FOUNDING_PERCENT,
tierNamed, tierForBand, appTierForBand, reviewTier, planPrice, extraStorageBlocks,
};
+9 -3
View File
@@ -7,6 +7,7 @@
*/
const crypto = require('crypto');
const { KEY_PREFIXES } = require('./products');
let cachedKey = null;
function key() {
@@ -35,11 +36,16 @@ function decrypt(stored) {
// No 0/O, 1/I/L, 5/S, 8/B — easy to read out over the phone.
const KEY_ALPHABET = 'ACDEFGHJKMNPQRTUVWXY234679';
/** A licence key: CEH-XXXX-XXXX-XXXX-XXXX (16 characters from 26, ~75 bits of randomness). */
function licenceKey() {
/**
* A licence key for a product: CEH-XXXX-XXXX-XXXX-XXXX for Events, CCA-/CCW-/CCP- for Accounts,
* Website and App (16 characters from 26, ~75 bits of randomness).
*/
function licenceKey(product = 'events') {
const prefix = KEY_PREFIXES[product];
if (!prefix) throw new Error(`Unknown product: ${product}`);
const bytes = crypto.randomBytes(20);
const chars = Array.from(bytes, b => KEY_ALPHABET[b % KEY_ALPHABET.length]).join('');
return `CEH-${chars.slice(0, 4)}-${chars.slice(4, 8)}-${chars.slice(8, 12)}-${chars.slice(12, 16)}`;
return `${prefix}-${chars.slice(0, 4)}-${chars.slice(4, 8)}-${chars.slice(8, 12)}-${chars.slice(12, 16)}`;
}
/** Tidy what someone typed: upper case, no spaces. */
+4
View File
@@ -35,6 +35,10 @@ function buildPayload(licence, install, customerName, now = new Date()) {
v: 1,
licenceId: licence.id,
installId: install.id,
// Hub 2.0 (contracts licencePayloadSchema): optional fields, still v 1. An install refuses a
// token for another product; Cross Events 2.1 ignores both.
customerId: licence.customerId,
product: licence.product || 'events',
customer: customerName,
plan: licence.plan,
status: licence.status,
+82
View File
@@ -0,0 +1,82 @@
/**
* Creating licences (Hub 2.0): one licence per product per customer that isn't revoked, a key
* with the product's prefix, and the free Accounts licence that comes with any other product.
*/
const { licenceKey } = require('./crypto');
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 });
/** The customer's licence for a product that isn't revoked, or null. */
function openLicence(db, customerId, product) {
return db.licence.findFirst({ where: { customerId, product, status: { not: 'revoked' } } });
}
const productTaken = product =>
conflict(`This customer already has a ${PRODUCT_NAMES[product]} licence. Revoke it first to issue a new one (a customer has one of each product).`, 'PRODUCT_LICENCE_EXISTS');
/**
* A new licence for `product`, with a fresh key. A key collision (vanishingly rare) is retried; a
* second open licence for the product is refused with 409 PRODUCT_LICENCE_EXISTS, also when two
* requests race (the partial unique index catches the second).
*/
async function createLicence(db, { customerId, product = 'events', data = {} }) {
if (!isProduct(product)) throw Object.assign(new Error('Unknown product.'), { status: 400 });
if (await openLicence(db, customerId, product)) throw productTaken(product);
for (let attempt = 0; attempt < 5; attempt++) {
try {
return await db.licence.create({ data: { ...data, customerId, product, key: licenceKey(product) } });
} catch (e) {
if (e?.code !== 'P2002') throw e;
if (await openLicence(db, customerId, product)) throw productTaken(product);
// Otherwise the key collided: try another.
}
}
throw new Error('Could not generate a unique licence key.');
}
/**
* The customer's Accounts licence, created (free, never invoiced) if it has none that isn't
* revoked. Returns { licence, created }.
*/
async function ensureAccountsLicence(db, customerId) {
const existing = await openLicence(db, customerId, 'accounts');
if (existing) return { licence: existing, created: false };
try {
const licence = await createLicence(db, { customerId, product: 'accounts', data: { plan: 'included', status: 'active', notes: 'Comes with the church\'s other products (free).' } });
return { licence, created: true };
} catch (e) {
// Created by a request running at the same time.
if (e.code === 'PRODUCT_LICENCE_EXISTS') return { licence: await openLicence(db, customerId, 'accounts'), created: false };
throw e;
}
}
/**
* 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 = {}, 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);
return { licence, accounts: created ? accounts : null };
}
/**
* Changing a licence's status back from revoked would give the customer two open licences for the
* product: refused with 409 PRODUCT_LICENCE_EXISTS.
*/
async function checkReopen(db, licence, nextStatus) {
if (licence.status !== 'revoked' || !nextStatus || nextStatus === 'revoked') return;
const other = await openLicence(db, licence.customerId, licence.product);
if (other && other.id !== licence.id) throw productTaken(licence.product);
}
module.exports = { openLicence, createLicence, ensureAccountsLicence, generateLicence, checkReopen };
+2 -2
View File
@@ -61,8 +61,8 @@ async function testSmtp(overrides, to) {
await t.sendMail({
from: fromAddress(smtp),
to,
subject: 'Cross Events Hub: test email',
text: `This is a test email from the Cross Events Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`,
subject: 'Cross Code Hub: test email',
text: `This is a test email from the Cross Code Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`,
});
} finally {
t.close();
+37
View File
@@ -0,0 +1,37 @@
/**
* The Cross Code products a church can have (Hub 2.0, ROADMAP-v3 §5). The same names as the
* `Product` enum in schema.prisma and `productSchema` in @crosscode/contracts.
*
* - A customer has at most one licence per product that isn't revoked (a partial unique index).
* - Accounts is free and comes with any other product: its licence is created with the first one.
*/
const PRODUCTS = ['events', 'accounts', 'website', 'app'];
const PRODUCT_NAMES = {
events: 'Cross Events',
accounts: 'Accounts',
website: 'Church Website',
app: 'Church App',
};
/** Licence key prefixes. CEH- (Cross Events Hub) predates 2.0 and stays for Events. */
const KEY_PREFIXES = {
events: 'CEH',
accounts: 'CCA',
website: 'CCW',
app: 'CCP',
};
/** The product a licence key is for, from its prefix, or null. */
function productOfKey(key) {
const prefix = String(key || '').slice(0, 3).toUpperCase();
return PRODUCTS.find(p => KEY_PREFIXES[p] === prefix) || null;
}
const isProduct = p => PRODUCTS.includes(p);
/** 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 };
+55
View File
@@ -0,0 +1,55 @@
/**
* Hub protocol versions (Hub 2.0). v1 is Cross Events 2.1 (docs/hub-protocol.md); v2 is every
* Cross Code product, defined in @crosscode/contracts (`hub`). The Hub accepts both, so Events
* installs keep reporting until they update; v1 requests and replies are exactly as before.
*
* v2 adds: `product` on register and heartbeat (stats per product), the install's public key,
* and `linkedProducts` in the replies. v2 bodies are checked with the contracts' zod schemas:
* unknown fields are dropped, anything missing or malformed is `400 INVALID_REQUEST`.
*/
const { hub } = require('@crosscode/contracts');
const prisma = require('../config/db');
const PROTOCOL_VERSIONS = [...hub.HUB_PROTOCOL_VERSIONS];
const isV2 = body => body?.protocolVersion === 2;
/** "install.url: Invalid URL" for the first problem zod found. */
function describeIssues(error) {
const issue = error.issues[0];
if (!issue) return 'The request is not valid.';
const where = issue.path.length ? `${issue.path.join('.')}: ` : '';
return `${where}${issue.message}`;
}
/**
* A v2 body checked against a contract schema: { ok: true, data } or { ok: false, status, code,
* message }. v1 bodies aren't checked here (they keep the v1 handling).
*/
function parseV2(schema, body) {
const result = schema.safeParse(body);
if (result.success) return { ok: true, data: result.data };
return { ok: false, status: 400, code: 'INVALID_REQUEST', message: describeIssues(result.error) };
}
/**
* The church's other installs, for v2 replies: product, id, URL and public key, nothing else.
* Only installs that are in use (not released, licence not revoked) and have sent a public key
* (protocol v2) are listed, so a sibling can always verify what it's sent.
*/
async function linkedProductsFor(install, db = prisma) {
const others = await db.install.findMany({
where: {
customerId: install.customerId,
id: { not: install.id },
releasedAt: null,
publicKey: { not: null },
licence: { is: { status: { not: 'revoked' } } },
},
select: { id: true, product: true, url: true, publicKey: true },
orderBy: { registeredAt: 'asc' },
});
return others.map(o => ({ product: o.product, installId: o.id, url: o.url, publicKey: o.publicKey }));
}
module.exports = { PROTOCOL_VERSIONS, isV2, parseV2, describeIssues, linkedProductsFor };
+176 -46
View File
@@ -1,18 +1,24 @@
/**
* Releases from git (Gitea): every v1.2.3 tag of the Cross Events repo is a release, dated by its
* commit, and the notes come from the repo's WHATS-NEW.md on its default branch ("## 1.2.3" sections;
* "urgent" or "security" in the heading marks an urgent release). Notes only attach to tagged
* versions, so a section written ahead of a release stays hidden until it's tagged, and a note can be
* corrected after release without a new version. Runs every 15 minutes and from
* "Sync now" on the Releases page, when a repo is set; git is then the only source of releases.
* Releases from git (Gitea), per product (Hub 2.0). Each product has one or more release sources
* (Releases page): a repository, a tag prefix and a notes file. Every tag `<prefix>1.2.3` is a
* release of that product, dated by its commit; the notes come from the notes file on the
* repository's default branch ("## 1.2.3" sections; "urgent" or "security" in the heading marks an
* urgent release, "requires accounts 1.2.0" a requirement). Notes only attach to tagged versions,
* so a section written ahead of a release stays hidden until it's tagged, and a note can be
* corrected after release without a new version. Runs every 15 minutes and from "Sync now".
*
* A product's releases are the tags of all its sources. Releases of a product are only removed
* when every one of its sources was read and at least one tag was found, so an unreachable git
* server (or a mistyped address) never wipes releases. A product with no source is managed by hand.
*/
const prisma = require('../config/db');
const { getSettings, setSettings, releaseRepoToken } = require('./settings');
const { syncLatestVersion } = require('./releases');
const { PRODUCTS, PRODUCT_NAMES, isProduct } = require('./products');
const TIMEOUT_MS = 20000;
const TAG_RE = /^v?(\d+\.\d+\.\d+)$/;
const PLATFORM_REPO = 'https://c-git.crosscode.co.za/joshua/crosscode-platform';
/** https://git.example.com/owner/repo(.git) → { api, owner, repo }, or null. */
function parseRepoUrl(url) {
@@ -27,6 +33,61 @@ function parseRepoUrl(url) {
}
}
/**
* The default sources: every product from the platform monorepo (`events@1.2.3`, `accounts@…`,
* with notes in `apps/<product>/WHATS-NEW.md`), plus Cross Events before the move, from the
* repository set before Hub 2.0 (`release_repo_url`, `v1.2.3` tags).
*/
function defaultSources(settings = {}) {
const platform = product => ({ product, repo: PLATFORM_REPO, tagPrefix: `${product}@`, notesPath: `apps/${product}/WHATS-NEW.md` });
const legacy = parseRepoUrl(settings.release_repo_url)
? [{ product: 'events', repo: String(settings.release_repo_url).trim(), tagPrefix: 'v', notesPath: settings.release_notes_path || 'WHATS-NEW.md' }]
: [];
return [platform('events'), ...legacy, platform('accounts'), platform('website'), platform('app')];
}
const bad = message => Object.assign(new Error(message), { status: 400 });
/** Checked and tidied sources from the Releases page. Throws (status 400) on a bad one. */
function cleanSources(list) {
if (!Array.isArray(list)) throw bad('Release sources must be a list.');
if (list.length > 20) throw bad('At most 20 release sources.');
const seen = new Set();
return list.map((s, i) => {
const n = `Source ${i + 1}`;
if (!isProduct(s?.product)) throw bad(`${n}: choose a product.`);
const repo = String(s.repo || '').trim();
if (!parseRepoUrl(repo)) throw bad(`${n}: the repository address looks like https://git.example.com/owner/repo.`);
const tagPrefix = String(s.tagPrefix ?? '').trim();
if (!/^[A-Za-z0-9._@/-]{0,40}$/.test(tagPrefix)) throw bad(`${n}: the tag prefix can only have letters, digits and . _ @ / -.`);
const notesPath = String(s.notesPath || 'WHATS-NEW.md').trim().replace(/^\/+/, '');
if (!notesPath || notesPath.includes('..') || notesPath.length > 200) throw bad(`${n}: give the notes file's path in the repository.`);
const key = `${parseRepoUrl(repo).api}#${tagPrefix}`;
if (seen.has(key)) throw bad(`${n}: the same repository and tag prefix are listed twice.`);
seen.add(key);
return { product: s.product, repo, tagPrefix, notesPath };
});
}
/** The sources in use: the saved list (release_sources), or the defaults when none is saved. */
function releaseSources(settings = {}) {
const raw = String(settings.release_sources || '').trim();
if (!raw) return defaultSources(settings);
try {
return cleanSources(JSON.parse(raw));
} catch {
return defaultSources(settings);
}
}
const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
/** The tag pattern for a prefix: `v` also accepts a bare 1.2.3 (as before Hub 2.0). */
function tagPattern(prefix) {
if (prefix === 'v') return /^v?(\d+\.\d+\.\d+)$/;
return new RegExp(`^${escapeRegExp(prefix)}(\\d+\\.\\d+\\.\\d+)$`);
}
/** Markdown to the plain notes installs show: list lines stay "- ", the rest loses its markup. */
function plainNotes(lines) {
const out = [];
@@ -50,9 +111,27 @@ function plainNotes(lines) {
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
}
const REQUIREMENT_RE = new RegExp(`\\b(${PRODUCTS.join('|')})\\s+v?(\\d+\\.\\d+\\.\\d+)`, 'gi');
/**
* The sections of WHATS-NEW.md: { "1.46.2": { notes, urgent } }. A section is a "## 1.46.2" heading
* (optionally "[1.46.2]", "v1.46.2", a date or "— urgent" after it) up to the next "## ".
* What a heading needs: "— requires accounts 1.2.0, website 1.1.0 — urgent" →
* [{ product: 'accounts', version: '1.2.0' }, { product: 'website', version: '1.1.0' }].
*/
function parseRequirements(heading) {
const at = String(heading || '').search(/\brequires?\b/i);
if (at < 0) return [];
const out = [];
for (const m of heading.slice(at).matchAll(REQUIREMENT_RE)) {
const product = m[1].toLowerCase();
if (!out.some(r => r.product === product)) out.push({ product, version: m[2] });
}
return out;
}
/**
* The sections of a notes file: { "1.46.2": { notes, urgent, requires } }. A section is a
* "## 1.46.2" heading (optionally "[1.46.2]", "v1.46.2", a date, "— urgent" or "— requires
* accounts 1.2.0" after it) up to the next "## ".
*/
function parseNotes(markdown) {
const text = String(markdown || '').replace(/<!--[\s\S]*?-->/g, '');
@@ -62,14 +141,16 @@ function parseNotes(markdown) {
const heading = /^##\s+(.*)$/.exec(line);
if (heading) {
const v = /\[?v?(\d+\.\d+\.\d+)\]?/.exec(heading[1]);
current = v ? { version: v[1], urgent: /\b(urgent|security)\b/i.test(heading[1]), lines: [] } : null;
current = v
? { version: v[1], urgent: /\b(urgent|security)\b/i.test(heading[1]), requires: parseRequirements(heading[1].slice(v.index + v[0].length)), lines: [] }
: null;
if (current) sections[current.version] = current;
continue;
}
if (/^#\s/.test(line)) { current = null; continue; }
if (current) current.lines.push(line);
}
return Object.fromEntries(Object.values(sections).map(s => [s.version, { notes: plainNotes(s.lines), urgent: s.urgent }]));
return Object.fromEntries(Object.values(sections).map(s => [s.version, { notes: plainNotes(s.lines), urgent: s.urgent, requires: s.requires }]));
}
async function get(url, token, { raw = false } = {}) {
@@ -85,65 +166,114 @@ async function get(url, token, { raw = false } = {}) {
return raw ? res.text() : res.json();
}
/** Every v1.2.3 tag: [{ version, date }]. */
/** Every tag of a repository: [{ name, date }]. */
async function fetchTags(repo, token) {
const tags = [];
for (let page = 1; page <= 20; page++) {
const batch = await get(`${repo.api}/tags?limit=50&page=${page}`, token);
if (batch === null) throw new Error('The repository was not found. Check its address (and the token if it is private).');
for (const t of batch) {
const m = TAG_RE.exec(t.name || '');
if (m) tags.push({ version: m[1], date: t.commit?.created || null });
}
for (const t of batch) if (t?.name) tags.push({ name: t.name, date: t.commit?.created || null });
if (batch.length < 50) break;
}
return tags;
}
const sameRequires = (a, b) => JSON.stringify(a || []) === JSON.stringify(b || []);
const sourceLabel = s => `${PRODUCT_NAMES[s.product]} (${parseRepoUrl(s.repo)?.repo || s.repo}, ${s.tagPrefix || 'no prefix'}1.2.3)`;
/**
* Bring the releases in line with git: add new tags, update notes and urgency from WHATS-NEW.md, and
* remove releases that have no tag. Returns { tags, added, updated, removed, latest }.
* Read every source: { found: { product: Map(version → { date, notes, urgent, requires }) },
* failed: Set(product), problems: [message], counts: [{ source, tags }] }. A repository's tags and
* notes files are fetched once per sync, however many sources use them.
*/
async function readSources(sources, token) {
const found = {};
const failed = new Set();
const problems = [];
const counts = [];
const tagCache = new Map();
const notesCache = new Map();
for (const source of sources) {
try {
const repo = parseRepoUrl(source.repo);
if (!tagCache.has(repo.api)) tagCache.set(repo.api, fetchTags(repo, token));
const pattern = tagPattern(source.tagPrefix);
const tags = (await tagCache.get(repo.api)).map(t => ({ ...t, m: pattern.exec(t.name) })).filter(t => t.m);
let notes = {};
if (tags.length) {
const url = `${repo.api}/raw/${source.notesPath.split('/').map(encodeURIComponent).join('/')}`;
if (!notesCache.has(url)) notesCache.set(url, get(url, token, { raw: true }));
const markdown = await notesCache.get(url);
if (markdown === null) problems.push(`${sourceLabel(source)}: ${source.notesPath} was not found on the default branch, so there are no notes.`);
notes = parseNotes(markdown || '');
}
const map = found[source.product] || (found[source.product] = new Map());
for (const t of tags) {
const version = t.m[1];
// The first source listed wins if two tag the same version.
if (map.has(version)) continue;
const n = notes[version] || { notes: '', urgent: false, requires: [] };
map.set(version, { date: t.date, notes: n.notes, urgent: n.urgent, requires: n.requires.filter(r => r.product !== source.product) });
}
counts.push({ source: sourceLabel(source), tags: tags.length });
} catch (e) {
failed.add(source.product);
problems.push(`${sourceLabel(source)}: ${e.message}`);
}
}
return { found, failed, problems, counts };
}
/**
* Bring each product's releases in line with its sources: add new tags, update notes, urgency and
* requirements, and remove releases that have no tag (only when all the product's sources were
* read and found tags). Returns { sources, added, updated, removed, latest, problems }; throws when
* no source could be read at all.
*/
async function syncReleases() {
const settings = await getSettings();
const repo = parseRepoUrl(settings.release_repo_url);
if (!repo) return { skipped: 'no repository set' };
try {
const token = await releaseRepoToken();
const tags = await fetchTags(repo, token);
if (!tags.length) throw new Error('The repository has no version tags (v1.2.3) yet.');
const path = (settings.release_notes_path || 'WHATS-NEW.md').replace(/^\/+/, '').split('/').map(encodeURIComponent).join('/');
const markdown = await get(`${repo.api}/raw/${path}`, token, { raw: true });
const notes = parseNotes(markdown || '');
const sources = releaseSources(settings);
if (!sources.length) return { skipped: 'no release sources' };
const { found, failed, problems, counts } = await readSources(sources, await releaseRepoToken());
if (counts.length === 0) {
await setSettings({ release_sync_error: `${new Date().toISOString()} ${problems.join(' · ')}`.slice(0, 2000) });
throw new Error(problems.join(' · '));
}
const existing = new Map((await prisma.release.findMany()).map(r => [r.version, r]));
const tagged = new Set(tags.map(t => t.version));
let added = 0;
let updated = 0;
for (const tag of tags) {
const n = notes[tag.version] || { notes: '', urgent: false };
const had = existing.get(tag.version);
let added = 0;
let updated = 0;
let removed = 0;
for (const product of new Set(sources.map(s => s.product))) {
const tagged = found[product] || new Map();
const existing = new Map((await prisma.release.findMany({ where: { product } })).map(r => [r.version, r]));
for (const [version, t] of tagged) {
const had = existing.get(version);
if (!had) {
await prisma.release.create({ data: { version: tag.version, notes: n.notes, urgent: n.urgent, releasedAt: tag.date ? new Date(tag.date) : new Date() } });
await prisma.release.create({ data: { product, version, notes: t.notes, urgent: t.urgent, requires: t.requires, releasedAt: t.date ? new Date(t.date) : new Date() } });
added++;
} else {
// Releases added by hand (or from the old latest_version setting) take the tag's date.
const date = tag.date ? new Date(tag.date) : had.releasedAt;
if (had.notes !== n.notes || had.urgent !== n.urgent || date.getTime() !== new Date(had.releasedAt).getTime()) {
await prisma.release.update({ where: { id: had.id }, data: { notes: n.notes, urgent: n.urgent, releasedAt: date } });
const date = t.date ? new Date(t.date) : had.releasedAt;
if (had.notes !== t.notes || had.urgent !== t.urgent || !sameRequires(had.requires, t.requires) || date.getTime() !== new Date(had.releasedAt).getTime()) {
await prisma.release.update({ where: { id: had.id }, data: { notes: t.notes, urgent: t.urgent, requires: t.requires, releasedAt: date } });
updated++;
}
}
}
if (failed.has(product)) continue;
if (!tagged.size) {
if (existing.size) problems.push(`${PRODUCT_NAMES[product]}: no version tags found in its sources, so its ${existing.size} release(s) were kept. Check the sources.`);
continue;
}
const gone = [...existing.values()].filter(r => !tagged.has(r.version)).map(r => r.id);
if (gone.length) await prisma.release.deleteMany({ where: { id: { in: gone } } });
const latest = await syncLatestVersion();
await setSettings({ release_synced_at: new Date().toISOString(), release_sync_error: markdown === null ? `${settings.release_notes_path} was not found on the default branch, so there are no notes.` : '' });
return { tags: tags.length, added, updated, removed: gone.length, latest };
} catch (e) {
await setSettings({ release_sync_error: `${new Date().toISOString()} ${e.message}`.slice(0, 500) });
throw e;
if (gone.length) {
await prisma.release.deleteMany({ where: { id: { in: gone } } });
removed += gone.length;
}
}
const latest = await syncLatestVersion();
await setSettings({ release_synced_at: new Date().toISOString(), release_sync_error: problems.join('\n').slice(0, 2000) });
return { sources: counts, added, updated, removed, latest, problems };
}
module.exports = { parseRepoUrl, parseNotes, plainNotes, syncReleases };
module.exports = { PLATFORM_REPO, parseRepoUrl, parseNotes, parseRequirements, plainNotes, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases };
+82 -13
View File
@@ -1,11 +1,17 @@
/**
* Cross Events releases and their notes (Releases page). The highest version is the latest one,
* kept in the latest_version setting so alerts and the install API read it as before.
* Releases per product (Hub 2.0) and their notes (Releases page). The highest version of a product
* is its latest. `latest_version` keeps the Cross Events latest for older code paths and the
* Settings page.
*
* Requirements: a release can need a minimum version of a sibling product (`requires`, from
* "— requires accounts 1.2.0" in WHATS-NEW.md). An install can't ask for an update until the
* church's install of each required product runs that version or later.
*/
const prisma = require('../config/db');
const { compareVersions } = require('./alerts');
const { setSettings } = require('./settings');
const { PRODUCT_NAMES } = require('./products');
const VERSION_RE = /^\d+\.\d+\.\d+$/;
const MAX_SENT = 20;
@@ -15,27 +21,90 @@ function sortReleases(releases) {
return [...releases].sort((a, b) => compareVersions(b.version, a.version));
}
const requirementsOf = r => (Array.isArray(r.requires) ? r.requires.filter(q => q && q.product && VERSION_RE.test(q.version)) : []);
/**
* What an install on `version` is told (§3): every release newer than it, newest first — at most
* 20, so a long-neglected install still gets a reply of sensible size.
* 20, so a long-neglected install still gets a reply of sensible size. `withRequires` (protocol v2)
* adds each release's requirements (contracts 1.1.0); v1 replies stay as they were.
*/
function releasesFor(releases, version) {
function releasesFor(releases, version, { withRequires = false } = {}) {
return sortReleases(releases)
.filter(r => !version || compareVersions(r.version, version) > 0)
.slice(0, MAX_SENT)
.map(r => ({ version: r.version, releasedAt: new Date(r.releasedAt).toISOString(), urgent: !!r.urgent, notes: r.notes || '' }));
.map(r => {
const out = { version: r.version, releasedAt: new Date(r.releasedAt).toISOString(), urgent: !!r.urgent, notes: r.notes || '' };
const requires = requirementsOf(r);
return withRequires && requires.length ? { ...out, requires } : out;
});
}
/** Point latest_version at the highest release (blank when there are none). */
async function syncLatestVersion() {
const releases = await prisma.release.findMany({ select: { version: true } });
const latest = sortReleases(releases)[0]?.version || '';
await setSettings({ latest_version: latest });
/** { events: '2.1.1', website: '1.0.0', … } — the highest release of each product that has any. */
function latestByProduct(releases) {
const out = {};
for (const r of releases) {
const p = r.product || 'events';
if (!out[p] || compareVersions(r.version, out[p]) > 0) out[p] = r.version;
}
return out;
}
async function latestVersions(db = prisma) {
return latestByProduct(await db.release.findMany({ select: { product: true, version: true } }));
}
/** Keep latest_version on the Cross Events latest (blank when there are none). Returns the map. */
async function syncLatestVersion(db = prisma) {
const latest = await latestVersions(db);
await setSettings({ latest_version: latest.events || '' });
return latest;
}
async function releasesForInstall(version) {
return releasesFor(await prisma.release.findMany(), version);
async function releasesForInstall(product, version, options = {}, db = prisma) {
return releasesFor(await db.release.findMany({ where: { product } }), version, options);
}
module.exports = { VERSION_RE, sortReleases, releasesFor, releasesForInstall, syncLatestVersion };
/**
* What updating `install` from its version to `target` needs from its siblings: the highest
* required version per product over every release it would get (so a requirement in a skipped
* release still counts). `siblings` are the church's other installs in use: [{ product, version }].
* Returns [{ product, version, current }] for the ones not met (current: null = not installed).
*/
function unmetRequirements({ releases, from, target, siblings }) {
const needed = {};
for (const r of releases) {
if (from && compareVersions(r.version, from) <= 0) continue;
if (compareVersions(r.version, target) > 0) continue;
for (const q of requirementsOf(r)) {
if (!needed[q.product] || compareVersions(q.version, needed[q.product]) > 0) needed[q.product] = q.version;
}
}
const out = [];
for (const [product, version] of Object.entries(needed)) {
const running = siblings.filter(s => s.product === product && s.version).map(s => s.version).sort((a, b) => compareVersions(b, a))[0] || null;
if (!running || compareVersions(running, version) < 0) out.push({ product, version, current: running });
}
return out;
}
/** "Accounts must be updated to 1.2.0 first (it runs 1.1.0)." for each unmet requirement. */
function requirementMessage(unmet) {
return unmet.map(u => (u.current
? `${PRODUCT_NAMES[u.product] || u.product} must be updated to ${u.version} first (it runs ${u.current}).`
: `${PRODUCT_NAMES[u.product] || u.product} ${u.version} or later must be installed first.`)).join(' ');
}
/** The requirements `install` hasn't met for updating to `target` (database version). */
async function unmetRequirementsFor(install, target, db = prisma) {
if (!target) return [];
const [releases, siblings] = await Promise.all([
db.release.findMany({ where: { product: install.product } }),
db.install.findMany({ where: { customerId: install.customerId, id: { not: install.id }, releasedAt: null }, select: { product: true, version: true } }),
]);
return unmetRequirements({ releases, from: install.version, target, siblings });
}
module.exports = {
VERSION_RE, sortReleases, releasesFor, releasesForInstall, latestByProduct, latestVersions, syncLatestVersion,
unmetRequirements, unmetRequirementsFor, requirementMessage,
};
+4 -1
View File
@@ -18,7 +18,10 @@ const DEFAULTS = {
smtp_user: '',
smtp_pass: '',
smtp_from: '',
// Releases and their notes are read from git (utils/releaseSync.js) when a repo is set.
// Releases and their notes are read from git (utils/releaseSync.js). Hub 2.0: release_sources
// is the list of sources per product (JSON, Releases page); blank = the defaults, which include
// release_repo_url (Cross Events before the monorepo, v1.2.3 tags) and release_notes_path.
release_sources: '',
release_repo_url: 'https://c-git.crosscode.co.za/joshua/hope-events',
release_notes_path: 'WHATS-NEW.md',
release_repo_token: '',
+1 -1
View File
@@ -67,7 +67,7 @@ function verifyCode(secret, code, now = Date.now()) {
}
/** The otpauth:// link an authenticator app scans (as a QR code). */
function otpauthUrl(secret, account, issuer = 'Cross Events Hub') {
function otpauthUrl(secret, account, issuer = 'Cross Code Hub') {
return `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
}
+24 -3
View File
@@ -2,14 +2,18 @@
// mocked Claude.
const mockRows = [];
const mockState = { licence: null };
const mockState = { licence: null, installs: [{ id: 'inst_1' }] };
const mockDb = {
licence: { findUnique: jest.fn(async () => mockState.licence) },
// Hub 2.0: the cap and markup are the church's (kept on mockState.licence here for the tests), and
// its installs share the cap.
customer: { findUnique: jest.fn(async () => ({ aiMonthlyCapCents: mockState.licence.aiMonthlyCapCents, aiMarkupPercent: mockState.licence.aiMarkupPercent })) },
install: { findMany: jest.fn(async () => mockState.installs) },
aiUsage: {
aggregate: jest.fn(async ({ where }) => {
const cutoff = where.OR[1].createdAt.gt;
const sum = mockRows
.filter(r => r.installId === where.installId && r.month === where.month)
.filter(r => where.installId.in.includes(r.installId) && r.month === where.month)
.filter(r => r.status !== 'reserved' || r.createdAt > cutoff)
.reduce((n, r) => n + r.chargedMillicents, 0);
return { _sum: { chargedMillicents: sum } };
@@ -37,7 +41,7 @@ jest.mock('@anthropic-ai/sdk', () => {
const ai = require('../src/utils/ai');
const install = { id: 'inst_1', licenceId: 'lic_1' };
const install = { id: 'inst_1', licenceId: 'lic_1', customerId: 'c1' };
const price = { model: 'claude-haiku-5-5', inUsd: 0.1, outUsd: 0.5, cacheReadUsd: 0.01, usdZar: 20, markup: 40 };
const body = { protocolVersion: 1, helper: 'draft_message', system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 1000 };
const reply = (usage, extra = {}) => ({ model: 'claude-haiku-5-5', stop_reason: 'end_turn', content: [{ type: 'text', text: 'Hi all!' }], usage, ...extra });
@@ -45,6 +49,7 @@ const reply = (usage, extra = {}) => ({ model: 'claude-haiku-5-5', stop_reason:
beforeEach(() => {
mockRows.length = 0;
mockState.licence = { id: 'lic_1', status: 'active', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 5000, aiMarkupPercent: null };
mockState.installs = [{ id: 'inst_1' }];
mockCreate.mockReset();
});
@@ -201,3 +206,19 @@ describe('complete', () => {
expect(mockCreate).not.toHaveBeenCalled();
});
});
describe('the cap is the church\'s (Hub 2.0)', () => {
test('what its other installs used this month counts against it', async () => {
mockState.installs = [{ id: 'inst_1' }, { id: 'inst_website' }];
mockRows.push({ id: 'w1', installId: 'inst_website', month: ai.monthOf(), status: 'done', chargedMillicents: 4999 * 1000, createdAt: new Date() });
const status = await ai.statusFor(install);
expect(status).toMatchObject({ enabled: true, capReached: true, usedCents: 4999 });
await expect(ai.complete(install, body)).rejects.toMatchObject({ code: 'AI_CAP_REACHED' });
expect(mockCreate).not.toHaveBeenCalled();
});
test('another church\'s use doesn\'t count', async () => {
mockRows.push({ id: 'o1', installId: 'inst_other_church', month: ai.monthOf(), status: 'done', chargedMillicents: 4999 * 1000, createdAt: new Date() });
expect((await ai.statusFor(install)).usedCents).toBe(0);
});
});
+232 -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([]);
});
});
@@ -199,3 +347,47 @@ describe('payments and statements', () => {
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);
});
});
describe('monthly recurring revenue (dashboard)', () => {
const { monthlyRecurringCents } = require('../src/utils/billing/compute');
const now = new Date('2026-11-20T10:00:00Z');
test('a full month of each product charged now, after founding and bundle, plus add-ons', () => {
// Founding: 360 + 64 = R424, less 15% = R360.40, plus a Cross Code address R10.
expect(monthlyRecurringCents(customer({ founding: true, addressType: 'crosscode' }), [events(), website(), accounts()], now)).toBe(37040);
});
test('days owed from before a period aren\'t recurring; a product not charged yet doesn\'t count', () => {
expect(monthlyRecurringCents(customer(), [events(), app({ billedFrom: day('2026-11-10'), billedUntil: null })], now)).toBe(Math.round((55000 + 9900) * 0.85));
expect(monthlyRecurringCents(customer(), [events(), app({ billedFrom: day('2026-12-15'), billedUntil: null })], now)).toBe(55000);
});
test('yearly is a twelfth of the year\'s invoice; not billed is 0', () => {
expect(monthlyRecurringCents(customer({ billingCycle: 'yearly' }), [events()], now)).toBe(Math.round((55000 * 10) / 12));
expect(monthlyRecurringCents(customer({ billingCycle: 'none' }), [events()], now)).toBe(0);
});
});
+172
View File
@@ -0,0 +1,172 @@
// Hub 2.0 step 1: products, licence keys per product, one open licence per product per customer
// (with the partial unique index simulated), the free Accounts licence, and protocol v1
// registering Events licences only. In-memory database.
const mockLicences = [];
const mockInstalls = [];
const isOpen = l => l.status !== 'revoked';
const mockDb = {
licence: {
findFirst: jest.fn(async ({ where }) => mockLicences.find(l => l.customerId === where.customerId && l.product === where.product && (!where.status?.not || l.status !== where.status.not)) || null),
findUnique: jest.fn(async ({ where, include }) => {
const l = mockLicences.find(x => (where.key ? x.key === where.key : x.id === where.id));
if (!l) return null;
return include ? { ...l, install: mockInstalls.find(i => i.licenceId === l.id) || null, customer: { id: l.customerId, name: 'Hope Church' } } : l;
}),
create: jest.fn(async ({ data }) => {
// The unique key and the partial unique index on (customerId, product) WHERE status <> 'revoked'.
if (mockLicences.some(l => l.key === data.key)) throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
const status = data.status || 'active';
if (status !== 'revoked' && mockLicences.some(l => isOpen(l) && l.customerId === data.customerId && l.product === data.product)) {
throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
}
const row = { id: `lic_${mockLicences.length + 1}`, status, plan: 'standard', createdAt: new Date(), ...data };
mockLicences.push(row);
return row;
}),
},
install: {
create: jest.fn(async ({ data }) => { const row = { id: `inst_${mockInstalls.length + 1}`, ...data }; mockInstalls.push(row); return row; }),
update: jest.fn(),
},
installEvent: { create: jest.fn(async () => ({})) },
};
jest.mock('../src/config/db', () => mockDb);
jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => ({ latest_version: '2.1.1' })) }));
jest.mock('../src/utils/releases', () => ({ releasesForInstall: jest.fn(async () => []), latestVersions: jest.fn(async () => ({ events: '2.1.1' })) }));
jest.mock('../src/utils/notices', () => ({ noticesForInstall: jest.fn(async () => []) }));
jest.mock('../src/utils/licenceToken', () => ({ sign: jest.fn(() => 'hel1.token.sig'), buildPayload: jest.fn(() => ({})) }));
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123';
const express = require('express');
const { licenceKey } = require('../src/utils/crypto');
const { PRODUCTS, KEY_PREFIXES, productOfKey } = require('../src/utils/products');
const { generateLicence, createLicence, checkReopen } = require('../src/utils/licences');
const { productSchema } = require('@crosscode/contracts');
beforeEach(() => { mockLicences.length = 0; mockInstalls.length = 0; });
describe('products', () => {
test('the Hub has the same products as the contracts', () => {
expect([...PRODUCTS].sort()).toEqual([...productSchema.options].sort());
});
test.each(PRODUCTS)('%s keys have their own prefix and are recognised', product => {
const key = licenceKey(product);
expect(key).toMatch(new RegExp(`^${KEY_PREFIXES[product]}(-[ACDEFGHJKMNPQRTUVWXY234679]{4}){4}$`));
expect(productOfKey(key)).toBe(product);
});
test('Events keys keep CEH-, and the default is Events', () => {
expect(licenceKey()).toMatch(/^CEH-/);
expect(() => licenceKey('nope')).toThrow();
});
});
describe('licences', () => {
test('the first product licence comes with a free Accounts licence', async () => {
const { licence, accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'website', data: { status: 'active' } });
expect(licence).toMatchObject({ product: 'website', key: expect.stringMatching(/^CCW-/) });
expect(accounts).toMatchObject({ product: 'accounts', plan: 'included', key: expect.stringMatching(/^CCA-/) });
});
test('a later product licence does not make a second Accounts licence', async () => {
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
const { accounts } = await generateLicence(mockDb, { customerId: 'c1', product: 'app', data: {} });
expect(accounts).toBeNull();
expect(mockLicences.filter(l => l.product === 'accounts')).toHaveLength(1);
});
test('a second open licence for the same product is refused', async () => {
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
await expect(generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} })).rejects.toMatchObject({ status: 409, code: 'PRODUCT_LICENCE_EXISTS' });
});
test('another customer can have the same product', async () => {
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
await expect(generateLicence(mockDb, { customerId: 'c2', product: 'events', data: {} })).resolves.toBeTruthy();
});
test('a revoked licence can be replaced', async () => {
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
licence.status = 'revoked';
await expect(generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} })).resolves.toBeTruthy();
});
test('a race is caught by the unique index', async () => {
// Both requests pass the check before either inserts: the second insert hits the index.
mockDb.licence.findFirst.mockResolvedValueOnce(null);
await createLicence(mockDb, { customerId: 'c1', product: 'app', data: {} });
mockDb.licence.findFirst.mockResolvedValueOnce(null);
await expect(createLicence(mockDb, { customerId: 'c1', product: 'app', data: {} })).rejects.toMatchObject({ code: 'PRODUCT_LICENCE_EXISTS' });
});
test('un-revoking is refused when the product has another open licence', async () => {
const { licence: old } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
old.status = 'revoked';
await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
await expect(checkReopen(mockDb, old, 'active')).rejects.toMatchObject({ code: 'PRODUCT_LICENCE_EXISTS' });
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 });
});
});
describe('register (protocol v1)', () => {
let server;
let base;
beforeAll(async () => {
const app = express();
app.use(express.json());
app.use('/api', require('../src/routes/installApi'));
await new Promise(resolve => { server = app.listen(0, '127.0.0.1', resolve); });
base = `http://127.0.0.1:${server.address().port}/api`;
});
afterAll(() => new Promise(resolve => server.close(resolve)));
const register = key => fetch(`${base}/installs/register`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ protocolVersion: 1, licenceKey: key, install: { name: 'Hope Church', url: 'https://events.hope.test', version: '2.1.1' } }),
});
test('an Events licence registers, and the install is an Events install', async () => {
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'events', data: {} });
const res = await register(licence.key);
expect(res.status).toBe(201);
expect(mockInstalls[0]).toMatchObject({ product: 'events', licenceId: licence.id });
});
test('another product\'s licence is refused with WRONG_PRODUCT', async () => {
const { licence } = await generateLicence(mockDb, { customerId: 'c1', product: 'website', data: {} });
const res = await register(licence.key);
expect(res.status).toBe(409);
expect(await res.json()).toMatchObject({ code: 'WRONG_PRODUCT' });
expect(mockInstalls).toHaveLength(0);
});
});
+291
View File
@@ -0,0 +1,291 @@
// Hub 2.0 step 2: protocol v2 next to v1. The contract samples (@crosscode/contracts/samples) go
// through the real install API with signed requests, and every v2 reply is checked against the
// contract's response schema. In-memory database.
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const mockC1 = '0b8f3c2a-5d4e-4f6a-9b7c-1d2e3f4a5b6c';
const mockC2 = '1c9a4d3b-6e5f-4a7b-8c8d-2e3f4a5b6c7d';
const mockL_EVENTS = '2d0b5e4c-7f6a-4b8c-9d9e-3f4a5b6c7d8e';
const mockL_WEBSITE = '3e1c6f5d-8a7b-4c9d-8eaf-4a5b6c7d8e9f';
const mockL_OTHER = '4f2d7a6e-9b8c-4dae-9fb0-5b6c7d8e9fa0';
const mockDb = (() => {
const t = { licences: [], installs: [], events: [], heartbeats: [], releases: [] };
const id = p => `${p}_${crypto.randomUUID()}`;
const customers = { [mockC1]: { id: mockC1, name: 'Hope Family Church' }, [mockC2]: { id: mockC2, name: 'Grace Church' } };
const withLicence = l => l && { ...l, install: t.installs.find(i => i.licenceId === l.id) || null, customer: customers[l.customerId] };
return {
t,
licence: {
findUnique: jest.fn(async ({ where }) => withLicence(t.licences.find(l => (where.key ? l.key === where.key : l.id === where.id)))),
},
install: {
findUnique: jest.fn(async ({ where }) => t.installs.find(i => i.id === where.id) || null),
create: jest.fn(async ({ data }) => { const row = { id: crypto.randomUUID(), registeredAt: new Date(Date.now() + t.installs.length), releasedAt: null, ...data }; t.installs.push(row); return row; }),
update: jest.fn(async ({ where, data }) => Object.assign(t.installs.find(i => i.id === where.id), Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined)))),
findMany: jest.fn(async ({ where, select }) => t.installs
.filter(i => i.customerId === where.customerId && i.id !== where.id.not && i.releasedAt === null)
.filter(i => !where.publicKey || i.publicKey != null)
.filter(i => !where.licence || t.licences.find(l => l.id === i.licenceId)?.status !== 'revoked')
.sort((a, b) => a.registeredAt - b.registeredAt)
.map(i => Object.fromEntries(Object.keys(select).map(k => [k, i[k]])))),
},
installEvent: {
create: jest.fn(async ({ data }) => { const row = { id: id('ev'), createdAt: new Date(), ...data }; t.events.push(row); return row; }),
updateMany: jest.fn(async () => ({ count: 0 })),
findFirst: jest.fn(async () => null),
findMany: jest.fn(async () => []),
},
heartbeat: { create: jest.fn(async ({ data }) => { t.heartbeats.push(data); return data; }) },
release: { findMany: jest.fn(async ({ where } = {}) => t.releases.filter(r => !where?.product || r.product === where.product)) },
customer: { findUnique: jest.fn(async ({ where }) => customers[where.id]) },
$transaction: jest.fn(async ops => Promise.all(ops)),
};
})();
jest.mock('../src/config/db', () => mockDb);
// Every test registers: the hourly register limit would cut in part-way through the file.
jest.mock('express-rate-limit', () => () => (req, res, next) => next());
jest.mock('../src/utils/settings', () => ({ getSettings: jest.fn(async () => ({})), setSettings: jest.fn(async () => ({})) }));
jest.mock('../src/utils/notices', () => ({ noticesForInstall: jest.fn(async () => []) }));
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123';
const hubKey = crypto.generateKeyPairSync('ed25519');
process.env.HUB_SIGNING_KEY = hubKey.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
const express = require('express');
const { hub } = require('@crosscode/contracts');
const licenceToken = require('../src/utils/licenceToken');
const { signature } = require('../src/utils/signing');
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
const sample = name => JSON.parse(fs.readFileSync(path.join(SAMPLES, name), 'utf8'));
const pem = () => crypto.generateKeyPairSync('ed25519').publicKey.export({ type: 'spki', format: 'pem' }).toString();
const KEYS = { events: 'CEH-7K2M-9QXA-P4RT-WD8C', website: 'CCW-AC3D-E4FG-H6JK-M7NP', events2: 'CEH-QRTU-VWXY-2346-79AC' };
let server;
let base;
beforeAll(async () => {
const app = express();
app.use(express.json({ verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } }));
app.use('/api', require('../src/routes/installApi'));
await new Promise(resolve => { server = app.listen(0, '127.0.0.1', resolve); });
base = `http://127.0.0.1:${server.address().port}/api`;
});
afterAll(() => new Promise(resolve => server.close(resolve)));
beforeEach(() => {
const { t } = mockDb;
t.installs.length = 0; t.events.length = 0; t.heartbeats.length = 0;
t.releases.splice(0, t.releases.length,
{ product: 'events', version: '2.4.0', releasedAt: new Date('2026-11-20T08:00:00Z'), urgent: false, notes: '- Event feed', requires: [] },
{ product: 'events', version: '3.0.0', releasedAt: new Date('2026-12-01T08:00:00Z'), urgent: false, notes: '- Sign in with your church account', requires: [{ product: 'accounts', version: '1.2.0' }] },
{ product: 'website', version: '1.0.0', releasedAt: new Date('2026-11-25T08:00:00Z'), urgent: false, notes: '- First release', requires: [] },
{ product: 'website', version: '1.1.0', releasedAt: new Date('2026-12-05T08:00:00Z'), urgent: false, notes: '- Sermon series', requires: [] },
);
t.licences.splice(0, t.licences.length,
{ id: mockL_EVENTS, customerId: mockC1, product: 'events', key: KEYS.events, status: 'active', plan: 'Grow', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 0 },
{ id: mockL_WEBSITE, customerId: mockC1, product: 'website', key: KEYS.website, status: 'active', plan: 'Website', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 0 },
{ id: mockL_OTHER, customerId: mockC2, product: 'events', key: KEYS.events2, status: 'active', plan: 'Seed', expiresAt: null, graceDays: 14, aiMonthlyCapCents: 0 },
);
});
const post = (url, body, headers = {}) => fetch(`${base}${url}`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: typeof body === 'string' ? body : JSON.stringify(body) });
/** A signed request from an install (§3). */
function signed(url, reg, body) {
const raw = JSON.stringify(body);
const timestamp = new Date().toISOString();
return post(url, raw, { 'X-Hub-Install': reg.installId, 'X-Hub-Timestamp': timestamp, 'X-Hub-Signature': signature(reg.installSecret, timestamp, raw) });
}
const eventsRegistration = () => sample('hub-register-request.json');
const websiteRegistration = () => {
const r = sample('hub-register-request.json');
return { ...r, licenceKey: KEYS.website, product: 'website', install: { ...r.install, url: 'https://www.hopefamily.co.za', version: '1.0.0', features: {}, publicKey: pem() } };
};
async function register(body) {
const res = await post('/installs/register', body);
return { status: res.status, json: await res.json() };
}
describe('register', () => {
test('the v2 sample registers, and the reply fits the contract', async () => {
const { status, json } = await register(eventsRegistration());
expect(status).toBe(201);
expect(hub.registerResponseSchema.safeParse(json).error?.issues ?? []).toEqual([]);
expect(json.linkedProducts).toEqual([]);
expect(mockDb.t.installs[0]).toMatchObject({ product: 'events', protocolVersion: 2, publicKey: expect.stringContaining('BEGIN PUBLIC KEY') });
});
test('the licence token carries the customer and product, and fits the contract', async () => {
const { json } = await register(eventsRegistration());
const payload = licenceToken.verify(json.licence, hubKey.publicKey);
expect(hub.licencePayloadSchema.safeParse(payload).error?.issues ?? []).toEqual([]);
expect(payload).toMatchObject({ customerId: mockC1, product: 'events', installId: json.installId });
});
test('a second product lists the first in linkedProducts (and nothing more)', async () => {
const events = await register(eventsRegistration());
const { status, json } = await register(websiteRegistration());
expect(status).toBe(201);
expect(json.linkedProducts).toEqual([{ product: 'events', installId: events.json.installId, url: 'https://events.hopefamily.co.za', publicKey: eventsRegistration().install.publicKey }]);
});
test('another church\'s installs are never listed', async () => {
await register({ ...eventsRegistration(), licenceKey: KEYS.events2, install: { ...eventsRegistration().install, url: 'https://events.grace.test' } });
const { json } = await register(eventsRegistration());
expect(json.linkedProducts).toEqual([]);
});
test('a product that doesn\'t match the licence is refused', async () => {
const { status, json } = await register({ ...websiteRegistration(), product: 'events' });
expect(status).toBe(409);
expect(json.code).toBe('WRONG_PRODUCT');
});
test('a key typed in lower case with spaces still registers', async () => {
const { status } = await register({ ...eventsRegistration(), licenceKey: ' ceh-7k2m-9qxa-p4rt-wd8c ' });
expect(status).toBe(201);
});
test('a v2 body that breaks the contract is refused with what is wrong', async () => {
const body = eventsRegistration();
delete body.install.publicKey;
const { status, json } = await register(body);
expect(status).toBe(400);
expect(json).toMatchObject({ code: 'INVALID_REQUEST', message: expect.stringContaining('install.publicKey') });
});
test('v1 registers as before: Events, no linkedProducts, no public key', async () => {
await register(websiteRegistration());
const r = eventsRegistration();
const { status, json } = await register({ protocolVersion: 1, licenceKey: r.licenceKey, install: { name: r.install.name, url: r.install.url, version: '2.1.1' } });
expect(status).toBe(201);
expect(json).not.toHaveProperty('linkedProducts');
expect(mockDb.t.installs.find(i => i.product === 'events')).toMatchObject({ protocolVersion: 1, publicKey: undefined });
});
test('protocol 3 is refused', async () => {
const { status, json } = await register({ ...eventsRegistration(), protocolVersion: 3 });
expect(status).toBe(400);
expect(json.code).toBe('UNSUPPORTED_PROTOCOL');
});
});
describe('heartbeat', () => {
test.each([
['events', eventsRegistration, 'hub-heartbeat-events.json'],
['website', websiteRegistration, 'hub-heartbeat-website.json'],
])('the %s sample is recorded, and the reply fits the contract', async (product, registration, file) => {
const { json: reg } = await register(registration());
const res = await signed('/installs/heartbeat', reg, sample(file));
const json = await res.json();
expect(res.status).toBe(200);
expect(hub.heartbeatResponseSchema.safeParse(json).error?.issues ?? []).toEqual([]);
expect(mockDb.t.installs.find(i => i.id === reg.installId).stats).toEqual(sample(file).stats);
});
test('linkedProducts in the heartbeat reply', async () => {
const { json: events } = await register(eventsRegistration());
const { json: website } = await register(websiteRegistration());
const json = await (await signed('/installs/heartbeat', events, sample('hub-heartbeat-events.json'))).json();
expect(json.linkedProducts.map(l => [l.product, l.installId])).toEqual([['website', website.installId]]);
});
test('each product is told its own releases', async () => {
const { json: website } = await register(websiteRegistration());
expect(website.latestVersion).toBe('1.1.0');
expect(website.releases.map(r => r.version)).toEqual(['1.1.0']);
const { json: events } = await register(eventsRegistration());
expect(events.latestVersion).toBe('3.0.0');
expect(events.releases.map(r => r.version)).toEqual(['3.0.0', '2.4.0']);
});
test('v2 replies carry requirements; v1 replies are as before', async () => {
const { json: v2 } = await register(eventsRegistration());
expect(v2.releases[0].requires).toEqual([{ product: 'accounts', version: '1.2.0' }]);
expect(v2.releases[1]).not.toHaveProperty('requires');
const r = eventsRegistration();
const { json: v1 } = await register({ protocolVersion: 1, licenceKey: r.licenceKey, install: { name: r.install.name, url: r.install.url, version: '2.1.1' } });
expect(v1.releases.every(x => !('requires' in x))).toBe(true);
});
test('a heartbeat for another product is refused', async () => {
const { json: reg } = await register(eventsRegistration());
const res = await signed('/installs/heartbeat', reg, sample('hub-heartbeat-website.json'));
expect(res.status).toBe(409);
expect((await res.json()).code).toBe('WRONG_PRODUCT');
});
test('a v2 heartbeat that breaks the contract is refused', async () => {
const { json: reg } = await register(eventsRegistration());
const body = sample('hub-heartbeat-events.json');
delete body.health;
const res = await signed('/installs/heartbeat', reg, body);
expect(res.status).toBe(400);
expect((await res.json()).code).toBe('INVALID_REQUEST');
});
test('a v1 heartbeat is answered as before (no linkedProducts)', async () => {
const r = eventsRegistration();
const { json: reg } = await register({ protocolVersion: 1, licenceKey: r.licenceKey, install: { name: r.install.name, url: r.install.url, version: '2.1.1' } });
const res = await signed('/installs/heartbeat', reg, { protocolVersion: 1, version: '2.1.1', health: { db: true }, stats: { users: 3 } });
const json = await res.json();
expect(res.status).toBe(200);
expect(Object.keys(json).sort()).toEqual(['latestVersion', 'licence', 'notices', 'releases', 'serverTime']);
});
test('an unsigned heartbeat is refused', async () => {
const { json: reg } = await register(eventsRegistration());
const res = await post('/installs/heartbeat', sample('hub-heartbeat-events.json'), { 'X-Hub-Install': reg.installId, 'X-Hub-Timestamp': new Date().toISOString(), 'X-Hub-Signature': 'nope' });
expect(res.status).toBe(401);
});
});
describe('update requests (v2)', () => {
test('a v2 request without its version is refused', async () => {
const { json: reg } = await register(eventsRegistration());
const res = await signed('/installs/update-request', reg, { protocolVersion: 2 });
expect(res.status).toBe(400);
expect((await res.json()).code).toBe('INVALID_REQUEST');
});
test('an update that needs Accounts first is refused until Accounts is new enough', async () => {
const { json: reg } = await register(eventsRegistration());
let res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' });
let json = await res.json();
expect(res.status).toBe(409);
expect(json).toMatchObject({ code: 'REQUIREMENT_NOT_MET', requirements: [{ product: 'accounts', version: '1.2.0', current: null }] });
expect(json.message).toContain('Accounts 1.2.0 or later must be installed first');
// The church's Accounts install, on 1.1.0: still refused, and the message says what it runs.
mockDb.t.installs.push({ id: crypto.randomUUID(), customerId: mockC1, product: 'accounts', version: '1.1.0', releasedAt: null, registeredAt: new Date() });
json = await (await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' })).json();
expect(json.message).toContain('Accounts must be updated to 1.2.0 first (it runs 1.1.0)');
// On 1.2.0: the request goes through, and fits the contract.
mockDb.t.installs.find(i => i.product === 'accounts').version = '1.2.0';
res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' });
json = await res.json();
expect(res.status).toBe(201);
expect(json.version).toBe('3.0.0');
expect(hub.updateRequestResponseSchema.safeParse(json).error?.issues ?? []).toEqual([]);
});
test('another church\'s Accounts doesn\'t count', async () => {
mockDb.t.installs.push({ id: crypto.randomUUID(), customerId: mockC2, product: 'accounts', version: '9.0.0', releasedAt: null, registeredAt: new Date() });
const { json: reg } = await register(eventsRegistration());
const res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '2.3.0' });
expect(res.status).toBe(409);
});
test('a product with no requirements updates as before', async () => {
const { json: reg } = await register(websiteRegistration());
const res = await signed('/installs/update-request', reg, { protocolVersion: 2, version: '1.0.0' });
expect(res.status).toBe(201);
});
});
+210
View File
@@ -0,0 +1,210 @@
// Hub 2.0 step 3: releases per product from several git sources, requirements in the notes, and
// the rules that keep an unreachable source from wiping releases. Gitea is faked with a fetch
// stub; the database is in memory.
const mockReleases = [];
const mockSettings = { values: {} };
const mockDb = {
release: {
findMany: jest.fn(async ({ where, select } = {}) => {
const rows = mockReleases.filter(r => !where?.product || r.product === where.product);
return select ? rows.map(r => Object.fromEntries(Object.keys(select).map(k => [k, r[k]]))) : rows;
}),
create: jest.fn(async ({ data }) => { const row = { id: `r${mockReleases.length + 1}_${data.product}_${data.version}`, requires: [], ...data }; mockReleases.push(row); return row; }),
update: jest.fn(async ({ where, data }) => Object.assign(mockReleases.find(r => r.id === where.id), data)),
deleteMany: jest.fn(async ({ where }) => {
const ids = new Set(where.id.in);
for (let i = mockReleases.length - 1; i >= 0; i--) if (ids.has(mockReleases[i].id)) mockReleases.splice(i, 1);
return { count: ids.size };
}),
},
};
jest.mock('../src/config/db', () => mockDb);
jest.mock('../src/utils/settings', () => ({
getSettings: jest.fn(async () => ({ ...mockSettings.values })),
setSettings: jest.fn(async v => { Object.assign(mockSettings.values, v); return mockSettings.values; }),
releaseRepoToken: jest.fn(async () => ''),
}));
const { parseNotes, parseRequirements, tagPattern, defaultSources, cleanSources, releaseSources, syncReleases, PLATFORM_REPO } = require('../src/utils/releaseSync');
const { unmetRequirements, latestByProduct } = require('../src/utils/releases');
const LEGACY = 'https://c-git.crosscode.co.za/joshua/hope-events';
const api = repo => `https://c-git.crosscode.co.za/api/v1/repos/joshua/${repo}`;
/** A fake Gitea: { 'hope-events': { tags: [...], files: { 'WHATS-NEW.md': '...' } } }; a repo set to 'down' fails. */
let gitea;
global.fetch = jest.fn(async url => {
const m = /\/repos\/joshua\/([^/]+)\/(tags|raw\/(.+))/.exec(url);
const repo = m && gitea[m[1]];
if (repo === 'down') throw new Error('connect ECONNREFUSED');
if (!repo) return { ok: false, status: 404 };
if (m[2].startsWith('tags')) {
const page = Number(new URL(url).searchParams.get('page'));
return { ok: true, status: 200, json: async () => (page === 1 ? repo.tags.map(name => ({ name, commit: { created: '2026-11-01T10:00:00Z' } })) : []) };
}
const file = repo.files?.[decodeURIComponent(m[3])];
return file == null ? { ok: false, status: 404 } : { ok: true, status: 200, text: async () => file };
});
beforeEach(() => {
mockReleases.length = 0;
mockSettings.values = { release_repo_url: LEGACY, release_notes_path: 'WHATS-NEW.md' };
gitea = {
'hope-events': { tags: ['v2.0.0', 'v2.1.0', 'v2.1.1', 'not-a-version'], files: { 'WHATS-NEW.md': '## 2.1.1\n- Feedback in the background\n## 2.1.0\n- Feedback page' } },
'crosscode-platform': {
tags: ['contracts@1.0.0', 'contracts@1.1.0', 'events@2.2.0', 'events@3.0.0', 'accounts@1.2.0', 'website@1.0.0'],
files: {
'apps/events/WHATS-NEW.md': '## 3.0.0 — requires accounts 1.2.0\n- Sign in with your church account\n## 2.2.0\n- Moved into the monorepo',
'apps/accounts/WHATS-NEW.md': '## 1.2.0\n- Authenticator app',
'apps/website/WHATS-NEW.md': '## 1.0.0 — requires events 2.4.0\n- First release',
},
},
};
});
const versions = product => mockReleases.filter(r => r.product === product).map(r => r.version).sort();
describe('sources', () => {
test('the defaults: every product from the monorepo, plus Cross Events from the repo set before 2.0', () => {
expect(defaultSources(mockSettings.values)).toEqual([
{ product: 'events', repo: PLATFORM_REPO, tagPrefix: 'events@', notesPath: 'apps/events/WHATS-NEW.md' },
{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' },
{ product: 'accounts', repo: PLATFORM_REPO, tagPrefix: 'accounts@', notesPath: 'apps/accounts/WHATS-NEW.md' },
{ product: 'website', repo: PLATFORM_REPO, tagPrefix: 'website@', notesPath: 'apps/website/WHATS-NEW.md' },
{ product: 'app', repo: PLATFORM_REPO, tagPrefix: 'app@', notesPath: 'apps/app/WHATS-NEW.md' },
]);
});
test('a saved list replaces the defaults', () => {
const saved = [{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' }];
expect(releaseSources({ release_sources: JSON.stringify(saved) })).toEqual(saved);
});
test('bad sources are refused with what is wrong', () => {
expect(() => cleanSources([{ product: 'shop', repo: LEGACY }])).toThrow(/product/);
expect(() => cleanSources([{ product: 'events', repo: 'not a url' }])).toThrow(/repository/);
expect(() => cleanSources([{ product: 'events', repo: LEGACY, tagPrefix: 'a b' }])).toThrow(/prefix/);
expect(() => cleanSources([{ product: 'events', repo: LEGACY, notesPath: '../x' }])).toThrow(/notes/);
expect(() => cleanSources([{ product: 'events', repo: LEGACY, tagPrefix: 'v' }, { product: 'events', repo: `${LEGACY}.git`, tagPrefix: 'v' }])).toThrow(/twice/);
});
test('tag patterns: a prefix, and v (also bare versions, as before 2.0)', () => {
expect(tagPattern('events@').exec('events@2.2.0')[1]).toBe('2.2.0');
expect(tagPattern('events@').exec('website@2.2.0')).toBeNull();
expect(tagPattern('events@').exec('events@2.2.0-rc1')).toBeNull();
expect(tagPattern('v').exec('v2.1.1')[1]).toBe('2.1.1');
expect(tagPattern('v').exec('2.1.1')[1]).toBe('2.1.1');
});
});
describe('requirements in the notes', () => {
test('"— requires accounts 1.2.0, website v1.1.0 — urgent"', () => {
expect(parseNotes('## 3.0.0 — requires accounts 1.2.0, website v1.1.0 — urgent\n- x')['3.0.0']).toEqual({
notes: '- x', urgent: true, requires: [{ product: 'accounts', version: '1.2.0' }, { product: 'website', version: '1.1.0' }],
});
});
test('no "requires" means no requirements, even if a product is named', () => {
expect(parseRequirements(' — works with the website 1.0.0')).toEqual([]);
expect(parseNotes('## 2.4.0\n- x')['2.4.0'].requires).toEqual([]);
});
});
describe('sync', () => {
test('every product gets the tags of its sources, with notes and requirements', async () => {
const result = await syncReleases();
expect(versions('events')).toEqual(['2.0.0', '2.1.0', '2.1.1', '2.2.0', '3.0.0']);
expect(versions('accounts')).toEqual(['1.2.0']);
expect(versions('website')).toEqual(['1.0.0']);
expect(versions('app')).toEqual([]);
expect(mockReleases.find(r => r.product === 'events' && r.version === '3.0.0').requires).toEqual([{ product: 'accounts', version: '1.2.0' }]);
expect(mockReleases.find(r => r.product === 'events' && r.version === '2.1.1').notes).toBe('- Feedback in the background');
expect(result.latest).toEqual({ events: '3.0.0', accounts: '1.2.0', website: '1.0.0' });
expect(mockSettings.values.latest_version).toBe('3.0.0');
});
test('contracts@ tags are nobody\'s release', async () => {
await syncReleases();
expect(mockReleases.some(r => r.version === '1.1.0')).toBe(false);
});
test('a removed tag removes its release', async () => {
await syncReleases();
gitea['hope-events'].tags = ['v2.1.0', 'v2.1.1'];
const result = await syncReleases();
expect(versions('events')).toEqual(['2.1.0', '2.1.1', '2.2.0', '3.0.0']);
expect(result.removed).toBe(1);
});
test('a source that can\'t be reached keeps its product\'s releases', async () => {
await syncReleases();
gitea['hope-events'] = 'down';
const result = await syncReleases();
expect(versions('events')).toEqual(['2.0.0', '2.1.0', '2.1.1', '2.2.0', '3.0.0']);
expect(result.problems.join(' ')).toMatch(/hope-events.*ECONNREFUSED/);
// The other products still sync.
gitea['crosscode-platform'].tags.push('accounts@1.3.0');
await syncReleases();
expect(versions('accounts')).toEqual(['1.2.0', '1.3.0']);
});
test('a product whose sources have no tags any more keeps its releases (and says so)', async () => {
mockSettings.values.release_sources = JSON.stringify([{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' }]);
await syncReleases();
gitea['hope-events'].tags = [];
const result = await syncReleases();
expect(versions('events')).toEqual(['2.0.0', '2.1.0', '2.1.1']);
expect(result.problems.join(' ')).toMatch(/kept/);
});
test('when nothing can be read, the sync fails and changes nothing', async () => {
await syncReleases();
gitea['hope-events'] = 'down';
gitea['crosscode-platform'] = 'down';
await expect(syncReleases()).rejects.toThrow(/ECONNREFUSED/);
expect(versions('events')).toHaveLength(5);
});
test('a product with no source is left alone (managed by hand)', async () => {
mockReleases.push({ id: 'manual', product: 'app', version: '0.9.0', notes: '', urgent: false, requires: [], releasedAt: new Date() });
mockSettings.values.release_sources = JSON.stringify([{ product: 'events', repo: LEGACY, tagPrefix: 'v', notesPath: 'WHATS-NEW.md' }]);
await syncReleases();
expect(versions('app')).toEqual(['0.9.0']);
});
test('a requirement can\'t be on the product itself', async () => {
gitea['crosscode-platform'].files['apps/events/WHATS-NEW.md'] = '## 3.0.0 — requires events 2.9.0, accounts 1.2.0\n- x';
await syncReleases();
expect(mockReleases.find(r => r.product === 'events' && r.version === '3.0.0').requires).toEqual([{ product: 'accounts', version: '1.2.0' }]);
});
});
describe('unmet requirements', () => {
const releases = [
{ version: '2.4.0', requires: [] },
{ version: '2.5.0', requires: [{ product: 'accounts', version: '1.1.0' }] },
{ version: '3.0.0', requires: [{ product: 'accounts', version: '1.2.0' }, { product: 'website', version: '1.0.0' }] },
{ version: '3.1.0', requires: [{ product: 'accounts', version: '1.5.0' }] },
];
test('the highest requirement over every release up to the target counts', () => {
expect(unmetRequirements({ releases, from: '2.4.0', target: '3.0.0', siblings: [{ product: 'accounts', version: '1.1.0' }] })).toEqual([
{ product: 'accounts', version: '1.2.0', current: '1.1.0' },
{ product: 'website', version: '1.0.0', current: null },
]);
});
test('releases already installed, or beyond the target, don\'t count', () => {
expect(unmetRequirements({ releases, from: '2.5.0', target: '2.5.0', siblings: [] })).toEqual([]);
expect(unmetRequirements({ releases, from: '3.0.0', target: '3.1.0', siblings: [{ product: 'accounts', version: '1.5.0' }] })).toEqual([]);
});
test('met when the sibling runs that version or later', () => {
expect(unmetRequirements({ releases, from: '2.4.0', target: '3.0.0', siblings: [{ product: 'accounts', version: '1.2.1' }, { product: 'website', version: '1.0.0' }] })).toEqual([]);
});
test('latest per product', () => {
expect(latestByProduct([{ product: 'events', version: '2.10.0' }, { product: 'events', version: '2.9.0' }, { product: 'app', version: '1.0.0' }])).toEqual({ events: '2.10.0', app: '1.0.0' });
});
});
Binary file not shown.
+4 -2
View File
@@ -2,8 +2,10 @@
Cross Events Hub becomes **Cross Code Hub**: every product's customers, licences, stats, AI and
billing in one place (ROADMAP-v3 §5, phase 1, in `hope-events/docs/ROADMAP-v3.md`). Planned
2026-11-04. Each step is its own branch, merged into `main` with its tests when it's done; only the
finished set is tagged and deployed as **2.0.0** (as Cross Events 2.0 was built).
2026-11-04. Each step is its own branch (`feat/hub2-<step>`), merged with its tests into
**`release/2.0`** when it's done; `release/2.0` is merged into `main` and tagged **2.0.0** only when
every step is in (as Cross Events 2.0 was built). `main` stays at 1.7.x until then, so
`scripts/deploy.sh` (which deploys the latest `main` by default) never ships half of 2.0.
**Cross Events 2.1.x installs keep working unchanged:** protocol v1 replies stay identical. Events
moves to protocol v2 in Events 2.4.0.
@@ -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>
))}
+63 -30
View File
@@ -6,7 +6,8 @@ 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";
import { CustomerBilling } from "@/components/billing/CustomerBilling";
@@ -21,8 +22,6 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
plan: licence.plan,
expiresAt: dateInput(licence.expiresAt),
graceDays: String(licence.graceDays),
aiRand: String(licence.aiMonthlyCapCents / 100),
aiMarkup: licence.aiMarkupPercent == null ? "" : String(licence.aiMarkupPercent),
notes: licence.notes || "",
});
const [busy, setBusy] = useState(false);
@@ -39,8 +38,6 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
// End of the chosen day, South African time.
expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null,
graceDays: form.graceDays,
aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100),
aiMarkupPercent: form.aiMarkup.trim() === "" ? null : form.aiMarkup,
notes: form.notes,
},
});
@@ -62,6 +59,7 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
<div className="card space-y-3">
<div className="flex flex-wrap items-center gap-2">
<KeyRound className="h-4 w-4 text-slate-400" />
<span className="font-semibold">{PRODUCT_NAMES[licence.product]}</span>
<code className="text-sm font-semibold tracking-wide">{licence.key}</code>
<button className="text-xs text-indigo-600 hover:underline" onClick={() => navigator.clipboard?.writeText(licence.key)} aria-label="Copy key"><Copy className="inline h-3.5 w-3.5" /> Copy</button>
<span className="ml-auto"><Badge value={licence.status} /></span>
@@ -69,16 +67,24 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
<div className="text-sm text-slate-600">
{licence.install
? <>Used by <Link href={`/installs/${licence.install.id}`} className="text-indigo-600 hover:underline">{licence.install.url}</Link> · last heartbeat {ago(licence.install.lastHeartbeatAt)}</>
: "Not used yet — enter this key in the church's Cross Events setup (or Site settings → Licence)."}
: `Not used yet — enter this key in ${KEY_WHERE[licence.product]}.`}
</div>
<div className="grid gap-3 sm:grid-cols-6">
<div>
<label className="label" htmlFor={`plan-${licence.id}`}>Plan</label>
<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>
<p className="mt-1 text-xs text-slate-500">Shown on the church&apos;s Licence page. Billing and founding status are under Billing below.</p>
{licence.product === "accounts" ? (
<input id={`plan-${licence.id}`} className="input" value="Included" disabled />
) : (
<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"
? "Free: comes with the church's other products."
: "Shown on the church's Licence page. Billing and founding status are under Billing below."}
</p>
</div>
<div>
<label className="label">Status</label>
@@ -97,16 +103,6 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
<label className="label">Grace (days)</label>
<input type="number" min={0} max={90} className="input" value={form.graceDays} onChange={e => setForm({ ...form, graceDays: e.target.value })} />
</div>
<div>
<label className="label">AI cap (R / month)</label>
<input type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">0 = off (no AI buttons). Counted in charged rand.</p>
</div>
<div>
<label className="label" htmlFor={`markup-${licence.id}`}>AI markup (%)</label>
<input id={`markup-${licence.id}`} type="number" min={0} max={500} step="1" className="input" placeholder="Default" value={form.aiMarkup} onChange={e => setForm({ ...form, aiMarkup: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">Blank uses the default (Settings → AI).</p>
</div>
</div>
<div>
<label className="label">Notes</label>
@@ -124,23 +120,36 @@ function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved:
export default function CustomerPage() {
const { id } = useParams<{ id: string }>();
const [c, setC] = useState<Customer | null>(null);
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "" });
const [newLicence, setNewLicence] = useState({ expiresAt: "", graceDays: "14" });
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "", aiRand: "0", aiMarkup: "" });
const [newLicence, setNewLicence] = useState<{ product: Product | ""; expiresAt: string; graceDays: string }>({ product: "", expiresAt: "", graceDays: "14" });
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => api<Customer>(`/api/admin/customers/${id}`).then(x => {
setC(x);
setForm({ name: x.name, contactName: x.contactName || "", email: x.email || "", phone: x.phone || "", notes: x.notes || "" });
setForm({
name: x.name, contactName: x.contactName || "", email: x.email || "", phone: x.phone || "", notes: x.notes || "",
aiRand: String(x.aiMonthlyCapCents / 100), aiMarkup: x.aiMarkupPercent == null ? "" : String(x.aiMarkupPercent),
});
}).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => { load(); }, [load]);
if (!c) return msg ? <Message msg={msg} /> : <Loading />;
// One open (not revoked) licence per product; Accounts comes with the first other product.
const taken = new Set(c.licences.filter(l => l.status !== "revoked").map(l => l.product));
const available = PRODUCTS.filter(p => !taken.has(p));
const product: Product | undefined = newLicence.product && available.includes(newLicence.product) ? newLicence.product : available.find(p => p !== "accounts") || available[0];
const licences = [...c.licences].sort((a, b) => byProduct(a, b) || (a.status === "revoked" ? 1 : 0) - (b.status === "revoked" ? 1 : 0));
const saveDetails = async (e: React.FormEvent) => {
e.preventDefault();
try {
await api(`/api/admin/customers/${id}`, { method: "PUT", body: form });
setMsg({ type: "ok", text: "Saved." });
const { aiRand, aiMarkup, ...details } = form;
await api(`/api/admin/customers/${id}`, {
method: "PUT",
body: { ...details, aiMonthlyCapCents: Math.round((parseFloat(aiRand) || 0) * 100), aiMarkupPercent: aiMarkup.trim() === "" ? null : aiMarkup },
});
setMsg({ type: "ok", text: "Saved. The church's sites pick up an AI change with their next heartbeat (within 15 minutes)." });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
@@ -148,11 +157,15 @@ export default function CustomerPage() {
const generate = async (e: React.FormEvent) => {
e.preventDefault();
try {
const l = await api<Licence>(`/api/admin/customers/${id}/licences`, {
const l = await api<Licence & { accountsLicence: Licence | null }>(`/api/admin/customers/${id}/licences`, {
method: "POST",
body: { expiresAt: newLicence.expiresAt ? `${newLicence.expiresAt}T23:59:59+02:00` : null, graceDays: newLicence.graceDays },
body: { product, expiresAt: newLicence.expiresAt ? `${newLicence.expiresAt}T23:59:59+02:00` : null, graceDays: newLicence.graceDays },
});
setMsg({
type: "ok",
text: `${PRODUCT_NAMES[l.product]} licence ${l.key} created. Send it to the church for their setup.`
+ (l.accountsLicence ? ` Their Accounts licence (free) was created too: ${l.accountsLicence.key}.` : ""),
});
setMsg({ type: "ok", text: `Licence ${l.key} created. Send it to the church for their setup.` });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
@@ -171,17 +184,37 @@ export default function CustomerPage() {
<div><label className="label">Email</label><input type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
<div><label className="label">Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div><label className="label">Notes</label><textarea className="input" rows={4} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Plan, billing, anything worth remembering" /></div>
<div className="grid gap-3 sm:grid-cols-2">
<div>
<label className="label" htmlFor="ai-cap">AI cap (R / month)</label>
<input id="ai-cap" type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
</div>
<div>
<label className="label" htmlFor="ai-markup">AI markup (%)</label>
<input id="ai-markup" type="number" min={0} max={500} step="1" className="input" placeholder="Default" value={form.aiMarkup} onChange={e => setForm({ ...form, aiMarkup: e.target.value })} />
</div>
</div>
<p className="text-xs text-slate-500">The AI allowance is the church&apos;s, shared by all its sites: 0 = off (no AI buttons). Counted in charged rand. A blank markup uses the default (Settings → AI).</p>
<button className="btn-secondary">Save details</button>
</form>
<div className="space-y-4">
<h2 className="font-semibold">Licences</h2>
{c.licences.map(l => <LicenceCard key={`${l.id}-${l.status}-${l.expiresAt}`} licence={l} onSaved={load} setMsg={setMsg} />)}
{licences.map(l => <LicenceCard key={`${l.id}-${l.status}-${l.expiresAt}`} licence={l} onSaved={load} setMsg={setMsg} />)}
{product ? (
<form onSubmit={generate} className="card flex flex-wrap items-end gap-3">
<div>
<label className="label" htmlFor="new-product">Product</label>
<select id="new-product" className="input" value={product} onChange={e => setNewLicence({ ...newLicence, product: e.target.value as Product })}>
{available.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
</select>
</div>
<div><label className="label">Expires (optional)</label><input type="date" className="input" value={newLicence.expiresAt} onChange={e => setNewLicence({ ...newLicence, expiresAt: e.target.value })} /></div>
<div><label className="label">Grace (days)</label><input type="number" min={0} max={90} className="input w-24" value={newLicence.graceDays} onChange={e => setNewLicence({ ...newLicence, graceDays: e.target.value })} /></div>
<button className="btn-primary"><KeyRound className="h-4 w-4" /> Generate licence</button>
<p className="w-full text-xs text-slate-500">One licence per product (revoke one to replace it). Accounts is free and is created with the first other product.</p>
</form>
) : <p className="text-sm text-slate-500">This customer has a licence for every product.</p>}
</div>
</div>
+3 -2
View File
@@ -8,6 +8,7 @@ import { api, errorText } from "@/lib/api";
import { ago } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import type { Customer } from "@/lib/types";
import { PRODUCT_NAMES, byProduct } from "@/lib/products";
import { Badge, Loading, Message, PageTitle, Pager, SearchInput } from "@/components/ui";
export default function CustomersPage() {
@@ -56,8 +57,8 @@ export default function CustomersPage() {
{paged.rows.map(c => (
<tr key={c.id} className="border-t hover:bg-slate-50">
<td className="p-3"><Link href={`/customers/${c.id}`} className="font-medium text-indigo-700 hover:underline">{c.name}</Link><div className="text-xs text-slate-500">{[c.contactName, c.email].filter(Boolean).join(" · ")}</div></td>
<td className="p-3">{c.licences.length ? c.licences.map(l => <span key={l.id} className="mr-1"><Badge value={l.status} /></span>) : <span className="text-xs text-slate-400">none</span>}</td>
<td className="p-3">{c.installs.length ? c.installs.map(i => <div key={i.id} className="text-xs">{i.url} <span className="text-slate-400">· {ago(i.lastHeartbeatAt)}</span></div>) : <span className="text-xs text-slate-400">not connected</span>}</td>
<td className="p-3">{c.licences.length ? [...c.licences].sort(byProduct).map(l => <span key={l.id} className="mr-2 inline-flex items-center gap-1 text-xs">{PRODUCT_NAMES[l.product]} <Badge value={l.status} /></span>) : <span className="text-xs text-slate-400">none</span>}</td>
<td className="p-3">{c.installs.length ? c.installs.map(i => <div key={i.id} className="text-xs"><span className="text-slate-500">{PRODUCT_NAMES[i.product]}:</span> {i.url} <span className="text-slate-400">· {ago(i.lastHeartbeatAt)}</span></div>) : <span className="text-xs text-slate-400">not connected</span>}</td>
</tr>
))}
</tbody>
+42 -7
View File
@@ -8,7 +8,8 @@ import { api, errorText } from "@/lib/api";
import { ago, bytes, fmtDate, rand, randFine } from "@/lib/format";
import { usePaged } from "@/lib/paging";
import { tierForBand, tierPrice } from "@/lib/tiers";
import type { AiHelperUse, AiMonth, AiStatus, Health, InstallEvent, InstallSummary, Licence, Stats } from "@/lib/types";
import { PRODUCT_NAMES, type Product } from "@/lib/products";
import type { AiHelperUse, AiMonth, AiStatus, Health, InstallEvent, InstallSummary, Licence, Stats, UnmetRequirement } from "@/lib/types";
import { Badge, Loading, Message, PageTitle, Pager } from "@/components/ui";
type Detail = {
@@ -16,12 +17,15 @@ type Detail = {
adminContact: { name?: string; email?: string } | null; server: { node?: string; postgres?: string; os?: string } | null;
features: Record<string, unknown> | null; registeredAt: string; lastHeartbeatAt: string | null; releasedAt: string | null;
health: Health | null; stats: Stats | null;
customer: { id: string; name: string };
customer: { id: string; name: string; aiMonthlyCapCents: number; aiMarkupPercent: number | null };
licence: (Licence & { tokenPreview: { status: string; validUntil: string; licenceExpiresAt: string | null } }) | null;
summary: InstallSummary;
events: InstallEvent[];
heartbeats: { receivedAt: string; version: string | null; stats: Stats | null }[];
ai: { status: AiStatus; months: AiMonth[]; helpers: AiHelperUse[] };
update: { latestVersion: string | null; behind: boolean; unmetRequirements: UnmetRequirement[] };
linkedProducts: { product: Product; installId: string; url: string }[];
siblings: { id: string; product: Product; url: string; version: string | null; protocolVersion: number; hasPublicKey: boolean; lastHeartbeatAt: string | null }[];
};
const NO_EVENTS: InstallEvent[] = [];
@@ -63,7 +67,7 @@ export default function InstallPage() {
<>
<Link href="/" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Installs</Link>
<PageTitle
title={d.customer.name}
title={`${d.customer.name}: ${PRODUCT_NAMES[d.summary.product]}`}
subtitle={<a href={d.url} target="_blank" rel="noopener noreferrer" className="text-indigo-600 hover:underline">{d.url}</a>}
actions={<Badge value={d.summary.status} />}
/>
@@ -73,12 +77,43 @@ export default function InstallPage() {
{d.summary.problems.map(p => <div key={p.type} className="flex items-center gap-2 text-sm"><Badge value={p.level} /> {p.message}</div>)}
</div>
)}
{d.update.unmetRequirements.length > 0 && (
<div className="card mb-6 border-amber-200 bg-amber-50 text-sm text-amber-900">
<p className="font-medium">Updating to {d.update.latestVersion} needs the church&apos;s other products first, so Request update is refused until then:</p>
<ul className="mt-1 list-disc pl-5">
{d.update.unmetRequirements.map(u => (
<li key={u.product}>{PRODUCT_NAMES[u.product]} {u.version} or later{u.current ? ` (it runs ${u.current})` : " (not installed)"}</li>
))}
</ul>
</div>
)}
<div className="card mb-6 text-sm">
<h2 className="mb-2 font-semibold">The church&apos;s other products</h2>
{d.siblings.length === 0 ? <p className="text-slate-500">None: this is the church&apos;s only product in use.</p> : (
<>
<table className="w-full">
<tbody>
{d.siblings.map(s => (
<tr key={s.id} className="border-t border-slate-100 first:border-0">
<td className="py-1.5 pr-3"><Link href={`/installs/${s.id}`} className="text-indigo-700 hover:underline">{PRODUCT_NAMES[s.product]}</Link></td>
<td className="py-1.5 pr-3 text-slate-600">{s.url}</td>
<td className="py-1.5 pr-3">{s.version || "—"}</td>
<td className="py-1.5 text-right text-xs">{d.linkedProducts.some(l => l.installId === s.id) ? <span className="text-green-700">listed to this site</span> : <span className="text-slate-500">{s.hasPublicKey ? "not listed (licence revoked)" : `not listed (protocol ${s.protocolVersion}: no public key yet)`}</span>}</td>
</tr>
))}
</tbody>
</table>
<p className="mt-2 text-xs text-slate-500">{d.protocolVersion >= 2 ? "This site is told about the products listed to it in each heartbeat reply (Linked products), so it can connect to them." : "This site uses protocol 1 (Cross Events before 2.4), so it isn't told about the others yet."}</p>
</>
)}
</div>
<div className="grid gap-6 md:grid-cols-2">
<div className="card">
<h2 className="mb-2 font-semibold">Health</h2>
<Row k="Last heartbeat" v={`${ago(d.lastHeartbeatAt)} (${fmtDate(d.lastHeartbeatAt)})`} />
<Row k="Version" v={`${d.version || "—"}${d.summary.behind ? " (behind)" : ""}`} />
<Row k="Version" v={`${d.version || "—"}${d.summary.behind ? ` (latest ${d.update.latestVersion})` : ""}`} />
<Row k="Database" v={h.db === false ? "Not OK" : h.db ? "OK" : "—"} />
<Row k="Background jobs" v={h.jobs ? `${h.jobs.mode || "?"}, ${h.jobs.failedLast24h ?? 0} failed (24 h)` : "—"} />
<Row k="Last backup" v={h.lastBackupAt ? `${ago(h.lastBackupAt)}` : "none reported"} />
@@ -125,8 +160,8 @@ export default function InstallPage() {
v={<>{tier.name} · {tierPrice(tier)}{d.licence.plan !== tier.name && d.licence.plan !== "Trial" && <span className="ml-1 text-amber-700">(plan is {d.licence.plan})</span>}</>}
/>
)}
<Row k="AI cap" v={d.licence.aiMonthlyCapCents ? `${rand(d.licence.aiMonthlyCapCents)} / month` : "off"} />
<Row k="AI markup" v={d.licence.aiMarkupPercent == null ? "default" : `${d.licence.aiMarkupPercent}%`} />
<Row k="AI cap (church)" v={d.customer.aiMonthlyCapCents ? `${rand(d.customer.aiMonthlyCapCents)} / month` : "off"} />
<Row k="AI markup" v={d.customer.aiMarkupPercent == null ? "default" : `${d.customer.aiMarkupPercent}%`} />
<Link href={`/customers/${d.customer.id}`} className="mt-3 inline-block text-sm text-indigo-600 hover:underline">Change the licence →</Link>
</>
) : <p className="text-sm text-slate-500">No licence (released).</p>}
@@ -150,7 +185,7 @@ export default function InstallPage() {
<div className="card mt-6">
<h2 className="mb-2 font-semibold">AI</h2>
{!d.ai.status.enabled && d.ai.months.length === 0 ? (
<p className="text-sm text-slate-500">Off for this site{d.licence?.aiMonthlyCapCents ? " (AI isn't set up in Settings → AI, or the licence isn't active)" : " (cap R0)"}.</p>
<p className="text-sm text-slate-500">Off for this site{d.customer.aiMonthlyCapCents ? " (AI isn't set up in Settings → AI, or the licence isn't active)" : " (cap R0)"}.</p>
) : (
<>
<Row k="This month (charged)" v={`${randFine(d.ai.status.usedCents)} of ${rand(d.ai.status.capCents)} (${d.ai.status.usedPercent}%)${d.ai.status.capReached ? " — used up" : ""}`} />
+39 -5
View File
@@ -6,14 +6,22 @@ import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import { matches, usePaged } from "@/lib/paging";
import type { InstallSummary } from "@/lib/types";
import { PRODUCTS, PRODUCT_NAMES, type Product } from "@/lib/products";
import { Badge, Loading, PageTitle, Pager, SearchInput, Stat } from "@/components/ui";
type Dashboard = {
latestVersion: string | null;
counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record<string, number> };
latestVersions: Partial<Record<Product, string>>;
counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record<string, number>; billedCustomers: number; overdueInvoices: number };
// Hub 2.0: per product, and the money.
byProduct: Record<Product, { installs: number; behind: number; critical: number; licences: Record<string, number> }>;
monthlyRecurringCents: number;
overdueCents: number;
installs: InstallSummary[];
};
const rands = (cents: number) => `R${Math.round(cents / 100).toLocaleString("en-ZA")}`;
type Health = "all" | InstallSummary["status"] | "behind";
const HEALTH: { key: Health; label: string }[] = [
{ key: "all", label: "All health" },
@@ -49,7 +57,12 @@ export default function OverviewPage() {
return (
<>
<PageTitle title="Installs" subtitle={data.latestVersion ? `Latest release: ${data.latestVersion}` : "Add the latest release on the Releases page to see who is behind."} />
<PageTitle
title="Installs"
subtitle={PRODUCTS.some(p => data.latestVersions[p])
? `Latest releases: ${PRODUCTS.filter(p => data.latestVersions[p]).map(p => `${PRODUCT_NAMES[p]} ${data.latestVersions[p]}`).join(" · ")}`
: "Releases appear on the Releases page once they're tagged; then you can see who is behind."}
/>
<div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-5">
<Stat label="Installs" value={c.installs} />
<Stat label="Healthy" value={c.healthy} tone="green" />
@@ -58,9 +71,30 @@ export default function OverviewPage() {
<Stat label="Behind latest" value={c.behind} tone={c.behind ? "amber" : undefined} />
</div>
<div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-6">
<Link href="/billing" className="col-span-2 md:col-span-1"><Stat label="Monthly recurring" value={rands(data.monthlyRecurringCents)} /></Link>
<Link href="/billing" className="col-span-2 md:col-span-1"><Stat label="Overdue" value={c.overdueInvoices ? `${rands(data.overdueCents)} (${c.overdueInvoices})` : "None"} tone={c.overdueInvoices ? "red" : undefined} /></Link>
{PRODUCTS.map(p => {
const b = data.byProduct[p];
const licences = Object.entries(b.licences).filter(([, n]) => n).map(([s, n]) => `${n} ${s}`).join(", ") || "no licences";
return (
<div key={p} className="card">
<div className="text-sm text-slate-500">{PRODUCT_NAMES[p]}</div>
<div className="mt-1 text-2xl font-semibold tabular-nums">{b.installs} <span className="text-sm font-normal text-slate-500">install{b.installs === 1 ? "" : "s"}</span></div>
<div className="mt-1 text-xs text-slate-500">
{data.latestVersions[p] ? `Latest ${data.latestVersions[p]}` : "No release yet"}
{b.behind ? <span className="text-amber-700"> · {b.behind} behind</span> : null}
{b.critical ? <span className="text-red-700"> · {b.critical} critical</span> : null}
</div>
<div className="text-xs text-slate-400">{licences}</div>
</div>
);
})}
</div>
{data.installs.length === 0 ? (
<div className="card text-sm text-slate-600">
No installs yet. Add a <Link href="/customers" className="text-indigo-600 hover:underline">customer</Link>, generate a licence, and enter its key in the church&apos;s Cross Events setup.
No installs yet. Add a <Link href="/customers" className="text-indigo-600 hover:underline">customer</Link>, generate a licence, and enter its key in the church&apos;s setup (Cross Events, Website, App or Accounts).
</div>
) : (
<>
@@ -81,13 +115,13 @@ export default function OverviewPage() {
<tr key={i.id} className="border-t align-top hover:bg-slate-50">
<td className="p-3">
<Link href={`/installs/${i.id}`} className="font-medium text-indigo-700 hover:underline">{i.customer?.name || i.name}</Link>
<div className="text-xs text-slate-500">{i.url}</div>
<div className="text-xs text-slate-500">{PRODUCT_NAMES[i.product]} · {i.url}</div>
</td>
<td className="p-3">
<Badge value={i.status} />
{i.problems.filter(p => p.level !== "info").map(p => <div key={p.type} className="mt-1 text-xs text-slate-600">{p.message}</div>)}
</td>
<td className="p-3 whitespace-nowrap">{i.version || "—"}{i.behind && <span className="ml-1 text-xs text-amber-700">(behind)</span>}</td>
<td className="p-3 whitespace-nowrap">{i.version || "—"}{i.behind && <span className="ml-1 text-xs text-amber-700">(latest {i.latestVersion})</span>}</td>
<td className="p-3 whitespace-nowrap">
{i.licence ? <><Badge value={i.licence.status} />{i.licence.expiresAt && <div className="mt-1 text-xs text-slate-500">to {fmtDate(i.licence.expiresAt, false)}</div>}</> : <span className="text-xs text-slate-400">none</span>}
</td>
+117 -58
View File
@@ -1,24 +1,32 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { GitBranch, RefreshCw, ShieldAlert } from "lucide-react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { GitBranch, Link2, Plus, RefreshCw, ShieldAlert, Trash2 } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import type { Release } from "@/lib/types";
import { PRODUCTS, PRODUCT_NAMES, type Product } from "@/lib/products";
import type { Release, ReleaseSource } from "@/lib/types";
import { Badge, Loading, Message, PageTitle, ReleaseNotes } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
type Form = { version: string; notes: string; urgent: boolean; releasedAt: string };
type Form = { product: Product; version: string; notes: string; urgent: boolean; releasedAt: string };
const today = () => new Date().toISOString().slice(0, 10);
const empty = (): Form => ({ version: "", notes: "", urgent: false, releasedAt: today() });
/** Add or edit one release. */
function ReleaseForm({ initial, onSave, onCancel, busy }: { initial: Form; onSave: (f: Form) => void; onCancel?: () => void; busy: boolean }) {
/** Add or edit one release (only for a product with no release source). */
function ReleaseForm({ initial, products, onSave, onCancel, busy }: { initial: Form; products: Product[] | null; onSave: (f: Form) => void; onCancel?: () => void; busy: boolean }) {
const [form, setForm] = useState(initial);
return (
<form onSubmit={e => { e.preventDefault(); onSave(form); }} className="space-y-3">
<div className="grid gap-3 sm:grid-cols-3">
<div className="grid gap-3 sm:grid-cols-4">
{products && (
<div>
<label className="label" htmlFor="rel_product">Product</label>
<select id="rel_product" className="input" value={form.product} onChange={e => setForm({ ...form, product: e.target.value as Product })}>
{products.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
</select>
</div>
)}
<div>
<label className="label" htmlFor="rel_version">Version</label>
<input id="rel_version" className="input" placeholder="1.47.0" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })} required />
@@ -35,7 +43,7 @@ function ReleaseForm({ initial, onSave, onCancel, busy }: { initial: Form; onSav
<div>
<label className="label" htmlFor="rel_notes">What&apos;s new</label>
<textarea id="rel_notes" className="input min-h-40 font-mono" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder={"Written for the church, not for developers.\n- Volunteer rosters: plan who serves where\n- Fixed: kids tickets were offered publicly"} />
<p className="mt-1 text-xs text-slate-500">Lines starting with &quot;- &quot; show as a list. Churches see this on Site settings → Licence before they ask for the update.{form.urgent && " Urgent releases can't be put off with \"Not now\"."}</p>
<p className="mt-1 text-xs text-slate-500">Lines starting with &quot;- &quot; show as a list. Churches see this on their Licence page before they ask for the update.{form.urgent && " Urgent releases can't be put off with \"Not now\"."}</p>
</div>
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save release"}</button>
@@ -45,86 +53,118 @@ function ReleaseForm({ initial, onSave, onCancel, busy }: { initial: Form; onSav
);
}
type Source = { release_repo_url: string; release_notes_path: string; release_repo_token_set: string; release_synced_at: string; release_sync_error: string };
type SyncState = { release_synced_at: string; release_sync_error: string; release_repo_token_set: string; release_sources: string };
type SyncResult = { sources: { source: string; tags: number }[]; added: number; updated: number; removed: number; latest: Partial<Record<Product, string>>; problems: string[] };
/** Where releases come from: the git repository's tags and WHATS-NEW.md (synced every 15 minutes). */
function GitSource({ source, onSaved, setMsg }: { source: Source; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({ url: source.release_repo_url, path: source.release_notes_path || "WHATS-NEW.md", token: "", clearToken: false });
const latestText = (latest: Partial<Record<Product, string>>) =>
PRODUCTS.filter(p => latest[p]).map(p => `${PRODUCT_NAMES[p]} ${latest[p]}`).join(", ") || "none yet";
/**
* Where releases come from: per product, one or more git sources (a repository, a tag prefix and a
* notes file), synced every 15 minutes.
*/
function Sources({ sources, state, onSaved, setMsg }: { sources: ReleaseSource[]; state: SyncState; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [rows, setRows] = useState<ReleaseSource[]>(sources);
const [token, setToken] = useState({ value: "", clear: false });
const [busy, setBusy] = useState(false);
const saved = !!state.release_sources?.trim();
const syncNow = async (saved = false) => {
const syncNow = async (prefix = "Synced") => {
try {
const r = await api<{ tags: number; added: number; updated: number; removed: number; latest: string | null }>("/api/admin/releases/sync", { method: "POST" });
setMsg({ type: "ok", text: `${saved ? "Saved and synced" : "Synced"}: ${r.tags} version tags, ${r.added} new, ${r.updated} updated, ${r.removed} removed. Latest is ${r.latest || "not set"}.` });
const r = await api<SyncResult>("/api/admin/releases/sync", { method: "POST" });
const tags = r.sources.reduce((n, s) => n + s.tags, 0);
setMsg({ type: r.problems.length ? "err" : "ok", text: `${prefix}: ${tags} version tags in ${r.sources.length} sources, ${r.added} new, ${r.updated} updated, ${r.removed} removed. Latest: ${latestText(r.latest)}.${r.problems.length ? ` Problems: ${r.problems.join(" ")}` : ""}` });
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
onSaved();
};
const save = async (e: React.FormEvent) => {
e.preventDefault();
const save = async (list: ReleaseSource[] | null) => {
setBusy(true);
setMsg(null);
try {
await api("/api/admin/settings", { method: "PUT", body: { settings: { release_repo_url: form.url.trim(), release_notes_path: form.path.trim(), release_repo_token: form.token, release_repo_token_clear: form.clearToken } } });
setForm({ ...form, token: "", clearToken: false });
if (form.url.trim()) await syncNow(true);
else { setMsg({ type: "ok", text: "Saved. Releases are added by hand now." }); onSaved(); }
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
await api("/api/admin/settings", { method: "PUT", body: { settings: { release_sources: list, release_repo_token: token.value, release_repo_token_clear: token.clear } } });
setToken({ value: "", clear: false });
await syncNow(list ? "Saved and synced" : "Back to the defaults and synced");
} catch (err) { setMsg({ type: "err", text: errorText(err) }); onSaved(); }
setBusy(false);
};
const set = (i: number, patch: Partial<ReleaseSource>) => setRows(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)));
return (
<form onSubmit={save} className="card mb-6 space-y-3">
<form onSubmit={e => { e.preventDefault(); save(rows); }} className="card mb-6 space-y-3">
<div className="flex flex-wrap items-center gap-2">
<GitBranch className="h-4 w-4 text-slate-400" />
<h2 className="font-semibold">From git</h2>
{source.release_repo_url && <span className="text-xs text-slate-500">Last synced {ago(source.release_synced_at || null)}</span>}
{source.release_repo_url && (
<button type="button" className="btn-secondary ml-auto px-2 py-1 text-xs" disabled={busy} onClick={async () => { setBusy(true); setMsg(null); await syncNow(); setBusy(false); }}>
<RefreshCw className={`mr-1 inline h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} /> Sync now
</button>
)}
<h2 className="font-semibold">Release sources</h2>
<span className="text-xs text-slate-500">{saved ? "Your list" : "The defaults"} · last synced {ago(state.release_synced_at || null)}</span>
<button type="button" className="btn-secondary ml-auto px-2 py-1 text-xs" disabled={busy} onClick={async () => { setBusy(true); setMsg(null); await syncNow(); setBusy(false); }}>
<RefreshCw className={`mr-1 inline h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} /> Sync now
</button>
</div>
<p className="text-sm text-slate-600">Every <code>v1.2.3</code> tag is a release, and the newest tag is the latest version. The notes come from the file below on the default branch, for tagged versions only (so they can be written ahead, or corrected later): a <code>## 1.2.3</code> heading per version, with <code>urgent</code> or <code>security</code> in the heading for an urgent release. Checked every 15 minutes. Leave the address blank to add releases by hand.</p>
<div className="grid gap-3 sm:grid-cols-3">
<div className="sm:col-span-2"><label className="label" htmlFor="repo_url">Repository</label><input id="repo_url" className="input" placeholder="https://c-git.crosscode.co.za/joshua/hope-events" value={form.url} onChange={e => setForm({ ...form, url: e.target.value })} /></div>
<div><label className="label" htmlFor="notes_path">Notes file</label><input id="notes_path" className="input" value={form.path} onChange={e => setForm({ ...form, path: e.target.value })} /></div>
<p className="text-sm text-slate-600">
Every tag <code>&lt;prefix&gt;1.2.3</code> in a source is a release of its product (e.g. <code>events@2.2.0</code>; the prefix <code>v</code> also takes a bare <code>1.2.3</code>), and a product&apos;s newest is its latest version.
The notes come from the notes file on the default branch, for tagged versions only: a <code>## 1.2.3</code> heading per version, with <code>urgent</code> or <code>security</code> in it for an urgent release
and <code>requires accounts 1.2.0</code> for a release that needs another product first. Checked every 15 minutes. A product with no source has its releases added by hand.
</p>
<div className="space-y-2">
{rows.map((r, i) => (
<div key={i} className="grid items-end gap-2 sm:grid-cols-[10rem_1fr_8rem_14rem_auto]">
<div>
<label className="label" htmlFor={`src_product_${i}`}>Product</label>
<select id={`src_product_${i}`} className="input" value={r.product} onChange={e => set(i, { product: e.target.value as Product })}>
{PRODUCTS.map(p => <option key={p} value={p}>{PRODUCT_NAMES[p]}</option>)}
</select>
</div>
<div><label className="label" htmlFor={`src_repo_${i}`}>Repository</label><input id={`src_repo_${i}`} className="input" value={r.repo} onChange={e => set(i, { repo: e.target.value })} placeholder="https://c-git.crosscode.co.za/joshua/crosscode-platform" required /></div>
<div><label className="label" htmlFor={`src_prefix_${i}`}>Tag prefix</label><input id={`src_prefix_${i}`} className="input font-mono" value={r.tagPrefix} onChange={e => set(i, { tagPrefix: e.target.value })} placeholder="events@" /></div>
<div><label className="label" htmlFor={`src_notes_${i}`}>Notes file</label><input id={`src_notes_${i}`} className="input font-mono" value={r.notesPath} onChange={e => set(i, { notesPath: e.target.value })} placeholder="WHATS-NEW.md" /></div>
<button type="button" className="btn-secondary mb-0.5 px-2" aria-label={`Remove source ${i + 1}`} onClick={() => setRows(rows.filter((_, j) => j !== i))}><Trash2 className="h-4 w-4" /></button>
</div>
))}
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setRows([...rows, { product: "events", repo: rows[0]?.repo || "", tagPrefix: "", notesPath: "WHATS-NEW.md" }])}><Plus className="mr-1 inline h-3.5 w-3.5" /> Add a source</button>
</div>
<div>
<label className="label" htmlFor="repo_token">Access token (private repositories only)</label>
<input id="repo_token" className="input" type="password" autoComplete="new-password" disabled={form.clearToken} placeholder={source.release_repo_token_set ? "Saved — leave blank to keep it" : "Not needed for a public repository"} value={form.token} onChange={e => setForm({ ...form, token: e.target.value })} />
{source.release_repo_token_set && <label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={form.clearToken} onChange={e => setForm({ ...form, token: "", clearToken: e.target.checked })} /> Remove the saved token</label>}
<label className="label" htmlFor="repo_token">Access token (private repositories only; used for every source)</label>
<input id="repo_token" className="input" type="password" autoComplete="new-password" disabled={token.clear} placeholder={state.release_repo_token_set ? "Saved — leave blank to keep it" : "Not needed for public repositories"} value={token.value} onChange={e => setToken({ ...token, value: e.target.value })} />
{state.release_repo_token_set && <label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={token.clear} onChange={e => setToken({ value: "", clear: e.target.checked })} /> Remove the saved token</label>}
</div>
{state.release_sync_error && <p className="whitespace-pre-line rounded-lg bg-amber-50 p-3 text-sm text-amber-900">{state.release_sync_error}</p>}
<div className="flex flex-wrap gap-2">
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save sources"}</button>
{saved && <button type="button" className="btn-secondary" disabled={busy} onClick={() => { if (confirm("Go back to the default sources? Your list is removed.")) save(null); }}>Use the defaults</button>}
</div>
{source.release_sync_error && <p className="rounded-lg bg-amber-50 p-3 text-sm text-amber-900">{source.release_sync_error}</p>}
<button className="btn-primary" disabled={busy}>{busy ? "Saving…" : "Save"}</button>
</form>
);
}
/** Cross Events versions and what's new in each. The newest is the latest version installs are offered. */
/** Each product's versions and what's new in each. A product's newest is the latest version its installs are offered. */
export default function ReleasesPage() {
const [releases, setReleases] = useState<Release[] | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [adding, setAdding] = useState(false);
const [editing, setEditing] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [filter, setFilter] = useState<Product | "all">("all");
const [state, setState] = useState<{ settings: SyncState; releaseSources: ReleaseSource[] } | null>(null);
const [source, setSource] = useState<Source | null>(null);
const load = useCallback(() => {
api<Release[]>("/api/admin/releases").then(setReleases).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ settings: Source }>("/api/admin/settings").then(r => setSource(r.settings)).catch(() => {});
api<{ settings: SyncState; releaseSources: ReleaseSource[] }>("/api/admin/settings").then(setState).catch(() => {});
}, []);
const fromGit = !!source?.release_repo_url;
useEffect(() => { load(); }, [load]);
const body = (f: Form) => ({ version: f.version, notes: f.notes, urgent: f.urgent, releasedAt: f.releasedAt ? `${f.releasedAt}T12:00:00+02:00` : null });
const fromGit = useMemo(() => new Set((state?.releaseSources || []).map(s => s.product)), [state]);
const manual = PRODUCTS.filter(p => !fromGit.has(p));
const shown = (releases || []).filter(r => filter === "all" || r.product === filter);
const body = (f: Form) => ({ product: f.product, version: f.version, notes: f.notes, urgent: f.urgent, releasedAt: f.releasedAt ? `${f.releasedAt}T12:00:00+02:00` : null });
const save = async (f: Form, id?: string) => {
setBusy(true);
setMsg(null);
try {
const r = await api<{ latestVersion: string | null }>(id ? `/api/admin/releases/${id}` : "/api/admin/releases", { method: id ? "PUT" : "POST", body: body(f) });
setMsg({ type: "ok", text: `Saved. The latest version is ${r.latestVersion || "not set"}; installs see it with their next heartbeat (within 15 minutes).` });
setMsg({ type: "ok", text: `Saved. The latest ${PRODUCT_NAMES[f.product]} version is ${r.latestVersion || "not set"}; its installs see it with their next heartbeat (within 15 minutes).` });
setAdding(false);
setEditing(null);
load();
@@ -132,10 +172,10 @@ export default function ReleasesPage() {
};
const remove = async (r: Release) => {
if (!confirm(`Delete release ${r.version}? Installs stop being offered it${releases?.[0]?.id === r.id ? ", and the version before it becomes the latest" : ""}.`)) return;
if (!confirm(`Delete ${PRODUCT_NAMES[r.product]} ${r.version}? Its installs stop being offered it${r.latest ? ", and the version before it becomes the latest" : ""}.`)) return;
try {
const res = await api<{ latestVersion: string | null }>(`/api/admin/releases/${r.id}`, { method: "DELETE" });
setMsg({ type: "ok", text: `Deleted. The latest version is ${res.latestVersion || "not set"}.` });
setMsg({ type: "ok", text: `Deleted. The latest ${PRODUCT_NAMES[r.product]} version is ${res.latestVersion || "not set"}.` });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
@@ -144,27 +184,46 @@ export default function ReleasesPage() {
<>
<PageTitle
title="Releases"
subtitle="Each Cross Events version and what's new in it. The newest is the latest version: installs on an older one see “Update available” with the notes for every version they'd get."
actions={!adding && !fromGit && source && <button className="btn-primary" onClick={() => { setAdding(true); setEditing(null); }}>Add release</button>}
subtitle="Each product's versions and what's new in them. A product's newest is its latest version: its installs on an older one see “Update available” with the notes for every version they'd get."
actions={!adding && state && manual.length > 0 && <button className="btn-primary" onClick={() => { setAdding(true); setEditing(null); }}>Add release</button>}
/>
{msg && <div className="mb-4"><Message msg={msg} /></div>}
{source && <GitSource key={source.release_synced_at + source.release_repo_url} source={source} onSaved={load} setMsg={setMsg} />}
{adding && <div className="card mb-6"><h2 className="mb-3 font-semibold">New release</h2><ReleaseForm initial={empty()} busy={busy} onSave={f => save(f)} onCancel={() => setAdding(false)} /></div>}
{state && <Sources key={state.settings.release_synced_at + state.settings.release_sources} sources={state.releaseSources} state={state.settings} onSaved={load} setMsg={setMsg} />}
{adding && (
<div className="card mb-6">
<h2 className="mb-1 font-semibold">New release</h2>
<p className="mb-3 text-xs text-slate-500">Only for products with no release source.</p>
<ReleaseForm initial={{ product: manual[0], version: "", notes: "", urgent: false, releasedAt: today() }} products={manual} busy={busy} onSave={f => save(f)} onCancel={() => setAdding(false)} />
</div>
)}
{!releases ? <Loading /> : releases.length === 0 ? <p className="text-sm text-slate-500">No releases yet. Add the version installs should be on.</p> : (
<div className="mb-4 flex flex-wrap gap-2" role="group" aria-label="Show releases of">
{(["all", ...PRODUCTS] as const).map(p => (
<button key={p} type="button" className={filter === p ? "btn-primary px-3 py-1 text-xs" : "btn-secondary px-3 py-1 text-xs"} aria-pressed={filter === p} onClick={() => setFilter(p)}>
{p === "all" ? "All products" : PRODUCT_NAMES[p]}
</button>
))}
</div>
{!releases ? <Loading /> : shown.length === 0 ? <p className="text-sm text-slate-500">No releases yet{filter === "all" ? "" : ` for ${PRODUCT_NAMES[filter]}`}.</p> : (
<div className="space-y-4">
{releases.map((r, i) => (
{shown.map(r => (
<div key={r.id} className="card">
{editing === r.id ? (
<ReleaseForm initial={{ version: r.version, notes: r.notes, urgent: r.urgent, releasedAt: r.releasedAt.slice(0, 10) }} busy={busy} onSave={f => save(f, r.id)} onCancel={() => setEditing(null)} />
<ReleaseForm initial={{ product: r.product, version: r.version, notes: r.notes, urgent: r.urgent, releasedAt: r.releasedAt.slice(0, 10) }} products={null} busy={busy} onSave={f => save(f, r.id)} onCancel={() => setEditing(null)} />
) : (
<>
<div className="mb-2 flex flex-wrap items-center gap-2">
<h2 className="text-lg font-semibold">{r.version}</h2>
{i === 0 && <Badge value="ok" label="Latest" />}
<h2 className="text-lg font-semibold"><span className="text-slate-500">{PRODUCT_NAMES[r.product]}</span> {r.version}</h2>
{r.latest && <Badge value="ok" label="Latest" />}
{r.urgent && <span className="inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 ring-1 ring-inset ring-red-200"><ShieldAlert className="h-3 w-3" /> Urgent</span>}
{r.requires.length > 0 && (
<span className="inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-800 ring-1 ring-inset ring-amber-200">
<Link2 className="h-3 w-3" /> Needs {r.requires.map(q => `${PRODUCT_NAMES[q.product]} ${q.version}`).join(" and ")}
</span>
)}
<span className="text-xs text-slate-500">{fmtDate(r.releasedAt, false)} · {r.installs} install{r.installs === 1 ? "" : "s"} on it</span>
{!fromGit && (
{!fromGit.has(r.product) && (
<span className="ml-auto flex gap-2">
<button className="btn-secondary px-2 py-1 text-xs" onClick={() => { setEditing(r.id); setAdding(false); }}>Edit</button>
<button className="btn-danger px-2 py-1 text-xs" onClick={() => remove(r)}>Delete</button>
+5 -4
View File
@@ -8,6 +8,7 @@ import { matches, usePaged } from "@/lib/paging";
import type { AiInstallUse } from "@/lib/types";
import { Loading, Message, PageTitle, Pager, SearchInput, Tabs } from "@/components/ui";
import { BillingSettings } from "@/components/billing/BillingSettings";
import { PRODUCT_NAMES } from "@/lib/products";
type Settings = Record<string, string>;
type AuditRow = { id: string; action: string; target: string | null; metadata: unknown; createdAt: string; actor: { name: string } | null };
@@ -145,11 +146,11 @@ function AiTab({ settings, models, onSaved, setMsg }: { settings: Settings; mode
{!usage ? <Loading /> : usage.installs.length === 0 ? <p className="px-5 pb-5 text-sm text-slate-500">No AI use in {usage.month}.</p> : (
<div className="overflow-x-auto px-5 pb-5">
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Site</th><th>Cap</th><th>Uses</th><th className="text-right">Real cost</th><th className="text-right">Charged</th><th className="text-right">Profit</th></tr></thead>
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Site</th><th>Church cap</th><th>Uses</th><th className="text-right">Real cost</th><th className="text-right">Charged</th><th className="text-right">Profit</th></tr></thead>
<tbody>
{usage.installs.map(i => (
<tr key={i.installId} className="border-t border-slate-100">
<td className="py-1"><Link href={`/installs/${i.installId}`} className="text-indigo-700 hover:underline">{i.name}</Link></td>
<td className="py-1"><Link href={`/installs/${i.installId}`} className="text-indigo-700 hover:underline">{i.customer?.name || i.name}</Link> <span className="text-xs text-slate-500">{PRODUCT_NAMES[i.product]}</span></td>
<td>{i.capCents ? rand(i.capCents) : "off"}</td>
<td>{i.calls}</td>
<td className="text-right">{randFine(i.realCents)}</td>
@@ -261,7 +262,7 @@ export default function SettingsPage() {
<div role="tabpanel" id={`panel-${tab}`} aria-labelledby={`tab-${tab}`}>
{tab === "alerts" && (
<form onSubmit={save} className="card max-w-2xl space-y-4">
<p className="text-sm text-slate-600">The latest Cross Events version is the newest one on the <Link href="/releases" className="text-indigo-700 hover:underline">Releases</Link> page{settings.latest_version ? ` (now ${settings.latest_version})` : ""}.</p>
<p className="text-sm text-slate-600">Each product&apos;s latest version is its newest one on the <Link href="/releases" className="text-indigo-700 hover:underline">Releases</Link> page{settings.latest_version ? ` (Cross Events: ${settings.latest_version})` : ""}; an install on an older one shows as behind.</p>
{FIELDS.map(f => (
<div key={f.key}>
<label className="label" htmlFor={f.key}>{f.label}</label>
@@ -290,7 +291,7 @@ export default function SettingsPage() {
<label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={smtpPass.clear} onChange={e => setSmtpPass({ value: "", clear: e.target.checked })} /> Remove the saved password</label>
)}
</div>
<div><label className="label" htmlFor="smtp_from">From address</label><input id="smtp_from" className="input" placeholder="Cross Events Hub <hub@crosscode.co.za>" value={settings.smtp_from ?? ""} onChange={e => setSettings({ ...settings, smtp_from: e.target.value })} /><p className="mt-1 text-xs text-slate-500">Blank uses the username.</p></div>
<div><label className="label" htmlFor="smtp_from">From address</label><input id="smtp_from" className="input" placeholder="Cross Code Hub <hub@crosscode.co.za>" value={settings.smtp_from ?? ""} onChange={e => setSettings({ ...settings, smtp_from: e.target.value })} /><p className="mt-1 text-xs text-slate-500">Blank uses the username.</p></div>
<button className="btn-primary">Save email settings</button>
<div className="border-t border-slate-100 pt-3">
<label className="label" htmlFor="smtp_test_to">Send a test email to</label>
+1 -1
View File
@@ -2,7 +2,7 @@ import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "Cross Events Hub",
title: "Cross Code Hub",
description: "Installs, licences and health for Cross Events",
robots: { index: false, follow: false },
};
+1 -1
View File
@@ -57,7 +57,7 @@ export default function LoginPage() {
<div className="flex min-h-screen items-center justify-center p-4">
<div className="card w-full max-w-sm">
<Logo markOnly className="mb-3 h-10 w-10" />
<h1 className="text-xl font-semibold">Cross Events Hub</h1>
<h1 className="text-xl font-semibold">Cross Code Hub</h1>
{step === "password" && (
<form onSubmit={submitPassword} className="mt-5 space-y-4">
<div>
@@ -5,45 +5,156 @@ 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;
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[];
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>
);
}
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. */
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 +162,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 +177,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 +205,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 +219,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 +308,25 @@ 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">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">
<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.addressType, c.addressCustomCents, c.licences.map(l => [l.plan, l.billedFrom, l.billedUntil, l.customMonthlyCents, l.status])])} />
</div>
</div>
</div>
@@ -199,7 +355,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>
+2 -2
View File
@@ -13,7 +13,7 @@ const STATUS_TONE: Record<string, string> = {
};
const STATUS_LABEL: Record<string, string> = { ok: "Healthy", warning: "Warning", critical: "Critical", info: "Info" };
/** The Cross Events Hub mark (same artwork as app/icon.svg), with the name beside it unless markOnly. */
/** The Cross Code Hub mark (same artwork as app/icon.svg), with the name beside it unless markOnly. */
export function Logo({ className = "h-8 w-8", markOnly }: { className?: string; markOnly?: boolean }) {
const mark = (
<svg viewBox="0 0 64 64" className={`${className} shrink-0`} aria-hidden="true">
@@ -25,7 +25,7 @@ export function Logo({ className = "h-8 w-8", markOnly }: { className?: string;
return (
<span className="flex items-center gap-2.5">
{mark}
<span className="font-semibold leading-tight">Cross Events Hub</span>
<span className="font-semibold leading-tight">Cross Code Hub</span>
</span>
);
}
+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 = {
+23
View File
@@ -0,0 +1,23 @@
// The Cross Code products (Hub 2.0). The same list as backend/src/utils/products.js.
export type Product = "events" | "accounts" | "website" | "app";
export const PRODUCTS: Product[] = ["events", "accounts", "website", "app"];
export const PRODUCT_NAMES: Record<Product, string> = {
events: "Cross Events",
accounts: "Accounts",
website: "Church Website",
app: "Church App",
};
/** Where the church enters a licence key, per product. */
export const KEY_WHERE: Record<Product, string> = {
events: "the church's Cross Events setup (or Site settings → Licence)",
accounts: "the church's Accounts setup",
website: "the church's Website setup",
app: "the church's App setup",
};
/** Product order for lists: Events, Accounts, Website, App. */
export const byProduct = <T extends { product: Product }>(a: T, b: T) => PRODUCTS.indexOf(a.product) - PRODUCTS.indexOf(b.product);
+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;
+14 -5
View File
@@ -1,8 +1,11 @@
import type { Product } from "./products";
export type Problem = { type: string; level: "info" | "warning" | "critical"; message: string };
export type LicenceStatus = "active" | "suspended" | "revoked";
export type InstallSummary = {
id: string;
product: Product;
name: string;
url: string;
customer: { id: string; name: string } | null;
@@ -10,6 +13,7 @@ export type InstallSummary = {
behind: boolean;
licence: { id: string; status: LicenceStatus; expiresAt: string | null } | null;
lastHeartbeatAt: string | null;
latestVersion: string | null;
status: "ok" | "warning" | "critical";
problems: Problem[];
releasedAt: string | null;
@@ -18,12 +22,11 @@ export type InstallSummary = {
export type Licence = {
id: string;
key: string;
product: Product;
plan: string;
status: LicenceStatus;
expiresAt: string | null;
graceDays: number;
aiMonthlyCapCents: number;
aiMarkupPercent: number | null;
notes: string | null;
createdAt: string;
install?: { id: string; name: string; url: string; lastHeartbeatAt: string | null } | null;
@@ -37,8 +40,11 @@ export type Customer = {
phone: string | null;
notes: string | null;
createdAt: string;
/** Hub 2.0: the church's AI allowance, shared by all its installs. */
aiMonthlyCapCents: number;
aiMarkupPercent: number | null;
licences: Licence[];
installs: { id: string; url: string; name?: string; lastHeartbeatAt: string | null; releasedAt?: string | null; version?: string | null }[];
installs: { id: string; product: Product; url: string; name?: string; lastHeartbeatAt: string | null; releasedAt?: string | null; version?: string | null }[];
};
export type Health = {
@@ -70,9 +76,12 @@ export type InstallEvent = { id: string; type: string; level: Problem["level"];
export type AiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string };
export type AiMonth = { month: string; calls: number; inputTokens: number; outputTokens: number; realCents: number; chargedCents: number; profitCents: number };
export type AiHelperUse = { helper: string; calls: number; chargedCents: number };
export type AiInstallUse = { installId: string; name: string; url: string; capCents: number; calls: number; realCents: number; chargedCents: number; profitCents: number };
export type AiInstallUse = { installId: string; name: string; url: string; product: Product; customer: { id: string; name: string } | null; capCents: number; calls: number; realCents: number; chargedCents: number; profitCents: number };
export type Release ={ id: string; version: string; notes: string; urgent: boolean; releasedAt: string; installs: number };
export type ReleaseRequirement = { product: Product; version: string };
export type Release = { id: string; product: Product; version: string; notes: string; urgent: boolean; requires: ReleaseRequirement[]; releasedAt: string; latest: boolean; installs: number };
export type ReleaseSource = { product: Product; repo: string; tagPrefix: string; notesPath: string };
export type UnmetRequirement = { product: Product; version: string; current: string | null };
export type NoticeLevel = "info" | "maintenance" | "warning";
export type Notice = {