Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/prisma/schema/email-inbox.prisma
T
2026-07-08 16:15:37 +02:00

224 lines
9.3 KiB
Plaintext

// VA-P23 (P23) Postfach-Sync (Gmail/Outlook) — aligned to ENTITY-MODEL Domäne 8
// (M09-email-inbox, OAuth-sync/inbox/threading recut only; the v1 sending domain
// in email.prisma is NOT touched — outbound mail goes through the user mailbox).
//
// AD-21: self-contained schema. `tenantId` / `userId` are BARE String scalars
// (no `@relation` to Tenant/User) → zero merge-conflict surface against
// core.prisma/accounts.prisma. Intra-module relations (Mailbox → Message /
// SyncCursor / WebhookEvent) stay inside this file. Matched CRM entities
// (Kontakt/Lead/Projekt, AD-20 — no "Deal" FK) are bare scalars as well.
//
// A mailbox is PER-USER: each user connects their own Gmail/Microsoft account.
// OAuth refresh/access tokens are stored ENVELOPE-ENCRYPTED via the per-tenant
// DEK seam (AD-8, packages/db/src/crypto/tenant-envelope.server.ts), never plain.
//
// RLS ships separately in prisma/rls/email-inbox-isolation.sql (deferred cutover
// like the other modules). On the feature branch: `prisma db push` only — the
// merge migration is created at main-merge (AD-21). Visibility: email.read_own
// restricts list + activity to mailboxes with ownerUserId = self (M09 Block I).
/// Mailbox provider. Both land in v2 (M096/M097).
enum EmailInboxProvider {
gmail
microsoft
}
/// Lifecycle status of a connected mailbox (M09 Block B/D).
enum EmailMailboxStatus {
connecting
active
paused
error
revoked
}
/// Direction of a mirrored message.
enum EmailDirection {
inbound
outbound
}
/// How the CRM link on a message came to be (M09 Block E).
enum EmailMatchConfidence {
high
medium
low
manual
none
}
/// Initial 90-day sync lifecycle (resumable, M09 Block D).
enum EmailInitialSyncStatus {
pending
running
completed
failed
}
/// Worker processing state of an inbound provider push (M09 Block D).
enum EmailWebhookProcessingStatus {
pending
processing
completed
failed
skipped
}
/// A user's connected mailbox. PER-USER, tenant-scoped. OAuth tokens are
/// AES-256-GCM per-tenant-DEK envelopes (AD-8); never selected into a list
/// view-model. `webhookClientState` is the per-mailbox shared secret echoed by
/// Microsoft Graph notifications (its only auth mechanism) and doubles as the
/// Gmail channel verification token. `dataConnectionId` is an OPTIONAL read-only
/// reference to the Apps-Engine DataConnection catalog entry (bare scalar).
model EmailIntegrationMailbox {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
ownerUserId String
provider EmailInboxProvider
// User-visible account identity (connection card + Gmail push lookup).
emailAddress String
externalAccountId String
displayName String?
// Sensitive: per-tenant envelope ciphertext (AD-8). Never serialised to a VM.
oauthRefreshTokenCiphertext String?
oauthAccessTokenCiphertext String?
oauthAccessTokenExpiresAt DateTime?
// Granted OAuth scopes; a reduction by the user triggers a Klartext re-connect.
oauthScopes String[]
// Provider push handle: Gmail watch (historyId anchor lives in the cursor) or
// Graph subscription id. Gmail watches expire after ~7d, Graph after ~3d —
// one renewal cron covers BOTH providers via webhookSubscriptionExpiresAt.
webhookSubscriptionId String?
webhookSubscriptionExpiresAt DateTime?
webhookClientState String?
isDefaultForUser Boolean @default(false)
status EmailMailboxStatus @default(connecting)
lastSyncAt DateTime?
// Klartext failure detail when status = error (M002).
lastErrorText String?
// Read-only Apps-Engine catalog reference (AD-21 bare scalar, optional).
dataConnectionId String?
isDemoData Boolean @default(false)
archivedAt DateTime?
messages EmailIntegrationMessage[]
syncCursors EmailIntegrationSyncCursor[]
webhookEvents EmailIntegrationWebhookEvent[]
@@unique([tenantId, ownerUserId, provider, externalAccountId])
@@index([tenantId, ownerUserId, status, archivedAt])
// Gmail Pub/Sub pushes carry only {emailAddress, historyId} → address lookup.
@@index([tenantId, emailAddress])
// Renewal cron scans both providers by expiry; stale-poll fallback by lastSyncAt.
@@index([tenantId, webhookSubscriptionExpiresAt])
@@index([tenantId, status, lastSyncAt])
}
/// Mirror of a provider message. Tenant-scoped; visibility is owner-filtered in
/// code (email.read_own vs read_all). Archiving is HiveGrid-side only — the
/// provider mailbox is never mutated by archive. `internetMessageId` (RFC 5322)
/// is the cross-provider dedupe key: Graph sendMail returns 202 without an id,
/// so the sent-items delta re-ingest must collapse onto the local outbound mirror.
model EmailIntegrationMessage {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
mailboxId String
providerMessageId String
providerThreadId String?
internetMessageId String?
direction EmailDirection
fromAddress String
fromName String?
toAddresses Json @default("[]")
ccAddresses Json @default("[]")
bccAddresses Json @default("[]")
subject String?
// First ~140 chars of the text body for the list view (no body decrypt/parse).
snippet String?
bodyHtml String?
bodyText String?
sentAt DateTime
receivedAt DateTime?
isRead Boolean @default(false)
isStarred Boolean @default(false)
// List-Unsubscribe header present → flagged, excluded from auto-match (M09 E).
isNewsletter Boolean @default(false)
hasAttachments Boolean @default(false)
providerLabels Json @default("[]")
// AD-20 match targets (bare scalars — crm.prisma/leads.prisma/projekt.prisma).
matchedKontaktId String?
matchedLeadId String?
matchedProjektId String?
matchConfidence EmailMatchConfidence @default(none)
// A manual override wins and blocks any re-match (M09 Block E).
manualOverrideAt DateTime?
manualOverrideUserId String?
isDemoData Boolean @default(false)
archivedAt DateTime?
mailbox EmailIntegrationMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)
@@unique([tenantId, mailboxId, providerMessageId])
@@index([tenantId, mailboxId, sentAt(sort: Desc)])
@@index([tenantId, providerThreadId])
@@index([tenantId, internetMessageId])
@@index([tenantId, matchedKontaktId, sentAt(sort: Desc)])
@@index([tenantId, matchedLeadId, sentAt(sort: Desc)])
@@index([tenantId, matchedProjektId, sentAt(sort: Desc)])
@@index([tenantId, fromAddress])
}
/// Per-mailbox-per-folder delta cursor. Gmail uses ONE pseudo-folder (`*`,
/// historyId is mailbox-global); Microsoft Graph delta is PER FOLDER (inbox +
/// sentitems each get a cursor). `initialSyncProgress` keeps pageToken /
/// fetchedCount / oldestFetchedAt so an aborted 90-day initial sync resumes.
model EmailIntegrationSyncCursor {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
mailboxId String
externalFolderId String
// Gmail historyId / Graph deltaToken for incremental pulls.
cursorToken String?
initialSyncStatus EmailInitialSyncStatus @default(pending)
initialSyncProgress Json?
lastCursorAdvanceAt DateTime?
lastFullSyncAt DateTime?
// Klartext failure detail when initialSyncStatus = failed (M002).
errorText String?
mailbox EmailIntegrationMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)
@@unique([mailboxId, externalFolderId])
@@index([tenantId, mailboxId])
@@index([tenantId, initialSyncStatus])
}
/// Persisted inbound provider push (idempotency + retry). Append-only; a fast
/// 200/202 is returned to the provider and a worker drains `pending` rows.
/// Retention: 30 days (failed rows 90 days) via the cleanup cron.
model EmailIntegrationWebhookEvent {
id String @id @default(cuid())
receivedAt DateTime @default(now())
tenantId String
mailboxId String
provider EmailInboxProvider
notificationPayload Json
processingStatus EmailWebhookProcessingStatus @default(pending)
processingErrorText String?
processedAt DateTime?
// Which EmailIntegrationMessage ids were derived from this push.
derivedMessageIds Json @default("[]")
mailbox EmailIntegrationMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)
@@index([tenantId, processingStatus, receivedAt])
@@index([tenantId, mailboxId])
@@index([receivedAt])
}