/* !!! 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 /// Stored normalized for new writes. A functional lower(trim(email))\n /// unique index in migration SQL also protects legacy mixed-case rows.\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 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 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\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 idempotencyKeys IdempotencyKey[]\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 workflows Workflow[]\n workflowExecutions WorkflowExecution[]\n workflowVariables WorkflowVariable[]\n workflowCredentials WorkflowCredential[]\n feedback Feedback[]\n supportTickets SupportTicket[]\n credits Credit[]\n checkoutSessions CheckoutSessionStatus[]\n productAcquisitions TenantProductAcquisition[]\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\n// Seat billing bucket / default UI mode. `office` = back-office / desk work,\n// `field` = on-site (Baustelle) work. Shared across the Prisma schema folder\n// (Role.seatCategory, TenantUser.seatType).\nenum SeatType {\n office\n field\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 // null = derived from the user's roles at read time (any office role => office\n // seat); an explicit value is an admin billing override.\n seatType SeatType?\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 /// One live pending invite per tenant and normalized email is enforced by a\n /// partial functional index in migration SQL. A second partial unique index\n /// protects every non-null token hash globally. Prisma cannot declare either.\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 selectedOfficeSeatQuantity Int?\n selectedFieldSeatQuantity Int?\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\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 append-only AuditEvent Querschnitt (tenantId=null,\n// actorType=\"admin\") β€” NOT a parallel audit table. All authors reference\n// the tenant-less AdminUser identity from adminIdentity.prisma.\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 AdminUser? @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 AdminUser? @relation(\"supportTicketMessageAuthor\", fields: [authorUserId], references: [id], onDelete: SetNull)\n\n @@index([supportTicketId, createdAt], name: \"support_ticket_message_ticket_created_idx\")\n}\n\n// VA-P28f: public booking and availability for HiveGrid's own sales team.\n//\n// These records never carry tenantId. Public requests first resolve a published\n// page through a narrow SECURITY DEFINER function and then bind app.user_id to\n// the page owner. Provider actions are performed by bounded worker contracts.\n\nenum AdminAvailabilityDay {\n monday\n tuesday\n wednesday\n thursday\n friday\n saturday\n sunday\n}\n\nenum AdminAvailabilityOverrideKind {\n unavailable\n custom_window\n}\n\nenum AdminBookingStatus {\n reserved\n confirmed\n cancelled\n rescheduled\n completed\n no_show\n provider_sync_failed\n}\n\nenum AdminBookingAssignmentKind {\n round_robin\n manual\n}\n\nenum AdminBookingReminderStatus {\n pending\n processing\n sent\n skipped\n failed\n cancelled\n}\n\nmodel AdminMeetingType {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n createdByAdminUserId String\n name String\n slug String @unique\n description String?\n durationMinutes Int\n bufferBeforeMinutes Int @default(0)\n bufferAfterMinutes Int @default(0)\n slotIncrementMinutes Int @default(15)\n minimumNoticeMinutes Int @default(240)\n bookingHorizonDays Int @default(60)\n hostAdminUserIds String[] @default([])\n intakeQuestions Json @default(\"[]\")\n reminderOffsetsMinutes Int[] @default([])\n active Boolean @default(true)\n\n pages AdminBookingPage[]\n bookings AdminBooking[]\n\n @@index([active, archivedAt, name], name: \"admin_meeting_type_active_idx\")\n @@index([createdByAdminUserId, archivedAt], name: \"admin_meeting_type_creator_idx\")\n}\n\nmodel AdminAvailabilityRule {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n dayOfWeek AdminAvailabilityDay\n startMinutes Int\n endMinutes Int\n timeZone String\n\n @@index([adminUserId, dayOfWeek, archivedAt], name: \"admin_availability_rule_owner_day_idx\")\n}\n\nmodel AdminAvailabilityOverride {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n date DateTime @db.Date\n kind AdminAvailabilityOverrideKind\n startMinutes Int?\n endMinutes Int?\n timeZone String\n reason String?\n\n @@index([adminUserId, date, archivedAt], name: \"admin_availability_override_owner_date_idx\")\n}\n\nmodel AdminBookingPage {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n createdByAdminUserId String\n meetingTypeId String\n slug String @unique\n title String\n description String?\n published Boolean @default(false)\n tokenVersion Int @default(1)\n allowedEmailDomains String[] @default([])\n maxBookingsPerEmailPerDay Int @default(3)\n\n meetingType AdminMeetingType @relation(fields: [meetingTypeId], references: [id], onDelete: Restrict)\n bookings AdminBooking[]\n\n @@index([createdByAdminUserId, published, archivedAt], name: \"admin_booking_page_creator_status_idx\")\n @@index([meetingTypeId, published, archivedAt], name: \"admin_booking_page_type_status_idx\")\n}\n\nmodel AdminBooking {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n bookingPageId String\n meetingTypeId String\n calendarConnectionId String?\n contactId String\n dealId String?\n startsAt DateTime\n endsAt DateTime\n bookerTimeZone String\n status AdminBookingStatus @default(reserved)\n idempotencyKey String @unique\n slotReservationKey String @unique\n providerEventId String?\n providerEventVersion String?\n providerSyncedAt DateTime?\n intakeAnswers Json @default(\"{}\")\n manageTokenVersion Int @default(1)\n manageTokenExpiresAt DateTime\n lastManageNonceHash String?\n confirmedAt DateTime?\n cancelledAt DateTime?\n cancellationReason String?\n rescheduledFromId String? @unique\n\n bookingPage AdminBookingPage @relation(fields: [bookingPageId], references: [id], onDelete: Restrict)\n meetingType AdminMeetingType @relation(fields: [meetingTypeId], references: [id], onDelete: Restrict)\n calendarConnection AdminCalendarConnection? @relation(fields: [calendarConnectionId], references: [id], onDelete: SetNull)\n contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Restrict)\n deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)\n rescheduledFrom AdminBooking? @relation(\"AdminBookingReschedule\", fields: [rescheduledFromId], references: [id], onDelete: SetNull)\n rescheduledTo AdminBooking? @relation(\"AdminBookingReschedule\")\n participants AdminBookingParticipant[]\n assignment AdminBookingAssignment?\n reminders AdminBookingReminder[]\n activities AdminActivity[]\n\n @@index([adminUserId, startsAt], name: \"admin_booking_owner_start_idx\")\n @@index([status, startsAt], name: \"admin_booking_status_start_idx\")\n @@index([contactId, startsAt(sort: Desc)], name: \"admin_booking_contact_start_idx\")\n @@index([dealId, startsAt(sort: Desc)], name: \"admin_booking_deal_start_idx\")\n @@index([bookingPageId, startsAt], name: \"admin_booking_page_start_idx\")\n}\n\nmodel AdminBookingParticipant {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n bookingId String\n email String\n name String\n locale String?\n timeZone String?\n isOrganizer Boolean @default(false)\n\n booking AdminBooking @relation(fields: [bookingId], references: [id], onDelete: Cascade)\n\n @@unique([bookingId, email], name: \"admin_booking_participant_email_key\")\n @@index([adminUserId, createdAt(sort: Desc)], name: \"admin_booking_participant_owner_idx\")\n}\n\nmodel AdminBookingAssignment {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n bookingId String @unique\n kind AdminBookingAssignmentKind\n selectedHostAdminUserId String\n previousHostAdminUserId String?\n overriddenByAdminUserId String?\n eligibleHostAdminUserIds String[]\n excludedHosts Json @default(\"[]\")\n loadSnapshot Json\n selectionReason String\n\n booking AdminBooking @relation(fields: [bookingId], references: [id], onDelete: Cascade)\n\n @@index([adminUserId, createdAt(sort: Desc)], name: \"admin_booking_assignment_owner_idx\")\n @@index([selectedHostAdminUserId, createdAt(sort: Desc)], name: \"admin_booking_assignment_host_idx\")\n}\n\nmodel AdminBookingReminder {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n bookingId String\n offsetMinutes Int\n scheduledFor DateTime\n status AdminBookingReminderStatus @default(pending)\n idempotencyKey String @unique\n attemptCount Int @default(0)\n sentAt DateTime?\n lastErrorCode String?\n\n booking AdminBooking @relation(fields: [bookingId], references: [id], onDelete: Cascade)\n\n @@unique([bookingId, offsetMinutes], name: \"admin_booking_reminder_offset_key\")\n @@index([status, scheduledFor], name: \"admin_booking_reminder_due_idx\")\n @@index([adminUserId, scheduledFor], name: \"admin_booking_reminder_owner_idx\")\n}\n\n// VA-P28f: personal calendars for HiveGrid's tenant-less admin sales workspace.\n//\n// OAuth credentials remain exclusively in AdminDataConnection. Calendar sync\n// stores provider cursors plus anonymous busy intervals; titles, descriptions\n// and attendee lists from unrelated external events are deliberately discarded.\n\nenum AdminCalendarConnectionStatus {\n active\n degraded\n reconnect_required\n revoked\n}\n\nenum AdminCalendarSyncStatus {\n pending\n syncing\n active\n recovery_required\n failed\n}\n\nmodel AdminCalendarConnection {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n dataConnectionId String @unique\n externalCalendarId String\n externalCalendarLabel String?\n timeZone String\n status AdminCalendarConnectionStatus @default(active)\n lastSyncAt DateTime?\n lastErrorCode String?\n healthMessageKey String?\n webhookExpiresAt DateTime?\n\n adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)\n dataConnection AdminDataConnection @relation(fields: [dataConnectionId], references: [id], onDelete: Restrict)\n syncCursors AdminCalendarSyncCursor[]\n bookings AdminBooking[]\n\n @@unique([adminUserId, externalCalendarId], name: \"admin_calendar_owner_external_key\")\n @@index([adminUserId, status, archivedAt], name: \"admin_calendar_owner_status_idx\")\n @@index([status, webhookExpiresAt], name: \"admin_calendar_webhook_renewal_idx\")\n}\n\nmodel AdminCalendarSyncCursor {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n calendarConnectionId String\n externalCalendarId String\n cursorToken String?\n deltaLink String?\n busyIntervals Json @default(\"[]\")\n status AdminCalendarSyncStatus @default(pending)\n lastFullSyncAt DateTime?\n lastIncrementalSyncAt DateTime?\n recoveryRequestedAt DateTime?\n lastErrorCode String?\n\n calendarConnection AdminCalendarConnection @relation(fields: [calendarConnectionId], references: [id], onDelete: Cascade)\n\n @@unique([calendarConnectionId, externalCalendarId], name: \"admin_calendar_cursor_external_key\")\n @@index([adminUserId, status, updatedAt], name: \"admin_calendar_cursor_owner_status_idx\")\n}\n\n// VA-P28c: provider-neutral connections for HiveGrid's own admin sales workspace.\n//\n// These rows are tenant-less and belong to one active AdminUser. Credentials\n// use a dedicated platform envelope key and never reuse a Tenant DEK or the\n// legacy CRYPTO_SECRET contract.\n\nenum AdminConnectionProvider {\n google_mail\n microsoft_mail\n aircall\n google_calendar\n microsoft_calendar\n slack\n linkedin\n meeting_webhook\n}\n\nenum AdminConnectionCapability {\n email\n telephony\n calendar\n team_chat\n professional_network\n meeting_artifact\n}\n\nenum AdminConnectionStatus {\n pending\n active\n degraded\n revoked\n}\n\nmodel AdminDataConnection {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n provider AdminConnectionProvider\n capability AdminConnectionCapability\n label String\n externalAccountId String?\n externalAccountEmail String?\n status AdminConnectionStatus @default(pending)\n scopes String[] @default([])\n tokenExpiresAt DateTime?\n lastHealthCheckAt DateTime?\n healthMessageKey String?\n webhookRegistrationId String?\n revokedAt DateTime?\n archivedAt DateTime?\n\n adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)\n credential AdminConnectionCredential?\n mailboxes AdminMailbox[]\n phoneConnection AdminPhoneConnection?\n calendarConnection AdminCalendarConnection?\n\n @@unique([adminUserId, provider, externalAccountId], name: \"admin_data_connection_account_key\")\n @@index([adminUserId, capability, archivedAt], name: \"admin_data_connection_owner_capability_idx\")\n @@index([provider, status, tokenExpiresAt], name: \"admin_data_connection_refresh_idx\")\n}\n\nmodel AdminConnectionCredential {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n connectionId String @unique\n adminUserId String\n wrappedDek Bytes\n ciphertext String\n keyVersion Int @default(1)\n rotatedAt DateTime?\n revokedAt DateTime?\n\n connection AdminDataConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)\n adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)\n\n @@index([adminUserId, revokedAt], name: \"admin_connection_credential_owner_revoked_idx\")\n}\n\n// VA-P28c: tenant-less email workspace for HiveGrid's own sales team.\n//\n// Every row is owned by an active AdminUser. Worker-readable rows repeat the\n// owner id deliberately so Postgres RLS can enforce the boundary without a\n// tenant context or an unreviewable join chain.\n\nenum AdminMailboxStatus {\n connecting\n active\n degraded\n revoked\n}\n\nenum AdminMailboxSyncStatus {\n pending\n running\n complete\n failed\n}\n\nenum AdminEmailDirection {\n inbound\n outbound\n}\n\nenum AdminEmailMatchStatus {\n matched\n ambiguous\n unmatched\n manual\n}\n\nenum AdminEmailEventType {\n queued\n sent\n delivered\n bounced\n opened\n clicked\n replied\n}\n\nenum AdminScheduledEmailStatus {\n draft\n blocked\n queued\n sending\n sent\n cancelled\n failed\n}\n\nenum AdminNoReplyReminderStatus {\n pending\n fired\n dismissed\n cancelled\n}\n\nenum AdminBulkEmailRunStatus {\n draft\n blocked\n queued\n running\n complete\n cancelled\n failed\n}\n\nenum AdminSendingDomainStatus {\n pending\n verified\n degraded\n revoked\n}\n\nmodel AdminMailbox {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n connectionId String @unique\n emailAddress String\n normalizedEmail String\n displayName String?\n providerAccountId String\n status AdminMailboxStatus @default(connecting)\n lastSyncAt DateTime?\n lastRecoveryPollAt DateTime?\n webhookExpiresAt DateTime?\n lastErrorMessageKey String?\n\n adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)\n connection AdminDataConnection @relation(fields: [connectionId], references: [id], onDelete: Restrict)\n syncCursors AdminMailboxSyncCursor[]\n webhookEvents AdminMailboxWebhookEvent[]\n threads AdminEmailThread[]\n messages AdminEmailMessage[]\n scheduled AdminScheduledEmail[]\n bulkRuns AdminBulkEmailRun[]\n bccAddresses AdminBccAddress[]\n\n @@unique([adminUserId, normalizedEmail], name: \"admin_mailbox_owner_email_key\")\n @@index([adminUserId, status, archivedAt], name: \"admin_mailbox_owner_status_idx\")\n @@index([status, lastSyncAt], name: \"admin_mailbox_recovery_poll_idx\")\n}\n\nmodel AdminMailboxSyncCursor {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n mailboxId String\n externalFolderId String\n cursorToken String?\n syncStatus AdminMailboxSyncStatus @default(pending)\n recoveryGeneration Int @default(0)\n lastAttemptAt DateTime?\n lastSuccessAt DateTime?\n lastErrorMessageKey String?\n\n mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)\n\n @@unique([mailboxId, externalFolderId], name: \"admin_mailbox_cursor_folder_key\")\n @@index([adminUserId, syncStatus, lastAttemptAt], name: \"admin_mailbox_cursor_owner_status_idx\")\n}\n\nmodel AdminMailboxWebhookEvent {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n processedAt DateTime?\n failedAt DateTime?\n adminUserId String\n mailboxId String\n providerEventId String\n idempotencyKey String @unique\n payload Json\n lastErrorMessageKey String?\n\n mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)\n\n @@unique([mailboxId, providerEventId], name: \"admin_mailbox_webhook_provider_event_key\")\n @@index([adminUserId, processedAt, createdAt], name: \"admin_mailbox_webhook_pending_idx\")\n}\n\nmodel AdminEmailThread {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n mailboxId String\n providerThreadId String\n normalizedSubject String?\n latestMessageAt DateTime\n messageCount Int @default(0)\n unreadCount Int @default(0)\n\n mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)\n messages AdminEmailMessage[]\n scheduled AdminScheduledEmail[]\n\n @@unique([mailboxId, providerThreadId], name: \"admin_email_thread_provider_key\")\n @@index([adminUserId, latestMessageAt(sort: Desc)], name: \"admin_email_thread_owner_latest_idx\")\n}\n\nmodel AdminEmailMessage {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n mailboxId String\n threadId String\n providerMessageId String\n internetMessageId String?\n direction AdminEmailDirection\n fromAddress String\n subject String?\n snippet String?\n bodyHtml String?\n bodyText String?\n sentAt DateTime\n receivedAt DateTime?\n isRead Boolean @default(false)\n isNewsletter Boolean @default(false)\n providerLabels String[] @default([])\n matchStatus AdminEmailMatchStatus @default(unmatched)\n matchedContactId String?\n matchedLeadId String?\n matchedDealId String?\n matchedAt DateTime?\n matchedByAdminUserId String?\n matchingReason String?\n matchingCandidates Json?\n\n mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)\n thread AdminEmailThread @relation(fields: [threadId], references: [id], onDelete: Cascade)\n matchedContact AdminContact? @relation(fields: [matchedContactId], references: [id], onDelete: SetNull)\n matchedLead AdminLead? @relation(fields: [matchedLeadId], references: [id], onDelete: SetNull)\n matchedDeal AdminDeal? @relation(fields: [matchedDealId], references: [id], onDelete: SetNull)\n participants AdminEmailParticipant[]\n attachments AdminEmailAttachment[]\n events AdminEmailEvent[]\n links AdminEmailLink[]\n activities AdminActivity[]\n reminders AdminNoReplyReminder[]\n\n @@unique([mailboxId, providerMessageId], name: \"admin_email_message_provider_key\")\n @@index([mailboxId, internetMessageId], name: \"admin_email_message_rfc_id_idx\")\n @@index([adminUserId, matchStatus, receivedAt(sort: Desc)], name: \"admin_email_message_match_queue_idx\")\n @@index([matchedContactId, sentAt(sort: Desc)], name: \"admin_email_message_contact_time_idx\")\n @@index([matchedLeadId, sentAt(sort: Desc)], name: \"admin_email_message_lead_time_idx\")\n @@index([matchedDealId, sentAt(sort: Desc)], name: \"admin_email_message_deal_time_idx\")\n}\n\nmodel AdminEmailParticipant {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n messageId String\n kind String\n emailAddress String\n displayName String?\n\n message AdminEmailMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)\n\n @@unique([messageId, kind, emailAddress], name: \"admin_email_participant_message_kind_address_key\")\n @@index([adminUserId, emailAddress], name: \"admin_email_participant_owner_address_idx\")\n}\n\nmodel AdminEmailAttachment {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n messageId String\n providerAttachmentId String?\n filename String\n mimeType String?\n sizeBytes Int\n storageBucket String\n storageKey String\n checksumSha256 String\n scannedAt DateTime\n linkedDealId String?\n\n message AdminEmailMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)\n\n @@unique([messageId, checksumSha256], name: \"admin_email_attachment_message_checksum_key\")\n @@index([adminUserId, linkedDealId, createdAt], name: \"admin_email_attachment_owner_deal_idx\")\n}\n\nmodel AdminEmailEvent {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n messageId String\n type AdminEmailEventType\n providerEventId String?\n recipient String?\n linkId String?\n occurredAt DateTime\n rawExpiresAt DateTime?\n metadata Json?\n\n message AdminEmailMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)\n link AdminEmailLink? @relation(fields: [linkId], references: [id], onDelete: SetNull)\n\n @@unique([messageId, type, providerEventId], name: \"admin_email_event_provider_key\")\n @@index([adminUserId, type, occurredAt(sort: Desc)], name: \"admin_email_event_owner_type_idx\")\n @@index([rawExpiresAt], name: \"admin_email_event_retention_idx\")\n}\n\nmodel AdminEmailLink {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n messageId String\n destinationUrl String\n trackingTokenHash String @unique\n\n message AdminEmailMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)\n events AdminEmailEvent[]\n\n @@index([adminUserId, messageId], name: \"admin_email_link_owner_message_idx\")\n}\n\nmodel AdminEmailTemplate {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n name String\n subjectTemplate String\n htmlTemplate String\n textTemplate String?\n allowedPlaceholders String[] @default([])\n version Int @default(1)\n\n @@unique([adminUserId, name, version], name: \"admin_email_template_owner_name_version_key\")\n @@index([adminUserId, archivedAt, name], name: \"admin_email_template_owner_archive_idx\")\n}\n\nmodel AdminEmailSnippet {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n shortcut String\n title String\n content String\n\n @@unique([adminUserId, shortcut], name: \"admin_email_snippet_owner_shortcut_key\")\n @@index([adminUserId, archivedAt, title], name: \"admin_email_snippet_owner_archive_idx\")\n}\n\nmodel AdminEmailSignature {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String @unique\n html String\n text String?\n\n @@index([adminUserId, updatedAt], name: \"admin_email_signature_owner_updated_idx\")\n}\n\nmodel AdminEmailOutboundPolicy {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String @unique\n timeZone String\n workdayStartMinutes Int\n workdayEndMinutes Int\n allowedWeekDays Int[] @default([])\n dailySendLimit Int\n bulkDailySendLimit Int\n consentRulesConfigured Boolean @default(false)\n trackingEnabled Boolean @default(false)\n liveOpenEnabled Boolean @default(false)\n trackingRetentionDays Int @default(180)\n configuredAt DateTime?\n\n @@index([adminUserId, configuredAt], name: \"admin_email_outbound_policy_owner_config_idx\")\n}\n\nmodel AdminScheduledEmail {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n mailboxId String\n contactId String?\n leadId String?\n dealId String?\n threadId String?\n bulkRunId String?\n toAddresses String[]\n ccAddresses String[] @default([])\n bccAddresses String[] @default([])\n subject String\n bodyHtml String\n bodyText String?\n scheduledFor DateTime\n timeZone String\n noReplyAfterDays Int?\n status AdminScheduledEmailStatus @default(draft)\n idempotencyKey String @unique\n claimedAt DateTime?\n sentAt DateTime?\n sendAttemptCount Int @default(0)\n providerMessageId String?\n sentMessageId String?\n lastErrorMessageKey String?\n\n mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Restrict)\n thread AdminEmailThread? @relation(fields: [threadId], references: [id], onDelete: SetNull)\n bulkRun AdminBulkEmailRun? @relation(fields: [bulkRunId], references: [id], onDelete: SetNull)\n\n @@index([adminUserId, status, scheduledFor], name: \"admin_scheduled_email_due_idx\")\n @@index([dealId, scheduledFor], name: \"admin_scheduled_email_deal_idx\")\n @@index([bulkRunId, status], name: \"admin_scheduled_email_bulk_status_idx\")\n}\n\nmodel AdminNoReplyReminder {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n outboundMessageId String\n dueAt DateTime\n status AdminNoReplyReminderStatus @default(pending)\n taskId String?\n idempotencyKey String @unique\n\n outboundMessage AdminEmailMessage @relation(fields: [outboundMessageId], references: [id], onDelete: Cascade)\n\n @@index([adminUserId, status, dueAt], name: \"admin_no_reply_reminder_due_idx\")\n}\n\nmodel AdminBulkEmailRun {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n mailboxId String\n name String\n selectedContactIds String[] @default([])\n templateId String?\n status AdminBulkEmailRunStatus @default(draft)\n scheduledFor DateTime?\n timeZone String\n recipientCount Int @default(0)\n sentCount Int @default(0)\n failedCount Int @default(0)\n idempotencyKey String @unique\n lastErrorMessageKey String?\n\n mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Restrict)\n scheduled AdminScheduledEmail[]\n\n @@index([adminUserId, status, scheduledFor], name: \"admin_bulk_email_run_due_idx\")\n}\n\nmodel AdminSendingDomain {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n domain String @unique\n spfRecordName String\n spfExpectedValue String\n dkimRecordName String\n dkimExpectedValue String\n status AdminSendingDomainStatus @default(pending)\n spfStatus String\n dkimStatus String\n lastCheckedAt DateTime?\n lastErrorMessageKey String?\n\n @@index([adminUserId, status, archivedAt], name: \"admin_sending_domain_owner_status_idx\")\n}\n\nmodel AdminBccAddress {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n mailboxId String\n localPartHash String @unique\n displayAddress String\n rotatedAt DateTime?\n\n mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)\n\n @@index([adminUserId, archivedAt], name: \"admin_bcc_address_owner_archive_idx\")\n}\n\n// VR-P28a / M038-M039: platform operator identity and authorization.\n//\n// These models are deliberately tenant-less. Authentik is the only productive\n// login authority; HiveGrid stores the resulting operator identity, session,\n// role grants and MFA assurance. The local development fallback may provision\n// an AdminUser without an Authentik subject only behind the fail-closed guards\n// documented in AGENTS.md.\n\nenum AdminUserStatus {\n active\n disabled\n locked\n}\n\nmodel AdminUser {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n email String @unique\n firstName String\n lastName String\n avatar String?\n locale String?\n status AdminUserStatus @default(active)\n authentikSubject String? @unique\n authentikGroups String[] @default([])\n lastSsoLoginAt DateTime?\n lastLoginIpHash String?\n disabledAt DateTime?\n disabledReason String?\n\n sessions AdminSession[]\n roles AdminUserRole[]\n dataConnections AdminDataConnection[]\n connectionCredentials AdminConnectionCredential[]\n mailboxes AdminMailbox[]\n phoneConnections AdminPhoneConnection[]\n calendarConnections AdminCalendarConnection[]\n notificationDeliveries NotificationDelivery[]\n supportTicketMessages SupportTicketMessage[] @relation(\"supportTicketMessageAuthor\")\n adminTenantNotesAuthored AdminTenantNote[] @relation(\"adminTenantNoteAuthor\")\n\n @@index([status, email], name: \"admin_user_status_email_idx\")\n @@index([lastSsoLoginAt(sort: Desc)], name: \"admin_user_last_sso_login_idx\")\n}\n\nmodel AdminSession {\n id String @id @default(cuid())\n adminUserId String\n tokenHash String @unique\n createdAt DateTime @default(now())\n lastSeenAt DateTime @default(now())\n expiresAt DateTime\n revokedAt DateTime?\n ipHash String?\n userAgent String?\n approxLocation String?\n authenticationMethods String[] @default([])\n mfaAssuredAt DateTime?\n\n adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Cascade)\n\n @@index([adminUserId, revokedAt], name: \"admin_session_user_revoked_idx\")\n @@index([expiresAt], name: \"admin_session_expiry_idx\")\n}\n\nmodel AdminRole {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n name String @unique\n description String\n systemKey String? @unique\n isSystem Boolean @default(false)\n active Boolean @default(true)\n\n permissions AdminRolePermission[]\n users AdminUserRole[]\n\n @@index([active, name], name: \"admin_role_active_name_idx\")\n}\n\nmodel AdminPermission {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n name String @unique\n description String\n\n roles AdminRolePermission[]\n}\n\nmodel AdminRolePermission {\n adminRoleId String\n adminPermissionId String\n createdAt DateTime @default(now())\n\n role AdminRole @relation(fields: [adminRoleId], references: [id], onDelete: Cascade)\n permission AdminPermission @relation(fields: [adminPermissionId], references: [id], onDelete: Cascade)\n\n @@id([adminRoleId, adminPermissionId])\n @@index([adminPermissionId], name: \"admin_role_permission_permission_idx\")\n}\n\nmodel AdminUserRole {\n adminUserId String\n adminRoleId String\n createdAt DateTime @default(now())\n grantedByAdminUserId String?\n\n user AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Cascade)\n role AdminRole @relation(fields: [adminRoleId], references: [id], onDelete: Cascade)\n\n @@id([adminUserId, adminRoleId])\n @@index([adminRoleId], name: \"admin_user_role_role_idx\")\n}\n\n// R-LEADS / M040a - HiveGrid's operator-wide sales lead intake.\n//\n// Platform leads deliberately carry no tenantId. They are isolated by the\n// platform-admin RLS contract and are visible only to authenticated operators.\n// Anonymous S2S intake uses a reviewed SECURITY DEFINER capability; the API\n// runtime role never receives direct table access outside those policies.\n\nenum AdminLeadStatus {\n new\n contacted\n qualified\n disqualified\n}\n\nenum AdminLeadActivityType {\n captured\n imported\n manually_created\n status_changed\n assigned\n note_added\n archived\n restored\n duplicate_hint_recorded\n legacy_event\n}\n\nmodel AdminLeadSource {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n key String @unique\n displayName String\n enabled Boolean @default(true)\n defaultAssigneeAdminUserId String?\n notifyAdminUserIds String[] @default([])\n rateLimitPerMinute Int @default(60)\n metadata Json?\n\n leads AdminLead[]\n credentials AdminLeadSourceCredential[]\n\n @@index([enabled, displayName], name: \"admin_lead_source_enabled_display_name_idx\")\n @@index([defaultAssigneeAdminUserId], name: \"admin_lead_source_default_assignee_idx\")\n}\n\n/// Rotatable source credential. Only a one-way digest is persisted; the raw\n/// bearer value is returned once by the source administration service.\nmodel AdminLeadSourceCredential {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n sourceId String\n keyHash String @unique\n keyPrefix String\n expiresAt DateTime?\n revokedAt DateTime?\n lastUsedAt DateTime?\n\n source AdminLeadSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)\n\n @@index([sourceId, revokedAt, expiresAt], name: \"admin_lead_source_credential_active_idx\")\n @@index([sourceId, keyPrefix], name: \"admin_lead_source_credential_prefix_idx\")\n}\n\nmodel AdminLead {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n capturedAt DateTime @default(now())\n archivedAt DateTime?\n sourceId String\n sourceDetail String?\n externalId String?\n idempotencyKey String?\n firstName String?\n lastName String?\n email String?\n normalizedEmail String?\n phone String?\n normalizedPhone String?\n company String?\n message String?\n utmSource String?\n utmMedium String?\n utmCampaign String?\n utmTerm String?\n utmContent String?\n referrer String?\n landingPage String?\n status AdminLeadStatus @default(new)\n assignedToAdminUserId String?\n duplicateHintOfLeadId String?\n metadata Json?\n\n source AdminLeadSource @relation(fields: [sourceId], references: [id], onDelete: Restrict)\n activities AdminLeadActivity[]\n duplicateHint AdminLead? @relation(\"AdminLeadDuplicateHint\", fields: [duplicateHintOfLeadId], references: [id], onDelete: SetNull)\n duplicates AdminLead[] @relation(\"AdminLeadDuplicateHint\")\n convertedCompany AdminCompany? @relation(\"AdminLeadConvertedCompany\")\n convertedContact AdminContact? @relation(\"AdminLeadConvertedContact\")\n convertedDeal AdminDeal? @relation(\"AdminLeadConvertedDeal\")\n salesActivities AdminActivity[]\n qualification AdminLeadQualification?\n duplicateCandidatesPrimary AdminDuplicateCandidate[] @relation(\"AdminDuplicatePrimaryLead\")\n duplicateCandidatesSecondary AdminDuplicateCandidate[] @relation(\"AdminDuplicateSecondaryLead\")\n mergeRecordsSurvived AdminMergeRecord[] @relation(\"AdminMergeSurvivorLead\")\n mergeRecordMerged AdminMergeRecord? @relation(\"AdminMergeMergedLead\")\n emailMessages AdminEmailMessage[]\n callSessions AdminCallSession[]\n callMatchCandidates AdminCallMatchCandidate[]\n\n @@unique([sourceId, externalId], name: \"admin_lead_source_external_id_key\")\n @@unique([sourceId, idempotencyKey], name: \"admin_lead_source_idempotency_key\")\n @@index([status, archivedAt, capturedAt(sort: Desc)], name: \"admin_lead_status_archive_captured_idx\")\n @@index([sourceId, capturedAt(sort: Desc)], name: \"admin_lead_source_captured_idx\")\n @@index([assignedToAdminUserId, status, capturedAt(sort: Desc)], name: \"admin_lead_assignee_status_captured_idx\")\n @@index([normalizedEmail], name: \"admin_lead_normalized_email_idx\")\n @@index([normalizedPhone], name: \"admin_lead_normalized_phone_idx\")\n @@index([duplicateHintOfLeadId], name: \"admin_lead_duplicate_hint_idx\")\n}\n\n/// Append-only business timeline. Notes are activities rather than a mutable\n/// blob on AdminLead so every operator-visible change remains attributable.\nmodel AdminLeadActivity {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n leadId String\n type AdminLeadActivityType\n actorAdminUserId String?\n payload Json\n\n lead AdminLead @relation(fields: [leadId], references: [id], onDelete: Cascade)\n\n @@index([leadId, createdAt(sort: Desc)], name: \"admin_lead_activity_lead_created_idx\")\n @@index([type, createdAt(sort: Desc)], name: \"admin_lead_activity_type_created_idx\")\n @@index([actorAdminUserId, createdAt(sort: Desc)], name: \"admin_lead_activity_actor_created_idx\")\n}\n\n// VA-P28b / M040b: tenant-less platform sales workspace.\n//\n// These records belong to HiveGrid's own sales operation. They never carry a\n// tenantId and are protected by the platform-admin RLS contract. A won deal may\n// later reference a Tenant explicitly, but that does not turn sales data into\n// tenant-owned CRM data.\n\nenum AdminContactChannelKind {\n email\n phone\n linkedin\n website\n other\n}\n\nenum AdminPipelineStageKind {\n open\n won\n lost\n}\n\nenum AdminDealStatus {\n open\n won\n lost\n}\n\nenum AdminActivityType {\n configuration_changed\n data_job_requested\n data_job_updated\n company_created\n company_updated\n contact_created\n contact_updated\n note_added\n lead_updated\n lead_converted\n lead_assigned\n lead_scored\n lead_enriched\n lead_merged\n deal_created\n deal_updated\n deal_stage_changed\n deal_won\n deal_lost\n task_created\n task_completed\n email\n call\n meeting\n sequence\n quote\n signature\n tenant_linked\n}\n\nenum AdminLeadAssignmentStrategy {\n fixed\n round_robin\n}\n\nenum AdminLeadRuleOperator {\n equals\n not_equals\n contains\n present\n}\n\nenum AdminLeadScoreField {\n source\n region\n country\n company\n has_email\n has_phone\n}\n\nenum AdminDuplicateCandidateStatus {\n open\n dismissed\n merged\n}\n\nenum AdminLeadEnrichmentStatus {\n pending\n complete\n unavailable\n failed\n}\n\nenum AdminTaskPriority {\n low\n normal\n high\n urgent\n}\n\nenum AdminTaskStatus {\n open\n completed\n cancelled\n}\n\nenum AdminTaskSource {\n manual\n email\n call\n}\n\nenum AdminTaskRecurrenceFrequency {\n daily\n weekly\n monthly\n}\n\nenum AdminSalesCustomFieldTarget {\n contact\n deal\n}\n\nenum AdminSalesCustomFieldType {\n text\n number\n boolean\n date\n single_select\n}\n\nenum AdminSalesDataJobStatus {\n pending\n running\n completed\n completed_with_errors\n failed\n}\n\nmodel AdminCompany {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n name String\n normalizedName String\n legalName String?\n domain String?\n website String?\n phone String?\n normalizedPhone String?\n region String?\n countryCode String?\n industry String?\n employeeRange String?\n ownerAdminUserId String?\n sourceLeadId String? @unique\n enrichmentMetadata Json?\n\n sourceLead AdminLead? @relation(\"AdminLeadConvertedCompany\", fields: [sourceLeadId], references: [id], onDelete: SetNull)\n contacts AdminContact[]\n deals AdminDeal[]\n activities AdminActivity[]\n\n @@index([normalizedName, archivedAt], name: \"admin_company_name_archive_idx\")\n @@index([domain, archivedAt], name: \"admin_company_domain_archive_idx\")\n @@index([ownerAdminUserId, archivedAt], name: \"admin_company_owner_archive_idx\")\n}\n\nmodel AdminContact {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n companyId String?\n firstName String\n lastName String\n jobTitle String?\n email String?\n normalizedEmail String?\n phone String?\n normalizedPhone String?\n locale String?\n timeZone String?\n ownerAdminUserId String?\n sourceLeadId String? @unique\n enrichmentMetadata Json?\n\n sourceLead AdminLead? @relation(\"AdminLeadConvertedContact\", fields: [sourceLeadId], references: [id], onDelete: SetNull)\n company AdminCompany? @relation(fields: [companyId], references: [id], onDelete: SetNull)\n channels AdminContactChannel[]\n deals AdminDealContact[]\n tasks AdminTask[]\n tags AdminContactTag[]\n customFieldValues AdminCustomFieldValue[]\n notes AdminContactNote[]\n activities AdminActivity[]\n emailMessages AdminEmailMessage[]\n callSessions AdminCallSession[]\n callMatchCandidates AdminCallMatchCandidate[]\n dialerEntries AdminDialerEntry[]\n outboundCallRequests AdminOutboundCallRequest[]\n bookings AdminBooking[]\n doNotCall Boolean @default(false)\n doNotCallReason String?\n doNotCallAt DateTime?\n\n @@index([companyId, archivedAt, lastName, firstName], name: \"admin_contact_company_name_idx\")\n @@index([normalizedEmail, archivedAt], name: \"admin_contact_email_archive_idx\")\n @@index([normalizedPhone, archivedAt], name: \"admin_contact_phone_archive_idx\")\n @@index([ownerAdminUserId, archivedAt], name: \"admin_contact_owner_archive_idx\")\n}\n\nmodel AdminContactChannel {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n contactId String\n kind AdminContactChannelKind\n label String?\n value String\n normalizedValue String?\n isPrimary Boolean @default(false)\n\n contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Cascade)\n\n @@unique([contactId, kind, normalizedValue], name: \"admin_contact_channel_normalized_key\")\n @@index([kind, normalizedValue, archivedAt], name: \"admin_contact_channel_lookup_idx\")\n @@index([contactId, isPrimary, archivedAt], name: \"admin_contact_channel_primary_idx\")\n}\n\nmodel AdminPipeline {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n name String\n description String?\n isDefault Boolean @default(false)\n\n stages AdminPipelineStage[]\n deals AdminDeal[]\n lossReasons AdminDealLossReason[]\n activities AdminActivity[]\n\n @@index([archivedAt, name], name: \"admin_pipeline_archive_name_idx\")\n @@index([isDefault, archivedAt], name: \"admin_pipeline_default_idx\")\n}\n\nmodel AdminPipelineStage {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n pipelineId String\n name String\n position Int\n kind AdminPipelineStageKind @default(open)\n probabilityBasisPoints Int\n agingThresholdDays Int?\n color String?\n\n pipeline AdminPipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)\n deals AdminDeal[]\n requiredFields AdminStageRequiredField[]\n historyFrom AdminDealStageHistory[] @relation(\"AdminDealStageHistoryFrom\")\n historyTo AdminDealStageHistory[] @relation(\"AdminDealStageHistoryTo\")\n\n @@unique([pipelineId, position], name: \"admin_pipeline_stage_position_key\")\n @@unique([pipelineId, name], name: \"admin_pipeline_stage_name_key\")\n @@index([pipelineId, kind, archivedAt], name: \"admin_pipeline_stage_kind_idx\")\n}\n\nmodel AdminStageRequiredField {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n stageId String\n fieldKey String\n\n stage AdminPipelineStage @relation(fields: [stageId], references: [id], onDelete: Cascade)\n\n @@unique([stageId, fieldKey], name: \"admin_stage_required_field_key\")\n}\n\nmodel AdminDealLossReason {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n pipelineId String\n label String\n position Int\n\n pipeline AdminPipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)\n deals AdminDeal[]\n\n @@unique([pipelineId, label], name: \"admin_deal_loss_reason_label_key\")\n @@unique([pipelineId, position], name: \"admin_deal_loss_reason_position_key\")\n}\n\nmodel AdminDeal {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n title String\n pipelineId String\n stageId String\n companyId String?\n sourceLeadId String? @unique\n ownerAdminUserId String\n status AdminDealStatus @default(open)\n amountCents Int?\n currencyCode String @default(\"EUR\")\n probabilityBasisPoints Int\n expectedCloseDate DateTime?\n nextStep String?\n nextStepDueAt DateTime?\n stageEnteredAt DateTime @default(now())\n wonAt DateTime?\n lostAt DateTime?\n lossReasonId String?\n lossReasonNote String?\n promotedTenantId String?\n promotedAt DateTime?\n\n sourceLead AdminLead? @relation(\"AdminLeadConvertedDeal\", fields: [sourceLeadId], references: [id], onDelete: SetNull)\n pipeline AdminPipeline @relation(fields: [pipelineId], references: [id], onDelete: Restrict)\n stage AdminPipelineStage @relation(fields: [stageId], references: [id], onDelete: Restrict)\n company AdminCompany? @relation(fields: [companyId], references: [id], onDelete: SetNull)\n lossReason AdminDealLossReason? @relation(fields: [lossReasonId], references: [id], onDelete: SetNull)\n contacts AdminDealContact[]\n history AdminDealStageHistory[]\n tasks AdminTask[]\n customFieldValues AdminCustomFieldValue[]\n activities AdminActivity[]\n emailMessages AdminEmailMessage[]\n callSessions AdminCallSession[]\n outboundCallRequests AdminOutboundCallRequest[]\n bookings AdminBooking[]\n\n @@index([pipelineId, stageId, stageEnteredAt], name: \"admin_deal_pipeline_stage_age_idx\")\n @@index([ownerAdminUserId, status, expectedCloseDate], name: \"admin_deal_owner_status_close_idx\")\n @@index([companyId, status], name: \"admin_deal_company_status_idx\")\n @@index([promotedTenantId], name: \"admin_deal_promoted_tenant_idx\")\n}\n\nmodel AdminDealContact {\n dealId String\n contactId String\n createdAt DateTime @default(now())\n role String?\n isPrimary Boolean @default(false)\n\n deal AdminDeal @relation(fields: [dealId], references: [id], onDelete: Cascade)\n contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Cascade)\n\n @@id([dealId, contactId])\n @@index([contactId, createdAt], name: \"admin_deal_contact_contact_idx\")\n @@index([dealId, isPrimary], name: \"admin_deal_contact_primary_idx\")\n}\n\n/// Immutable record of every deal stage transition. The first history row has\n/// no fromStageId and represents entry into the pipeline.\nmodel AdminDealStageHistory {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n dealId String\n fromStageId String?\n toStageId String\n actorAdminUserId String\n enteredAt DateTime\n exitedAt DateTime?\n reason String?\n\n deal AdminDeal @relation(fields: [dealId], references: [id], onDelete: Cascade)\n fromStage AdminPipelineStage? @relation(\"AdminDealStageHistoryFrom\", fields: [fromStageId], references: [id], onDelete: Restrict)\n toStage AdminPipelineStage @relation(\"AdminDealStageHistoryTo\", fields: [toStageId], references: [id], onDelete: Restrict)\n\n @@index([dealId, enteredAt(sort: Desc)], name: \"admin_deal_stage_history_deal_time_idx\")\n @@index([toStageId, enteredAt], name: \"admin_deal_stage_history_stage_time_idx\")\n @@index([actorAdminUserId, enteredAt(sort: Desc)], name: \"admin_deal_stage_history_actor_time_idx\")\n}\n\nmodel AdminTaskRecurrence {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n createdByAdminUserId String\n frequency AdminTaskRecurrenceFrequency\n interval Int @default(1)\n timeZone String\n weekDays Int[] @default([])\n dayOfMonth Int?\n reminderOffsetMinutes Int?\n endsAt DateTime?\n\n tasks AdminTask[]\n\n @@index([archivedAt, frequency, endsAt], name: \"admin_task_recurrence_active_idx\")\n @@index([createdByAdminUserId, archivedAt], name: \"admin_task_recurrence_creator_idx\")\n}\n\nmodel AdminTask {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n title String\n description String?\n contactId String?\n dealId String?\n assignedToAdminUserId String\n createdByAdminUserId String\n dueAt DateTime\n timeZone String\n reminderAt DateTime?\n reminderSentAt DateTime?\n priority AdminTaskPriority @default(normal)\n status AdminTaskStatus @default(open)\n completedAt DateTime?\n source AdminTaskSource @default(manual)\n sourceActivityId String? @unique\n recurrenceId String?\n recurrenceSequence Int @default(0)\n\n contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: SetNull)\n deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)\n recurrence AdminTaskRecurrence? @relation(fields: [recurrenceId], references: [id], onDelete: Restrict)\n sourceActivity AdminActivity? @relation(\"AdminTaskSourceActivity\", fields: [sourceActivityId], references: [id], onDelete: SetNull)\n activities AdminActivity[] @relation(\"AdminActivityTask\")\n callbackCall AdminCallSession?\n\n @@unique([recurrenceId, recurrenceSequence], name: \"admin_task_recurrence_sequence_key\")\n @@index([assignedToAdminUserId, status, dueAt], name: \"admin_task_owner_status_due_idx\")\n @@index([status, reminderAt, reminderSentAt], name: \"admin_task_reminder_due_idx\")\n @@index([contactId, status, dueAt], name: \"admin_task_contact_due_idx\")\n @@index([dealId, status, dueAt], name: \"admin_task_deal_due_idx\")\n}\n\nmodel AdminTag {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n name String\n normalizedName String @unique\n color String?\n createdByAdminUserId String\n\n contacts AdminContactTag[]\n\n @@index([archivedAt, name], name: \"admin_tag_archive_name_idx\")\n}\n\nmodel AdminContactTag {\n contactId String\n tagId String\n createdAt DateTime @default(now())\n createdByAdminUserId String\n\n contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Cascade)\n tag AdminTag @relation(fields: [tagId], references: [id], onDelete: Restrict)\n\n @@id([contactId, tagId])\n @@index([tagId, createdAt], name: \"admin_contact_tag_tag_time_idx\")\n}\n\nmodel AdminCustomFieldDefinition {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n target AdminSalesCustomFieldTarget\n key String\n label String\n type AdminSalesCustomFieldType\n options String[] @default([])\n required Boolean @default(false)\n position Int\n createdByAdminUserId String\n\n values AdminCustomFieldValue[]\n\n @@unique([target, key], name: \"admin_custom_field_target_key\")\n @@unique([target, position], name: \"admin_custom_field_target_position\")\n @@index([target, archivedAt, position], name: \"admin_custom_field_target_active_idx\")\n}\n\nmodel AdminCustomFieldValue {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n definitionId String\n contactId String?\n dealId String?\n textValue String?\n numberValue Float?\n booleanValue Boolean?\n dateValue DateTime?\n optionValue String?\n updatedByAdminUserId String\n\n definition AdminCustomFieldDefinition @relation(fields: [definitionId], references: [id], onDelete: Restrict)\n contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: Cascade)\n deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: Cascade)\n\n @@unique([definitionId, contactId], name: \"admin_custom_field_contact_value\")\n @@unique([definitionId, dealId], name: \"admin_custom_field_deal_value\")\n @@index([contactId, definitionId], name: \"admin_custom_field_contact_idx\")\n @@index([dealId, definitionId], name: \"admin_custom_field_deal_idx\")\n}\n\nmodel AdminContactNote {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n contactId String\n body String\n createdByAdminUserId String\n\n contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Cascade)\n activities AdminActivity[]\n\n @@index([contactId, createdAt(sort: Desc)], name: \"admin_contact_note_contact_time_idx\")\n @@index([createdByAdminUserId, createdAt(sort: Desc)], name: \"admin_contact_note_actor_time_idx\")\n}\n\nmodel AdminImportJob {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n requestedByAdminUserId String\n status AdminSalesDataJobStatus @default(pending)\n fileName String\n sourceBucket String\n sourceKey String\n sourceHeaders String[] @default([])\n fieldMapping String[] @default([])\n totalRows Int @default(0)\n acceptedRows Int @default(0)\n rejectedRows Int @default(0)\n errorReportBucket String?\n errorReportKey String?\n queuedAt DateTime?\n startedAt DateTime?\n completedAt DateTime?\n errorCode String?\n errorMessage String?\n idempotencyKey String @unique\n\n errors AdminImportRowError[]\n\n @@index([status, createdAt], name: \"admin_import_job_status_time_idx\")\n @@index([requestedByAdminUserId, createdAt(sort: Desc)], name: \"admin_import_job_requester_time_idx\")\n}\n\nmodel AdminImportRowError {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n importJobId String\n rowNumber Int\n fieldKey String?\n code String\n message String\n rawValues String[] @default([])\n\n importJob AdminImportJob @relation(fields: [importJobId], references: [id], onDelete: Cascade)\n\n @@index([importJobId, rowNumber], name: \"admin_import_row_error_job_row_idx\")\n}\n\nmodel AdminExportJob {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n requestedByAdminUserId String\n status AdminSalesDataJobStatus @default(pending)\n selectedContactIds String[] @default([])\n artifactBucket String?\n artifactKey String?\n rowCount Int @default(0)\n queuedAt DateTime?\n startedAt DateTime?\n completedAt DateTime?\n expiresAt DateTime?\n errorCode String?\n errorMessage String?\n idempotencyKey String @unique\n\n @@index([status, createdAt], name: \"admin_export_job_status_time_idx\")\n @@index([requestedByAdminUserId, createdAt(sort: Desc)], name: \"admin_export_job_requester_time_idx\")\n}\n\n/// Append-only business timeline shared by leads, contacts, companies and\n/// deals. At least one context id is required by the repository contract.\nmodel AdminActivity {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n type AdminActivityType\n actorAdminUserId String\n leadId String?\n pipelineId String?\n companyId String?\n contactId String?\n dealId String?\n taskId String?\n noteId String? @unique\n emailMessageId String?\n callSessionId String?\n bookingId String?\n summary String\n payload Json\n occurredAt DateTime @default(now())\n\n lead AdminLead? @relation(fields: [leadId], references: [id], onDelete: SetNull)\n pipeline AdminPipeline? @relation(fields: [pipelineId], references: [id], onDelete: SetNull)\n company AdminCompany? @relation(fields: [companyId], references: [id], onDelete: SetNull)\n contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: SetNull)\n deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)\n task AdminTask? @relation(\"AdminActivityTask\", fields: [taskId], references: [id], onDelete: SetNull)\n sourcedTask AdminTask? @relation(\"AdminTaskSourceActivity\")\n note AdminContactNote? @relation(fields: [noteId], references: [id], onDelete: SetNull)\n emailMessage AdminEmailMessage? @relation(fields: [emailMessageId], references: [id], onDelete: SetNull)\n callSession AdminCallSession? @relation(fields: [callSessionId], references: [id], onDelete: SetNull)\n booking AdminBooking? @relation(fields: [bookingId], references: [id], onDelete: SetNull)\n\n @@index([leadId, occurredAt(sort: Desc)], name: \"admin_activity_lead_time_idx\")\n @@index([pipelineId, occurredAt(sort: Desc)], name: \"admin_activity_pipeline_time_idx\")\n @@index([companyId, occurredAt(sort: Desc)], name: \"admin_activity_company_time_idx\")\n @@index([contactId, occurredAt(sort: Desc)], name: \"admin_activity_contact_time_idx\")\n @@index([dealId, occurredAt(sort: Desc)], name: \"admin_activity_deal_time_idx\")\n @@index([taskId, occurredAt(sort: Desc)], name: \"admin_activity_task_time_idx\")\n @@index([actorAdminUserId, occurredAt(sort: Desc)], name: \"admin_activity_actor_time_idx\")\n @@index([type, occurredAt(sort: Desc)], name: \"admin_activity_type_time_idx\")\n @@index([emailMessageId, occurredAt(sort: Desc)], name: \"admin_activity_email_message_time_idx\")\n @@index([callSessionId, occurredAt(sort: Desc)], name: \"admin_activity_call_session_time_idx\")\n @@index([bookingId, occurredAt(sort: Desc)], name: \"admin_activity_booking_time_idx\")\n}\n\n/// Ordered, deterministic assignment rule. `sourceId` and `region` are ANDed;\n/// a null criterion is a wildcard. The mutable cursor is locked together with\n/// the lead so concurrent round-robin assignments cannot select the same slot.\nmodel AdminLeadAssignmentRule {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n name String\n active Boolean @default(true)\n priority Int\n sourceId String?\n region String?\n strategy AdminLeadAssignmentStrategy\n fixedAssigneeAdminUserId String?\n roundRobinAdminUserIds String[] @default([])\n nextAssigneeIndex Int @default(0)\n lastAssignedAt DateTime?\n\n @@unique([priority, name], name: \"admin_lead_assignment_rule_priority_name_key\")\n @@index([active, archivedAt, priority, id], name: \"admin_lead_assignment_rule_resolution_idx\")\n @@index([sourceId, region, active], name: \"admin_lead_assignment_rule_match_idx\")\n}\n\n/// Versionable score rule. Rules are additive and evaluated in stable\n/// priority/id order. The score snapshot on AdminLeadQualification records the\n/// rule-set version so historical decisions stay explainable.\nmodel AdminLeadScoreRule {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n name String\n active Boolean @default(true)\n priority Int\n field AdminLeadScoreField\n operator AdminLeadRuleOperator\n value String?\n points Int\n version Int @default(1)\n\n @@unique([priority, name], name: \"admin_lead_score_rule_priority_name_key\")\n @@index([active, archivedAt, priority, id], name: \"admin_lead_score_rule_resolution_idx\")\n}\n\nmodel AdminLeadQualification {\n leadId String @id\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n score Int @default(0)\n scoreBand String\n scoreVersion Int @default(1)\n scoreBreakdown Json\n enrichmentStatus AdminLeadEnrichmentStatus @default(pending)\n enrichmentProvider String?\n enrichmentData Json?\n enrichedAt DateTime?\n\n lead AdminLead @relation(fields: [leadId], references: [id], onDelete: Cascade)\n\n @@index([score, updatedAt(sort: Desc)], name: \"admin_lead_qualification_score_idx\")\n @@index([enrichmentStatus, updatedAt], name: \"admin_lead_qualification_enrichment_idx\")\n}\n\nmodel AdminDuplicateCandidate {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n primaryLeadId String\n duplicateLeadId String\n status AdminDuplicateCandidateStatus @default(open)\n matchKeys String[] @default([])\n confidenceBasisPoints Int\n resolvedAt DateTime?\n resolvedByAdminUserId String?\n resolutionReason String?\n\n primaryLead AdminLead @relation(\"AdminDuplicatePrimaryLead\", fields: [primaryLeadId], references: [id], onDelete: Cascade)\n duplicateLead AdminLead @relation(\"AdminDuplicateSecondaryLead\", fields: [duplicateLeadId], references: [id], onDelete: Cascade)\n\n @@unique([primaryLeadId, duplicateLeadId], name: \"admin_duplicate_candidate_pair_key\")\n @@index([status, confidenceBasisPoints(sort: Desc), createdAt], name: \"admin_duplicate_candidate_queue_idx\")\n @@index([duplicateLeadId, status], name: \"admin_duplicate_candidate_duplicate_idx\")\n}\n\n/// Append-only record of a controlled lead merge. The losing lead is archived,\n/// never deleted, and its original activity stream remains intact.\nmodel AdminMergeRecord {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n survivorLeadId String\n mergedLeadId String\n actorAdminUserId String\n reason String\n survivorSnapshot Json\n mergedSnapshot Json\n\n survivorLead AdminLead @relation(\"AdminMergeSurvivorLead\", fields: [survivorLeadId], references: [id], onDelete: Restrict)\n mergedLead AdminLead @relation(\"AdminMergeMergedLead\", fields: [mergedLeadId], references: [id], onDelete: Restrict)\n\n @@unique([mergedLeadId], name: \"admin_merge_record_merged_lead_key\")\n @@index([survivorLeadId, createdAt(sort: Desc)], name: \"admin_merge_record_survivor_idx\")\n @@index([actorAdminUserId, createdAt(sort: Desc)], name: \"admin_merge_record_actor_idx\")\n}\n\n// VA-P28d: tenant-less telephony for HiveGrid's own admin sales workspace.\n//\n// Aircall credentials remain in AdminDataConnection. Every operator-owned row\n// carries adminUserId so Postgres can enforce the platform-admin user context;\n// worker writes use the reviewed worker branch of the same policies.\n\nenum AdminCallDirection {\n inbound\n outbound\n}\n\nenum AdminCallStatus {\n ringing\n answered\n completed\n missed\n failed\n}\n\nenum AdminCallMatchStatus {\n unmatched\n unique\n ambiguous\n confirmed\n}\n\nenum AdminCallParticipantKind {\n admin\n contact\n lead\n external\n}\n\nenum AdminCallRecordingStatus {\n pending\n processing\n clean\n rejected\n expired\n deleted\n}\n\nenum AdminDialerListStatus {\n draft\n active\n paused\n completed\n}\n\nenum AdminDialerEntryStatus {\n pending\n active\n completed\n skipped\n blocked\n}\n\nenum AdminOutboundCallRequestStatus {\n pending\n processing\n accepted\n failed\n cancelled\n}\n\nmodel AdminPhoneConnection {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n connectionId String @unique\n providerCompanyId String?\n providerUserId String?\n providerUserEmail String?\n defaultPhoneNumberId String?\n webhookTokenHash String? @unique\n webhookVerifiedAt DateTime?\n lastEventAt DateTime?\n\n adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)\n connection AdminDataConnection @relation(fields: [connectionId], references: [id], onDelete: Restrict)\n defaultPhoneNumber AdminPhoneNumber? @relation(\"AdminDefaultPhoneNumber\", fields: [defaultPhoneNumberId], references: [id], onDelete: SetNull)\n phoneNumbers AdminPhoneNumber[] @relation(\"AdminPhoneConnectionNumbers\")\n calls AdminCallSession[]\n outboundRequests AdminOutboundCallRequest[]\n\n @@index([adminUserId, archivedAt], name: \"admin_phone_connection_owner_archive_idx\")\n @@index([providerCompanyId, archivedAt], name: \"admin_phone_connection_company_idx\")\n}\n\nmodel AdminPhoneNumber {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n phoneConnectionId String\n providerNumberId String\n label String\n e164 String\n countryCode String?\n selected Boolean @default(true)\n\n phoneConnection AdminPhoneConnection @relation(\"AdminPhoneConnectionNumbers\", fields: [phoneConnectionId], references: [id], onDelete: Cascade)\n defaultFor AdminPhoneConnection[] @relation(\"AdminDefaultPhoneNumber\")\n\n @@unique([phoneConnectionId, providerNumberId], name: \"admin_phone_number_provider_key\")\n @@index([adminUserId, selected, archivedAt], name: \"admin_phone_number_owner_selected_idx\")\n @@index([e164, archivedAt], name: \"admin_phone_number_e164_idx\")\n}\n\nmodel AdminTelephonyPolicy {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String @unique\n outboundEnabled Boolean @default(false)\n recordingEnabled Boolean @default(false)\n recordingConsentText String?\n recordingConsentVersion String?\n recordingConsentAt DateTime?\n recordingRetentionDays Int @default(90)\n dncEnforced Boolean @default(true)\n dailyCallLimit Int?\n workDayStartMinutes Int?\n workDayEndMinutes Int?\n workDays Int[] @default([])\n timeZone String?\n\n @@index([outboundEnabled, adminUserId], name: \"admin_telephony_policy_outbound_idx\")\n @@index([recordingEnabled, adminUserId], name: \"admin_telephony_policy_recording_idx\")\n}\n\nmodel AdminCallDisposition {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n code String @unique\n label String\n position Int @unique\n active Boolean @default(true)\n isSystem Boolean @default(true)\n\n calls AdminCallSession[]\n\n @@index([active, archivedAt, position], name: \"admin_call_disposition_active_idx\")\n}\n\nmodel AdminCallSession {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n phoneConnectionId String\n providerCallId String\n direction AdminCallDirection\n status AdminCallStatus\n providerUserId String?\n fromNumber String\n toNumber String\n externalNumber String\n startedAt DateTime\n answeredAt DateTime?\n endedAt DateTime?\n durationSeconds Int?\n contactId String?\n leadId String?\n dealId String?\n matchStatus AdminCallMatchStatus @default(unmatched)\n matchConfidenceBasisPoints Int?\n note String?\n dispositionId String?\n dispositionCodeSnapshot String?\n dispositionLabelSnapshot String?\n callbackTaskId String? @unique\n recordingOffered Boolean @default(false)\n recordingConsentConfirmedAt DateTime?\n\n phoneConnection AdminPhoneConnection @relation(fields: [phoneConnectionId], references: [id], onDelete: Restrict)\n contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: SetNull)\n lead AdminLead? @relation(fields: [leadId], references: [id], onDelete: SetNull)\n deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)\n disposition AdminCallDisposition? @relation(fields: [dispositionId], references: [id], onDelete: SetNull)\n callbackTask AdminTask? @relation(fields: [callbackTaskId], references: [id], onDelete: SetNull)\n participants AdminCallParticipant[]\n events AdminCallEvent[]\n matchCandidates AdminCallMatchCandidate[]\n recording AdminCallRecording?\n dialerEntry AdminDialerEntry?\n activities AdminActivity[]\n\n @@unique([phoneConnectionId, providerCallId], name: \"admin_call_provider_key\")\n @@index([adminUserId, startedAt(sort: Desc)], name: \"admin_call_owner_started_idx\")\n @@index([contactId, startedAt(sort: Desc)], name: \"admin_call_contact_started_idx\")\n @@index([leadId, startedAt(sort: Desc)], name: \"admin_call_lead_started_idx\")\n @@index([dealId, startedAt(sort: Desc)], name: \"admin_call_deal_started_idx\")\n @@index([matchStatus, startedAt(sort: Desc)], name: \"admin_call_match_queue_idx\")\n @@index([status, startedAt], name: \"admin_call_status_started_idx\")\n}\n\nmodel AdminCallParticipant {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n callSessionId String\n kind AdminCallParticipantKind\n externalId String?\n displayName String?\n phone String\n\n callSession AdminCallSession @relation(fields: [callSessionId], references: [id], onDelete: Cascade)\n\n @@unique([callSessionId, kind, phone], name: \"admin_call_participant_identity_key\")\n @@index([adminUserId, createdAt(sort: Desc)], name: \"admin_call_participant_owner_idx\")\n}\n\nmodel AdminCallEvent {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n callSessionId String\n dedupeKey String @unique\n providerEvent String\n status AdminCallStatus\n occurredAt DateTime\n durationSeconds Int?\n\n callSession AdminCallSession @relation(fields: [callSessionId], references: [id], onDelete: Cascade)\n\n @@index([adminUserId, occurredAt(sort: Desc)], name: \"admin_call_event_owner_time_idx\")\n @@index([callSessionId, occurredAt], name: \"admin_call_event_session_time_idx\")\n}\n\nmodel AdminCallMatchCandidate {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n adminUserId String\n callSessionId String\n contactId String?\n leadId String?\n confidenceBasisPoints Int\n matchReason String\n\n callSession AdminCallSession @relation(fields: [callSessionId], references: [id], onDelete: Cascade)\n contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: Cascade)\n lead AdminLead? @relation(fields: [leadId], references: [id], onDelete: Cascade)\n\n @@unique([callSessionId, contactId], name: \"admin_call_match_contact_key\")\n @@unique([callSessionId, leadId], name: \"admin_call_match_lead_key\")\n @@index([adminUserId, createdAt(sort: Desc)], name: \"admin_call_match_candidate_owner_idx\")\n}\n\nmodel AdminCallRecording {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n callSessionId String @unique\n status AdminCallRecordingStatus @default(pending)\n providerUrlWrappedDek Bytes?\n providerUrlCiphertext String?\n providerUrlKeyVersion Int?\n storageBucket String?\n storageKey String?\n encryptedSizeBytes Int?\n checksumSha256 String?\n wrappedDek Bytes?\n iv Bytes?\n authTag Bytes?\n processingAt DateTime?\n attemptCount Int @default(0)\n lastErrorCode String?\n scannedAt DateTime?\n retainedUntil DateTime\n expiredAt DateTime?\n deletedAt DateTime?\n rejectionCode String?\n\n callSession AdminCallSession @relation(fields: [callSessionId], references: [id], onDelete: Restrict)\n\n @@index([adminUserId, createdAt(sort: Desc)], name: \"admin_call_recording_owner_idx\")\n @@index([status, retainedUntil], name: \"admin_call_recording_retention_idx\")\n}\n\nmodel AdminDialerList {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n archivedAt DateTime?\n adminUserId String\n name String\n status AdminDialerListStatus @default(draft)\n currentPosition Int?\n startedAt DateTime?\n completedAt DateTime?\n\n entries AdminDialerEntry[]\n\n @@index([adminUserId, status, updatedAt(sort: Desc)], name: \"admin_dialer_list_owner_status_idx\")\n}\n\nmodel AdminDialerEntry {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n dialerListId String\n contactId String\n position Int\n status AdminDialerEntryStatus @default(pending)\n callSessionId String? @unique\n blockedReason String?\n activatedAt DateTime?\n completedAt DateTime?\n\n dialerList AdminDialerList @relation(fields: [dialerListId], references: [id], onDelete: Cascade)\n contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Restrict)\n callSession AdminCallSession? @relation(fields: [callSessionId], references: [id], onDelete: SetNull)\n outboundRequests AdminOutboundCallRequest[]\n\n @@unique([dialerListId, position], name: \"admin_dialer_entry_position_key\")\n @@unique([dialerListId, contactId], name: \"admin_dialer_entry_contact_key\")\n @@index([adminUserId, status, createdAt], name: \"admin_dialer_entry_owner_status_idx\")\n}\n\nmodel AdminOutboundCallRequest {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n adminUserId String\n phoneConnectionId String\n contactId String\n dealId String?\n dialerEntryId String?\n idempotencyKey String @unique\n destinationE164 String\n status AdminOutboundCallRequestStatus @default(pending)\n requestedAt DateTime @default(now())\n processingAt DateTime?\n acceptedAt DateTime?\n failedAt DateTime?\n attemptCount Int @default(0)\n errorCode String?\n\n phoneConnection AdminPhoneConnection @relation(fields: [phoneConnectionId], references: [id], onDelete: Restrict)\n contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Restrict)\n deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)\n dialerEntry AdminDialerEntry? @relation(fields: [dialerEntryId], references: [id], onDelete: SetNull)\n\n @@index([adminUserId, status, requestedAt], name: \"admin_outbound_call_owner_status_idx\")\n @@index([status, requestedAt], name: \"admin_outbound_call_worker_queue_idx\")\n @@index([contactId, requestedAt(sort: Desc)], name: \"admin_outbound_call_contact_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 @@index([portalId, createdAt])\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 @@index([portalId, createdAt])\n @@index([uniqueVisitorId])\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], onDelete: SetNull)\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 @@index([featureFlagId])\n @@index([portalId, createdAt])\n @@index([uniqueVisitorId])\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\nenum AppEntityBindingState {\n active\n quarantined\n missing\n ignored\n unlinked\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 entityBindings AppEntityBinding[]\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/// Durable provider-neutral identity mapping. AppSyncItem remains the history\n/// of one run; this row survives runs, reconnects and process restarts.\nmodel AppEntityBinding {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n dataConnectionId String\n externalEntityType String\n localEntityType String\n externalId String\n localId String\n state AppEntityBindingState @default(active)\n normalizedSnapshot Json\n fingerprint String\n overwrittenLocalSnapshot Json?\n revision Int @default(1)\n lastSeenAt DateTime?\n lastSyncedAt DateTime?\n missingSince DateTime?\n unlinkedAt DateTime?\n\n dataConnection DataConnection @relation(fields: [dataConnectionId], references: [id], onDelete: Cascade)\n\n @@unique([tenantId, dataConnectionId, externalEntityType, externalId])\n @@unique([tenantId, dataConnectionId, localEntityType, localId])\n @@index([tenantId, dataConnectionId, state, lastSyncedAt])\n @@index([tenantId, localEntityType, localId, state])\n}\n\nmodel AuditChainCheckpoint {\n id String @id\n createdAt DateTime\n chainKey String\n tenantId String?\n deletedThroughAt DateTime\n lastDeletedEventId String\n lastDeletedEventHash String?\n deletedCount Int\n previousCheckpointMac String?\n checkpointMac String @unique\n\n @@index([chainKey, createdAt(sort: Desc)], name: \"audit_checkpoint_chain_created_at_idx\")\n @@index([tenantId, createdAt(sort: Desc)], name: \"audit_checkpoint_tenant_created_at_idx\")\n}\n\nmodel AuditChainHead {\n chainKey String @id\n tenantId String?\n eventId String\n eventHash String\n eventCreatedAt DateTime\n headMac String\n\n @@index([tenantId], name: \"audit_chain_head_tenant_idx\")\n}\n\nmodel AuditChainCheckpointHead {\n chainKey String @id\n tenantId String?\n checkpointId String @unique\n checkpointMac String\n updatedAt DateTime\n\n @@index([tenantId], name: \"audit_checkpoint_head_tenant_idx\")\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 projekt Projekt @relation(fields: [projektId], references: [id], onDelete: Cascade)\n\n @@index([tenantId, projektId, archivedAt])\n @@index([tenantId, userId, archivedAt, projektId])\n @@index([tenantId, groupId, archivedAt, projektId])\n}\n\n/// WF-P8 S02-T: appointment kind offered by the \"Termin erstellen\" modal.\nenum ProjektTerminTyp {\n vor_ort\n telefon\n online\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 /// WF-P8 S02-T. Defaults to the on-site case, which is the SHK norm.\n typ ProjektTerminTyp @default(vor_ort)\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 /// Set when the invoice moves to `bezahlt`, cleared when it moves away again.\n /// `updatedAt` cannot stand in for this: any later edit overwrites it, which\n /// makes revenue by payment date and days-to-payment unmeasurable. Invoices\n /// already marked paid before this field existed stay null and are excluded\n /// from payment-date reporting rather than counted at a wrong date.\n bezahltAm 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, bezahltAm])\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 projekt Projekt @relation(fields: [projektId], references: [id], onDelete: Cascade)\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, status])\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 is LIVE since 20260713190000_appwide_rls_cutover (ENABLE+FORCE on all\n// calendar tables); prisma/rls/calendar-isolation.sql remains the\n// feature-branch template for db-push-only databases. Tables are tracked in\n// 20260703150000_ak_schema_parity_catchup. 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 @@index([tenantId, connectionId, provider, externalEventId])\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// AK-P15b (P15) Team Chat β€” typed internal chat domain model.\n//\n// AD-21: this module owns its schema. Cross-module identifiers such as\n// `tenantId`, `createdByUserId`, `userId`, and `projektId` remain bare String\n// scalars so shared Tenant, User, and Projekt schemas need no back-relations.\n// Attachments use FileEntityLink with FileEntityType.chat_message instead of a\n// second attachment model. All relations below stay inside this module.\n\nenum TeamChatKind {\n project\n group\n dm\n}\n\nenum TeamChatArchivedReason {\n manual\n project_completed\n project_cancelled\n}\n\nenum TeamChatNotificationPreference {\n all_messages\n mentions_only\n muted\n}\n\nenum TeamChatMemberRole {\n admin\n member\n}\n\nenum TeamChatMessageFormat {\n markdown\n system\n}\n\nenum TeamChatSystemEventKind {\n group_created\n project_created\n project_leader_changed\n member_write_access_changed\n member_added\n member_removed\n channel_renamed\n channel_privacy_changed\n channel_archived\n project_stage_changed\n acceptance_completed\n task_created\n}\n\n/// Durable mutation types used for WebSocket reconnect gap-fill. Presence and\n/// typing are intentionally absent because they are ephemeral Redis signals.\nenum TeamChatEventType {\n message_created @map(\"chat.message.created\")\n message_updated @map(\"chat.message.updated\")\n message_deleted @map(\"chat.message.deleted\")\n reaction_added @map(\"chat.reaction.added\")\n reaction_removed @map(\"chat.reaction.removed\")\n thread_reply @map(\"chat.thread.reply\")\n read_updated @map(\"chat.read.updated\")\n member_added @map(\"chat.member.added\")\n member_removed @map(\"chat.member.removed\")\n channel_archived @map(\"chat.channel.archived\")\n message_pin_changed @map(\"chat.message.pin_changed\")\n link_preview_ready @map(\"chat.link_preview.ready\")\n}\n\n/// A project-linked, group, or direct-message channel. Project and direct\n/// message channels are always private; group privacy is selected at creation.\n/// The merge migration enforces kind-specific CHECK constraints and partial\n/// unique indexes for active project channels and direct-message pairs.\nmodel TeamChat {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n // System-created project channels may not have a user actor (for example,\n // an automated qualified-lead conversion), so ownership is tenant-scoped\n // and the creator remains optional.\n createdByUserId String?\n kind TeamChatKind\n name String?\n description String?\n projektId String?\n isPrivate Boolean @default(false)\n archivedAt DateTime?\n archivedReason TeamChatArchivedReason?\n lastMessageAt DateTime?\n notificationDefault TeamChatNotificationPreference @default(all_messages)\n eventStreamId String @unique @default(cuid())\n // Canonically sorted user ids let the merge migration enforce one active DM\n // per tenant and member pair with a partial unique index.\n dmPairKey String?\n isDemoData Boolean @default(false)\n\n members TeamChatMember[]\n groupSources TeamChatGroupSource[]\n messages TeamChatMessage[]\n threads TeamChatThread[]\n pinnedMessages TeamChatPinnedMessage[]\n events TeamChatEvent[]\n\n @@unique([id, tenantId])\n @@index([tenantId, kind, archivedAt, lastMessageAt(sort: Desc)])\n @@index([tenantId, projektId])\n @@index([tenantId, dmPairKey, archivedAt])\n}\n\n/// Permission-group sources selected while creating a group chat. Sources are\n/// kept even when synchronization is disabled so the channel configuration is\n/// explicit and can be enabled later without guessing its original scope.\n/// `groupId` deliberately remains a bare cross-module identifier (AD-21).\nmodel TeamChatGroupSource {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n chatId String\n groupId String\n syncEnabled Boolean @default(false)\n\n chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)\n\n @@unique([chatId, groupId])\n @@index([tenantId, groupId, syncEnabled])\n @@index([tenantId, chatId])\n}\n\n/// Append-only event ledger for reconnect gap-fill. The wire cursor combines\n/// the channel's `eventStreamId` with `sequence`, which is serialized as a\n/// decimal string so JavaScript clients never lose BigInt precision. Redis\n/// fans these events out but is never their source of truth.\nmodel TeamChatEvent {\n id String @id @default(cuid())\n sequence BigInt @unique @default(autoincrement())\n occurredAt DateTime @default(now())\n tenantId String\n chatId String\n type TeamChatEventType\n actorUserId String?\n entityId String?\n requestId String\n data Json\n\n chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Restrict)\n\n @@index([tenantId, chatId, sequence])\n @@index([tenantId, actorUserId, occurredAt(sort: Desc)])\n}\n\n/// One user's membership and per-channel notification/read preferences.\n/// Rejoining reactivates the existing row by clearing `leftAt`.\nmodel TeamChatMember {\n id String @id @default(cuid())\n tenantId String\n chatId String\n userId String\n joinedAt DateTime @default(now())\n joinedViaUserId String?\n // Materialized effective role. Source-specific roles below remain\n // independent so losing one grant can deterministically fall back to the\n // strongest remaining grant without retaining stale admin privileges.\n roleInChat TeamChatMemberRole @default(member)\n notificationPref TeamChatNotificationPreference\n lastReadMessageId String?\n lastReadAt DateTime?\n isPinned Boolean @default(false)\n // Membership can have independent manual, project, and permission-group\n // origins. A manually invited project guest survives project reconciliation,\n // while later grants reuse this row without overwriting another source.\n isProjectManaged Boolean @default(false)\n isManualMember Boolean @default(true)\n manualRoleInChat TeamChatMemberRole?\n projectRoleInChat TeamChatMemberRole?\n // Group-managed membership is independent from an explicit invitation. A\n // user remains active when either source is still present.\n isGroupManaged Boolean @default(false)\n // Leaving an auto-synced group channel is a durable user decision. Group\n // reconciliation retains provenance but never reactivates an opted-out row;\n // an explicit join/invite clears this timestamp.\n groupSyncOptOutAt DateTime?\n // Former project members keep the immutable channel history readable until\n // archive, but may no longer publish mutations unless another membership\n // source grants write access again.\n writeRevokedAt DateTime?\n leftAt DateTime?\n\n chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)\n lastReadMessage TeamChatMessage? @relation(\"TeamChatMemberLastReadMessage\", fields: [lastReadMessageId, tenantId, chatId], references: [id, tenantId, chatId], onDelete: NoAction)\n\n @@unique([chatId, userId])\n @@index([tenantId, userId, leftAt])\n @@index([tenantId, chatId, userId])\n}\n\n/// A channel message or one-level thread reply. User-authored sends use a\n/// stable client id so retries and WebSocket echoes remain idempotent.\nmodel TeamChatMessage {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n tenantId String\n chatId String\n // System timeline entries may be emitted by automation without a user\n // actor. User-authored messages always keep their concrete author id.\n authorUserId String?\n clientMessageId String\n body String\n bodyFormat TeamChatMessageFormat @default(markdown)\n parentMessageId String?\n mentions Json @default(\"[]\")\n linkPreviews Json @default(\"[]\")\n editedAt DateTime?\n deletedAt DateTime?\n deletedByUserId String?\n // Stable domain-event key. System hooks retry with the same key so one\n // semantic event creates exactly one timeline entry per channel.\n systemEventKey String?\n systemEventKind TeamChatSystemEventKind?\n systemEventMetadata Json?\n isDemoData Boolean @default(false)\n\n chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)\n parentMessage TeamChatMessage? @relation(\"TeamChatMessageReplies\", fields: [parentMessageId, tenantId, chatId], references: [id, tenantId, chatId], onDelete: Cascade)\n replies TeamChatMessage[] @relation(\"TeamChatMessageReplies\")\n thread TeamChatThread? @relation(\"TeamChatThreadParent\")\n pinnedRecords TeamChatPinnedMessage[]\n reactions TeamChatReaction[]\n reads TeamChatRead[]\n lastReadByMembers TeamChatMember[] @relation(\"TeamChatMemberLastReadMessage\")\n\n @@unique([tenantId, authorUserId, clientMessageId])\n @@unique([tenantId, chatId, clientMessageId])\n @@unique([tenantId, chatId, systemEventKey])\n @@unique([id, tenantId])\n @@unique([id, tenantId, chatId])\n @@index([tenantId, chatId, parentMessageId, createdAt(sort: Desc)])\n @@index([mentions], type: Gin, map: \"TeamChatMessage_mentions_gin_idx\")\n @@index([body(ops: raw(\"gin_trgm_ops\"))], type: Gin, map: \"TeamChatMessage_body_trgm_idx\")\n}\n\n/// Denormalized aggregate for the one-level reply list of a parent message.\nmodel TeamChatThread {\n id String @id @default(cuid())\n tenantId String\n chatId String\n parentMessageId String\n createdAt DateTime @default(now())\n createdByUserId String\n lastReplyAt DateTime\n replyCount Int @default(0)\n participantUserIds String[] @default([])\n\n chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)\n parentMessage TeamChatMessage @relation(\"TeamChatThreadParent\", fields: [parentMessageId, tenantId, chatId], references: [id, tenantId, chatId], onDelete: Cascade)\n\n @@unique([parentMessageId, tenantId, chatId])\n @@index([tenantId, chatId, lastReplyAt(sort: Desc)])\n}\n\n/// A channel-level message pin. Domain guards enforce the 50-pin limit and\n/// reject message pins for direct-message channels.\nmodel TeamChatPinnedMessage {\n id String @id @default(cuid())\n tenantId String\n chatId String\n messageId String\n pinnedByUserId String\n pinnedAt DateTime @default(now())\n note String?\n\n chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)\n message TeamChatMessage @relation(fields: [messageId, tenantId, chatId], references: [id, tenantId, chatId], onDelete: Cascade)\n\n @@unique([chatId, messageId])\n @@index([tenantId, chatId, pinnedAt(sort: Desc)])\n}\n\n/// One user's Unicode emoji reaction to a message.\nmodel TeamChatReaction {\n id String @id @default(cuid())\n tenantId String\n messageId String\n userId String\n emoji String\n reactedAt DateTime @default(now())\n\n message TeamChatMessage @relation(fields: [messageId, tenantId], references: [id, tenantId], onDelete: Cascade)\n\n @@unique([messageId, userId, emoji])\n @@index([tenantId, messageId, reactedAt])\n}\n\n/// Per-user read receipt written only after a message was visibly read.\nmodel TeamChatRead {\n id String @id @default(cuid())\n tenantId String\n messageId String\n userId String\n readAt DateTime @default(now())\n\n message TeamChatMessage @relation(fields: [messageId, tenantId], references: [id, tenantId], onDelete: Cascade)\n\n @@unique([messageId, userId])\n @@index([tenantId, messageId, 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 tenantId String?\n partitionKey String\n systemOwned Boolean @default(false)\n scope String\n key String\n requestHash String\n responseStatus Int\n responseBody Json?\n responseHeaders Json?\n tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)\n\n @@unique([partitionKey, scope, key], name: \"idempotency_key_partition_scope_key\", map: \"idempotency_key_partition_scope_key\")\n @@index([tenantId, expiresAt], name: \"idempotency_key_tenant_expires_at_idx\")\n @@index([systemOwned, expiresAt], name: \"idempotency_key_system_expires_at_idx\")\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], onDelete: SetNull)\n userId String?\n user User? @relation(fields: [userId], references: [id], onDelete: SetNull)\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 // WF-P8 S05: the remaining types Davids field picker offers. Added to the\n // shared enum so the picker can store them; value rendering is a plain text\n // box for every type today, new and old alike.\n prozent\n datum_zeit\n person_team\n adresse\n link\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 // WF-P8 S02 company card (P8 baseline, consumed read-only there). Company\n // master data belongs to the contact, not to a project: the same company shows\n // up on many projects, and duplicating these per project would fork the truth.\n website String?\n ustIdNr String?\n handelsregister String?\n kundennummer String?\n kundeSeit DateTime?\n branche String?\n mitarbeiterzahl Int?\n // WF-P8 S02 contact-person card (kontaktTyp = privatperson).\n position String?\n erreichbarkeit String?\n // Free text on both card types: the standing arrangements with this contact\n // (how they want to be invoiced, who decides, when to call). Not the activity\n // timeline β€” that records what happened, this is what stays true.\n notizen String?\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`.\n/// WF-P8 S02 asks for \"Durchwahl\" and \"Mobil\" next to the main number. That is a\n/// kind of number, not two more scalars on Kontakt β€” a contact can have several\n/// of each, which is exactly what KontaktTelefon already models.\nenum KontaktTelefonTyp {\n haupt\n durchwahl\n mobil\n fax\n}\n\nmodel KontaktTelefon {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n tenantId String\n kontaktId String\n telefon String\n typ KontaktTelefonTyp @default(haupt)\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 @@index([tenantId, campaignId, kontaktId])\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 // AK-P15b Β· source message for an idempotently created task.\n chat_message\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\nenum FeatureFlagLifecycleStage {\n beta\n rollout\n ga\n deprecated\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 defaultValue Boolean?\n lifecycleStage FeatureFlagLifecycleStage @default(beta)\n ownerAdminUserId String?\n targetModule String?\n archivedAt DateTime?\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 tenantOverrides AdminFeatureFlagOverride[]\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 @@index([lifecycleStage, archivedAt], name: \"feature_flag_lifecycle_archive_idx\")\n @@index([ownerAdminUserId, archivedAt], name: \"feature_flag_owner_archive_idx\")\n @@index([targetModule, archivedAt], name: \"feature_flag_module_archive_idx\")\n}\n\nmodel FeatureFlagFilter {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @default(now()) @updatedAt\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 name String @default(\"Legacy filter\")\n priority Int @default(0)\n resultValue Boolean?\n criteria Json?\n active Boolean @default(true)\n createdByAdminUserId String?\n\n @@index([featureFlagId, active, priority, createdAt], name: \"feature_flag_filter_evaluation_idx\")\n}\n\n/// Operator-managed rollout override. This is deliberately not the\n/// subscription/entitlement TenantFeatureOverride model.\nmodel AdminFeatureFlagOverride {\n id String @id @default(cuid())\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n featureFlagId String\n tenantId String\n value Boolean\n note String?\n expiresAt DateTime?\n setByAdminUserId String\n\n featureFlag FeatureFlag @relation(fields: [featureFlagId], references: [id], onDelete: Cascade)\n\n @@unique([featureFlagId, tenantId], name: \"admin_feature_flag_override_flag_tenant_key\")\n @@index([tenantId, featureFlagId], name: \"admin_feature_flag_override_tenant_flag_idx\")\n @@index([featureFlagId, expiresAt], name: \"admin_feature_flag_override_expiry_idx\")\n @@index([setByAdminUserId, updatedAt], name: \"admin_feature_flag_override_actor_idx\")\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 actorType String @default(\"admin\")\n action String // create | update | delete | toggle\n oldValue Json?\n newValue Json?\n metadata 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 @@index([actorType, createdAt], name: \"feature_flag_audit_scope_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 // AK-P15b Β· Team Chat attachment linked through FileEntityLink.\n // ADDITIVE cross-module touch of files.prisma, flagged per AD-21.\n chat_message\n // AK-P21 Β· in-app feedback attachment (SupportTicket) linked through\n // FileEntityLink. ADDITIVE cross-module touch of files.prisma, flagged per\n // AD-21.\n support_ticket\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 /// Exactly one of createdByUserId / createdByPortalUserId must be non-null.\n /// The merge migration adds the database CHECK; shared service helpers enforce\n /// the same invariant while feature branches use prisma db push (AD-21).\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 createdByPortalUserId String?\n isDemoData Boolean @default(false)\n archivedAt DateTime?\n\n links FileEntityLink[]\n createdByPortalUser PortalUser? @relation(\"PortalFileActor\", fields: [createdByPortalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)\n portalDocuments PortalProjectDocument[]\n\n @@unique([id, tenantId])\n @@index([tenantId, archivedAt, createdAt(sort: Desc)])\n @@index([tenantId, createdByUserId])\n @@index([tenantId, createdByPortalUserId])\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 /// Exactly one actor column is set; see the merge-migration CHECK contract.\n createdByUserId String?\n createdByPortalUserId 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 createdByPortalUser PortalUser? @relation(\"PortalFileEntityLinkActor\", fields: [createdByPortalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)\n\n @@unique([fileId, entityType, entityId])\n @@index([tenantId, entityType, entityId])\n @@index([tenantId, fileId])\n @@index([tenantId, createdByPortalUserId])\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 /// Exactly one actor column is set; see the merge-migration CHECK contract.\n createdByUserId String?\n createdByPortalUserId 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 createdByPortalUser PortalUser? @relation(\"PortalFileUploadActor\", fields: [createdByPortalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)\n\n @@index([tenantId, createdByUserId, status])\n @@index([tenantId, createdByPortalUserId, 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 `