Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
@@ -2,6 +2,8 @@ model User {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
/// Stored normalized for new writes. A functional lower(trim(email))
|
||||
/// unique index in migration SQL also protects legacy mixed-case rows.
|
||||
email String @unique
|
||||
passwordHash String?
|
||||
firstName String
|
||||
@@ -34,7 +36,6 @@ model User {
|
||||
pseudonymized Boolean @default(false)
|
||||
pseudonymizedAt DateTime?
|
||||
deletionRequestId String? @unique
|
||||
admin AdminUser? // Has access to the admin panel
|
||||
createdApiKeys ApiKey[]
|
||||
createdGroups Group[]
|
||||
groups GroupUser[]
|
||||
@@ -59,8 +60,6 @@ model User {
|
||||
feedback Feedback[]
|
||||
supportTickets SupportTicket[]
|
||||
assignedSupportTickets SupportTicket[] @relation("supportTicketAssignee")
|
||||
supportTicketMessages SupportTicketMessage[] @relation("supportTicketMessageAuthor")
|
||||
adminTenantNotesAuthored AdminTenantNote[] @relation("adminTenantNoteAuthor")
|
||||
credits Credit[]
|
||||
portals Portal[]
|
||||
impersonationAuditsActor ImpersonationAudit[] @relation("ImpersonationAuditActor")
|
||||
@@ -95,24 +94,6 @@ model MagicLinkToken {
|
||||
@@index([expiresAt, consumedAt])
|
||||
}
|
||||
|
||||
// Has access to the admin panel
|
||||
model AdminUser {
|
||||
userId String @id @unique
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
// Phase 09 #82 — OIDC SSO link to external IdP (Authentik).
|
||||
// ssoProvider / ssoSubjectId together identify the federated identity
|
||||
// (typically `authentik` + the IdP-stable `sub` claim). Both nullable so
|
||||
// legacy bootstrap admins predating SSO continue to function.
|
||||
ssoProvider String?
|
||||
ssoSubjectId String?
|
||||
ssoGroups String[] @default([])
|
||||
lastSsoLoginAt DateTime?
|
||||
|
||||
@@unique([ssoProvider, ssoSubjectId])
|
||||
@@index([ssoSubjectId])
|
||||
}
|
||||
|
||||
model Tenant {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
@@ -126,6 +107,7 @@ model Tenant {
|
||||
deactivatedReason String?
|
||||
apiKeys ApiKey[]
|
||||
apiKeyLogs ApiKeyLog[]
|
||||
idempotencyKeys IdempotencyKey[]
|
||||
groups Group[]
|
||||
logs Log[]
|
||||
subscription TenantSubscription?
|
||||
@@ -146,7 +128,6 @@ model Tenant {
|
||||
ipAddresses TenantIpAddress[]
|
||||
metricLogs MetricLog[]
|
||||
knowledgeBases KnowledgeBase[]
|
||||
types TenantType[]
|
||||
workflows Workflow[]
|
||||
workflowExecutions WorkflowExecution[]
|
||||
workflowVariables WorkflowVariable[]
|
||||
@@ -154,6 +135,8 @@ model Tenant {
|
||||
feedback Feedback[]
|
||||
supportTickets SupportTicket[]
|
||||
credits Credit[]
|
||||
checkoutSessions CheckoutSessionStatus[]
|
||||
productAcquisitions TenantProductAcquisition[]
|
||||
portals Portal[]
|
||||
portalsUsers PortalUser[]
|
||||
widgets Widget[]
|
||||
@@ -227,16 +210,27 @@ model ImpersonationAudit {
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
// Seat billing bucket / default UI mode. `office` = back-office / desk work,
|
||||
// `field` = on-site (Baustelle) work. Shared across the Prisma schema folder
|
||||
// (Role.seatCategory, TenantUser.seatType).
|
||||
enum SeatType {
|
||||
office
|
||||
field
|
||||
}
|
||||
|
||||
model TenantUser {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
tenantId String
|
||||
userId String
|
||||
type Int
|
||||
joined Int
|
||||
status Int
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
// null = derived from the user's roles at read time (any office role => office
|
||||
// seat); an explicit value is an admin billing override.
|
||||
seatType SeatType?
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([tenantId, userId])
|
||||
@@index([userId])
|
||||
@@ -267,6 +261,9 @@ model TenantUserInvitation {
|
||||
revokedByUser User? @relation(name: "revokedByUser", fields: [revokedByUserId], references: [id])
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
|
||||
/// One live pending invite per tenant and normalized email is enforced by a
|
||||
/// partial functional index in migration SQL. A second partial unique index
|
||||
/// protects every non-null token hash globally. Prisma cannot declare either.
|
||||
@@index([tenantId, status, expiresAt])
|
||||
@@index([tenantId, email, status])
|
||||
@@index([tenantId, tokenPrefix])
|
||||
@@ -285,6 +282,8 @@ model Registration {
|
||||
ipAddress String?
|
||||
company String?
|
||||
selectedSubscriptionPriceId String?
|
||||
selectedOfficeSeatQuantity Int?
|
||||
selectedFieldSeatQuantity Int?
|
||||
leadConversionLeadId String?
|
||||
leadConversionToken String?
|
||||
leadConversionPlanId String?
|
||||
@@ -315,15 +314,3 @@ model TenantIpAddress {
|
||||
|
||||
@@unique([tenantId, ip, userId, apiKeyId])
|
||||
}
|
||||
|
||||
model TenantType {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
title String @unique
|
||||
titlePlural String
|
||||
description String?
|
||||
isDefault Boolean @default(false)
|
||||
tenants Tenant[]
|
||||
subscriptionProducts SubscriptionProduct[]
|
||||
}
|
||||
@@ -4,11 +4,9 @@
|
||||
// world is deliberately a *separate* world: these rows carry NO
|
||||
// `tenant_id`-based RLS scoping of their own beyond a plain FK, because
|
||||
// admin actions span tenants. Cross-tenant admin actions are recorded
|
||||
// through the shared AuditEvent Querschnitt (tenantId=null,
|
||||
// actorType="admin") — NOT a parallel audit table (see AK-P19 plan,
|
||||
// DoD #7). v1 also reuses the boilerplate User model as the admin
|
||||
// identity (AdminUser extension + admin-mfa-gate); the separate
|
||||
// AdminUser/AdminRole/AdminSession identity is v2 (M038/M039).
|
||||
// through the shared append-only AuditEvent Querschnitt (tenantId=null,
|
||||
// actorType="admin") — NOT a parallel audit table. All authors reference
|
||||
// the tenant-less AdminUser identity from adminIdentity.prisma.
|
||||
|
||||
/// AdminTenantNote — free-form operator notes pinned to a tenant.
|
||||
/// ENTITY-MODEL Domäne 11: markdown note_text, category, pinned.
|
||||
@@ -25,7 +23,7 @@ model AdminTenantNote {
|
||||
pinned Boolean @default(false)
|
||||
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
author User? @relation("adminTenantNoteAuthor", fields: [authorUserId], references: [id], onDelete: SetNull)
|
||||
author AdminUser? @relation("adminTenantNoteAuthor", fields: [authorUserId], references: [id], onDelete: SetNull)
|
||||
|
||||
// Detail view lists pinned-first, newest-first, per tenant.
|
||||
@@index([tenantId, pinned, createdAt], name: "admin_tenant_note_tenant_pinned_created_idx")
|
||||
@@ -46,7 +44,7 @@ model SupportTicketMessage {
|
||||
internalNote Boolean @default(false)
|
||||
|
||||
ticket SupportTicket @relation(fields: [supportTicketId], references: [id], onDelete: Cascade)
|
||||
author User? @relation("supportTicketMessageAuthor", fields: [authorUserId], references: [id], onDelete: SetNull)
|
||||
author AdminUser? @relation("supportTicketMessageAuthor", fields: [authorUserId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([supportTicketId, createdAt], name: "support_ticket_message_ticket_created_idx")
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// VA-P28f: public booking and availability for HiveGrid's own sales team.
|
||||
//
|
||||
// These records never carry tenantId. Public requests first resolve a published
|
||||
// page through a narrow SECURITY DEFINER function and then bind app.user_id to
|
||||
// the page owner. Provider actions are performed by bounded worker contracts.
|
||||
|
||||
enum AdminAvailabilityDay {
|
||||
monday
|
||||
tuesday
|
||||
wednesday
|
||||
thursday
|
||||
friday
|
||||
saturday
|
||||
sunday
|
||||
}
|
||||
|
||||
enum AdminAvailabilityOverrideKind {
|
||||
unavailable
|
||||
custom_window
|
||||
}
|
||||
|
||||
enum AdminBookingStatus {
|
||||
reserved
|
||||
confirmed
|
||||
cancelled
|
||||
rescheduled
|
||||
completed
|
||||
no_show
|
||||
provider_sync_failed
|
||||
}
|
||||
|
||||
enum AdminBookingAssignmentKind {
|
||||
round_robin
|
||||
manual
|
||||
}
|
||||
|
||||
enum AdminBookingReminderStatus {
|
||||
pending
|
||||
processing
|
||||
sent
|
||||
skipped
|
||||
failed
|
||||
cancelled
|
||||
}
|
||||
|
||||
model AdminMeetingType {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
createdByAdminUserId String
|
||||
name String
|
||||
slug String @unique
|
||||
description String?
|
||||
durationMinutes Int
|
||||
bufferBeforeMinutes Int @default(0)
|
||||
bufferAfterMinutes Int @default(0)
|
||||
slotIncrementMinutes Int @default(15)
|
||||
minimumNoticeMinutes Int @default(240)
|
||||
bookingHorizonDays Int @default(60)
|
||||
hostAdminUserIds String[] @default([])
|
||||
intakeQuestions Json @default("[]")
|
||||
reminderOffsetsMinutes Int[] @default([])
|
||||
active Boolean @default(true)
|
||||
|
||||
pages AdminBookingPage[]
|
||||
bookings AdminBooking[]
|
||||
|
||||
@@index([active, archivedAt, name], name: "admin_meeting_type_active_idx")
|
||||
@@index([createdByAdminUserId, archivedAt], name: "admin_meeting_type_creator_idx")
|
||||
}
|
||||
|
||||
model AdminAvailabilityRule {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
dayOfWeek AdminAvailabilityDay
|
||||
startMinutes Int
|
||||
endMinutes Int
|
||||
timeZone String
|
||||
|
||||
@@index([adminUserId, dayOfWeek, archivedAt], name: "admin_availability_rule_owner_day_idx")
|
||||
}
|
||||
|
||||
model AdminAvailabilityOverride {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
date DateTime @db.Date
|
||||
kind AdminAvailabilityOverrideKind
|
||||
startMinutes Int?
|
||||
endMinutes Int?
|
||||
timeZone String
|
||||
reason String?
|
||||
|
||||
@@index([adminUserId, date, archivedAt], name: "admin_availability_override_owner_date_idx")
|
||||
}
|
||||
|
||||
model AdminBookingPage {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
createdByAdminUserId String
|
||||
meetingTypeId String
|
||||
slug String @unique
|
||||
title String
|
||||
description String?
|
||||
published Boolean @default(false)
|
||||
tokenVersion Int @default(1)
|
||||
allowedEmailDomains String[] @default([])
|
||||
maxBookingsPerEmailPerDay Int @default(3)
|
||||
|
||||
meetingType AdminMeetingType @relation(fields: [meetingTypeId], references: [id], onDelete: Restrict)
|
||||
bookings AdminBooking[]
|
||||
|
||||
@@index([createdByAdminUserId, published, archivedAt], name: "admin_booking_page_creator_status_idx")
|
||||
@@index([meetingTypeId, published, archivedAt], name: "admin_booking_page_type_status_idx")
|
||||
}
|
||||
|
||||
model AdminBooking {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
bookingPageId String
|
||||
meetingTypeId String
|
||||
calendarConnectionId String?
|
||||
contactId String
|
||||
dealId String?
|
||||
startsAt DateTime
|
||||
endsAt DateTime
|
||||
bookerTimeZone String
|
||||
status AdminBookingStatus @default(reserved)
|
||||
idempotencyKey String @unique
|
||||
slotReservationKey String @unique
|
||||
providerEventId String?
|
||||
providerEventVersion String?
|
||||
providerSyncedAt DateTime?
|
||||
intakeAnswers Json @default("{}")
|
||||
manageTokenVersion Int @default(1)
|
||||
manageTokenExpiresAt DateTime
|
||||
lastManageNonceHash String?
|
||||
confirmedAt DateTime?
|
||||
cancelledAt DateTime?
|
||||
cancellationReason String?
|
||||
rescheduledFromId String? @unique
|
||||
|
||||
bookingPage AdminBookingPage @relation(fields: [bookingPageId], references: [id], onDelete: Restrict)
|
||||
meetingType AdminMeetingType @relation(fields: [meetingTypeId], references: [id], onDelete: Restrict)
|
||||
calendarConnection AdminCalendarConnection? @relation(fields: [calendarConnectionId], references: [id], onDelete: SetNull)
|
||||
contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Restrict)
|
||||
deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)
|
||||
rescheduledFrom AdminBooking? @relation("AdminBookingReschedule", fields: [rescheduledFromId], references: [id], onDelete: SetNull)
|
||||
rescheduledTo AdminBooking? @relation("AdminBookingReschedule")
|
||||
participants AdminBookingParticipant[]
|
||||
assignment AdminBookingAssignment?
|
||||
reminders AdminBookingReminder[]
|
||||
activities AdminActivity[]
|
||||
|
||||
@@index([adminUserId, startsAt], name: "admin_booking_owner_start_idx")
|
||||
@@index([status, startsAt], name: "admin_booking_status_start_idx")
|
||||
@@index([contactId, startsAt(sort: Desc)], name: "admin_booking_contact_start_idx")
|
||||
@@index([dealId, startsAt(sort: Desc)], name: "admin_booking_deal_start_idx")
|
||||
@@index([bookingPageId, startsAt], name: "admin_booking_page_start_idx")
|
||||
}
|
||||
|
||||
model AdminBookingParticipant {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
bookingId String
|
||||
email String
|
||||
name String
|
||||
locale String?
|
||||
timeZone String?
|
||||
isOrganizer Boolean @default(false)
|
||||
|
||||
booking AdminBooking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([bookingId, email], name: "admin_booking_participant_email_key")
|
||||
@@index([adminUserId, createdAt(sort: Desc)], name: "admin_booking_participant_owner_idx")
|
||||
}
|
||||
|
||||
model AdminBookingAssignment {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
bookingId String @unique
|
||||
kind AdminBookingAssignmentKind
|
||||
selectedHostAdminUserId String
|
||||
previousHostAdminUserId String?
|
||||
overriddenByAdminUserId String?
|
||||
eligibleHostAdminUserIds String[]
|
||||
excludedHosts Json @default("[]")
|
||||
loadSnapshot Json
|
||||
selectionReason String
|
||||
|
||||
booking AdminBooking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([adminUserId, createdAt(sort: Desc)], name: "admin_booking_assignment_owner_idx")
|
||||
@@index([selectedHostAdminUserId, createdAt(sort: Desc)], name: "admin_booking_assignment_host_idx")
|
||||
}
|
||||
|
||||
model AdminBookingReminder {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
bookingId String
|
||||
offsetMinutes Int
|
||||
scheduledFor DateTime
|
||||
status AdminBookingReminderStatus @default(pending)
|
||||
idempotencyKey String @unique
|
||||
attemptCount Int @default(0)
|
||||
sentAt DateTime?
|
||||
lastErrorCode String?
|
||||
|
||||
booking AdminBooking @relation(fields: [bookingId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([bookingId, offsetMinutes], name: "admin_booking_reminder_offset_key")
|
||||
@@index([status, scheduledFor], name: "admin_booking_reminder_due_idx")
|
||||
@@index([adminUserId, scheduledFor], name: "admin_booking_reminder_owner_idx")
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// VA-P28f: personal calendars for HiveGrid's tenant-less admin sales workspace.
|
||||
//
|
||||
// OAuth credentials remain exclusively in AdminDataConnection. Calendar sync
|
||||
// stores provider cursors plus anonymous busy intervals; titles, descriptions
|
||||
// and attendee lists from unrelated external events are deliberately discarded.
|
||||
|
||||
enum AdminCalendarConnectionStatus {
|
||||
active
|
||||
degraded
|
||||
reconnect_required
|
||||
revoked
|
||||
}
|
||||
|
||||
enum AdminCalendarSyncStatus {
|
||||
pending
|
||||
syncing
|
||||
active
|
||||
recovery_required
|
||||
failed
|
||||
}
|
||||
|
||||
model AdminCalendarConnection {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
dataConnectionId String @unique
|
||||
externalCalendarId String
|
||||
externalCalendarLabel String?
|
||||
timeZone String
|
||||
status AdminCalendarConnectionStatus @default(active)
|
||||
lastSyncAt DateTime?
|
||||
lastErrorCode String?
|
||||
healthMessageKey String?
|
||||
webhookExpiresAt DateTime?
|
||||
|
||||
adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)
|
||||
dataConnection AdminDataConnection @relation(fields: [dataConnectionId], references: [id], onDelete: Restrict)
|
||||
syncCursors AdminCalendarSyncCursor[]
|
||||
bookings AdminBooking[]
|
||||
|
||||
@@unique([adminUserId, externalCalendarId], name: "admin_calendar_owner_external_key")
|
||||
@@index([adminUserId, status, archivedAt], name: "admin_calendar_owner_status_idx")
|
||||
@@index([status, webhookExpiresAt], name: "admin_calendar_webhook_renewal_idx")
|
||||
}
|
||||
|
||||
model AdminCalendarSyncCursor {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
calendarConnectionId String
|
||||
externalCalendarId String
|
||||
cursorToken String?
|
||||
deltaLink String?
|
||||
busyIntervals Json @default("[]")
|
||||
status AdminCalendarSyncStatus @default(pending)
|
||||
lastFullSyncAt DateTime?
|
||||
lastIncrementalSyncAt DateTime?
|
||||
recoveryRequestedAt DateTime?
|
||||
lastErrorCode String?
|
||||
|
||||
calendarConnection AdminCalendarConnection @relation(fields: [calendarConnectionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([calendarConnectionId, externalCalendarId], name: "admin_calendar_cursor_external_key")
|
||||
@@index([adminUserId, status, updatedAt], name: "admin_calendar_cursor_owner_status_idx")
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// VA-P28c: provider-neutral connections for HiveGrid's own admin sales workspace.
|
||||
//
|
||||
// These rows are tenant-less and belong to one active AdminUser. Credentials
|
||||
// use a dedicated platform envelope key and never reuse a Tenant DEK or the
|
||||
// legacy CRYPTO_SECRET contract.
|
||||
|
||||
enum AdminConnectionProvider {
|
||||
google_mail
|
||||
microsoft_mail
|
||||
aircall
|
||||
google_calendar
|
||||
microsoft_calendar
|
||||
slack
|
||||
linkedin
|
||||
meeting_webhook
|
||||
}
|
||||
|
||||
enum AdminConnectionCapability {
|
||||
email
|
||||
telephony
|
||||
calendar
|
||||
team_chat
|
||||
professional_network
|
||||
meeting_artifact
|
||||
}
|
||||
|
||||
enum AdminConnectionStatus {
|
||||
pending
|
||||
active
|
||||
degraded
|
||||
revoked
|
||||
}
|
||||
|
||||
model AdminDataConnection {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
provider AdminConnectionProvider
|
||||
capability AdminConnectionCapability
|
||||
label String
|
||||
externalAccountId String?
|
||||
externalAccountEmail String?
|
||||
status AdminConnectionStatus @default(pending)
|
||||
scopes String[] @default([])
|
||||
tokenExpiresAt DateTime?
|
||||
lastHealthCheckAt DateTime?
|
||||
healthMessageKey String?
|
||||
webhookRegistrationId String?
|
||||
revokedAt DateTime?
|
||||
archivedAt DateTime?
|
||||
|
||||
adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)
|
||||
credential AdminConnectionCredential?
|
||||
mailboxes AdminMailbox[]
|
||||
phoneConnection AdminPhoneConnection?
|
||||
calendarConnection AdminCalendarConnection?
|
||||
|
||||
@@unique([adminUserId, provider, externalAccountId], name: "admin_data_connection_account_key")
|
||||
@@index([adminUserId, capability, archivedAt], name: "admin_data_connection_owner_capability_idx")
|
||||
@@index([provider, status, tokenExpiresAt], name: "admin_data_connection_refresh_idx")
|
||||
}
|
||||
|
||||
model AdminConnectionCredential {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
connectionId String @unique
|
||||
adminUserId String
|
||||
wrappedDek Bytes
|
||||
ciphertext String
|
||||
keyVersion Int @default(1)
|
||||
rotatedAt DateTime?
|
||||
revokedAt DateTime?
|
||||
|
||||
connection AdminDataConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)
|
||||
adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@index([adminUserId, revokedAt], name: "admin_connection_credential_owner_revoked_idx")
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
// VA-P28c: tenant-less email workspace for HiveGrid's own sales team.
|
||||
//
|
||||
// Every row is owned by an active AdminUser. Worker-readable rows repeat the
|
||||
// owner id deliberately so Postgres RLS can enforce the boundary without a
|
||||
// tenant context or an unreviewable join chain.
|
||||
|
||||
enum AdminMailboxStatus {
|
||||
connecting
|
||||
active
|
||||
degraded
|
||||
revoked
|
||||
}
|
||||
|
||||
enum AdminMailboxSyncStatus {
|
||||
pending
|
||||
running
|
||||
complete
|
||||
failed
|
||||
}
|
||||
|
||||
enum AdminEmailDirection {
|
||||
inbound
|
||||
outbound
|
||||
}
|
||||
|
||||
enum AdminEmailMatchStatus {
|
||||
matched
|
||||
ambiguous
|
||||
unmatched
|
||||
manual
|
||||
}
|
||||
|
||||
enum AdminEmailEventType {
|
||||
queued
|
||||
sent
|
||||
delivered
|
||||
bounced
|
||||
opened
|
||||
clicked
|
||||
replied
|
||||
}
|
||||
|
||||
enum AdminScheduledEmailStatus {
|
||||
draft
|
||||
blocked
|
||||
queued
|
||||
sending
|
||||
sent
|
||||
cancelled
|
||||
failed
|
||||
}
|
||||
|
||||
enum AdminNoReplyReminderStatus {
|
||||
pending
|
||||
fired
|
||||
dismissed
|
||||
cancelled
|
||||
}
|
||||
|
||||
enum AdminBulkEmailRunStatus {
|
||||
draft
|
||||
blocked
|
||||
queued
|
||||
running
|
||||
complete
|
||||
cancelled
|
||||
failed
|
||||
}
|
||||
|
||||
enum AdminSendingDomainStatus {
|
||||
pending
|
||||
verified
|
||||
degraded
|
||||
revoked
|
||||
}
|
||||
|
||||
model AdminMailbox {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
connectionId String @unique
|
||||
emailAddress String
|
||||
normalizedEmail String
|
||||
displayName String?
|
||||
providerAccountId String
|
||||
status AdminMailboxStatus @default(connecting)
|
||||
lastSyncAt DateTime?
|
||||
lastRecoveryPollAt DateTime?
|
||||
webhookExpiresAt DateTime?
|
||||
lastErrorMessageKey String?
|
||||
|
||||
adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)
|
||||
connection AdminDataConnection @relation(fields: [connectionId], references: [id], onDelete: Restrict)
|
||||
syncCursors AdminMailboxSyncCursor[]
|
||||
webhookEvents AdminMailboxWebhookEvent[]
|
||||
threads AdminEmailThread[]
|
||||
messages AdminEmailMessage[]
|
||||
scheduled AdminScheduledEmail[]
|
||||
bulkRuns AdminBulkEmailRun[]
|
||||
bccAddresses AdminBccAddress[]
|
||||
|
||||
@@unique([adminUserId, normalizedEmail], name: "admin_mailbox_owner_email_key")
|
||||
@@index([adminUserId, status, archivedAt], name: "admin_mailbox_owner_status_idx")
|
||||
@@index([status, lastSyncAt], name: "admin_mailbox_recovery_poll_idx")
|
||||
}
|
||||
|
||||
model AdminMailboxSyncCursor {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
mailboxId String
|
||||
externalFolderId String
|
||||
cursorToken String?
|
||||
syncStatus AdminMailboxSyncStatus @default(pending)
|
||||
recoveryGeneration Int @default(0)
|
||||
lastAttemptAt DateTime?
|
||||
lastSuccessAt DateTime?
|
||||
lastErrorMessageKey String?
|
||||
|
||||
mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([mailboxId, externalFolderId], name: "admin_mailbox_cursor_folder_key")
|
||||
@@index([adminUserId, syncStatus, lastAttemptAt], name: "admin_mailbox_cursor_owner_status_idx")
|
||||
}
|
||||
|
||||
model AdminMailboxWebhookEvent {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
processedAt DateTime?
|
||||
failedAt DateTime?
|
||||
adminUserId String
|
||||
mailboxId String
|
||||
providerEventId String
|
||||
idempotencyKey String @unique
|
||||
payload Json
|
||||
lastErrorMessageKey String?
|
||||
|
||||
mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([mailboxId, providerEventId], name: "admin_mailbox_webhook_provider_event_key")
|
||||
@@index([adminUserId, processedAt, createdAt], name: "admin_mailbox_webhook_pending_idx")
|
||||
}
|
||||
|
||||
model AdminEmailThread {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
mailboxId String
|
||||
providerThreadId String
|
||||
normalizedSubject String?
|
||||
latestMessageAt DateTime
|
||||
messageCount Int @default(0)
|
||||
unreadCount Int @default(0)
|
||||
|
||||
mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)
|
||||
messages AdminEmailMessage[]
|
||||
scheduled AdminScheduledEmail[]
|
||||
|
||||
@@unique([mailboxId, providerThreadId], name: "admin_email_thread_provider_key")
|
||||
@@index([adminUserId, latestMessageAt(sort: Desc)], name: "admin_email_thread_owner_latest_idx")
|
||||
}
|
||||
|
||||
model AdminEmailMessage {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
mailboxId String
|
||||
threadId String
|
||||
providerMessageId String
|
||||
internetMessageId String?
|
||||
direction AdminEmailDirection
|
||||
fromAddress String
|
||||
subject String?
|
||||
snippet String?
|
||||
bodyHtml String?
|
||||
bodyText String?
|
||||
sentAt DateTime
|
||||
receivedAt DateTime?
|
||||
isRead Boolean @default(false)
|
||||
isNewsletter Boolean @default(false)
|
||||
providerLabels String[] @default([])
|
||||
matchStatus AdminEmailMatchStatus @default(unmatched)
|
||||
matchedContactId String?
|
||||
matchedLeadId String?
|
||||
matchedDealId String?
|
||||
matchedAt DateTime?
|
||||
matchedByAdminUserId String?
|
||||
matchingReason String?
|
||||
matchingCandidates Json?
|
||||
|
||||
mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)
|
||||
thread AdminEmailThread @relation(fields: [threadId], references: [id], onDelete: Cascade)
|
||||
matchedContact AdminContact? @relation(fields: [matchedContactId], references: [id], onDelete: SetNull)
|
||||
matchedLead AdminLead? @relation(fields: [matchedLeadId], references: [id], onDelete: SetNull)
|
||||
matchedDeal AdminDeal? @relation(fields: [matchedDealId], references: [id], onDelete: SetNull)
|
||||
participants AdminEmailParticipant[]
|
||||
attachments AdminEmailAttachment[]
|
||||
events AdminEmailEvent[]
|
||||
links AdminEmailLink[]
|
||||
activities AdminActivity[]
|
||||
reminders AdminNoReplyReminder[]
|
||||
|
||||
@@unique([mailboxId, providerMessageId], name: "admin_email_message_provider_key")
|
||||
@@index([mailboxId, internetMessageId], name: "admin_email_message_rfc_id_idx")
|
||||
@@index([adminUserId, matchStatus, receivedAt(sort: Desc)], name: "admin_email_message_match_queue_idx")
|
||||
@@index([matchedContactId, sentAt(sort: Desc)], name: "admin_email_message_contact_time_idx")
|
||||
@@index([matchedLeadId, sentAt(sort: Desc)], name: "admin_email_message_lead_time_idx")
|
||||
@@index([matchedDealId, sentAt(sort: Desc)], name: "admin_email_message_deal_time_idx")
|
||||
}
|
||||
|
||||
model AdminEmailParticipant {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
messageId String
|
||||
kind String
|
||||
emailAddress String
|
||||
displayName String?
|
||||
|
||||
message AdminEmailMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([messageId, kind, emailAddress], name: "admin_email_participant_message_kind_address_key")
|
||||
@@index([adminUserId, emailAddress], name: "admin_email_participant_owner_address_idx")
|
||||
}
|
||||
|
||||
model AdminEmailAttachment {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
messageId String
|
||||
providerAttachmentId String?
|
||||
filename String
|
||||
mimeType String?
|
||||
sizeBytes Int
|
||||
storageBucket String
|
||||
storageKey String
|
||||
checksumSha256 String
|
||||
scannedAt DateTime
|
||||
linkedDealId String?
|
||||
|
||||
message AdminEmailMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([messageId, checksumSha256], name: "admin_email_attachment_message_checksum_key")
|
||||
@@index([adminUserId, linkedDealId, createdAt], name: "admin_email_attachment_owner_deal_idx")
|
||||
}
|
||||
|
||||
model AdminEmailEvent {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
messageId String
|
||||
type AdminEmailEventType
|
||||
providerEventId String?
|
||||
recipient String?
|
||||
linkId String?
|
||||
occurredAt DateTime
|
||||
rawExpiresAt DateTime?
|
||||
metadata Json?
|
||||
|
||||
message AdminEmailMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)
|
||||
link AdminEmailLink? @relation(fields: [linkId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([messageId, type, providerEventId], name: "admin_email_event_provider_key")
|
||||
@@index([adminUserId, type, occurredAt(sort: Desc)], name: "admin_email_event_owner_type_idx")
|
||||
@@index([rawExpiresAt], name: "admin_email_event_retention_idx")
|
||||
}
|
||||
|
||||
model AdminEmailLink {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
messageId String
|
||||
destinationUrl String
|
||||
trackingTokenHash String @unique
|
||||
|
||||
message AdminEmailMessage @relation(fields: [messageId], references: [id], onDelete: Cascade)
|
||||
events AdminEmailEvent[]
|
||||
|
||||
@@index([adminUserId, messageId], name: "admin_email_link_owner_message_idx")
|
||||
}
|
||||
|
||||
model AdminEmailTemplate {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
name String
|
||||
subjectTemplate String
|
||||
htmlTemplate String
|
||||
textTemplate String?
|
||||
allowedPlaceholders String[] @default([])
|
||||
version Int @default(1)
|
||||
|
||||
@@unique([adminUserId, name, version], name: "admin_email_template_owner_name_version_key")
|
||||
@@index([adminUserId, archivedAt, name], name: "admin_email_template_owner_archive_idx")
|
||||
}
|
||||
|
||||
model AdminEmailSnippet {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
shortcut String
|
||||
title String
|
||||
content String
|
||||
|
||||
@@unique([adminUserId, shortcut], name: "admin_email_snippet_owner_shortcut_key")
|
||||
@@index([adminUserId, archivedAt, title], name: "admin_email_snippet_owner_archive_idx")
|
||||
}
|
||||
|
||||
model AdminEmailSignature {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String @unique
|
||||
html String
|
||||
text String?
|
||||
|
||||
@@index([adminUserId, updatedAt], name: "admin_email_signature_owner_updated_idx")
|
||||
}
|
||||
|
||||
model AdminEmailOutboundPolicy {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String @unique
|
||||
timeZone String
|
||||
workdayStartMinutes Int
|
||||
workdayEndMinutes Int
|
||||
allowedWeekDays Int[] @default([])
|
||||
dailySendLimit Int
|
||||
bulkDailySendLimit Int
|
||||
consentRulesConfigured Boolean @default(false)
|
||||
trackingEnabled Boolean @default(false)
|
||||
liveOpenEnabled Boolean @default(false)
|
||||
trackingRetentionDays Int @default(180)
|
||||
configuredAt DateTime?
|
||||
|
||||
@@index([adminUserId, configuredAt], name: "admin_email_outbound_policy_owner_config_idx")
|
||||
}
|
||||
|
||||
model AdminScheduledEmail {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
mailboxId String
|
||||
contactId String?
|
||||
leadId String?
|
||||
dealId String?
|
||||
threadId String?
|
||||
bulkRunId String?
|
||||
toAddresses String[]
|
||||
ccAddresses String[] @default([])
|
||||
bccAddresses String[] @default([])
|
||||
subject String
|
||||
bodyHtml String
|
||||
bodyText String?
|
||||
scheduledFor DateTime
|
||||
timeZone String
|
||||
noReplyAfterDays Int?
|
||||
status AdminScheduledEmailStatus @default(draft)
|
||||
idempotencyKey String @unique
|
||||
claimedAt DateTime?
|
||||
sentAt DateTime?
|
||||
sendAttemptCount Int @default(0)
|
||||
providerMessageId String?
|
||||
sentMessageId String?
|
||||
lastErrorMessageKey String?
|
||||
|
||||
mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Restrict)
|
||||
thread AdminEmailThread? @relation(fields: [threadId], references: [id], onDelete: SetNull)
|
||||
bulkRun AdminBulkEmailRun? @relation(fields: [bulkRunId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([adminUserId, status, scheduledFor], name: "admin_scheduled_email_due_idx")
|
||||
@@index([dealId, scheduledFor], name: "admin_scheduled_email_deal_idx")
|
||||
@@index([bulkRunId, status], name: "admin_scheduled_email_bulk_status_idx")
|
||||
}
|
||||
|
||||
model AdminNoReplyReminder {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
outboundMessageId String
|
||||
dueAt DateTime
|
||||
status AdminNoReplyReminderStatus @default(pending)
|
||||
taskId String?
|
||||
idempotencyKey String @unique
|
||||
|
||||
outboundMessage AdminEmailMessage @relation(fields: [outboundMessageId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([adminUserId, status, dueAt], name: "admin_no_reply_reminder_due_idx")
|
||||
}
|
||||
|
||||
model AdminBulkEmailRun {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
mailboxId String
|
||||
name String
|
||||
selectedContactIds String[] @default([])
|
||||
templateId String?
|
||||
status AdminBulkEmailRunStatus @default(draft)
|
||||
scheduledFor DateTime?
|
||||
timeZone String
|
||||
recipientCount Int @default(0)
|
||||
sentCount Int @default(0)
|
||||
failedCount Int @default(0)
|
||||
idempotencyKey String @unique
|
||||
lastErrorMessageKey String?
|
||||
|
||||
mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Restrict)
|
||||
scheduled AdminScheduledEmail[]
|
||||
|
||||
@@index([adminUserId, status, scheduledFor], name: "admin_bulk_email_run_due_idx")
|
||||
}
|
||||
|
||||
model AdminSendingDomain {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
domain String @unique
|
||||
spfRecordName String
|
||||
spfExpectedValue String
|
||||
dkimRecordName String
|
||||
dkimExpectedValue String
|
||||
status AdminSendingDomainStatus @default(pending)
|
||||
spfStatus String
|
||||
dkimStatus String
|
||||
lastCheckedAt DateTime?
|
||||
lastErrorMessageKey String?
|
||||
|
||||
@@index([adminUserId, status, archivedAt], name: "admin_sending_domain_owner_status_idx")
|
||||
}
|
||||
|
||||
model AdminBccAddress {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
mailboxId String
|
||||
localPartHash String @unique
|
||||
displayAddress String
|
||||
rotatedAt DateTime?
|
||||
|
||||
mailbox AdminMailbox @relation(fields: [mailboxId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([adminUserId, archivedAt], name: "admin_bcc_address_owner_archive_idx")
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// VR-P28a / M038-M039: platform operator identity and authorization.
|
||||
//
|
||||
// These models are deliberately tenant-less. Authentik is the only productive
|
||||
// login authority; HiveGrid stores the resulting operator identity, session,
|
||||
// role grants and MFA assurance. The local development fallback may provision
|
||||
// an AdminUser without an Authentik subject only behind the fail-closed guards
|
||||
// documented in AGENTS.md.
|
||||
|
||||
enum AdminUserStatus {
|
||||
active
|
||||
disabled
|
||||
locked
|
||||
}
|
||||
|
||||
model AdminUser {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
email String @unique
|
||||
firstName String
|
||||
lastName String
|
||||
avatar String?
|
||||
locale String?
|
||||
status AdminUserStatus @default(active)
|
||||
authentikSubject String? @unique
|
||||
authentikGroups String[] @default([])
|
||||
lastSsoLoginAt DateTime?
|
||||
lastLoginIpHash String?
|
||||
disabledAt DateTime?
|
||||
disabledReason String?
|
||||
|
||||
sessions AdminSession[]
|
||||
roles AdminUserRole[]
|
||||
dataConnections AdminDataConnection[]
|
||||
connectionCredentials AdminConnectionCredential[]
|
||||
mailboxes AdminMailbox[]
|
||||
phoneConnections AdminPhoneConnection[]
|
||||
calendarConnections AdminCalendarConnection[]
|
||||
notificationDeliveries NotificationDelivery[]
|
||||
supportTicketMessages SupportTicketMessage[] @relation("supportTicketMessageAuthor")
|
||||
adminTenantNotesAuthored AdminTenantNote[] @relation("adminTenantNoteAuthor")
|
||||
|
||||
@@index([status, email], name: "admin_user_status_email_idx")
|
||||
@@index([lastSsoLoginAt(sort: Desc)], name: "admin_user_last_sso_login_idx")
|
||||
}
|
||||
|
||||
model AdminSession {
|
||||
id String @id @default(cuid())
|
||||
adminUserId String
|
||||
tokenHash String @unique
|
||||
createdAt DateTime @default(now())
|
||||
lastSeenAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
revokedAt DateTime?
|
||||
ipHash String?
|
||||
userAgent String?
|
||||
approxLocation String?
|
||||
authenticationMethods String[] @default([])
|
||||
mfaAssuredAt DateTime?
|
||||
|
||||
adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([adminUserId, revokedAt], name: "admin_session_user_revoked_idx")
|
||||
@@index([expiresAt], name: "admin_session_expiry_idx")
|
||||
}
|
||||
|
||||
model AdminRole {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
name String @unique
|
||||
description String
|
||||
systemKey String? @unique
|
||||
isSystem Boolean @default(false)
|
||||
active Boolean @default(true)
|
||||
|
||||
permissions AdminRolePermission[]
|
||||
users AdminUserRole[]
|
||||
|
||||
@@index([active, name], name: "admin_role_active_name_idx")
|
||||
}
|
||||
|
||||
model AdminPermission {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
name String @unique
|
||||
description String
|
||||
|
||||
roles AdminRolePermission[]
|
||||
}
|
||||
|
||||
model AdminRolePermission {
|
||||
adminRoleId String
|
||||
adminPermissionId String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
role AdminRole @relation(fields: [adminRoleId], references: [id], onDelete: Cascade)
|
||||
permission AdminPermission @relation(fields: [adminPermissionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([adminRoleId, adminPermissionId])
|
||||
@@index([adminPermissionId], name: "admin_role_permission_permission_idx")
|
||||
}
|
||||
|
||||
model AdminUserRole {
|
||||
adminUserId String
|
||||
adminRoleId String
|
||||
createdAt DateTime @default(now())
|
||||
grantedByAdminUserId String?
|
||||
|
||||
user AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Cascade)
|
||||
role AdminRole @relation(fields: [adminRoleId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([adminUserId, adminRoleId])
|
||||
@@index([adminRoleId], name: "admin_user_role_role_idx")
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// R-LEADS / M040a - HiveGrid's operator-wide sales lead intake.
|
||||
//
|
||||
// Platform leads deliberately carry no tenantId. They are isolated by the
|
||||
// platform-admin RLS contract and are visible only to authenticated operators.
|
||||
// Anonymous S2S intake uses a reviewed SECURITY DEFINER capability; the API
|
||||
// runtime role never receives direct table access outside those policies.
|
||||
|
||||
enum AdminLeadStatus {
|
||||
new
|
||||
contacted
|
||||
qualified
|
||||
disqualified
|
||||
}
|
||||
|
||||
enum AdminLeadActivityType {
|
||||
captured
|
||||
imported
|
||||
manually_created
|
||||
status_changed
|
||||
assigned
|
||||
note_added
|
||||
archived
|
||||
restored
|
||||
duplicate_hint_recorded
|
||||
legacy_event
|
||||
}
|
||||
|
||||
model AdminLeadSource {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
key String @unique
|
||||
displayName String
|
||||
enabled Boolean @default(true)
|
||||
defaultAssigneeAdminUserId String?
|
||||
notifyAdminUserIds String[] @default([])
|
||||
rateLimitPerMinute Int @default(60)
|
||||
metadata Json?
|
||||
|
||||
leads AdminLead[]
|
||||
credentials AdminLeadSourceCredential[]
|
||||
|
||||
@@index([enabled, displayName], name: "admin_lead_source_enabled_display_name_idx")
|
||||
@@index([defaultAssigneeAdminUserId], name: "admin_lead_source_default_assignee_idx")
|
||||
}
|
||||
|
||||
/// Rotatable source credential. Only a one-way digest is persisted; the raw
|
||||
/// bearer value is returned once by the source administration service.
|
||||
model AdminLeadSourceCredential {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
sourceId String
|
||||
keyHash String @unique
|
||||
keyPrefix String
|
||||
expiresAt DateTime?
|
||||
revokedAt DateTime?
|
||||
lastUsedAt DateTime?
|
||||
|
||||
source AdminLeadSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([sourceId, revokedAt, expiresAt], name: "admin_lead_source_credential_active_idx")
|
||||
@@index([sourceId, keyPrefix], name: "admin_lead_source_credential_prefix_idx")
|
||||
}
|
||||
|
||||
model AdminLead {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
capturedAt DateTime @default(now())
|
||||
archivedAt DateTime?
|
||||
sourceId String
|
||||
sourceDetail String?
|
||||
externalId String?
|
||||
idempotencyKey String?
|
||||
firstName String?
|
||||
lastName String?
|
||||
email String?
|
||||
normalizedEmail String?
|
||||
phone String?
|
||||
normalizedPhone String?
|
||||
company String?
|
||||
message String?
|
||||
utmSource String?
|
||||
utmMedium String?
|
||||
utmCampaign String?
|
||||
utmTerm String?
|
||||
utmContent String?
|
||||
referrer String?
|
||||
landingPage String?
|
||||
status AdminLeadStatus @default(new)
|
||||
assignedToAdminUserId String?
|
||||
duplicateHintOfLeadId String?
|
||||
metadata Json?
|
||||
|
||||
source AdminLeadSource @relation(fields: [sourceId], references: [id], onDelete: Restrict)
|
||||
activities AdminLeadActivity[]
|
||||
duplicateHint AdminLead? @relation("AdminLeadDuplicateHint", fields: [duplicateHintOfLeadId], references: [id], onDelete: SetNull)
|
||||
duplicates AdminLead[] @relation("AdminLeadDuplicateHint")
|
||||
convertedCompany AdminCompany? @relation("AdminLeadConvertedCompany")
|
||||
convertedContact AdminContact? @relation("AdminLeadConvertedContact")
|
||||
convertedDeal AdminDeal? @relation("AdminLeadConvertedDeal")
|
||||
salesActivities AdminActivity[]
|
||||
qualification AdminLeadQualification?
|
||||
duplicateCandidatesPrimary AdminDuplicateCandidate[] @relation("AdminDuplicatePrimaryLead")
|
||||
duplicateCandidatesSecondary AdminDuplicateCandidate[] @relation("AdminDuplicateSecondaryLead")
|
||||
mergeRecordsSurvived AdminMergeRecord[] @relation("AdminMergeSurvivorLead")
|
||||
mergeRecordMerged AdminMergeRecord? @relation("AdminMergeMergedLead")
|
||||
emailMessages AdminEmailMessage[]
|
||||
callSessions AdminCallSession[]
|
||||
callMatchCandidates AdminCallMatchCandidate[]
|
||||
|
||||
@@unique([sourceId, externalId], name: "admin_lead_source_external_id_key")
|
||||
@@unique([sourceId, idempotencyKey], name: "admin_lead_source_idempotency_key")
|
||||
@@index([status, archivedAt, capturedAt(sort: Desc)], name: "admin_lead_status_archive_captured_idx")
|
||||
@@index([sourceId, capturedAt(sort: Desc)], name: "admin_lead_source_captured_idx")
|
||||
@@index([assignedToAdminUserId, status, capturedAt(sort: Desc)], name: "admin_lead_assignee_status_captured_idx")
|
||||
@@index([normalizedEmail], name: "admin_lead_normalized_email_idx")
|
||||
@@index([normalizedPhone], name: "admin_lead_normalized_phone_idx")
|
||||
@@index([duplicateHintOfLeadId], name: "admin_lead_duplicate_hint_idx")
|
||||
}
|
||||
|
||||
/// Append-only business timeline. Notes are activities rather than a mutable
|
||||
/// blob on AdminLead so every operator-visible change remains attributable.
|
||||
model AdminLeadActivity {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
leadId String
|
||||
type AdminLeadActivityType
|
||||
actorAdminUserId String?
|
||||
payload Json
|
||||
|
||||
lead AdminLead @relation(fields: [leadId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([leadId, createdAt(sort: Desc)], name: "admin_lead_activity_lead_created_idx")
|
||||
@@index([type, createdAt(sort: Desc)], name: "admin_lead_activity_type_created_idx")
|
||||
@@index([actorAdminUserId, createdAt(sort: Desc)], name: "admin_lead_activity_actor_created_idx")
|
||||
}
|
||||
@@ -0,0 +1,744 @@
|
||||
// VA-P28b / M040b: tenant-less platform sales workspace.
|
||||
//
|
||||
// These records belong to HiveGrid's own sales operation. They never carry a
|
||||
// tenantId and are protected by the platform-admin RLS contract. A won deal may
|
||||
// later reference a Tenant explicitly, but that does not turn sales data into
|
||||
// tenant-owned CRM data.
|
||||
|
||||
enum AdminContactChannelKind {
|
||||
email
|
||||
phone
|
||||
linkedin
|
||||
website
|
||||
other
|
||||
}
|
||||
|
||||
enum AdminPipelineStageKind {
|
||||
open
|
||||
won
|
||||
lost
|
||||
}
|
||||
|
||||
enum AdminDealStatus {
|
||||
open
|
||||
won
|
||||
lost
|
||||
}
|
||||
|
||||
enum AdminActivityType {
|
||||
configuration_changed
|
||||
data_job_requested
|
||||
data_job_updated
|
||||
company_created
|
||||
company_updated
|
||||
contact_created
|
||||
contact_updated
|
||||
note_added
|
||||
lead_updated
|
||||
lead_converted
|
||||
lead_assigned
|
||||
lead_scored
|
||||
lead_enriched
|
||||
lead_merged
|
||||
deal_created
|
||||
deal_updated
|
||||
deal_stage_changed
|
||||
deal_won
|
||||
deal_lost
|
||||
task_created
|
||||
task_completed
|
||||
email
|
||||
call
|
||||
meeting
|
||||
sequence
|
||||
quote
|
||||
signature
|
||||
tenant_linked
|
||||
}
|
||||
|
||||
enum AdminLeadAssignmentStrategy {
|
||||
fixed
|
||||
round_robin
|
||||
}
|
||||
|
||||
enum AdminLeadRuleOperator {
|
||||
equals
|
||||
not_equals
|
||||
contains
|
||||
present
|
||||
}
|
||||
|
||||
enum AdminLeadScoreField {
|
||||
source
|
||||
region
|
||||
country
|
||||
company
|
||||
has_email
|
||||
has_phone
|
||||
}
|
||||
|
||||
enum AdminDuplicateCandidateStatus {
|
||||
open
|
||||
dismissed
|
||||
merged
|
||||
}
|
||||
|
||||
enum AdminLeadEnrichmentStatus {
|
||||
pending
|
||||
complete
|
||||
unavailable
|
||||
failed
|
||||
}
|
||||
|
||||
enum AdminTaskPriority {
|
||||
low
|
||||
normal
|
||||
high
|
||||
urgent
|
||||
}
|
||||
|
||||
enum AdminTaskStatus {
|
||||
open
|
||||
completed
|
||||
cancelled
|
||||
}
|
||||
|
||||
enum AdminTaskSource {
|
||||
manual
|
||||
email
|
||||
call
|
||||
}
|
||||
|
||||
enum AdminTaskRecurrenceFrequency {
|
||||
daily
|
||||
weekly
|
||||
monthly
|
||||
}
|
||||
|
||||
enum AdminSalesCustomFieldTarget {
|
||||
contact
|
||||
deal
|
||||
}
|
||||
|
||||
enum AdminSalesCustomFieldType {
|
||||
text
|
||||
number
|
||||
boolean
|
||||
date
|
||||
single_select
|
||||
}
|
||||
|
||||
enum AdminSalesDataJobStatus {
|
||||
pending
|
||||
running
|
||||
completed
|
||||
completed_with_errors
|
||||
failed
|
||||
}
|
||||
|
||||
model AdminCompany {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
name String
|
||||
normalizedName String
|
||||
legalName String?
|
||||
domain String?
|
||||
website String?
|
||||
phone String?
|
||||
normalizedPhone String?
|
||||
region String?
|
||||
countryCode String?
|
||||
industry String?
|
||||
employeeRange String?
|
||||
ownerAdminUserId String?
|
||||
sourceLeadId String? @unique
|
||||
enrichmentMetadata Json?
|
||||
|
||||
sourceLead AdminLead? @relation("AdminLeadConvertedCompany", fields: [sourceLeadId], references: [id], onDelete: SetNull)
|
||||
contacts AdminContact[]
|
||||
deals AdminDeal[]
|
||||
activities AdminActivity[]
|
||||
|
||||
@@index([normalizedName, archivedAt], name: "admin_company_name_archive_idx")
|
||||
@@index([domain, archivedAt], name: "admin_company_domain_archive_idx")
|
||||
@@index([ownerAdminUserId, archivedAt], name: "admin_company_owner_archive_idx")
|
||||
}
|
||||
|
||||
model AdminContact {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
companyId String?
|
||||
firstName String
|
||||
lastName String
|
||||
jobTitle String?
|
||||
email String?
|
||||
normalizedEmail String?
|
||||
phone String?
|
||||
normalizedPhone String?
|
||||
locale String?
|
||||
timeZone String?
|
||||
ownerAdminUserId String?
|
||||
sourceLeadId String? @unique
|
||||
enrichmentMetadata Json?
|
||||
|
||||
sourceLead AdminLead? @relation("AdminLeadConvertedContact", fields: [sourceLeadId], references: [id], onDelete: SetNull)
|
||||
company AdminCompany? @relation(fields: [companyId], references: [id], onDelete: SetNull)
|
||||
channels AdminContactChannel[]
|
||||
deals AdminDealContact[]
|
||||
tasks AdminTask[]
|
||||
tags AdminContactTag[]
|
||||
customFieldValues AdminCustomFieldValue[]
|
||||
notes AdminContactNote[]
|
||||
activities AdminActivity[]
|
||||
emailMessages AdminEmailMessage[]
|
||||
callSessions AdminCallSession[]
|
||||
callMatchCandidates AdminCallMatchCandidate[]
|
||||
dialerEntries AdminDialerEntry[]
|
||||
outboundCallRequests AdminOutboundCallRequest[]
|
||||
bookings AdminBooking[]
|
||||
doNotCall Boolean @default(false)
|
||||
doNotCallReason String?
|
||||
doNotCallAt DateTime?
|
||||
|
||||
@@index([companyId, archivedAt, lastName, firstName], name: "admin_contact_company_name_idx")
|
||||
@@index([normalizedEmail, archivedAt], name: "admin_contact_email_archive_idx")
|
||||
@@index([normalizedPhone, archivedAt], name: "admin_contact_phone_archive_idx")
|
||||
@@index([ownerAdminUserId, archivedAt], name: "admin_contact_owner_archive_idx")
|
||||
}
|
||||
|
||||
model AdminContactChannel {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
contactId String
|
||||
kind AdminContactChannelKind
|
||||
label String?
|
||||
value String
|
||||
normalizedValue String?
|
||||
isPrimary Boolean @default(false)
|
||||
|
||||
contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([contactId, kind, normalizedValue], name: "admin_contact_channel_normalized_key")
|
||||
@@index([kind, normalizedValue, archivedAt], name: "admin_contact_channel_lookup_idx")
|
||||
@@index([contactId, isPrimary, archivedAt], name: "admin_contact_channel_primary_idx")
|
||||
}
|
||||
|
||||
model AdminPipeline {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
name String
|
||||
description String?
|
||||
isDefault Boolean @default(false)
|
||||
|
||||
stages AdminPipelineStage[]
|
||||
deals AdminDeal[]
|
||||
lossReasons AdminDealLossReason[]
|
||||
activities AdminActivity[]
|
||||
|
||||
@@index([archivedAt, name], name: "admin_pipeline_archive_name_idx")
|
||||
@@index([isDefault, archivedAt], name: "admin_pipeline_default_idx")
|
||||
}
|
||||
|
||||
model AdminPipelineStage {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
pipelineId String
|
||||
name String
|
||||
position Int
|
||||
kind AdminPipelineStageKind @default(open)
|
||||
probabilityBasisPoints Int
|
||||
agingThresholdDays Int?
|
||||
color String?
|
||||
|
||||
pipeline AdminPipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)
|
||||
deals AdminDeal[]
|
||||
requiredFields AdminStageRequiredField[]
|
||||
historyFrom AdminDealStageHistory[] @relation("AdminDealStageHistoryFrom")
|
||||
historyTo AdminDealStageHistory[] @relation("AdminDealStageHistoryTo")
|
||||
|
||||
@@unique([pipelineId, position], name: "admin_pipeline_stage_position_key")
|
||||
@@unique([pipelineId, name], name: "admin_pipeline_stage_name_key")
|
||||
@@index([pipelineId, kind, archivedAt], name: "admin_pipeline_stage_kind_idx")
|
||||
}
|
||||
|
||||
model AdminStageRequiredField {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
stageId String
|
||||
fieldKey String
|
||||
|
||||
stage AdminPipelineStage @relation(fields: [stageId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([stageId, fieldKey], name: "admin_stage_required_field_key")
|
||||
}
|
||||
|
||||
model AdminDealLossReason {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
pipelineId String
|
||||
label String
|
||||
position Int
|
||||
|
||||
pipeline AdminPipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)
|
||||
deals AdminDeal[]
|
||||
|
||||
@@unique([pipelineId, label], name: "admin_deal_loss_reason_label_key")
|
||||
@@unique([pipelineId, position], name: "admin_deal_loss_reason_position_key")
|
||||
}
|
||||
|
||||
model AdminDeal {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
title String
|
||||
pipelineId String
|
||||
stageId String
|
||||
companyId String?
|
||||
sourceLeadId String? @unique
|
||||
ownerAdminUserId String
|
||||
status AdminDealStatus @default(open)
|
||||
amountCents Int?
|
||||
currencyCode String @default("EUR")
|
||||
probabilityBasisPoints Int
|
||||
expectedCloseDate DateTime?
|
||||
nextStep String?
|
||||
nextStepDueAt DateTime?
|
||||
stageEnteredAt DateTime @default(now())
|
||||
wonAt DateTime?
|
||||
lostAt DateTime?
|
||||
lossReasonId String?
|
||||
lossReasonNote String?
|
||||
promotedTenantId String?
|
||||
promotedAt DateTime?
|
||||
|
||||
sourceLead AdminLead? @relation("AdminLeadConvertedDeal", fields: [sourceLeadId], references: [id], onDelete: SetNull)
|
||||
pipeline AdminPipeline @relation(fields: [pipelineId], references: [id], onDelete: Restrict)
|
||||
stage AdminPipelineStage @relation(fields: [stageId], references: [id], onDelete: Restrict)
|
||||
company AdminCompany? @relation(fields: [companyId], references: [id], onDelete: SetNull)
|
||||
lossReason AdminDealLossReason? @relation(fields: [lossReasonId], references: [id], onDelete: SetNull)
|
||||
contacts AdminDealContact[]
|
||||
history AdminDealStageHistory[]
|
||||
tasks AdminTask[]
|
||||
customFieldValues AdminCustomFieldValue[]
|
||||
activities AdminActivity[]
|
||||
emailMessages AdminEmailMessage[]
|
||||
callSessions AdminCallSession[]
|
||||
outboundCallRequests AdminOutboundCallRequest[]
|
||||
bookings AdminBooking[]
|
||||
|
||||
@@index([pipelineId, stageId, stageEnteredAt], name: "admin_deal_pipeline_stage_age_idx")
|
||||
@@index([ownerAdminUserId, status, expectedCloseDate], name: "admin_deal_owner_status_close_idx")
|
||||
@@index([companyId, status], name: "admin_deal_company_status_idx")
|
||||
@@index([promotedTenantId], name: "admin_deal_promoted_tenant_idx")
|
||||
}
|
||||
|
||||
model AdminDealContact {
|
||||
dealId String
|
||||
contactId String
|
||||
createdAt DateTime @default(now())
|
||||
role String?
|
||||
isPrimary Boolean @default(false)
|
||||
|
||||
deal AdminDeal @relation(fields: [dealId], references: [id], onDelete: Cascade)
|
||||
contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([dealId, contactId])
|
||||
@@index([contactId, createdAt], name: "admin_deal_contact_contact_idx")
|
||||
@@index([dealId, isPrimary], name: "admin_deal_contact_primary_idx")
|
||||
}
|
||||
|
||||
/// Immutable record of every deal stage transition. The first history row has
|
||||
/// no fromStageId and represents entry into the pipeline.
|
||||
model AdminDealStageHistory {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
dealId String
|
||||
fromStageId String?
|
||||
toStageId String
|
||||
actorAdminUserId String
|
||||
enteredAt DateTime
|
||||
exitedAt DateTime?
|
||||
reason String?
|
||||
|
||||
deal AdminDeal @relation(fields: [dealId], references: [id], onDelete: Cascade)
|
||||
fromStage AdminPipelineStage? @relation("AdminDealStageHistoryFrom", fields: [fromStageId], references: [id], onDelete: Restrict)
|
||||
toStage AdminPipelineStage @relation("AdminDealStageHistoryTo", fields: [toStageId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@index([dealId, enteredAt(sort: Desc)], name: "admin_deal_stage_history_deal_time_idx")
|
||||
@@index([toStageId, enteredAt], name: "admin_deal_stage_history_stage_time_idx")
|
||||
@@index([actorAdminUserId, enteredAt(sort: Desc)], name: "admin_deal_stage_history_actor_time_idx")
|
||||
}
|
||||
|
||||
model AdminTaskRecurrence {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
createdByAdminUserId String
|
||||
frequency AdminTaskRecurrenceFrequency
|
||||
interval Int @default(1)
|
||||
timeZone String
|
||||
weekDays Int[] @default([])
|
||||
dayOfMonth Int?
|
||||
reminderOffsetMinutes Int?
|
||||
endsAt DateTime?
|
||||
|
||||
tasks AdminTask[]
|
||||
|
||||
@@index([archivedAt, frequency, endsAt], name: "admin_task_recurrence_active_idx")
|
||||
@@index([createdByAdminUserId, archivedAt], name: "admin_task_recurrence_creator_idx")
|
||||
}
|
||||
|
||||
model AdminTask {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
title String
|
||||
description String?
|
||||
contactId String?
|
||||
dealId String?
|
||||
assignedToAdminUserId String
|
||||
createdByAdminUserId String
|
||||
dueAt DateTime
|
||||
timeZone String
|
||||
reminderAt DateTime?
|
||||
reminderSentAt DateTime?
|
||||
priority AdminTaskPriority @default(normal)
|
||||
status AdminTaskStatus @default(open)
|
||||
completedAt DateTime?
|
||||
source AdminTaskSource @default(manual)
|
||||
sourceActivityId String? @unique
|
||||
recurrenceId String?
|
||||
recurrenceSequence Int @default(0)
|
||||
|
||||
contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
|
||||
deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)
|
||||
recurrence AdminTaskRecurrence? @relation(fields: [recurrenceId], references: [id], onDelete: Restrict)
|
||||
sourceActivity AdminActivity? @relation("AdminTaskSourceActivity", fields: [sourceActivityId], references: [id], onDelete: SetNull)
|
||||
activities AdminActivity[] @relation("AdminActivityTask")
|
||||
callbackCall AdminCallSession?
|
||||
|
||||
@@unique([recurrenceId, recurrenceSequence], name: "admin_task_recurrence_sequence_key")
|
||||
@@index([assignedToAdminUserId, status, dueAt], name: "admin_task_owner_status_due_idx")
|
||||
@@index([status, reminderAt, reminderSentAt], name: "admin_task_reminder_due_idx")
|
||||
@@index([contactId, status, dueAt], name: "admin_task_contact_due_idx")
|
||||
@@index([dealId, status, dueAt], name: "admin_task_deal_due_idx")
|
||||
}
|
||||
|
||||
model AdminTag {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
name String
|
||||
normalizedName String @unique
|
||||
color String?
|
||||
createdByAdminUserId String
|
||||
|
||||
contacts AdminContactTag[]
|
||||
|
||||
@@index([archivedAt, name], name: "admin_tag_archive_name_idx")
|
||||
}
|
||||
|
||||
model AdminContactTag {
|
||||
contactId String
|
||||
tagId String
|
||||
createdAt DateTime @default(now())
|
||||
createdByAdminUserId String
|
||||
|
||||
contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Cascade)
|
||||
tag AdminTag @relation(fields: [tagId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@id([contactId, tagId])
|
||||
@@index([tagId, createdAt], name: "admin_contact_tag_tag_time_idx")
|
||||
}
|
||||
|
||||
model AdminCustomFieldDefinition {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
target AdminSalesCustomFieldTarget
|
||||
key String
|
||||
label String
|
||||
type AdminSalesCustomFieldType
|
||||
options String[] @default([])
|
||||
required Boolean @default(false)
|
||||
position Int
|
||||
createdByAdminUserId String
|
||||
|
||||
values AdminCustomFieldValue[]
|
||||
|
||||
@@unique([target, key], name: "admin_custom_field_target_key")
|
||||
@@unique([target, position], name: "admin_custom_field_target_position")
|
||||
@@index([target, archivedAt, position], name: "admin_custom_field_target_active_idx")
|
||||
}
|
||||
|
||||
model AdminCustomFieldValue {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
definitionId String
|
||||
contactId String?
|
||||
dealId String?
|
||||
textValue String?
|
||||
numberValue Float?
|
||||
booleanValue Boolean?
|
||||
dateValue DateTime?
|
||||
optionValue String?
|
||||
updatedByAdminUserId String
|
||||
|
||||
definition AdminCustomFieldDefinition @relation(fields: [definitionId], references: [id], onDelete: Restrict)
|
||||
contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: Cascade)
|
||||
deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([definitionId, contactId], name: "admin_custom_field_contact_value")
|
||||
@@unique([definitionId, dealId], name: "admin_custom_field_deal_value")
|
||||
@@index([contactId, definitionId], name: "admin_custom_field_contact_idx")
|
||||
@@index([dealId, definitionId], name: "admin_custom_field_deal_idx")
|
||||
}
|
||||
|
||||
model AdminContactNote {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
contactId String
|
||||
body String
|
||||
createdByAdminUserId String
|
||||
|
||||
contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Cascade)
|
||||
activities AdminActivity[]
|
||||
|
||||
@@index([contactId, createdAt(sort: Desc)], name: "admin_contact_note_contact_time_idx")
|
||||
@@index([createdByAdminUserId, createdAt(sort: Desc)], name: "admin_contact_note_actor_time_idx")
|
||||
}
|
||||
|
||||
model AdminImportJob {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
requestedByAdminUserId String
|
||||
status AdminSalesDataJobStatus @default(pending)
|
||||
fileName String
|
||||
sourceBucket String
|
||||
sourceKey String
|
||||
sourceHeaders String[] @default([])
|
||||
fieldMapping String[] @default([])
|
||||
totalRows Int @default(0)
|
||||
acceptedRows Int @default(0)
|
||||
rejectedRows Int @default(0)
|
||||
errorReportBucket String?
|
||||
errorReportKey String?
|
||||
queuedAt DateTime?
|
||||
startedAt DateTime?
|
||||
completedAt DateTime?
|
||||
errorCode String?
|
||||
errorMessage String?
|
||||
idempotencyKey String @unique
|
||||
|
||||
errors AdminImportRowError[]
|
||||
|
||||
@@index([status, createdAt], name: "admin_import_job_status_time_idx")
|
||||
@@index([requestedByAdminUserId, createdAt(sort: Desc)], name: "admin_import_job_requester_time_idx")
|
||||
}
|
||||
|
||||
model AdminImportRowError {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
importJobId String
|
||||
rowNumber Int
|
||||
fieldKey String?
|
||||
code String
|
||||
message String
|
||||
rawValues String[] @default([])
|
||||
|
||||
importJob AdminImportJob @relation(fields: [importJobId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([importJobId, rowNumber], name: "admin_import_row_error_job_row_idx")
|
||||
}
|
||||
|
||||
model AdminExportJob {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
requestedByAdminUserId String
|
||||
status AdminSalesDataJobStatus @default(pending)
|
||||
selectedContactIds String[] @default([])
|
||||
artifactBucket String?
|
||||
artifactKey String?
|
||||
rowCount Int @default(0)
|
||||
queuedAt DateTime?
|
||||
startedAt DateTime?
|
||||
completedAt DateTime?
|
||||
expiresAt DateTime?
|
||||
errorCode String?
|
||||
errorMessage String?
|
||||
idempotencyKey String @unique
|
||||
|
||||
@@index([status, createdAt], name: "admin_export_job_status_time_idx")
|
||||
@@index([requestedByAdminUserId, createdAt(sort: Desc)], name: "admin_export_job_requester_time_idx")
|
||||
}
|
||||
|
||||
/// Append-only business timeline shared by leads, contacts, companies and
|
||||
/// deals. At least one context id is required by the repository contract.
|
||||
model AdminActivity {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
type AdminActivityType
|
||||
actorAdminUserId String
|
||||
leadId String?
|
||||
pipelineId String?
|
||||
companyId String?
|
||||
contactId String?
|
||||
dealId String?
|
||||
taskId String?
|
||||
noteId String? @unique
|
||||
emailMessageId String?
|
||||
callSessionId String?
|
||||
bookingId String?
|
||||
summary String
|
||||
payload Json
|
||||
occurredAt DateTime @default(now())
|
||||
|
||||
lead AdminLead? @relation(fields: [leadId], references: [id], onDelete: SetNull)
|
||||
pipeline AdminPipeline? @relation(fields: [pipelineId], references: [id], onDelete: SetNull)
|
||||
company AdminCompany? @relation(fields: [companyId], references: [id], onDelete: SetNull)
|
||||
contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
|
||||
deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)
|
||||
task AdminTask? @relation("AdminActivityTask", fields: [taskId], references: [id], onDelete: SetNull)
|
||||
sourcedTask AdminTask? @relation("AdminTaskSourceActivity")
|
||||
note AdminContactNote? @relation(fields: [noteId], references: [id], onDelete: SetNull)
|
||||
emailMessage AdminEmailMessage? @relation(fields: [emailMessageId], references: [id], onDelete: SetNull)
|
||||
callSession AdminCallSession? @relation(fields: [callSessionId], references: [id], onDelete: SetNull)
|
||||
booking AdminBooking? @relation(fields: [bookingId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([leadId, occurredAt(sort: Desc)], name: "admin_activity_lead_time_idx")
|
||||
@@index([pipelineId, occurredAt(sort: Desc)], name: "admin_activity_pipeline_time_idx")
|
||||
@@index([companyId, occurredAt(sort: Desc)], name: "admin_activity_company_time_idx")
|
||||
@@index([contactId, occurredAt(sort: Desc)], name: "admin_activity_contact_time_idx")
|
||||
@@index([dealId, occurredAt(sort: Desc)], name: "admin_activity_deal_time_idx")
|
||||
@@index([taskId, occurredAt(sort: Desc)], name: "admin_activity_task_time_idx")
|
||||
@@index([actorAdminUserId, occurredAt(sort: Desc)], name: "admin_activity_actor_time_idx")
|
||||
@@index([type, occurredAt(sort: Desc)], name: "admin_activity_type_time_idx")
|
||||
@@index([emailMessageId, occurredAt(sort: Desc)], name: "admin_activity_email_message_time_idx")
|
||||
@@index([callSessionId, occurredAt(sort: Desc)], name: "admin_activity_call_session_time_idx")
|
||||
@@index([bookingId, occurredAt(sort: Desc)], name: "admin_activity_booking_time_idx")
|
||||
}
|
||||
|
||||
/// Ordered, deterministic assignment rule. `sourceId` and `region` are ANDed;
|
||||
/// a null criterion is a wildcard. The mutable cursor is locked together with
|
||||
/// the lead so concurrent round-robin assignments cannot select the same slot.
|
||||
model AdminLeadAssignmentRule {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
name String
|
||||
active Boolean @default(true)
|
||||
priority Int
|
||||
sourceId String?
|
||||
region String?
|
||||
strategy AdminLeadAssignmentStrategy
|
||||
fixedAssigneeAdminUserId String?
|
||||
roundRobinAdminUserIds String[] @default([])
|
||||
nextAssigneeIndex Int @default(0)
|
||||
lastAssignedAt DateTime?
|
||||
|
||||
@@unique([priority, name], name: "admin_lead_assignment_rule_priority_name_key")
|
||||
@@index([active, archivedAt, priority, id], name: "admin_lead_assignment_rule_resolution_idx")
|
||||
@@index([sourceId, region, active], name: "admin_lead_assignment_rule_match_idx")
|
||||
}
|
||||
|
||||
/// Versionable score rule. Rules are additive and evaluated in stable
|
||||
/// priority/id order. The score snapshot on AdminLeadQualification records the
|
||||
/// rule-set version so historical decisions stay explainable.
|
||||
model AdminLeadScoreRule {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
name String
|
||||
active Boolean @default(true)
|
||||
priority Int
|
||||
field AdminLeadScoreField
|
||||
operator AdminLeadRuleOperator
|
||||
value String?
|
||||
points Int
|
||||
version Int @default(1)
|
||||
|
||||
@@unique([priority, name], name: "admin_lead_score_rule_priority_name_key")
|
||||
@@index([active, archivedAt, priority, id], name: "admin_lead_score_rule_resolution_idx")
|
||||
}
|
||||
|
||||
model AdminLeadQualification {
|
||||
leadId String @id
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
score Int @default(0)
|
||||
scoreBand String
|
||||
scoreVersion Int @default(1)
|
||||
scoreBreakdown Json
|
||||
enrichmentStatus AdminLeadEnrichmentStatus @default(pending)
|
||||
enrichmentProvider String?
|
||||
enrichmentData Json?
|
||||
enrichedAt DateTime?
|
||||
|
||||
lead AdminLead @relation(fields: [leadId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([score, updatedAt(sort: Desc)], name: "admin_lead_qualification_score_idx")
|
||||
@@index([enrichmentStatus, updatedAt], name: "admin_lead_qualification_enrichment_idx")
|
||||
}
|
||||
|
||||
model AdminDuplicateCandidate {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
primaryLeadId String
|
||||
duplicateLeadId String
|
||||
status AdminDuplicateCandidateStatus @default(open)
|
||||
matchKeys String[] @default([])
|
||||
confidenceBasisPoints Int
|
||||
resolvedAt DateTime?
|
||||
resolvedByAdminUserId String?
|
||||
resolutionReason String?
|
||||
|
||||
primaryLead AdminLead @relation("AdminDuplicatePrimaryLead", fields: [primaryLeadId], references: [id], onDelete: Cascade)
|
||||
duplicateLead AdminLead @relation("AdminDuplicateSecondaryLead", fields: [duplicateLeadId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([primaryLeadId, duplicateLeadId], name: "admin_duplicate_candidate_pair_key")
|
||||
@@index([status, confidenceBasisPoints(sort: Desc), createdAt], name: "admin_duplicate_candidate_queue_idx")
|
||||
@@index([duplicateLeadId, status], name: "admin_duplicate_candidate_duplicate_idx")
|
||||
}
|
||||
|
||||
/// Append-only record of a controlled lead merge. The losing lead is archived,
|
||||
/// never deleted, and its original activity stream remains intact.
|
||||
model AdminMergeRecord {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
survivorLeadId String
|
||||
mergedLeadId String
|
||||
actorAdminUserId String
|
||||
reason String
|
||||
survivorSnapshot Json
|
||||
mergedSnapshot Json
|
||||
|
||||
survivorLead AdminLead @relation("AdminMergeSurvivorLead", fields: [survivorLeadId], references: [id], onDelete: Restrict)
|
||||
mergedLead AdminLead @relation("AdminMergeMergedLead", fields: [mergedLeadId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@unique([mergedLeadId], name: "admin_merge_record_merged_lead_key")
|
||||
@@index([survivorLeadId, createdAt(sort: Desc)], name: "admin_merge_record_survivor_idx")
|
||||
@@index([actorAdminUserId, createdAt(sort: Desc)], name: "admin_merge_record_actor_idx")
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
// VA-P28d: tenant-less telephony for HiveGrid's own admin sales workspace.
|
||||
//
|
||||
// Aircall credentials remain in AdminDataConnection. Every operator-owned row
|
||||
// carries adminUserId so Postgres can enforce the platform-admin user context;
|
||||
// worker writes use the reviewed worker branch of the same policies.
|
||||
|
||||
enum AdminCallDirection {
|
||||
inbound
|
||||
outbound
|
||||
}
|
||||
|
||||
enum AdminCallStatus {
|
||||
ringing
|
||||
answered
|
||||
completed
|
||||
missed
|
||||
failed
|
||||
}
|
||||
|
||||
enum AdminCallMatchStatus {
|
||||
unmatched
|
||||
unique
|
||||
ambiguous
|
||||
confirmed
|
||||
}
|
||||
|
||||
enum AdminCallParticipantKind {
|
||||
admin
|
||||
contact
|
||||
lead
|
||||
external
|
||||
}
|
||||
|
||||
enum AdminCallRecordingStatus {
|
||||
pending
|
||||
processing
|
||||
clean
|
||||
rejected
|
||||
expired
|
||||
deleted
|
||||
}
|
||||
|
||||
enum AdminDialerListStatus {
|
||||
draft
|
||||
active
|
||||
paused
|
||||
completed
|
||||
}
|
||||
|
||||
enum AdminDialerEntryStatus {
|
||||
pending
|
||||
active
|
||||
completed
|
||||
skipped
|
||||
blocked
|
||||
}
|
||||
|
||||
enum AdminOutboundCallRequestStatus {
|
||||
pending
|
||||
processing
|
||||
accepted
|
||||
failed
|
||||
cancelled
|
||||
}
|
||||
|
||||
model AdminPhoneConnection {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
connectionId String @unique
|
||||
providerCompanyId String?
|
||||
providerUserId String?
|
||||
providerUserEmail String?
|
||||
defaultPhoneNumberId String?
|
||||
webhookTokenHash String? @unique
|
||||
webhookVerifiedAt DateTime?
|
||||
lastEventAt DateTime?
|
||||
|
||||
adminUser AdminUser @relation(fields: [adminUserId], references: [id], onDelete: Restrict)
|
||||
connection AdminDataConnection @relation(fields: [connectionId], references: [id], onDelete: Restrict)
|
||||
defaultPhoneNumber AdminPhoneNumber? @relation("AdminDefaultPhoneNumber", fields: [defaultPhoneNumberId], references: [id], onDelete: SetNull)
|
||||
phoneNumbers AdminPhoneNumber[] @relation("AdminPhoneConnectionNumbers")
|
||||
calls AdminCallSession[]
|
||||
outboundRequests AdminOutboundCallRequest[]
|
||||
|
||||
@@index([adminUserId, archivedAt], name: "admin_phone_connection_owner_archive_idx")
|
||||
@@index([providerCompanyId, archivedAt], name: "admin_phone_connection_company_idx")
|
||||
}
|
||||
|
||||
model AdminPhoneNumber {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
phoneConnectionId String
|
||||
providerNumberId String
|
||||
label String
|
||||
e164 String
|
||||
countryCode String?
|
||||
selected Boolean @default(true)
|
||||
|
||||
phoneConnection AdminPhoneConnection @relation("AdminPhoneConnectionNumbers", fields: [phoneConnectionId], references: [id], onDelete: Cascade)
|
||||
defaultFor AdminPhoneConnection[] @relation("AdminDefaultPhoneNumber")
|
||||
|
||||
@@unique([phoneConnectionId, providerNumberId], name: "admin_phone_number_provider_key")
|
||||
@@index([adminUserId, selected, archivedAt], name: "admin_phone_number_owner_selected_idx")
|
||||
@@index([e164, archivedAt], name: "admin_phone_number_e164_idx")
|
||||
}
|
||||
|
||||
model AdminTelephonyPolicy {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String @unique
|
||||
outboundEnabled Boolean @default(false)
|
||||
recordingEnabled Boolean @default(false)
|
||||
recordingConsentText String?
|
||||
recordingConsentVersion String?
|
||||
recordingConsentAt DateTime?
|
||||
recordingRetentionDays Int @default(90)
|
||||
dncEnforced Boolean @default(true)
|
||||
dailyCallLimit Int?
|
||||
workDayStartMinutes Int?
|
||||
workDayEndMinutes Int?
|
||||
workDays Int[] @default([])
|
||||
timeZone String?
|
||||
|
||||
@@index([outboundEnabled, adminUserId], name: "admin_telephony_policy_outbound_idx")
|
||||
@@index([recordingEnabled, adminUserId], name: "admin_telephony_policy_recording_idx")
|
||||
}
|
||||
|
||||
model AdminCallDisposition {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
code String @unique
|
||||
label String
|
||||
position Int @unique
|
||||
active Boolean @default(true)
|
||||
isSystem Boolean @default(true)
|
||||
|
||||
calls AdminCallSession[]
|
||||
|
||||
@@index([active, archivedAt, position], name: "admin_call_disposition_active_idx")
|
||||
}
|
||||
|
||||
model AdminCallSession {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
phoneConnectionId String
|
||||
providerCallId String
|
||||
direction AdminCallDirection
|
||||
status AdminCallStatus
|
||||
providerUserId String?
|
||||
fromNumber String
|
||||
toNumber String
|
||||
externalNumber String
|
||||
startedAt DateTime
|
||||
answeredAt DateTime?
|
||||
endedAt DateTime?
|
||||
durationSeconds Int?
|
||||
contactId String?
|
||||
leadId String?
|
||||
dealId String?
|
||||
matchStatus AdminCallMatchStatus @default(unmatched)
|
||||
matchConfidenceBasisPoints Int?
|
||||
note String?
|
||||
dispositionId String?
|
||||
dispositionCodeSnapshot String?
|
||||
dispositionLabelSnapshot String?
|
||||
callbackTaskId String? @unique
|
||||
recordingOffered Boolean @default(false)
|
||||
recordingConsentConfirmedAt DateTime?
|
||||
|
||||
phoneConnection AdminPhoneConnection @relation(fields: [phoneConnectionId], references: [id], onDelete: Restrict)
|
||||
contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: SetNull)
|
||||
lead AdminLead? @relation(fields: [leadId], references: [id], onDelete: SetNull)
|
||||
deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)
|
||||
disposition AdminCallDisposition? @relation(fields: [dispositionId], references: [id], onDelete: SetNull)
|
||||
callbackTask AdminTask? @relation(fields: [callbackTaskId], references: [id], onDelete: SetNull)
|
||||
participants AdminCallParticipant[]
|
||||
events AdminCallEvent[]
|
||||
matchCandidates AdminCallMatchCandidate[]
|
||||
recording AdminCallRecording?
|
||||
dialerEntry AdminDialerEntry?
|
||||
activities AdminActivity[]
|
||||
|
||||
@@unique([phoneConnectionId, providerCallId], name: "admin_call_provider_key")
|
||||
@@index([adminUserId, startedAt(sort: Desc)], name: "admin_call_owner_started_idx")
|
||||
@@index([contactId, startedAt(sort: Desc)], name: "admin_call_contact_started_idx")
|
||||
@@index([leadId, startedAt(sort: Desc)], name: "admin_call_lead_started_idx")
|
||||
@@index([dealId, startedAt(sort: Desc)], name: "admin_call_deal_started_idx")
|
||||
@@index([matchStatus, startedAt(sort: Desc)], name: "admin_call_match_queue_idx")
|
||||
@@index([status, startedAt], name: "admin_call_status_started_idx")
|
||||
}
|
||||
|
||||
model AdminCallParticipant {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
callSessionId String
|
||||
kind AdminCallParticipantKind
|
||||
externalId String?
|
||||
displayName String?
|
||||
phone String
|
||||
|
||||
callSession AdminCallSession @relation(fields: [callSessionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([callSessionId, kind, phone], name: "admin_call_participant_identity_key")
|
||||
@@index([adminUserId, createdAt(sort: Desc)], name: "admin_call_participant_owner_idx")
|
||||
}
|
||||
|
||||
model AdminCallEvent {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
callSessionId String
|
||||
dedupeKey String @unique
|
||||
providerEvent String
|
||||
status AdminCallStatus
|
||||
occurredAt DateTime
|
||||
durationSeconds Int?
|
||||
|
||||
callSession AdminCallSession @relation(fields: [callSessionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([adminUserId, occurredAt(sort: Desc)], name: "admin_call_event_owner_time_idx")
|
||||
@@index([callSessionId, occurredAt], name: "admin_call_event_session_time_idx")
|
||||
}
|
||||
|
||||
model AdminCallMatchCandidate {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
adminUserId String
|
||||
callSessionId String
|
||||
contactId String?
|
||||
leadId String?
|
||||
confidenceBasisPoints Int
|
||||
matchReason String
|
||||
|
||||
callSession AdminCallSession @relation(fields: [callSessionId], references: [id], onDelete: Cascade)
|
||||
contact AdminContact? @relation(fields: [contactId], references: [id], onDelete: Cascade)
|
||||
lead AdminLead? @relation(fields: [leadId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([callSessionId, contactId], name: "admin_call_match_contact_key")
|
||||
@@unique([callSessionId, leadId], name: "admin_call_match_lead_key")
|
||||
@@index([adminUserId, createdAt(sort: Desc)], name: "admin_call_match_candidate_owner_idx")
|
||||
}
|
||||
|
||||
model AdminCallRecording {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
callSessionId String @unique
|
||||
status AdminCallRecordingStatus @default(pending)
|
||||
providerUrlWrappedDek Bytes?
|
||||
providerUrlCiphertext String?
|
||||
providerUrlKeyVersion Int?
|
||||
storageBucket String?
|
||||
storageKey String?
|
||||
encryptedSizeBytes Int?
|
||||
checksumSha256 String?
|
||||
wrappedDek Bytes?
|
||||
iv Bytes?
|
||||
authTag Bytes?
|
||||
processingAt DateTime?
|
||||
attemptCount Int @default(0)
|
||||
lastErrorCode String?
|
||||
scannedAt DateTime?
|
||||
retainedUntil DateTime
|
||||
expiredAt DateTime?
|
||||
deletedAt DateTime?
|
||||
rejectionCode String?
|
||||
|
||||
callSession AdminCallSession @relation(fields: [callSessionId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@index([adminUserId, createdAt(sort: Desc)], name: "admin_call_recording_owner_idx")
|
||||
@@index([status, retainedUntil], name: "admin_call_recording_retention_idx")
|
||||
}
|
||||
|
||||
model AdminDialerList {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
adminUserId String
|
||||
name String
|
||||
status AdminDialerListStatus @default(draft)
|
||||
currentPosition Int?
|
||||
startedAt DateTime?
|
||||
completedAt DateTime?
|
||||
|
||||
entries AdminDialerEntry[]
|
||||
|
||||
@@index([adminUserId, status, updatedAt(sort: Desc)], name: "admin_dialer_list_owner_status_idx")
|
||||
}
|
||||
|
||||
model AdminDialerEntry {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
dialerListId String
|
||||
contactId String
|
||||
position Int
|
||||
status AdminDialerEntryStatus @default(pending)
|
||||
callSessionId String? @unique
|
||||
blockedReason String?
|
||||
activatedAt DateTime?
|
||||
completedAt DateTime?
|
||||
|
||||
dialerList AdminDialerList @relation(fields: [dialerListId], references: [id], onDelete: Cascade)
|
||||
contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Restrict)
|
||||
callSession AdminCallSession? @relation(fields: [callSessionId], references: [id], onDelete: SetNull)
|
||||
outboundRequests AdminOutboundCallRequest[]
|
||||
|
||||
@@unique([dialerListId, position], name: "admin_dialer_entry_position_key")
|
||||
@@unique([dialerListId, contactId], name: "admin_dialer_entry_contact_key")
|
||||
@@index([adminUserId, status, createdAt], name: "admin_dialer_entry_owner_status_idx")
|
||||
}
|
||||
|
||||
model AdminOutboundCallRequest {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
adminUserId String
|
||||
phoneConnectionId String
|
||||
contactId String
|
||||
dealId String?
|
||||
dialerEntryId String?
|
||||
idempotencyKey String @unique
|
||||
destinationE164 String
|
||||
status AdminOutboundCallRequestStatus @default(pending)
|
||||
requestedAt DateTime @default(now())
|
||||
processingAt DateTime?
|
||||
acceptedAt DateTime?
|
||||
failedAt DateTime?
|
||||
attemptCount Int @default(0)
|
||||
errorCode String?
|
||||
|
||||
phoneConnection AdminPhoneConnection @relation(fields: [phoneConnectionId], references: [id], onDelete: Restrict)
|
||||
contact AdminContact @relation(fields: [contactId], references: [id], onDelete: Restrict)
|
||||
deal AdminDeal? @relation(fields: [dealId], references: [id], onDelete: SetNull)
|
||||
dialerEntry AdminDialerEntry? @relation(fields: [dialerEntryId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([adminUserId, status, requestedAt], name: "admin_outbound_call_owner_status_idx")
|
||||
@@index([status, requestedAt], name: "admin_outbound_call_worker_queue_idx")
|
||||
@@index([contactId, requestedAt(sort: Desc)], name: "admin_outbound_call_contact_idx")
|
||||
}
|
||||
@@ -33,6 +33,8 @@ model AnalyticsUniqueVisitor {
|
||||
portal Portal? @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
portalUserId String?
|
||||
portalUser PortalUser? @relation(fields: [portalUserId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([portalId, createdAt])
|
||||
}
|
||||
|
||||
model AnalyticsPageView {
|
||||
@@ -46,6 +48,9 @@ model AnalyticsPageView {
|
||||
portal Portal? @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
portalUserId String?
|
||||
portalUser PortalUser? @relation(fields: [portalUserId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([portalId, createdAt])
|
||||
@@index([uniqueVisitorId])
|
||||
}
|
||||
|
||||
model AnalyticsEvent {
|
||||
@@ -60,9 +65,13 @@ model AnalyticsEvent {
|
||||
url String?
|
||||
route String?
|
||||
featureFlagId String?
|
||||
featureFlag FeatureFlag? @relation(fields: [featureFlagId], references: [id])
|
||||
featureFlag FeatureFlag? @relation(fields: [featureFlagId], references: [id], onDelete: SetNull)
|
||||
portalId String?
|
||||
portal Portal? @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
portalUserId String?
|
||||
portalUser PortalUser? @relation(fields: [portalUserId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([featureFlagId])
|
||||
@@index([portalId, createdAt])
|
||||
@@index([uniqueVisitorId])
|
||||
}
|
||||
@@ -77,6 +77,14 @@ enum AppSyncItemStatus {
|
||||
skipped
|
||||
}
|
||||
|
||||
enum AppEntityBindingState {
|
||||
active
|
||||
quarantined
|
||||
missing
|
||||
ignored
|
||||
unlinked
|
||||
}
|
||||
|
||||
/// Global catalog definition of an integratable app (no tenant, no RLS). The
|
||||
/// `connectionSchema` drives the auto-generated credential form; `connectionType`
|
||||
/// selects the connect flow. New apps are registered by the build-time adapter
|
||||
@@ -121,7 +129,8 @@ model DataConnection {
|
||||
isDemoData Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
|
||||
syncRuns AppSyncRun[]
|
||||
syncRuns AppSyncRun[]
|
||||
entityBindings AppEntityBinding[]
|
||||
|
||||
@@index([tenantId, appId, archivedAt])
|
||||
@@index([tenantId, connectionStatus])
|
||||
@@ -189,3 +198,33 @@ model AppSyncItem {
|
||||
@@index([tenantId, entityType, entityId])
|
||||
@@index([tenantId, externalId])
|
||||
}
|
||||
|
||||
/// Durable provider-neutral identity mapping. AppSyncItem remains the history
|
||||
/// of one run; this row survives runs, reconnects and process restarts.
|
||||
model AppEntityBinding {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
dataConnectionId String
|
||||
externalEntityType String
|
||||
localEntityType String
|
||||
externalId String
|
||||
localId String
|
||||
state AppEntityBindingState @default(active)
|
||||
normalizedSnapshot Json
|
||||
fingerprint String
|
||||
overwrittenLocalSnapshot Json?
|
||||
revision Int @default(1)
|
||||
lastSeenAt DateTime?
|
||||
lastSyncedAt DateTime?
|
||||
missingSince DateTime?
|
||||
unlinkedAt DateTime?
|
||||
|
||||
dataConnection DataConnection @relation(fields: [dataConnectionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([tenantId, dataConnectionId, externalEntityType, externalId])
|
||||
@@unique([tenantId, dataConnectionId, localEntityType, localId])
|
||||
@@index([tenantId, dataConnectionId, state, lastSyncedAt])
|
||||
@@index([tenantId, localEntityType, localId, state])
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
model AuditChainCheckpoint {
|
||||
id String @id
|
||||
createdAt DateTime
|
||||
chainKey String
|
||||
tenantId String?
|
||||
deletedThroughAt DateTime
|
||||
lastDeletedEventId String
|
||||
lastDeletedEventHash String?
|
||||
deletedCount Int
|
||||
previousCheckpointMac String?
|
||||
checkpointMac String @unique
|
||||
|
||||
@@index([chainKey, createdAt(sort: Desc)], name: "audit_checkpoint_chain_created_at_idx")
|
||||
@@index([tenantId, createdAt(sort: Desc)], name: "audit_checkpoint_tenant_created_at_idx")
|
||||
}
|
||||
|
||||
model AuditChainHead {
|
||||
chainKey String @id
|
||||
tenantId String?
|
||||
eventId String
|
||||
eventHash String
|
||||
eventCreatedAt DateTime
|
||||
headMac String
|
||||
|
||||
@@index([tenantId], name: "audit_chain_head_tenant_idx")
|
||||
}
|
||||
|
||||
model AuditChainCheckpointHead {
|
||||
chainKey String @id
|
||||
tenantId String?
|
||||
checkpointId String @unique
|
||||
checkpointMac String
|
||||
updatedAt DateTime
|
||||
|
||||
@@index([tenantId], name: "audit_checkpoint_head_tenant_idx")
|
||||
}
|
||||
@@ -106,9 +106,18 @@ model ProjektMitglied {
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
|
||||
projekt Projekt @relation(fields: [projektId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([tenantId, projektId, archivedAt])
|
||||
@@index([tenantId, userId])
|
||||
@@index([tenantId, groupId])
|
||||
@@index([tenantId, userId, archivedAt, projektId])
|
||||
@@index([tenantId, groupId, archivedAt, projektId])
|
||||
}
|
||||
|
||||
/// WF-P8 S02-T: appointment kind offered by the "Termin erstellen" modal.
|
||||
enum ProjektTerminTyp {
|
||||
vor_ort
|
||||
telefon
|
||||
online
|
||||
}
|
||||
|
||||
model ProjektTermin {
|
||||
@@ -123,6 +132,8 @@ model ProjektTermin {
|
||||
startAt DateTime
|
||||
endAt DateTime?
|
||||
status ProjektTerminStatus @default(geplant)
|
||||
/// WF-P8 S02-T. Defaults to the on-site case, which is the SHK norm.
|
||||
typ ProjektTerminTyp @default(vor_ort)
|
||||
isDemoData Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -143,6 +154,12 @@ model Rechnung {
|
||||
status RechnungStatus @default(entwurf)
|
||||
datum DateTime @default(now())
|
||||
faelligAm DateTime?
|
||||
/// Set when the invoice moves to `bezahlt`, cleared when it moves away again.
|
||||
/// `updatedAt` cannot stand in for this: any later edit overwrites it, which
|
||||
/// makes revenue by payment date and days-to-payment unmeasurable. Invoices
|
||||
/// already marked paid before this field existed stay null and are excluded
|
||||
/// from payment-date reporting rather than counted at a wrong date.
|
||||
bezahltAm DateTime?
|
||||
dateiId String?
|
||||
quelle RechnungQuelle @default(manuell)
|
||||
isDemoData Boolean @default(false)
|
||||
@@ -153,6 +170,7 @@ model Rechnung {
|
||||
@@unique([tenantId, rechnungsnummer])
|
||||
@@index([tenantId, projektId, archivedAt])
|
||||
@@index([tenantId, status])
|
||||
@@index([tenantId, bezahltAm])
|
||||
@@index([tenantId, dateiId])
|
||||
}
|
||||
|
||||
@@ -168,7 +186,8 @@ model ProjektChecklist {
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
|
||||
items ProjektChecklistItem[]
|
||||
projekt Projekt @relation(fields: [projektId], references: [id], onDelete: Cascade)
|
||||
items ProjektChecklistItem[]
|
||||
|
||||
@@index([tenantId, projektId, typ, archivedAt])
|
||||
}
|
||||
@@ -189,7 +208,7 @@ model ProjektChecklistItem {
|
||||
|
||||
checklist ProjektChecklist @relation(fields: [checklistId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([tenantId, checklistId])
|
||||
@@index([tenantId, checklistId, status])
|
||||
@@index([tenantId, status])
|
||||
@@index([tenantId, fotoFileId])
|
||||
}
|
||||
|
||||
@@ -14,9 +14,10 @@
|
||||
// READ-ONLY through the bare `dataConnectionId` scalar — calendar owns its own
|
||||
// per-user connection lifecycle (RLS here is tenant- AND owner-scoped in code).
|
||||
//
|
||||
// RLS ships separately in prisma/rls/calendar-isolation.sql (deferred cutover
|
||||
// like the other modules). On the feature branch: `prisma db push` only — the
|
||||
// merge migration is created at main-merge (AD-21). Leak-protection (DoD 3):
|
||||
// RLS is LIVE since 20260713190000_appwide_rls_cutover (ENABLE+FORCE on all
|
||||
// calendar tables); prisma/rls/calendar-isolation.sql remains the
|
||||
// feature-branch template for db-push-only databases. Tables are tracked in
|
||||
// 20260703150000_ak_schema_parity_catchup. Leak-protection (DoD 3):
|
||||
// external event contents are owner-only; availability exposes busy slots only.
|
||||
|
||||
/// Calendar provider. v1 = google; microsoft → v2 (interface stays agnostic).
|
||||
@@ -173,6 +174,7 @@ model CalendarEventMapping {
|
||||
|
||||
@@unique([internalEventId, provider, externalCalendarId])
|
||||
@@index([tenantId, connectionId])
|
||||
@@index([tenantId, connectionId, provider, externalEventId])
|
||||
}
|
||||
|
||||
/// Per-connection-per-calendar delta cursor (Google syncToken). Drives the
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
// AK-P15b (P15) Team Chat — typed internal chat domain model.
|
||||
//
|
||||
// AD-21: this module owns its schema. Cross-module identifiers such as
|
||||
// `tenantId`, `createdByUserId`, `userId`, and `projektId` remain bare String
|
||||
// scalars so shared Tenant, User, and Projekt schemas need no back-relations.
|
||||
// Attachments use FileEntityLink with FileEntityType.chat_message instead of a
|
||||
// second attachment model. All relations below stay inside this module.
|
||||
|
||||
enum TeamChatKind {
|
||||
project
|
||||
group
|
||||
dm
|
||||
}
|
||||
|
||||
enum TeamChatArchivedReason {
|
||||
manual
|
||||
project_completed
|
||||
project_cancelled
|
||||
}
|
||||
|
||||
enum TeamChatNotificationPreference {
|
||||
all_messages
|
||||
mentions_only
|
||||
muted
|
||||
}
|
||||
|
||||
enum TeamChatMemberRole {
|
||||
admin
|
||||
member
|
||||
}
|
||||
|
||||
enum TeamChatMessageFormat {
|
||||
markdown
|
||||
system
|
||||
}
|
||||
|
||||
enum TeamChatSystemEventKind {
|
||||
group_created
|
||||
project_created
|
||||
project_leader_changed
|
||||
member_write_access_changed
|
||||
member_added
|
||||
member_removed
|
||||
channel_renamed
|
||||
channel_privacy_changed
|
||||
channel_archived
|
||||
project_stage_changed
|
||||
acceptance_completed
|
||||
task_created
|
||||
}
|
||||
|
||||
/// Durable mutation types used for WebSocket reconnect gap-fill. Presence and
|
||||
/// typing are intentionally absent because they are ephemeral Redis signals.
|
||||
enum TeamChatEventType {
|
||||
message_created @map("chat.message.created")
|
||||
message_updated @map("chat.message.updated")
|
||||
message_deleted @map("chat.message.deleted")
|
||||
reaction_added @map("chat.reaction.added")
|
||||
reaction_removed @map("chat.reaction.removed")
|
||||
thread_reply @map("chat.thread.reply")
|
||||
read_updated @map("chat.read.updated")
|
||||
member_added @map("chat.member.added")
|
||||
member_removed @map("chat.member.removed")
|
||||
channel_archived @map("chat.channel.archived")
|
||||
message_pin_changed @map("chat.message.pin_changed")
|
||||
link_preview_ready @map("chat.link_preview.ready")
|
||||
}
|
||||
|
||||
/// A project-linked, group, or direct-message channel. Project and direct
|
||||
/// message channels are always private; group privacy is selected at creation.
|
||||
/// The merge migration enforces kind-specific CHECK constraints and partial
|
||||
/// unique indexes for active project channels and direct-message pairs.
|
||||
model TeamChat {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
// System-created project channels may not have a user actor (for example,
|
||||
// an automated qualified-lead conversion), so ownership is tenant-scoped
|
||||
// and the creator remains optional.
|
||||
createdByUserId String?
|
||||
kind TeamChatKind
|
||||
name String?
|
||||
description String?
|
||||
projektId String?
|
||||
isPrivate Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
archivedReason TeamChatArchivedReason?
|
||||
lastMessageAt DateTime?
|
||||
notificationDefault TeamChatNotificationPreference @default(all_messages)
|
||||
eventStreamId String @unique @default(cuid())
|
||||
// Canonically sorted user ids let the merge migration enforce one active DM
|
||||
// per tenant and member pair with a partial unique index.
|
||||
dmPairKey String?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
members TeamChatMember[]
|
||||
groupSources TeamChatGroupSource[]
|
||||
messages TeamChatMessage[]
|
||||
threads TeamChatThread[]
|
||||
pinnedMessages TeamChatPinnedMessage[]
|
||||
events TeamChatEvent[]
|
||||
|
||||
@@unique([id, tenantId])
|
||||
@@index([tenantId, kind, archivedAt, lastMessageAt(sort: Desc)])
|
||||
@@index([tenantId, projektId])
|
||||
@@index([tenantId, dmPairKey, archivedAt])
|
||||
}
|
||||
|
||||
/// Permission-group sources selected while creating a group chat. Sources are
|
||||
/// kept even when synchronization is disabled so the channel configuration is
|
||||
/// explicit and can be enabled later without guessing its original scope.
|
||||
/// `groupId` deliberately remains a bare cross-module identifier (AD-21).
|
||||
model TeamChatGroupSource {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
tenantId String
|
||||
chatId String
|
||||
groupId String
|
||||
syncEnabled Boolean @default(false)
|
||||
|
||||
chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([chatId, groupId])
|
||||
@@index([tenantId, groupId, syncEnabled])
|
||||
@@index([tenantId, chatId])
|
||||
}
|
||||
|
||||
/// Append-only event ledger for reconnect gap-fill. The wire cursor combines
|
||||
/// the channel's `eventStreamId` with `sequence`, which is serialized as a
|
||||
/// decimal string so JavaScript clients never lose BigInt precision. Redis
|
||||
/// fans these events out but is never their source of truth.
|
||||
model TeamChatEvent {
|
||||
id String @id @default(cuid())
|
||||
sequence BigInt @unique @default(autoincrement())
|
||||
occurredAt DateTime @default(now())
|
||||
tenantId String
|
||||
chatId String
|
||||
type TeamChatEventType
|
||||
actorUserId String?
|
||||
entityId String?
|
||||
requestId String
|
||||
data Json
|
||||
|
||||
chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
|
||||
@@index([tenantId, chatId, sequence])
|
||||
@@index([tenantId, actorUserId, occurredAt(sort: Desc)])
|
||||
}
|
||||
|
||||
/// One user's membership and per-channel notification/read preferences.
|
||||
/// Rejoining reactivates the existing row by clearing `leftAt`.
|
||||
model TeamChatMember {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
chatId String
|
||||
userId String
|
||||
joinedAt DateTime @default(now())
|
||||
joinedViaUserId String?
|
||||
// Materialized effective role. Source-specific roles below remain
|
||||
// independent so losing one grant can deterministically fall back to the
|
||||
// strongest remaining grant without retaining stale admin privileges.
|
||||
roleInChat TeamChatMemberRole @default(member)
|
||||
notificationPref TeamChatNotificationPreference
|
||||
lastReadMessageId String?
|
||||
lastReadAt DateTime?
|
||||
isPinned Boolean @default(false)
|
||||
// Membership can have independent manual, project, and permission-group
|
||||
// origins. A manually invited project guest survives project reconciliation,
|
||||
// while later grants reuse this row without overwriting another source.
|
||||
isProjectManaged Boolean @default(false)
|
||||
isManualMember Boolean @default(true)
|
||||
manualRoleInChat TeamChatMemberRole?
|
||||
projectRoleInChat TeamChatMemberRole?
|
||||
// Group-managed membership is independent from an explicit invitation. A
|
||||
// user remains active when either source is still present.
|
||||
isGroupManaged Boolean @default(false)
|
||||
// Leaving an auto-synced group channel is a durable user decision. Group
|
||||
// reconciliation retains provenance but never reactivates an opted-out row;
|
||||
// an explicit join/invite clears this timestamp.
|
||||
groupSyncOptOutAt DateTime?
|
||||
// Former project members keep the immutable channel history readable until
|
||||
// archive, but may no longer publish mutations unless another membership
|
||||
// source grants write access again.
|
||||
writeRevokedAt DateTime?
|
||||
leftAt DateTime?
|
||||
|
||||
chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
lastReadMessage TeamChatMessage? @relation("TeamChatMemberLastReadMessage", fields: [lastReadMessageId, tenantId, chatId], references: [id, tenantId, chatId], onDelete: NoAction)
|
||||
|
||||
@@unique([chatId, userId])
|
||||
@@index([tenantId, userId, leftAt])
|
||||
@@index([tenantId, chatId, userId])
|
||||
}
|
||||
|
||||
/// A channel message or one-level thread reply. User-authored sends use a
|
||||
/// stable client id so retries and WebSocket echoes remain idempotent.
|
||||
model TeamChatMessage {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
chatId String
|
||||
// System timeline entries may be emitted by automation without a user
|
||||
// actor. User-authored messages always keep their concrete author id.
|
||||
authorUserId String?
|
||||
clientMessageId String
|
||||
body String
|
||||
bodyFormat TeamChatMessageFormat @default(markdown)
|
||||
parentMessageId String?
|
||||
mentions Json @default("[]")
|
||||
linkPreviews Json @default("[]")
|
||||
editedAt DateTime?
|
||||
deletedAt DateTime?
|
||||
deletedByUserId String?
|
||||
// Stable domain-event key. System hooks retry with the same key so one
|
||||
// semantic event creates exactly one timeline entry per channel.
|
||||
systemEventKey String?
|
||||
systemEventKind TeamChatSystemEventKind?
|
||||
systemEventMetadata Json?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
parentMessage TeamChatMessage? @relation("TeamChatMessageReplies", fields: [parentMessageId, tenantId, chatId], references: [id, tenantId, chatId], onDelete: Cascade)
|
||||
replies TeamChatMessage[] @relation("TeamChatMessageReplies")
|
||||
thread TeamChatThread? @relation("TeamChatThreadParent")
|
||||
pinnedRecords TeamChatPinnedMessage[]
|
||||
reactions TeamChatReaction[]
|
||||
reads TeamChatRead[]
|
||||
lastReadByMembers TeamChatMember[] @relation("TeamChatMemberLastReadMessage")
|
||||
|
||||
@@unique([tenantId, authorUserId, clientMessageId])
|
||||
@@unique([tenantId, chatId, clientMessageId])
|
||||
@@unique([tenantId, chatId, systemEventKey])
|
||||
@@unique([id, tenantId])
|
||||
@@unique([id, tenantId, chatId])
|
||||
@@index([tenantId, chatId, parentMessageId, createdAt(sort: Desc)])
|
||||
@@index([mentions], type: Gin, map: "TeamChatMessage_mentions_gin_idx")
|
||||
@@index([body(ops: raw("gin_trgm_ops"))], type: Gin, map: "TeamChatMessage_body_trgm_idx")
|
||||
}
|
||||
|
||||
/// Denormalized aggregate for the one-level reply list of a parent message.
|
||||
model TeamChatThread {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
chatId String
|
||||
parentMessageId String
|
||||
createdAt DateTime @default(now())
|
||||
createdByUserId String
|
||||
lastReplyAt DateTime
|
||||
replyCount Int @default(0)
|
||||
participantUserIds String[] @default([])
|
||||
|
||||
chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
parentMessage TeamChatMessage @relation("TeamChatThreadParent", fields: [parentMessageId, tenantId, chatId], references: [id, tenantId, chatId], onDelete: Cascade)
|
||||
|
||||
@@unique([parentMessageId, tenantId, chatId])
|
||||
@@index([tenantId, chatId, lastReplyAt(sort: Desc)])
|
||||
}
|
||||
|
||||
/// A channel-level message pin. Domain guards enforce the 50-pin limit and
|
||||
/// reject message pins for direct-message channels.
|
||||
model TeamChatPinnedMessage {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
chatId String
|
||||
messageId String
|
||||
pinnedByUserId String
|
||||
pinnedAt DateTime @default(now())
|
||||
note String?
|
||||
|
||||
chat TeamChat @relation(fields: [chatId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
message TeamChatMessage @relation(fields: [messageId, tenantId, chatId], references: [id, tenantId, chatId], onDelete: Cascade)
|
||||
|
||||
@@unique([chatId, messageId])
|
||||
@@index([tenantId, chatId, pinnedAt(sort: Desc)])
|
||||
}
|
||||
|
||||
/// One user's Unicode emoji reaction to a message.
|
||||
model TeamChatReaction {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
messageId String
|
||||
userId String
|
||||
emoji String
|
||||
reactedAt DateTime @default(now())
|
||||
|
||||
message TeamChatMessage @relation(fields: [messageId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([messageId, userId, emoji])
|
||||
@@index([tenantId, messageId, reactedAt])
|
||||
}
|
||||
|
||||
/// Per-user read receipt written only after a message was visibly read.
|
||||
model TeamChatRead {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
messageId String
|
||||
userId String
|
||||
readAt DateTime @default(now())
|
||||
|
||||
message TeamChatMessage @relation(fields: [messageId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([messageId, userId])
|
||||
@@index([tenantId, messageId, userId])
|
||||
}
|
||||
@@ -88,14 +88,20 @@ model IdempotencyKey {
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
expiresAt DateTime?
|
||||
tenantId String?
|
||||
partitionKey String
|
||||
systemOwned Boolean @default(false)
|
||||
scope String
|
||||
key String
|
||||
requestHash String
|
||||
responseStatus Int
|
||||
responseBody Json?
|
||||
responseHeaders Json?
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([scope, key], name: "idempotency_key_scope_key")
|
||||
@@unique([partitionKey, scope, key], name: "idempotency_key_partition_scope_key", map: "idempotency_key_partition_scope_key")
|
||||
@@index([tenantId, expiresAt], name: "idempotency_key_tenant_expires_at_idx")
|
||||
@@index([systemOwned, expiresAt], name: "idempotency_key_system_expires_at_idx")
|
||||
@@index([expiresAt], name: "idempotency_key_expires_at_idx")
|
||||
}
|
||||
|
||||
@@ -154,9 +160,9 @@ model Event {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
tenantId String?
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id])
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: SetNull)
|
||||
userId String?
|
||||
user User? @relation(fields: [userId], references: [id])
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
name String
|
||||
data String
|
||||
resource String?
|
||||
|
||||
@@ -76,6 +76,14 @@ enum CustomFieldDatentyp {
|
||||
email
|
||||
telefon
|
||||
datei
|
||||
// WF-P8 S05: the remaining types Davids field picker offers. Added to the
|
||||
// shared enum so the picker can store them; value rendering is a plain text
|
||||
// box for every type today, new and old alike.
|
||||
prozent
|
||||
datum_zeit
|
||||
person_team
|
||||
adresse
|
||||
link
|
||||
}
|
||||
|
||||
/// A contact (Kontakt), the CRM core entity. Oberbegriff for both private persons
|
||||
@@ -96,6 +104,23 @@ model Kontakt {
|
||||
// Organisation fields (kontaktTyp = organisation).
|
||||
orgName String?
|
||||
orgMerkmal OrgMerkmal?
|
||||
// WF-P8 S02 company card (P8 baseline, consumed read-only there). Company
|
||||
// master data belongs to the contact, not to a project: the same company shows
|
||||
// up on many projects, and duplicating these per project would fork the truth.
|
||||
website String?
|
||||
ustIdNr String?
|
||||
handelsregister String?
|
||||
kundennummer String?
|
||||
kundeSeit DateTime?
|
||||
branche String?
|
||||
mitarbeiterzahl Int?
|
||||
// WF-P8 S02 contact-person card (kontaktTyp = privatperson).
|
||||
position String?
|
||||
erreichbarkeit String?
|
||||
// Free text on both card types: the standing arrangements with this contact
|
||||
// (how they want to be invoiced, who decides, when to call). Not the activity
|
||||
// timeline — that records what happened, this is what stays true.
|
||||
notizen String?
|
||||
// Denormalised primary channels, kept in sync from KontaktEmail/KontaktTelefon
|
||||
// by the service so list/dup-check queries stay single-table.
|
||||
primaerEmail String?
|
||||
@@ -161,13 +186,24 @@ model KontaktEmail {
|
||||
|
||||
/// One of a contact's phone numbers. Exactly one carries `primaer = true`
|
||||
/// (enforced in the service), mirrored to `Kontakt.primaerTelefon`.
|
||||
/// WF-P8 S02 asks for "Durchwahl" and "Mobil" next to the main number. That is a
|
||||
/// kind of number, not two more scalars on Kontakt — a contact can have several
|
||||
/// of each, which is exactly what KontaktTelefon already models.
|
||||
enum KontaktTelefonTyp {
|
||||
haupt
|
||||
durchwahl
|
||||
mobil
|
||||
fax
|
||||
}
|
||||
|
||||
model KontaktTelefon {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
tenantId String
|
||||
kontaktId String
|
||||
telefon String
|
||||
primaer Boolean @default(false)
|
||||
typ KontaktTelefonTyp @default(haupt)
|
||||
primaer Boolean @default(false)
|
||||
|
||||
kontakt Kontakt @relation(fields: [kontaktId], references: [id], onDelete: Cascade)
|
||||
|
||||
|
||||
@@ -155,6 +155,7 @@ model OutboundEmail {
|
||||
clicks OutboundEmailClick[]
|
||||
|
||||
@@index([tenantId, sentAt])
|
||||
@@index([tenantId, campaignId, kontaktId])
|
||||
}
|
||||
|
||||
model OutboundEmailOpen {
|
||||
|
||||
@@ -24,6 +24,8 @@ enum LinkableEntityType {
|
||||
order
|
||||
appointment
|
||||
form_submission
|
||||
// AK-P15b · source message for an idempotently created task.
|
||||
chat_message
|
||||
}
|
||||
|
||||
/// A directed, role-labelled link from one entity to another, scoped per tenant.
|
||||
|
||||
@@ -1,56 +1,105 @@
|
||||
enum FeatureFlagLifecycleStage {
|
||||
beta
|
||||
rollout
|
||||
ga
|
||||
deprecated
|
||||
}
|
||||
|
||||
model FeatureFlag {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
key String?
|
||||
scope String @default("global")
|
||||
tenantId String?
|
||||
userId String?
|
||||
name String
|
||||
description String
|
||||
enabled Boolean @default(false)
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
key String?
|
||||
scope String @default("global")
|
||||
tenantId String?
|
||||
userId String?
|
||||
name String
|
||||
description String
|
||||
enabled Boolean @default(false)
|
||||
defaultValue Boolean?
|
||||
lifecycleStage FeatureFlagLifecycleStage @default(beta)
|
||||
ownerAdminUserId String?
|
||||
targetModule String?
|
||||
archivedAt DateTime?
|
||||
// v2 targeting engine fields (task #53). All nullable / defaulted so
|
||||
// legacy rows continue to evaluate via boolean `enabled` only.
|
||||
rules Json?
|
||||
variants Json[] @default([])
|
||||
enabledFrom DateTime?
|
||||
enabledUntil DateTime?
|
||||
parentFlagId String?
|
||||
parentFlag FeatureFlag? @relation("FeatureFlagDependency", fields: [parentFlagId], references: [id], onDelete: SetNull)
|
||||
childFlags FeatureFlag[] @relation("FeatureFlagDependency")
|
||||
audits FeatureFlagAudit[]
|
||||
events AnalyticsEvent[]
|
||||
filters FeatureFlagFilter[]
|
||||
rules Json?
|
||||
variants Json[] @default([])
|
||||
enabledFrom DateTime?
|
||||
enabledUntil DateTime?
|
||||
parentFlagId String?
|
||||
parentFlag FeatureFlag? @relation("FeatureFlagDependency", fields: [parentFlagId], references: [id], onDelete: SetNull)
|
||||
childFlags FeatureFlag[] @relation("FeatureFlagDependency")
|
||||
audits FeatureFlagAudit[]
|
||||
events AnalyticsEvent[]
|
||||
filters FeatureFlagFilter[]
|
||||
tenantOverrides AdminFeatureFlagOverride[]
|
||||
|
||||
@@unique([name, description])
|
||||
@@index([key, scope], name: "feature_flag_key_scope_idx")
|
||||
@@index([tenantId, key], name: "feature_flag_tenant_key_idx")
|
||||
@@index([userId, key], name: "feature_flag_user_key_idx")
|
||||
@@index([parentFlagId], name: "feature_flag_parent_idx")
|
||||
@@index([lifecycleStage, archivedAt], name: "feature_flag_lifecycle_archive_idx")
|
||||
@@index([ownerAdminUserId, archivedAt], name: "feature_flag_owner_archive_idx")
|
||||
@@index([targetModule, archivedAt], name: "feature_flag_module_archive_idx")
|
||||
}
|
||||
|
||||
model FeatureFlagFilter {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
featureFlagId String
|
||||
featureFlag FeatureFlag @relation(fields: [featureFlagId], references: [id], onDelete: Cascade)
|
||||
type String // [FeatureFlagsFilterType] percentage, darkMode, language.is, page.is, analytics.browser.is...
|
||||
value String? // 0-100, true, false, en, de, fr, ...
|
||||
action String?
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
featureFlagId String
|
||||
featureFlag FeatureFlag @relation(fields: [featureFlagId], references: [id], onDelete: Cascade)
|
||||
type String // [FeatureFlagsFilterType] percentage, darkMode, language.is, page.is, analytics.browser.is...
|
||||
value String? // 0-100, true, false, en, de, fr, ...
|
||||
action String?
|
||||
name String @default("Legacy filter")
|
||||
priority Int @default(0)
|
||||
resultValue Boolean?
|
||||
criteria Json?
|
||||
active Boolean @default(true)
|
||||
createdByAdminUserId String?
|
||||
|
||||
@@index([featureFlagId, active, priority, createdAt], name: "feature_flag_filter_evaluation_idx")
|
||||
}
|
||||
|
||||
/// Operator-managed rollout override. This is deliberately not the
|
||||
/// subscription/entitlement TenantFeatureOverride model.
|
||||
model AdminFeatureFlagOverride {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
featureFlagId String
|
||||
tenantId String
|
||||
value Boolean
|
||||
note String?
|
||||
expiresAt DateTime?
|
||||
setByAdminUserId String
|
||||
|
||||
featureFlag FeatureFlag @relation(fields: [featureFlagId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([featureFlagId, tenantId], name: "admin_feature_flag_override_flag_tenant_key")
|
||||
@@index([tenantId, featureFlagId], name: "admin_feature_flag_override_tenant_flag_idx")
|
||||
@@index([featureFlagId, expiresAt], name: "admin_feature_flag_override_expiry_idx")
|
||||
@@index([setByAdminUserId, updatedAt], name: "admin_feature_flag_override_actor_idx")
|
||||
}
|
||||
|
||||
/// Append-only audit trail for every mutation of a FeatureFlag (create / update / delete / toggle).
|
||||
/// Never UPDATE or DELETE rows from app code — preserves tamper-resistance for compliance.
|
||||
model FeatureFlagAudit {
|
||||
id String @id @default(cuid())
|
||||
flagId String
|
||||
flag FeatureFlag @relation(fields: [flagId], references: [id], onDelete: Cascade)
|
||||
actorUserId String?
|
||||
action String // create | update | delete | toggle
|
||||
oldValue Json?
|
||||
newValue Json?
|
||||
createdAt DateTime @default(now())
|
||||
id String @id @default(cuid())
|
||||
flagId String
|
||||
flag FeatureFlag @relation(fields: [flagId], references: [id], onDelete: Cascade)
|
||||
actorUserId String?
|
||||
actorType String @default("admin")
|
||||
action String // create | update | delete | toggle
|
||||
oldValue Json?
|
||||
newValue Json?
|
||||
metadata Json?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([flagId, createdAt], name: "feature_flag_audit_flag_idx")
|
||||
@@index([actorUserId, createdAt], name: "feature_flag_audit_actor_idx")
|
||||
@@index([actorType, createdAt], name: "feature_flag_audit_scope_idx")
|
||||
}
|
||||
@@ -62,6 +62,13 @@ enum FileEntityType {
|
||||
// VA-P23 · mirrored mailbox message (email-inbox attachments -> Files).
|
||||
// ADDITIVE cross-module touch of files.prisma, flagged per AD-21.
|
||||
email_message
|
||||
// AK-P15b · Team Chat attachment linked through FileEntityLink.
|
||||
// ADDITIVE cross-module touch of files.prisma, flagged per AD-21.
|
||||
chat_message
|
||||
// AK-P21 · in-app feedback attachment (SupportTicket) linked through
|
||||
// FileEntityLink. ADDITIVE cross-module touch of files.prisma, flagged per
|
||||
// AD-21.
|
||||
support_ticket
|
||||
}
|
||||
|
||||
/// A stored file, scoped per tenant. `storageKey` points at the original object
|
||||
@@ -73,7 +80,10 @@ model File {
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
createdByUserId String
|
||||
/// Exactly one of createdByUserId / createdByPortalUserId must be non-null.
|
||||
/// The merge migration adds the database CHECK; shared service helpers enforce
|
||||
/// the same invariant while feature branches use prisma db push (AD-21).
|
||||
createdByUserId String?
|
||||
displayName String
|
||||
mimeType String
|
||||
sizeBytes Int
|
||||
@@ -87,16 +97,18 @@ model File {
|
||||
tags String[] @default([])
|
||||
notes String?
|
||||
source FileSource @default(manual_upload)
|
||||
// Customer-portal upload prepared (DoD 12): nullable attribution, full portal
|
||||
// flow = v2. Defaults to empty/invisible.
|
||||
createdByPortalUserId String?
|
||||
isDemoData Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
|
||||
links FileEntityLink[]
|
||||
createdByPortalUser PortalUser? @relation("PortalFileActor", fields: [createdByPortalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
portalDocuments PortalProjectDocument[]
|
||||
|
||||
@@unique([id, tenantId])
|
||||
@@index([tenantId, archivedAt, createdAt(sort: Desc)])
|
||||
@@index([tenantId, createdByUserId])
|
||||
@@index([tenantId, createdByPortalUserId])
|
||||
@@index([tenantId, assignedToUserId])
|
||||
@@index([tenantId, checksumSha256])
|
||||
// pg_trgm GIN index for fast ILIKE search on displayName; created originally
|
||||
@@ -112,17 +124,21 @@ model FileEntityLink {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
tenantId String
|
||||
createdByUserId String
|
||||
/// Exactly one actor column is set; see the merge-migration CHECK contract.
|
||||
createdByUserId String?
|
||||
createdByPortalUserId String?
|
||||
fileId String
|
||||
entityType FileEntityType
|
||||
entityId String
|
||||
linkRole String?
|
||||
|
||||
file File @relation(fields: [fileId], references: [id], onDelete: Cascade)
|
||||
createdByPortalUser PortalUser? @relation("PortalFileEntityLinkActor", fields: [createdByPortalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
|
||||
@@unique([fileId, entityType, entityId])
|
||||
@@index([tenantId, entityType, entityId])
|
||||
@@index([tenantId, fileId])
|
||||
@@index([tenantId, createdByPortalUserId])
|
||||
}
|
||||
|
||||
/// Chunked-upload session (replaces spec `FileUploadProgress`, renamed to avoid
|
||||
@@ -134,7 +150,9 @@ model FileUpload {
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
createdByUserId String
|
||||
/// Exactly one actor column is set; see the merge-migration CHECK contract.
|
||||
createdByUserId String?
|
||||
createdByPortalUserId String?
|
||||
originalFilename String
|
||||
totalSizeBytes Int
|
||||
mimeType String
|
||||
@@ -146,8 +164,10 @@ model FileUpload {
|
||||
failureReason String?
|
||||
|
||||
chunks FileUploadChunk[]
|
||||
createdByPortalUser PortalUser? @relation("PortalFileUploadActor", fields: [createdByPortalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
|
||||
@@index([tenantId, createdByUserId, status])
|
||||
@@index([tenantId, createdByPortalUserId, status])
|
||||
@@index([expiresAt])
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,12 @@ model FormSubmission {
|
||||
id String @id @default(cuid())
|
||||
formId String
|
||||
tenantId String
|
||||
/// Authenticated submissions have exactly one internal or PortalUser actor.
|
||||
/// The merge migration adds the database CHECK after legacy public-form
|
||||
/// backfill; portal services enforce the invariant immediately.
|
||||
createdByUserId String?
|
||||
createdByPortalUserId String?
|
||||
projectId String?
|
||||
/// Validated payload as { values: Record<string, string|number|boolean|null> }.
|
||||
payload Json
|
||||
/// Origin header recorded at submission time, for audit / forensics.
|
||||
@@ -74,6 +80,7 @@ model FormSubmission {
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
form Form @relation(fields: [formId], references: [id], onDelete: Cascade)
|
||||
createdByPortalUser PortalUser? @relation("PortalFormSubmissionActor", fields: [createdByPortalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
files FormFile[]
|
||||
actionLogs FormActionLog[]
|
||||
|
||||
@@ -82,6 +89,8 @@ model FormSubmission {
|
||||
@@index([tenantId, createdAt(sort: Desc)])
|
||||
@@index([status])
|
||||
@@index([tenantId, linkedEntityType, linkedEntityId])
|
||||
@@index([tenantId, createdByPortalUserId, createdAt(sort: Desc)])
|
||||
@@index([tenantId, projectId, createdAt(sort: Desc)])
|
||||
}
|
||||
|
||||
enum FormStatus {
|
||||
@@ -97,6 +106,11 @@ enum FormSubtype {
|
||||
survey
|
||||
booking_intake
|
||||
hr_request
|
||||
/// WF-P16 S01 type selection: submissions feed the lead inbox by default.
|
||||
lead
|
||||
/// WF-P16 S01 type selection: staff-only form without a public link.
|
||||
internal
|
||||
portal_form
|
||||
}
|
||||
|
||||
enum FormFieldType {
|
||||
@@ -125,6 +139,7 @@ enum FormActionType {
|
||||
send_email_to_submitter
|
||||
webhook
|
||||
trigger_automation
|
||||
start_double_opt_in
|
||||
}
|
||||
|
||||
enum FormActionLogStatus {
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
// VR-P32b/VR-P32d — KWP inbound project capability.
|
||||
//
|
||||
// AD-21: this module owns its schema. Cross-module references intentionally
|
||||
// remain bare scalars and are protected by the generated tenant-policy
|
||||
// contract. KWP is read-only; no outbound mutation or KWP numbering model
|
||||
// belongs in this file.
|
||||
|
||||
enum KwpCapabilityStatus {
|
||||
active
|
||||
paused
|
||||
}
|
||||
|
||||
enum KwpProjectCatalogStatus {
|
||||
pending
|
||||
syncing
|
||||
ready
|
||||
partial
|
||||
paused
|
||||
}
|
||||
|
||||
enum KwpProjectCatalogItemState {
|
||||
discovered
|
||||
active
|
||||
missing
|
||||
}
|
||||
|
||||
model KwpApiContractSnapshot {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
dataConnectionId String
|
||||
capability String
|
||||
apiVersion String
|
||||
semanticFingerprint String
|
||||
consumedContract Json
|
||||
adapterRevision String
|
||||
validatedAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@unique([tenantId, dataConnectionId, capability, semanticFingerprint])
|
||||
@@index([tenantId, dataConnectionId, createdAt(sort: Desc)])
|
||||
}
|
||||
|
||||
model KwpCapabilityState {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
dataConnectionId String
|
||||
capability String
|
||||
status KwpCapabilityStatus @default(active)
|
||||
reasonCode String?
|
||||
observedFingerprint String?
|
||||
approvedFingerprint String?
|
||||
adapterRevision String
|
||||
revision Int @default(1)
|
||||
pausedAt DateTime?
|
||||
lastCheckedAt DateTime?
|
||||
approvedAt DateTime?
|
||||
approvedByUserId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([tenantId, dataConnectionId, capability])
|
||||
@@index([tenantId, status])
|
||||
}
|
||||
|
||||
model KwpErrorReport {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
dataConnectionId String
|
||||
capability String
|
||||
code String
|
||||
redactedDetails Json
|
||||
createdAt DateTime @default(now())
|
||||
resolvedAt DateTime?
|
||||
resolvedByUserId String?
|
||||
|
||||
@@index([tenantId, dataConnectionId, createdAt(sort: Desc)])
|
||||
@@index([tenantId, resolvedAt])
|
||||
}
|
||||
|
||||
/// Stable provider-status to HiveGrid Pipeline/Stage routing. Names are never
|
||||
/// used as runtime identifiers; archived/missing targets quarantine the item.
|
||||
model KwpProjectRouting {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
dataConnectionId String
|
||||
externalStatus Int
|
||||
pipelineId String
|
||||
stageId String
|
||||
revision Int @default(1)
|
||||
createdByUserId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([tenantId, dataConnectionId, externalStatus])
|
||||
@@index([tenantId, pipelineId, stageId])
|
||||
}
|
||||
|
||||
/// Connection-level progress for the automatic read-only KWP project catalog.
|
||||
/// Discovery is intentionally cursorless and represents only the project set
|
||||
/// visible through the confirmed mandant's Projektampel settings.
|
||||
model KwpProjectCatalogState {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
dataConnectionId String
|
||||
status KwpProjectCatalogStatus @default(pending)
|
||||
discoveredCount Int @default(0)
|
||||
hydratedCount Int @default(0)
|
||||
revision Int @default(1)
|
||||
lastDiscoveryAt DateTime?
|
||||
nextDiscoveryAt DateTime @default(now())
|
||||
lastCompletedAt DateTime?
|
||||
lastErrorCode String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([tenantId, dataConnectionId], map: "KwpProjectCatalogState_tenant_connection_key")
|
||||
@@index([tenantId, status, nextDiscoveryAt], map: "KwpProjectCatalogState_tenant_due_idx")
|
||||
}
|
||||
|
||||
/// Safe, normalized project fields used for cache-first KWP search. No raw
|
||||
/// provider payload and no prohibited financial/address-internal fields are
|
||||
/// persisted here.
|
||||
model KwpProjectCatalogItem {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
dataConnectionId String
|
||||
externalProjectNumber String
|
||||
name String
|
||||
searchText String
|
||||
status Int?
|
||||
projectAddressCode String?
|
||||
invoiceAddressCode String?
|
||||
clientAddressCode String?
|
||||
startDate DateTime?
|
||||
orderValue Decimal? @db.Decimal(18, 2)
|
||||
normalizedFingerprint String
|
||||
state KwpProjectCatalogItemState @default(discovered)
|
||||
discoveredAt DateTime @default(now())
|
||||
lastSeenAt DateTime @default(now())
|
||||
lastSyncedAt DateTime?
|
||||
nextRefreshAt DateTime @default(now())
|
||||
missingSince DateTime?
|
||||
refreshAttempts Int @default(0)
|
||||
lastErrorCode String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([tenantId, dataConnectionId, externalProjectNumber], map: "KwpProjectCatalogItem_connection_external_key")
|
||||
@@index([tenantId, dataConnectionId, state, nextRefreshAt], map: "KwpProjectCatalogItem_tenant_due_idx")
|
||||
@@index([tenantId, dataConnectionId, externalProjectNumber], map: "KwpProjectCatalogItem_tenant_external_idx")
|
||||
@@index([searchText(ops: raw("gin_trgm_ops"))], type: Gin, map: "KwpProjectCatalogItem_searchText_trgm_idx")
|
||||
}
|
||||
|
||||
/// Read-only material/ERP position mirrored from the KWP project view. KWP is
|
||||
/// authoritative for these fields; local project data remains independent.
|
||||
model KwpMaterialPosition {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
dataConnectionId String
|
||||
projektId String
|
||||
externalId String
|
||||
positionNumber String?
|
||||
text String
|
||||
longText String?
|
||||
quantity Decimal? @db.Decimal(18, 4)
|
||||
unit String?
|
||||
unitPrice Decimal? @db.Decimal(18, 2)
|
||||
totalPrice Decimal? @db.Decimal(18, 2)
|
||||
positionMarker Int
|
||||
normalizedFingerprint String
|
||||
lastSeenAt DateTime
|
||||
lastSyncedAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
archivedAt DateTime?
|
||||
|
||||
@@unique([tenantId, dataConnectionId, projektId, externalId])
|
||||
@@index([tenantId, projektId, archivedAt, positionNumber])
|
||||
@@index([tenantId, dataConnectionId, lastSyncedAt])
|
||||
}
|
||||
@@ -3,8 +3,10 @@
|
||||
// AD-21: this module owns its schema file. Cross-module references to Kontakt,
|
||||
// Projekt and User are intentionally bare String scalars so P7 can land without
|
||||
// touching crm.prisma/accounts.prisma or a not-yet-existing project schema.
|
||||
// App-level isolation runs through leadService + withTenantRLS(); the deferred
|
||||
// RLS rollout artifact lives in prisma/rls/leads-isolation.sql.
|
||||
// Isolation: Postgres enforces FORCE ROW LEVEL SECURITY on all three tables
|
||||
// since 20260713190000_appwide_rls_cutover; the app binds context through
|
||||
// leadService + withTenantRLS(). Historic rollout artifact:
|
||||
// prisma/rls/leads-isolation.sql.
|
||||
|
||||
enum LeadQuelle {
|
||||
form
|
||||
|
||||
@@ -17,6 +17,7 @@ model NotificationDelivery {
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String?
|
||||
userId String?
|
||||
adminUserId String?
|
||||
channel NotificationPreferenceChannel
|
||||
category String
|
||||
messageKey String
|
||||
@@ -30,12 +31,21 @@ model NotificationDelivery {
|
||||
readAt DateTime?
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: SetNull)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
adminUser AdminUser? @relation(fields: [adminUserId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([tenantId, userId, status], name: "notification_delivery_tenant_user_status_idx")
|
||||
@@index([tenantId, channel, category], name: "notification_delivery_tenant_channel_category_idx")
|
||||
@@index([userId, channel, sourceKey], name: "notification_delivery_platform_source_lookup_idx")
|
||||
@@index([adminUserId, status, createdAt(sort: Desc)], name: "notification_delivery_admin_status_time_idx")
|
||||
@@index([status, updatedAt], name: "notification_delivery_status_updated_at_idx")
|
||||
@@index([providerMessageId], name: "notification_delivery_provider_message_id_idx")
|
||||
/// Tenant delivery uniqueness is covered by this composite key. Platform
|
||||
/// delivery uniqueness additionally requires the merge-migration-managed
|
||||
/// partial unique index `notification_delivery_platform_source_key` on
|
||||
/// (userId, channel, sourceKey) WHERE tenantId IS NULL because PostgreSQL
|
||||
/// treats NULL values as distinct and Prisma cannot declare partial indexes.
|
||||
@@unique([tenantId, userId, channel, sourceKey], name: "notification_delivery_source_key")
|
||||
@@unique([adminUserId, channel, sourceKey], name: "notification_delivery_admin_source_key")
|
||||
}
|
||||
|
||||
model UserNotificationPreference {
|
||||
|
||||
@@ -14,6 +14,9 @@ model OutboxEvent {
|
||||
createdAt DateTime @default(now())
|
||||
processedAt DateTime?
|
||||
retries Int @default(0)
|
||||
/// Monotone operator-replay generation. Automatic enqueue retries keep the
|
||||
/// same value so enqueue/ACK ambiguity still deduplicates in BullMQ.
|
||||
deliveryGeneration Int @default(0)
|
||||
lastError String?
|
||||
scheduledAt DateTime @default(now())
|
||||
dispatchKey String?
|
||||
|
||||
@@ -10,6 +10,10 @@ model Role {
|
||||
assignToNewUsers Boolean
|
||||
isDefault Boolean
|
||||
order Int
|
||||
// Which billing bucket / default UI mode this role belongs to (office vs field).
|
||||
seatCategory SeatType @default(office)
|
||||
// Marks a role seeded from the SHK template (hint flag, per M27 spec C.3).
|
||||
isTemplateOrigin Boolean @default(false)
|
||||
permissions RolePermission[]
|
||||
users UserRole[]
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// WF-P8 Subframe delta (S00 boards start page) — pipeline access requests.
|
||||
//
|
||||
// A viewer who is locked out of a pipeline (deny-based PipelineAccess rule
|
||||
// with kannSehen=false) can still see the board greyed out on the boards
|
||||
// start page and ask for access ("Nutzung anfragen"). Each request is
|
||||
// tracked here until a projects.admin grants access (approved) or dismisses
|
||||
// it.
|
||||
//
|
||||
// AD-21: this module owns its schema file. Cross-module references to
|
||||
// Pipeline and User are intentionally bare String scalars so this slice does
|
||||
// not modify projekt/core/accounts schemas.
|
||||
|
||||
enum PipelineAccessRequestStatus {
|
||||
open
|
||||
approved
|
||||
dismissed
|
||||
}
|
||||
|
||||
model PipelineAccessRequest {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
pipelineId String
|
||||
requestedByUserId String
|
||||
status PipelineAccessRequestStatus @default(open)
|
||||
createdAt DateTime @default(now())
|
||||
resolvedAt DateTime?
|
||||
resolvedByUserId String?
|
||||
|
||||
@@index([tenantId, pipelineId, status])
|
||||
@@index([tenantId, requestedByUserId])
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// WF-P8 M04 (Pipeline-Uebergabe) — records a project's move from one pipeline
|
||||
// into its successor together with the companion data the salesperson picked.
|
||||
//
|
||||
// AD-21: this slice owns its own schema file. `tenantId`, `performedByUserId`
|
||||
// and the per-item `sourceId` are intentionally bare String scalars so the
|
||||
// module does not modify core/accounts or the owning P8 `projekt.prisma`
|
||||
// beyond the additive successor-pipeline field.
|
||||
//
|
||||
// The handover is NOT button-triggered: reaching the final stage of the source
|
||||
// pipeline opens M04, and only "Auswahl uebernehmen" writes this record and
|
||||
// re-points `Projekt.pipelineId`/`stageId` at the successor pipeline. There is
|
||||
// no second project row (AD-20: one `Projekt` core, pipelines are views).
|
||||
|
||||
/// Which companion entity a handover item carries over. Kept as an enum because
|
||||
/// the set is closed by the M04 tab strip (Notizen / Dateien / Aufgaben / Termine).
|
||||
enum PipelineHandoverItemKind {
|
||||
notiz
|
||||
datei
|
||||
aufgabe
|
||||
termin
|
||||
}
|
||||
|
||||
/// One completed pipeline handover of a single project. Append-only: an undo
|
||||
/// writes a new `ProjektStageChange`, it does not delete the handover trail.
|
||||
model PipelineHandover {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
createdAt DateTime @default(now())
|
||||
projektId String
|
||||
fromPipelineId String
|
||||
toPipelineId String
|
||||
fromStageId String
|
||||
toStageId String
|
||||
performedByUserId String?
|
||||
|
||||
items PipelineHandoverItem[]
|
||||
|
||||
@@index([tenantId, projektId, createdAt])
|
||||
@@index([tenantId, toPipelineId, createdAt])
|
||||
}
|
||||
|
||||
/// A single companion record the user ticked in M04. `sourceId` addresses the
|
||||
/// note/file/task/appointment; it stays a bare scalar because the four sources
|
||||
/// live in four different module schemas.
|
||||
model PipelineHandoverItem {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
handoverId String
|
||||
kind PipelineHandoverItemKind
|
||||
sourceId String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
handover PipelineHandover @relation(fields: [handoverId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([handoverId, kind, sourceId])
|
||||
@@index([tenantId, kind, sourceId])
|
||||
}
|
||||
@@ -1,16 +1,127 @@
|
||||
enum PortalUserStatus {
|
||||
invited
|
||||
active
|
||||
disabled
|
||||
}
|
||||
|
||||
enum PortalUserKind {
|
||||
customer
|
||||
subcontractor
|
||||
}
|
||||
|
||||
enum PortalUploadCategory {
|
||||
complaint
|
||||
photo
|
||||
attachment
|
||||
audio
|
||||
other
|
||||
}
|
||||
|
||||
enum PortalUploadStatus {
|
||||
reserved
|
||||
uploading
|
||||
scanning
|
||||
clean
|
||||
failed
|
||||
cancelled
|
||||
}
|
||||
|
||||
enum PortalComplaintStatus {
|
||||
open
|
||||
in_review
|
||||
resolved
|
||||
rejected
|
||||
}
|
||||
|
||||
enum PortalLifecycleMode {
|
||||
customer
|
||||
project
|
||||
}
|
||||
|
||||
enum PortalNotificationEvent {
|
||||
stage_changed
|
||||
document_released
|
||||
upload_confirmation
|
||||
status_mail
|
||||
lifecycle
|
||||
}
|
||||
|
||||
enum PortalServiceInboxKind {
|
||||
complaint
|
||||
upload
|
||||
login
|
||||
download
|
||||
}
|
||||
|
||||
enum PortalServiceInboxStatus {
|
||||
open
|
||||
in_progress
|
||||
resolved
|
||||
dismissed
|
||||
}
|
||||
|
||||
enum PortalRoutingTargetKind {
|
||||
user
|
||||
role
|
||||
}
|
||||
|
||||
enum PortalDeletionRequestStatus {
|
||||
pending
|
||||
cancelled
|
||||
processing
|
||||
completed
|
||||
failed
|
||||
}
|
||||
|
||||
enum PortalGdprExportStatus {
|
||||
queued
|
||||
processing
|
||||
ready
|
||||
expired
|
||||
failed
|
||||
}
|
||||
|
||||
enum PortalDomainDnsStatus {
|
||||
pending
|
||||
txt_verified
|
||||
cname_verified
|
||||
verified
|
||||
failed
|
||||
}
|
||||
|
||||
enum PortalCustomDomainStatus {
|
||||
awaiting_payment
|
||||
awaiting_dns
|
||||
dns_verified
|
||||
provisioning
|
||||
active
|
||||
degraded
|
||||
failed
|
||||
disabled
|
||||
deprovisioning
|
||||
cooldown
|
||||
released
|
||||
}
|
||||
|
||||
enum PortalTokenPurpose {
|
||||
magic_link
|
||||
setup
|
||||
verify_email
|
||||
reset_password
|
||||
}
|
||||
|
||||
model Portal {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String?
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
tenantId String
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
createdByUserId String?
|
||||
createdByUser User? @relation(fields: [createdByUserId], references: [id], onDelete: Cascade)
|
||||
subdomain String @unique
|
||||
domain String? @unique
|
||||
title String
|
||||
isPublished Boolean @default(false)
|
||||
paymentProviderAccountId String?
|
||||
paymentProviderAccountId String?
|
||||
themeColor String?
|
||||
themeScheme String?
|
||||
seoTitle String?
|
||||
@@ -33,44 +144,589 @@ model Portal {
|
||||
brandingFavicon String?
|
||||
metadata Json?
|
||||
users PortalUser[]
|
||||
projectAccesses PortalProjectAccess[]
|
||||
stageVisibilities PortalStageVisibility[]
|
||||
projectDocuments PortalProjectDocument[]
|
||||
emailTemplates PortalEmailTemplate[]
|
||||
domainHostnameClaims PortalDomainHostnameClaim[]
|
||||
customDomain PortalCustomDomain?
|
||||
configuration PortalConfiguration?
|
||||
uploads PortalUpload[]
|
||||
complaints PortalComplaint[]
|
||||
subcontractorAccesses PortalSubcontractorAccess[]
|
||||
documentAutoReleaseRules PortalDocumentAutoReleaseRule[]
|
||||
serviceInboxItems PortalServiceInboxItem[]
|
||||
activityRoutingRules PortalActivityRoutingRule[]
|
||||
deletionRequests PortalDeletionRequest[]
|
||||
gdprExportJobs PortalGdprExportJob[]
|
||||
pages PortalPage[]
|
||||
registrations PortalUserRegistration[]
|
||||
subscriptionProducts PortalSubscriptionProduct[]
|
||||
subscriptionPrices PortalSubscriptionPrice[]
|
||||
subscriptionFeatures PortalSubscriptionFeature[]
|
||||
userSubscriptions PortalUserSubscription[]
|
||||
userSubscriptionProducts PortalUserSubscriptionProduct[]
|
||||
userSubscriptionProductPrices PortalUserSubscriptionProductPrice[]
|
||||
checkoutSessionStatus PortalCheckoutSessionStatus[]
|
||||
analyticsUniqueVisitors AnalyticsUniqueVisitor[]
|
||||
analyticsPageViews AnalyticsPageView[]
|
||||
analyticsEvents AnalyticsEvent[]
|
||||
|
||||
@@unique([tenantId])
|
||||
@@unique([id, tenantId])
|
||||
}
|
||||
|
||||
model PortalUser {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String?
|
||||
tenant Tenant? @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
tenantId String
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
email String
|
||||
passwordHash String
|
||||
emailNormalized String
|
||||
passwordHash String?
|
||||
firstName String
|
||||
lastName String
|
||||
avatar String?
|
||||
phone String?
|
||||
verifyToken String?
|
||||
locale String?
|
||||
fromRegistration PortalUserRegistration?
|
||||
kind PortalUserKind @default(customer)
|
||||
status PortalUserStatus @default(invited)
|
||||
locale String @default("de")
|
||||
emailVerifiedAt DateTime?
|
||||
/// Server-canonical legal notice acknowledged during first-access setup.
|
||||
/// PortalUser_privacyAcknowledgement_pair_check requires both fields to be
|
||||
/// NULL or populated together; existing identities are not backfilled.
|
||||
privacyNoticeAcknowledgedAt DateTime?
|
||||
privacyNoticeAcknowledgedUrl String?
|
||||
archivedAt DateTime?
|
||||
lastLoginAt DateTime?
|
||||
lastActivityAt DateTime?
|
||||
isDemoData Boolean @default(false)
|
||||
sessions PortalSession[]
|
||||
tokens PortalToken[]
|
||||
projectAccesses PortalProjectAccess[]
|
||||
uploadedFiles File[] @relation("PortalFileActor")
|
||||
fileUploads FileUpload[] @relation("PortalFileUploadActor")
|
||||
fileEntityLinks FileEntityLink[] @relation("PortalFileEntityLinkActor")
|
||||
formSubmissions FormSubmission[] @relation("PortalFormSubmissionActor")
|
||||
uploads PortalUpload[]
|
||||
complaints PortalComplaint[]
|
||||
subcontractorAccesses PortalSubcontractorAccess[]
|
||||
notificationPreferences PortalNotificationPreference[]
|
||||
serviceInboxItems PortalServiceInboxItem[]
|
||||
deletionRequests PortalDeletionRequest[]
|
||||
gdprExportJobs PortalGdprExportJob[]
|
||||
analyticsUniqueVisitors AnalyticsUniqueVisitor[]
|
||||
analyticsPageViews AnalyticsPageView[]
|
||||
analyticsEvents AnalyticsEvent[]
|
||||
subscription PortalUserSubscription?
|
||||
|
||||
@@unique([portalId, email])
|
||||
@@unique([portalId, emailNormalized])
|
||||
@@unique([id, tenantId])
|
||||
@@index([portalId])
|
||||
@@index([tenantId, status, archivedAt])
|
||||
}
|
||||
|
||||
/// Server-side session for the separate customer-portal identity class. The
|
||||
/// raw cookie value is never stored; tenantId and portalUserId are immutable
|
||||
/// under the dedicated portal RLS policy.
|
||||
model PortalSession {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalUserId String
|
||||
tokenHash String @unique
|
||||
expiresAt DateTime
|
||||
lastSeenAt DateTime?
|
||||
revokedAt DateTime?
|
||||
ipAddressHash String?
|
||||
userAgent String?
|
||||
/// Canonical origin selected by the trusted host resolver when the session
|
||||
/// was issued. Legacy null rows are rejected and are backfilled/revoked by
|
||||
/// the merge migration; every newly issued session is host-bound.
|
||||
origin String?
|
||||
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@index([tenantId, portalUserId, expiresAt])
|
||||
@@index([expiresAt, revokedAt])
|
||||
}
|
||||
|
||||
/// Durable global hostname reservation. The row survives deprovisioning and
|
||||
/// carries the 30-day reclaim cooldown so a dangling CNAME cannot be claimed
|
||||
/// by another workspace. Only the SHA-256 TXT proof is persisted.
|
||||
model PortalDomainHostnameClaim {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
hostname String @unique
|
||||
verificationTokenHash String @unique
|
||||
verificationTokenExpiresAt DateTime
|
||||
dnsStatus PortalDomainDnsStatus @default(pending)
|
||||
txtVerifiedAt DateTime?
|
||||
cnameVerifiedAt DateTime?
|
||||
verifiedAt DateTime?
|
||||
lastDnsCheckedAt DateTime?
|
||||
verificationAttemptCount Int @default(0)
|
||||
lastDnsObservation Json?
|
||||
generation Int @default(1)
|
||||
billingScopeKey String?
|
||||
idempotencyKey String
|
||||
claimedAt DateTime @default(now())
|
||||
releasedAt DateTime?
|
||||
cooldownUntil DateTime?
|
||||
/// Signed controller deprovision proof copied before the portal's single
|
||||
/// current-domain row can be retargeted to another hostname.
|
||||
deprovisionedAt DateTime?
|
||||
deprovisionCommandHash String?
|
||||
deprovisionResultHash String?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
customDomain PortalCustomDomain?
|
||||
|
||||
@@unique([id, tenantId])
|
||||
@@unique([tenantId, idempotencyKey])
|
||||
@@index([tenantId, portalId, releasedAt])
|
||||
@@index([dnsStatus, lastDnsCheckedAt])
|
||||
@@index([cooldownUntil])
|
||||
}
|
||||
|
||||
/// Exactly one current custom-domain generation per portal. Host resolution
|
||||
/// reads only `active` rows with a matching claim generation and non-null
|
||||
/// origin through a SECURITY DEFINER function; the portal login has no direct
|
||||
/// table grant.
|
||||
model PortalCustomDomain {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String @unique
|
||||
claimId String @unique
|
||||
generation Int
|
||||
status PortalCustomDomainStatus @default(awaiting_payment)
|
||||
activeOrigin String?
|
||||
entitlementValidatedAt DateTime?
|
||||
paymentAcquisitionId String?
|
||||
controllerCommandId String?
|
||||
controllerContentHash String?
|
||||
controllerResultContentHash String?
|
||||
controllerResultAttempt Int @default(0)
|
||||
controllerResultStatus String?
|
||||
lastHealthAckAt DateTime?
|
||||
provisionedAt DateTime?
|
||||
nextRevalidationAt DateTime?
|
||||
firstFailureAt DateTime?
|
||||
lastFailureAt DateTime?
|
||||
failureCount Int @default(0)
|
||||
lastFailureCode String?
|
||||
nextRetryAt DateTime?
|
||||
tlsObservedAt DateTime?
|
||||
certificateExpiresAt DateTime?
|
||||
disabledAt DateTime?
|
||||
disabledReason String?
|
||||
deprovisioningStartedAt DateTime?
|
||||
deprovisionedAt DateTime?
|
||||
killSwitchEnabled Boolean @default(false)
|
||||
killSwitchReason String?
|
||||
cooldownUntil DateTime?
|
||||
releasedAt DateTime?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
claim PortalDomainHostnameClaim @relation(fields: [claimId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
|
||||
@@unique([id, tenantId])
|
||||
@@unique([portalId, tenantId])
|
||||
@@unique([claimId, tenantId])
|
||||
@@index([tenantId, status, updatedAt])
|
||||
@@index([status, nextRetryAt])
|
||||
@@index([status, nextRevalidationAt])
|
||||
@@index([certificateExpiresAt])
|
||||
}
|
||||
|
||||
/// Hashed, single-purpose portal authentication capability. Magic-link,
|
||||
/// first-login setup, email verification and password reset share this table
|
||||
/// but can never be exchanged across purposes.
|
||||
model PortalToken {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
tenantId String
|
||||
portalUserId String
|
||||
purpose PortalTokenPurpose
|
||||
tokenHash String @unique
|
||||
expiresAt DateTime
|
||||
consumedAt DateTime?
|
||||
revokedAt DateTime?
|
||||
/// Lowercase SHA-256 client-IP binding. System-issued setup capabilities may
|
||||
/// start unbound; consumption claims the IP atomically. The migration-only
|
||||
/// PortalToken_requestedIpHash_binding_check enforces every other value.
|
||||
requestedIpHash String?
|
||||
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
// PortalToken_one_live_setup_per_user_key is a migration-only partial unique
|
||||
// index over live, unconsumed setup capabilities.
|
||||
@@index([tenantId, portalUserId, purpose, expiresAt])
|
||||
@@index([expiresAt, consumedAt, revokedAt])
|
||||
}
|
||||
|
||||
/// Explicit project allow-list for one portal identity. Project visibility is
|
||||
/// never inferred from tenant membership alone.
|
||||
model PortalProjectAccess {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
portalUserId String
|
||||
projectId String
|
||||
active Boolean @default(true)
|
||||
statusEmailsEnabled Boolean @default(true)
|
||||
revokedAt DateTime?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
project Projekt @relation(fields: [projectId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
subcontractorAccess PortalSubcontractorAccess?
|
||||
|
||||
@@unique([portalId, portalUserId, projectId])
|
||||
@@unique([id, tenantId])
|
||||
@@index([tenantId, portalUserId, active])
|
||||
@@index([tenantId, projectId, active])
|
||||
}
|
||||
|
||||
/// Tenant-admin configuration for the stages that an end customer may see.
|
||||
model PortalStageVisibility {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
stageId String
|
||||
visible Boolean @default(false)
|
||||
customerLabel String?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
stage PipelineStage @relation(fields: [stageId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([portalId, stageId])
|
||||
@@index([tenantId, stageId, visible])
|
||||
}
|
||||
|
||||
/// Explicit document release. A File or FileEntityLink by itself never grants
|
||||
/// customer-portal read access.
|
||||
model PortalProjectDocument {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
projectId String
|
||||
fileId String
|
||||
releasedAt DateTime @default(now())
|
||||
releasedByUserId String?
|
||||
revokedAt DateTime?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
project Projekt @relation(fields: [projectId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
file File @relation(fields: [fileId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([portalId, projectId, fileId])
|
||||
@@index([tenantId, projectId, revokedAt])
|
||||
@@index([tenantId, fileId])
|
||||
}
|
||||
|
||||
/// Stage-change mail template managed by the tenant-facing core application.
|
||||
/// The portal runtime only reads rendered project/status data, never edits it.
|
||||
model PortalEmailTemplate {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
stageId String
|
||||
locale String @default("de")
|
||||
subject String
|
||||
body String
|
||||
active Boolean @default(false)
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
stage PipelineStage @relation(fields: [stageId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([portalId, stageId, locale])
|
||||
@@index([tenantId, stageId, active])
|
||||
}
|
||||
|
||||
/// Persisted contract for one portal upload. File/FileUpload/FileEntityLink
|
||||
/// identifiers remain bare cross-module scalars per AD-21; the file tables
|
||||
/// independently carry the same PortalUser actor and tenant scope.
|
||||
model PortalUpload {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
portalUserId String
|
||||
projectId String
|
||||
fileUploadId String?
|
||||
fileId String?
|
||||
fileEntityLinkId String?
|
||||
category PortalUploadCategory @default(attachment)
|
||||
description String?
|
||||
status PortalUploadStatus @default(reserved)
|
||||
quotaBytes Int
|
||||
requestChecksumSha256 String
|
||||
scanCompletedAt DateTime?
|
||||
completedAt DateTime?
|
||||
effectsCompletedAt DateTime?
|
||||
failedAt DateTime?
|
||||
failureCode String?
|
||||
idempotencyKey String
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([tenantId, idempotencyKey])
|
||||
@@unique([fileUploadId])
|
||||
@@unique([fileId])
|
||||
@@index([tenantId, portalUserId, status, createdAt(sort: Desc)])
|
||||
@@index([tenantId, projectId, createdAt(sort: Desc)])
|
||||
}
|
||||
|
||||
/// Authenticated portal-form complaint. The validated form payload remains in
|
||||
/// FormSubmission; this row supplies the portal/project lifecycle contract.
|
||||
model PortalComplaint {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
portalUserId String
|
||||
projectId String
|
||||
formSubmissionId String @unique
|
||||
subject String?
|
||||
status PortalComplaintStatus @default(open)
|
||||
effectsCompletedAt DateTime?
|
||||
resolvedAt DateTime?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@index([tenantId, projectId, status, createdAt(sort: Desc)])
|
||||
@@index([tenantId, portalUserId, createdAt(sort: Desc)])
|
||||
}
|
||||
|
||||
/// One-to-one visibility extension for a subcontractor project grant. Customer
|
||||
/// access continues to use PortalProjectAccess without this restricted matrix.
|
||||
model PortalSubcontractorAccess {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
portalUserId String
|
||||
projectId String
|
||||
projectAccessId String
|
||||
companyName String
|
||||
roleLabel String?
|
||||
validFrom DateTime?
|
||||
validUntil DateTime?
|
||||
visibleStageIds String[] @default([])
|
||||
visibleDocumentTypes String[] @default([])
|
||||
canSeeOtherSubcontractors Boolean @default(false)
|
||||
canUpload Boolean @default(true)
|
||||
active Boolean @default(true)
|
||||
revokedAt DateTime?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
projectAccess PortalProjectAccess @relation(fields: [projectAccessId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([portalId, portalUserId, projectId])
|
||||
@@unique([projectAccessId, tenantId])
|
||||
@@index([tenantId, portalUserId, active, revokedAt])
|
||||
@@index([tenantId, projectId, active, revokedAt])
|
||||
}
|
||||
|
||||
model PortalConfiguration {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
lifecycleMode PortalLifecycleMode @default(customer)
|
||||
projectAutoCloseMonths Int @default(12)
|
||||
inactivityDisableMonths Int @default(24)
|
||||
enabledProjectTypes String[] @default([])
|
||||
uploadMaxFiles Int @default(10)
|
||||
uploadMaxFileSizeBytes Int @default(52428800)
|
||||
statusEmailsEnabled Boolean @default(true)
|
||||
welcomeMessage String?
|
||||
supportEmail String?
|
||||
supportPhone String?
|
||||
imprintUrl String?
|
||||
privacyUrl String?
|
||||
termsUrl String?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([id, tenantId])
|
||||
@@unique([portalId, tenantId])
|
||||
@@index([tenantId])
|
||||
}
|
||||
|
||||
model PortalDocumentAutoReleaseRule {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
projectType String?
|
||||
documentType String
|
||||
enabled Boolean @default(true)
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([portalId, projectType, documentType])
|
||||
@@index([tenantId, enabled])
|
||||
}
|
||||
|
||||
model PortalNotificationPreference {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalUserId String
|
||||
eventType PortalNotificationEvent
|
||||
emailEnabled Boolean @default(true)
|
||||
mutedUntil DateTime?
|
||||
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
|
||||
@@unique([portalUserId, eventType])
|
||||
@@index([tenantId, portalUserId])
|
||||
}
|
||||
|
||||
/// Persistent, seven-day internal service queue. It is written by trusted
|
||||
/// app/worker consumers and deliberately never exposed to hivegrid_portal.
|
||||
model PortalServiceInboxItem {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
portalUserId String
|
||||
projectId String?
|
||||
kind PortalServiceInboxKind
|
||||
status PortalServiceInboxStatus @default(open)
|
||||
priority Int
|
||||
sourceKey String
|
||||
sourceId String?
|
||||
titleKey String
|
||||
metadata Json @default("{}")
|
||||
occurredAt DateTime
|
||||
lastOccurredAt DateTime
|
||||
bundledCount Int @default(1)
|
||||
expiresAt DateTime
|
||||
ownerUserId String?
|
||||
routingRuleId String?
|
||||
resolvedAt DateTime?
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
routingRule PortalActivityRoutingRule? @relation(fields: [routingRuleId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([tenantId, sourceKey])
|
||||
@@index([tenantId, status, priority(sort: Desc), occurredAt(sort: Desc)])
|
||||
@@index([tenantId, portalUserId, occurredAt(sort: Desc)])
|
||||
@@index([expiresAt])
|
||||
}
|
||||
|
||||
model PortalActivityRoutingRule {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
activityType PortalServiceInboxKind
|
||||
targetKind PortalRoutingTargetKind
|
||||
targetUserId String?
|
||||
targetRoleId String?
|
||||
priority Int @default(100)
|
||||
enabled Boolean @default(true)
|
||||
notifyEnabled Boolean @default(true)
|
||||
matchConfig Json @default("{}")
|
||||
isDemoData Boolean @default(false)
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
inboxItems PortalServiceInboxItem[]
|
||||
|
||||
@@unique([portalId, activityType, priority])
|
||||
@@index([tenantId, activityType, enabled, priority])
|
||||
}
|
||||
|
||||
model PortalDeletionRequest {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
portalUserId String
|
||||
status PortalDeletionRequestStatus @default(pending)
|
||||
requestedAt DateTime @default(now())
|
||||
confirmedAt DateTime?
|
||||
confirmationEmailSentAt DateTime?
|
||||
cancellableUntil DateTime
|
||||
cancelledAt DateTime?
|
||||
processingStartedAt DateTime?
|
||||
completedAt DateTime?
|
||||
failureCode String?
|
||||
idempotencyKey String
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
|
||||
@@unique([tenantId, idempotencyKey])
|
||||
@@index([tenantId, portalUserId, status])
|
||||
@@index([status, cancellableUntil])
|
||||
}
|
||||
|
||||
model PortalGdprExportJob {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
portalId String
|
||||
portalUserId String
|
||||
requestedByUserId String?
|
||||
status PortalGdprExportStatus @default(queued)
|
||||
progressPercent Int @default(0)
|
||||
resultFileId String?
|
||||
resultBucket String?
|
||||
resultKey String?
|
||||
resultSizeBytes Int?
|
||||
resultExpiresAt DateTime?
|
||||
downloadCount Int @default(0)
|
||||
lastDownloadedAt DateTime?
|
||||
processingStartedAt DateTime?
|
||||
processingFinishedAt DateTime?
|
||||
failureCode String?
|
||||
idempotencyKey String
|
||||
|
||||
portal Portal @relation(fields: [portalId, tenantId], references: [id, tenantId], onDelete: Cascade)
|
||||
portalUser PortalUser @relation(fields: [portalUserId, tenantId], references: [id, tenantId], onDelete: Restrict)
|
||||
|
||||
@@unique([tenantId, idempotencyKey])
|
||||
@@index([tenantId, portalUserId, status, createdAt(sort: Desc)])
|
||||
@@index([status, resultExpiresAt])
|
||||
}
|
||||
|
||||
model PortalPage {
|
||||
@@ -84,128 +740,3 @@ model PortalPage {
|
||||
|
||||
@@unique([portalId, name])
|
||||
}
|
||||
|
||||
model PortalUserRegistration {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
email String
|
||||
firstName String
|
||||
lastName String
|
||||
slug String?
|
||||
token String @unique
|
||||
ipAddress String?
|
||||
company String?
|
||||
selectedSubscriptionPriceId String?
|
||||
createdPortalUserId String? @unique
|
||||
createdPortalUser PortalUser? @relation(fields: [createdPortalUserId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([portalId, email])
|
||||
}
|
||||
|
||||
model PortalSubscriptionProduct {
|
||||
id String @id @default(cuid())
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
billingProviderId String
|
||||
order Int
|
||||
title String
|
||||
active Boolean
|
||||
model Int
|
||||
public Boolean
|
||||
groupTitle String?
|
||||
groupDescription String?
|
||||
description String?
|
||||
badge String?
|
||||
billingAddressCollection String @default("auto")
|
||||
hasQuantity Boolean @default(false)
|
||||
canBuyAgain Boolean @default(false)
|
||||
prices PortalSubscriptionPrice[]
|
||||
features PortalSubscriptionFeature[]
|
||||
portalUserProducts PortalUserSubscriptionProduct[]
|
||||
}
|
||||
|
||||
model PortalSubscriptionPrice {
|
||||
id String @id @default(cuid())
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
subscriptionProductId String
|
||||
subscriptionProduct PortalSubscriptionProduct @relation(fields: [subscriptionProductId], references: [id], onDelete: Cascade)
|
||||
billingProviderId String
|
||||
type Int
|
||||
billingPeriod Int
|
||||
price Decimal
|
||||
currency String
|
||||
trialDays Int
|
||||
active Boolean
|
||||
portalUserProductPrices PortalUserSubscriptionProductPrice[]
|
||||
}
|
||||
|
||||
model PortalSubscriptionFeature {
|
||||
id String @id @default(cuid())
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
subscriptionProductId String
|
||||
order Int
|
||||
title String
|
||||
name String
|
||||
type Int
|
||||
value Int
|
||||
href String?
|
||||
badge String?
|
||||
accumulate Boolean @default(false)
|
||||
subscriptionProduct PortalSubscriptionProduct @relation(fields: [subscriptionProductId], references: [id], onDelete: Cascade)
|
||||
}
|
||||
|
||||
model PortalUserSubscription {
|
||||
id String @id @default(cuid())
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
portalUserId String @unique
|
||||
billingProviderCustomerId String?
|
||||
portalUser PortalUser @relation(fields: [portalUserId], references: [id], onDelete: Cascade)
|
||||
products PortalUserSubscriptionProduct[]
|
||||
}
|
||||
|
||||
model PortalUserSubscriptionProduct {
|
||||
id String @id @default(cuid())
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
portalUserSubscriptionId String
|
||||
subscriptionProductId String
|
||||
cancelledAt DateTime?
|
||||
endsAt DateTime?
|
||||
billingProviderSubscriptionId String?
|
||||
quantity Int?
|
||||
fromCheckoutSessionId String?
|
||||
currentPeriodStart DateTime?
|
||||
currentPeriodEnd DateTime?
|
||||
portalUserSubscription PortalUserSubscription @relation(fields: [portalUserSubscriptionId], references: [id], onDelete: Cascade)
|
||||
subscriptionProduct PortalSubscriptionProduct @relation(fields: [subscriptionProductId], references: [id])
|
||||
prices PortalUserSubscriptionProductPrice[]
|
||||
}
|
||||
|
||||
model PortalUserSubscriptionProductPrice {
|
||||
id String @id @default(cuid())
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
portalUserSubscriptionProductId String
|
||||
portalUserSubscriptionProduct PortalUserSubscriptionProduct @relation(fields: [portalUserSubscriptionProductId], references: [id], onDelete: Cascade)
|
||||
subscriptionPriceId String?
|
||||
subscriptionPrice PortalSubscriptionPrice? @relation(fields: [subscriptionPriceId], references: [id])
|
||||
}
|
||||
|
||||
model PortalCheckoutSessionStatus {
|
||||
id String @unique
|
||||
portalId String
|
||||
portal Portal @relation(fields: [portalId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
pending Boolean @default(true) // has not added products to tenant
|
||||
email String
|
||||
fromUrl String
|
||||
fromUserId String?
|
||||
createdUserId String?
|
||||
}
|
||||
@@ -65,15 +65,23 @@ model Pipeline {
|
||||
isDefault Boolean @default(false)
|
||||
isDemoData Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
/// WF-P8 M04: pipeline a project hands over to once it reaches the final
|
||||
/// stage here. Null = this pipeline is terminal and M04 never opens.
|
||||
nachfolgePipelineId String?
|
||||
|
||||
stages PipelineStage[]
|
||||
accessRules PipelineAccess[]
|
||||
fieldConfigs PipelineFieldConfig[]
|
||||
fieldGroups PipelineFieldGroup[]
|
||||
projekte Projekt[]
|
||||
|
||||
nachfolgePipeline Pipeline? @relation("PipelineNachfolge", fields: [nachfolgePipelineId], references: [id], onDelete: SetNull)
|
||||
vorgaengerPipelines Pipeline[] @relation("PipelineNachfolge")
|
||||
|
||||
@@unique([tenantId, name])
|
||||
@@index([tenantId, typHint, archivedAt])
|
||||
@@index([tenantId, position])
|
||||
@@index([tenantId, nachfolgePipelineId])
|
||||
}
|
||||
|
||||
model PipelineStage {
|
||||
@@ -93,8 +101,11 @@ model PipelineStage {
|
||||
pipeline Pipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)
|
||||
fieldConfigs PipelineFieldConfig[]
|
||||
projekte Projekt[]
|
||||
portalVisibilities PortalStageVisibility[]
|
||||
portalEmailTemplates PortalEmailTemplate[]
|
||||
|
||||
@@unique([pipelineId, name])
|
||||
@@unique([id, tenantId])
|
||||
@@index([tenantId, pipelineId, archivedAt])
|
||||
@@index([tenantId, stageKind])
|
||||
}
|
||||
@@ -115,6 +126,27 @@ model PipelineAccess {
|
||||
@@index([tenantId, principalType, principalId])
|
||||
}
|
||||
|
||||
/// WF-P8 S05: a named section of the project detail template ("Grunddaten",
|
||||
/// "Planung & Verantwortliche", "KWP-Integration", …). System groups ship with
|
||||
/// the pipeline and may be reordered but not deleted (`istSystem`).
|
||||
model PipelineFieldGroup {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
pipelineId String
|
||||
name String
|
||||
reihenfolge Int @default(0)
|
||||
istSystem Boolean @default(false)
|
||||
isDemoData Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
pipeline Pipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)
|
||||
fieldConfigs PipelineFieldConfig[]
|
||||
|
||||
@@unique([pipelineId, name])
|
||||
@@index([tenantId, pipelineId, reihenfolge])
|
||||
}
|
||||
|
||||
model PipelineFieldConfig {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
@@ -126,14 +158,28 @@ model PipelineFieldConfig {
|
||||
reihenfolge Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
/// WF-P8 S05 template layout: owning section. Null = field sits in the
|
||||
/// "Bestandsfelder" pool outside the template.
|
||||
groupId String?
|
||||
/// WF-P8 S05 "Pflicht ab Board-Spalte": the field only becomes mandatory once
|
||||
/// the project reaches this stage. Null = `pflicht` applies unconditionally.
|
||||
pflichtAbStageId String?
|
||||
/// WF-P8 S05 optional helper text rendered under the field.
|
||||
hinweis String?
|
||||
/// WF-P8 S05: system fields may be reordered/locked but never deleted.
|
||||
istSystem Boolean @default(false)
|
||||
/// WF-P8 S05 legend "gesperrt / nur lesbar".
|
||||
gesperrt Boolean @default(false)
|
||||
|
||||
pipeline Pipeline @relation(fields: [pipelineId], references: [id], onDelete: Cascade)
|
||||
stage PipelineStage? @relation(fields: [stageId], references: [id], onDelete: Cascade)
|
||||
group PipelineFieldGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull)
|
||||
visibilities PipelineFieldVisibility[]
|
||||
|
||||
@@unique([pipelineId, stageId, fieldKey])
|
||||
@@index([tenantId, pipelineId])
|
||||
@@index([tenantId, fieldKey])
|
||||
@@index([tenantId, groupId, reihenfolge])
|
||||
}
|
||||
|
||||
model PipelineFieldVisibility {
|
||||
@@ -158,6 +204,14 @@ model LostReason {
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
name String
|
||||
/// WF-P8 S06: one-line explanation shown next to the reason in the admin table.
|
||||
beschreibung String?
|
||||
/// WF-P8 S06: free-text grouping ("Preis", "Budget", "Wettbewerb", ...).
|
||||
kategorie String?
|
||||
/// WF-P8 S06: true for the SHK reasons the tenant seed ships, false for
|
||||
/// reasons the tenant created itself. Distinct from isDemoData, which marks
|
||||
/// throwaway demo rows.
|
||||
istVorlage Boolean @default(false)
|
||||
position Int @default(0)
|
||||
isDemoData Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
@@ -179,6 +233,13 @@ model Projekt {
|
||||
beschreibung String?
|
||||
projekttyp String?
|
||||
quelle String?
|
||||
/// WF-P8 S02 "Grunddaten": campaign/promotion the project came in through.
|
||||
promotion String?
|
||||
/// WF-P8 S02 "Projektkontaktdaten": contact channels of the project itself,
|
||||
/// distinct from the linked Kontakt records (site office, site phone, ...).
|
||||
email String?
|
||||
telefon String?
|
||||
fax String?
|
||||
prioritaet ProjektPrioritaet @default(normal)
|
||||
pipelineId String
|
||||
stageId String
|
||||
@@ -196,6 +257,14 @@ model Projekt {
|
||||
wonAt DateTime?
|
||||
lostAt DateTime?
|
||||
undoStageChangeUntil DateTime?
|
||||
// WF-P8 M03 "Wiederholen": the stage an undo moved the project away from, so
|
||||
// the board can offer redo without querying the stage history per card. Set
|
||||
// when an undo runs, cleared by the next forward move.
|
||||
redoStageId String?
|
||||
// The reason that came with the undone move. A lost stage cannot be entered
|
||||
// without one, so a redo would otherwise be rejected for exactly the moves
|
||||
// the undo window exists for.
|
||||
redoLostReasonId String?
|
||||
isDemoData Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
|
||||
@@ -204,8 +273,14 @@ model Projekt {
|
||||
lostReason LostReason? @relation(fields: [lostReasonId], references: [id], onDelete: SetNull)
|
||||
kontakte ProjektKontakt[]
|
||||
stageChanges ProjektStageChange[]
|
||||
mitglieder ProjektMitglied[]
|
||||
adressDetails ProjektAdressDetail[]
|
||||
checklists ProjektChecklist[]
|
||||
portalAccesses PortalProjectAccess[]
|
||||
portalDocuments PortalProjectDocument[]
|
||||
|
||||
@@unique([tenantId, projektNummer])
|
||||
@@unique([id, tenantId])
|
||||
@@index([tenantId, pipelineId, stageId, archivedAt])
|
||||
@@index([tenantId, zustaendigePersonId])
|
||||
@@index([tenantId, projektleiterId])
|
||||
@@ -220,6 +295,8 @@ model ProjektStageChange {
|
||||
fromStageId String
|
||||
toStageId String
|
||||
lostReasonId String?
|
||||
/// WF-P8 M01: free-text note the user leaves when marking a project lost.
|
||||
notiz String?
|
||||
changedByUserId String?
|
||||
undoUntil DateTime?
|
||||
undoneAt DateTime?
|
||||
@@ -269,3 +346,48 @@ model ProjektKontakt {
|
||||
@@index([tenantId, projektId])
|
||||
@@index([tenantId, kontaktId])
|
||||
}
|
||||
|
||||
/// WF-P8 S02 "Adressdaten": which of the three project address slots a detail row
|
||||
/// belongs to. Mirrors the three address FKs on Projekt.
|
||||
enum ProjektAdressSlot {
|
||||
projekt
|
||||
rechnung
|
||||
bauherr
|
||||
}
|
||||
|
||||
/// The per-slot extras the S02 address group asks for on top of the shared
|
||||
/// `Adresse`. Deliberately NOT columns on `Adresse`: that is a shared CRM entity
|
||||
/// which contacts reuse, so a project's "Zahlungsziel" or "Zufahrt" would leak
|
||||
/// into every contact address. One row per project and slot.
|
||||
model ProjektAdressDetail {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
projektId String
|
||||
slot ProjektAdressSlot
|
||||
/// Slot "projekt": where on the site the work happens and how to get there.
|
||||
bauabschnitt String?
|
||||
zufahrt String?
|
||||
koordinaten String?
|
||||
/// Slot "rechnung": who receives the invoice, on what terms, and where the
|
||||
/// invoice itself is sent. Separate from `Projekt.email`, which is the
|
||||
/// operational contact address of the project.
|
||||
empfaenger String?
|
||||
zahlungsziel String?
|
||||
rechnungsEmail String?
|
||||
/// Slot "bauherr": whether the building owner wants postal mail, and who to
|
||||
/// reach on site. The owner is often not the CRM contact carrying the project.
|
||||
postErwuenscht Boolean @default(false)
|
||||
telefon String?
|
||||
ansprechpartnerVorOrt String?
|
||||
/// Free text, one per slot. The content is slot-specific — delivery
|
||||
/// constraints at the site, payment remarks on the invoice address — so it
|
||||
/// cannot live on the shared `Adresse` any more than the fields above.
|
||||
notizen String?
|
||||
|
||||
projekt Projekt @relation(fields: [projektId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([projektId, slot])
|
||||
@@index([tenantId, projektId])
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// WF-P8 S02-N (Modal Notiz erstellen) — project-scoped notes with an explicit
|
||||
// visibility gate.
|
||||
//
|
||||
// AD-21: own schema file; `tenantId` / `autorUserId` are bare String scalars.
|
||||
//
|
||||
// Why a typed table and not `Activity`: the activity stream is an append-only,
|
||||
// per-entity timeline with a flat `summaryText` and no reader gate. S02-N
|
||||
// requires an editable body AND a visibility choice ("Alle mit Projektzugriff"
|
||||
// / "Nur Innendienst" / "Nur ich"), which the timeline cannot express. Creating
|
||||
// a note still appends an `Activity` entry via `logActivity` (AGENTS DoD #14).
|
||||
|
||||
/// Who may read a note. `nur_ich` is author-only, `innendienst` is gated by the
|
||||
/// `projects.notes.read_internal` permission, `alle` follows normal project access.
|
||||
enum ProjektNotizSichtbarkeit {
|
||||
alle
|
||||
innendienst
|
||||
nur_ich
|
||||
}
|
||||
|
||||
model ProjektNotiz {
|
||||
id String @id @default(cuid())
|
||||
tenantId String
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
projektId String
|
||||
autorUserId String?
|
||||
inhalt String
|
||||
sichtbarkeit ProjektNotizSichtbarkeit @default(alle)
|
||||
isDemoData Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
|
||||
@@index([tenantId, projektId, createdAt(sort: Desc)])
|
||||
@@index([tenantId, autorUserId])
|
||||
}
|
||||
@@ -1,8 +1,27 @@
|
||||
enum SubscriptionProductKind {
|
||||
base_plan
|
||||
recurring_add_on
|
||||
one_time_setup
|
||||
contract_override
|
||||
}
|
||||
|
||||
enum TenantProductAcquisitionStatus {
|
||||
pending
|
||||
provider_pending
|
||||
payment_pending
|
||||
active
|
||||
failed
|
||||
cancelled
|
||||
expired
|
||||
refunded
|
||||
}
|
||||
|
||||
model SubscriptionProduct {
|
||||
id String @id @default(cuid())
|
||||
billingProviderId String
|
||||
code String?
|
||||
lagoPlanCode String?
|
||||
kind SubscriptionProductKind @default(base_plan)
|
||||
order Int
|
||||
title String
|
||||
active Boolean
|
||||
@@ -18,9 +37,8 @@ model SubscriptionProduct {
|
||||
prices SubscriptionPrice[]
|
||||
features SubscriptionFeature[]
|
||||
tenantProducts TenantSubscriptionProduct[]
|
||||
acquisitions TenantProductAcquisition[]
|
||||
usageBasedPrices SubscriptionUsageBasedPrice[]
|
||||
assignsTenantTypes TenantType[]
|
||||
|
||||
@@index([code])
|
||||
@@index([lagoPlanCode])
|
||||
}
|
||||
@@ -30,8 +48,12 @@ model SubscriptionPrice {
|
||||
subscriptionProductId String
|
||||
subscriptionProduct SubscriptionProduct @relation(fields: [subscriptionProductId], references: [id], onDelete: Cascade)
|
||||
billingProviderId String
|
||||
lagoPlanCode String?
|
||||
lagoFeeCode String?
|
||||
molliePriceReference String?
|
||||
billingCadence String @default("monthly")
|
||||
contractMonths Int @default(1)
|
||||
requiredPaymentMethod String @default("any")
|
||||
type Int
|
||||
billingPeriod Int
|
||||
price Decimal
|
||||
@@ -39,7 +61,9 @@ model SubscriptionPrice {
|
||||
trialDays Int
|
||||
active Boolean
|
||||
tenantProductPrices TenantSubscriptionProductPrice[]
|
||||
acquisitions TenantProductAcquisition[]
|
||||
|
||||
@@index([lagoPlanCode])
|
||||
@@index([lagoFeeCode])
|
||||
@@index([molliePriceReference])
|
||||
}
|
||||
@@ -98,6 +122,11 @@ model TenantSubscription {
|
||||
mollieCustomerId String?
|
||||
planCode String?
|
||||
seatQuantity Int @default(1)
|
||||
officeSeatQuantity Int @default(0)
|
||||
fieldSeatQuantity Int @default(0)
|
||||
billingCadence String @default("monthly")
|
||||
commitmentEndsAt DateTime?
|
||||
storageAddOnCodes String[] @default([])
|
||||
lastInvoiceExternalId String?
|
||||
lastPaymentExternalId String?
|
||||
status String @default("trial")
|
||||
@@ -133,6 +162,11 @@ model TenantSubscriptionProduct {
|
||||
lagoSubscriptionId String?
|
||||
planCode String?
|
||||
seatQuantity Int?
|
||||
officeSeatQuantity Int?
|
||||
fieldSeatQuantity Int?
|
||||
billingCadence String @default("monthly")
|
||||
commitmentEndsAt DateTime?
|
||||
storageAddOnCodes String[] @default([])
|
||||
quantity Int?
|
||||
fromCheckoutSessionId String?
|
||||
currentPeriodStart DateTime?
|
||||
@@ -140,11 +174,69 @@ model TenantSubscriptionProduct {
|
||||
tenantSubscription TenantSubscription @relation(fields: [tenantSubscriptionId], references: [id], onDelete: Cascade)
|
||||
subscriptionProduct SubscriptionProduct @relation(fields: [subscriptionProductId], references: [id])
|
||||
prices TenantSubscriptionProductPrice[]
|
||||
acquisition TenantProductAcquisition?
|
||||
|
||||
@@index([lagoSubscriptionId])
|
||||
@@index([planCode])
|
||||
}
|
||||
|
||||
/// Idempotent tenant-owned ledger for products acquired outside the one-base-plan
|
||||
/// lifecycle. `scopeKey` is the stable business scope (for example `tenant` or a
|
||||
/// normalized hostname) and makes provider retries safe without granting the same
|
||||
/// entitlement twice. Provider failures remain local to this row and must never
|
||||
/// mutate the base TenantSubscription status.
|
||||
model TenantProductAcquisition {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
subscriptionProductId String
|
||||
subscriptionPriceId String?
|
||||
productKind SubscriptionProductKind
|
||||
scopeKey String
|
||||
requestHash String
|
||||
status TenantProductAcquisitionStatus @default(pending)
|
||||
version Int @default(1)
|
||||
quantity Int @default(1)
|
||||
amountCents Int?
|
||||
currency String?
|
||||
checkoutSessionId String? @unique
|
||||
tenantSubscriptionProductId String? @unique
|
||||
provider String?
|
||||
providerAttempt Int @default(1)
|
||||
providerPaymentId String? @unique
|
||||
lagoInvoiceIntentReference String?
|
||||
providerPaymentExpiresAt DateTime?
|
||||
providerPaidAt DateTime?
|
||||
invoiceExternalId String?
|
||||
lagoSubscriptionId String?
|
||||
lagoProviderSubscriptionId String?
|
||||
initialLagoInvoiceExternalId String? @unique
|
||||
checkoutUrl String?
|
||||
sourceReference String?
|
||||
failureCode String?
|
||||
providerStartedAt DateTime?
|
||||
reservationExpiresAt DateTime?
|
||||
activatedAt DateTime?
|
||||
failedAt DateTime?
|
||||
cancelledAt DateTime?
|
||||
expiredAt DateTime?
|
||||
refundedAt DateTime?
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
subscriptionProduct SubscriptionProduct @relation(fields: [subscriptionProductId], references: [id])
|
||||
subscriptionPrice SubscriptionPrice? @relation(fields: [subscriptionPriceId], references: [id])
|
||||
checkoutSession CheckoutSessionStatus? @relation(fields: [checkoutSessionId], references: [id], onDelete: SetNull)
|
||||
tenantSubscriptionProduct TenantSubscriptionProduct? @relation(fields: [tenantSubscriptionProductId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([tenantId, subscriptionProductId, scopeKey])
|
||||
@@index([tenantId, status, updatedAt])
|
||||
@@index([tenantId, status, reservationExpiresAt])
|
||||
@@index([subscriptionProductId, productKind, status])
|
||||
@@index([invoiceExternalId])
|
||||
@@index([lagoSubscriptionId])
|
||||
@@index([lagoProviderSubscriptionId])
|
||||
}
|
||||
|
||||
model TenantSubscriptionProductPrice {
|
||||
id String @id @default(cuid())
|
||||
tenantSubscriptionProductId String
|
||||
@@ -174,13 +266,16 @@ model TenantSubscriptionUsageRecord {
|
||||
}
|
||||
|
||||
model TenantProductConfiguration {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String @unique
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
blueprintId String @default("crm-saas")
|
||||
notes String?
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String @unique
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
blueprintId String @default("crm-saas")
|
||||
notes String?
|
||||
signupSubscriptionPriceId String?
|
||||
signupOfficeSeatQuantity Int?
|
||||
signupFieldSeatQuantity Int?
|
||||
}
|
||||
|
||||
model TenantFeatureOverride {
|
||||
@@ -198,14 +293,15 @@ model TenantFeatureOverride {
|
||||
}
|
||||
|
||||
model CheckoutSessionStatus {
|
||||
id String @id
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
id String @unique
|
||||
tenantId String
|
||||
tenant Tenant @relation(fields: [tenantId], references: [id], onDelete: Cascade)
|
||||
pending Boolean @default(true) // has not added products to tenant
|
||||
email String
|
||||
fromUrl String
|
||||
fromUserId String?
|
||||
fromTenantId String?
|
||||
createdUserId String?
|
||||
createdTenantId String?
|
||||
provider String?
|
||||
@@ -215,14 +311,22 @@ model CheckoutSessionStatus {
|
||||
subscriptionPriceId String?
|
||||
lagoSubscriptionId String?
|
||||
planCode String?
|
||||
productKind SubscriptionProductKind @default(base_plan)
|
||||
scopeKey String?
|
||||
quantity Int @default(1)
|
||||
officeSeatQuantity Int @default(0)
|
||||
fieldSeatQuantity Int @default(0)
|
||||
billingCadence String @default("monthly")
|
||||
commitmentEndsAt DateTime?
|
||||
storageAddOnCodes String[] @default([])
|
||||
amountCents Int?
|
||||
currency String?
|
||||
checkoutUrl String?
|
||||
status String @default("open")
|
||||
productAcquisition TenantProductAcquisition?
|
||||
|
||||
@@index([providerPaymentId])
|
||||
@@index([fromTenantId, pending])
|
||||
@@index([tenantId, pending])
|
||||
}
|
||||
|
||||
model BillingWebhookLog {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// AK-P15a (P15) Telephony (Aircall) — typed provider-neutral domain model.
|
||||
//
|
||||
// AD-21: this module owns its schema. Cross-module identifiers such as
|
||||
// `dataConnectionId`, `tenantUserId`, and CRM match ids remain bare scalars so
|
||||
// no back-relations are required in shared schema files. The generated RLS
|
||||
// contract enforces same-tenant ownership for every security-critical scalar
|
||||
// reference on insert and update.
|
||||
//
|
||||
// OAuth credentials and the raw webhook token live only in the Apps Engine's
|
||||
// encrypted DataConnection credentials. TelephonyConnection stores the
|
||||
// one-way webhook token hash needed by the public bootstrap resolver; secrets
|
||||
// are never duplicated in this module.
|
||||
|
||||
enum TelephonyProvider {
|
||||
aircall
|
||||
hallopetra
|
||||
}
|
||||
|
||||
enum TelephonyBindingSource {
|
||||
email_auto
|
||||
manual
|
||||
}
|
||||
|
||||
enum TelephonyCallDirection {
|
||||
inbound
|
||||
outbound
|
||||
}
|
||||
|
||||
enum TelephonyCallStatus {
|
||||
ringing
|
||||
answered
|
||||
completed
|
||||
missed
|
||||
failed
|
||||
}
|
||||
|
||||
enum TelephonyMatchConfidence {
|
||||
hard
|
||||
soft
|
||||
manual
|
||||
none
|
||||
}
|
||||
|
||||
enum TelephonyWebhookProcessingStatus {
|
||||
pending
|
||||
processing
|
||||
completed
|
||||
failed
|
||||
skipped
|
||||
}
|
||||
|
||||
/// Tenant-specific provider extension of one Apps Engine DataConnection.
|
||||
/// Credentials and lifecycle status remain canonical on DataConnection.
|
||||
model TelephonyConnection {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
dataConnectionId String @unique
|
||||
provider TelephonyProvider @default(aircall)
|
||||
providerAccountId String?
|
||||
providerAccountName String?
|
||||
webhookId String?
|
||||
// SHA-256 one-way lookup digest only. The raw token remains encrypted in the
|
||||
// linked DataConnection and must never be serialized or persisted in events.
|
||||
webhookTokenHash String? @unique
|
||||
|
||||
userBindings TelephonyUserBinding[]
|
||||
callSessions TelephonyCallSession[]
|
||||
webhookEvents TelephonyWebhookEvent[]
|
||||
|
||||
// One historical slot per provider and tenant. The service layer permits at
|
||||
// most one active telephony provider while revoked slots remain auditable.
|
||||
@@unique([tenantId, provider])
|
||||
@@index([tenantId, dataConnectionId])
|
||||
@@index([tenantId, providerAccountId])
|
||||
}
|
||||
|
||||
/// Mapping between a HiveGrid TenantUser and a provider user (Aircall in v1).
|
||||
model TelephonyUserBinding {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
connectionId String
|
||||
tenantUserId String
|
||||
providerUserId String
|
||||
providerEmail String?
|
||||
providerDisplayName String?
|
||||
defaultProviderNumberId String?
|
||||
source TelephonyBindingSource @default(manual)
|
||||
|
||||
connection TelephonyConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([connectionId, tenantUserId])
|
||||
@@unique([connectionId, providerUserId])
|
||||
@@index([tenantId, tenantUserId])
|
||||
@@index([tenantId, providerEmail])
|
||||
}
|
||||
|
||||
/// Normalized inbound or outbound call, optionally matched to one CRM entity.
|
||||
model TelephonyCallSession {
|
||||
id String @id @default(cuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
tenantId String
|
||||
connectionId String
|
||||
providerCallId String
|
||||
providerUserId String?
|
||||
tenantUserId String?
|
||||
direction TelephonyCallDirection
|
||||
status TelephonyCallStatus
|
||||
fromNumber String
|
||||
toNumber String
|
||||
startedAt DateTime
|
||||
answeredAt DateTime?
|
||||
endedAt DateTime?
|
||||
durationSeconds Int?
|
||||
matchedKontaktId String?
|
||||
matchedLeadId String?
|
||||
matchedProjektId String?
|
||||
matchConfidence TelephonyMatchConfidence @default(none)
|
||||
manualOverrideAt DateTime?
|
||||
manualOverrideUserId String?
|
||||
noteMarkdown String?
|
||||
recordingUrl String?
|
||||
isDemoData Boolean @default(false)
|
||||
archivedAt DateTime?
|
||||
|
||||
connection TelephonyConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)
|
||||
webhookEvents TelephonyWebhookEvent[]
|
||||
|
||||
@@unique([connectionId, providerCallId])
|
||||
@@index([tenantId, startedAt(sort: Desc)])
|
||||
@@index([tenantId, status, startedAt(sort: Desc)])
|
||||
@@index([tenantId, matchedKontaktId, startedAt(sort: Desc)])
|
||||
@@index([tenantId, matchedLeadId, startedAt(sort: Desc)])
|
||||
@@index([tenantId, matchedProjektId, startedAt(sort: Desc)])
|
||||
@@index([tenantId, tenantUserId, startedAt(sort: Desc)])
|
||||
}
|
||||
|
||||
/// Redacted provider webhook envelope. Provider payload data is immutable;
|
||||
/// only processing metadata changes. Completed rows expire after 30 days and
|
||||
/// failed rows after 90 days through the tenant-scoped retention worker.
|
||||
model TelephonyWebhookEvent {
|
||||
id String @id @default(cuid())
|
||||
receivedAt DateTime @default(now())
|
||||
tenantId String
|
||||
connectionId String
|
||||
callSessionId String?
|
||||
eventType String
|
||||
dedupeKey String
|
||||
authenticationValid Boolean @default(true)
|
||||
notificationPayload Json
|
||||
processingStatus TelephonyWebhookProcessingStatus @default(pending)
|
||||
// A renewable, crash-recoverable worker claim. A redelivery may reclaim a
|
||||
// processing event only after this lease expires.
|
||||
processingLeaseId String?
|
||||
processingLeaseUntil DateTime?
|
||||
processingAttempt Int @default(0)
|
||||
processingErrorText String?
|
||||
processedAt DateTime?
|
||||
|
||||
connection TelephonyConnection @relation(fields: [connectionId], references: [id], onDelete: Cascade)
|
||||
callSession TelephonyCallSession? @relation(fields: [callSessionId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([tenantId, dedupeKey])
|
||||
@@index([tenantId, processingStatus, receivedAt])
|
||||
@@index([tenantId, processingStatus, processingLeaseUntil])
|
||||
@@index([tenantId, connectionId, receivedAt(sort: Desc)])
|
||||
@@index([receivedAt])
|
||||
}
|
||||
Reference in new issue
Block a user