Files
crosscode-platform/apps/app/backend/prisma/schema.prisma
T
joshuaandClaude Opus 5.5 8bfd0b767d app: email and WhatsApp's backend (APP-1.0-PLAN §8)
The church's one set of settings from Accounts (messaging.get; the SMTP
password and WAWP token sealed with the link's secret, kept encrypted in
AppSetting messaging_settings), fetched when the App links to Accounts, on
Accounts' signed messaging.changed, once a day and on the admin's Fetch again.

messages-send (every minute): the outbox by email (nodemailer) and WhatsApp
(WAWP), STOP checked before every WhatsApp (the member and anyone with the
same number), email instead for what a member asked for (never
announcements), retries after 2, 4, 8 and 16 minutes, a reminder never after
its slot started, nothing more than 3 days late. announcement-sends and
devotional-sends queue "Also send it" at the publish time and today's
devotional at each member's time. Members' choices (NotificationSettings),
news consent kept from Accounts, MessageCount for the heartbeat's messages,
the admin's Email and WhatsApp API with Send a test.

Migration messaging (checked on PostgreSQL 18). 110 backend tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 14:29:13 +02:00

544 lines
20 KiB
Plaintext

// Church App 1.0.0 (docs/APP-1.0-PLAN.md). One database per church.
//
// The foundation (§1, §2, §10, §12): members and their roles, sessions, links to the church's other
// products, the audit log and settings. The modules' tables (House of Prayer, prayer requests,
// announcements, devotionals, events) come with each module. Shared facts (name, logo, colours,
// timezone, contact) are the church profile's, in Accounts (§9), and are never stored here.
generator client {
provider = "prisma-client"
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
output = "../src/generated/prisma"
moduleFormat = "esm"
importFileExtension = "js"
}
datasource db {
provider = "postgresql"
}
/// The App's roles above Member (§10). Held here, per product: an Events or Website role gives
/// nothing in the App. A person can have several; every one of them needs 2FA (§2, decision 7).
enum AppRole {
owner
church_admin
content_admin
devotional_writer
prayer_coordinator
pastoral_care
}
/// Someone who has signed in to the App: keyed by their account's `sub` from Accounts. Everyone
/// signed in is a Member; `roles` adds what the admin can do. A copy of the Accounts profile, kept
/// up to date by `user.updated`.
model Member {
id String @id
name String
email String
/// The verified number from Accounts (reminders by WhatsApp), or null.
phone String?
/// The person replied STOP to the church's WhatsApp number (decision 11): no WhatsApp of any kind.
whatsappOptedOut Boolean @default(false)
/// News consent from Accounts (`news_consent`): announcements the church sends go only on these (§8).
newsEmail Boolean @default(false)
newsWhatsApp Boolean @default(false)
roles AppRole[] @default([])
/// The last day they used the App signed in (written at most once a day): active members (§10).
lastActiveAt DateTime?
lastSignInAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
sessions Session[]
prayerCommitments PrayerCommitment[]
testimonies Testimony[]
outboxMessages OutboxMessage[]
prayerRequests PrayerRequest[]
notifications NotificationSettings?
@@index([lastActiveAt])
}
/// A sign-in (the `cca_session` cookie holds the token; only its SHA-256 is kept). It lasts 8 days,
/// renewed by each visit, and never past `absoluteExpiresAt`, 90 days from the sign-in (§2).
/// `sid` is Accounts' session id, so a back-channel logout ends the matching sessions.
model Session {
id String @id @default(uuid())
tokenHash String @unique
memberId String
member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
sid String?
/// Whether Accounts did a second step for this sign-in (`amr` has `mfa`): needed for any role.
mfa Boolean @default(false)
/// The ID token (encrypted), for "Sign out" at Accounts (`id_token_hint`).
idToken String?
createdAt DateTime @default(now())
lastSeenAt DateTime @default(now())
expiresAt DateTime
absoluteExpiresAt DateTime
@@index([memberId])
@@index([sid])
}
/// A link to another of the church's products (`crosscode.link/1`): Accounts, for signing in and
/// the shared email and WhatsApp settings, and Events / the Website for the event feed (§7, §8).
/// The secret is encrypted.
model ProductLink {
installId String @id
product String
url String
publicKey String
secret String
connectedAt DateTime @default(now())
connectedById String?
/// Show this sibling's events in the App (the event feed, §7). Accounts has none.
showEvents Boolean @default(true)
lastSyncAt DateTime?
lastGoodAt DateTime?
lastSyncError String?
updatedAt DateTime @updatedAt
importedEvents ImportedEvent[]
}
/// Nonces of link messages seen in the last hour (replays are refused).
model LinkNonce {
nonce String @id
seenAt DateTime @default(now())
}
/// Who changed what in the admin (§10, Audit log).
model AuditLog {
id String @id @default(uuid())
actorId String?
actorRole String
action String
targetType String
targetId String?
metadata Json?
ip String?
createdAt DateTime @default(now())
@@index([createdAt])
}
model AppSetting {
key String @id
value String
updatedAt DateTime @updatedAt
}
// ── House of Prayer (§3) ─────────────────────────────────────────────────────────────────────
// The wall's rules (slot length, target, booking limits, the cancel window, the coordinator to
// contact) are in AppSetting `prayer_wall`. Days are local dates (YYYY-MM-DD) in the church's
// timezone; minutes are after local midnight (src/prayer/rules.ts).
enum PrayerRecurrence {
once
daily
weekly
}
/// When a member is reminded of a slot (P6): none, 15 minutes or an hour before, or 20:00 the evening before.
enum PrayerReminder {
none
min15
hour1
evening
}
/// How a member is reached for one kind of message (§8).
enum MessageChannel {
email
whatsapp
both
}
/// A commitment to pray: a rule (start, length, recurrence, end) plus the dates skipped, never a
/// row per occurrence (§3). The member's name is never in coverage; only the prayer team sees it.
model PrayerCommitment {
id String @id @default(uuid())
/// Null once the member deleted their account: past occurrences stay as counts only (§11).
memberId String?
member Member? @relation(fields: [memberId], references: [id], onDelete: SetNull)
/// The first local date it happens on (a weekly rule keeps this date's weekday).
startDate String
/// Minutes after local midnight (02:00 = 120), on a slot boundary when booked.
startMinute Int
durationMinutes Int
recurrence PrayerRecurrence
/// The last local date with an occurrence (a once rule: its start date).
endDate String
reminder PrayerReminder @default(hour1)
/// Reminders and renewal notices for this commitment.
channel MessageChannel @default(email)
/// "Where I'll pray", for the member alone.
note String?
/// A prayer coordinator who booked it on the member's behalf.
bookedById String?
/// Renewal notices sent for the current end date: 0, 1 (14 days before) or 2 (3 days before).
renewalNoticesSent Int @default(0)
renewedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
skips PrayerSkip[]
marks PrayedMark[]
@@index([endDate])
@@index([memberId])
}
/// One occurrence skipped ("Skip 14 December").
model PrayerSkip {
id String @id @default(uuid())
commitmentId String
commitment PrayerCommitment @relation(fields: [commitmentId], references: [id], onDelete: Cascade)
date String
createdAt DateTime @default(now())
@@unique([commitmentId, date])
}
/// "I prayed" for one occurrence: self-reported, counted as a number only, never a ranking (§3).
model PrayedMark {
id String @id @default(uuid())
commitmentId String
commitment PrayerCommitment @relation(fields: [commitmentId], references: [id], onDelete: Cascade)
memberId String?
date String
createdAt DateTime @default(now())
@@unique([commitmentId, date])
@@index([date])
}
/// A time-bound focus ("21 days of prayer", P7): collective coverage and hours prayed only.
model PrayerCampaign {
id String @id @default(uuid())
title String
description String
imageUrl String?
startDate String
endDate String
/// "Every hour covered", shown as the campaign's aim.
goal String?
/// The campaign's own people per slot, instead of the wall's target, while it runs.
targetPerSlot Int?
createdById String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
testimonies Testimony[]
@@index([endDate])
}
enum TestimonyStatus {
pending
approved
removed
}
/// What God has done, shared by a member: moderated before anyone sees it, the first name or
/// "Anonymous", removable by its author at any time (§3). Deleted with the account (§11).
model Testimony {
id String @id @default(uuid())
memberId String
member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
campaignId String?
campaign PrayerCampaign? @relation(fields: [campaignId], references: [id], onDelete: SetNull)
text String
showName Boolean @default(false)
status TestimonyStatus @default(pending)
/// Why a coordinator removed it (sent to the author).
removedReason String?
moderatedById String?
moderatedAt DateTime?
createdAt DateTime @default(now())
@@index([status, createdAt])
}
/// Who saw names (§3, §10 Access log): every view of bookings with names, and later of prayer requests.
model AccessLog {
id String @id @default(uuid())
actorId String
action String
targetType String
targetId String?
metadata Json?
ip String?
createdAt DateTime @default(now())
@@index([createdAt])
}
/// Email and WhatsApp to send (§8): reminders, renewal notices, the prayer team's and submitters'
/// notices, announcements and devotionals. Written once (`dedupeKey`), sent by the `messages-send`
/// job with the church's settings from Accounts; what's in `payload` is the message's facts only
/// (never a prayer request's text). `sentVia` says what went (`email`, `whatsapp`, `email,whatsapp`,
/// or `none` when there was nothing to send it on); `error` why a channel didn't.
model OutboxMessage {
id String @id @default(uuid())
memberId String
member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
kind String
channel MessageChannel
payload Json
dedupeKey String @unique
sendAfter DateTime
sentAt DateTime?
sentVia String?
failedAt DateTime?
error String?
attempts Int @default(0)
createdAt DateTime @default(now())
@@index([sentAt, sendAfter])
}
// ── Email and WhatsApp (§8) ──────────────────────────────────────────────────────────────────
// The church's one set of settings comes from Accounts (`messaging.get`) and is kept encrypted in
// AppSetting `messaging_settings`; the App never asks for its own (decision 4).
/// How a member wants one kind of message: email, WhatsApp, both or not at all (§8).
enum NotifyChoice {
off
email
whatsapp
both
}
/// What a member chose the App sends them (§8). Prayer reminders and renewals follow each
/// commitment's own channel; these are the rest. No row: the defaults.
model NotificationSettings {
memberId String @id
member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
/// Approved, someone prayed, a reply (email by default).
requestUpdates NotifyChoice @default(email)
/// The announcements the church sends (off until the member turns them on, P13).
announcements NotifyChoice @default(off)
/// Today's devotional (offered at the first sign-in, §6).
devotional NotifyChoice @default(off)
/// When (HH:MM in the church's timezone), 06:00 by default.
devotionalTime String @default("06:00")
/// When the first-sign-in offer was answered or dismissed.
devotionalOfferedAt DateTime?
/// The last local day a devotional was queued for them (once a day).
lastDevotionalDate String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([devotional])
}
/// Messages sent per local day and channel, for the heartbeat (`messages.email30d`, `whatsapp30d`).
/// Counts only: kept when a member or their messages are deleted. `key` is `<day>:<channel>`.
model MessageCount {
key String @id
day String
channel String
count Int @default(0)
@@index([day])
}
// ── Prayer requests (§4) ─────────────────────────────────────────────────────────────────────
// Special personal information (POPIA s26): never in stats, the heartbeat, AI or an email's text.
// The rules (closing after 30 days, fully anonymous requests, emergency numbers) are in AppSetting
// `prayer_requests`. Every view of a request with its sender goes in the access log.
/// Who sees a request (P8): the prayer team only (the default), or members after approval.
enum RequestVisibility {
team
members
}
/// A shared request's moderation: waiting, approved (shown to members) or removed (with a reason).
/// Team-only requests are never moderated (`none`).
enum RequestModeration {
none
pending
approved
removed
}
model PrayerRequest {
id String @id @default(uuid())
memberId String
member Member @relation(fields: [memberId], references: [id], onDelete: Cascade)
text String
visibility RequestVisibility @default(team)
/// For members: show the submitter's first name (else "Anonymous").
showName Boolean @default(false)
/// Fully anonymous (P9, when the church allows it): the prayer team doesn't see who sent it either.
anonymous Boolean @default(false)
moderation RequestModeration @default(none)
/// A coordinator edited out names or details; the submitter is told what changed.
redactedAt DateTime?
redactionNote String?
removedReason String?
moderatedById String?
moderatedAt DateTime?
/// Safeguarding (§4): sent to Pastoral care at once; it leaves the shared list; the submitter sees nothing different.
escalatedAt DateTime?
escalatedById String?
escalationNote String?
/// Closes itself then (30 days by default), unless closed before.
closesAt DateTime
closedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
updates PrayerRequestUpdate[]
prayers RequestPrayer[]
@@index([moderation, createdAt])
@@index([memberId])
@@index([closedAt])
@@index([closesAt])
}
/// "Answered!" from the submitter (shown with the request), or a private reply from the prayer team
/// (to the submitter alone).
model PrayerRequestUpdate {
id String @id @default(uuid())
requestId String
request PrayerRequest @relation(fields: [requestId], references: [id], onDelete: Cascade)
/// `submitter` or `team`.
author String
authorId String?
text String
createdAt DateTime @default(now())
@@index([requestId, createdAt])
}
/// "I prayed" on a shared request: the submitter sees how many, never who.
model RequestPrayer {
id String @id @default(uuid())
requestId String
request PrayerRequest @relation(fields: [requestId], references: [id], onDelete: Cascade)
memberId String
createdAt DateTime @default(now())
@@unique([requestId, memberId])
}
// ── Announcements (§5) ───────────────────────────────────────────────────────────────────────
enum AnnouncementAudience {
everyone
members
}
/// News from the church: public ones are pages of their own (SEO, §11); members-only ones are noindex.
model Announcement {
id String @id @default(uuid())
slug String @unique
title String
/// Markdown, shown sanitised (no HTML).
body String
imageUrl String?
buttonLabel String?
buttonUrl String?
/// A campus's slug from the church profile, or null for every campus.
campus String?
audience AnnouncementAudience @default(everyone)
pinned Boolean @default(false)
/// Shown from then (now or later); a draft has none.
publishAt DateTime?
/// Hidden after this, if set.
endsAt DateTime?
/// Also send it at the publish time (to members who chose announcements, §8).
sendEmail Boolean @default(false)
sendWhatsApp Boolean @default(false)
/// When the sends were queued (once).
sentAt DateTime?
createdById String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([publishAt])
}
// ── Devotionals (§6) ─────────────────────────────────────────────────────────────────────────
// `crosscode.devotional/1`: Cross Code's (from the Hub, the next 2 weeks each night) and the
// church's own, side by side; Settings → Devotionals (AppSetting `devotionals_source`) picks which
// one shows. One per day per source.
enum DevotionalSource {
crosscode
church
}
model Devotional {
id String @id @default(uuid())
source DevotionalSource
/// The Hub's id for Cross Code's (`crosscode.devotional/1` `id`).
originId String?
/// The local day it's for (YYYY-MM-DD, the church's timezone).
date String
title String
reference String
/// `passageLocationSchema`: book, chapter and verses (for the YouVersion link).
location Json
translation String
passageText String
/// Markdown, shown sanitised.
body String
prayer String?
author String?
/// Only for signed-in members (noindex); public by default (§6).
membersOnly Boolean @default(false)
createdById String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([source, date])
@@index([date])
}
// ── Events (§7) ──────────────────────────────────────────────────────────────────────────────
// As the Website's: simple events made in the App, read-only copies of the siblings' events (the
// feed), and removals listed for 90 days.
model SimpleEvent {
id String @id @default(uuid())
slug String @unique
title String
startsAt DateTime
endsAt DateTime?
allDay Boolean @default(false)
timezone String @default("Africa/Johannesburg")
location String?
description String?
imageUrl String?
link String?
cancelled Boolean @default(false)
publishedAt DateTime?
updatedBy String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([startsAt])
}
model ImportedEvent {
id String @id @default(uuid())
linkId String
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
originProduct String
originId String
startsAt DateTime
endsAt DateTime
data Json
syncedAt DateTime @default(now())
@@unique([originProduct, originId])
@@index([startsAt])
@@index([linkId])
}
model FeedRemoval {
eventId String @id
removedAt DateTime @default(now())
}