// 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 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 (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 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()) // 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? 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) }