Files
events-hub/backend/prisma/schema.prisma
T
joshuaandClaude Opus 5.5 ad602b2846 Hub 2.0 step 1: products foundation
- Product enum (events, accounts, website, app) on Licence and Install,
  Install.publicKey; existing rows are events
- One open licence per product per customer: partial unique index, with a
  migration guard that names customers with duplicates (npm run check:hub2
  lists them beforehand)
- Licence keys per product (CEH-, CCA-, CCW-, CCP-); free Accounts licence
  created with the first other product licence
- Protocol v1 registers Events licences only (409 WRONG_PRODUCT); only Events
  licences can be invoiced until billing per customer
- Cross Code Hub in the UI, emails and PDFs
- @crosscode/contracts 1.0.0 vendored (backend/vendor)
- Steps merge into release/2.0, not main (plan updated)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:28:06 +02:00

413 lines
14 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Cross Events Hub — customers, licences, installs and their heartbeats.
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
}
// Someone who logs in to the Hub (Joshua, later support staff). Two-factor (authenticator
// app) is required: totpSecret is set up on first login.
model AdminUser {
id String @id @default(uuid())
email String @unique
name String
password String
// AES-GCM encrypted (utils/crypto.js); null until two-factor is set up.
totpSecret String?
totpEnabled Boolean @default(false)
// Bumped to sign out everywhere.
tokenVersion Int @default(0)
lastLoginAt DateTime?
createdAt DateTime @default(now())
auditLogs AuditLog[]
}
model Customer {
id String @id @default(uuid())
name String
contactName String?
email String?
phone String?
notes String?
// Billing (1.7.0). Invoices go to billingEmail, else the site's admin contact, else email.
billingEmail String?
// The postal address printed on invoices and statements.
billingAddress String?
// A founding church pays the founding price on every tier (35% less) while it stays.
founding Boolean @default(false)
foundingSince DateTime? @db.Date
foundingNote String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
licences Licence[]
installs Install[]
invoices Invoice[]
payments Payment[]
licenceChanges LicenceChange[]
billingEmails BillingEmail[]
}
enum LicenceStatus {
active
suspended
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 (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
// A price per month instead of the tier's (e.g. the Network tier), in cents.
customMonthlyCents Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// One licence = one install.
install Install?
invoices Invoice[]
licenceChanges LicenceChange[]
@@index([customerId, product])
}
enum BillingCycle {
none
monthly
yearly
}
model Install {
id String @id @default(uuid())
customerId String
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?
protocolVersion Int @default(1)
adminContact Json?
server Json?
timezone String?
features Json?
// From the latest heartbeat.
lastHeartbeatAt DateTime?
health Json?
stats Json?
notes String?
registeredAt DateTime @default(now())
// Set when Joshua releases the licence (e.g. the church moved domain): heartbeats are refused.
releasedAt DateTime?
heartbeats Heartbeat[]
events InstallEvent[]
aiUsage AiUsage[]
@@index([lastHeartbeatAt])
}
enum AiUsageStatus {
// The worst case is held against the cap while the call runs.
reserved
done
failed
}
// One AI call from an install (Cross Events 2.0). No prompt or response text is kept — only what's
// needed to meter it. Amounts are in millicents (1/1000 of a cent, rand): a call costs a few cents.
model AiUsage {
id String @id @default(uuid())
installId String
install Install @relation(fields: [installId], references: [id], onDelete: Cascade)
helper String
model String
// The billing month, YYYY-MM in South African time.
month String
status AiUsageStatus @default(reserved)
inputTokens Int @default(0)
outputTokens Int @default(0)
cacheReadTokens Int @default(0)
cacheWriteTokens Int @default(0)
// What Claude cost (real) and what the church is charged (real × (1 + markup)).
realMillicents Int @default(0)
chargedMillicents Int @default(0)
markupPercent Int
// Rand per US dollar used for this call.
usdZar Float
createdAt DateTime @default(now())
@@index([installId, month])
@@index([month])
}
// Every heartbeat for 30 days, then one per install per day.
model Heartbeat {
id String @id @default(uuid())
installId String
install Install @relation(fields: [installId], references: [id], onDelete: Cascade)
receivedAt DateTime @default(now())
version String?
health Json?
stats Json?
@@index([installId, receivedAt])
}
enum EventLevel {
info
warning
critical
}
// Things that happened to an install: alerts (offline, backup failing, disk low, errors,
// licence expiring), version changes, registration. An alert stays open (resolvedAt null)
// until the condition clears, so it's emailed once.
model InstallEvent {
id String @id @default(uuid())
installId String
install Install @relation(fields: [installId], references: [id], onDelete: Cascade)
type String
level EventLevel @default(info)
message String
createdAt DateTime @default(now())
resolvedAt DateTime?
@@index([installId, createdAt])
@@index([type, resolvedAt])
}
model AuditLog {
id String @id @default(uuid())
actorId String?
actor AdminUser? @relation(fields: [actorId], references: [id], onDelete: SetNull)
action String
target String?
metadata Json?
ip String?
createdAt DateTime @default(now())
@@index([createdAt])
}
model Setting {
key String @id
value String
}
// A Cross Events version and what's new in it, shown to installs on an older version so the church
// can decide whether to ask for the update. The highest version is the latest (kept in the
// 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
// Plain text; lines starting with "- " show as a list.
notes String @default("")
urgent Boolean @default(false)
releasedAt DateTime @default(now())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
enum NoticeLevel {
info
maintenance
warning
}
// A message from Joshua to churches: a banner on their site for site admins and supervisors
// (between startsAt and endsAt), an email to the customer and the install's admin contact, or both.
model Notice {
id String @id @default(uuid())
title String
message String
level NoticeLevel @default(info)
// Every install, or only the ones listed.
allInstalls Boolean @default(true)
installIds String[] @default([])
showBanner Boolean @default(true)
// Null = straight away / until ended.
startsAt DateTime?
endsAt DateTime?
// Set when the email went out (sent once, when the notice is created).
emailedAt DateTime?
emailedTo Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([endsAt])
}
// ─── Billing (1.7.0) ───────────────────────────────────────────────────────────
enum InvoiceStatus {
// Made 14 days before its date and emailed to Joshua for approval. Can be edited.
draft
// Goes out automatically on its date. Can still be edited until then.
approved
sent
void
}
// One invoice for one licence's period, in cents (rand). Payment state comes from its payments.
model Invoice {
id String @id @default(uuid())
number String @unique
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
licenceId String?
licence Licence? @relation(fields: [licenceId], references: [id], onDelete: SetNull)
status InvoiceStatus @default(draft)
// The day it's sent (and dated), and when payment is due.
issueDate DateTime @db.Date
dueDate DateTime @db.Date
periodStart DateTime? @db.Date
periodEnd DateTime? @db.Date
cycle BillingCycle @default(monthly)
// The tier billed, and how it was chosen (the income band at a review).
plan String?
incomeBand String?
reviewed Boolean @default(false)
founding Boolean @default(false)
// A tier change that comes with this invoice: { from, to, fromMonthlyCents, toMonthlyCents }.
planChange Json?
// [{ description, quantity, unitCents, amountCents }]
lines Json
totalCents Int
// VAT included in the total (0 unless VAT registered).
vatCents Int @default(0)
vatRate Float?
notes String?
// Things Joshua should check before approving (e.g. no income band reported).
warnings String[] @default([])
recipientEmail String?
approvedAt DateTime?
approvedById String?
approvalEmailedAt DateTime?
// Emailed to Joshua when its date came and it still wasn't approved.
overdueEmailedAt DateTime?
sentAt DateTime?
sendError String?
voidedAt DateTime?
voidReason String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
payments Payment[]
licenceChanges LicenceChange[]
@@unique([licenceId, periodStart])
@@index([status, issueDate])
@@index([customerId])
}
// Money received from a church, optionally against one invoice. Each gets a receipt number.
model Payment {
id String @id @default(uuid())
receiptNumber String @unique
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
invoiceId String?
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: SetNull)
amountCents Int
paidOn DateTime @db.Date
// eft, card, cash, other
method String @default("eft")
reference String?
notes String?
receiptSentAt DateTime?
createdById String?
createdAt DateTime @default(now())
@@index([customerId, paidOn])
}
// A notice to a church that its tier (and price) changes from a date. Sent when the invoice
// that brings the change is approved, or by hand from the customer page.
model LicenceChange {
id String @id @default(uuid())
number String @unique
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
licenceId String?
licence Licence? @relation(fields: [licenceId], references: [id], onDelete: SetNull)
invoiceId String?
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: SetNull)
fromPlan String
toPlan String
fromMonthlyCents Int?
toMonthlyCents Int?
effectiveDate DateTime @db.Date
reason String?
incomeBand String?
// Set once the plan has been changed on the licence (on the effective date).
appliedAt DateTime?
sentAt DateTime?
createdAt DateTime @default(now())
@@index([licenceId, appliedAt])
}
// Every billing email: invoices, receipts, statements, licence-change notices and approval
// requests to Joshua.
model BillingEmail {
id String @id @default(uuid())
customerId String?
customer Customer? @relation(fields: [customerId], references: [id], onDelete: SetNull)
// invoice, receipt, statement, licence_change, approval, reminder
kind String
refId String?
to String
subject String
error String?
sentAt DateTime @default(now())
@@index([customerId, sentAt])
}
// Document numbers (INV-2026-0001…): one counter per prefix and year, incremented atomically.
model DocumentCounter {
key String @id
value Int @default(0)
}