Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -39,14 +39,6 @@ model User {
createdGroups Group[]
groups GroupUser[]
logs Log[]
createdRows Row[]
createdRowComments RowComment[]
createdRowCommentReactions RowCommentReaction[]
createdEntityViews EntityView[] @relation("createdByUser")
rowPermissions RowPermission[]
assignedTasks RowTask[] @relation("assignedToUser")
completedTasks RowTask[] @relation("completedByUser")
createdRowTasks RowTask[] @relation("createdByUser")
tenants TenantUser[]
invitation TenantUserInvitation? @relation("createdUser")
sentInvitations TenantUserInvitation[] @relation("fromUser")
@@ -54,12 +46,10 @@ model User {
revokedInvitations TenantUserInvitation[] @relation("revokedByUser")
roles UserRole[]
readEmails EmailRead[]
entityViews EntityView[]
onboardingSessions OnboardingSession[]
tenantIpAddresses TenantIpAddress[]
analyticsUniqueSessions AnalyticsUniqueVisitor[]
metricLogs MetricLog[]
formulaLogs FormulaLog[]
knowledgeBaseArticles KnowledgeBaseArticle[]
events Event[]
workflowsCreated Workflow[] @relation("createdByUser")
@@ -68,6 +58,9 @@ model User {
workflowCredentialsCreated WorkflowCredential[]
feedback Feedback[]
supportTickets SupportTicket[]
assignedSupportTickets SupportTicket[] @relation("supportTicketAssignee")
supportTicketMessages SupportTicketMessage[] @relation("supportTicketMessageAuthor")
adminTenantNotesAuthored AdminTenantNote[] @relation("adminTenantNoteAuthor")
credits Credit[]
portals Portal[]
impersonationAuditsActor ImpersonationAudit[] @relation("ImpersonationAuditActor")
@@ -79,8 +72,8 @@ model User {
deviceTokens DeviceToken[]
magicLinkTokens MagicLinkToken[]
appsInstalled App[] @relation("appInstalledByUser")
appSyncRuns AppSyncRun[] @relation("appSyncRunCreatedByUser")
// Apps-Engine (R-P5) uses bare String scalars for tenantId/createdByUserId
// (AD-21) — no back-relations here.
sitesCreated Site[] @relation("sitesCreatedByUser")
@@ -135,8 +128,6 @@ model Tenant {
apiKeyLogs ApiKeyLog[]
groups Group[]
logs Log[]
rows Row[]
rowPermissions RowPermission[]
subscription TenantSubscription?
productConfiguration TenantProductConfiguration?
featureOverrides TenantFeatureOverride[]
@@ -147,20 +138,15 @@ model Tenant {
inboundAddresses TenantInboundAddress[]
events Event[]
fromRegistration Registration?
entityViews EntityView[]
emailSenders EmailSender[]
campaigns Campaign[]
outboundEmails OutboundEmail[]
onboardingSessions OnboardingSession[]
onboardingDemoProvisionings OnboardingDemoProvisioning[]
ipAddresses TenantIpAddress[]
tenantSettingsRow TenantSettingsRow?
metricLogs MetricLog[]
formulaLogs FormulaLog[]
knowledgeBases KnowledgeBase[]
types TenantType[]
entityProperties Property[]
entityGroupConfigurations EntityGroupConfiguration[]
entityTemplates EntityTemplate[]
workflows Workflow[]
workflowExecutions WorkflowExecution[]
workflowVariables WorkflowVariable[]
@@ -172,6 +158,7 @@ model Tenant {
portalsUsers PortalUser[]
widgets Widget[]
impersonationAudits ImpersonationAudit[]
adminTenantNotes AdminTenantNote[]
notificationDeliveries NotificationDelivery[]
notificationPreferences UserNotificationPreference[]
deviceTokens DeviceToken[]
@@ -180,9 +167,13 @@ model Tenant {
theme String?
themeConfig String?
apps App[]
dataConnections DataConnection[]
appSyncRuns AppSyncRun[]
// Apps-Engine (R-P5): App is global; DataConnection/AppSyncRun use bare
// tenantId scalars (AD-21) — no back-relations here.
// Global du/Sie formality toggle (Anrede). Default "du" keeps the effective
// i18next language equal to the base locale, so existing rendering stays
// byte-identical; "sie" resolves to the "<locale>-formal" variant.
anrede String? @default("du")
sites Site[]
@@ -246,6 +237,10 @@ model TenantUser {
status Int
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([tenantId, userId])
@@index([userId])
@@index([tenantId, status])
}
model TenantUserInvitation {
@@ -0,0 +1,52 @@
// AK-P19 — Platform-Admin module (admin.hivegrid.de).
//
// Per AD-21 each module owns its own schema file. The platform-admin
// world is deliberately a *separate* world: these rows carry NO
// `tenant_id`-based RLS scoping of their own beyond a plain FK, because
// admin actions span tenants. Cross-tenant admin actions are recorded
// through the shared AuditEvent Querschnitt (tenantId=null,
// actorType="admin") — NOT a parallel audit table (see AK-P19 plan,
// DoD #7). v1 also reuses the boilerplate User model as the admin
// identity (AdminUser extension + admin-mfa-gate); the separate
// AdminUser/AdminRole/AdminSession identity is v2 (M038/M039).
/// AdminTenantNote — free-form operator notes pinned to a tenant.
/// ENTITY-MODEL Domäne 11: markdown note_text, category, pinned.
/// Written from the admin tenant-detail screen; every write also emits
/// an admin AuditEvent (tenantId=null, actorType="admin").
model AdminTenantNote {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
authorUserId String?
noteText String
category String @default("general")
pinned Boolean @default(false)
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
author User? @relation("adminTenantNoteAuthor", fields: [authorUserId], references: [id], onDelete: SetNull)
// Detail view lists pinned-first, newest-first, per tenant.
@@index([tenantId, pinned, createdAt], name: "admin_tenant_note_tenant_pinned_created_idx")
@@index([tenantId, category], name: "admin_tenant_note_tenant_category_idx")
}
/// SupportTicketMessage — conversation thread for the admin Support-Inbox.
/// Extends the existing helpDesk `SupportTicket` (which already carries
/// source/status/priority/tenant) with replies and internal notes.
/// `internalNote=true` rows are operator-only and never surfaced to the
/// tenant. A null author means an inbound message from the customer side.
model SupportTicketMessage {
id String @id @default(cuid())
createdAt DateTime @default(now())
supportTicketId String
authorUserId String?
body String
internalNote Boolean @default(false)
ticket SupportTicket @relation(fields: [supportTicketId], references: [id], onDelete: Cascade)
author User? @relation("supportTicketMessageAuthor", fields: [authorUserId], references: [id], onDelete: SetNull)
@@index([supportTicketId, createdAt], name: "support_ticket_message_ticket_created_idx")
}
@@ -1,96 +1,191 @@
// R-P5 (P5) Apps-Engine & Integrations-Framework — aligned to ENTITY-MODEL
// Domäne 4 (AD-20 Pivot-Vorrang). Replaces the stock boilerplate models.
//
// AD-21: self-contained schema. `tenantId` / `createdByUserId` are BARE String
// scalars (no `@relation` to Tenant/User) → zero merge-conflict surface against
// core.prisma/accounts.prisma. Intra-module relations (App→DataConnection→
// AppSyncRun→Log/Item) stay inside this file.
//
// `App` is GLOBAL (a definition/catalog table, no tenantId, no RLS). Everything
// tenant-facing (DataConnection + sync rows) is tenant-scoped + RLS
// (prisma/rls/apps-engine-isolation.sql, deferred activation like the other
// modules). Credentials are stored ENVELOPE-ENCRYPTED via the per-tenant DEK
// (R-P5 Phase 1: packages/db/src/crypto/tenant-envelope.server.ts), never plain.
//
// Scope (AD-26 recut): connection types oauth2 / api_key / rest_api only have a
// v1 flow; `windows_client` (KWP) stays in the datamodel but has NO v1 UI/logic.
// Concrete app adapters (Gmail/Outlook/AirCall/Mollie) belong to P14/P15/P16/P20,
// not here — P5 ships only the generic framework + the sample-data-sync adapter.
enum AppCategory {
erp
communication
calendar
signature
payment
ki
}
enum AppConnectionType {
oauth2
api_key
rest_api
windows_client
}
enum DataConnectionStatus {
pending
active
degraded
broken
revoked
}
enum AppSyncKind {
manual
scheduled
webhook
}
enum AppSyncStatus {
pending
running
completed
partial
failed
cancelled
}
enum AppSyncLogSeverity {
info
success
warning
error
}
enum AppSyncItemOperation {
created
updated
deleted
skipped
}
enum AppSyncItemStatus {
pending
synced
failed
skipped
}
/// Global catalog definition of an integratable app (no tenant, no RLS). The
/// `connectionSchema` drives the auto-generated credential form; `connectionType`
/// selects the connect flow. New apps are registered by the build-time adapter
/// scan + this catalog (drift-check warns in the platform admin).
model App {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
type String // App type identifier e.g., "sample-data-sync"
config String @default("{}") // JSON configuration
icon String?
isActive Boolean @default(true)
installedByUserId String?
installedByUser User? @relation("appInstalledByUser", fields: [installedByUserId], references: [id])
syncRuns AppSyncRun[]
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
key String @unique
title String
category AppCategory
connectionType AppConnectionType
connectionSchema Json @default("{}")
phase String?
icon String?
isActive Boolean @default(true)
@@unique([tenantId, type])
@@index([tenantId])
@@index([category])
}
/// A tenant's connection to an App. Multiple per (tenant, app) with a user
/// `label` (e.g. three Gmail mailboxes). Credentials live encrypted in
/// `credentialsCiphertext`. Disconnect sets `connectionStatus = revoked` (no
/// hard-delete → sync history preserved). Soft-delete via `archivedAt`.
model DataConnection {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
name String
type String // Connection type e.g., "rest-api", "oauth2", "webhook"
config String @default("{}") // Encrypted JSON credentials
description String?
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
// The app's stable catalog `key` (bare scalar per AD-21; matches the adapter
// registry + INTEGRATION_CATALOG). App is a global catalog, not an FK target.
appId String
label String
// AES-256-GCM per-tenant DEK envelope (AD-8). Never selected into list VMs.
credentialsCiphertext String?
connectionStatus DataConnectionStatus @default(pending)
lastHealthCheck DateTime?
// i18n key describing the current health state (Klartext, M002/M003).
healthMessageKey String?
tokenExpiresAt DateTime?
createdByUserId String?
isDemoData Boolean @default(false)
archivedAt DateTime?
@@index([tenantId])
syncRuns AppSyncRun[]
@@index([tenantId, appId, archivedAt])
@@index([tenantId, connectionStatus])
@@index([tenantId, tokenExpiresAt])
}
/// One sync run for a DataConnection. `summaryText` is the Klartext summary.
model AppSyncRun {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
appId String
app App @relation(fields: [appId], references: [id], onDelete: Cascade)
tenantId String
tenant Tenant @relation(fields: [tenantId], references: [id])
taskKey String // e.g., "sync-products"
taskName String // e.g., "Sync Products"
description String?
status String @default("pending") // pending, running, completed, partial, failed, cancelled, reverted
executionMode String @default("manual") // manual, scheduled, webhook
startedAt DateTime?
completedAt DateTime?
duration Int @default(0) // Duration in milliseconds
itemsProcessed Int @default(0)
itemsCreated Int @default(0)
itemsUpdated Int @default(0)
itemsFailed Int @default(0)
error String?
metadata String @default("{}")
createdByUserId String?
createdByUser User? @relation("appSyncRunCreatedByUser", fields: [createdByUserId], references: [id])
logs AppSyncRunLog[]
syncItems AppSyncItem[]
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
dataConnectionId String
kind AppSyncKind @default(manual)
status AppSyncStatus @default(pending)
itemsTotal Int @default(0)
itemsSucceeded Int @default(0)
itemsFailed Int @default(0)
summaryText String?
startedAt DateTime?
completedAt DateTime?
createdByUserId String?
@@index([appId, taskKey])
@@index([tenantId])
dataConnection DataConnection @relation(fields: [dataConnectionId], references: [id], onDelete: Cascade)
logs AppSyncRunLog[]
items AppSyncItem[]
@@index([tenantId, dataConnectionId, createdAt(sort: Desc)])
@@index([tenantId, status])
}
/// A log line of a sync run (Klartext `messageText` + optional `techDetails`).
model AppSyncRunLog {
id String @id @default(cuid())
createdAt DateTime @default(now())
syncRunId String
syncRun AppSyncRun @relation(fields: [syncRunId], references: [id], onDelete: Cascade)
type String @default("info") // info, success, warning, error
message String
metadata String?
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
syncRunId String
severity AppSyncLogSeverity @default(info)
messageText String
techDetails String?
@@index([syncRunId])
syncRun AppSyncRun @relation(fields: [syncRunId], references: [id], onDelete: Cascade)
@@index([tenantId, syncRunId])
}
/// A single synced object: maps a HiveGrid entity (`entityType`/`entityId`) to an
/// external system id (`externalId`). Polymorphic.
model AppSyncItem {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
syncRunId String
syncRun AppSyncRun @relation(fields: [syncRunId], references: [id], onDelete: Cascade)
objectType String // e.g., "product", "customer"
sourceId String // ID from external system
destinationId String? // ID in our system
description String?
status String @default("pending") // synced, failed, skipped, pending, reverted
action String? // created, updated, deleted, skipped
sourceData String // JSON of source data
destinationData String? // JSON of destination data
error String?
rolledBackData String? // JSON of rollback information
rolledBackAt DateTime?
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
syncRunId String
entityType String
entityId String?
externalId String
operation AppSyncItemOperation @default(created)
status AppSyncItemStatus @default(pending)
errorText String?
@@index([syncRunId])
@@index([objectType, sourceId])
syncRun AppSyncRun @relation(fields: [syncRunId], references: [id], onDelete: Cascade)
@@index([tenantId, syncRunId])
@@index([tenantId, entityType, entityId])
@@index([tenantId, externalId])
}
@@ -0,0 +1,363 @@
// R-P9a (P9 Auftrag view + project sub-areas).
//
// AD-20: order work is a view on the existing `Projekt` core, not a second
// project/order object and not a won-handoff copy. These rows are sub-areas
// addressed by `projektId` bare scalar.
//
// AD-21: this module owns its schema file. Cross-module references to Projekt,
// User, Group, File and Form are intentionally bare String scalars so this slice
// does not modify projekt/accounts/files/forms schemas.
enum ProjektMitgliedRolle {
monteur
projektleiter
zustaendig
beobachter
}
enum ProjektTerminStatus {
geplant
bestaetigt
erledigt
abgesagt
}
enum RechnungStatus {
entwurf
gestellt
bezahlt
storniert
}
enum RechnungQuelle {
manuell
kwp
}
enum ProjektChecklistTyp {
generisch
maengel
abnahme_doku
}
enum ProjektChecklistItemStatus {
offen
erledigt
entfaellt
}
enum ScheduleEntryStatus {
planned
confirmed
in_progress
done
cancelled
}
enum ScheduleConflictType {
double_booking
absence
availability
}
enum ScheduleConflictSeverity {
warning
blocking
}
enum ScheduleSyncStatus {
pending
synced
failed
}
enum AcceptanceKind {
full
with_defects
rejected
}
enum AcceptanceSignerRole {
kunde
monteur
}
enum OfflineSyncOperation {
schedule_upsert
schedule_status
acceptance_submit
}
enum OfflineSyncStatus {
pending
applied
failed
}
model ProjektMitglied {
id String @id @default(cuid())
tenantId String
projektId String
userId String?
groupId String?
rolle ProjektMitgliedRolle
createdByUserId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
@@index([tenantId, projektId, archivedAt])
@@index([tenantId, userId])
@@index([tenantId, groupId])
}
model ProjektTermin {
id String @id @default(cuid())
tenantId String
projektId String
createdByUserId String?
assignedToUserId String?
assignedToGroupId String?
titel String
beschreibung String?
startAt DateTime
endAt DateTime?
status ProjektTerminStatus @default(geplant)
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
@@index([tenantId, projektId, archivedAt, startAt])
@@index([tenantId, assignedToUserId])
@@index([tenantId, assignedToGroupId])
}
model Rechnung {
id String @id @default(cuid())
tenantId String
projektId String
createdByUserId String?
rechnungsnummer String
betrag Decimal
status RechnungStatus @default(entwurf)
datum DateTime @default(now())
faelligAm DateTime?
dateiId String?
quelle RechnungQuelle @default(manuell)
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
@@unique([tenantId, rechnungsnummer])
@@index([tenantId, projektId, archivedAt])
@@index([tenantId, status])
@@index([tenantId, dateiId])
}
model ProjektChecklist {
id String @id @default(cuid())
tenantId String
projektId String
createdByUserId String?
titel String
typ ProjektChecklistTyp @default(generisch)
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
items ProjektChecklistItem[]
@@index([tenantId, projektId, typ, archivedAt])
}
model ProjektChecklistItem {
id String @id @default(cuid())
tenantId String
checklistId String
titel String
status ProjektChecklistItemStatus @default(offen)
maengelKlasse String?
fotoFileId String?
assignedToUserId String?
dueAt DateTime?
position Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
checklist ProjektChecklist @relation(fields: [checklistId], references: [id], onDelete: Cascade)
@@index([tenantId, checklistId])
@@index([tenantId, status])
@@index([tenantId, fotoFileId])
}
model AuftragPipelineStageConfig {
id String @id @default(cuid())
tenantId String
pipelineId String
stageId String
requiresAcceptanceProtocol Boolean @default(false)
acceptanceFormTemplateId String?
autoArchiveAfterDays Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([tenantId, stageId])
@@index([tenantId, pipelineId])
@@index([tenantId, acceptanceFormTemplateId])
}
model AcceptanceFormTemplate {
id String @id @default(cuid())
tenantId String
name String
formId String?
definition Json @default("{}")
isDefault Boolean @default(false)
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
@@unique([tenantId, name])
@@index([tenantId, archivedAt])
@@index([tenantId, formId])
}
model ProjectTemplate {
id String @id @default(cuid())
tenantId String
name String
defaultPipelineId String?
defaultStageId String?
defaultMembers Json @default("[]")
defaultTasks Json @default("[]")
customFields Json @default("{}")
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
@@unique([tenantId, name])
@@index([tenantId, archivedAt])
@@index([tenantId, defaultPipelineId])
}
model ScheduleEntry {
id String @id @default(cuid())
tenantId String
projektId String
assignedUserId String
createdByUserId String?
title String
startAt DateTime
endAt DateTime
status ScheduleEntryStatus @default(planned)
calendarEventId String?
syncStatus ScheduleSyncStatus @default(pending)
conflictOverrideReason String?
clientMutationId String?
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
conflicts ScheduleConflict[]
@@unique([tenantId, clientMutationId])
@@index([tenantId, projektId, archivedAt])
@@index([tenantId, assignedUserId, startAt, endAt])
@@index([tenantId, status])
@@index([tenantId, calendarEventId])
}
model ScheduleConflict {
id String @id @default(cuid())
tenantId String
entryId String
type ScheduleConflictType
severity ScheduleConflictSeverity @default(warning)
messageKey String
sourceKind String?
sourceId String?
createdAt DateTime @default(now())
resolvedAt DateTime?
overriddenAt DateTime?
entry ScheduleEntry @relation(fields: [entryId], references: [id], onDelete: Cascade)
@@index([tenantId, entryId])
@@index([tenantId, type, resolvedAt])
}
model AbnahmeProtokoll {
id String @id @default(cuid())
tenantId String
projektId String
maengelChecklistId String?
createdByUserId String?
datum DateTime @default(now())
acceptanceKind AcceptanceKind
anwesende Json @default("[]")
druckprobe Json @default("{}")
funktionspruefung Json @default("{}")
zaehlerstaende Json @default("{}")
dokumente Json @default("[]")
bemerkungen String?
pdfFileId String?
customerEmail String?
customerEmailQueuedAt DateTime?
clientMutationId String?
gesperrtAt DateTime?
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
signatures AbnahmeSignatur[]
@@unique([tenantId, clientMutationId])
@@index([tenantId, projektId, archivedAt])
@@index([tenantId, maengelChecklistId])
@@index([tenantId, pdfFileId])
@@index([tenantId, acceptanceKind])
}
model AbnahmeSignatur {
id String @id @default(cuid())
tenantId String
protokollId String
signerName String
signerRole AcceptanceSignerRole
signatureFileId String?
signerIpHash String?
signedAt DateTime @default(now())
createdAt DateTime @default(now())
protokoll AbnahmeProtokoll @relation(fields: [protokollId], references: [id], onDelete: Restrict)
@@index([tenantId, protokollId])
@@index([tenantId, signatureFileId])
}
model OfflineSyncMutation {
id String @id @default(cuid())
tenantId String
clientMutationId String
createdByUserId String?
operation OfflineSyncOperation
payload Json
status OfflineSyncStatus @default(pending)
resultEntityType String?
resultEntityId String?
errorMessageKey String?
createdAt DateTime @default(now())
appliedAt DateTime?
@@unique([tenantId, clientMutationId])
@@index([tenantId, createdByUserId, createdAt])
@@index([tenantId, status])
}
@@ -0,0 +1,191 @@
// R-P12a (P12 Automation) — typed automation engine foundation.
//
// AD-21: self-contained schema. User references are bare String scalars so the
// automation slice does not touch accounts/core back-relations while P12b can
// add the visual editor on top of these contracts.
enum AutomationRuleStatus {
draft
active
paused
archived
}
enum AutomationStepKind {
trigger
condition
action
flow_control
}
enum AutomationExecutionStatus {
queued
running
success
failed
paused
waiting
skipped
retrying
}
model AutomationRule {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
name String
description String?
status AutomationRuleStatus @default(draft)
enabled Boolean @default(false)
createdVia String @default("manual")
triggerKey String?
flowData Json @default("{}")
createdByUserId String?
isDemoData Boolean @default(false)
archivedAt DateTime?
steps AutomationRuleStep[]
executions AutomationExecution[]
@@unique([tenantId, name])
@@index([tenantId, status, enabled, archivedAt])
@@index([tenantId, triggerKey, enabled, archivedAt])
}
model AutomationRuleStep {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
ruleId String
stepKey String
stepKind AutomationStepKind
nodeType String
config Json @default("{}")
parentStepIds String[] @default([])
position Json @default("{}")
sortOrder Int @default(0)
summaryText String?
isDemoData Boolean @default(false)
rule AutomationRule @relation(fields: [ruleId], references: [id], onDelete: Cascade)
stepExecutions AutomationStepExecution[]
@@unique([ruleId, stepKey])
@@index([tenantId, ruleId, sortOrder])
@@index([tenantId, nodeType])
}
model AutomationExecution {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
ruleId String
triggerKey String
triggerPayload Json @default("{}")
status AutomationExecutionStatus @default(queued)
dryRun Boolean @default(false)
idempotencyKey String?
reverseWindowExpiresAt DateTime?
resumeFromStepId String?
summaryText String
errorText String?
queuedAt DateTime @default(now())
startedAt DateTime?
endedAt DateTime?
durationMs Int?
attempt Int @default(1)
nextRetryAt DateTime?
createdByUserId String?
isDemoData Boolean @default(false)
rule AutomationRule @relation(fields: [ruleId], references: [id], onDelete: Cascade)
stepExecutions AutomationStepExecution[]
@@unique([tenantId, idempotencyKey])
@@index([tenantId, ruleId, createdAt(sort: Desc)])
@@index([tenantId, triggerKey, createdAt(sort: Desc)])
@@index([tenantId, status, createdAt(sort: Desc)])
}
model AutomationStepExecution {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
executionId String
ruleStepId String?
stepKey String
stepKind AutomationStepKind
nodeType String
status AutomationExecutionStatus @default(queued)
input Json @default("{}")
output Json @default("{}")
summaryText String
errorText String?
startedAt DateTime?
endedAt DateTime?
durationMs Int?
attempt Int @default(1)
sortOrder Int @default(0)
execution AutomationExecution @relation(fields: [executionId], references: [id], onDelete: Cascade)
ruleStep AutomationRuleStep? @relation(fields: [ruleStepId], references: [id], onDelete: SetNull)
@@index([tenantId, executionId, sortOrder])
@@index([tenantId, status, createdAt(sort: Desc)])
}
model AutomationCredential {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
name String
kind String
encryptedValue String
metadata Json @default("{}")
createdByUserId String?
archivedAt DateTime?
@@unique([tenantId, name])
@@index([tenantId, kind, archivedAt])
}
model AutomationTemplate {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String?
name String
description String?
category String
flowData Json @default("{}")
isPublished Boolean @default(false)
createdFromRuleId String?
createdByUserId String?
isDemoData Boolean @default(false)
archivedAt DateTime?
@@unique([tenantId, name])
@@index([tenantId, category, isPublished, archivedAt])
}
model AutomationTriggerMeter {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
triggerKey String
windowStart DateTime
windowMinutes Int @default(5)
count Int @default(0)
pausedUntil DateTime?
anomalyText String?
@@unique([tenantId, triggerKey, windowStart, windowMinutes])
@@index([tenantId, triggerKey, windowStart])
@@index([tenantId, pausedUntil])
}
@@ -0,0 +1,201 @@
// AK-P16b (P16) Booking — Calendly-style public booking pages, timezone-aware
// slot calculation, full appointment lifecycle. Aligned to ENTITY-MODEL Domäne 9
// (M06-booking).
//
// AD-21: self-contained schema. `tenantId` / `providerUserId` / `kontaktId` /
// `leadId` / `formSubmissionId` are BARE String scalars (no `@relation` to
// Tenant/User/Kontakt/Lead/Form) → zero merge-conflict surface against the shared
// core + neighbouring module schemas (crm.prisma / calendar.prisma / forms). The
// CRM/Form linkage runs through those bare scalars in the service layer.
// Intra-module relations (Page → Provider / Appointment, Appointment self-reschedule)
// stay inside this file.
//
// Cross-ticket gaps handled per user decision (2026-06-30):
// - leadId stays NULLABLE, reserved for R-P7 (typed CRM Lead not built yet). v1
// post-booking matches/creates a Kontakt + logs an Activity instead.
// - formSubmissionId stays NULLABLE, reserved for AK-P16c (Forms module not built
// yet). v1 stores the standard mini-form answers in `intakeAnswers` JSON.
//
// Slot availability subtracts the Google busy intervals from AK-P16a
// (CalendarEvent.isBusyForAvailability) via the pure availability.ts helpers —
// leak-protection holds: only busy {from,to} intervals cross over, never titles.
//
// RLS ships separately in prisma/rls/booking-isolation.sql (deferred cutover like
// the other modules). The hard double-booking guard (PostgreSQL EXCLUDE USING gist
// over a tstzrange per provider) ships in prisma/rls/booking-constraints.sql — it
// cannot be expressed in the Prisma schema. On the feature branch: `prisma db push`
// + manual `psql -f` for the constraint; the merge migration folds both in (AD-21).
/// Provider-assignment strategy (M06 A.2). v1 implements `first_available` only
/// ("Erster der frei ist"); round_robin / specific_provider_choice → v2. The enum
/// carries all three so the v2 switch is additive (no migration of stored values).
enum BookingAssignmentStrategy {
round_robin
specific_provider_choice
first_available
}
/// Weekday of a weekly availability rule (M06 A.3).
enum BookingDayOfWeek {
monday
tuesday
wednesday
thursday
friday
saturday
sunday
}
/// Date-specific override kind (M06 A.4). `unavailable` blocks the whole day;
/// `custom_window` replaces the standard rule for that date.
enum AvailabilityExceptionKind {
unavailable
custom_window
}
/// Appointment lifecycle status (M06 A.5 / M129). `rescheduled` keeps the old row
/// for history and points forward via `rescheduledFromId` on the successor.
enum AppointmentStatus {
scheduled
held
cancelled
no_show
rescheduled
}
/// Who triggered a cancellation (M06 A.5) — drives the Klartext + auto-mail copy.
enum AppointmentCancelledByKind {
customer
provider
system
}
/// A public booking page (M06 A.1). Tenant-scoped, soft-deletable. `slug` is unique
/// per tenant and powers the public URL `/b/{tenant}/{slug}`. `intakeFormId` is a
/// bare reserved scalar for the AK-P16c Forms module (null = standard mini-form).
model BookingPage {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
createdByUserId String?
slug String
title String
description String?
durationMinutes Int
bufferBeforeMinutes Int @default(0)
bufferAfterMinutes Int @default(0)
slotIncrementMinutes Int @default(15)
minNoticeHours Int @default(4)
maxAdvanceDays Int @default(60)
assignmentStrategy BookingAssignmentStrategy @default(first_available)
confirmationEmailSubject String
confirmationEmailBody String
internalEventTitleTemplate String?
redirectUrlAfterBooking String?
// Reserved bare scalar for AK-P16c (Forms). Null → standard mini-form.
intakeFormId String?
isPublished Boolean @default(false)
isDemoData Boolean @default(false)
archivedAt DateTime?
providers BookingPageProvider[]
appointments Appointment[]
@@unique([tenantId, slug])
@@index([tenantId, archivedAt, isPublished])
}
/// M:N between BookingPage and tenant users who hold its appointments (M06 A.2).
/// `providerUserId` is a bare scalar (no @relation to User, AD-21).
model BookingPageProvider {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
bookingPageId String
providerUserId String
displayOrder Int @default(0)
isActive Boolean @default(true)
bookingPage BookingPage @relation(fields: [bookingPageId], references: [id], onDelete: Cascade)
@@unique([bookingPageId, providerUserId])
@@index([tenantId, providerUserId])
}
/// Weekly standard availability per tenant user (M06 A.3). Several rows per weekday
/// allowed (e.g. 09:00-12:00 + 14:00-17:00). Times are local "HH:mm" in `timezone`.
model AvailabilityRule {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
providerUserId String
dayOfWeek BookingDayOfWeek
startTime String
endTime String
timezone String
@@index([tenantId, providerUserId, dayOfWeek])
}
/// Date-specific override of the standard rules (M06 A.4). `startTime`/`endTime`
/// only set when kind = custom_window (null for a full-day `unavailable`).
model AvailabilityException {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
providerUserId String
date DateTime @db.Date
kind AvailabilityExceptionKind
startTime String?
endTime String?
reason String?
timezone String
@@index([tenantId, providerUserId, date])
}
/// A booked appointment (M06 A.5). Tenant-scoped. `startAt`/`endAt` are UTC;
/// `timezone` records the booker's IANA zone for display. CRM/Form links are bare
/// nullable scalars (kontaktId set on match/create; leadId reserved for R-P7,
/// formSubmissionId reserved for AK-P16c). `intakeAnswers` holds the v1 mini-form
/// payload. `internalCalendarEventId` points at the local CalendarEvent mirror that
/// blocks the provider's availability (AK-P16a write-path pushes it external later).
model Appointment {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
bookingPageId String
providerUserId String
startAt DateTime
endAt DateTime
timezone String
status AppointmentStatus @default(scheduled)
// CRM linkage (bare scalars, AD-21). leadId reserved for R-P7.
kontaktId String?
leadId String?
// Reserved for AK-P16c Forms. v1 answers live in intakeAnswers.
formSubmissionId String?
intakeAnswers Json @default("{}")
// Local CalendarEvent mirror id + external provider event ids (M06 J.2/J.3).
internalCalendarEventId String?
externalCalendarEventIds Json @default("[]")
cancelledAt DateTime?
cancelledByKind AppointmentCancelledByKind?
cancellationReason String?
rescheduledFromId String?
notesInternal String?
isDemoData Boolean @default(false)
bookingPage BookingPage @relation(fields: [bookingPageId], references: [id], onDelete: Cascade)
rescheduledFrom Appointment? @relation("AppointmentReschedule", fields: [rescheduledFromId], references: [id], onDelete: SetNull)
rescheduledTo Appointment[] @relation("AppointmentReschedule")
@@index([tenantId, providerUserId, startAt])
@@index([tenantId, status, startAt])
@@index([tenantId, kontaktId, startAt])
@@index([bookingPageId, startAt])
}
@@ -0,0 +1,236 @@
// AK-P16a (P16) Calendar-Sync (Google) — aligned to ENTITY-MODEL Domäne 9
// (M25-calendar-sync). v1 = Google only; Outlook/Microsoft → v2 (the provider
// enum + adapter interface stay provider-agnostic).
//
// 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 (Connection → Event /
// Mapping / Cursor / WebhookEvent / Conflict) stay inside this file.
//
// Connection is PER-USER (not per-tenant): each user connects their own Google
// 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. The Apps-Engine `App` catalog (appsEngine.prisma) is referenced
// READ-ONLY through the bare `dataConnectionId` scalar — calendar owns its own
// per-user connection lifecycle (RLS here is tenant- AND owner-scoped in code).
//
// RLS ships separately in prisma/rls/calendar-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). Leak-protection (DoD 3):
// external event contents are owner-only; availability exposes busy slots only.
/// Calendar provider. v1 = google; microsoft → v2 (interface stays agnostic).
enum CalendarProvider {
google
}
/// Sync direction of a connection (M25 Block D). Default bidirectional.
enum CalendarSyncDirection {
bidirectional
hivegrid_to_external_only
external_to_hivegrid_only
}
/// Lifecycle status of a calendar connection (M25 Block A/C).
enum CalendarConnectionStatus {
active
paused
error
revoked
}
/// Whether an event originates in HiveGrid or is a read-only external mirror.
enum CalendarEventSource {
hivegrid_internal
external_synced
}
/// Worker processing state of an inbound webhook notification (M25 Block E).
enum CalendarWebhookProcessingStatus {
pending
processing
completed
failed
skipped
}
/// How a sync conflict was resolved (M25 Block F — Last-Write-Wins variants).
enum CalendarConflictResolution {
external_won
hivegrid_won
external_deleted
hivegrid_deleted
}
/// A user's connection to an external calendar provider. PER-USER, tenant-scoped
/// for isolation. The OAuth tokens are AES-256-GCM per-tenant-DEK envelopes
/// (AD-8); never selected into a list view-model. `dataConnectionId` is an
/// OPTIONAL read-only reference to the Apps-Engine DataConnection catalog entry
/// (bare scalar, AD-21) — calendar runs autonomously if the catalog row is absent.
model CalendarConnection {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
userId String
provider CalendarProvider @default(google)
// User-visible account identity (for the connection card).
externalAccountEmail String
externalAccountId 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-subscription handle (Google channel.id) + renewal anchor.
webhookSubscriptionId String?
webhookSubscriptionExpiresAt DateTime?
// JSON list of selected external calendars to sync (default: primary).
selectedCalendars Json @default("[]")
syncDirection CalendarSyncDirection @default(bidirectional)
status CalendarConnectionStatus @default(active)
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?
events CalendarEvent[]
mappings CalendarEventMapping[]
syncCursors CalendarSyncCursor[]
webhookEvents CalendarWebhookEvent[]
conflicts CalendarConflict[]
@@unique([tenantId, userId, provider, externalAccountId])
@@index([tenantId, userId, status, archivedAt])
@@index([tenantId, webhookSubscriptionExpiresAt])
}
/// Cache of external events + HiveGrid-internal events. Tenant- and owner-scoped.
/// External events are owner-only (leak-protection, DoD 3); availability reads
/// only `isBusyForAvailability` busy intervals, never titles. `internalEntityLink`
/// is a polymorphic JSON pointer to a Booking/Projekt/Plantafel entity.
model CalendarEvent {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
userId String
connectionId String?
source CalendarEventSource
provider CalendarProvider?
externalEventId String?
externalCalendarId String?
title String?
description String?
location String?
startsAt DateTime
endsAt DateTime
isAllDay Boolean @default(false)
timeZone String?
recurrenceRule String?
attendees Json @default("[]")
// Provider concurrency token (Google etag) for conflict detection.
etag String?
lastModifiedExternal DateTime?
isBusyForAvailability Boolean @default(true)
internalEntityLink Json?
// Monotonic HiveGrid-side version for optimistic locking (M25 Block F).
versionToken Int @default(0)
isDemoData Boolean @default(false)
archivedAt DateTime?
connection CalendarConnection? @relation(fields: [connectionId], references: [id], onDelete: SetNull)
mappings CalendarEventMapping[]
@@unique([tenantId, userId, provider, externalEventId])
@@index([tenantId, userId, startsAt])
@@index([tenantId, userId, lastModifiedExternal(sort: Desc)])
@@index([tenantId, source, archivedAt])
}
/// Links a HiveGrid-internal event to its external mirror(s). One internal event
/// can map to several providers/calendars (e.g. Google + Microsoft in v2).
model CalendarEventMapping {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
internalEventId String
externalEventId String
provider CalendarProvider
externalCalendarId String
connectionId String
lastSyncedAt DateTime?
lastKnownExternalEtag String?
lastKnownInternalVersionToken Int?
internalEvent CalendarEvent @relation(fields: [internalEventId], references: [id], onDelete: Cascade)
connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)
@@unique([internalEventId, provider, externalCalendarId])
@@index([tenantId, connectionId])
}
/// Per-connection-per-calendar delta cursor (Google syncToken). Drives the
/// incremental external→HiveGrid sync (M25 Block D/E).
model CalendarSyncCursor {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
connectionId String
externalCalendarId String
cursorToken String?
lastFullSyncAt DateTime?
connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)
@@unique([connectionId, externalCalendarId])
@@index([tenantId, connectionId])
}
/// Persisted inbound webhook notification (idempotency + retry, M25 Block E).
/// A fast 200 is returned to the provider; a worker drains `pending` rows.
model CalendarWebhookEvent {
id String @id @default(cuid())
receivedAt DateTime @default(now())
tenantId String
connectionId String
provider CalendarProvider
notificationPayload Json
processingStatus CalendarWebhookProcessingStatus @default(pending)
processingErrorText String?
processedAt DateTime?
// Provider-specific resource state (Google X-Goog-Resource-State).
externalResourceState String?
connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)
@@index([tenantId, processingStatus, receivedAt])
@@index([tenantId, connectionId])
}
/// A resolved sync conflict (DoD 4). The connection-detail view shows the latest
/// 50 with a Klartext description + how it was resolved (Last-Write-Wins).
model CalendarConflict {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
connectionId String
userId String
internalEventId String?
externalEventId String?
resolution CalendarConflictResolution
// Klartext description shown in the conflict log (M002/M003 key + rendered text).
descriptionText String
isDemoData Boolean @default(false)
connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)
@@index([tenantId, connectionId, createdAt(sort: Desc)])
@@index([tenantId, userId])
}
@@ -32,22 +32,17 @@ model AppConfiguration {
}
model Log {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String?
userId String?
apiKeyId String?
rowId String?
url String
action String
details String?
commentId String?
apiKey ApiKey? @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)
comment RowComment? @relation(fields: [commentId], references: [id])
row Row? @relation(fields: [rowId], references: [id])
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
webhookLogs EntityWebhookLog[]
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String?
userId String?
apiKeyId String?
url String
action String
details String?
apiKey ApiKey? @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model AuditEvent {
@@ -68,6 +63,15 @@ model AuditEvent {
dataSensitivity String @default("internal")
regulatoryScope String[] @default([])
metadata Json?
// Structured field-level change capture (ENTITY-MODEL §Domäne 2, AK-P3 DoD 2).
// Nullable/additive: legacy rows and callers without diff capture stay valid.
// NOT part of the eventHash digest — the chain payload is frozen; binding
// diffs into the chain is a coordinated R-P1b follow-up.
beforeDiff Json?
afterDiff Json?
// Persisted German summary line; viewers fall back to a derived summary
// when null (pre-existing rows).
summaryText String?
previousHash String?
eventHash String?
@@ -80,9 +84,9 @@ model AuditEvent {
}
model IdempotencyKey {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
expiresAt DateTime?
scope String
key String
@@ -106,15 +110,14 @@ model ApiKey {
keyLastFour String?
hashedAt DateTime?
keyVersion Int @default(1)
scopes Json @default("[\"public_api:read\"]")
alias String
expires DateTime?
active Boolean
createdByUser User @relation(fields: [createdByUserId], references: [id], onDelete: Cascade)
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
entities ApiKeyEntity[]
apiKeyLogs ApiKeyLog[]
logs Log[]
createdRows Row[]
tenantIpAddresses TenantIpAddress[]
@@unique([tenantId, alias])
@@ -0,0 +1,264 @@
// R-P6 (P6 CRM core) — typed CRM entities that replace the generic Entity-Builder
// for the CRM domain (AD-2). Source of truth: ENTITY-MODEL.md Domäne 5 (LOCKED).
//
// AD-21: one self-contained schema file per module. `tenantId` /
// `createdByUserId` / `zustaendigerUserId` are intentionally BARE String scalars
// (no `@relation` to Tenant/User) so this file has zero merge-conflict surface
// against `core.prisma`/`accounts.prisma` (no back-relation fields on Tenant/User
// needed). Referential integrity to Tenant/User is carried at the application
// layer (crmService + crmAccess) plus the RLS policies added in the merge
// migration (see prisma/rls/crm-isolation.sql — deferred activation, like
// appsEngine/activity).
//
// Activity stream is NOT defined here: it lives in `activity.prisma` (model
// Activity, polymorphic subjectType/subjectId) and is appended via `logActivity()`
// from `@hivegrid/activity` (AGENTS DoD #14).
//
// Soft-delete via `archivedAt`. Demo-seed rows carry `isDemoData = true` and are
// bulk-removed on the production switch-over (per-module deleteMany).
//
// Lead → Projekt extension point (DoD 5, AD-20): Lead and Projekt are built in
// P7/P8. The polymorphic `CustomFieldEntityType` enum and the `TagAssignment`
// /`Activity` entityType strings already carry `lead`/`projekt`/`rechnung`, so
// custom fields, tags and activities attach to those entities without a schema
// change. A Kontakt is referenced from a future Lead/Projekt by bare id only.
/// Kontakt discriminator: a Kontakt is either a private person or an organisation.
enum KontaktTyp {
privatperson
organisation
}
/// Lifecycle status of a Kontakt (lead-independent commercial relationship state).
enum KontaktStatus {
kontakt
kunde
bestandskunde
}
/// Optional legal-form / classification marker for organisation contacts.
enum OrgMerkmal {
gmbh
kg
oeffentliche_einrichtung
sonstige
}
/// Role of a KontaktRelation (Kontaktart) — "this contact is the X of that one".
enum KontaktArt {
hauptkontakt
sekundaerkontakt
mitarbeiter
sonstige
}
/// Polymorphic target type for tenant custom fields. Carries `lead`/`projekt`/
/// `rechnung` already so P7/P8 attach without a migration (Lead → Projekt
/// extension point, DoD 5).
enum CustomFieldEntityType {
projekt
kontakt
lead
rechnung
}
/// Data type of a tenant custom field — drives the value renderer and validation.
enum CustomFieldDatentyp {
text
textarea
zahl
waehrung
datum
datum_range
select
multiselect
boolean
email
telefon
datei
}
/// A contact (Kontakt), the CRM core entity. Oberbegriff for both private persons
/// (kontaktTyp = privatperson → vorname/nachname) and organisations
/// (kontaktTyp = organisation → orgName/orgMerkmal). Scoped per tenant, soft-delete
/// via `archivedAt`. `zustaendigerUserId` is the owner for the crm.read_own filter.
model Kontakt {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
createdByUserId String
kontaktTyp KontaktTyp
kontaktStatus KontaktStatus @default(kontakt)
// Person fields (kontaktTyp = privatperson).
vorname String?
nachname String?
// Organisation fields (kontaktTyp = organisation).
orgName String?
orgMerkmal OrgMerkmal?
// Denormalised primary channels, kept in sync from KontaktEmail/KontaktTelefon
// by the service so list/dup-check queries stay single-table.
primaerEmail String?
primaerTelefon String?
// Single reusable address slot (Projekt has 3 slots, Kontakt has 1).
adresseId String?
// Owner of record — drives the crm.read_own owner filter (DoD 8).
zustaendigerUserId String?
// Preferred outbound language (i18n field per ENTITY-MODEL, AK-P3 DoD 6).
// Null = tenant default; outbound usage lands in v2 — no UI editor in v1.
language String?
isDemoData Boolean @default(false)
archivedAt DateTime?
adresse Adresse? @relation(fields: [adresseId], references: [id])
emails KontaktEmail[]
telefone KontaktTelefon[]
relationenVon KontaktRelation[] @relation("KontaktRelationVon")
relationenZu KontaktRelation[] @relation("KontaktRelationZu")
@@index([tenantId, archivedAt])
@@index([tenantId, kontaktTyp, archivedAt])
@@index([tenantId, primaerEmail])
@@index([tenantId, primaerTelefon])
@@index([tenantId, zustaendigerUserId])
@@index([tenantId, adresseId])
}
/// Self-referential M:N relation between contacts (e.g. organisation ↔ primary
/// contact person). The `rolle` (Kontaktart) is the role of the relation itself.
model KontaktRelation {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
vonKontaktId String
zuKontaktId String
rolle KontaktArt
kontext String? // optional free-text describing the relationship
vonKontakt Kontakt @relation("KontaktRelationVon", fields: [vonKontaktId], references: [id], onDelete: Cascade)
zuKontakt Kontakt @relation("KontaktRelationZu", fields: [zuKontaktId], references: [id], onDelete: Cascade)
@@unique([vonKontaktId, zuKontaktId, rolle])
@@index([tenantId, vonKontaktId])
@@index([tenantId, zuKontaktId])
}
/// One of a contact's e-mail addresses. Exactly one carries `primaer = true`
/// (enforced in the service), mirrored to `Kontakt.primaerEmail`.
model KontaktEmail {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
kontaktId String
email String
primaer Boolean @default(false)
kontakt Kontakt @relation(fields: [kontaktId], references: [id], onDelete: Cascade)
@@index([tenantId, kontaktId])
@@index([tenantId, email])
}
/// One of a contact's phone numbers. Exactly one carries `primaer = true`
/// (enforced in the service), mirrored to `Kontakt.primaerTelefon`.
model KontaktTelefon {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
kontaktId String
telefon String
primaer Boolean @default(false)
kontakt Kontakt @relation(fields: [kontaktId], references: [id], onDelete: Cascade)
@@index([tenantId, kontaktId])
@@index([tenantId, telefon])
}
/// A reusable postal address. v1 is DE-only (`land` defaults to "DE").
model Adresse {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
strasse String?
hausnummer String?
plz String?
ort String?
land String @default("DE")
kontakte Kontakt[]
@@index([tenantId])
}
/// Tenant-defined custom field for a polymorphic entity type. The actual values
/// live in CustomFieldValue. `archiviert` hides the field but keeps its values.
model CustomFieldDefinition {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
entityType CustomFieldEntityType
key String // machine name, unique per (tenant, entityType)
label String
datentyp CustomFieldDatentyp
optionen Json? // e.g. { "select": ["A", "B"] } for select/multiselect
archiviert Boolean @default(false)
isDemoData Boolean @default(false)
values CustomFieldValue[]
@@unique([tenantId, entityType, key])
@@index([tenantId, entityType])
}
/// Value of a custom field for a concrete entity. Polymorphic: `entityId` carries
/// NO DB foreign key — the service validates entityType match + entity existence.
model CustomFieldValue {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
definitionId String
entityType CustomFieldEntityType
entityId String
wert Json? // type-variable value (string, number, array for multiselect…)
definition CustomFieldDefinition @relation(fields: [definitionId], references: [id], onDelete: Cascade)
@@unique([definitionId, entityId])
@@index([tenantId, entityType, entityId])
@@index([definitionId])
}
/// A coloured tag. Cross-cutting and polymorphic via TagAssignment.
model Tag {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
name String
farbe String // hex code (#RRGGBB) or palette name
assignments TagAssignment[]
@@unique([tenantId, name])
@@index([tenantId])
}
/// Polymorphic M:N link Tag ↔ any entity. `entityType` is a String (extensible,
/// mirrors Activity.subjectType): kontakt | projekt | lead | rechnung | termin | …
/// `entityId` carries NO DB foreign key — the service validates existence.
model TagAssignment {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
tagId String
entityType String
entityId String
tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)
@@unique([tagId, entityId, entityType])
@@index([tenantId, entityType, entityId])
@@index([tenantId, tagId])
}
@@ -0,0 +1,35 @@
// R-P5 (P5) — per-tenant data-encryption-key store for AD-8 envelope encryption.
//
// AD-21: one self-contained schema file per module. `tenantId` is a BARE String
// scalar (no `@relation`) so this file has zero merge-conflict surface against
// `core.prisma`/`accounts.prisma` (no back-relation field on Tenant needed).
//
// AD-8 (revised by EXT-06: app-side envelope, no cloud-KMS): each tenant has ONE
// random Data-Encryption-Key (DEK). The DEK is never stored in the clear — only
// WRAPPED with the app master key (the `KeyWrapper` in
// packages/foundation/src/crypto/key-wrapper.ts; today EnvKeyWrapper over
// CRYPTO_SECRET, later swappable for self-hosted Vault/OpenBao WITHOUT
// re-encrypting any field). Sensitive fields across modules (HR password safe,
// HR emergency contact, R-P5 OAuth/API-key credentials) are sealed with the
// tenant DEK.
//
// Crypto-shredding (M165 / AK-P21): deleting a tenant's row here makes ALL of
// that tenant's envelope ciphertext permanently unreadable. The orchestration
// (load/create/destroy + in-memory unwrapped-DEK cache) lives in
// packages/db/src/crypto/tenant-envelope.server.ts.
/// One wrapped Data-Encryption-Key per tenant. `wrappedDek` is the tenant DEK
/// encrypted with the app master key (never the plaintext DEK). `keyVersion`
/// allows rotating the wrapping scheme without touching field ciphertext.
model TenantEncryptionKey {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String @unique
// The tenant DEK, wrapped (encrypted) with the app master key. Opaque blob;
// useless without the master key, so a DB leak alone exposes nothing.
wrappedDek Bytes
keyVersion Int @default(1)
@@index([tenantId])
}
@@ -0,0 +1,68 @@
// R-P11b (P11 Dashboard) — typed tenant dashboard layouts.
//
// AD-21: self-contained schema. User references are bare String scalars so this
// slice does not touch accounts/core back-relations while the v1 fixed role
// layouts stay independent from later drag/drop customization.
enum DashboardRole {
gf
office
monteur
}
model Dashboard {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
name String
description String?
role DashboardRole
isDefaultForRole Boolean @default(true)
isShared Boolean @default(true)
isDemoData Boolean @default(false)
archivedAt DateTime?
layouts DashboardLayout[]
instances WidgetInstance[]
@@unique([tenantId, role, name])
@@index([tenantId, role, isDefaultForRole, archivedAt])
@@index([tenantId, isShared, archivedAt])
}
model DashboardLayout {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
dashboardId String
userId String?
widgets Json @default("[]")
layoutData Json @default("{}")
isDemoData Boolean @default(false)
archivedAt DateTime?
dashboard Dashboard @relation(fields: [dashboardId], references: [id], onDelete: Cascade)
@@unique([dashboardId, userId])
@@index([tenantId, dashboardId, userId, archivedAt])
}
model WidgetInstance {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
dashboardId String
widgetCatalogKey String
config Json @default("{}")
position Json @default("{}")
size Json @default("{}")
isDemoData Boolean @default(false)
archivedAt DateTime?
dashboard Dashboard @relation(fields: [dashboardId], references: [id], onDelete: Cascade)
@@index([tenantId, dashboardId, widgetCatalogKey, archivedAt])
}
@@ -0,0 +1,223 @@
// 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])
}
@@ -1,9 +1,20 @@
model TenantInboundAddress {
id String @id @default(cuid())
tenantId String
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
address String @unique
email Email[]
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
address String @unique
// AK-P14a: structured address (local-part + full address) and routing purpose.
localPart String?
fullAddress String?
purpose EmailInboundPurpose @default(lead_inbox)
// BCC-logging toggle: a bcc_logging address may be shown but inactive.
enabled Boolean @default(true)
isDemoData Boolean @default(false)
archivedAt DateTime?
email Email[]
@@index([tenantId, purpose, archivedAt])
}
model Email {
@@ -20,6 +31,13 @@ model Email {
toName String?
textBody String
htmlBody String
// AK-P14a: delivery state + CRM linkage. relatedKontaktId/relatedProjektId are
// BARE String scalars (no @relation) — the Kontakt/Projekt FK is wired in R-P6
// (CRM-Kern); until then app-level scoping carries the link.
purpose String?
deliveryStatus String?
relatedKontaktId String?
relatedProjektId String?
reads EmailRead[]
attachments EmailAttachment[]
cc EmailCc[]
@@ -65,9 +83,16 @@ model EmailSender {
fromEmail String
fromName String?
replyToEmail String?
// AK-P14a: default-sender marker, demo seed flag, optional sending-domain link
// (bare scalar FK to TenantSendingDomain, resolved in the service layer).
isDefault Boolean @default(false)
isDemoData Boolean @default(false)
sendingDomainId String?
tenant Tenant? @relation(fields: [tenantId], references: [id])
campaigns Campaign[]
outboundEmails OutboundEmail[]
@@index([tenantId, isDefault])
}
model Campaign {
@@ -81,9 +106,24 @@ model Campaign {
status String @default("draft")
track Boolean
sentAt DateTime?
emailSender EmailSender @relation(fields: [emailSenderId], references: [id])
// AK-P14b: typed segment link + scheduling + DSGVO footer/preview metadata.
// recipientSegmentId is the typed audience source (the legacy Entity-Builder
// recipient path was removed by R-P14C). scheduledAt + timezone drive
// timezone-aware delayed sends.
recipientSegmentId String?
scheduledAt DateTime?
timezone String?
previewText String?
footerHtml String?
isDemoData Boolean @default(false)
archivedAt DateTime?
emailSender EmailSender @relation(fields: [emailSenderId], references: [id])
recipients OutboundEmail[]
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
variants CampaignVariant[]
segment RecipientSegment? @relation(fields: [recipientSegmentId], references: [id])
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
@@index([tenantId, status, archivedAt])
}
model OutboundEmail {
@@ -93,8 +133,14 @@ model OutboundEmail {
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
campaignId String?
campaign Campaign? @relation(fields: [campaignId], references: [id], onDelete: Cascade)
contactRowId String?
contactRow Row? @relation(fields: [contactRowId], references: [id])
// R-P14C (AD-2): the legacy Entity-Builder contactRowId/contactRow relation was
// dropped. The typed recipient link is the bare `kontaktId` scalar (R-P6 Kontakt
// id, AK-P14b). campaignVariantId attributes A/B sends; unsubscribeToken/
// trackingToken are per-recipient signed handles.
kontaktId String?
campaignVariantId String?
unsubscribeToken String?
trackingToken String?
email String
fromSenderId String
isPreview Boolean?
@@ -107,12 +153,16 @@ model OutboundEmail {
fromSender EmailSender @relation(fields: [fromSenderId], references: [id])
opens OutboundEmailOpen[]
clicks OutboundEmailClick[]
@@index([tenantId, sentAt])
}
model OutboundEmailOpen {
id String @id @default(cuid())
createdAt DateTime @default(now())
firstOpen Boolean
// AK-P14a: anonymized client IP (sha256, truncated) — never the raw address.
ipHash String?
outboundEmailId String
outboundEmail OutboundEmail @relation(fields: [outboundEmailId], references: [id], onDelete: Cascade)
}
@@ -121,6 +171,232 @@ model OutboundEmailClick {
id String @id @default(cuid())
createdAt DateTime @default(now())
link String
// AK-P14a: anonymized client IP (sha256, truncated) — never the raw address.
ipHash String?
outboundEmailId String
outboundEmail OutboundEmail @relation(fields: [outboundEmailId], references: [id], onDelete: Cascade)
}
// =============================================================================
// AK-P14a · P14 — Email foundation (sending-domain verification, BCC bridge,
// suppression, tracking). AD-21: these models live in this module file; new
// tenant-scoped models use BARE `tenantId String` scalars (no @relation) so the
// file keeps zero merge-conflict surface against core.prisma (same stance as
// hr.prisma). RLS ships separately in prisma/rls/email-isolation.sql (deferred
// cutover; app-level scoping via withTenantRLS carries isolation meanwhile).
// =============================================================================
/// AK-P14a · routing purpose of a tenant inbound address.
enum EmailInboundPurpose {
lead_inbox
bcc_logging
reply_routing
}
/// AK-P14a · DNS verification state of a tenant sending domain.
enum SendingDomainStatus {
pending
verifying
verified
failed
}
/// AK-P14a · why an address is suppressed from sending.
enum EmailSuppressionReason {
bounce
complaint
manual
}
/// A per-tenant sending domain (DKIM/SPF/DMARC). The tenant publishes the public
/// records (shown with copy buttons); the system auto-probes DNS every 5 minutes
/// and walks `verificationStatus` pending → verifying → verified|failed. After 7
/// days without success `lastError` carries a Klartext (M002) explanation. The
/// DKIM private key is stored ENVELOPE-ENCRYPTED per tenant (AD-8) and never
/// returned to the client. Soft-delete via `archivedAt`.
model TenantSendingDomain {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
domain String
dkimSelector String?
dkimRecord String?
spfRecord String?
dmarcRecord String?
// Sensitive: DKIM private key as per-tenant AES-256-GCM envelope ciphertext
// (AD-8, getTenantFieldCrypto). Never serialised to a view-model.
dkimPrivateKeyCiphertext String?
verificationStatus SendingDomainStatus @default(pending)
// Provider handle (Mailjet /v3/REST/dns id) for re-checks.
mailjetDnsId String?
// First probe anchors the 7-day "still not verified" Klartext window.
firstProbeAt DateTime?
lastProbedAt DateTime?
// Klartext failure detail surfaced after the 7-day window (M002).
lastError String?
isDemoData Boolean @default(false)
archivedAt DateTime?
@@unique([tenantId, domain])
@@index([tenantId, verificationStatus, archivedAt])
}
/// A per-tenant suppression entry: an address that must NOT be sent to. Populated
/// by bounce/complaint webhooks (reason bounce|complaint) and manual additions.
model EmailSuppressionList {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
emailAddress String
reason EmailSuppressionReason @default(manual)
// Free-text provider detail (e.g. Mailjet bounce comment).
detail String?
@@unique([tenantId, emailAddress])
@@index([tenantId, reason])
}
/// A reusable email template, scoped per tenant. `isDefault` marks the seed
/// starting point; `isDemoData` flags seedable demo rows. Soft-delete via
/// `archivedAt`.
model EmailTemplate {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
name String
subject String
htmlBody String
isDefault Boolean @default(false)
isDemoData Boolean @default(false)
archivedAt DateTime?
@@index([tenantId, archivedAt])
}
// =============================================================================
// AK-P14b · P14 — Email marketing (segments, A/B variants, marketing consent,
// unsubscribe). TYPED path (AD-2): segments read the R-P6 typed `Kontakt` model
// (NOT the Entity-Builder). Same AD-21 stance as AK-P14a: bare `tenantId String`
// scalars, no @relation to core; cross-module references (kontaktId, campaignId)
// are bare scalars resolved in the service layer. RLS ships in
// prisma/rls/email-isolation.sql (deferred cutover). The legacy Entity-Builder
// campaign path (OutboundEmail.contactRowId / CrmService) was removed by R-P14C
// (Variante A); recipients are typed via kontaktId + RecipientSegment.
// =============================================================================
/// Marketing consent lifecycle of a Kontakt (DSGVO double-opt-in). `none` = no
/// consent, `single` = opted in but not yet confirmed, `double` = confirmed via
/// the opt-in e-mail. Lives in email.prisma (NOT crm.prisma) so Raffael's R-P6
/// schema stays untouched (AD-21); `kontaktId` is a bare scalar.
enum MarketingConsentStatus {
none
single
double
}
/// Scope of an unsubscribe: `all` = the contact opts out of all marketing,
/// `campaign` = a single-campaign opt-out (rare, kept for completeness).
enum UnsubscribeScope {
all
campaign
}
/// A/B variant slot of a campaign.
enum CampaignVariantLabel {
a
b
}
/// A reusable recipient segment. `filterDefinition` is a nested AND/OR tree
/// (see segmentQuery.ts) evaluated read-only against the typed Kontakt model.
/// `isStaticSnapshot` freezes the resolved membership into SegmentSnapshotMember
/// at creation time; a dynamic segment re-resolves on every send.
model RecipientSegment {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
name String
// Polymorphic target type (mirrors TagAssignment.entityType). v1 = "kontakt".
entityType String @default("kontakt")
filterDefinition Json
isStaticSnapshot Boolean @default(false)
isDemoData Boolean @default(false)
archivedAt DateTime?
snapshotMembers SegmentSnapshotMember[]
campaigns Campaign[]
@@index([tenantId, archivedAt])
}
/// Frozen membership row of a static segment. `kontaktId` is a bare scalar
/// (typed Kontakt id, no DB FK — AD-21).
model SegmentSnapshotMember {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
segmentId String
kontaktId String
segment RecipientSegment @relation(fields: [segmentId], references: [id], onDelete: Cascade)
@@unique([segmentId, kontaktId])
@@index([tenantId, segmentId])
}
/// One A/B variant of a campaign. The send-engine splits the audience by
/// `weightPercent`; per-variant counters drive the A/B comparison report.
model CampaignVariant {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
campaignId String
label CampaignVariantLabel
subject String
htmlBody String
textBody String?
weightPercent Int @default(50)
deliveredCount Int @default(0)
openedCount Int @default(0)
clickedCount Int @default(0)
campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)
@@unique([campaignId, label])
@@index([tenantId, campaignId])
}
/// Per-tenant marketing consent for a Kontakt. `kontaktId` is a bare scalar
/// (typed Kontakt id). One row per (tenant, kontakt).
model KontaktMarketingConsent {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
kontaktId String
status MarketingConsentStatus @default(none)
// Where the opt-in came from (e.g. "form:<formId>", "import", "manual").
optInSource String?
optInAt DateTime?
// HMAC handle for the double-opt-in confirmation link (verified, not stored raw).
doubleOptInToken String?
confirmedAt DateTime?
unsubscribedAt DateTime?
@@unique([tenantId, kontaktId])
@@index([tenantId, status])
}
/// An unsubscribe record (one-click / List-Unsubscribe). `kontaktId` is a bare
/// scalar; `campaignId` is set only for a campaign-scoped opt-out.
model Unsubscribe {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
kontaktId String
scope UnsubscribeScope @default(all)
campaignId String?
reason String?
@@index([tenantId, kontaktId])
}
@@ -1,578 +0,0 @@
model Entity {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
moduleId String?
name String @unique
slug String @unique
order Int
prefix String @unique
type String @default("app") // app, admin, all
title String
titlePlural String
isAutogenerated Boolean
hasApi Boolean
icon String
active Boolean
showInSidebar Boolean @default(true)
hasTags Boolean @default(true)
hasComments Boolean @default(true)
hasTasks Boolean @default(true)
hasActivity Boolean @default(true)
hasBulkDelete Boolean @default(false)
hasViews Boolean @default(true)
defaultVisibility String @default("private")
onCreated String? @default("redirectToOverview") // redirectToOverview, redirectToNew, redirectToList, redirectToEdit, addAnother
onEdit String? @default("editRoute") // editRoute, overviewRoute, overviewAlwaysEditable
createdPermissions Permission[]
apiKeys ApiKeyEntity[]
tags EntityTag[]
permissions EntityTenantUserPermission[]
webhooks EntityWebhook[]
properties Property[]
rows Row[]
views EntityView[]
parentEntities EntityRelationship[] @relation(name: "childEntities")
childEntities EntityRelationship[] @relation(name: "parentEntities")
// module Module? @relation(fields: [moduleId], references: [id])
groups EntityGroupEntity[]
templates EntityTemplate[]
@@index([name], name: "entity_name")
@@index([slug], name: "entity_slug")
}
model Property {
id String @id @default(cuid())
entityId String
order Int
name String
title String
type Int
subtype String?
isDefault Boolean @default(false)
isRequired Boolean @default(false)
isHidden Boolean @default(false)
isDisplay Boolean @default(false)
isUnique Boolean @default(false) // TODO: Validate uniqueness
isReadOnly Boolean @default(false)
showInCreate Boolean @default(true)
canUpdate Boolean @default(true)
formulaId String?
formula Formula? @relation(fields: [formulaId], references: [id], onDelete: Cascade)
tenantId String?
tenant Tenant? @relation(fields: [tenantId], references: [id])
attributes PropertyAttribute[]
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
options PropertyOption[]
values RowValue[]
inViewProperties EntityViewProperty[]
inViewGroupBy EntityView[]
@@unique([entityId, name, tenantId])
@@unique([entityId, title, tenantId])
@@index([entityId], name: "entity_property")
@@index([entityId, name], name: "entity_property_name")
}
model EntityView {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdByUserId String?
createdByUser User? @relation(name: "createdByUser", fields: [createdByUserId], references: [id])
entityId String
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
tenantId String?
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
userId String?
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
layout String @default("table") // table, board, calendar, list, gallery...
order Int
name String
title String
pageSize Int
isDefault Boolean
isSystem Boolean @default(false)
gridColumns Int? @default(5)
gridColumnsSm Int? @default(2)
gridColumnsMd Int? @default(3)
gridColumnsLg Int? @default(4)
gridColumnsXl Int? @default(5)
gridColumns2xl Int? @default(6)
gridGap String? @default("sm")
properties EntityViewProperty[]
filters EntityViewFilter[]
sort EntityViewSort[]
groupByPropertyId String?
groupByProperty Property? @relation(fields: [groupByPropertyId], references: [id], onDelete: Cascade)
inGroups EntityGroupEntity[]
inChildRelationships EntityRelationship[] @relation(name: "childEntityView")
inParentRelationships EntityRelationship[] @relation(name: "parentEntityView")
@@index([entityId], name: "entity_view")
@@index([entityId, name], name: "entity_view_name")
}
model EntityViewProperty {
id String @id @default(cuid())
entityViewId String
entityView EntityView @relation(fields: [entityViewId], references: [id], onDelete: Cascade)
propertyId String?
property Property? @relation(fields: [propertyId], references: [id], onDelete: Cascade)
name String? // if not a property, e.g. "default.folio"
order Int
@@index([entityViewId], name: "entity_view_property")
@@index([entityViewId, name], name: "entity_view_property_name")
}
model EntityViewFilter {
id String @id @default(cuid())
entityViewId String
entityView EntityView @relation(fields: [entityViewId], references: [id], onDelete: Cascade)
match String @default("and") // and, or
name String
condition String // is, isNot, contains, doesNotContain...
value String
@@index([entityViewId], name: "entity_view_filter")
@@index([entityViewId, name], name: "entity_view_filter_name")
}
model EntityViewSort {
id String @id @default(cuid())
entityViewId String
entityView EntityView @relation(fields: [entityViewId], references: [id], onDelete: Cascade)
name String
asc Boolean
order Int
@@index([entityViewId], name: "entity_view_sort")
@@index([entityViewId, name], name: "entity_view_sort_name")
}
model PropertyAttribute {
id String @id @default(cuid())
propertyId String
property Property @relation(fields: [propertyId], references: [id], onDelete: Cascade)
name String // pattern, min, max, step, rows, defaultValue, maxSize, acceptFileTypes, uppercase...
value String
@@unique([propertyId, name])
@@index([propertyId], name: "property_attribute")
@@index([propertyId, name], name: "property_attribute_name")
}
model PropertyOption {
id String @id @default(cuid())
propertyId String
order Int
value String
name String?
color Int @default(0)
property Property @relation(fields: [propertyId], references: [id], onDelete: Cascade)
// values RowValueSelection[]
@@index([propertyId], name: "property_option")
@@index([propertyId, name], name: "property_option_name")
}
model EntityTag {
id String @id @default(cuid())
createdAt DateTime @default(now())
entityId String
value String
color Int
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
rowTags RowTag[]
@@index([entityId], name: "entity_tag")
@@index([entityId, value], name: "entity_tag_value")
}
model EntityTenantUserPermission {
id String @id @default(cuid())
entityId String
level Int
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
}
model EntityWebhook {
id String @id @default(cuid())
entityId String
action String
method String
endpoint String
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
logs EntityWebhookLog[]
}
model EntityWebhookLog {
id String @id @default(cuid())
webhookId String
logId String
status Int
error String?
log Log @relation(fields: [logId], references: [id], onDelete: Cascade)
webhook EntityWebhook @relation(fields: [webhookId], references: [id], onDelete: Cascade)
}
model EntityRelationship {
id String @id @default(cuid())
parentId String
parent Entity @relation(name: "parentEntities", fields: [parentId], references: [id], onDelete: Cascade)
childId String
child Entity @relation(name: "childEntities", fields: [childId], references: [id], onDelete: Cascade)
order Int?
title String?
type String @default("one-to-many")
required Boolean @default(false)
cascade Boolean @default(false)
readOnly Boolean @default(false)
hiddenIfEmpty Boolean @default(false)
childEntityViewId String?
childEntityView EntityView? @relation(name: "childEntityView", fields: [childEntityViewId], references: [id], onDelete: Cascade)
parentEntityViewId String?
parentEntityView EntityView? @relation(name: "parentEntityView", fields: [parentEntityViewId], references: [id], onDelete: Cascade)
rows RowRelationship[]
@@unique([parentId, childId, title])
@@index([parentId], name: "parent_entity_relationship")
@@index([childId], name: "child_entity_relationship")
@@index([parentId, childId], name: "parent_child_entity_relationship")
@@index([parentId, childId, order], name: "parent_child_entity_relationship_order")
}
model SampleCustomEntity {
rowId String @unique
row Row @relation(fields: [rowId], references: [id], onDelete: Cascade)
customText String
customNumber Decimal
customDate DateTime
customBoolean Boolean
customSelect String
}
model RowRelationship {
id String @id @default(cuid())
createdAt DateTime @default(now())
relationshipId String
relationship EntityRelationship @relation(fields: [relationshipId], references: [id], onDelete: Cascade)
parentId String
parent Row @relation(name: "parentRow", fields: [parentId], references: [id], onDelete: Cascade)
childId String
child Row @relation(name: "childRow", fields: [childId], references: [id], onDelete: Cascade)
metadata String?
@@unique([parentId, childId])
@@index([parentId], name: "parent_row_relationship")
@@index([childId], name: "child_row_relationship")
@@index([parentId, childId], name: "parent_child_row_relationship")
}
model Row {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deletedAt DateTime?
entityId String
tenantId String?
folio Int
createdByUserId String?
createdByApiKeyId String?
order Int @default(0)
createdByApiKey ApiKey? @relation(fields: [createdByApiKeyId], references: [id])
createdByUser User? @relation(fields: [createdByUserId], references: [id])
entity Entity @relation(fields: [entityId], references: [id])
tenant Tenant? @relation(fields: [tenantId], references: [id])
logs Log[]
comments RowComment[]
permissions RowPermission[]
tags RowTag[]
tasks RowTask[]
values RowValue[]
childRows RowRelationship[] @relation("parentRow")
parentRows RowRelationship[] @relation("childRow")
sampleCustomEntity SampleCustomEntity?
outboundEmails OutboundEmail[]
tenantSettingsRow TenantSettingsRow[]
formulaCalculationLogs FormulaComponentLog[]
inEntityGroupConfigurationRows EntityGroupConfigurationRow[]
@@index([deletedAt], name: "row_deletedAt")
@@index([entityId], name: "row_entity")
@@index([entityId, tenantId], name: "row_entity_tenant")
@@index([entityId, tenantId, createdAt], name: "row_entity_tenant_created_at")
@@index([tenantId], name: "row_tenant")
@@index([createdByUserId], name: "row_createdByUserId")
}
model RowValue {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime? @updatedAt
rowId String
propertyId String
textValue String?
numberValue Decimal?
dateValue DateTime?
booleanValue Boolean?
// selection RowValueSelection[] // TODO: MULTI SELECT
property Property @relation(fields: [propertyId], references: [id], onDelete: Cascade)
row Row @relation(fields: [rowId], references: [id], onDelete: Cascade)
media RowMedia[]
multiple RowValueMultiple[]
range RowValueRange?
@@index([rowId], name: "row_value_row")
@@index([rowId, propertyId], name: "row_value_row_property")
}
model RowValueMultiple {
id String @id @default(cuid())
rowValueId String
order Int
value String
rowValue RowValue @relation(fields: [rowValueId], references: [id], onDelete: Cascade)
@@index([rowValueId], name: "row_value_multiple_row_value")
}
model RowValueRange {
rowValueId String @unique
numberMin Decimal?
numberMax Decimal?
dateMin DateTime?
dateMax DateTime?
rowValue RowValue @relation(fields: [rowValueId], references: [id], onDelete: Cascade)
@@index([rowValueId], name: "row_value_range_row_value")
}
model RowPermission {
id String @id @default(cuid())
rowId String
tenantId String?
roleId String?
groupId String?
userId String?
public Boolean?
access String @default("view")
group Group? @relation(fields: [groupId], references: [id], onDelete: Cascade)
role Role? @relation(fields: [roleId], references: [id], onDelete: Cascade)
row Row @relation(fields: [rowId], references: [id], onDelete: Cascade)
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([rowId], name: "row_permission_row")
@@index([rowId, tenantId], name: "row_permission_row_tenant")
@@index([rowId, roleId], name: "row_permission_row_role")
@@index([rowId, groupId], name: "row_permission_row_group")
@@index([rowId, userId], name: "row_permission_row_user")
@@index([public], name: "row_permission_public")
}
model RowMedia {
id String @id @default(cuid())
rowValueId String
title String
name String
file String
type String
publicUrl String?
storageBucket String?
storageProvider String?
rowValue RowValue @relation(fields: [rowValueId], references: [id], onDelete: Cascade)
@@index([rowValueId], name: "row_media_row_value")
@@index([rowValueId, name], name: "row_media_row_value_name")
}
model RowTag {
id String @id @default(cuid())
createdAt DateTime @default(now())
rowId String
tagId String
row Row @relation(fields: [rowId], references: [id], onDelete: Cascade)
tag EntityTag @relation(fields: [tagId], references: [id], onDelete: Cascade)
@@index([rowId], name: "row_tag_row")
@@index([rowId, tagId], name: "row_tag_row_tag")
}
model RowComment {
id String @id @default(cuid())
createdAt DateTime @default(now())
createdByUserId String
rowId String
value String
isDeleted Boolean?
createdByUser User @relation(fields: [createdByUserId], references: [id], onDelete: Cascade)
row Row @relation(fields: [rowId], references: [id], onDelete: Cascade)
logs Log[]
reactions RowCommentReaction[]
@@index([rowId], name: "row_comment_row")
}
model RowCommentReaction {
id String @id @default(cuid())
createdAt DateTime @default(now())
createdByUserId String
rowCommentId String
reaction String
createdByUser User @relation(fields: [createdByUserId], references: [id], onDelete: Cascade)
rowComment RowComment @relation(fields: [rowCommentId], references: [id], onDelete: Cascade)
}
model RowTask {
id String @id @default(cuid())
createdAt DateTime @default(now())
createdByUserId String
rowId String
title String
description String
completed Boolean
completedAt DateTime?
completedByUserId String?
assignedToUserId String?
deadline DateTime?
assignedToUser User? @relation("assignedToUser", fields: [assignedToUserId], references: [id], onDelete: Cascade)
completedByUser User? @relation("completedByUser", fields: [completedByUserId], references: [id], onDelete: Cascade)
createdByUser User @relation("createdByUser", fields: [createdByUserId], references: [id], onDelete: Cascade)
row Row @relation(fields: [rowId], references: [id], onDelete: Cascade)
}
model EntityTemplate {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String?
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
entityId String
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
title String
config String
@@unique([tenantId, entityId, title])
}
model EntityGroup {
id String @id @default(cuid())
createdAt DateTime @default(now())
order Int
slug String
title String
icon String
collapsible Boolean
section String?
entities EntityGroupEntity[]
configurationRows EntityGroupConfiguration[]
@@unique([slug])
}
model EntityGroupEntity {
id String @id @default(cuid())
entityGroupId String
entityGroup EntityGroup @relation(fields: [entityGroupId], references: [id], onDelete: Cascade)
entityId String
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
allViewId String?
allView EntityView? @relation(fields: [allViewId], references: [id], onDelete: Cascade)
selectMin Int?
selectMax Int?
}
model Formula {
id String @id @default(cuid())
createdAt DateTime @default(now())
name String
description String?
resultAs String // string, number, boolean, date
calculationTrigger String // one or many: always, onList, onCreated, onOverview, onEdit, custom, manual
withLogs Boolean @default(false)
components FormulaComponent[]
inProperties Property[]
logs FormulaLog[]
}
model FormulaComponent {
id String @id @default(cuid())
formulaId String
formula Formula @relation(fields: [formulaId], references: [id], onDelete: Cascade)
order Int
type String //name, operator, parenthesis, value
value String
}
model FormulaLog {
id String @id @default(cuid())
createdAt DateTime @default(now())
formulaId String
userId String?
tenantId String?
originalTrigger String?
triggeredBy String
expression String
result String
duration Int @default(0)
error String?
rowValueId String?
formula Formula @relation(fields: [formulaId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
components FormulaComponentLog[]
}
model FormulaComponentLog {
id String @id @default(cuid())
order Int
type String //name, operator, parenthesis, value
value String
rowId String?
row Row? @relation(fields: [rowId], references: [id], onDelete: Cascade)
formulaLogId String
formulaLog FormulaLog @relation(fields: [formulaLogId], references: [id], onDelete: Cascade)
}
model EntityGroupConfiguration {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String?
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
entityGroupId String
entityGroup EntityGroup @relation(fields: [entityGroupId], references: [id], onDelete: Cascade)
title String
rows EntityGroupConfigurationRow[]
}
model EntityGroupConfigurationRow {
id String @id @default(cuid())
entityGroupConfigurationId String
entityGroupConfiguration EntityGroupConfiguration @relation(fields: [entityGroupConfigurationId], references: [id], onDelete: Cascade)
rowId String
row Row @relation(fields: [rowId], references: [id], onDelete: Cascade)
@@unique([entityGroupConfigurationId, rowId])
}
model ApiKeyEntity {
id String @id @default(cuid())
apiKeyId String
entityId String
create Boolean
read Boolean
update Boolean
delete Boolean
apiKey ApiKey @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)
entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)
}
model TenantSettingsRow {
tenantId String @id @unique
rowId String
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
row Row @relation(fields: [rowId], references: [id], onDelete: Cascade)
}
@@ -58,6 +58,10 @@ enum FileEntityType {
order
task
appointment
signature_document
// VA-P23 · mirrored mailbox message (email-inbox attachments -> Files).
// ADDITIVE cross-module touch of files.prisma, flagged per AD-21.
email_message
}
/// A stored file, scoped per tenant. `storageKey` points at the original object
@@ -95,6 +99,10 @@ model File {
@@index([tenantId, createdByUserId])
@@index([tenantId, assignedToUserId])
@@index([tenantId, checksumSha256])
// pg_trgm GIN index for fast ILIKE search on displayName; created originally
// via raw SQL in 20260623160000_p4a_files_platform. Modeled here so
// migrations<->schema parity holds (requires the pg_trgm extension).
@@index([displayName(ops: raw("gin_trgm_ops"))], type: Gin, map: "File_displayName_trgm_idx")
}
/// Polymorphic link of a file to any entity (cross-cutting). `entityType` +
@@ -10,12 +10,20 @@ model Form {
tenantId String
/// Public key used in the embed `<script data-form-key="…">`.
key String @unique @default(cuid())
/// Human-readable public URL slug for `/f/:tenant/:slug`.
slug String?
name String
subtype FormSubtype @default(standard)
status FormStatus @default(draft)
createdByUserId String?
publishedAt DateTime?
isPublic Boolean @default(false)
isDemoData Boolean @default(false)
/// Schema-versioned form definition JSON (validated by `FormDefinitionSchema`).
definition Json
/// Theme JSON (validated by `FormThemeSchema`). Empty object inherits tenant brand.
theme Json @default("{}")
/// "generic" | "crm-contact" | "entity-row".
/// Legacy route target. New AK-P16c action routing lives in FormAction.
targetType String @default("generic")
targetEntityId String?
/// Mapping from form field-key -> target row property-key.
@@ -32,8 +40,14 @@ model Form {
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
submissions FormSubmission[]
fields FormField[]
actions FormAction[]
files FormFile[]
@@unique([tenantId, slug])
@@index([tenantId, createdAt(sort: Desc)])
@@index([tenantId, createdByUserId, createdAt(sort: Desc)])
@@index([tenantId, status, createdAt(sort: Desc)])
@@index([key])
}
@@ -52,12 +66,161 @@ model FormSubmission {
status String @default("received")
/// JSON describing routing/webhook delivery outcome.
result Json?
linkedEntityType String?
linkedEntityId String?
idempotencyKey String?
gdprAccepted Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
form Form @relation(fields: [formId], references: [id], onDelete: Cascade)
files FormFile[]
actionLogs FormActionLog[]
@@unique([formId, idempotencyKey])
@@index([formId, createdAt(sort: Desc)])
@@index([tenantId, createdAt(sort: Desc)])
@@index([status])
@@index([tenantId, linkedEntityType, linkedEntityId])
}
enum FormStatus {
draft
published
archived
}
enum FormSubtype {
standard
acceptance_form
onboarding
survey
booking_intake
hr_request
}
enum FormFieldType {
text
textarea
number
date
time
select
multiselect
boolean
email
phone
file
photo
honeypot
}
enum FormActionType {
auto_match
create_lead
create_contact
create_project
create_task
send_email_to_team
send_email_to_submitter
webhook
trigger_automation
}
enum FormActionLogStatus {
pending
success
failed
skipped
}
model FormField {
id String @id @default(cuid())
formId String
tenantId String
fieldKey String
fieldType FormFieldType
label String
helpText String?
placeholder String?
required Boolean @default(false)
position Int
options Json @default("[]")
validationRules Json @default("{}")
conditionalLogic Json @default("[]")
isSystem Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
form Form @relation(fields: [formId], references: [id], onDelete: Cascade)
@@unique([formId, fieldKey])
@@index([tenantId, formId, position])
}
model FormFile {
id String @id @default(cuid())
formId String
submissionId String
tenantId String
fieldKey String
fileId String
kind String @default("file")
createdAt DateTime @default(now())
form Form @relation(fields: [formId], references: [id], onDelete: Cascade)
submission FormSubmission @relation(fields: [submissionId], references: [id], onDelete: Cascade)
@@index([tenantId, formId, fieldKey])
@@index([tenantId, submissionId])
@@index([fileId])
}
model FormAction {
id String @id @default(cuid())
formId String
tenantId String
actionType FormActionType
name String
position Int
enabled Boolean @default(true)
fieldMapping Json @default("{}")
actionConfig Json @default("{}")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
form Form @relation(fields: [formId], references: [id], onDelete: Cascade)
logs FormActionLog[]
@@index([tenantId, formId, position])
@@index([tenantId, actionType])
}
model FormActionLog {
id String @id @default(cuid())
formActionId String
submissionId String
formId String
tenantId String
actionType FormActionType
status FormActionLogStatus @default(pending)
attempt Int @default(1)
inputSnapshot Json @default("{}")
outputSnapshot Json?
errorMessage String?
targetType String?
targetId String?
idempotencyKey String
rerunOfLogId String?
startedAt DateTime @default(now())
finishedAt DateTime?
createdAt DateTime @default(now())
action FormAction @relation(fields: [formActionId], references: [id], onDelete: Cascade)
submission FormSubmission @relation(fields: [submissionId], references: [id], onDelete: Cascade)
@@unique([formActionId, submissionId, idempotencyKey])
@@index([tenantId, formId, createdAt(sort: Desc)])
@@index([tenantId, submissionId])
@@index([tenantId, status])
}
@@ -0,0 +1,107 @@
enum GdprExportScope {
user_self
tenant_full
}
enum GdprExportStatus {
queued
processing
ready
failed
expired
}
enum TenantDeletionRequestStatus {
pending
cancelled
executing
completed
failed
}
enum TenantDeletionReason {
voluntary
non_payment
suspended_violation
admin_initiated
}
model GdprExportJob {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
requestedByUserId String
targetUserId String?
scope GdprExportScope
status GdprExportStatus @default(queued)
progressPercent Int @default(0)
resultFileId String?
resultBucket String?
resultKey String?
resultSizeBytes Int?
resultExpiresAt DateTime?
downloadCount Int @default(0)
lastDownloadedAt DateTime?
errorMessage String?
processingStartedAt DateTime?
processingFinishedAt DateTime?
@@index([tenantId, status])
@@index([tenantId, requestedByUserId, scope, createdAt])
@@index([tenantId, targetUserId, scope, createdAt])
@@index([resultExpiresAt])
}
model TenantDeletionRequest {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
requestedByUserId String
reason TenantDeletionReason
reasonText String?
slugConfirmPhrase String
status TenantDeletionRequestStatus @default(pending)
gracePeriodEndsAt DateTime
cancelledAt DateTime?
cancelledByUserId String?
hardDeleteStartedAt DateTime?
hardDeleteEndedAt DateTime?
errorMessage String?
@@index([tenantId, status])
@@index([status, gracePeriodEndsAt])
}
model AvvAcceptance {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
acceptedByUserId String
acceptedIp String?
acceptedUserAgent String?
avvVersion String
pdfFileId String?
signerName String
signerRole String?
@@unique([tenantId, avvVersion])
@@index([tenantId, createdAt])
}
model Subprocessor {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String
purposeText String
country String
isEuEea Boolean @default(true)
dataCategories String[]
dpaUrl String?
activeSince DateTime?
archivedAt DateTime?
@@index([archivedAt])
}
@@ -25,8 +25,13 @@ model SupportTicket {
fromEmail String?
fromUrl String?
inboundMessageId String?
// AK-P19 — admin Support-Inbox: operator assignment + conversation thread.
assignedToUserId String?
assignedTo User? @relation("supportTicketAssignee", fields: [assignedToUserId], references: [id], onDelete: SetNull)
messages SupportTicketMessage[]
@@index([tenantId, status, createdAt])
@@index([source, createdAt])
@@index([assignedToUserId, status])
@@unique([inboundMessageId])
}
@@ -0,0 +1,679 @@
// P17 HR-Hub core (AK-P17a) — employee master data, locations, personnel
// documents and the encrypted team password safe.
//
// AD-21: one self-contained schema file per module. `tenantId` / `userId` /
// `*UserId` / `fileId` / `locationId` are intentionally BARE String scalars (no
// `@relation`) so this file has zero merge-conflict surface against
// `core.prisma`/`accounts.prisma` (no back-relation fields on Tenant/User
// needed). Referential integrity is carried by app-level scoping (the hr*Service
// helpers) plus the RLS policies from the merge migration (see
// prisma/rls/hr-isolation.sql). Documents reference File from files.prisma
// (AK-P4a/b) by bare `fileId` for the same reason.
//
// Scope v1 (AK-P17a ticket doc, strict): employee master data + locations +
// personnel documents + password safe ONLY. Announcements, leave/sick reports,
// payslips, requests, surveys and upload reminders belong to AK-P17b / follow-up
// and are intentionally NOT modelled here.
//
// ENCRYPTION (AD-8, deferred): sensitive values — the password-safe entry
// secrets and the employee emergency contact — are stored as ENVELOPE CIPHERTEXT
// strings (the `*Ciphertext` columns). Per the AK-P17a build decision the
// per-tenant DEK / KMS envelope layer is a separate infrastructure ticket; the
// service layer routes every read/write of these columns through the
// `hrFieldCrypto` seam (apps/web/app/utils/integrations/hrFieldCrypto.server.ts),
// whose production binding currently defers to that follow-up ticket. The schema
// is final; only the crypto binding is pending.
/// Visibility of an HR personnel document to the employee it belongs to.
/// `employee` = the employee can see (and, if self-uploaded, manage) it;
/// `hr_only` = visible to HR admins only.
enum HrDocumentVisibility {
employee
hr_only
}
/// Coarse kind of a personnel document (for filtering + upload reminders).
enum HrDocumentKind {
contract
certificate
identification
qualification
other
}
/// A linked HR resource / quick link kind.
enum HrResourceKind {
link
file
}
/// Access level a user holds on a password-safe vault. `read` may reveal/copy
/// values; `write` may also create/edit entries; `admin` may also manage access
/// and archive/delete the vault.
enum PasswordSafePermissionLevel {
read
write
admin
}
/// Per-tenant employee master record (1:1 with a global User). Self-maintainable
/// fields (e.g. position display, team) are edited by the employee; HR-managed
/// fields by HR admins (enforced in the service layer). The emergency contact is
/// sensitive and stored ENVELOPE-ENCRYPTED (`emergencyContactCiphertext`, holds
/// the name/phone/relation triple as encrypted JSON) — never returned without an
/// explicit, permission-checked reveal.
model HrEmployeeProfile {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
userId String
personalNumber String?
hireDate DateTime?
position String?
team String?
locationId String?
managerUserId String?
// Sensitive: AES-256-GCM envelope ciphertext (name/phone/relation as JSON).
emergencyContactCiphertext String?
isDemoData Boolean @default(false)
@@unique([tenantId, userId])
@@index([tenantId, locationId])
@@index([tenantId, managerUserId])
@@index([tenantId, team])
}
/// A physical company location, scoped per tenant. Soft-delete via `archivedAt`.
/// Exactly one location may be the tenant default (`isDefault`); enforced in the
/// service layer (set-default clears the previous default).
model HrLocation {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
name String
addressLine1 String?
addressLine2 String?
postalCode String?
city String?
country String?
phone String?
latitude Float?
longitude Float?
imageFileId String?
description String?
isDefault Boolean @default(false)
isDemoData Boolean @default(false)
archivedAt DateTime?
@@index([tenantId, archivedAt, name])
@@index([tenantId, isDefault])
}
/// A personnel document for one employee. The bytes live in a File (files.prisma,
/// referenced by bare `fileId`). `visibility` gates whether the employee sees it;
/// `uploadedByOffice` marks office-uploaded documents as READ-ONLY for the
/// employee (they may view/download but not edit or delete). Soft-delete via
/// `archivedAt`.
model HrEmployeeDocument {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
employeeUserId String
uploadedByUserId String
title String
documentKind HrDocumentKind @default(other)
fileId String
visibility HrDocumentVisibility @default(employee)
// True when uploaded by HR/office on behalf of the employee → read-only for
// the employee in the self-service "My documents" view.
uploadedByOffice Boolean @default(false)
validUntil DateTime?
isDemoData Boolean @default(false)
archivedAt DateTime?
@@index([tenantId, employeeUserId, archivedAt])
@@index([tenantId, documentKind])
@@index([tenantId, validUntil])
}
/// A shared HR resource (a link or a file) surfaced on the HR hub. Soft-delete
/// via `archivedAt`. `audience` is a coarse audience marker (e.g. "all",
/// "team:<id>"); fine-grained targeting is follow-up.
model HrResource {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
title String
kind HrResourceKind @default(link)
url String?
fileId String?
category String?
audience String @default("all")
sortOrder Int @default(0)
isDemoData Boolean @default(false)
archivedAt DateTime?
@@index([tenantId, archivedAt, category, sortOrder])
}
/// A quick link tile on the HR hub. Soft-delete via `archivedAt`.
model HrQuickLink {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
title String
url String
icon String?
audience String @default("all")
sortOrder Int @default(0)
isDemoData Boolean @default(false)
archivedAt DateTime?
@@index([tenantId, archivedAt, sortOrder])
}
/// A password-safe vault, scoped per tenant. Access is NOT implied by tenant
/// membership — a user only sees a vault they hold an EmployeePasswordSafeAccess
/// row for (or via the tenant-wide admin view, which never grants content
/// access). Soft-delete via `archivedAt`.
model EmployeePasswordSafeVault {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
name String
description String?
createdByUserId String
isDemoData Boolean @default(false)
archivedAt DateTime?
entries EmployeePasswordSafeEntry[]
access EmployeePasswordSafeAccess[]
@@index([tenantId, archivedAt, name])
}
/// A single secret in a vault. The secret values are stored ENVELOPE-ENCRYPTED
/// (`*Ciphertext`) and are NEVER selected into a list view — only an explicit,
/// permission-checked + audited reveal decrypts a single value on demand.
model EmployeePasswordSafeEntry {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
vaultId String
title String
tags String[] @default([])
url String?
// Sensitive: AES-256-GCM envelope ciphertext. Never returned in list queries.
usernameCiphertext String?
passwordCiphertext String?
notesCiphertext String?
isDemoData Boolean @default(false)
archivedAt DateTime?
vault EmployeePasswordSafeVault @relation(fields: [vaultId], references: [id], onDelete: Cascade)
@@index([tenantId, vaultId, archivedAt])
}
/// A user's access grant on a vault (M:N user↔vault with a permission level).
model EmployeePasswordSafeAccess {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
vaultId String
userId String
permissionLevel PasswordSafePermissionLevel @default(read)
grantedByUserId String
vault EmployeePasswordSafeVault @relation(fields: [vaultId], references: [id], onDelete: Cascade)
@@unique([vaultId, userId])
@@index([tenantId, userId])
}
// =============================================================================
// AK-P17b · P17 HR-Hub workflows — leave/sick, announcements, payslips, upload
// reminders, requests and surveys. Additive to this file (AD-21); same bare
// String-scalar convention (no `@relation` to core/User/File) so the merge
// surface against core.prisma/accounts.prisma stays zero. CalendarEvent (P16,
// M25) and the M05 FormSubmission (AK-P16c) are referenced by NULLABLE bare
// scalars only — both land after P17, so the actual calendar sync / form-render
// reuse is a deferred Dev-Nachzug; the columns are final.
//
// ENCRYPTION (AD-8): the sick-leave certificate ("AU-Schein") is sensitive. We
// envelope-encrypt the certificate File REFERENCE (`certificateRefCiphertext`)
// through the hrFieldCrypto seam (mirrors HrEmployeeProfile.emergencyContact):
// the column never reveals which File is the certificate without an explicit,
// permission-checked + audited reveal. (At-rest encryption of the File BYTES is
// a File-platform concern, tracked separately.)
// =============================================================================
/// Kind of a vacation/leave request.
enum HrVacationRequestKind {
vacation
special_leave
unpaid_leave
overtime_compensation
}
/// Approval state of a leave request. `clarification` = approver asked the
/// requester a question (Rückfrage) and awaits a reply before deciding.
enum HrLeaveRequestStatus {
submitted
clarification
approved
rejected
withdrawn
}
/// State of a sick-leave report.
enum HrSickLeaveStatus {
reported
closed
cancelled
}
/// Coarse audience marker for announcements / surveys / upload reminders.
/// `team`/`location` pair with `audienceRef` (the team or location id).
enum HrAudienceKind {
all
team
location
}
/// Kind of a generic HR request (template-driven).
enum HrRequestKind {
expense
hardware
training
reference
}
/// Approval state of an HR request (mirrors leave).
enum HrRequestStatus {
submitted
clarification
approved
rejected
withdrawn
}
/// Cadence of an upload reminder. `every_n_months` reads `intervalMonths`;
/// `on_expiry` derives the due date from a document's `validUntil`.
enum HrReminderCadenceKind {
once
yearly
every_n_months
on_expiry
}
/// Lifecycle of an upload-reminder definition.
enum HrReminderStatus {
active
paused
completed
}
/// State of a single dispatched reminder to one employee.
enum HrReminderDispatchStatus {
pending
sent
escalated
acknowledged
}
/// Survey item answer type.
enum HrSurveyItemType {
text
rating_5
nps
choice
boolean
date
}
/// Who may see a survey's aggregated results.
enum HrSurveyResultVisibility {
admins
participants
everyone
}
/// Lifecycle of a survey.
enum HrSurveyStatus {
draft
open
closed
}
/// A multi-step leave/vacation request. State machine: submitted →
/// {clarification ↔ submitted} → approved | rejected, or → withdrawn by the
/// requester. Only `approved` requests feed the absence calendar / plantafel
/// conflict feed (R-P9b). `calendarEventId` stays null until the P16 calendar
/// sync lands (deferred).
model EmployeeVacationRequest {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
employeeUserId String
requestKind HrVacationRequestKind @default(vacation)
startDate DateTime
endDate DateTime
note String?
status HrLeaveRequestStatus @default(submitted)
assignedApproverUserId String?
clarificationNote String?
decidedByUserId String?
decidedAt DateTime?
decisionNote String?
withdrawnAt DateTime?
// Deferred: CalendarEvent sync lands with P16 (M25). Bare nullable scalar.
calendarEventId String?
isDemoData Boolean @default(false)
@@index([tenantId, employeeUserId, status])
@@index([tenantId, assignedApproverUserId, status])
@@index([tenantId, status, startDate, endDate])
}
/// A sick-leave report, filed by the employee or by HR/office on their behalf
/// (`reportedByUserId`). The AU certificate reference is stored ENVELOPE-
/// ENCRYPTED (`certificateRefCiphertext`) and never returned without a
/// permission-checked + audited reveal.
model EmployeeSickLeaveReport {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
employeeUserId String
reportedByUserId String
startDate DateTime
expectedReturnDate DateTime?
returnDate DateTime?
// Sensitive: AES-256-GCM envelope ciphertext of the certificate File id.
certificateRefCiphertext String?
status HrSickLeaveStatus @default(reported)
note String?
// Deferred: CalendarEvent sync lands with P16 (M25).
calendarEventId String?
isDemoData Boolean @default(false)
@@index([tenantId, employeeUserId, status])
@@index([tenantId, status, startDate])
}
/// A company announcement. Markdown `body`, audience targeting, optional
/// acknowledgement requirement (read-receipt), scheduling (`publishAt`) and
/// expiry. Soft-delete via `archivedAt`.
model HrAnnouncement {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
authorUserId String
title String
body String
audienceKind HrAudienceKind @default(all)
audienceRef String?
requiresAcknowledgement Boolean @default(false)
pinnedAt DateTime?
publishAt DateTime?
expiresAt DateTime?
isDemoData Boolean @default(false)
archivedAt DateTime?
reads HrAnnouncementRead[]
reactions HrAnnouncementReaction[]
comments HrAnnouncementComment[]
@@index([tenantId, archivedAt, pinnedAt])
@@index([tenantId, publishAt])
}
/// Per-user read / acknowledgement receipt for an announcement.
/// `acknowledgedAt` is set only when the announcement required acknowledgement
/// and the user clicked confirm.
model HrAnnouncementRead {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
announcementId String
userId String
acknowledgedAt DateTime?
announcement HrAnnouncement @relation(fields: [announcementId], references: [id], onDelete: Cascade)
@@unique([announcementId, userId])
@@index([tenantId, userId])
}
/// A single emoji reaction by a user on an announcement.
model HrAnnouncementReaction {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
announcementId String
userId String
reaction String
announcement HrAnnouncement @relation(fields: [announcementId], references: [id], onDelete: Cascade)
@@unique([announcementId, userId, reaction])
@@index([tenantId, announcementId])
}
/// A single-level comment on an announcement. Soft-delete via `archivedAt`.
model HrAnnouncementComment {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
announcementId String
userId String
body String
archivedAt DateTime?
announcement HrAnnouncement @relation(fields: [announcementId], references: [id], onDelete: Cascade)
@@index([tenantId, announcementId, archivedAt])
}
/// A payslip PDF for one employee for one period. The bytes live in a File
/// (referenced by bare `fileId`). Opening the payslip marks it read
/// (`isRead`/`readAt`) and writes an audit event per read. Soft-delete via
/// `archivedAt`.
model EmployeePayslip {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
employeeUserId String
uploadedByUserId String
periodYear Int
periodMonth Int
fileId String
isRead Boolean @default(false)
readAt DateTime?
isDemoData Boolean @default(false)
archivedAt DateTime?
@@unique([tenantId, employeeUserId, periodYear, periodMonth])
@@index([tenantId, employeeUserId, archivedAt])
}
/// An upload-reminder definition: ask a targeted audience to upload a document
/// of a given kind on a cadence, optionally mandatory and escalating to the
/// manager when overdue. `linkedFormId` (M05) stays null until AK-P16c.
/// Soft-delete via `archivedAt`.
model EmployeeUploadReminder {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
title String
documentKind HrDocumentKind @default(other)
cadenceKind HrReminderCadenceKind @default(once)
intervalMonths Int?
audienceKind HrAudienceKind @default(all)
audienceRef String?
mandatory Boolean @default(false)
escalateToManager Boolean @default(false)
// M05 form template reference; null until AK-P16c renderer lands (deferred).
linkedFormId String?
dueAt DateTime?
status HrReminderStatus @default(active)
isDemoData Boolean @default(false)
archivedAt DateTime?
dispatches EmployeeUploadReminderDispatch[]
@@index([tenantId, status, dueAt])
}
/// One reminder dispatched to one employee for one due date. Idempotent per
/// (reminder, employee, dueAt) so the cadence worker never double-sends.
model EmployeeUploadReminderDispatch {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
reminderId String
employeeUserId String
dueAt DateTime
status HrReminderDispatchStatus @default(pending)
sentAt DateTime?
acknowledgedAt DateTime?
escalatedAt DateTime?
reminder EmployeeUploadReminder @relation(fields: [reminderId], references: [id], onDelete: Cascade)
@@unique([reminderId, employeeUserId, dueAt])
@@index([tenantId, employeeUserId, status])
}
/// A reusable HR request template (expense/hardware/training/reference) with an
/// optional default approver and linked M05 form (`linkedFormId`, null until
/// AK-P16c). Soft-delete via `archivedAt`.
model HrRequestTemplate {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
title String
requestKind HrRequestKind
description String?
defaultApproverUserId String?
linkedFormId String?
isActive Boolean @default(true)
isDemoData Boolean @default(false)
archivedAt DateTime?
requests HrRequest[]
@@index([tenantId, archivedAt, requestKind])
}
/// A generic HR request submitted by an employee, optionally from a template.
/// Until the M05 renderer (AK-P16c) lands, the payload is captured as a JSON
/// string in `details` (transitional form); `formSubmissionId` is wired in
/// later. Approval mirrors the leave state machine. Soft-delete via `archivedAt`.
model HrRequest {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
employeeUserId String
templateId String?
requestKind HrRequestKind
title String
// Transitional form payload (JSON string) until M05 submission is wired.
details String?
formSubmissionId String?
status HrRequestStatus @default(submitted)
assignedApproverUserId String?
clarificationNote String?
decidedByUserId String?
decidedAt DateTime?
decisionNote String?
withdrawnAt DateTime?
isDemoData Boolean @default(false)
archivedAt DateTime?
template HrRequestTemplate? @relation(fields: [templateId], references: [id], onDelete: SetNull)
@@index([tenantId, employeeUserId, status])
@@index([tenantId, assignedApproverUserId, status])
}
/// A survey. May be anonymous (`isAnonymous`); aggregated results are gated by
/// `resultVisibility`. Soft-delete via `archivedAt`.
model HrSurvey {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
authorUserId String
title String
description String?
isAnonymous Boolean @default(false)
resultVisibility HrSurveyResultVisibility @default(admins)
audienceKind HrAudienceKind @default(all)
audienceRef String?
status HrSurveyStatus @default(draft)
opensAt DateTime?
closesAt DateTime?
isDemoData Boolean @default(false)
archivedAt DateTime?
items HrSurveyItem[]
submissions HrSurveySubmission[]
@@index([tenantId, status, archivedAt])
}
/// One question in a survey. `options` holds the choices for `choice` items.
model HrSurveyItem {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
surveyId String
itemType HrSurveyItemType
prompt String
required Boolean @default(false)
options String[] @default([])
sortOrder Int @default(0)
survey HrSurvey @relation(fields: [surveyId], references: [id], onDelete: Cascade)
@@index([tenantId, surveyId])
}
/// One submission to a survey. For identified surveys `submitterUserId` is set
/// and unique per survey; for anonymous surveys it is null and `submitterHash`
/// (a non-reversible per-survey hash of the user) enforces one-submission
/// without re-identification. `answers` maps item id → answer value.
model HrSurveySubmission {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
surveyId String
submitterUserId String?
submitterHash String?
answers Json
survey HrSurvey @relation(fields: [surveyId], references: [id], onDelete: Cascade)
@@unique([surveyId, submitterUserId])
@@unique([surveyId, submitterHash])
@@index([tenantId, surveyId])
}
@@ -0,0 +1,121 @@
// R-P7 · P7 Lead-Inbox — typed lead intake domain (AD-20).
//
// AD-21: this module owns its schema file. Cross-module references to Kontakt,
// Projekt and User are intentionally bare String scalars so P7 can land without
// touching crm.prisma/accounts.prisma or a not-yet-existing project schema.
// App-level isolation runs through leadService + withTenantRLS(); the deferred
// RLS rollout artifact lives in prisma/rls/leads-isolation.sql.
enum LeadQuelle {
form
email
aircall
manual
custom
}
enum InboxLeadStatus {
new
qualified
converted
lost
spam
}
enum LeadWeiterverarbeitungFreigabe {
ja
nein
unklar
}
enum LeadSourceType {
system
custom
}
enum LeadAntiSpamMode {
quarantine
spam
}
model InboxLead {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
createdByUserId String?
zustaendigerUserId String?
quelle LeadQuelle
quelleDetail Json?
sourceId String?
sourceOrigin String?
submitterIpHash String?
status InboxLeadStatus @default(new)
weiterverarbeitungFreigabe LeadWeiterverarbeitungFreigabe @default(unklar)
vorname String?
nachname String?
email String?
telefon String?
message String?
rohdaten Json?
spamScore Int @default(0)
spamReason String?
isQuarantined Boolean @default(false)
konvertiertProjektId String?
verknuepfterKontaktId String?
convertedAt DateTime?
lostAt DateTime?
spamMarkedAt DateTime?
autoDeleteAt DateTime?
isDemoData Boolean @default(false)
archivedAt DateTime?
source LeadSource? @relation(fields: [sourceId], references: [id], onDelete: SetNull)
@@index([tenantId, status, createdAt])
@@index([tenantId, quelle, createdAt])
@@index([tenantId, sourceId, createdAt])
@@index([tenantId, submitterIpHash, createdAt])
@@index([tenantId, zustaendigerUserId, status])
@@index([tenantId, email])
@@index([tenantId, telefon])
@@index([tenantId, autoDeleteAt])
}
model LeadSource {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
type LeadSourceType
key String
name String
displayLabel String
defaultZustaendigerUserId String?
defaultTags Json?
webhookTokenHash String?
pausedAt DateTime?
archivedAt DateTime?
isDemoData Boolean @default(false)
leads InboxLead[]
@@unique([tenantId, key])
@@index([tenantId, type, archivedAt])
}
model LeadAntiSpamConfig {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String @unique
perSourcePerHourLimit Int @default(100)
perIpPerHourLimit Int @default(30)
anomalySpikeFactor Int @default(10)
mode LeadAntiSpamMode @default(quarantine)
disposableDomainEnabled Boolean @default(true)
honeypotEnabled Boolean @default(true)
fastSubmitEnabled Boolean @default(true)
lostAutoDeleteDays Int @default(0)
isDemoData Boolean @default(false)
}
@@ -0,0 +1,88 @@
// VR-MCP — OAuth 2.1 authorization state for remote MCP clients.
//
// Deliberately keeps bare tenant/user id scalars so the MCP auth module can
// evolve independently from the account core schema.
model McpOAuthClient {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
clientId String @unique
clientName String
redirectUris Json
grantTypes Json @default("[\"authorization_code\",\"refresh_token\"]")
scopes Json @default("[\"mcp:read\"]")
contacts Json?
metadata Json?
active Boolean @default(true)
authorizationCodes McpOAuthAuthorizationCode[]
accessTokens McpOAuthAccessToken[]
refreshTokens McpOAuthRefreshToken[]
@@index([active, createdAt], name: "mcp_oauth_client_active_created_idx")
}
model McpOAuthAuthorizationCode {
id String @id @default(cuid())
createdAt DateTime @default(now())
clientId String
userId String
tenantId String
tenantSlug String
codeHash String @unique
redirectUri String
scopes Json
resource String
codeChallenge String
codeChallengeMethod String
expiresAt DateTime
consumedAt DateTime?
client McpOAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade)
@@index([clientId, expiresAt], name: "mcp_oauth_code_client_expires_idx")
@@index([tenantId, userId], name: "mcp_oauth_code_tenant_user_idx")
}
model McpOAuthAccessToken {
id String @id @default(cuid())
createdAt DateTime @default(now())
clientId String
userId String
tenantId String
tenantSlug String
tokenHash String @unique
scopes Json
resource String
expiresAt DateTime
revokedAt DateTime?
refreshTokenId String?
client McpOAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade)
refreshToken McpOAuthRefreshToken? @relation(fields: [refreshTokenId], references: [id], onDelete: SetNull)
@@index([tenantId, userId], name: "mcp_oauth_access_tenant_user_idx")
@@index([clientId, expiresAt], name: "mcp_oauth_access_client_expires_idx")
}
model McpOAuthRefreshToken {
id String @id @default(cuid())
createdAt DateTime @default(now())
rotatedAt DateTime?
clientId String
userId String
tenantId String
tenantSlug String
tokenHash String @unique
scopes Json
resource String
expiresAt DateTime
revokedAt DateTime?
client McpOAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade)
accessTokens McpOAuthAccessToken[]
@@index([tenantId, userId], name: "mcp_oauth_refresh_tenant_user_idx")
@@index([clientId, expiresAt], name: "mcp_oauth_refresh_client_expires_idx")
}
@@ -55,9 +55,9 @@ model UserNotificationPreference {
@@index([tenantId, category], name: "user_notification_preference_tenant_category_idx")
}
// DeviceToken (Phase 08 #65 — Capacitor mobile wrapper).
// DeviceToken for PWA Web Push registrations.
//
// Tracks active APNs / FCM / WebPush device tokens per user. The
// Tracks active Web Push tokens per user. The
// register-device API endpoint upserts by `token` (globally unique).
// `lastSeenAt` is bumped on every successful send so an out-of-band
// cron can prune tokens older than 90d without disrupting active users.
@@ -71,7 +71,7 @@ model DeviceToken {
tenantId String?
platform String // 'ios' | 'android' | 'web'
token String @unique
pushProvider String // 'fcm' | 'apns' | 'webpush'
pushProvider String // 'webpush'
appVersion String?
lastSeenAt DateTime @default(now())
revokedAt DateTime?
@@ -81,3 +81,20 @@ model OnboardingSessionStep {
seenAt DateTime?
completedAt DateTime?
}
model OnboardingDemoProvisioning {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
createdByUserId String?
templateCode String
status String @default("active")
entitiesCreated Json
removableUntil DateTime?
deletedAt DateTime?
@@index([tenantId, templateCode, status])
@@index([tenantId, createdAt])
}
@@ -11,7 +11,6 @@ model Role {
isDefault Boolean
order Int
permissions RolePermission[]
rowPermissions RowPermission[]
users UserRole[]
@@index([tenantId, type])
@@ -28,8 +27,6 @@ model Permission {
isDefault Boolean
order Int
inRoles RolePermission[]
entityId String?
entity Entity? @relation(fields: [entityId], references: [id], onDelete: Cascade)
}
model RolePermission {
@@ -70,7 +67,6 @@ model Group {
createdByUser User @relation(fields: [createdByUserId], references: [id], onDelete: Cascade)
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
users GroupUser[]
rowPermissions RowPermission[]
@@index([createdByUserId], name: "group_createdByUserId")
}
@@ -83,4 +79,6 @@ model GroupUser {
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([groupId, userId], name: "group_user_membership_key")
@@index([userId])
@@index([groupId])
}
@@ -96,7 +96,7 @@ model PluginUserConfig {
// Phase 06 #23 — durable per-invocation audit row.
//
// One row per `toolctrl.plugin-invoke` job outcome. Capability-use rows
// One row per `hivegrid.plugin-invoke` job outcome. Capability-use rows
// reference the same `pluginInvocationId` so operators can correlate the
// high-level invocation outcome with the individual host capability
// calls emitted during sandbox execution. The row intentionally stores
@@ -10,7 +10,7 @@ model Portal {
domain String? @unique
title String
isPublished Boolean @default(false)
stripeAccountId String?
paymentProviderAccountId String?
themeColor String?
themeScheme String?
seoTitle String?
@@ -108,7 +108,7 @@ model PortalSubscriptionProduct {
id String @id @default(cuid())
portalId String
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
stripeId String
billingProviderId String
order Int
title String
active Boolean
@@ -132,7 +132,7 @@ model PortalSubscriptionPrice {
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
subscriptionProductId String
subscriptionProduct PortalSubscriptionProduct @relation(fields: [subscriptionProductId], references: [id], onDelete: Cascade)
stripeId String
billingProviderId String
type Int
billingPeriod Int
price Decimal
@@ -163,7 +163,7 @@ model PortalUserSubscription {
portalId String
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
portalUserId String @unique
stripeCustomerId String?
billingProviderCustomerId String?
portalUser PortalUser @relation(fields: [portalUserId], references: [id], onDelete: Cascade)
products PortalUserSubscriptionProduct[]
}
@@ -177,7 +177,7 @@ model PortalUserSubscriptionProduct {
subscriptionProductId String
cancelledAt DateTime?
endsAt DateTime?
stripeSubscriptionId String?
billingProviderSubscriptionId String?
quantity Int?
fromCheckoutSessionId String?
currentPeriodStart DateTime?
@@ -0,0 +1,271 @@
// R-P8a (P8 Projekt & Pipelines core) — typed project/pipeline entities.
//
// AD-20: there is ONE `Projekt` core. "Deal" and "Auftrag" are pipeline
// views (`Pipeline.typHint`), not separate entities and not a won-handoff copy.
//
// AD-21: this module owns its schema file. Cross-module references to Tenant,
// User, Kontakt, InboxLead and Adresse are intentionally bare String scalars so
// this slice does not modify core/accounts/crm/leads schemas.
enum PipelineTypHint {
sales
auftrag
custom
}
enum PipelineStageKind {
offen
gewonnen
verloren
}
enum PipelinePrincipalType {
role
group
user
}
enum ProjektPrioritaet {
niedrig
normal
hoch
dringend
}
enum ProjektKontaktRolle {
auftraggeber
bauherr
rechnungsempfaenger
ansprechpartner
}
model HiveNumberSeq {
id String @id @default(cuid())
tenantId String
entityType String
prefix String
nextNumber Int @default(1)
padding Int @default(5)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([tenantId, entityType])
@@index([tenantId])
}
model Pipeline {
id String @id @default(cuid())
tenantId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdByUserId String?
name String
typHint PipelineTypHint
position Int @default(0)
isDefault Boolean @default(false)
isDemoData Boolean @default(false)
archivedAt DateTime?
stages PipelineStage[]
accessRules PipelineAccess[]
fieldConfigs PipelineFieldConfig[]
projekte Projekt[]
@@unique([tenantId, name])
@@index([tenantId, typHint, archivedAt])
@@index([tenantId, position])
}
model PipelineStage {
id String @id @default(cuid())
tenantId String
pipelineId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String
stageKind PipelineStageKind
winProbability Int @default(0)
color String @default("#6b7280")
position Int @default(0)
isDemoData Boolean @default(false)
archivedAt DateTime?
pipeline Pipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)
fieldConfigs PipelineFieldConfig[]
projekte Projekt[]
@@unique([pipelineId, name])
@@index([tenantId, pipelineId, archivedAt])
@@index([tenantId, stageKind])
}
model PipelineAccess {
id String @id @default(cuid())
tenantId String
pipelineId String
principalType PipelinePrincipalType
principalId String
kannSehen Boolean @default(true)
kannBearbeiten Boolean @default(false)
createdAt DateTime @default(now())
pipeline Pipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)
@@unique([pipelineId, principalType, principalId])
@@index([tenantId, principalType, principalId])
}
model PipelineFieldConfig {
id String @id @default(cuid())
tenantId String
pipelineId String
stageId String?
fieldKey String
sichtbar Boolean @default(true)
pflicht Boolean @default(false)
reihenfolge Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
pipeline Pipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)
stage PipelineStage? @relation(fields: [stageId], references: [id], onDelete: Cascade)
visibilities PipelineFieldVisibility[]
@@unique([pipelineId, stageId, fieldKey])
@@index([tenantId, pipelineId])
@@index([tenantId, fieldKey])
}
model PipelineFieldVisibility {
id String @id @default(cuid())
tenantId String
fieldConfigId String
principalType PipelinePrincipalType
principalId String
kannSehen Boolean @default(true)
kannBearbeiten Boolean @default(false)
createdAt DateTime @default(now())
fieldConfig PipelineFieldConfig @relation(fields: [fieldConfigId], references: [id], onDelete: Cascade)
@@unique([fieldConfigId, principalType, principalId])
@@index([tenantId, principalType, principalId])
}
model LostReason {
id String @id @default(cuid())
tenantId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String
position Int @default(0)
isDemoData Boolean @default(false)
archivedAt DateTime?
projekte Projekt[]
@@unique([tenantId, name])
@@index([tenantId, archivedAt])
}
model Projekt {
id String @id @default(cuid())
tenantId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdByUserId String?
projektNummer String
projektname String
beschreibung String?
projekttyp String?
quelle String?
prioritaet ProjektPrioritaet @default(normal)
pipelineId String
stageId String
potenziellerAuftragswert Decimal?
auftragsvolumen Decimal?
startDatum DateTime?
deadline DateTime?
zustaendigePersonId String?
projektleiterId String?
projektAdresseId String?
rechnungsAdresseId String?
bauherrAdresseId String?
konvertiertAusLeadId String?
lostReasonId String?
wonAt DateTime?
lostAt DateTime?
undoStageChangeUntil DateTime?
isDemoData Boolean @default(false)
archivedAt DateTime?
pipeline Pipeline @relation(fields: [pipelineId], references: [id])
stage PipelineStage @relation(fields: [stageId], references: [id])
lostReason LostReason? @relation(fields: [lostReasonId], references: [id], onDelete: SetNull)
kontakte ProjektKontakt[]
stageChanges ProjektStageChange[]
@@unique([tenantId, projektNummer])
@@index([tenantId, pipelineId, stageId, archivedAt])
@@index([tenantId, zustaendigePersonId])
@@index([tenantId, projektleiterId])
@@index([tenantId, konvertiertAusLeadId])
@@index([tenantId, lostReasonId])
}
model ProjektStageChange {
id String @id @default(cuid())
tenantId String
projektId String
fromStageId String
toStageId String
lostReasonId String?
changedByUserId String?
undoUntil DateTime?
undoneAt DateTime?
createdAt DateTime @default(now())
projekt Projekt @relation(fields: [projektId], references: [id], onDelete: Cascade)
@@index([tenantId, projektId, createdAt])
@@index([tenantId, toStageId, createdAt])
@@index([tenantId, undoUntil])
}
model PipelineAggregateSnapshot {
id String @id @default(cuid())
tenantId String
pipelineId String
stageId String?
scopeKey String
projectCount Int @default(0)
potentialValue Decimal @default(0)
orderVolume Decimal @default(0)
weightedForecast Decimal @default(0)
realizedRevenue Decimal @default(0)
lostCount Int @default(0)
stageConversionRate Decimal?
lostReasonDistribution Json @default("{}")
isDemoDataIncluded Boolean @default(false)
calculatedAt DateTime @default(now())
@@unique([tenantId, pipelineId, scopeKey])
@@index([tenantId, pipelineId])
@@index([tenantId, calculatedAt])
}
model ProjektKontakt {
id String @id @default(cuid())
tenantId String
createdAt DateTime @default(now())
projektId String
kontaktId String
rolle ProjektKontaktRolle
primaer Boolean @default(false)
projekt Projekt @relation(fields: [projektId], references: [id], onDelete: Cascade)
@@unique([projektId, kontaktId, rolle])
@@index([tenantId, projektId])
@@index([tenantId, kontaktId])
}
@@ -0,0 +1,133 @@
// VR-P22b · Public API auth, scopes and webhooks.
//
// AD-21: public API owns this schema file. Shared core models like ApiKey and
// Tenant are referenced by bare String scalars unless a relation is already
// owned by the target module.
enum PublicWebhookAuthMode {
api_key
hmac
url_token
}
enum PublicWebhookEndpointStatus {
active
paused
archived
}
enum PublicWebhookDeliveryStatus {
queued
delivering
success
failed
retrying
disabled
}
model PublicIncomingWebhookEndpoint {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
slug String
name String
authMode PublicWebhookAuthMode
apiKeyId String?
tokenHash String?
tokenPrefix String?
tokenLastFour String?
hmacSecretHash String?
hmacSecretPrefix String?
hmacSecretLastFour String?
payloadMapping Json @default("{}")
autoMatchRules Json @default("{}")
status PublicWebhookEndpointStatus @default(active)
pausedAt DateTime?
archivedAt DateTime?
isDemoData Boolean @default(false)
ingestionLogs PublicWebhookIngestionLog[]
@@unique([tenantId, slug])
@@index([tenantId, status, archivedAt])
@@index([apiKeyId])
}
model PublicWebhookIngestionLog {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
endpointId String?
endpointSlug String
authMode PublicWebhookAuthMode?
requestId String?
sourceIp String?
status Int
result String
payloadHash String?
payloadPreview Json?
leadId String?
matchedKontaktId String?
automationRunId String?
error String?
endpoint PublicIncomingWebhookEndpoint? @relation(fields: [endpointId], references: [id], onDelete: SetNull)
@@index([tenantId, createdAt])
@@index([tenantId, endpointId, createdAt])
@@index([tenantId, leadId])
}
model PublicWebhookSubscription {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
name String
targetUrl String
eventTypes Json @default("[]")
signingSecretHash String
signingSecretPrefix String
signingSecretLastFour String
status PublicWebhookEndpointStatus @default(active)
failureCount Int @default(0)
lastDeliveredAt DateTime?
lastErrorAt DateTime?
autoDisabledAt DateTime?
pausedAt DateTime?
archivedAt DateTime?
createdByUserId String?
isDemoData Boolean @default(false)
deliveries PublicWebhookDeliveryLog[]
@@unique([tenantId, name])
@@index([tenantId, status, archivedAt])
}
model PublicWebhookDeliveryLog {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
subscriptionId String
eventType String
targetUrl String
status PublicWebhookDeliveryStatus @default(queued)
httpStatus Int?
attempt Int @default(1)
maxAttempts Int @default(5)
nextAttemptAt DateTime?
idempotencyKey String
payloadHash String
error String?
responsePreview Json?
sentAt DateTime?
subscription PublicWebhookSubscription @relation(fields: [subscriptionId], references: [id], onDelete: Cascade)
@@unique([subscriptionId, idempotencyKey])
@@index([tenantId, status, nextAttemptAt])
@@index([tenantId, eventType, createdAt])
}
@@ -0,0 +1,43 @@
// R-P11a (P11 Global Search) — typed search metadata and recent searches.
//
// AD-21: self-contained schema. Entity references are polymorphic bare scalars
// so this slice does not touch the owning module schemas. Meilisearch remains
// the keyword backend; these rows provide permission-aware metadata, recents,
// and tenant snapshot/restore coverage.
model SearchIndexEntry {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
tenantId String
entityType String
entityId String
title String
subtitle String?
bodyText String @default("")
routePath String
sourceIndex String
permissionSubject String
lastIndexedAt DateTime @default(now())
isArchived Boolean @default(false)
isDemoData Boolean @default(false)
metadata Json @default("{}")
@@unique([tenantId, entityType, entityId])
@@index([tenantId, entityType, isArchived])
@@index([tenantId, permissionSubject])
@@index([tenantId, updatedAt])
}
model RecentSearch {
id String @id @default(cuid())
createdAt DateTime @default(now())
tenantId String
userId String
queryText String
appliedFilters Json @default("{}")
resultCount Int @default(0)
@@index([tenantId, userId, createdAt(sort: Desc)])
@@index([tenantId, queryText])
}
@@ -0,0 +1,188 @@
// AK-P16d (P16) Signature — hardened self-hosted SES default plus optional
// PandaDoc BYOK adapter.
//
// AD-25: v1 default is the self-hosted SES flow (`ses-selfhosted`), not a
// mandatory external provider. PandaDoc remains an opt-in BYOK adapter
// (`pandadoc-byok`) through the Apps-Engine DataConnection. AD-20: signature
// documents attach to the `Projekt` core via bare `projektId`, never to a Deal.
//
// AD-21: this module owns its schema file. Cross-module references to Projekt,
// DataConnection, File, Kontakt and User are intentionally bare String scalars
// so this slice does not edit neighboring schema files. Intra-module relations
// stay inside this file.
enum SignatureProvider {
ses_selfhosted
pandadoc_byok
}
enum SignatureDocumentStatus {
draft
sent
viewed
signed
declined
revoked
expired
}
enum SignatureSignerStatus {
draft
sent
viewed
otp_verified
signed
declined
revoked
expired
}
enum SignatureSignerRole {
kunde
bauherr
auftraggeber
rechnungsempfaenger
intern
}
enum SignatureRoutingMode {
parallel
sequential
}
enum SignatureEventType {
link_created
link_opened
otp_requested
otp_verified
document_sent
document_viewed
signer_signed
signer_declined
reminder_sent
document_revoked
provider_webhook
pdf_sealed
certificate_created
}
model SignatureProviderConnection {
id String @id @default(cuid())
tenantId String
provider SignatureProvider
dataConnectionId String?
label String
isDefault Boolean @default(false)
webhookSharedKeyId String?
healthMessageKey String?
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
documents ProjektSignatureDocument[]
@@unique([tenantId, provider, dataConnectionId])
@@index([tenantId, provider, isDefault, archivedAt])
@@index([tenantId, dataConnectionId])
}
model ProjektSignatureDocument {
id String @id @default(cuid())
tenantId String
projektId String
providerConnectionId String?
provider SignatureProvider @default(ses_selfhosted)
providerDocumentId String?
sourcePdfFileId String
signedPdfFileId String?
completionCertFileId String?
status SignatureDocumentStatus @default(draft)
routingMode SignatureRoutingMode @default(parallel)
title String
subject String?
message String?
externalStatusPayload Json @default("{}")
documentHashSha256 String?
sealedPdfHashSha256 String?
completionCertHashSha256 String?
sentAt DateTime?
completedAt DateTime?
revokedAt DateTime?
declinedAt DateTime?
expiresAt DateTime?
createdByUserId String?
isDemoData Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
archivedAt DateTime?
providerConnection SignatureProviderConnection? @relation(fields: [providerConnectionId], references: [id], onDelete: SetNull)
signers ProjektSignatureSigner[]
events SignatureEvent[]
@@index([tenantId, projektId, archivedAt, createdAt])
@@index([tenantId, status])
@@index([tenantId, provider, providerDocumentId])
@@index([tenantId, sourcePdfFileId])
@@index([tenantId, signedPdfFileId])
@@index([tenantId, completionCertFileId])
}
model ProjektSignatureSigner {
id String @id @default(cuid())
tenantId String
documentId String
signerEmail String
signerName String
signerRole SignatureSignerRole @default(kunde)
linkedKontaktId String?
status SignatureSignerStatus @default(draft)
signingOrder Int @default(0)
accessTokenHash String? @unique
otpHash String?
otpExpiresAt DateTime?
lastLinkOpenedAt DateTime?
lastReminderAt DateTime?
viewedAt DateTime?
signedAt DateTime?
declinedAt DateTime?
revokedAt DateTime?
signerIpHash String?
signerUserAgent String?
intentText String?
signatureSvg String?
signatureImageFileId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
document ProjektSignatureDocument @relation(fields: [documentId], references: [id], onDelete: Cascade)
events SignatureEvent[]
@@index([tenantId, documentId, signingOrder])
@@index([tenantId, signerEmail])
@@index([tenantId, linkedKontaktId])
@@index([tenantId, accessTokenHash])
}
model SignatureEvent {
id String @id @default(cuid())
tenantId String
documentId String
signerId String?
eventType SignatureEventType
actorUserId String?
providerEventId String?
ipHash String?
userAgent String?
metadata Json @default("{}")
createdAt DateTime @default(now())
document ProjektSignatureDocument @relation(fields: [documentId], references: [id], onDelete: Cascade)
signer ProjektSignatureSigner? @relation(fields: [signerId], references: [id], onDelete: SetNull)
@@unique([tenantId, providerEventId])
@@index([tenantId, documentId, createdAt])
@@index([tenantId, signerId, createdAt])
@@index([tenantId, eventType, createdAt])
}
@@ -1,6 +1,8 @@
model SubscriptionProduct {
id String @id @default(cuid())
stripeId String
billingProviderId String
code String?
lagoPlanCode String?
order Int
title String
active Boolean
@@ -18,13 +20,18 @@ model SubscriptionProduct {
tenantProducts TenantSubscriptionProduct[]
usageBasedPrices SubscriptionUsageBasedPrice[]
assignsTenantTypes TenantType[]
@@index([code])
@@index([lagoPlanCode])
}
model SubscriptionPrice {
id String @id @default(cuid())
subscriptionProductId String
subscriptionProduct SubscriptionProduct @relation(fields: [subscriptionProductId], references: [id], onDelete: Cascade)
stripeId String
billingProviderId String
lagoFeeCode String?
molliePriceReference String?
type Int
billingPeriod Int
price Decimal
@@ -32,13 +39,16 @@ model SubscriptionPrice {
trialDays Int
active Boolean
tenantProductPrices TenantSubscriptionProductPrice[]
@@index([lagoFeeCode])
@@index([molliePriceReference])
}
model SubscriptionUsageBasedPrice {
id String @id @default(cuid())
subscriptionProductId String
subscriptionProduct SubscriptionProduct @relation(fields: [subscriptionProductId], references: [id], onDelete: Cascade)
stripeId String
billingProviderId String
billingPeriod Int
currency String
unit String
@@ -68,20 +78,47 @@ model SubscriptionFeature {
order Int
title String
name String
code String?
type Int
value Int
quotaValue Json?
href String?
badge String?
accumulate Boolean @default(false)
subscriptionProduct SubscriptionProduct @relation(fields: [subscriptionProductId], references: [id], onDelete: Cascade)
@@index([code])
}
model TenantSubscription {
id String @id @default(cuid())
tenantId String @unique
stripeCustomerId String?
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
products TenantSubscriptionProduct[]
id String @id @default(cuid())
tenantId String @unique
billingProviderCustomerId String?
lagoCustomerId String?
mollieCustomerId String?
planCode String?
seatQuantity Int @default(1)
lastInvoiceExternalId String?
lastPaymentExternalId String?
status String @default("trial")
trialStartsAt DateTime?
trialEndsAt DateTime?
pastDueSince DateTime?
frozenAt DateTime?
cancelledAt DateTime?
dunningAttemptCount Int @default(0)
lastDunningSentAt DateTime?
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
products TenantSubscriptionProduct[]
usageRecords TenantSubscriptionUsageRecord[]
@@index([status])
@@index([planCode])
@@index([lagoCustomerId])
@@index([mollieCustomerId])
@@index([trialEndsAt])
@@index([pastDueSince])
@@index([frozenAt])
}
model TenantSubscriptionProduct {
@@ -92,7 +129,10 @@ model TenantSubscriptionProduct {
customEntitlementPlanId String?
cancelledAt DateTime?
endsAt DateTime?
stripeSubscriptionId String?
billingProviderSubscriptionId String?
lagoSubscriptionId String?
planCode String?
seatQuantity Int?
quantity Int?
fromCheckoutSessionId String?
currentPeriodStart DateTime?
@@ -100,6 +140,9 @@ model TenantSubscriptionProduct {
tenantSubscription TenantSubscription @relation(fields: [tenantSubscriptionId], references: [id], onDelete: Cascade)
subscriptionProduct SubscriptionProduct @relation(fields: [subscriptionProductId], references: [id])
prices TenantSubscriptionProductPrice[]
@@index([lagoSubscriptionId])
@@index([planCode])
}
model TenantSubscriptionProductPrice {
@@ -110,16 +153,24 @@ model TenantSubscriptionProductPrice {
subscriptionPrice SubscriptionPrice? @relation(fields: [subscriptionPriceId], references: [id])
subscriptionUsageBasedPriceId String?
subscriptionUsageBasedPrice SubscriptionUsageBasedPrice? @relation(fields: [subscriptionUsageBasedPriceId], references: [id])
usageRecords TenantSubscriptionUsageRecord[]
quantity Int @default(1)
isMetered Boolean @default(false)
}
model TenantSubscriptionUsageRecord {
id String @id @default(cuid())
tenantId String
tenantSubscriptionId String
tenantSubscriptionProductPriceId String
tenantSubscriptionProductPrice TenantSubscriptionProductPrice @relation(fields: [tenantSubscriptionProductPriceId], references: [id], onDelete: Cascade)
tenantSubscription TenantSubscription @relation(fields: [tenantSubscriptionId], references: [id], onDelete: Cascade)
metricCode String @default("legacy")
timestamp Int
quantity Int
stripeSubscriptionItemId String?
idempotencyKey String?
billingProviderSubscriptionItemId String?
@@unique([tenantId, metricCode, idempotencyKey])
@@index([tenantId, metricCode, timestamp])
}
model TenantProductConfiguration {
@@ -147,16 +198,44 @@ model TenantFeatureOverride {
}
model CheckoutSessionStatus {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @unique
pending Boolean @default(true) // has not added products to tenant
email String
fromUrl String
fromUserId String?
fromTenantId String?
createdUserId String?
createdTenantId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
id String @unique
pending Boolean @default(true) // has not added products to tenant
email String
fromUrl String
fromUserId String?
fromTenantId String?
createdUserId String?
createdTenantId String?
provider String?
providerPaymentId String?
invoiceExternalId String?
subscriptionProductId String?
subscriptionPriceId String?
lagoSubscriptionId String?
planCode String?
quantity Int @default(1)
amountCents Int?
currency String?
checkoutUrl String?
status String @default("open")
@@index([providerPaymentId])
@@index([fromTenantId, pending])
}
model BillingWebhookLog {
id String @id @default(cuid())
createdAt DateTime @default(now())
providerEventId String @unique
eventType String
processedAt DateTime?
relatedTenantId String?
error String?
@@index([eventType, createdAt])
@@index([relatedTenantId, createdAt])
}
model Credit {
@@ -86,6 +86,10 @@ model Task {
@@index([tenantId, createdByUserId])
@@index([tenantId, linkedEntityType, linkedEntityId])
@@index([tenantId, status, completedAt]) // for the 30-day archive sweep
// pg_trgm GIN index for fast ILIKE title search; created originally via raw
// SQL in 20260624120000_p4b_tasks_entitylinks. Modeled here so
// migrations<->schema parity holds (requires the pg_trgm extension).
@@index([title(ops: raw("gin_trgm_ops"))], type: Gin, map: "Task_title_trgm_idx")
}
/// A user watching a task (M:N). Watchers receive reminder notifications in