Files
calvana/pledge-now-pay-later/prisma/schema.prisma
Omair Saleh c52c97df17 Automations engine: multi-channel messaging + dashboard
THE STAR OF THE SHOW — the automation engine is now visible.

## New: Unified Messaging Layer (src/lib/messaging.ts)
Channel waterfall: WhatsApp → SMS → Email
- sendToDonor() routes to best available channel
- Respects donor consent flags (whatsappOptIn, emailOptIn)
- Falls back automatically if primary channel fails
- Every attempt logged to AnalyticsEvent for dashboard

## New: Email Integration (src/lib/email.ts)
Bring-your-own-key: charity pastes their Resend or SendGrid API key
- Resend: free 3,000 emails/month
- SendGrid: free 100/day
- Messages come from THEIR domain (donations@mymosque.org)
- Plain text auto-converted to clean HTML

## New: SMS Integration (src/lib/sms.ts)
Bring-your-own-key: charity pastes their Twilio credentials
- Pay-as-you-go (~3p per SMS)
- UK number normalization (07xxx → +447xxx)
- Reaches donors without WhatsApp or email

## New: /dashboard/automations — the visible engine
A. Dark hero stats: Messages this week per channel + delivery rate
B. Live channels: WhatsApp/Email/SMS with status, features, stats
C. The Pipeline: visual 4-step automation sequence
   - What triggers, what's sent, which channels, waterfall explanation
D. Scheduled reminders: upcoming messages with timing
E. Message feed: recent messages with channel icon, status, time

## New: /api/messaging/status — dashboard data endpoint
Returns channels, stats (7 day), history (50 recent), pending reminders

## New: /api/messaging/test — send test message to admin

## Schema: 8 new Organization columns
emailProvider, emailApiKey, emailFromAddress, emailFromName
smsProvider, smsAccountSid, smsAuthToken, smsFromNumber

## Settings: 2 new channel rows in the checklist
- Email: provider selector (Resend/SendGrid) + API key + from address
- SMS: Twilio credentials + from number
Both follow the same checklist expand/collapse pattern

## Nav: Automations added between Money and Reports
Home → Collect → Money → Automations → Reports → Settings

## Stats tracking
Messages logged as AnalyticsEvent:
  message.whatsapp.receipt.sent
  message.email.reminder_1.failed
  message.sms.reminder_2.sent
Donor PII masked in logs (last 4 digits of phone, email obfuscated)
2026-03-04 23:20:50 +08:00

251 lines
8.0 KiB
Plaintext

generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}
model Organization {
id String @id @default(cuid())
name String
slug String @unique
orgType String @default("charity") // charity | fundraiser
country String @default("UK")
timezone String @default("Europe/London")
bankName String?
bankSortCode String?
bankAccountNo String?
bankAccountName String?
refPrefix String @default("PNPL")
logo String?
primaryColor String @default("#1e40af")
gcAccessToken String?
gcEnvironment String @default("sandbox")
stripeSecretKey String?
stripeWebhookSecret String?
emailProvider String? // resend, sendgrid, smtp
emailApiKey String?
emailFromAddress String? // e.g. donations@mymosque.org
emailFromName String? // e.g. "Al Furqan Mosque"
smsProvider String? // twilio
smsAccountSid String?
smsAuthToken String?
smsFromNumber String? // e.g. +447123456789
whatsappConnected Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
users User[]
events Event[]
pledges Pledge[]
imports Import[]
@@index([slug])
}
model User {
id String @id @default(cuid())
email String @unique
name String?
hashedPassword String?
role String @default("staff") // super_admin, org_admin, staff, volunteer
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([organizationId])
}
model Event {
id String @id @default(cuid())
name String
slug String
description String?
eventDate DateTime?
location String?
goalAmount Int? // in pence
currency String @default("GBP")
status String @default("active") // draft, active, closed, archived
paymentMode String @default("self") // self = we show bank details, external = redirect to URL
externalUrl String? // e.g. https://launchgood.com/my-campaign
externalPlatform String? // launchgood, enthuse, justgiving, gofundme, other
zakatEligible Boolean @default(false) // is this campaign Zakat-eligible?
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
qrSources QrSource[]
pledges Pledge[]
@@unique([organizationId, slug])
@@index([organizationId, status])
}
model QrSource {
id String @id @default(cuid())
label String // "Table 5", "Volunteer: Ahmed"
code String @unique // short token for URL
volunteerName String?
tableName String?
eventId String
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
scanCount Int @default(0)
createdAt DateTime @default(now())
pledges Pledge[]
@@index([eventId])
@@index([code])
}
model Pledge {
id String @id @default(cuid())
reference String @unique // human-safe bank ref e.g. "PNPL-7K4P-50"
amountPence Int
currency String @default("GBP")
rail String // bank, gocardless, card
status String @default("new") // new, initiated, paid, overdue, cancelled
donorName String?
donorEmail String?
donorPhone String?
// --- Home address (required by HMRC for Gift Aid claims) ---
donorAddressLine1 String?
donorPostcode String?
// --- Gift Aid (HMRC) ---
giftAid Boolean @default(false)
giftAidAt DateTime? // when the declaration was made
isZakat Boolean @default(false) // donor marked this as Zakat
// --- Communication consent (GDPR / PECR) ---
emailOptIn Boolean @default(false)
whatsappOptIn Boolean @default(false)
// --- Consent audit trail (immutable evidence) ---
// Stores exact text shown, timestamps, IP, user agent per consent type
consentMeta Json?
iPaidClickedAt DateTime?
notes String?
// Payment scheduling — the core of "pledge now, pay later"
dueDate DateTime? // null = pay now, set = promise to pay on this date
planId String? // groups installments together
installmentNumber Int? // e.g. 1 (of 4)
installmentTotal Int? // e.g. 4
reminderSentForDueDate Boolean @default(false)
eventId String
event Event @relation(fields: [eventId], references: [id])
qrSourceId String?
qrSource QrSource? @relation(fields: [qrSourceId], references: [id])
organizationId String
organization Organization @relation(fields: [organizationId], references: [id])
paymentInstruction PaymentInstruction?
payments Payment[]
reminders Reminder[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
paidAt DateTime?
cancelledAt DateTime?
@@index([organizationId, status])
@@index([reference])
@@index([eventId, status])
@@index([donorEmail])
@@index([donorPhone])
@@index([dueDate, status])
@@index([planId])
}
model PaymentInstruction {
id String @id @default(cuid())
pledgeId String @unique
pledge Pledge @relation(fields: [pledgeId], references: [id], onDelete: Cascade)
bankReference String // the unique ref to use
bankDetails Json // {sortCode, accountNo, accountName, bankName}
gcMandateId String?
gcMandateUrl String?
sentAt DateTime?
createdAt DateTime @default(now())
@@index([bankReference])
}
model Payment {
id String @id @default(cuid())
pledgeId String
pledge Pledge @relation(fields: [pledgeId], references: [id], onDelete: Cascade)
provider String // bank, gocardless, stripe
providerRef String? // external ID
amountPence Int
status String @default("pending") // pending, confirmed, failed
matchedBy String? // auto, manual
receivedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
importId String?
import Import? @relation(fields: [importId], references: [id])
@@index([pledgeId])
@@index([providerRef])
}
model Reminder {
id String @id @default(cuid())
pledgeId String
pledge Pledge @relation(fields: [pledgeId], references: [id], onDelete: Cascade)
step Int // 0=instructions, 1=nudge, 2=urgency, 3=final
channel String @default("email") // email, sms, whatsapp
scheduledAt DateTime
sentAt DateTime?
status String @default("pending") // pending, sent, skipped, failed
payload Json?
createdAt DateTime @default(now())
@@index([pledgeId])
@@index([scheduledAt, status])
}
model Import {
id String @id @default(cuid())
organizationId String
organization Organization @relation(fields: [organizationId], references: [id])
kind String // bank_statement, gocardless_export, crm_export
fileName String?
rowCount Int @default(0)
matchedCount Int @default(0)
unmatchedCount Int @default(0)
mappingConfig Json?
stats Json?
status String @default("pending") // pending, processing, completed, failed
uploadedAt DateTime @default(now())
payments Payment[]
@@index([organizationId])
}
model AnalyticsEvent {
id String @id @default(cuid())
eventType String // pledge_start, amount_selected, rail_selected, identity_submitted, pledge_completed, instruction_copy_clicked, i_paid_clicked, payment_matched
pledgeId String?
eventId String?
qrSourceId String?
metadata Json?
createdAt DateTime @default(now())
@@index([eventType])
@@index([pledgeId])
@@index([eventId])
@@index([createdAt])
}