Files
events-hub/backend/prisma/schema.prisma
T
joshua 1816f3088a Merge branch 'fix/void-refunded'
# Conflicts:
#	CHANGELOG.md
2026-11-17 13:34:19 +02:00

672 lines
24 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?
// 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[]
installs Install[]
invoices Invoice[]
payments Payment[]
licenceChanges LicenceChange[]
billingEmails BillingEmail[]
deployments Deployment[]
}
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)
notes String?
// 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())
updatedAt DateTime @updatedAt
// One licence = one install.
install Install?
invoices Invoice[]
licenceChanges LicenceChange[]
@@index([customerId, product])
}
enum AddressType {
own_domain
crosscode
included
}
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[]
deployment Deployment?
@@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())
// 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 {
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)
// 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
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?
// 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?
// 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[]
// 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])
}
// 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?
// A refund: the money went back to the church. The payment stays on record (and its receipt), but
// no longer counts as paid, so the invoice can be voided or paid again.
refundedAt DateTime? @db.Date
refundNote String?
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)
}
// ─── Servers and the agent (2.1.0, crosscode-platform docs/AGENT-1.0-PLAN.md) ──────────────────
enum ServerMode {
church
central
}
// A server running the crosscode agent. It joined with a one-time token and its two public keys:
// Ed25519 (checks its requests) and X25519 (config is sealed to it). The agent polls; the Hub
// never connects to a server.
model Server {
id String @id
name String
mode ServerMode @default(church)
hostname String?
ed25519Key String
x25519Key String
// Server configuration (§5): database host, port and admin, TRUST_PROXY, … AES-GCM encrypted
// JSON (utils/crypto.js); sealed to the server's key in each job that needs it.
config String?
agentVersion String?
lastSeenAt DateTime?
// The latest stats (crosscode.agent-stats/1), for the Servers page.
lastStats Json?
joinedAt DateTime @default(now())
removedAt DateTime?
notes String?
stats ServerStat[]
jobs Job[]
deployments Deployment[]
ports Port[]
alerts ServerAlert[]
}
// One-time join tokens (Servers → Add server), valid an hour. Only the hash is kept.
model ServerJoinToken {
id String @id @default(uuid())
tokenHash String @unique
name String
mode ServerMode @default(church)
expiresAt DateTime
usedAt DateTime?
serverId String?
createdById String?
createdAt DateTime @default(now())
}
enum StatGranularity {
minute
hour
}
// Server stats: one row a minute for 7 days, then one an hour (average and peak) for 90 days.
model ServerStat {
id String @id @default(uuid())
serverId String
server Server @relation(fields: [serverId], references: [id], onDelete: Cascade)
at DateTime
granularity StatGranularity @default(minute)
cpuPercent Float
cpuPeak Float
ramUsedPercent Float
ramPeak Float
ramUsedBytes BigInt
ramTotalBytes BigInt
diskUsedPercent Float
load1 Float
@@index([serverId, granularity, at])
}
// Open problems on a server (agent silent, disk, RAM, a process restarting, frpc, the central
// checks). Emailed once when they start and once when they clear.
model ServerAlert {
id String @id @default(uuid())
serverId String
server Server @relation(fields: [serverId], references: [id], onDelete: Cascade)
type String
level EventLevel @default(warning)
message String
createdAt DateTime @default(now())
resolvedAt DateTime?
@@index([serverId, resolvedAt])
}
enum DeploymentStatus {
installing
waiting_for_proxy
live
failed
uninstalling
removed
}
// A product installed on a server through the agent (or an existing install linked to it): the
// church's short name, domain and tunnel ports. Linked to its Install once the site registers.
model Deployment {
id String @id @default(uuid())
serverId String
server Server @relation(fields: [serverId], references: [id], onDelete: Restrict)
customerId String
customer Customer @relation(fields: [customerId], references: [id], onDelete: Restrict)
licenceId String?
installId String? @unique
install Install? @relation(fields: [installId], references: [id], onDelete: SetNull)
product Product @default(events)
// Folders, PM2, database and tunnel names on the server: hope → /var/www/sites/hope/events.
shortName String
domain String
webPort Int
apiPort Int
timezone String?
// The church's site admin, for the welcome and update emails.
adminName String?
adminEmail String?
status DeploymentStatus @default(installing)
// The release it runs (from reports and heartbeats).
version String?
liveAt DateTime?
removedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
jobs Job[]
exports Export[]
@@unique([shortName, product])
@@index([serverId])
}
enum JobStatus {
// Waiting for its time (a scheduled update, or a batch's later installs).
scheduled
// Due: handed to the agent on its next poll.
queued
delivered
succeeded
failed
rolled_back
refused
expired
// Its time passed before the agent picked it up: nothing ran.
missed
cancelled
}
// A signed job for a server's agent (crosscode.agent-job/1) and its report.
model Job {
id String @id
serverId String
server Server @relation(fields: [serverId], references: [id], onDelete: Restrict)
deploymentId String?
deployment Deployment? @relation(fields: [deploymentId], references: [id], onDelete: SetNull)
type String
args Json
status JobStatus @default(queued)
notBefore DateTime
expiresAt DateTime
// An update with notice to the church (§8); emergency = at least 15 minutes, with a reason.
scheduled Boolean @default(false)
emergency Boolean @default(false)
reason String?
// A batch runs its jobs one at a time and stops at the first failure.
batchId String?
batchOrder Int?
// The notice (banner) for a scheduled job, removed when it's done or cancelled.
noticeId String?
remindedAt DateTime?
createdById String?
deliveredAt DateTime?
finishedAt DateTime?
// crosscode.agent-report/1 (without the export key).
report Json?
message String?
createdAt DateTime @default(now())
@@index([serverId, status, notBefore])
@@index([batchId])
@@index([status, expiresAt])
}
// The port list (§6): every port frps opens on the central server, unique across servers.
model Port {
port Int @id
serverId String?
server Server? @relation(fields: [serverId], references: [id], onDelete: SetNull)
deploymentId String?
// web, api, or taken (found in use / reserved by hand).
role String
note String?
// Free again 30 days after an uninstall.
releasedAt DateTime?
createdAt DateTime @default(now())
@@index([serverId])
}
// A church's data when it leaves (§9): encrypted on the server with a key only in the emailed
// link, so the Hub stores it but can't read it. Deleted after 30 days (extendable once).
model Export {
id String @id
deploymentId String?
deployment Deployment? @relation(fields: [deploymentId], references: [id], onDelete: SetNull)
data Bytes?
bytes Int @default(0)
expiresAt DateTime
extended Boolean @default(false)
downloadedAt DateTime?
deletedAt DateTime?
createdAt DateTime @default(now())
}