/* !!! This is code generated by Prisma. Do not edit directly. !!! */ /* eslint-disable */ // biome-ignore-all lint: generated file // @ts-nocheck /* * WARNING: This is an internal file that is subject to change! * * 🛑 Under no circumstances should you import this file directly! 🛑 * * Please import the `PrismaClient` class from the `client.ts` file instead. */ import * as runtime from "@prisma/client/runtime/client" import type * as Prisma from "./prismaNamespace.ts" const config: runtime.GetPrismaClientConfig = { "previewFeatures": [], "clientVersion": "7.8.0", "engineVersion": "3c6e192761c0362d496ed980de936e2f3cebcd3a", "activeProvider": "postgresql", "inlineSchema": "model User {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n email String @unique\n passwordHash String?\n firstName String\n lastName String\n avatar String?\n phone String?\n defaultTenantId String?\n verifyToken String?\n verifyTokenCreatedAt DateTime?\n locale String?\n lightOrDarkMode String?\n totpSecretEncrypted String?\n totpPendingSecretEncrypted String?\n totpEnabledAt DateTime?\n totpPendingCreatedAt DateTime?\n mfaRecoveryCodeHashes Json?\n mfaRecoveryCodesGeneratedAt DateTime?\n mfaRecoveryCodeLastUsedAt DateTime?\n active Boolean @default(false)\n // Phase 10 Task #68 — DSGVO bulk-ops self-service flags.\n // `pendingDeletion` is set the moment the user confirms a delete request via\n // the email-verification token; `scheduledDeletionAt` carries the 30-day\n // grace deadline. `pseudonymized` is flipped permanently once the cascade\n // job has rewritten PII to deterministic pseudonyms (Art. 17 alternative\n // path for retention-bound rows such as AuditEvents). `deletionRequestId`\n // is the idempotency token shared with the worker job + audit trail.\n pendingDeletion Boolean @default(false)\n scheduledDeletionAt DateTime?\n deletionRequestedAt DateTime?\n pseudonymized Boolean @default(false)\n pseudonymizedAt DateTime?\n deletionRequestId String? @unique\n admin AdminUser? // Has access to the admin panel\n createdApiKeys ApiKey[]\n createdGroups Group[]\n groups GroupUser[]\n logs Log[]\n tenants TenantUser[]\n invitation TenantUserInvitation? @relation(\"createdUser\")\n sentInvitations TenantUserInvitation[] @relation(\"fromUser\")\n acceptedInvitations TenantUserInvitation[] @relation(\"acceptedByUser\")\n revokedInvitations TenantUserInvitation[] @relation(\"revokedByUser\")\n roles UserRole[]\n readEmails EmailRead[]\n onboardingSessions OnboardingSession[]\n tenantIpAddresses TenantIpAddress[]\n analyticsUniqueSessions AnalyticsUniqueVisitor[]\n metricLogs MetricLog[]\n knowledgeBaseArticles KnowledgeBaseArticle[]\n events Event[]\n workflowsCreated Workflow[] @relation(\"createdByUser\")\n workflowsExecuted WorkflowExecution[] @relation(\"executedByUser\")\n workflowVariablesCreated WorkflowVariable[]\n workflowCredentialsCreated WorkflowCredential[]\n feedback Feedback[]\n supportTickets SupportTicket[]\n assignedSupportTickets SupportTicket[] @relation(\"supportTicketAssignee\")\n supportTicketMessages SupportTicketMessage[] @relation(\"supportTicketMessageAuthor\")\n adminTenantNotesAuthored AdminTenantNote[] @relation(\"adminTenantNoteAuthor\")\n credits Credit[]\n portals Portal[]\n impersonationAuditsActor ImpersonationAudit[] @relation(\"ImpersonationAuditActor\")\n impersonationAuditsTarget ImpersonationAudit[] @relation(\"ImpersonationAuditTarget\")\n notificationDeliveries NotificationDelivery[]\n userSessions UserSession[]\n trustedDevices TrustedDevice[]\n notificationPreferences UserNotificationPreference[]\n deviceTokens DeviceToken[]\n magicLinkTokens MagicLinkToken[]\n\n // Apps-Engine (R-P5) uses bare String scalars for tenantId/createdByUserId\n // (AD-21) — no back-relations here.\n\n sitesCreated Site[] @relation(\"sitesCreatedByUser\")\n\n // Phase 10 Task #68 — grace-period cron query scans pendingDeletion users\n // whose deadline has elapsed. Index keeps the cron O(log n).\n @@index([pendingDeletion, scheduledDeletionAt], name: \"user_pending_deletion_due_idx\")\n}\n\nmodel MagicLinkToken {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n userId String\n tokenHash String @unique\n expiresAt DateTime\n consumedAt DateTime?\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId, expiresAt])\n @@index([expiresAt, consumedAt])\n}\n\n// Has access to the admin panel\nmodel AdminUser {\n userId String @id @unique\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n // Phase 09 #82 — OIDC SSO link to external IdP (Authentik).\n // ssoProvider / ssoSubjectId together identify the federated identity\n // (typically `authentik` + the IdP-stable `sub` claim). Both nullable so\n // legacy bootstrap admins predating SSO continue to function.\n ssoProvider String?\n ssoSubjectId String?\n ssoGroups String[] @default([])\n lastSsoLoginAt DateTime?\n\n @@unique([ssoProvider, ssoSubjectId])\n @@index([ssoSubjectId])\n}\n\nmodel Tenant {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n slug String @unique\n name String\n icon String?\n logo String?\n subscriptionId String?\n active Boolean @default(false)\n deactivatedReason String?\n apiKeys ApiKey[]\n apiKeyLogs ApiKeyLog[]\n groups Group[]\n logs Log[]\n subscription TenantSubscription?\n productConfiguration TenantProductConfiguration?\n featureOverrides TenantFeatureOverride[]\n users TenantUser[]\n roles Role[]\n invitations TenantUserInvitation[]\n userRoles UserRole[]\n inboundAddresses TenantInboundAddress[]\n events Event[]\n fromRegistration Registration?\n emailSenders EmailSender[]\n campaigns Campaign[]\n outboundEmails OutboundEmail[]\n onboardingSessions OnboardingSession[]\n onboardingDemoProvisionings OnboardingDemoProvisioning[]\n ipAddresses TenantIpAddress[]\n metricLogs MetricLog[]\n knowledgeBases KnowledgeBase[]\n types TenantType[]\n workflows Workflow[]\n workflowExecutions WorkflowExecution[]\n workflowVariables WorkflowVariable[]\n workflowCredentials WorkflowCredential[]\n feedback Feedback[]\n supportTickets SupportTicket[]\n credits Credit[]\n portals Portal[]\n portalsUsers PortalUser[]\n widgets Widget[]\n impersonationAudits ImpersonationAudit[]\n adminTenantNotes AdminTenantNote[]\n notificationDeliveries NotificationDelivery[]\n notificationPreferences UserNotificationPreference[]\n deviceTokens DeviceToken[]\n authProviders WorkspaceAuthProvider[]\n\n theme String?\n themeConfig String?\n\n // Apps-Engine (R-P5): App is global; DataConnection/AppSyncRun use bare\n // tenantId scalars (AD-21) — no back-relations here.\n\n // Global du/Sie formality toggle (Anrede). Default \"du\" keeps the effective\n // i18next language equal to the base locale, so existing rendering stays\n // byte-identical; \"sie\" resolves to the \"-formal\" variant.\n anrede String? @default(\"du\")\n\n sites Site[]\n\n forms Form[]\n\n @@index([slug])\n}\n\nmodel WorkspaceAuthProvider {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n kind String\n name String\n slug String\n enabled Boolean @default(false)\n issuer String?\n authorizationUrl String?\n tokenUrl String?\n jwksUrl String?\n clientId String?\n entityId String?\n ssoUrl String?\n certificateFingerprint String?\n metadataUpdatedAt DateTime?\n tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n\n @@unique([tenantId, slug])\n @@index([tenantId, kind, enabled])\n @@index([tenantId, updatedAt])\n}\n\nmodel ImpersonationAudit {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n actorUserId String?\n targetUserId String?\n tenantId String?\n action String\n reason String?\n requestPath String\n metadata String?\n actor User? @relation(\"ImpersonationAuditActor\", fields: [actorUserId], references: [id], onDelete: SetNull)\n target User? @relation(\"ImpersonationAuditTarget\", fields: [targetUserId], references: [id], onDelete: SetNull)\n tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: SetNull)\n\n @@index([actorUserId])\n @@index([targetUserId])\n @@index([tenantId])\n @@index([createdAt])\n}\n\nmodel TenantUser {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n userId String\n type Int\n joined Int\n status Int\n tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@unique([tenantId, userId])\n @@index([userId])\n @@index([tenantId, status])\n}\n\nmodel TenantUserInvitation {\n id String @id @default(cuid())\n tenantId String\n email String\n firstName String\n lastName String\n type Int\n pending Boolean\n status String @default(\"pending\")\n tokenHash String?\n tokenPrefix String?\n expiresAt DateTime?\n acceptedAt DateTime?\n revokedAt DateTime?\n createdUserId String? @unique\n fromUserId String?\n acceptedByUserId String?\n revokedByUserId String?\n fromUser User? @relation(name: \"fromUser\", fields: [fromUserId], references: [id])\n user User? @relation(name: \"createdUser\", fields: [createdUserId], references: [id])\n acceptedByUser User? @relation(name: \"acceptedByUser\", fields: [acceptedByUserId], references: [id])\n revokedByUser User? @relation(name: \"revokedByUser\", fields: [revokedByUserId], references: [id])\n tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, status, expiresAt])\n @@index([tenantId, email, status])\n @@index([tenantId, tokenPrefix])\n @@index([acceptedByUserId])\n @@index([revokedByUserId])\n}\n\nmodel Registration {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n email String @unique\n firstName String\n lastName String\n slug String?\n token String @unique\n ipAddress String?\n company String?\n selectedSubscriptionPriceId String?\n leadConversionLeadId String?\n leadConversionToken String?\n leadConversionPlanId String?\n createdTenantId String? @unique\n createdTenant Tenant? @relation(fields: [createdTenantId], references: [id], onDelete: Cascade)\n}\n\nmodel Blacklist {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n type String // email, domain, ip\n value String\n active Boolean @default(true)\n registerAttempts Int @default(0)\n}\n\nmodel TenantIpAddress {\n id String @id @default(cuid())\n tenantId String\n tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n userId String?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n apiKeyId String?\n apiKey ApiKey? @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)\n ip String\n fromUrl String\n createdAt DateTime @default(now())\n\n @@unique([tenantId, ip, userId, apiKeyId])\n}\n\nmodel TenantType {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n title String @unique\n titlePlural String\n description String?\n isDefault Boolean @default(false)\n tenants Tenant[]\n subscriptionProducts SubscriptionProduct[]\n}\n\n/// Actor that produced an activity. Small closed set → enum.\nenum ActivityActorKind {\n user\n system\n automation\n ki_agent\n}\n\n/// User-facing business activity timeline (M045 / M01 Block E).\n///\n/// DISTINCT from the tamper-evident, hash-chained `AuditEvent` (M001): `Activity`\n/// is the per-entity, human-readable stream shown to tenant users (calls, notes,\n/// emails, status changes, …). Every writing module appends here via\n/// `logActivity()` from `@hivegrid/activity` (AGENTS DoD #14).\n///\n/// `activityType` and `subjectType` are stored as strings (extensible per module —\n/// see the `ActivityType` / `ActivitySubjectType` unions in `@hivegrid/activity`),\n/// not Prisma enums, to avoid a schema migration for every new module event.\n///\n/// Tenant isolation: RLS policy is added with M27 (Auth/Tenancy); until then access\n/// is App-Level-scoped via the tenant-scoped query helpers.\nmodel Activity {\n id String @id @default(cuid())\n tenantId String\n createdAt DateTime @default(now())\n actorUserId String?\n actorKind ActivityActorKind\n activityType String\n subjectType String\n subjectId String\n relatedEntityRefs Json?\n metadata Json?\n summaryText String\n\n // Per-entity timeline (default view), tenant-wide stream, and type filter.\n @@index([tenantId, subjectType, subjectId, createdAt])\n @@index([tenantId, createdAt])\n @@index([tenantId, activityType])\n}\n\n// AK-P19 — Platform-Admin module (admin.hivegrid.de).\n//\n// Per AD-21 each module owns its own schema file. The platform-admin\n// world is deliberately a *separate* world: these rows carry NO\n// `tenant_id`-based RLS scoping of their own beyond a plain FK, because\n// admin actions span tenants. Cross-tenant admin actions are recorded\n// through the shared AuditEvent Querschnitt (tenantId=null,\n// actorType=\"admin\") — NOT a parallel audit table (see AK-P19 plan,\n// DoD #7). v1 also reuses the boilerplate User model as the admin\n// identity (AdminUser extension + admin-mfa-gate); the separate\n// AdminUser/AdminRole/AdminSession identity is v2 (M038/M039).\n\n/// AdminTenantNote — free-form operator notes pinned to a tenant.\n/// ENTITY-MODEL Domäne 11: markdown note_text, category, pinned.\n/// Written from the admin tenant-detail screen; every write also emits\n/// an admin AuditEvent (tenantId=null, actorType=\"admin\").\nmodel AdminTenantNote {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n authorUserId String?\n noteText String\n category String @default(\"general\")\n pinned Boolean @default(false)\n\n tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n author User? @relation(\"adminTenantNoteAuthor\", fields: [authorUserId], references: [id], onDelete: SetNull)\n\n // Detail view lists pinned-first, newest-first, per tenant.\n @@index([tenantId, pinned, createdAt], name: \"admin_tenant_note_tenant_pinned_created_idx\")\n @@index([tenantId, category], name: \"admin_tenant_note_tenant_category_idx\")\n}\n\n/// SupportTicketMessage — conversation thread for the admin Support-Inbox.\n/// Extends the existing helpDesk `SupportTicket` (which already carries\n/// source/status/priority/tenant) with replies and internal notes.\n/// `internalNote=true` rows are operator-only and never surfaced to the\n/// tenant. A null author means an inbound message from the customer side.\nmodel SupportTicketMessage {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n supportTicketId String\n authorUserId String?\n body String\n internalNote Boolean @default(false)\n\n ticket SupportTicket @relation(fields: [supportTicketId], references: [id], onDelete: Cascade)\n author User? @relation(\"supportTicketMessageAuthor\", fields: [authorUserId], references: [id], onDelete: SetNull)\n\n @@index([supportTicketId, createdAt], name: \"support_ticket_message_ticket_created_idx\")\n}\n\nmodel AnalyticsSettings {\n id String @id @default(cuid())\n public Boolean @default(false)\n ignorePages String\n onlyPages String\n}\n\nmodel AnalyticsUniqueVisitor {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n cookie String @unique\n via String?\n httpReferrer String?\n browser String?\n browserVersion String?\n os String?\n osVersion String?\n device String?\n source String?\n medium String?\n campaign String?\n content String?\n term String?\n country String?\n city String?\n fromUrl String?\n fromRoute String?\n pageViews AnalyticsPageView[]\n events AnalyticsEvent[]\n userId String?\n user User? @relation(fields: [userId], references: [id])\n portalId String?\n portal Portal? @relation(fields: [portalId], references: [id], onDelete: Cascade)\n portalUserId String?\n portalUser PortalUser? @relation(fields: [portalUserId], references: [id], onDelete: Cascade)\n}\n\nmodel AnalyticsPageView {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n uniqueVisitorId String\n uniqueVisitor AnalyticsUniqueVisitor @relation(fields: [uniqueVisitorId], references: [id], onDelete: Cascade)\n url String\n route String?\n portalId String?\n portal Portal? @relation(fields: [portalId], references: [id], onDelete: Cascade)\n portalUserId String?\n portalUser PortalUser? @relation(fields: [portalUserId], references: [id], onDelete: Cascade)\n}\n\nmodel AnalyticsEvent {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n uniqueVisitorId String\n uniqueVisitor AnalyticsUniqueVisitor @relation(fields: [uniqueVisitorId], references: [id], onDelete: Cascade)\n action String\n category String?\n label String?\n value String?\n url String?\n route String?\n featureFlagId String?\n featureFlag FeatureFlag? @relation(fields: [featureFlagId], references: [id])\n portalId String?\n portal Portal? @relation(fields: [portalId], references: [id], onDelete: Cascade)\n portalUserId String?\n portalUser PortalUser? @relation(fields: [portalUserId], references: [id], onDelete: Cascade)\n}\n\n// custom database models\n\n// R-P5 (P5) Apps-Engine & Integrations-Framework — aligned to ENTITY-MODEL\n// Domäne 4 (AD-20 Pivot-Vorrang). Replaces the stock boilerplate models.\n//\n// AD-21: self-contained schema. `tenantId` / `createdByUserId` are BARE String\n// scalars (no `@relation` to Tenant/User) → zero merge-conflict surface against\n// core.prisma/accounts.prisma. Intra-module relations (App→DataConnection→\n// AppSyncRun→Log/Item) stay inside this file.\n//\n// `App` is GLOBAL (a definition/catalog table, no tenantId, no RLS). Everything\n// tenant-facing (DataConnection + sync rows) is tenant-scoped + RLS\n// (prisma/rls/apps-engine-isolation.sql, deferred activation like the other\n// modules). Credentials are stored ENVELOPE-ENCRYPTED via the per-tenant DEK\n// (R-P5 Phase 1: packages/db/src/crypto/tenant-envelope.server.ts), never plain.\n//\n// Scope (AD-26 recut): connection types oauth2 / api_key / rest_api only have a\n// v1 flow; `windows_client` (KWP) stays in the datamodel but has NO v1 UI/logic.\n// Concrete app adapters (Gmail/Outlook/AirCall/Mollie) belong to P14/P15/P16/P20,\n// not here — P5 ships only the generic framework + the sample-data-sync adapter.\n\nenum AppCategory {\n erp\n communication\n calendar\n signature\n payment\n ki\n}\n\nenum AppConnectionType {\n oauth2\n api_key\n rest_api\n windows_client\n}\n\nenum DataConnectionStatus {\n pending\n active\n degraded\n broken\n revoked\n}\n\nenum AppSyncKind {\n manual\n scheduled\n webhook\n}\n\nenum AppSyncStatus {\n pending\n running\n completed\n partial\n failed\n cancelled\n}\n\nenum AppSyncLogSeverity {\n info\n success\n warning\n error\n}\n\nenum AppSyncItemOperation {\n created\n updated\n deleted\n skipped\n}\n\nenum AppSyncItemStatus {\n pending\n synced\n failed\n skipped\n}\n\n/// Global catalog definition of an integratable app (no tenant, no RLS). The\n/// `connectionSchema` drives the auto-generated credential form; `connectionType`\n/// selects the connect flow. New apps are registered by the build-time adapter\n/// scan + this catalog (drift-check warns in the platform admin).\nmodel App {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n key String @unique\n title String\n category AppCategory\n connectionType AppConnectionType\n connectionSchema Json @default(\"{}\")\n phase String?\n icon String?\n isActive Boolean @default(true)\n\n @@index([category])\n}\n\n/// A tenant's connection to an App. Multiple per (tenant, app) with a user\n/// `label` (e.g. three Gmail mailboxes). Credentials live encrypted in\n/// `credentialsCiphertext`. Disconnect sets `connectionStatus = revoked` (no\n/// hard-delete → sync history preserved). Soft-delete via `archivedAt`.\nmodel DataConnection {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n // The app's stable catalog `key` (bare scalar per AD-21; matches the adapter\n // registry + INTEGRATION_CATALOG). App is a global catalog, not an FK target.\n appId String\n label String\n // AES-256-GCM per-tenant DEK envelope (AD-8). Never selected into list VMs.\n credentialsCiphertext String?\n connectionStatus DataConnectionStatus @default(pending)\n lastHealthCheck DateTime?\n // i18n key describing the current health state (Klartext, M002/M003).\n healthMessageKey String?\n tokenExpiresAt DateTime?\n createdByUserId String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n syncRuns AppSyncRun[]\n\n @@index([tenantId, appId, archivedAt])\n @@index([tenantId, connectionStatus])\n @@index([tenantId, tokenExpiresAt])\n}\n\n/// One sync run for a DataConnection. `summaryText` is the Klartext summary.\nmodel AppSyncRun {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n dataConnectionId String\n kind AppSyncKind @default(manual)\n status AppSyncStatus @default(pending)\n itemsTotal Int @default(0)\n itemsSucceeded Int @default(0)\n itemsFailed Int @default(0)\n summaryText String?\n startedAt DateTime?\n completedAt DateTime?\n createdByUserId String?\n\n dataConnection DataConnection @relation(fields: [dataConnectionId], references: [id], onDelete: Cascade)\n logs AppSyncRunLog[]\n items AppSyncItem[]\n\n @@index([tenantId, dataConnectionId, createdAt(sort: Desc)])\n @@index([tenantId, status])\n}\n\n/// A log line of a sync run (Klartext `messageText` + optional `techDetails`).\nmodel AppSyncRunLog {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n syncRunId String\n severity AppSyncLogSeverity @default(info)\n messageText String\n techDetails String?\n\n syncRun AppSyncRun @relation(fields: [syncRunId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, syncRunId])\n}\n\n/// A single synced object: maps a HiveGrid entity (`entityType`/`entityId`) to an\n/// external system id (`externalId`). Polymorphic.\nmodel AppSyncItem {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n syncRunId String\n entityType String\n entityId String?\n externalId String\n operation AppSyncItemOperation @default(created)\n status AppSyncItemStatus @default(pending)\n errorText String?\n\n syncRun AppSyncRun @relation(fields: [syncRunId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, syncRunId])\n @@index([tenantId, entityType, entityId])\n @@index([tenantId, externalId])\n}\n\n// R-P9a (P9 Auftrag view + project sub-areas).\n//\n// AD-20: order work is a view on the existing `Projekt` core, not a second\n// project/order object and not a won-handoff copy. These rows are sub-areas\n// addressed by `projektId` bare scalar.\n//\n// AD-21: this module owns its schema file. Cross-module references to Projekt,\n// User, Group, File and Form are intentionally bare String scalars so this slice\n// does not modify projekt/accounts/files/forms schemas.\n\nenum ProjektMitgliedRolle {\n monteur\n projektleiter\n zustaendig\n beobachter\n}\n\nenum ProjektTerminStatus {\n geplant\n bestaetigt\n erledigt\n abgesagt\n}\n\nenum RechnungStatus {\n entwurf\n gestellt\n bezahlt\n storniert\n}\n\nenum RechnungQuelle {\n manuell\n kwp\n}\n\nenum ProjektChecklistTyp {\n generisch\n maengel\n abnahme_doku\n}\n\nenum ProjektChecklistItemStatus {\n offen\n erledigt\n entfaellt\n}\n\nenum ScheduleEntryStatus {\n planned\n confirmed\n in_progress\n done\n cancelled\n}\n\nenum ScheduleConflictType {\n double_booking\n absence\n availability\n}\n\nenum ScheduleConflictSeverity {\n warning\n blocking\n}\n\nenum ScheduleSyncStatus {\n pending\n synced\n failed\n}\n\nenum AcceptanceKind {\n full\n with_defects\n rejected\n}\n\nenum AcceptanceSignerRole {\n kunde\n monteur\n}\n\nenum OfflineSyncOperation {\n schedule_upsert\n schedule_status\n acceptance_submit\n}\n\nenum OfflineSyncStatus {\n pending\n applied\n failed\n}\n\nmodel ProjektMitglied {\n id String @id @default(cuid())\n tenantId String\n projektId String\n userId String?\n groupId String?\n rolle ProjektMitgliedRolle\n createdByUserId String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n\n @@index([tenantId, projektId, archivedAt])\n @@index([tenantId, userId])\n @@index([tenantId, groupId])\n}\n\nmodel ProjektTermin {\n id String @id @default(cuid())\n tenantId String\n projektId String\n createdByUserId String?\n assignedToUserId String?\n assignedToGroupId String?\n titel String\n beschreibung String?\n startAt DateTime\n endAt DateTime?\n status ProjektTerminStatus @default(geplant)\n isDemoData Boolean @default(false)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n\n @@index([tenantId, projektId, archivedAt, startAt])\n @@index([tenantId, assignedToUserId])\n @@index([tenantId, assignedToGroupId])\n}\n\nmodel Rechnung {\n id String @id @default(cuid())\n tenantId String\n projektId String\n createdByUserId String?\n rechnungsnummer String\n betrag Decimal\n status RechnungStatus @default(entwurf)\n datum DateTime @default(now())\n faelligAm DateTime?\n dateiId String?\n quelle RechnungQuelle @default(manuell)\n isDemoData Boolean @default(false)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n\n @@unique([tenantId, rechnungsnummer])\n @@index([tenantId, projektId, archivedAt])\n @@index([tenantId, status])\n @@index([tenantId, dateiId])\n}\n\nmodel ProjektChecklist {\n id String @id @default(cuid())\n tenantId String\n projektId String\n createdByUserId String?\n titel String\n typ ProjektChecklistTyp @default(generisch)\n isDemoData Boolean @default(false)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n\n items ProjektChecklistItem[]\n\n @@index([tenantId, projektId, typ, archivedAt])\n}\n\nmodel ProjektChecklistItem {\n id String @id @default(cuid())\n tenantId String\n checklistId String\n titel String\n status ProjektChecklistItemStatus @default(offen)\n maengelKlasse String?\n fotoFileId String?\n assignedToUserId String?\n dueAt DateTime?\n position Int @default(0)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n checklist ProjektChecklist @relation(fields: [checklistId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, checklistId])\n @@index([tenantId, status])\n @@index([tenantId, fotoFileId])\n}\n\nmodel AuftragPipelineStageConfig {\n id String @id @default(cuid())\n tenantId String\n pipelineId String\n stageId String\n requiresAcceptanceProtocol Boolean @default(false)\n acceptanceFormTemplateId String?\n autoArchiveAfterDays Int?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([tenantId, stageId])\n @@index([tenantId, pipelineId])\n @@index([tenantId, acceptanceFormTemplateId])\n}\n\nmodel AcceptanceFormTemplate {\n id String @id @default(cuid())\n tenantId String\n name String\n formId String?\n definition Json @default(\"{}\")\n isDefault Boolean @default(false)\n isDemoData Boolean @default(false)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n\n @@unique([tenantId, name])\n @@index([tenantId, archivedAt])\n @@index([tenantId, formId])\n}\n\nmodel ProjectTemplate {\n id String @id @default(cuid())\n tenantId String\n name String\n defaultPipelineId String?\n defaultStageId String?\n defaultMembers Json @default(\"[]\")\n defaultTasks Json @default(\"[]\")\n customFields Json @default(\"{}\")\n isDemoData Boolean @default(false)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n\n @@unique([tenantId, name])\n @@index([tenantId, archivedAt])\n @@index([tenantId, defaultPipelineId])\n}\n\nmodel ScheduleEntry {\n id String @id @default(cuid())\n tenantId String\n projektId String\n assignedUserId String\n createdByUserId String?\n title String\n startAt DateTime\n endAt DateTime\n status ScheduleEntryStatus @default(planned)\n calendarEventId String?\n syncStatus ScheduleSyncStatus @default(pending)\n conflictOverrideReason String?\n clientMutationId String?\n isDemoData Boolean @default(false)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n\n conflicts ScheduleConflict[]\n\n @@unique([tenantId, clientMutationId])\n @@index([tenantId, projektId, archivedAt])\n @@index([tenantId, assignedUserId, startAt, endAt])\n @@index([tenantId, status])\n @@index([tenantId, calendarEventId])\n}\n\nmodel ScheduleConflict {\n id String @id @default(cuid())\n tenantId String\n entryId String\n type ScheduleConflictType\n severity ScheduleConflictSeverity @default(warning)\n messageKey String\n sourceKind String?\n sourceId String?\n createdAt DateTime @default(now())\n resolvedAt DateTime?\n overriddenAt DateTime?\n\n entry ScheduleEntry @relation(fields: [entryId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, entryId])\n @@index([tenantId, type, resolvedAt])\n}\n\nmodel AbnahmeProtokoll {\n id String @id @default(cuid())\n tenantId String\n projektId String\n maengelChecklistId String?\n createdByUserId String?\n datum DateTime @default(now())\n acceptanceKind AcceptanceKind\n anwesende Json @default(\"[]\")\n druckprobe Json @default(\"{}\")\n funktionspruefung Json @default(\"{}\")\n zaehlerstaende Json @default(\"{}\")\n dokumente Json @default(\"[]\")\n bemerkungen String?\n pdfFileId String?\n customerEmail String?\n customerEmailQueuedAt DateTime?\n clientMutationId String?\n gesperrtAt DateTime?\n isDemoData Boolean @default(false)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n\n signatures AbnahmeSignatur[]\n\n @@unique([tenantId, clientMutationId])\n @@index([tenantId, projektId, archivedAt])\n @@index([tenantId, maengelChecklistId])\n @@index([tenantId, pdfFileId])\n @@index([tenantId, acceptanceKind])\n}\n\nmodel AbnahmeSignatur {\n id String @id @default(cuid())\n tenantId String\n protokollId String\n signerName String\n signerRole AcceptanceSignerRole\n signatureFileId String?\n signerIpHash String?\n signedAt DateTime @default(now())\n createdAt DateTime @default(now())\n\n protokoll AbnahmeProtokoll @relation(fields: [protokollId], references: [id], onDelete: Restrict)\n\n @@index([tenantId, protokollId])\n @@index([tenantId, signatureFileId])\n}\n\nmodel OfflineSyncMutation {\n id String @id @default(cuid())\n tenantId String\n clientMutationId String\n createdByUserId String?\n operation OfflineSyncOperation\n payload Json\n status OfflineSyncStatus @default(pending)\n resultEntityType String?\n resultEntityId String?\n errorMessageKey String?\n createdAt DateTime @default(now())\n appliedAt DateTime?\n\n @@unique([tenantId, clientMutationId])\n @@index([tenantId, createdByUserId, createdAt])\n @@index([tenantId, status])\n}\n\n// R-P2a S4 — serverseitige Sessions (Postgres als Source-of-Truth, Redis-Cache davor, AD-4).\n// Eigenes Modul-Schema (AD-21): neue Modelle NICHT in accounts.prisma/core.prisma; die\n// Rueck-Relation auf User bleibt minimal (User.userSessions).\n//\n// Das Login-Cookie traegt einen opaken Zufalls-Token; gespeichert wird nur dessen SHA-256-Hash\n// (tokenHash). Eine Session ist gueltig, solange revokedAt = null und expiresAt in der Zukunft\n// liegt. Die Geraete-Liste (Settings > Sicherheit), Revoke-einzeln und \"ueberall abmelden\"\n// arbeiten auf diesen Zeilen.\n\nmodel UserSession {\n id String @id @default(cuid())\n userId String\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n // Nur der Hash des Cookie-Tokens wird persistiert (kein Klartext-Token in der DB).\n tokenHash String @unique\n\n createdAt DateTime @default(now())\n lastSeenAt DateTime @default(now())\n expiresAt DateTime\n revokedAt DateTime?\n\n // Trust-Device (S5/2FA): markiert eine Session als vertrauenswuerdig, damit fuer sie kein\n // erneuter TOTP-Code verlangt wird.\n trustedAt DateTime?\n\n // Kontext fuer die Geraete-Liste. AD-22: KEINE Klartext-IP persistieren — nur der Hash (hashIp)\n // zur \"gleiches Geraet\"-Wiedererkennung; angezeigt wird das Land (approxLocation via geoip).\n ipHash String?\n userAgent String?\n deviceLabel String?\n approxLocation String?\n browserFingerprint String?\n\n @@index([userId])\n @@index([userId, revokedAt])\n @@index([expiresAt])\n}\n\n// D1 (Trust-Device) — \"diesem Geraet vertrauen\" beim 2FA-Login. UEBERLEBT den Logout (anders als\n// UserSession.trustedAt, das per Session lebt) -> eigene, langlebige Tabelle. Das Geraete-Cookie\n// traegt einen opaken Zufalls-Token; persistiert wird nur dessen SHA-256-Hash (tokenHash). Ein Geraet\n// ueberspringt den zweiten Faktor, solange revokedAt = null und expiresAt in der Zukunft liegt. Die\n// Geraete-Liste (Settings > Sicherheit), Revoke-einzeln und \"ueberall vergessen\" arbeiten auf diesen\n// Zeilen -> erfuellt den DoD-Screen \"Trust-Device-Revoke\" (R-P2a) widerrufbar statt nur Cookie.\nmodel TrustedDevice {\n id String @id @default(cuid())\n userId String\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n // Nur der Hash des Cookie-Tokens wird persistiert (kein Klartext-Token in der DB).\n tokenHash String @unique\n\n createdAt DateTime @default(now())\n lastUsedAt DateTime @default(now())\n expiresAt DateTime\n revokedAt DateTime?\n\n // Kontext fuer die Geraete-Liste. AD-22: KEINE Klartext-IP persistieren — nur der Hash (hashIp);\n // angezeigt wird das Land (approxLocation via geoip).\n ipHash String?\n userAgent String?\n deviceLabel String?\n approxLocation String?\n\n @@index([userId])\n @@index([userId, revokedAt])\n @@index([expiresAt])\n}\n\n// R-P12a (P12 Automation) — typed automation engine foundation.\n//\n// AD-21: self-contained schema. User references are bare String scalars so the\n// automation slice does not touch accounts/core back-relations while P12b can\n// add the visual editor on top of these contracts.\n\nenum AutomationRuleStatus {\n draft\n active\n paused\n archived\n}\n\nenum AutomationStepKind {\n trigger\n condition\n action\n flow_control\n}\n\nenum AutomationExecutionStatus {\n queued\n running\n success\n failed\n paused\n waiting\n skipped\n retrying\n}\n\nmodel AutomationRule {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n name String\n description String?\n status AutomationRuleStatus @default(draft)\n enabled Boolean @default(false)\n createdVia String @default(\"manual\")\n triggerKey String?\n flowData Json @default(\"{}\")\n createdByUserId String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n steps AutomationRuleStep[]\n executions AutomationExecution[]\n\n @@unique([tenantId, name])\n @@index([tenantId, status, enabled, archivedAt])\n @@index([tenantId, triggerKey, enabled, archivedAt])\n}\n\nmodel AutomationRuleStep {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n ruleId String\n stepKey String\n stepKind AutomationStepKind\n nodeType String\n config Json @default(\"{}\")\n parentStepIds String[] @default([])\n position Json @default(\"{}\")\n sortOrder Int @default(0)\n summaryText String?\n isDemoData Boolean @default(false)\n\n rule AutomationRule @relation(fields: [ruleId], references: [id], onDelete: Cascade)\n stepExecutions AutomationStepExecution[]\n\n @@unique([ruleId, stepKey])\n @@index([tenantId, ruleId, sortOrder])\n @@index([tenantId, nodeType])\n}\n\nmodel AutomationExecution {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n ruleId String\n triggerKey String\n triggerPayload Json @default(\"{}\")\n status AutomationExecutionStatus @default(queued)\n dryRun Boolean @default(false)\n idempotencyKey String?\n reverseWindowExpiresAt DateTime?\n resumeFromStepId String?\n summaryText String\n errorText String?\n queuedAt DateTime @default(now())\n startedAt DateTime?\n endedAt DateTime?\n durationMs Int?\n attempt Int @default(1)\n nextRetryAt DateTime?\n createdByUserId String?\n isDemoData Boolean @default(false)\n\n rule AutomationRule @relation(fields: [ruleId], references: [id], onDelete: Cascade)\n stepExecutions AutomationStepExecution[]\n\n @@unique([tenantId, idempotencyKey])\n @@index([tenantId, ruleId, createdAt(sort: Desc)])\n @@index([tenantId, triggerKey, createdAt(sort: Desc)])\n @@index([tenantId, status, createdAt(sort: Desc)])\n}\n\nmodel AutomationStepExecution {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n executionId String\n ruleStepId String?\n stepKey String\n stepKind AutomationStepKind\n nodeType String\n status AutomationExecutionStatus @default(queued)\n input Json @default(\"{}\")\n output Json @default(\"{}\")\n summaryText String\n errorText String?\n startedAt DateTime?\n endedAt DateTime?\n durationMs Int?\n attempt Int @default(1)\n sortOrder Int @default(0)\n\n execution AutomationExecution @relation(fields: [executionId], references: [id], onDelete: Cascade)\n ruleStep AutomationRuleStep? @relation(fields: [ruleStepId], references: [id], onDelete: SetNull)\n\n @@index([tenantId, executionId, sortOrder])\n @@index([tenantId, status, createdAt(sort: Desc)])\n}\n\nmodel AutomationCredential {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n name String\n kind String\n encryptedValue String\n metadata Json @default(\"{}\")\n createdByUserId String?\n archivedAt DateTime?\n\n @@unique([tenantId, name])\n @@index([tenantId, kind, archivedAt])\n}\n\nmodel AutomationTemplate {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String?\n name String\n description String?\n category String\n flowData Json @default(\"{}\")\n isPublished Boolean @default(false)\n createdFromRuleId String?\n createdByUserId String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n @@unique([tenantId, name])\n @@index([tenantId, category, isPublished, archivedAt])\n}\n\nmodel AutomationTriggerMeter {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n triggerKey String\n windowStart DateTime\n windowMinutes Int @default(5)\n count Int @default(0)\n pausedUntil DateTime?\n anomalyText String?\n\n @@unique([tenantId, triggerKey, windowStart, windowMinutes])\n @@index([tenantId, triggerKey, windowStart])\n @@index([tenantId, pausedUntil])\n}\n\n// AK-P16b (P16) Booking — Calendly-style public booking pages, timezone-aware\n// slot calculation, full appointment lifecycle. Aligned to ENTITY-MODEL Domäne 9\n// (M06-booking).\n//\n// AD-21: self-contained schema. `tenantId` / `providerUserId` / `kontaktId` /\n// `leadId` / `formSubmissionId` are BARE String scalars (no `@relation` to\n// Tenant/User/Kontakt/Lead/Form) → zero merge-conflict surface against the shared\n// core + neighbouring module schemas (crm.prisma / calendar.prisma / forms). The\n// CRM/Form linkage runs through those bare scalars in the service layer.\n// Intra-module relations (Page → Provider / Appointment, Appointment self-reschedule)\n// stay inside this file.\n//\n// Cross-ticket gaps handled per user decision (2026-06-30):\n// - leadId stays NULLABLE, reserved for R-P7 (typed CRM Lead not built yet). v1\n// post-booking matches/creates a Kontakt + logs an Activity instead.\n// - formSubmissionId stays NULLABLE, reserved for AK-P16c (Forms module not built\n// yet). v1 stores the standard mini-form answers in `intakeAnswers` JSON.\n//\n// Slot availability subtracts the Google busy intervals from AK-P16a\n// (CalendarEvent.isBusyForAvailability) via the pure availability.ts helpers —\n// leak-protection holds: only busy {from,to} intervals cross over, never titles.\n//\n// RLS ships separately in prisma/rls/booking-isolation.sql (deferred cutover like\n// the other modules). The hard double-booking guard (PostgreSQL EXCLUDE USING gist\n// over a tstzrange per provider) ships in prisma/rls/booking-constraints.sql — it\n// cannot be expressed in the Prisma schema. On the feature branch: `prisma db push`\n// + manual `psql -f` for the constraint; the merge migration folds both in (AD-21).\n\n/// Provider-assignment strategy (M06 A.2). v1 implements `first_available` only\n/// (\"Erster der frei ist\"); round_robin / specific_provider_choice → v2. The enum\n/// carries all three so the v2 switch is additive (no migration of stored values).\nenum BookingAssignmentStrategy {\n round_robin\n specific_provider_choice\n first_available\n}\n\n/// Weekday of a weekly availability rule (M06 A.3).\nenum BookingDayOfWeek {\n monday\n tuesday\n wednesday\n thursday\n friday\n saturday\n sunday\n}\n\n/// Date-specific override kind (M06 A.4). `unavailable` blocks the whole day;\n/// `custom_window` replaces the standard rule for that date.\nenum AvailabilityExceptionKind {\n unavailable\n custom_window\n}\n\n/// Appointment lifecycle status (M06 A.5 / M129). `rescheduled` keeps the old row\n/// for history and points forward via `rescheduledFromId` on the successor.\nenum AppointmentStatus {\n scheduled\n held\n cancelled\n no_show\n rescheduled\n}\n\n/// Who triggered a cancellation (M06 A.5) — drives the Klartext + auto-mail copy.\nenum AppointmentCancelledByKind {\n customer\n provider\n system\n}\n\n/// A public booking page (M06 A.1). Tenant-scoped, soft-deletable. `slug` is unique\n/// per tenant and powers the public URL `/b/{tenant}/{slug}`. `intakeFormId` is a\n/// bare reserved scalar for the AK-P16c Forms module (null = standard mini-form).\nmodel BookingPage {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n createdByUserId String?\n slug String\n title String\n description String?\n durationMinutes Int\n bufferBeforeMinutes Int @default(0)\n bufferAfterMinutes Int @default(0)\n slotIncrementMinutes Int @default(15)\n minNoticeHours Int @default(4)\n maxAdvanceDays Int @default(60)\n assignmentStrategy BookingAssignmentStrategy @default(first_available)\n confirmationEmailSubject String\n confirmationEmailBody String\n internalEventTitleTemplate String?\n redirectUrlAfterBooking String?\n // Reserved bare scalar for AK-P16c (Forms). Null → standard mini-form.\n intakeFormId String?\n isPublished Boolean @default(false)\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n providers BookingPageProvider[]\n appointments Appointment[]\n\n @@unique([tenantId, slug])\n @@index([tenantId, archivedAt, isPublished])\n}\n\n/// M:N between BookingPage and tenant users who hold its appointments (M06 A.2).\n/// `providerUserId` is a bare scalar (no @relation to User, AD-21).\nmodel BookingPageProvider {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n bookingPageId String\n providerUserId String\n displayOrder Int @default(0)\n isActive Boolean @default(true)\n\n bookingPage BookingPage @relation(fields: [bookingPageId], references: [id], onDelete: Cascade)\n\n @@unique([bookingPageId, providerUserId])\n @@index([tenantId, providerUserId])\n}\n\n/// Weekly standard availability per tenant user (M06 A.3). Several rows per weekday\n/// allowed (e.g. 09:00-12:00 + 14:00-17:00). Times are local \"HH:mm\" in `timezone`.\nmodel AvailabilityRule {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n providerUserId String\n dayOfWeek BookingDayOfWeek\n startTime String\n endTime String\n timezone String\n\n @@index([tenantId, providerUserId, dayOfWeek])\n}\n\n/// Date-specific override of the standard rules (M06 A.4). `startTime`/`endTime`\n/// only set when kind = custom_window (null for a full-day `unavailable`).\nmodel AvailabilityException {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n providerUserId String\n date DateTime @db.Date\n kind AvailabilityExceptionKind\n startTime String?\n endTime String?\n reason String?\n timezone String\n\n @@index([tenantId, providerUserId, date])\n}\n\n/// A booked appointment (M06 A.5). Tenant-scoped. `startAt`/`endAt` are UTC;\n/// `timezone` records the booker's IANA zone for display. CRM/Form links are bare\n/// nullable scalars (kontaktId set on match/create; leadId reserved for R-P7,\n/// formSubmissionId reserved for AK-P16c). `intakeAnswers` holds the v1 mini-form\n/// payload. `internalCalendarEventId` points at the local CalendarEvent mirror that\n/// blocks the provider's availability (AK-P16a write-path pushes it external later).\nmodel Appointment {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n bookingPageId String\n providerUserId String\n startAt DateTime\n endAt DateTime\n timezone String\n status AppointmentStatus @default(scheduled)\n // CRM linkage (bare scalars, AD-21). leadId reserved for R-P7.\n kontaktId String?\n leadId String?\n // Reserved for AK-P16c Forms. v1 answers live in intakeAnswers.\n formSubmissionId String?\n intakeAnswers Json @default(\"{}\")\n // Local CalendarEvent mirror id + external provider event ids (M06 J.2/J.3).\n internalCalendarEventId String?\n externalCalendarEventIds Json @default(\"[]\")\n cancelledAt DateTime?\n cancelledByKind AppointmentCancelledByKind?\n cancellationReason String?\n rescheduledFromId String?\n notesInternal String?\n isDemoData Boolean @default(false)\n\n bookingPage BookingPage @relation(fields: [bookingPageId], references: [id], onDelete: Cascade)\n rescheduledFrom Appointment? @relation(\"AppointmentReschedule\", fields: [rescheduledFromId], references: [id], onDelete: SetNull)\n rescheduledTo Appointment[] @relation(\"AppointmentReschedule\")\n\n @@index([tenantId, providerUserId, startAt])\n @@index([tenantId, status, startAt])\n @@index([tenantId, kontaktId, startAt])\n @@index([bookingPageId, startAt])\n}\n\n// AK-P16a (P16) Calendar-Sync (Google) — aligned to ENTITY-MODEL Domäne 9\n// (M25-calendar-sync). v1 = Google only; Outlook/Microsoft → v2 (the provider\n// enum + adapter interface stay provider-agnostic).\n//\n// AD-21: self-contained schema. `tenantId` / `userId` are BARE String scalars\n// (no `@relation` to Tenant/User) → zero merge-conflict surface against\n// core.prisma/accounts.prisma. Intra-module relations (Connection → Event /\n// Mapping / Cursor / WebhookEvent / Conflict) stay inside this file.\n//\n// Connection is PER-USER (not per-tenant): each user connects their own Google\n// account. OAuth refresh/access tokens are stored ENVELOPE-ENCRYPTED via the\n// per-tenant DEK seam (AD-8, packages/db/src/crypto/tenant-envelope.server.ts),\n// never plain. The Apps-Engine `App` catalog (appsEngine.prisma) is referenced\n// READ-ONLY through the bare `dataConnectionId` scalar — calendar owns its own\n// per-user connection lifecycle (RLS here is tenant- AND owner-scoped in code).\n//\n// RLS ships separately in prisma/rls/calendar-isolation.sql (deferred cutover\n// like the other modules). On the feature branch: `prisma db push` only — the\n// merge migration is created at main-merge (AD-21). Leak-protection (DoD 3):\n// external event contents are owner-only; availability exposes busy slots only.\n\n/// Calendar provider. v1 = google; microsoft → v2 (interface stays agnostic).\nenum CalendarProvider {\n google\n}\n\n/// Sync direction of a connection (M25 Block D). Default bidirectional.\nenum CalendarSyncDirection {\n bidirectional\n hivegrid_to_external_only\n external_to_hivegrid_only\n}\n\n/// Lifecycle status of a calendar connection (M25 Block A/C).\nenum CalendarConnectionStatus {\n active\n paused\n error\n revoked\n}\n\n/// Whether an event originates in HiveGrid or is a read-only external mirror.\nenum CalendarEventSource {\n hivegrid_internal\n external_synced\n}\n\n/// Worker processing state of an inbound webhook notification (M25 Block E).\nenum CalendarWebhookProcessingStatus {\n pending\n processing\n completed\n failed\n skipped\n}\n\n/// How a sync conflict was resolved (M25 Block F — Last-Write-Wins variants).\nenum CalendarConflictResolution {\n external_won\n hivegrid_won\n external_deleted\n hivegrid_deleted\n}\n\n/// A user's connection to an external calendar provider. PER-USER, tenant-scoped\n/// for isolation. The OAuth tokens are AES-256-GCM per-tenant-DEK envelopes\n/// (AD-8); never selected into a list view-model. `dataConnectionId` is an\n/// OPTIONAL read-only reference to the Apps-Engine DataConnection catalog entry\n/// (bare scalar, AD-21) — calendar runs autonomously if the catalog row is absent.\nmodel CalendarConnection {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n userId String\n provider CalendarProvider @default(google)\n // User-visible account identity (for the connection card).\n externalAccountEmail String\n externalAccountId String\n // Sensitive: per-tenant envelope ciphertext (AD-8). Never serialised to a VM.\n oauthRefreshTokenCiphertext String?\n oauthAccessTokenCiphertext String?\n oauthAccessTokenExpiresAt DateTime?\n // Granted OAuth scopes; a reduction by the user triggers a Klartext re-connect.\n oauthScopes String[]\n // Provider push-subscription handle (Google channel.id) + renewal anchor.\n webhookSubscriptionId String?\n webhookSubscriptionExpiresAt DateTime?\n // JSON list of selected external calendars to sync (default: primary).\n selectedCalendars Json @default(\"[]\")\n syncDirection CalendarSyncDirection @default(bidirectional)\n status CalendarConnectionStatus @default(active)\n lastSyncAt DateTime?\n // Klartext failure detail when status = error (M002).\n lastErrorText String?\n // Read-only Apps-Engine catalog reference (AD-21 bare scalar, optional).\n dataConnectionId String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n events CalendarEvent[]\n mappings CalendarEventMapping[]\n syncCursors CalendarSyncCursor[]\n webhookEvents CalendarWebhookEvent[]\n conflicts CalendarConflict[]\n\n @@unique([tenantId, userId, provider, externalAccountId])\n @@index([tenantId, userId, status, archivedAt])\n @@index([tenantId, webhookSubscriptionExpiresAt])\n}\n\n/// Cache of external events + HiveGrid-internal events. Tenant- and owner-scoped.\n/// External events are owner-only (leak-protection, DoD 3); availability reads\n/// only `isBusyForAvailability` busy intervals, never titles. `internalEntityLink`\n/// is a polymorphic JSON pointer to a Booking/Projekt/Plantafel entity.\nmodel CalendarEvent {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n userId String\n connectionId String?\n source CalendarEventSource\n provider CalendarProvider?\n externalEventId String?\n externalCalendarId String?\n title String?\n description String?\n location String?\n startsAt DateTime\n endsAt DateTime\n isAllDay Boolean @default(false)\n timeZone String?\n recurrenceRule String?\n attendees Json @default(\"[]\")\n // Provider concurrency token (Google etag) for conflict detection.\n etag String?\n lastModifiedExternal DateTime?\n isBusyForAvailability Boolean @default(true)\n internalEntityLink Json?\n // Monotonic HiveGrid-side version for optimistic locking (M25 Block F).\n versionToken Int @default(0)\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n connection CalendarConnection? @relation(fields: [connectionId], references: [id], onDelete: SetNull)\n mappings CalendarEventMapping[]\n\n @@unique([tenantId, userId, provider, externalEventId])\n @@index([tenantId, userId, startsAt])\n @@index([tenantId, userId, lastModifiedExternal(sort: Desc)])\n @@index([tenantId, source, archivedAt])\n}\n\n/// Links a HiveGrid-internal event to its external mirror(s). One internal event\n/// can map to several providers/calendars (e.g. Google + Microsoft in v2).\nmodel CalendarEventMapping {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n internalEventId String\n externalEventId String\n provider CalendarProvider\n externalCalendarId String\n connectionId String\n lastSyncedAt DateTime?\n lastKnownExternalEtag String?\n lastKnownInternalVersionToken Int?\n\n internalEvent CalendarEvent @relation(fields: [internalEventId], references: [id], onDelete: Cascade)\n connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)\n\n @@unique([internalEventId, provider, externalCalendarId])\n @@index([tenantId, connectionId])\n}\n\n/// Per-connection-per-calendar delta cursor (Google syncToken). Drives the\n/// incremental external→HiveGrid sync (M25 Block D/E).\nmodel CalendarSyncCursor {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n connectionId String\n externalCalendarId String\n cursorToken String?\n lastFullSyncAt DateTime?\n\n connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)\n\n @@unique([connectionId, externalCalendarId])\n @@index([tenantId, connectionId])\n}\n\n/// Persisted inbound webhook notification (idempotency + retry, M25 Block E).\n/// A fast 200 is returned to the provider; a worker drains `pending` rows.\nmodel CalendarWebhookEvent {\n id String @id @default(cuid())\n receivedAt DateTime @default(now())\n tenantId String\n connectionId String\n provider CalendarProvider\n notificationPayload Json\n processingStatus CalendarWebhookProcessingStatus @default(pending)\n processingErrorText String?\n processedAt DateTime?\n // Provider-specific resource state (Google X-Goog-Resource-State).\n externalResourceState String?\n\n connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, processingStatus, receivedAt])\n @@index([tenantId, connectionId])\n}\n\n/// A resolved sync conflict (DoD 4). The connection-detail view shows the latest\n/// 50 with a Klartext description + how it was resolved (Last-Write-Wins).\nmodel CalendarConflict {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n connectionId String\n userId String\n internalEventId String?\n externalEventId String?\n resolution CalendarConflictResolution\n // Klartext description shown in the conflict log (M002/M003 key + rendered text).\n descriptionText String\n isDemoData Boolean @default(false)\n\n connection CalendarConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, connectionId, createdAt(sort: Desc)])\n @@index([tenantId, userId])\n}\n\n// Realtime Y.js document persistence (Phase 05 Task #59 — Hocuspocus + Y.js).\n//\n// `CollabDoc` is one row per (tenant, resourceType, resourceId) triple — the\n// Hocuspocus database extension fetches `ydocState` on connect, persists it\n// back on debounced flush, and bumps `version` + `lastUpdatedAt`. Documents\n// are tenant-scoped so the existing tenant-isolation tooling applies as-is.\n//\n// Refs: docs/improvement-plan/05-business-features/realtime-collab.md\n\nmodel CollabDoc {\n id String @id @default(cuid())\n tenantId String\n /// Logical resource family the doc belongs to. Examples today:\n /// \"kb-article\" | \"crm-note\" | \"workflow\" — extensible without schema-changes.\n resourceType String\n /// Resource primary-key inside `resourceType`. Free-form; consumers\n /// embed CUIDs / UUIDs / slugs depending on the upstream entity.\n resourceId String\n /// Encoded Y.js update payload — `Y.encodeStateAsUpdate(doc)`.\n /// Persisted as `bytea`; capped at HOCUSPOCUS_MAX_PAYLOAD_BYTES on store.\n ydocState Bytes\n /// Monotonic update counter, incremented per store-call. Surfaces in\n /// admin dashboards for \"is this doc still being edited\" queries.\n version Int @default(0)\n /// Touched on every store-call. `lastSnapshotAt` lags behind for the\n /// snapshot/compaction cadence (separate task #59 step 5).\n lastUpdatedAt DateTime @default(now())\n lastSnapshotAt DateTime?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([tenantId, resourceType, resourceId])\n @@index([tenantId, resourceType, lastUpdatedAt(sort: Desc)])\n @@index([lastUpdatedAt])\n}\n\nmodel AppConfiguration {\n id String @id @default(cuid())\n updatedAt DateTime @updatedAt\n name String\n url String\n theme String?\n authRequireEmailVerification Boolean @default(false)\n authRequireOrganization Boolean @default(true)\n authRequireName Boolean @default(true)\n analyticsEnabled Boolean @default(true)\n analyticsSimpleAnalytics Boolean @default(false)\n analyticsPlausibleAnalytics Boolean @default(false)\n subscriptionRequired Boolean @default(true)\n subscriptionAllowSubscribeBeforeSignUp Boolean @default(true)\n subscriptionAllowSignUpBeforeSubscribe Boolean @default(true)\n cookiesEnabled Boolean @default(false)\n metricsEnabled Boolean @default(false)\n metricsLogToConsole Boolean @default(false)\n metricsSaveToDatabase Boolean @default(false)\n metricsIgnoreUrls String?\n brandingLogo String?\n brandingLogoDarkMode String?\n brandingIcon String?\n brandingIconDarkMode String?\n brandingFavicon String?\n headScripts String?\n bodyScripts String?\n emailProvider String?\n emailFromEmail String?\n emailFromName String?\n emailSupportEmail String?\n}\n\nmodel Log {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String?\n userId String?\n apiKeyId String?\n url String\n action String\n details String?\n apiKey ApiKey? @relation(fields: [apiKeyId], references: [id], onDelete: Cascade)\n tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n\nmodel AuditEvent {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String?\n actorId String?\n actorType String\n actorEmail String?\n actorIp String?\n actorUserAgent String?\n action String\n targetType String?\n targetId String?\n requestId String?\n sourceModule String?\n outcome String @default(\"success\")\n dataSensitivity String @default(\"internal\")\n regulatoryScope String[] @default([])\n metadata Json?\n // Structured field-level change capture (ENTITY-MODEL §Domäne 2, AK-P3 DoD 2).\n // Nullable/additive: legacy rows and callers without diff capture stay valid.\n // NOT part of the eventHash digest — the chain payload is frozen; binding\n // diffs into the chain is a coordinated R-P1b follow-up.\n beforeDiff Json?\n afterDiff Json?\n // Persisted German summary line; viewers fall back to a derived summary\n // when null (pre-existing rows).\n summaryText String?\n previousHash String?\n eventHash String?\n\n @@index([tenantId, createdAt], name: \"audit_event_tenant_created_at_idx\")\n @@index([actorId, createdAt], name: \"audit_event_actor_created_at_idx\")\n @@index([action, createdAt], name: \"audit_event_action_created_at_idx\")\n @@index([requestId], name: \"audit_event_request_id_idx\")\n @@index([tenantId, action, createdAt], name: \"audit_event_tenant_action_created_at_idx\")\n @@index([tenantId, outcome, createdAt], name: \"audit_event_tenant_outcome_created_at_idx\")\n}\n\nmodel IdempotencyKey {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n expiresAt DateTime?\n scope String\n key String\n requestHash String\n responseStatus Int\n responseBody Json?\n responseHeaders Json?\n\n @@unique([scope, key], name: \"idempotency_key_scope_key\")\n @@index([expiresAt], name: \"idempotency_key_expires_at_idx\")\n}\n\nmodel ApiKey {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n createdByUserId String\n tenantId String\n key String @default(uuid())\n keyHash String?\n keyPrefix String?\n keyLastFour String?\n hashedAt DateTime?\n keyVersion Int @default(1)\n scopes Json @default(\"[\\\"public_api:read\\\"]\")\n alias String\n expires DateTime?\n active Boolean\n createdByUser User @relation(fields: [createdByUserId], references: [id], onDelete: Cascade)\n tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n apiKeyLogs ApiKeyLog[]\n logs Log[]\n tenantIpAddresses TenantIpAddress[]\n\n @@unique([tenantId, alias])\n @@unique([tenantId, key])\n @@unique([keyHash], name: \"api_key_hash_key\")\n @@index([key])\n}\n\nmodel ApiKeyLog {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n apiKeyId String?\n apiKey ApiKey? @relation(fields: [apiKeyId], references: [id])\n tenantId String?\n tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n ip String\n endpoint String\n method String\n params String\n status Int?\n duration Int?\n error String?\n type String?\n alias String?\n tenantName String?\n\n @@index([tenantId], name: \"api_key_log_tenant\")\n @@index([tenantId, createdAt], name: \"api_key_log_tenant_created_at\")\n @@index([tenantId, type], name: \"api_key_log_tenant_type\")\n @@index([apiKeyId, tenantId, createdAt(sort: Desc)], name: \"api_key_log_key_tenant_created_at\")\n}\n\nmodel Event {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String?\n tenant Tenant? @relation(fields: [tenantId], references: [id])\n userId String?\n user User? @relation(fields: [userId], references: [id])\n name String\n data String\n resource String?\n description String?\n attempts EventWebhookAttempt[]\n}\n\nmodel EventWebhookAttempt {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n startedAt DateTime?\n finishedAt DateTime?\n eventId String\n event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)\n endpoint String\n success Boolean?\n status Int?\n message String?\n body String?\n}\n\nmodel MetricLog {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n env String\n type String // loader, action\n route String\n url String\n function String\n duration Int\n userId String?\n tenantId String?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n}\n\nmodel FileUploadProgress {\n id String @id @default(cuid())\n fileName String\n progressServer Int\n progressStorage Int\n url String?\n error String?\n chunks FileChunk[]\n}\n\nmodel FileChunk {\n id Int @id @default(autoincrement())\n fileUploadId String\n fileUpload FileUploadProgress @relation(fields: [fileUploadId], references: [id], onDelete: Cascade)\n index Int\n data Bytes\n}\n\nmodel FileObject {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n provider String\n bucket String\n key String\n contentType String\n byteSize Int\n checksumSha256 String?\n publicUrl String?\n uploadedAt DateTime?\n lastSignedUploadAt DateTime?\n lastSignedDownloadAt DateTime?\n metadata Json?\n\n @@unique([provider, bucket, key], name: \"file_object_provider_bucket_key\")\n @@index([provider, bucket], name: \"file_object_provider_bucket_idx\")\n @@index([uploadedAt], name: \"file_object_uploaded_at_idx\")\n}\n\n/// Privacy (AD-22): `ip` speichert einen HMAC-SHA256-Pseudonym-Hash der Client-IP, KEINE Klartext-IP.\n/// Persistiert wird nur das Land (countryCode/countryName); regionCode/city/zipCode/latitude/longitude\n/// bleiben bewusst leer. Auflösung lokal (DB-IP Lite), kein externer Transfer.\nmodel IpAddress {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n ip String @unique\n provider String\n type String\n countryCode String\n countryName String\n regionCode String\n regionName String\n city String\n zipCode String\n latitude Decimal?\n longitude Decimal?\n metadata String\n logs IpAddressLog[]\n}\n\n/// Privacy (AD-22): `ip` ist der HMAC-Pseudonym-Hash der Client-IP, kein Klartext.\nmodel IpAddressLog {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n ip String\n url String\n action String\n description String\n success Boolean\n error String?\n metadata String?\n ipAddressId String?\n ipAddress IpAddress? @relation(fields: [ipAddressId], references: [id])\n}\n\nmodel Widget {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String?\n name String\n appearance String\n metadata String\n\n tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n\n @@unique([tenantId, name])\n}\n\nmodel Credential {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n name String @unique\n value Json\n}\n\n// R-P6 (P6 CRM core) — typed CRM entities that replace the generic Entity-Builder\n// for the CRM domain (AD-2). Source of truth: ENTITY-MODEL.md Domäne 5 (LOCKED).\n//\n// AD-21: one self-contained schema file per module. `tenantId` /\n// `createdByUserId` / `zustaendigerUserId` are intentionally BARE String scalars\n// (no `@relation` to Tenant/User) so this file has zero merge-conflict surface\n// against `core.prisma`/`accounts.prisma` (no back-relation fields on Tenant/User\n// needed). Referential integrity to Tenant/User is carried at the application\n// layer (crmService + crmAccess) plus the RLS policies added in the merge\n// migration (see prisma/rls/crm-isolation.sql — deferred activation, like\n// appsEngine/activity).\n//\n// Activity stream is NOT defined here: it lives in `activity.prisma` (model\n// Activity, polymorphic subjectType/subjectId) and is appended via `logActivity()`\n// from `@hivegrid/activity` (AGENTS DoD #14).\n//\n// Soft-delete via `archivedAt`. Demo-seed rows carry `isDemoData = true` and are\n// bulk-removed on the production switch-over (per-module deleteMany).\n//\n// Lead → Projekt extension point (DoD 5, AD-20): Lead and Projekt are built in\n// P7/P8. The polymorphic `CustomFieldEntityType` enum and the `TagAssignment`\n// /`Activity` entityType strings already carry `lead`/`projekt`/`rechnung`, so\n// custom fields, tags and activities attach to those entities without a schema\n// change. A Kontakt is referenced from a future Lead/Projekt by bare id only.\n\n/// Kontakt discriminator: a Kontakt is either a private person or an organisation.\nenum KontaktTyp {\n privatperson\n organisation\n}\n\n/// Lifecycle status of a Kontakt (lead-independent commercial relationship state).\nenum KontaktStatus {\n kontakt\n kunde\n bestandskunde\n}\n\n/// Optional legal-form / classification marker for organisation contacts.\nenum OrgMerkmal {\n gmbh\n kg\n oeffentliche_einrichtung\n sonstige\n}\n\n/// Role of a KontaktRelation (Kontaktart) — \"this contact is the X of that one\".\nenum KontaktArt {\n hauptkontakt\n sekundaerkontakt\n mitarbeiter\n sonstige\n}\n\n/// Polymorphic target type for tenant custom fields. Carries `lead`/`projekt`/\n/// `rechnung` already so P7/P8 attach without a migration (Lead → Projekt\n/// extension point, DoD 5).\nenum CustomFieldEntityType {\n projekt\n kontakt\n lead\n rechnung\n}\n\n/// Data type of a tenant custom field — drives the value renderer and validation.\nenum CustomFieldDatentyp {\n text\n textarea\n zahl\n waehrung\n datum\n datum_range\n select\n multiselect\n boolean\n email\n telefon\n datei\n}\n\n/// A contact (Kontakt), the CRM core entity. Oberbegriff for both private persons\n/// (kontaktTyp = privatperson → vorname/nachname) and organisations\n/// (kontaktTyp = organisation → orgName/orgMerkmal). Scoped per tenant, soft-delete\n/// via `archivedAt`. `zustaendigerUserId` is the owner for the crm.read_own filter.\nmodel Kontakt {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n createdByUserId String\n kontaktTyp KontaktTyp\n kontaktStatus KontaktStatus @default(kontakt)\n // Person fields (kontaktTyp = privatperson).\n vorname String?\n nachname String?\n // Organisation fields (kontaktTyp = organisation).\n orgName String?\n orgMerkmal OrgMerkmal?\n // Denormalised primary channels, kept in sync from KontaktEmail/KontaktTelefon\n // by the service so list/dup-check queries stay single-table.\n primaerEmail String?\n primaerTelefon String?\n // Single reusable address slot (Projekt has 3 slots, Kontakt has 1).\n adresseId String?\n // Owner of record — drives the crm.read_own owner filter (DoD 8).\n zustaendigerUserId String?\n // Preferred outbound language (i18n field per ENTITY-MODEL, AK-P3 DoD 6).\n // Null = tenant default; outbound usage lands in v2 — no UI editor in v1.\n language String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n adresse Adresse? @relation(fields: [adresseId], references: [id])\n emails KontaktEmail[]\n telefone KontaktTelefon[]\n relationenVon KontaktRelation[] @relation(\"KontaktRelationVon\")\n relationenZu KontaktRelation[] @relation(\"KontaktRelationZu\")\n\n @@index([tenantId, archivedAt])\n @@index([tenantId, kontaktTyp, archivedAt])\n @@index([tenantId, primaerEmail])\n @@index([tenantId, primaerTelefon])\n @@index([tenantId, zustaendigerUserId])\n @@index([tenantId, adresseId])\n}\n\n/// Self-referential M:N relation between contacts (e.g. organisation ↔ primary\n/// contact person). The `rolle` (Kontaktart) is the role of the relation itself.\nmodel KontaktRelation {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n vonKontaktId String\n zuKontaktId String\n rolle KontaktArt\n kontext String? // optional free-text describing the relationship\n\n vonKontakt Kontakt @relation(\"KontaktRelationVon\", fields: [vonKontaktId], references: [id], onDelete: Cascade)\n zuKontakt Kontakt @relation(\"KontaktRelationZu\", fields: [zuKontaktId], references: [id], onDelete: Cascade)\n\n @@unique([vonKontaktId, zuKontaktId, rolle])\n @@index([tenantId, vonKontaktId])\n @@index([tenantId, zuKontaktId])\n}\n\n/// One of a contact's e-mail addresses. Exactly one carries `primaer = true`\n/// (enforced in the service), mirrored to `Kontakt.primaerEmail`.\nmodel KontaktEmail {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n kontaktId String\n email String\n primaer Boolean @default(false)\n\n kontakt Kontakt @relation(fields: [kontaktId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, kontaktId])\n @@index([tenantId, email])\n}\n\n/// One of a contact's phone numbers. Exactly one carries `primaer = true`\n/// (enforced in the service), mirrored to `Kontakt.primaerTelefon`.\nmodel KontaktTelefon {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n kontaktId String\n telefon String\n primaer Boolean @default(false)\n\n kontakt Kontakt @relation(fields: [kontaktId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, kontaktId])\n @@index([tenantId, telefon])\n}\n\n/// A reusable postal address. v1 is DE-only (`land` defaults to \"DE\").\nmodel Adresse {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n strasse String?\n hausnummer String?\n plz String?\n ort String?\n land String @default(\"DE\")\n\n kontakte Kontakt[]\n\n @@index([tenantId])\n}\n\n/// Tenant-defined custom field for a polymorphic entity type. The actual values\n/// live in CustomFieldValue. `archiviert` hides the field but keeps its values.\nmodel CustomFieldDefinition {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n entityType CustomFieldEntityType\n key String // machine name, unique per (tenant, entityType)\n label String\n datentyp CustomFieldDatentyp\n optionen Json? // e.g. { \"select\": [\"A\", \"B\"] } for select/multiselect\n archiviert Boolean @default(false)\n isDemoData Boolean @default(false)\n\n values CustomFieldValue[]\n\n @@unique([tenantId, entityType, key])\n @@index([tenantId, entityType])\n}\n\n/// Value of a custom field for a concrete entity. Polymorphic: `entityId` carries\n/// NO DB foreign key — the service validates entityType match + entity existence.\nmodel CustomFieldValue {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n definitionId String\n entityType CustomFieldEntityType\n entityId String\n wert Json? // type-variable value (string, number, array for multiselect…)\n\n definition CustomFieldDefinition @relation(fields: [definitionId], references: [id], onDelete: Cascade)\n\n @@unique([definitionId, entityId])\n @@index([tenantId, entityType, entityId])\n @@index([definitionId])\n}\n\n/// A coloured tag. Cross-cutting and polymorphic via TagAssignment.\nmodel Tag {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n name String\n farbe String // hex code (#RRGGBB) or palette name\n\n assignments TagAssignment[]\n\n @@unique([tenantId, name])\n @@index([tenantId])\n}\n\n/// Polymorphic M:N link Tag ↔ any entity. `entityType` is a String (extensible,\n/// mirrors Activity.subjectType): kontakt | projekt | lead | rechnung | termin | …\n/// `entityId` carries NO DB foreign key — the service validates existence.\nmodel TagAssignment {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n tagId String\n entityType String\n entityId String\n\n tag Tag @relation(fields: [tagId], references: [id], onDelete: Cascade)\n\n @@unique([tagId, entityId, entityType])\n @@index([tenantId, entityType, entityId])\n @@index([tenantId, tagId])\n}\n\n// R-P5 (P5) — per-tenant data-encryption-key store for AD-8 envelope encryption.\n//\n// AD-21: one self-contained schema file per module. `tenantId` is a BARE String\n// scalar (no `@relation`) so this file has zero merge-conflict surface against\n// `core.prisma`/`accounts.prisma` (no back-relation field on Tenant needed).\n//\n// AD-8 (revised by EXT-06: app-side envelope, no cloud-KMS): each tenant has ONE\n// random Data-Encryption-Key (DEK). The DEK is never stored in the clear — only\n// WRAPPED with the app master key (the `KeyWrapper` in\n// packages/foundation/src/crypto/key-wrapper.ts; today EnvKeyWrapper over\n// CRYPTO_SECRET, later swappable for self-hosted Vault/OpenBao WITHOUT\n// re-encrypting any field). Sensitive fields across modules (HR password safe,\n// HR emergency contact, R-P5 OAuth/API-key credentials) are sealed with the\n// tenant DEK.\n//\n// Crypto-shredding (M165 / AK-P21): deleting a tenant's row here makes ALL of\n// that tenant's envelope ciphertext permanently unreadable. The orchestration\n// (load/create/destroy + in-memory unwrapped-DEK cache) lives in\n// packages/db/src/crypto/tenant-envelope.server.ts.\n\n/// One wrapped Data-Encryption-Key per tenant. `wrappedDek` is the tenant DEK\n/// encrypted with the app master key (never the plaintext DEK). `keyVersion`\n/// allows rotating the wrapping scheme without touching field ciphertext.\nmodel TenantEncryptionKey {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String @unique\n // The tenant DEK, wrapped (encrypted) with the app master key. Opaque blob;\n // useless without the master key, so a DB leak alone exposes nothing.\n wrappedDek Bytes\n keyVersion Int @default(1)\n\n @@index([tenantId])\n}\n\n// R-P11b (P11 Dashboard) — typed tenant dashboard layouts.\n//\n// AD-21: self-contained schema. User references are bare String scalars so this\n// slice does not touch accounts/core back-relations while the v1 fixed role\n// layouts stay independent from later drag/drop customization.\n\nenum DashboardRole {\n gf\n office\n monteur\n}\n\nmodel Dashboard {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n name String\n description String?\n role DashboardRole\n isDefaultForRole Boolean @default(true)\n isShared Boolean @default(true)\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n layouts DashboardLayout[]\n instances WidgetInstance[]\n\n @@unique([tenantId, role, name])\n @@index([tenantId, role, isDefaultForRole, archivedAt])\n @@index([tenantId, isShared, archivedAt])\n}\n\nmodel DashboardLayout {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n dashboardId String\n userId String?\n widgets Json @default(\"[]\")\n layoutData Json @default(\"{}\")\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n dashboard Dashboard @relation(fields: [dashboardId], references: [id], onDelete: Cascade)\n\n @@unique([dashboardId, userId])\n @@index([tenantId, dashboardId, userId, archivedAt])\n}\n\nmodel WidgetInstance {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n dashboardId String\n widgetCatalogKey String\n config Json @default(\"{}\")\n position Json @default(\"{}\")\n size Json @default(\"{}\")\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n dashboard Dashboard @relation(fields: [dashboardId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, dashboardId, widgetCatalogKey, archivedAt])\n}\n\n// VA-P23 (P23) Postfach-Sync (Gmail/Outlook) — aligned to ENTITY-MODEL Domäne 8\n// (M09-email-inbox, OAuth-sync/inbox/threading recut only; the v1 sending domain\n// in email.prisma is NOT touched — outbound mail goes through the user mailbox).\n//\n// AD-21: self-contained schema. `tenantId` / `userId` are BARE String scalars\n// (no `@relation` to Tenant/User) → zero merge-conflict surface against\n// core.prisma/accounts.prisma. Intra-module relations (Mailbox → Message /\n// SyncCursor / WebhookEvent) stay inside this file. Matched CRM entities\n// (Kontakt/Lead/Projekt, AD-20 — no \"Deal\" FK) are bare scalars as well.\n//\n// A mailbox is PER-USER: each user connects their own Gmail/Microsoft account.\n// OAuth refresh/access tokens are stored ENVELOPE-ENCRYPTED via the per-tenant\n// DEK seam (AD-8, packages/db/src/crypto/tenant-envelope.server.ts), never plain.\n//\n// RLS ships separately in prisma/rls/email-inbox-isolation.sql (deferred cutover\n// like the other modules). On the feature branch: `prisma db push` only — the\n// merge migration is created at main-merge (AD-21). Visibility: email.read_own\n// restricts list + activity to mailboxes with ownerUserId = self (M09 Block I).\n\n/// Mailbox provider. Both land in v2 (M096/M097).\nenum EmailInboxProvider {\n gmail\n microsoft\n}\n\n/// Lifecycle status of a connected mailbox (M09 Block B/D).\nenum EmailMailboxStatus {\n connecting\n active\n paused\n error\n revoked\n}\n\n/// Direction of a mirrored message.\nenum EmailDirection {\n inbound\n outbound\n}\n\n/// How the CRM link on a message came to be (M09 Block E).\nenum EmailMatchConfidence {\n high\n medium\n low\n manual\n none\n}\n\n/// Initial 90-day sync lifecycle (resumable, M09 Block D).\nenum EmailInitialSyncStatus {\n pending\n running\n completed\n failed\n}\n\n/// Worker processing state of an inbound provider push (M09 Block D).\nenum EmailWebhookProcessingStatus {\n pending\n processing\n completed\n failed\n skipped\n}\n\n/// A user's connected mailbox. PER-USER, tenant-scoped. OAuth tokens are\n/// AES-256-GCM per-tenant-DEK envelopes (AD-8); never selected into a list\n/// view-model. `webhookClientState` is the per-mailbox shared secret echoed by\n/// Microsoft Graph notifications (its only auth mechanism) and doubles as the\n/// Gmail channel verification token. `dataConnectionId` is an OPTIONAL read-only\n/// reference to the Apps-Engine DataConnection catalog entry (bare scalar).\nmodel EmailIntegrationMailbox {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n ownerUserId String\n provider EmailInboxProvider\n // User-visible account identity (connection card + Gmail push lookup).\n emailAddress String\n externalAccountId String\n displayName String?\n // Sensitive: per-tenant envelope ciphertext (AD-8). Never serialised to a VM.\n oauthRefreshTokenCiphertext String?\n oauthAccessTokenCiphertext String?\n oauthAccessTokenExpiresAt DateTime?\n // Granted OAuth scopes; a reduction by the user triggers a Klartext re-connect.\n oauthScopes String[]\n // Provider push handle: Gmail watch (historyId anchor lives in the cursor) or\n // Graph subscription id. Gmail watches expire after ~7d, Graph after ~3d —\n // one renewal cron covers BOTH providers via webhookSubscriptionExpiresAt.\n webhookSubscriptionId String?\n webhookSubscriptionExpiresAt DateTime?\n webhookClientState String?\n isDefaultForUser Boolean @default(false)\n status EmailMailboxStatus @default(connecting)\n lastSyncAt DateTime?\n // Klartext failure detail when status = error (M002).\n lastErrorText String?\n // Read-only Apps-Engine catalog reference (AD-21 bare scalar, optional).\n dataConnectionId String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n messages EmailIntegrationMessage[]\n syncCursors EmailIntegrationSyncCursor[]\n webhookEvents EmailIntegrationWebhookEvent[]\n\n @@unique([tenantId, ownerUserId, provider, externalAccountId])\n @@index([tenantId, ownerUserId, status, archivedAt])\n // Gmail Pub/Sub pushes carry only {emailAddress, historyId} → address lookup.\n @@index([tenantId, emailAddress])\n // Renewal cron scans both providers by expiry; stale-poll fallback by lastSyncAt.\n @@index([tenantId, webhookSubscriptionExpiresAt])\n @@index([tenantId, status, lastSyncAt])\n}\n\n/// Mirror of a provider message. Tenant-scoped; visibility is owner-filtered in\n/// code (email.read_own vs read_all). Archiving is HiveGrid-side only — the\n/// provider mailbox is never mutated by archive. `internetMessageId` (RFC 5322)\n/// is the cross-provider dedupe key: Graph sendMail returns 202 without an id,\n/// so the sent-items delta re-ingest must collapse onto the local outbound mirror.\nmodel EmailIntegrationMessage {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n mailboxId String\n providerMessageId String\n providerThreadId String?\n internetMessageId String?\n direction EmailDirection\n fromAddress String\n fromName String?\n toAddresses Json @default(\"[]\")\n ccAddresses Json @default(\"[]\")\n bccAddresses Json @default(\"[]\")\n subject String?\n // First ~140 chars of the text body for the list view (no body decrypt/parse).\n snippet String?\n bodyHtml String?\n bodyText String?\n sentAt DateTime\n receivedAt DateTime?\n isRead Boolean @default(false)\n isStarred Boolean @default(false)\n // List-Unsubscribe header present → flagged, excluded from auto-match (M09 E).\n isNewsletter Boolean @default(false)\n hasAttachments Boolean @default(false)\n providerLabels Json @default(\"[]\")\n // AD-20 match targets (bare scalars — crm.prisma/leads.prisma/projekt.prisma).\n matchedKontaktId String?\n matchedLeadId String?\n matchedProjektId String?\n matchConfidence EmailMatchConfidence @default(none)\n // A manual override wins and blocks any re-match (M09 Block E).\n manualOverrideAt DateTime?\n manualOverrideUserId String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n mailbox EmailIntegrationMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)\n\n @@unique([tenantId, mailboxId, providerMessageId])\n @@index([tenantId, mailboxId, sentAt(sort: Desc)])\n @@index([tenantId, providerThreadId])\n @@index([tenantId, internetMessageId])\n @@index([tenantId, matchedKontaktId, sentAt(sort: Desc)])\n @@index([tenantId, matchedLeadId, sentAt(sort: Desc)])\n @@index([tenantId, matchedProjektId, sentAt(sort: Desc)])\n @@index([tenantId, fromAddress])\n}\n\n/// Per-mailbox-per-folder delta cursor. Gmail uses ONE pseudo-folder (`*`,\n/// historyId is mailbox-global); Microsoft Graph delta is PER FOLDER (inbox +\n/// sentitems each get a cursor). `initialSyncProgress` keeps pageToken /\n/// fetchedCount / oldestFetchedAt so an aborted 90-day initial sync resumes.\nmodel EmailIntegrationSyncCursor {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n mailboxId String\n externalFolderId String\n // Gmail historyId / Graph deltaToken for incremental pulls.\n cursorToken String?\n initialSyncStatus EmailInitialSyncStatus @default(pending)\n initialSyncProgress Json?\n lastCursorAdvanceAt DateTime?\n lastFullSyncAt DateTime?\n // Klartext failure detail when initialSyncStatus = failed (M002).\n errorText String?\n\n mailbox EmailIntegrationMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)\n\n @@unique([mailboxId, externalFolderId])\n @@index([tenantId, mailboxId])\n @@index([tenantId, initialSyncStatus])\n}\n\n/// Persisted inbound provider push (idempotency + retry). Append-only; a fast\n/// 200/202 is returned to the provider and a worker drains `pending` rows.\n/// Retention: 30 days (failed rows 90 days) via the cleanup cron.\nmodel EmailIntegrationWebhookEvent {\n id String @id @default(cuid())\n receivedAt DateTime @default(now())\n tenantId String\n mailboxId String\n provider EmailInboxProvider\n notificationPayload Json\n processingStatus EmailWebhookProcessingStatus @default(pending)\n processingErrorText String?\n processedAt DateTime?\n // Which EmailIntegrationMessage ids were derived from this push.\n derivedMessageIds Json @default(\"[]\")\n\n mailbox EmailIntegrationMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, processingStatus, receivedAt])\n @@index([tenantId, mailboxId])\n @@index([receivedAt])\n}\n\nmodel TenantInboundAddress {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n address String @unique\n // AK-P14a: structured address (local-part + full address) and routing purpose.\n localPart String?\n fullAddress String?\n purpose EmailInboundPurpose @default(lead_inbox)\n // BCC-logging toggle: a bcc_logging address may be shown but inactive.\n enabled Boolean @default(true)\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n email Email[]\n\n @@index([tenantId, purpose, archivedAt])\n}\n\nmodel Email {\n id String @id @default(cuid())\n tenantInboundAddressId String?\n tenantInboundAddress TenantInboundAddress? @relation(fields: [tenantInboundAddressId], references: [id], onDelete: Cascade)\n messageId String @unique\n type String // inbound, outbound\n date DateTime\n subject String\n fromEmail String\n fromName String?\n toEmail String\n toName String?\n textBody String\n htmlBody String\n // AK-P14a: delivery state + CRM linkage. relatedKontaktId/relatedProjektId are\n // BARE String scalars (no @relation) — the Kontakt/Projekt FK is wired in R-P6\n // (CRM-Kern); until then app-level scoping carries the link.\n purpose String?\n deliveryStatus String?\n relatedKontaktId String?\n relatedProjektId String?\n reads EmailRead[]\n attachments EmailAttachment[]\n cc EmailCc[]\n}\n\nmodel EmailRead {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n emailId String\n email Email @relation(fields: [emailId], references: [id], onDelete: Cascade)\n userId String\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n}\n\nmodel EmailCc {\n id String @id @default(cuid())\n emailId String\n toEmail String\n toName String?\n email Email @relation(fields: [emailId], references: [id], onDelete: Cascade)\n}\n\nmodel EmailAttachment {\n id String @id @default(cuid())\n emailId String\n name String\n type String\n length Int\n content String\n publicUrl String?\n storageBucket String?\n storageProvider String?\n email Email @relation(fields: [emailId], references: [id], onDelete: Cascade)\n}\n\nmodel EmailSender {\n id String @id @default(cuid())\n tenantId String?\n provider String\n stream String\n apiKey String\n apiSecret String?\n fromEmail String\n fromName String?\n replyToEmail String?\n // AK-P14a: default-sender marker, demo seed flag, optional sending-domain link\n // (bare scalar FK to TenantSendingDomain, resolved in the service layer).\n isDefault Boolean @default(false)\n isDemoData Boolean @default(false)\n sendingDomainId String?\n tenant Tenant? @relation(fields: [tenantId], references: [id])\n campaigns Campaign[]\n outboundEmails OutboundEmail[]\n\n @@index([tenantId, isDefault])\n}\n\nmodel Campaign {\n id String @id @default(cuid())\n tenantId String?\n emailSenderId String\n name String\n subject String\n htmlBody String\n textBody String?\n status String @default(\"draft\")\n track Boolean\n sentAt DateTime?\n // AK-P14b: typed segment link + scheduling + DSGVO footer/preview metadata.\n // recipientSegmentId is the typed audience source (the legacy Entity-Builder\n // recipient path was removed by R-P14C). scheduledAt + timezone drive\n // timezone-aware delayed sends.\n recipientSegmentId String?\n scheduledAt DateTime?\n timezone String?\n previewText String?\n footerHtml String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n emailSender EmailSender @relation(fields: [emailSenderId], references: [id])\n recipients OutboundEmail[]\n variants CampaignVariant[]\n segment RecipientSegment? @relation(fields: [recipientSegmentId], references: [id])\n tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, status, archivedAt])\n}\n\nmodel OutboundEmail {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String?\n tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n campaignId String?\n campaign Campaign? @relation(fields: [campaignId], references: [id], onDelete: Cascade)\n // R-P14C (AD-2): the legacy Entity-Builder contactRowId/contactRow relation was\n // dropped. The typed recipient link is the bare `kontaktId` scalar (R-P6 Kontakt\n // id, AK-P14b). campaignVariantId attributes A/B sends; unsubscribeToken/\n // trackingToken are per-recipient signed handles.\n kontaktId String?\n campaignVariantId String?\n unsubscribeToken String?\n trackingToken String?\n email String\n fromSenderId String\n isPreview Boolean?\n error String?\n sentAt DateTime?\n deliveredAt DateTime?\n bouncedAt DateTime?\n spamComplainedAt DateTime?\n unsubscribedAt DateTime?\n fromSender EmailSender @relation(fields: [fromSenderId], references: [id])\n opens OutboundEmailOpen[]\n clicks OutboundEmailClick[]\n\n @@index([tenantId, sentAt])\n}\n\nmodel OutboundEmailOpen {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n firstOpen Boolean\n // AK-P14a: anonymized client IP (sha256, truncated) — never the raw address.\n ipHash String?\n outboundEmailId String\n outboundEmail OutboundEmail @relation(fields: [outboundEmailId], references: [id], onDelete: Cascade)\n}\n\nmodel OutboundEmailClick {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n link String\n // AK-P14a: anonymized client IP (sha256, truncated) — never the raw address.\n ipHash String?\n outboundEmailId String\n outboundEmail OutboundEmail @relation(fields: [outboundEmailId], references: [id], onDelete: Cascade)\n}\n\n// =============================================================================\n// AK-P14a · P14 — Email foundation (sending-domain verification, BCC bridge,\n// suppression, tracking). AD-21: these models live in this module file; new\n// tenant-scoped models use BARE `tenantId String` scalars (no @relation) so the\n// file keeps zero merge-conflict surface against core.prisma (same stance as\n// hr.prisma). RLS ships separately in prisma/rls/email-isolation.sql (deferred\n// cutover; app-level scoping via withTenantRLS carries isolation meanwhile).\n// =============================================================================\n\n/// AK-P14a · routing purpose of a tenant inbound address.\nenum EmailInboundPurpose {\n lead_inbox\n bcc_logging\n reply_routing\n}\n\n/// AK-P14a · DNS verification state of a tenant sending domain.\nenum SendingDomainStatus {\n pending\n verifying\n verified\n failed\n}\n\n/// AK-P14a · why an address is suppressed from sending.\nenum EmailSuppressionReason {\n bounce\n complaint\n manual\n}\n\n/// A per-tenant sending domain (DKIM/SPF/DMARC). The tenant publishes the public\n/// records (shown with copy buttons); the system auto-probes DNS every 5 minutes\n/// and walks `verificationStatus` pending → verifying → verified|failed. After 7\n/// days without success `lastError` carries a Klartext (M002) explanation. The\n/// DKIM private key is stored ENVELOPE-ENCRYPTED per tenant (AD-8) and never\n/// returned to the client. Soft-delete via `archivedAt`.\nmodel TenantSendingDomain {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n domain String\n dkimSelector String?\n dkimRecord String?\n spfRecord String?\n dmarcRecord String?\n // Sensitive: DKIM private key as per-tenant AES-256-GCM envelope ciphertext\n // (AD-8, getTenantFieldCrypto). Never serialised to a view-model.\n dkimPrivateKeyCiphertext String?\n verificationStatus SendingDomainStatus @default(pending)\n // Provider handle (Mailjet /v3/REST/dns id) for re-checks.\n mailjetDnsId String?\n // First probe anchors the 7-day \"still not verified\" Klartext window.\n firstProbeAt DateTime?\n lastProbedAt DateTime?\n // Klartext failure detail surfaced after the 7-day window (M002).\n lastError String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n @@unique([tenantId, domain])\n @@index([tenantId, verificationStatus, archivedAt])\n}\n\n/// A per-tenant suppression entry: an address that must NOT be sent to. Populated\n/// by bounce/complaint webhooks (reason bounce|complaint) and manual additions.\nmodel EmailSuppressionList {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n emailAddress String\n reason EmailSuppressionReason @default(manual)\n // Free-text provider detail (e.g. Mailjet bounce comment).\n detail String?\n\n @@unique([tenantId, emailAddress])\n @@index([tenantId, reason])\n}\n\n/// A reusable email template, scoped per tenant. `isDefault` marks the seed\n/// starting point; `isDemoData` flags seedable demo rows. Soft-delete via\n/// `archivedAt`.\nmodel EmailTemplate {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n name String\n subject String\n htmlBody String\n isDefault Boolean @default(false)\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n @@index([tenantId, archivedAt])\n}\n\n// =============================================================================\n// AK-P14b · P14 — Email marketing (segments, A/B variants, marketing consent,\n// unsubscribe). TYPED path (AD-2): segments read the R-P6 typed `Kontakt` model\n// (NOT the Entity-Builder). Same AD-21 stance as AK-P14a: bare `tenantId String`\n// scalars, no @relation to core; cross-module references (kontaktId, campaignId)\n// are bare scalars resolved in the service layer. RLS ships in\n// prisma/rls/email-isolation.sql (deferred cutover). The legacy Entity-Builder\n// campaign path (OutboundEmail.contactRowId / CrmService) was removed by R-P14C\n// (Variante A); recipients are typed via kontaktId + RecipientSegment.\n// =============================================================================\n\n/// Marketing consent lifecycle of a Kontakt (DSGVO double-opt-in). `none` = no\n/// consent, `single` = opted in but not yet confirmed, `double` = confirmed via\n/// the opt-in e-mail. Lives in email.prisma (NOT crm.prisma) so Raffael's R-P6\n/// schema stays untouched (AD-21); `kontaktId` is a bare scalar.\nenum MarketingConsentStatus {\n none\n single\n double\n}\n\n/// Scope of an unsubscribe: `all` = the contact opts out of all marketing,\n/// `campaign` = a single-campaign opt-out (rare, kept for completeness).\nenum UnsubscribeScope {\n all\n campaign\n}\n\n/// A/B variant slot of a campaign.\nenum CampaignVariantLabel {\n a\n b\n}\n\n/// A reusable recipient segment. `filterDefinition` is a nested AND/OR tree\n/// (see segmentQuery.ts) evaluated read-only against the typed Kontakt model.\n/// `isStaticSnapshot` freezes the resolved membership into SegmentSnapshotMember\n/// at creation time; a dynamic segment re-resolves on every send.\nmodel RecipientSegment {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n name String\n // Polymorphic target type (mirrors TagAssignment.entityType). v1 = \"kontakt\".\n entityType String @default(\"kontakt\")\n filterDefinition Json\n isStaticSnapshot Boolean @default(false)\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n snapshotMembers SegmentSnapshotMember[]\n campaigns Campaign[]\n\n @@index([tenantId, archivedAt])\n}\n\n/// Frozen membership row of a static segment. `kontaktId` is a bare scalar\n/// (typed Kontakt id, no DB FK — AD-21).\nmodel SegmentSnapshotMember {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n segmentId String\n kontaktId String\n segment RecipientSegment @relation(fields: [segmentId], references: [id], onDelete: Cascade)\n\n @@unique([segmentId, kontaktId])\n @@index([tenantId, segmentId])\n}\n\n/// One A/B variant of a campaign. The send-engine splits the audience by\n/// `weightPercent`; per-variant counters drive the A/B comparison report.\nmodel CampaignVariant {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n campaignId String\n label CampaignVariantLabel\n subject String\n htmlBody String\n textBody String?\n weightPercent Int @default(50)\n deliveredCount Int @default(0)\n openedCount Int @default(0)\n clickedCount Int @default(0)\n campaign Campaign @relation(fields: [campaignId], references: [id], onDelete: Cascade)\n\n @@unique([campaignId, label])\n @@index([tenantId, campaignId])\n}\n\n/// Per-tenant marketing consent for a Kontakt. `kontaktId` is a bare scalar\n/// (typed Kontakt id). One row per (tenant, kontakt).\nmodel KontaktMarketingConsent {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n kontaktId String\n status MarketingConsentStatus @default(none)\n // Where the opt-in came from (e.g. \"form:\", \"import\", \"manual\").\n optInSource String?\n optInAt DateTime?\n // HMAC handle for the double-opt-in confirmation link (verified, not stored raw).\n doubleOptInToken String?\n confirmedAt DateTime?\n unsubscribedAt DateTime?\n\n @@unique([tenantId, kontaktId])\n @@index([tenantId, status])\n}\n\n/// An unsubscribe record (one-click / List-Unsubscribe). `kontaktId` is a bare\n/// scalar; `campaignId` is set only for a campaign-scoped opt-out.\nmodel Unsubscribe {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n kontaktId String\n scope UnsubscribeScope @default(all)\n campaignId String?\n reason String?\n\n @@index([tenantId, kontaktId])\n}\n\n// Marketing-Funnel Phase 3 (Phase 05 Task #80).\n//\n// Email-sequence engine: operator-defined drip campaigns triggered by outbox\n// events. `EmailSequence` is the sequence definition (steps as a JSON\n// array). `EmailSequenceRun` is one in-flight execution against a single\n// Lead / Tenant target. `EmailSequenceStepDelivery` records the per-step\n// send + open + click outcome and powers the statistics dashboard.\n//\n// V1 sequences are linear (step 0, 1, 2, ...). Conditions per step and\n// per-step delay-from-trigger make sequences reusable without date-math\n// in the definition schema. Branching / parallel paths would require a\n// schema-refactor (separate Step table) but are not in scope today.\n\nmodel EmailSequence {\n id String @id @default(cuid())\n /// NULL for system-wide sequences; set for tenant-scoped ones.\n tenantId String?\n name String\n description String?\n\n /// `lead.captured` | `lead.qualified` | `lead.stale_60d` |\n /// `lead.converted_to_trial` | `lead.converted_to_customer` |\n /// `tenant.signup` | `tenant.trial_expiring` | `tenant.cancelled` |\n /// `custom`. Matched against outbox eventType (dotted-snake suffix).\n triggerEvent String\n\n /// JSON array of `EmailSequenceStep` objects. Shape:\n /// `{ stepIndex, delayHours, template, subject, conditions?, variables? }`.\n /// See packages/email-sequences/src/types.ts for the runtime type.\n stepsJson Json\n\n /// Optional sequence-level conditions (e.g. \"only customers with plan=pro\").\n /// JSON object — same DSL as per-step conditions.\n conditionsJson Json?\n\n /// Operator kill-switch. When false, trigger handler skips this sequence\n /// even if the event matches.\n isEnabled Boolean @default(true)\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n runs EmailSequenceRun[]\n\n @@index([triggerEvent, isEnabled])\n @@index([tenantId, createdAt(sort: Desc)])\n}\n\nmodel EmailSequenceRun {\n id String @id @default(cuid())\n sequenceId String\n /// Target lead — set when the trigger came from a Lead event.\n leadId String?\n /// Target tenant — set when the trigger came from a Tenant event.\n tenantId String?\n /// Outbox eventId that started this run, for idempotency / debugging.\n triggerEventId String?\n /// Lifecycle: pending → running → (completed | cancelled | failed).\n /// `unsubscribed` is a terminal status set when the recipient opted out.\n status String @default(\"pending\")\n startedAt DateTime @default(now())\n completedAt DateTime?\n /// Free-form per-step state ({ lastStepIndex, lastScheduledAt, ... }).\n stepStateJson Json?\n\n sequence EmailSequence @relation(fields: [sequenceId], references: [id], onDelete: Cascade)\n deliveries EmailSequenceStepDelivery[]\n\n /// Prevent a duplicate run from the same outbox event-id.\n @@unique([sequenceId, triggerEventId])\n @@index([sequenceId, status])\n @@index([leadId])\n @@index([tenantId])\n @@index([startedAt(sort: Desc)])\n}\n\nmodel EmailSequenceStepDelivery {\n id String @id @default(cuid())\n runId String\n stepIndex Int\n /// `pending` (queued for send) | `sent` | `bounced` | `skipped` (condition\n /// false) | `failed` (transient error after retries).\n status String @default(\"pending\")\n scheduledAt DateTime\n sentAt DateTime?\n openedAt DateTime?\n clickedAt DateTime?\n bouncedAt DateTime?\n /// Mail-provider message-id for correlating webhooks.\n providerMessageId String?\n errorMessage String?\n\n run EmailSequenceRun @relation(fields: [runId], references: [id], onDelete: Cascade)\n\n @@unique([runId, stepIndex])\n @@index([status, scheduledAt])\n @@index([providerMessageId], name: \"email_sequence_step_delivery_provider_message_id_idx\")\n @@index([scheduledAt])\n}\n\n// P4 EntityLink (AK-P4b) — Gate W1 deliverable.\n//\n// AD-21: one self-contained schema file per module. `tenantId` /\n// `createdByUserId` are intentionally BARE String scalars (no `@relation`).\n//\n// Generic, fully polymorphic link between any two entities. Both sides\n// (source + target) are polymorphic so every later module docks onto this one\n// table instead of building its own link table. Reusable cross-cutting\n// primitive: R-P6 ff. attach Task<->CRM, File<->CRM (beyond FileEntityLink),\n// and any future relation here.\n//\n// Note: `FileEntityLink` (files.prisma) predates this table and stays as-is for\n// the file-specific upload flow; new generic links use `EntityLink`.\n\nenum LinkableEntityType {\n contact\n company\n lead\n deal\n project\n task\n file\n user\n order\n appointment\n form_submission\n}\n\n/// A directed, role-labelled link from one entity to another, scoped per tenant.\n/// Idempotent on the unique tuple (upsert in entityLinkService).\nmodel EntityLink {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n createdByUserId String\n sourceType LinkableEntityType\n sourceId String\n targetType LinkableEntityType\n targetId String\n linkRole String? // optional role label (e.g. \"depends-on\", \"reference\")\n\n @@unique([tenantId, sourceType, sourceId, targetType, targetId])\n @@index([tenantId, targetType, targetId])\n @@index([tenantId, sourceType, sourceId])\n}\n\nmodel FeatureFlag {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n key String?\n scope String @default(\"global\")\n tenantId String?\n userId String?\n name String\n description String\n enabled Boolean @default(false)\n // v2 targeting engine fields (task #53). All nullable / defaulted so\n // legacy rows continue to evaluate via boolean `enabled` only.\n rules Json?\n variants Json[] @default([])\n enabledFrom DateTime?\n enabledUntil DateTime?\n parentFlagId String?\n parentFlag FeatureFlag? @relation(\"FeatureFlagDependency\", fields: [parentFlagId], references: [id], onDelete: SetNull)\n childFlags FeatureFlag[] @relation(\"FeatureFlagDependency\")\n audits FeatureFlagAudit[]\n events AnalyticsEvent[]\n filters FeatureFlagFilter[]\n\n @@unique([name, description])\n @@index([key, scope], name: \"feature_flag_key_scope_idx\")\n @@index([tenantId, key], name: \"feature_flag_tenant_key_idx\")\n @@index([userId, key], name: \"feature_flag_user_key_idx\")\n @@index([parentFlagId], name: \"feature_flag_parent_idx\")\n}\n\nmodel FeatureFlagFilter {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n featureFlagId String\n featureFlag FeatureFlag @relation(fields: [featureFlagId], references: [id], onDelete: Cascade)\n type String // [FeatureFlagsFilterType] percentage, darkMode, language.is, page.is, analytics.browser.is...\n value String? // 0-100, true, false, en, de, fr, ...\n action String?\n}\n\n/// Append-only audit trail for every mutation of a FeatureFlag (create / update / delete / toggle).\n/// Never UPDATE or DELETE rows from app code — preserves tamper-resistance for compliance.\nmodel FeatureFlagAudit {\n id String @id @default(cuid())\n flagId String\n flag FeatureFlag @relation(fields: [flagId], references: [id], onDelete: Cascade)\n actorUserId String?\n action String // create | update | delete | toggle\n oldValue Json?\n newValue Json?\n createdAt DateTime @default(now())\n\n @@index([flagId, createdAt], name: \"feature_flag_audit_flag_idx\")\n @@index([actorUserId, createdAt], name: \"feature_flag_audit_actor_idx\")\n}\n\n// P4 Files (AK-P4a) — Files platform primitive.\n//\n// AD-21: one self-contained schema file per module. `tenantId` /\n// `createdByUserId` / `assignedToUserId` are intentionally BARE String scalars\n// (no `@relation`) so this file has zero merge-conflict surface against\n// `core.prisma`/`accounts.prisma` (no back-relation fields on Tenant/User\n// needed). Referential integrity is carried by app-level scoping\n// (withTenantScope, §7) plus the RLS policies from the merge migration (§8).\n//\n// Deliberately NOT reused: the legacy boilerplate models `FileObject`,\n// `FileChunk`, `FileUploadProgress` in core.prisma. The models here are named\n// differently (File, FileEntityLink, FileUpload, FileUploadChunk) to avoid a\n// name collision and any core edit.\n//\n// Scope v1 (designer brief 2026-06-12): NO versioning (FileVersion = v2),\n// no Office/Video previews, no resume upload, no OCR.\n\nenum FilePreviewStatus {\n pending\n generating\n ready\n failed\n not_supported\n}\n\nenum FileScanStatus {\n pending\n clean\n infected\n skipped\n}\n\nenum FileSource {\n manual_upload\n customer_portal\n form_submission\n email_attachment\n automation\n api\n}\n\nenum FileUploadStatus {\n in_progress\n completed\n failed\n expired\n cancelled\n}\n\nenum FileEntityType {\n contact\n company\n lead\n deal\n project\n user\n form_submission\n order\n task\n appointment\n signature_document\n // VA-P23 · mirrored mailbox message (email-inbox attachments -> Files).\n // ADDITIVE cross-module touch of files.prisma, flagged per AD-21.\n email_message\n}\n\n/// A stored file, scoped per tenant. `storageKey` points at the original object\n/// in the private Hetzner bucket (AD-23); delivery is only via the auth-proxy\n/// route. Soft-delete via `archivedAt` (archive flag). Hard-delete is a separate\n/// action (files.delete).\nmodel File {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n createdByUserId String\n displayName String\n mimeType String\n sizeBytes Int\n storageKey String\n checksumSha256 String?\n previewStatus FilePreviewStatus @default(pending)\n previewStorageKey String?\n thumbnailStorageKey String?\n scanStatus FileScanStatus @default(pending)\n assignedToUserId String?\n tags String[] @default([])\n notes String?\n source FileSource @default(manual_upload)\n // Customer-portal upload prepared (DoD 12): nullable attribution, full portal\n // flow = v2. Defaults to empty/invisible.\n createdByPortalUserId String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n links FileEntityLink[]\n\n @@index([tenantId, archivedAt, createdAt(sort: Desc)])\n @@index([tenantId, createdByUserId])\n @@index([tenantId, assignedToUserId])\n @@index([tenantId, checksumSha256])\n // pg_trgm GIN index for fast ILIKE search on displayName; created originally\n // via raw SQL in 20260623160000_p4a_files_platform. Modeled here so\n // migrations<->schema parity holds (requires the pg_trgm extension).\n @@index([displayName(ops: raw(\"gin_trgm_ops\"))], type: Gin, map: \"File_displayName_trgm_idx\")\n}\n\n/// Polymorphic link of a file to any entity (cross-cutting). `entityType` +\n/// `entityId` address the target entity, `linkRole` is an optional role label\n/// (e.g. \"contract\", \"photo\").\nmodel FileEntityLink {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n createdByUserId String\n fileId String\n entityType FileEntityType\n entityId String\n linkRole String?\n\n file File @relation(fields: [fileId], references: [id], onDelete: Cascade)\n\n @@unique([fileId, entityType, entityId])\n @@index([tenantId, entityType, entityId])\n @@index([tenantId, fileId])\n}\n\n/// Chunked-upload session (replaces spec `FileUploadProgress`, renamed to avoid\n/// the core collision). No resume in v1 — this session only carries progress up\n/// to `complete`. `expiresAt` = now + 24h; a cleanup cron sweeps expired\n/// sessions + temp chunks.\nmodel FileUpload {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n createdByUserId String\n originalFilename String\n totalSizeBytes Int\n mimeType String\n totalChunks Int\n receivedChunks Int @default(0)\n status FileUploadStatus @default(in_progress)\n targetFileId String?\n expiresAt DateTime\n failureReason String?\n\n chunks FileUploadChunk[]\n\n @@index([tenantId, createdByUserId, status])\n @@index([expiresAt])\n}\n\n/// One uploaded chunk of a `FileUpload` session (replaces spec `FileChunk`).\n/// Bytes live in temp storage (`storageKey`), not in the DB.\nmodel FileUploadChunk {\n id String @id @default(cuid())\n tenantId String\n uploadId String\n chunkIndex Int\n storageKey String\n sizeBytes Int\n checksumSha256 String?\n receivedAt DateTime @default(now())\n\n upload FileUpload @relation(fields: [uploadId], references: [id], onDelete: Cascade)\n\n @@unique([uploadId, chunkIndex])\n @@index([tenantId, uploadId])\n}\n\n// Embeddable Form-Widget (Phase 05 Task #58).\n//\n// `Form` is the tenant-authored definition + theme + delivery config that\n// powers the iframe-embedded mini-app. `FormSubmission` is the inbox for\n// payloads landing through the public submission endpoint. Both rows are\n// tenant-scoped so existing tenant-isolation tooling applies as-is.\n\nmodel Form {\n id String @id @default(cuid())\n tenantId String\n /// Public key used in the embed `