stack/apps/backend/prisma/schema.prisma
2026-01-09 11:39:07 -08:00

1040 lines
36 KiB
Plaintext

generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
}
model SchemaMigration {
id String @id @default(dbgenerated("gen_random_uuid()"))
finishedAt DateTime
migrationName String @unique
@@ignore
}
model Project {
// Note that the project with ID `internal` is handled as a special case. All other project IDs are UUIDs.
id String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
displayName String
description String @default("")
isProductionMode Boolean
ownerTeamId String? @db.Uuid
logoUrl String?
logoFullUrl String?
logoDarkModeUrl String?
logoFullDarkModeUrl String?
projectConfigOverride Json?
stripeAccountId String?
apiKeySets ApiKeySet[]
projectUsers ProjectUser[]
provisionedProject ProvisionedProject?
tenancies Tenancy[]
environmentConfigOverrides EnvironmentConfigOverride[]
@@index([ownerTeamId], map: "Project_ownerTeamId_idx")
}
model Tenancy {
id String @id @default(uuid()) @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
projectId String
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
branchId String
// If organizationId is NULL, hasNoOrganization must be TRUE. If organizationId is not NULL, hasNoOrganization must be NULL.
organizationId String? @db.Uuid
hasNoOrganization BooleanTrue?
emailOutboxes EmailOutbox[]
@@unique([projectId, branchId, organizationId])
@@unique([projectId, branchId, hasNoOrganization])
}
model EnvironmentConfigOverride {
projectId String
branchId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
config Json
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
@@id([projectId, branchId])
}
model Team {
tenancyId String @db.Uuid
teamId String @default(uuid()) @db.Uuid
// Team IDs must be unique across all organizations (but not necessarily across all branches).
// To model this in the DB, we add two columns that are always equal to tenancy.projectId and tenancy.branchId.
mirroredProjectId String
mirroredBranchId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
displayName String
clientMetadata Json?
clientReadOnlyMetadata Json?
serverMetadata Json?
profileImageUrl String?
teamMembers TeamMember[]
projectApiKey ProjectApiKey[]
@@id([tenancyId, teamId])
@@unique([mirroredProjectId, mirroredBranchId, teamId])
}
// This is used for fields that are boolean but only the true value is part of a unique constraint.
// For example if you want to allow only one selected team per user, you can make an optional field with this type and add a unique constraint.
// Only the true value is considered for the unique constraint, the null value is not.
enum BooleanTrue {
TRUE
}
model TeamMember {
tenancyId String @db.Uuid
projectUserId String @db.Uuid
teamId String @db.Uuid
// This will override the displayName of the user in this team.
displayName String?
profileImageUrl String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
team Team @relation(fields: [tenancyId, teamId], references: [tenancyId, teamId], onDelete: Cascade)
isSelected BooleanTrue?
teamMemberDirectPermissions TeamMemberDirectPermission[]
@@id([tenancyId, projectUserId, teamId])
@@unique([tenancyId, projectUserId, isSelected])
@@index([tenancyId, projectUserId, isSelected], map: "TeamMember_projectUserId_isSelected_idx")
}
model ProjectUserDirectPermission {
id String @id @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
projectUserId String @db.Uuid
permissionId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
@@unique([tenancyId, projectUserId, permissionId])
}
model TeamMemberDirectPermission {
id String @id @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
projectUserId String @db.Uuid
teamId String @db.Uuid
permissionId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
teamMember TeamMember @relation(fields: [tenancyId, projectUserId, teamId], references: [tenancyId, projectUserId, teamId], onDelete: Cascade)
@@unique([tenancyId, projectUserId, teamId, permissionId])
}
model ProjectUser {
tenancyId String @db.Uuid
projectUserId String @default(uuid()) @db.Uuid
// User IDs must be unique across all organizations (but not necessarily across all branches).
// To model this in the DB, we add two columns that are always equal to tenancy.projectId and tenancy.branchId.
mirroredProjectId String
mirroredBranchId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
lastActiveAt DateTime @default(now())
displayName String?
serverMetadata Json?
clientReadOnlyMetadata Json?
clientMetadata Json?
profileImageUrl String?
requiresTotpMfa Boolean @default(false)
totpSecret Bytes?
isAnonymous Boolean @default(false)
projectUserOAuthAccounts ProjectUserOAuthAccount[]
teamMembers TeamMember[]
contactChannels ContactChannel[]
authMethods AuthMethod[]
// some backlinks for the unique constraints on some auth methods
passwordAuthMethod PasswordAuthMethod[]
passkeyAuthMethod PasskeyAuthMethod[]
otpAuthMethod OtpAuthMethod[]
oauthAuthMethod OAuthAuthMethod[]
projectApiKey ProjectApiKey[]
directPermissions ProjectUserDirectPermission[]
Project Project? @relation(fields: [projectId], references: [id])
projectId String?
userNotificationPreference UserNotificationPreference[]
@@id([tenancyId, projectUserId])
@@unique([mirroredProjectId, mirroredBranchId, projectUserId])
// indices for sorting and filtering
@@index([tenancyId, displayName(sort: Asc)], name: "ProjectUser_displayName_asc")
@@index([tenancyId, displayName(sort: Desc)], name: "ProjectUser_displayName_desc")
@@index([tenancyId, createdAt(sort: Asc)], name: "ProjectUser_createdAt_asc")
@@index([tenancyId, createdAt(sort: Desc)], name: "ProjectUser_createdAt_desc")
}
// This should be renamed to "OAuthAccount" as it is not always bound to a user
// When ever a user goes through the OAuth flow and gets an account ID from the OAuth provider, we store that here.
model ProjectUserOAuthAccount {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
projectUserId String? @db.Uuid
configOAuthProviderId String
providerAccountId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// This is used for the user to distinguish between multiple accounts from the same provider.
// we might want to add more user info here later
email String?
// Before the OAuth account is connected to a user (for example, in the link oauth process), the projectUser is null.
projectUser ProjectUser? @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
oauthTokens OAuthToken[]
oauthAccessToken OAuthAccessToken[]
// if allowSignIn is true, oauthAuthMethod must be set
oauthAuthMethod OAuthAuthMethod?
allowConnectedAccounts Boolean @default(true)
allowSignIn Boolean @default(true)
@@id([tenancyId, id])
@@unique([tenancyId, configOAuthProviderId, projectUserId, providerAccountId])
@@index([tenancyId, projectUserId])
}
enum ContactChannelType {
EMAIL
// PHONE
}
model ContactChannel {
tenancyId String @db.Uuid
projectUserId String @db.Uuid
id String @default(uuid()) @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
type ContactChannelType
isPrimary BooleanTrue?
usedForAuth BooleanTrue?
isVerified Boolean
value String
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
@@id([tenancyId, projectUserId, id])
// each user has at most one primary contact channel of each type
@@unique([tenancyId, projectUserId, type, isPrimary])
// value must be unique per user per type
@@unique([tenancyId, projectUserId, type, value])
// only one contact channel per project with the same value and type can be used for auth
@@unique([tenancyId, type, value, usedForAuth])
}
model AuthMethod {
tenancyId String @db.Uuid
id String @default(uuid()) @db.Uuid
projectUserId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// exactly one of the xyzAuthMethods should be set
otpAuthMethod OtpAuthMethod?
passwordAuthMethod PasswordAuthMethod?
passkeyAuthMethod PasskeyAuthMethod?
oauthAuthMethod OAuthAuthMethod?
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
@@id([tenancyId, id])
@@index([tenancyId, projectUserId])
}
model OtpAuthMethod {
tenancyId String @db.Uuid
authMethodId String @db.Uuid
projectUserId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
authMethod AuthMethod @relation(fields: [tenancyId, authMethodId], references: [tenancyId, id], onDelete: Cascade)
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
@@id([tenancyId, authMethodId])
// a user can only have one OTP auth method
@@unique([tenancyId, projectUserId])
}
model PasswordAuthMethod {
tenancyId String @db.Uuid
authMethodId String @db.Uuid
projectUserId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
passwordHash String
authMethod AuthMethod @relation(fields: [tenancyId, authMethodId], references: [tenancyId, id], onDelete: Cascade)
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
@@id([tenancyId, authMethodId])
// a user can only have one password auth method
@@unique([tenancyId, projectUserId])
}
model PasskeyAuthMethod {
tenancyId String @db.Uuid
authMethodId String @db.Uuid
projectUserId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
credentialId String
publicKey String
userHandle String
transports String[]
credentialDeviceType String
counter Int
authMethod AuthMethod @relation(fields: [tenancyId, authMethodId], references: [tenancyId, id], onDelete: Cascade)
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
@@id([tenancyId, authMethodId])
// a user can only have one password auth method
@@unique([tenancyId, projectUserId])
}
// This connects to projectUserOauthAccount, which might be shared between auth method and connected account.
model OAuthAuthMethod {
tenancyId String @db.Uuid
authMethodId String @db.Uuid
configOAuthProviderId String
providerAccountId String
projectUserId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
authMethod AuthMethod @relation(fields: [tenancyId, authMethodId], references: [tenancyId, id], onDelete: Cascade)
oauthAccount ProjectUserOAuthAccount @relation(fields: [tenancyId, configOAuthProviderId, projectUserId, providerAccountId], references: [tenancyId, configOAuthProviderId, projectUserId, providerAccountId])
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
@@id([tenancyId, authMethodId])
@@unique([tenancyId, configOAuthProviderId, providerAccountId])
@@unique([tenancyId, projectUserId, configOAuthProviderId])
@@unique([tenancyId, configOAuthProviderId, projectUserId, providerAccountId])
}
enum StandardOAuthProviderType {
GITHUB
FACEBOOK
GOOGLE
MICROSOFT
SPOTIFY
DISCORD
GITLAB
BITBUCKET
LINKEDIN
APPLE
X
TWITCH
}
model OAuthToken {
id String @id @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
oauthAccountId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
projectUserOAuthAccount ProjectUserOAuthAccount @relation(fields: [tenancyId, oauthAccountId], references: [tenancyId, id], onDelete: Cascade)
refreshToken String
scopes String[]
isValid Boolean @default(true)
}
model OAuthAccessToken {
id String @id @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
oauthAccountId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
projectUserOAuthAccount ProjectUserOAuthAccount @relation(fields: [tenancyId, oauthAccountId], references: [tenancyId, id], onDelete: Cascade)
accessToken String
scopes String[]
expiresAt DateTime
isValid Boolean @default(true)
}
model OAuthOuterInfo {
id String @id @default(uuid()) @db.Uuid
info Json
innerState String @unique
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model ProjectUserRefreshToken {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
projectUserId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
lastActiveAt DateTime @default(now())
lastActiveAtIpInfo Json?
refreshToken String @unique
expiresAt DateTime?
isImpersonation Boolean @default(false)
@@id([tenancyId, id])
}
model ProjectUserAuthorizationCode {
tenancyId String @db.Uuid
projectUserId String @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
authorizationCode String @unique
redirectUri String
expiresAt DateTime
codeChallenge String
codeChallengeMethod String
newUser Boolean
afterCallbackRedirectUrl String?
@@id([tenancyId, authorizationCode])
}
model VerificationCode {
projectId String
branchId String
id String @default(uuid()) @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
type VerificationCodeType
code String
expiresAt DateTime
usedAt DateTime?
redirectUrl String?
method Json @default("null")
data Json
attemptCount Int @default(0)
@@id([projectId, branchId, id])
@@unique([projectId, branchId, code])
@@index([data(ops: JsonbPathOps)], type: Gin)
}
enum VerificationCodeType {
ONE_TIME_PASSWORD
PASSWORD_RESET
CONTACT_CHANNEL_VERIFICATION
TEAM_INVITATION
MFA_ATTEMPT
PASSKEY_REGISTRATION_CHALLENGE
PASSKEY_AUTHENTICATION_CHALLENGE
INTEGRATION_PROJECT_TRANSFER
PURCHASE_URL
}
//#region API keys
// Internal API keys
model ApiKeySet {
projectId String
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
id String @default(uuid()) @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
description String
expiresAt DateTime
manuallyRevokedAt DateTime?
publishableClientKey String? @unique
secretServerKey String? @unique
superSecretAdminKey String? @unique
@@id([projectId, id])
}
//#endregion
model ProjectApiKey {
tenancyId String @db.Uuid
id String @default(uuid()) @db.Uuid
secretApiKey String @unique
// Validity and revocation
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
expiresAt DateTime?
manuallyRevokedAt DateTime?
description String
isPublic Boolean
// exactly one of [teamId] or [projectUserId] must be set
teamId String? @db.Uuid
projectUserId String? @db.Uuid
projectUser ProjectUser? @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
team Team? @relation(fields: [tenancyId, teamId], references: [tenancyId, teamId], onDelete: Cascade)
@@id([tenancyId, id])
}
enum EmailTemplateType {
EMAIL_VERIFICATION
PASSWORD_RESET
MAGIC_LINK
TEAM_INVITATION
SIGN_IN_INVITATION
}
model EmailTemplate {
projectId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
content Json
type EmailTemplateType
subject String
@@id([projectId, type])
}
//#region IdP
model IdPAccountToCdfcResultMapping {
idpId String
id String
idpAccountId String @unique @db.Uuid
cdfcResult Json
@@id([idpId, id])
}
model ProjectWrapperCodes {
idpId String
id String @default(uuid()) @db.Uuid
interactionUid String
authorizationCode String @unique
cdfcResult Json
@@id([idpId, id])
}
model IdPAdapterData {
idpId String
model String
id String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
payload Json
expiresAt DateTime
@@id([idpId, model, id])
@@index([payload(ops: JsonbPathOps)], type: Gin)
@@index([expiresAt])
}
//#endregion
model ProvisionedProject {
projectId String @id
project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
clientId String
}
//#region Events
model Event {
id String @id @default(uuid()) @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// if isWide == false, then eventEndedAt is always equal to eventStartedAt
isWide Boolean
eventStartedAt DateTime
eventEndedAt DateTime
// TODO: add event_type, and at least one of either system_event_type or event_type is always set
systemEventTypeIds String[]
data Json
// ============================== BEGIN END USER PROPERTIES ==============================
// Below are properties describing the end user that caused this event to be logged
// This is different from a request IP. See: apps/backend/src/lib/end-users.tsx
// Note that the IP may have been spoofed, unless isEndUserIpInfoGuessTrusted is true
endUserIpInfoGuessId String? @db.Uuid
endUserIpInfoGuess EventIpInfo? @relation("EventIpInfo", fields: [endUserIpInfoGuessId], references: [id])
// If true, then endUserIpInfoGuess is not spoofed (might still be behind VPNs/proxies). If false, then the values may be spoofed.
isEndUserIpInfoGuessTrusted Boolean @default(false)
// =============================== END END USER PROPERTIES ===============================
@@index([data(ops: JsonbPathOps)], type: Gin)
}
// An IP address that was seen in an event. Use the location fields instead of refetching the location from the ip, as the real-world geoip data may have changed since the event was logged.
model EventIpInfo {
id String @id @default(uuid()) @db.Uuid
ip String
countryCode String?
regionCode String?
cityName String?
latitude Float?
longitude Float?
tzIdentifier String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
events Event[] @relation("EventIpInfo")
}
//#endregion
enum EmailOutboxStatus {
PAUSED
PREPARING
RENDERING
RENDER_ERROR
SCHEDULED
QUEUED
SENDING
SERVER_ERROR
SENT
SKIPPED
DELIVERY_DELAYED
BOUNCED
OPENED
CLICKED
MARKED_AS_SPAM
}
enum EmailOutboxSimpleStatus {
IN_PROGRESS
ERROR
OK
}
enum EmailOutboxSkippedReason {
USER_UNSUBSCRIBED
USER_ACCOUNT_DELETED
USER_HAS_NO_PRIMARY_EMAIL
NO_EMAIL_PROVIDED
LIKELY_NOT_DELIVERABLE
MANUALLY_CANCELLED
}
enum EmailOutboxCreatedWith {
DRAFT
PROGRAMMATIC_CALL
}
// In most displays, the way emails in the outbox should be ordered is:
// - by finishedSendingAt, descending (null comes first)
// - by scheduledAtIfNotYetQueued, descending (null comes last)
// - by priority, ascending
// - by id, ascending
model EmailOutbox {
tenancyId String @db.Uuid
id String @default(uuid()) @db.Uuid
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// note: [tsxSource, themeId, isHighPriority, toUserIds, toEmails, extraRenderVariables, shouldSkipDeliverabilityCheck, overrideSubject, overrideNotificationCategoryId] can be changed, but only while startedSendingAt is not set, and any modification should reset fields like [renderedByWorkerId, startedRenderingAt, finishedRenderingAt, renderError*, rendered*, isQueued] and any other fields with similar semantics to null.
tsxSource String
themeId String?
isHighPriority Boolean
// Who the email is being sent to. { type: "user-primary-email", userId: string } | { type: "user-custom-emails", userId: string, emails: string[] } | { type: "custom-emails", emails: string[] }
to Json
extraRenderVariables Json
overrideSubject String?
overrideNotificationCategoryId String?
shouldSkipDeliverabilityCheck Boolean
createdWith EmailOutboxCreatedWith
// If the email was created from a draft, it is kept around so we can later group by it. Must be set if and only if createdWith is DRAFT. (Enforced by EmailOutbox_email_draft_check and EmailOutbox_email_draft_reverse_check constraints.)
emailDraftId String?
// If the email was created from a template programmatically, it is kept around so we can later group by it. Must be NOT set if createdWith is NOT PROGRAMMATIC_CALL. If createdWith is PROGRAMMATIC_CALL and this is not set, then no template was used (eg. email was sent directly as HTML). (Enforced by EmailOutbox_email_programmatic_call_template_check constraint.)
emailProgrammaticCallTemplateId String?
// Computed from EmailOutbox can be the `status` of the email:
//
// - ⚪ `paused` : isPaused (can happen at any time)
// - ⚫ `skipped` : !isPaused && skippedReason (can happen at any time, like paused)
// - ⚪ `preparing` : !isPaused && !skippedReason && !startedRenderingAt
// - ⚪ `rendering` : !isPaused && !skippedReason && !finishedRenderingAt
// - 🔴 `render-error` : !isPaused && !skippedReason && finishedRenderingAt && renderError
// - ⚪ `scheduled` : !isPaused && !skippedReason && finishedRenderingAt && !renderError && !isQueued
// - ⚪ `queued` : !isPaused && !skippedReason && finishedRenderingAt && !renderError && isQueued && !startedSendingAt
// - ⚪ `sending` : !isPaused && !skippedReason && startedSendingAt && (canHaveDeliveryInfo ? !deliveredAt : !finishedSendingAt)
// - 🔴 `server-error` : !isPaused && !skippedReason && finishedSendingAt && sendServerErrorMessage
// - 🟢 `sent` : !isPaused && !skippedReason && finishedSendingAt && !openedAt && !markedAsSpamAt && !sendServerErrorMessage && (canHaveDeliveryInfo ? deliveredAt : finishedSendingAt)
// - ⚪ `delivery-delayed` : !isPaused && !skippedReason && canHaveDeliveryInfo && deliveryDelayedAt
// - 🔴 `bounced` : !isPaused && !skippedReason && canHaveDeliveryInfo && bouncedAt
// - 🔵 `opened` : !isPaused && !skippedReason && openedAt && !clickedAt && !markedAsSpamAt
// - 🟣 `clicked` : !isPaused && !skippedReason && clickedAt && !markedAsSpamAt
// - 🟡 `marked-as-spam` : !isPaused && !skippedReason && markedAsSpamAt
//
// NOTE: The `sending` status is NOT the same as `finishedSendingAt`! If the outbox can have delivery info, then
// `sending` is about deliveredAt. A better name would be `delivering`, but that name is less catchy than `sending`.
//
// This column is auto-generated as defined in the SQL migration. It can not be set manually. Note: Setting the dbgenerated value is NOT sufficient to create a generated column in Postgres! (Prisma dbgenerated only generates a value for the *default*, and won't reflect any updates.) You must create one manually in the migration file instead, and then update the value here to match.
status EmailOutboxStatus @default(dbgenerated("\nCASE\n WHEN \"isPaused\" THEN 'PAUSED'::\"EmailOutboxStatus\"\n WHEN (\"skippedReason\" IS NOT NULL) THEN 'SKIPPED'::\"EmailOutboxStatus\"\n WHEN (\"startedRenderingAt\" IS NULL) THEN 'PREPARING'::\"EmailOutboxStatus\"\n WHEN (\"finishedRenderingAt\" IS NULL) THEN 'RENDERING'::\"EmailOutboxStatus\"\n WHEN (\"renderErrorExternalMessage\" IS NOT NULL) THEN 'RENDER_ERROR'::\"EmailOutboxStatus\"\n WHEN ((\"startedSendingAt\" IS NULL) AND (\"isQueued\" IS FALSE)) THEN 'SCHEDULED'::\"EmailOutboxStatus\"\n WHEN (\"startedSendingAt\" IS NULL) THEN 'QUEUED'::\"EmailOutboxStatus\"\n WHEN (\"finishedSendingAt\" IS NULL) THEN 'SENDING'::\"EmailOutboxStatus\"\n WHEN ((\"canHaveDeliveryInfo\" IS TRUE) AND (\"deliveredAt\" IS NULL)) THEN 'SENDING'::\"EmailOutboxStatus\"\n WHEN (\"sendServerErrorExternalMessage\" IS NOT NULL) THEN 'SERVER_ERROR'::\"EmailOutboxStatus\"\n WHEN (\"canHaveDeliveryInfo\" IS FALSE) THEN 'SENT'::\"EmailOutboxStatus\"\n WHEN (\"markedAsSpamAt\" IS NOT NULL) THEN 'MARKED_AS_SPAM'::\"EmailOutboxStatus\"\n WHEN (\"clickedAt\" IS NOT NULL) THEN 'CLICKED'::\"EmailOutboxStatus\"\n WHEN (\"openedAt\" IS NOT NULL) THEN 'OPENED'::\"EmailOutboxStatus\"\n WHEN (\"bouncedAt\" IS NOT NULL) THEN 'BOUNCED'::\"EmailOutboxStatus\"\n WHEN (\"deliveryDelayedAt\" IS NOT NULL) THEN 'DELIVERY_DELAYED'::\"EmailOutboxStatus\"\n ELSE 'SENT'::\"EmailOutboxStatus\"\nEND"))
// A simplified version of the status property.
// In terms of the color mapping of `status`, white statuses have a `simpleStatus` of `in-progress`, red statuses have a `simpleStatus` of `error`, and everything else has a `simpleStatus` of `ok`.
//
// This column is auto-generated as defined in the SQL migration. It can not be set manually. See the note above on EmailOutboxStatus.status for more details on dbgenerated values.
simpleStatus EmailOutboxSimpleStatus @default(dbgenerated("\nCASE\n WHEN (\"skippedReason\" IS NOT NULL) THEN 'OK'::\"EmailOutboxSimpleStatus\"\n WHEN ((\"renderErrorExternalMessage\" IS NOT NULL) OR (\"sendServerErrorExternalMessage\" IS NOT NULL) OR (\"bouncedAt\" IS NOT NULL)) THEN 'ERROR'::\"EmailOutboxSimpleStatus\"\n WHEN ((\"finishedSendingAt\" IS NOT NULL) AND ((\"canHaveDeliveryInfo\" IS FALSE) OR (\"deliveredAt\" IS NOT NULL))) THEN 'OK'::\"EmailOutboxSimpleStatus\"\n WHEN ((\"finishedSendingAt\" IS NULL) OR ((\"canHaveDeliveryInfo\" IS TRUE) AND (\"deliveredAt\" IS NULL))) THEN 'IN_PROGRESS'::\"EmailOutboxSimpleStatus\"\n ELSE 'OK'::\"EmailOutboxSimpleStatus\"\nEND"))
// priority is the sending priority of the email among all emails that are not yet sent but already past their scheduled time. Higher priority means it should be sent sooner.
//
// This column is auto-generated based on the following formula:
// priority = (isHighPriority ? 100 : 0) + (renderedIsTransactional ? 10 : 0)
// See the note above on EmailOutboxStatus.status for more details on dbgenerated values.
priority Int @default(dbgenerated("(\nCASE\n WHEN \"isHighPriority\" THEN 100\n ELSE 0\nEND +\nCASE\n WHEN \"renderedIsTransactional\" THEN 10\n ELSE 0\nEND)"))
isPaused Boolean @default(false)
// either both or neither of [renderedByWorkerId, startedRenderingAt] must be set
renderedByWorkerId String? @db.Uuid
startedRenderingAt DateTime?
// if startedRenderingAt is not set, then finishedRenderingAt is also not set
finishedRenderingAt DateTime?
// if finishedRenderingAt is set, then exactly one of [renderedHtml, renderedText, renderedSubject, renderedIsTransactional, renderedNotificationCategoryId] or [renderErrorExternalMessage, renderErrorExternalDetails, renderErrorInternalMessage, renderErrorInternalDetails] must be set; if finishedRenderingAt is not set, then none of the aforementioned fields are set
renderErrorExternalMessage String?
renderErrorExternalDetails Json?
renderErrorInternalMessage String?
renderErrorInternalDetails Json?
renderedHtml String?
renderedText String?
renderedSubject String?
renderedIsTransactional Boolean?
renderedNotificationCategoryId String?
// The scheduled time of when the email should be added to the queue. Can be edited, but only if the email has not yet started sending. Doing so should set isQueued to false.
scheduledAt DateTime
// The scheduled time of the email if it is in the future.
isQueued Boolean @default(false)
// A generated column that is equal to scheduledAt if isQueued is false, otherwise null. See the note above on EmailOutboxStatus.status for more details on dbgenerated values.
scheduledAtIfNotYetQueued DateTime? @default(dbgenerated("\nCASE\n WHEN \"isQueued\" THEN NULL::timestamp without time zone\n ELSE \"scheduledAt\"\nEND"))
// if finishedRenderingAt is not set, then startedSendingAt is also not set
startedSendingAt DateTime?
// if startedSendingAt is not set, then finishedSendingAt is also not set
finishedSendingAt DateTime?
// A generated column that is equal to finishedSendingAt if canHaveDeliveryInfo is false, otherwise deliveredAt.
sentAt DateTime? @default(dbgenerated("\nCASE\n WHEN (\"canHaveDeliveryInfo\" IS TRUE) THEN \"deliveredAt\"\n WHEN (\"canHaveDeliveryInfo\" IS FALSE) THEN \"finishedSendingAt\"\n ELSE NULL::timestamp without time zone\nEND"))
// either all or none of [sendServerErrorExternalMessage, sendServerErrorExternalDetails, sendServerErrorInternalMessage, sendServerErrorInternalDetails] must be set. If finishedSendingAt is not set, then none of these are set.
sendServerErrorExternalMessage String?
sendServerErrorExternalDetails Json?
sendServerErrorInternalMessage String?
sendServerErrorInternalDetails Json?
// The reason why the email was skipped. Unlike most status-related fields, this can be set at any point in the email lifecycle (like isPaused). skippedDetails must be set if and only if skippedReason is set. (Enforced by EmailOutbox_skipped_details_consistency_check constraint.)
skippedReason EmailOutboxSkippedReason?
skippedDetails Json?
// Whether this email was sent through a server that provides delivery info. This is set if and only if finishedSendingAt is set (it is only determined once the email has been sent). If canHaveDeliveryInfo is false, then [deliveredAt, deliveryDelayedAt, bouncedAt] are all not set. This flag is usually set to true if the email provider is Resend.
canHaveDeliveryInfo Boolean?
// at most one of [deliveredAt, deliveryDelayedAt, bouncedAt] can be set. If finishedSendingAt is not set, then none of these are set.
deliveredAt DateTime?
deliveryDelayedAt DateTime?
bouncedAt DateTime?
// if finishedSendingAt is not set, then openedAt is also not set
openedAt DateTime?
// note: setting clickedAt should also set openedAt if it's not set yet
clickedAt DateTime?
unsubscribedAt DateTime?
markedAsSpamAt DateTime?
tenancy Tenancy @relation(fields: [tenancyId], references: [id], onDelete: Cascade)
@@id([tenancyId, id])
@@index([tenancyId, finishedSendingAt(sort: Desc), scheduledAtIfNotYetQueued(sort: Desc), priority, id], map: "EmailOutbox_ordering_idx")
@@index([tenancyId, simpleStatus], map: "EmailOutbox_simple_status_tenancy_idx")
@@index([tenancyId, status], map: "EmailOutbox_status_tenancy_idx")
}
model EmailOutboxProcessingMetadata {
key String @id
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
lastExecutedAt DateTime?
}
model EmailDraft {
tenancyId String @db.Uuid
id String @default(uuid()) @db.Uuid
displayName String
themeMode DraftThemeMode @default(PROJECT_DEFAULT)
themeId String?
tsxSource String
sentAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@id([tenancyId, id])
}
enum DraftThemeMode {
PROJECT_DEFAULT
NONE
CUSTOM
}
model CliAuthAttempt {
tenancyId String @db.Uuid
id String @default(uuid()) @db.Uuid
pollingCode String @unique
loginCode String @unique
refreshToken String?
expiresAt DateTime
usedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@id([tenancyId, id])
}
model UserNotificationPreference {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
projectUserId String @db.Uuid
notificationCategoryId String @db.Uuid
enabled Boolean
projectUser ProjectUser @relation(fields: [tenancyId, projectUserId], references: [tenancyId, projectUserId], onDelete: Cascade)
@@id([tenancyId, id])
@@unique([tenancyId, projectUserId, notificationCategoryId])
}
model ThreadMessage {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
threadId String @db.Uuid
content Json
createdAt DateTime @default(now())
@@id([tenancyId, id])
}
enum CustomerType {
USER
TEAM
CUSTOM
}
enum SubscriptionStatus {
active
trialing
canceled
paused
incomplete
incomplete_expired
past_due
unpaid
}
enum PurchaseCreationSource {
PURCHASE_PAGE
TEST_MODE
API_GRANT
}
model Subscription {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
customerId String
customerType CustomerType
productId String?
priceId String?
product Json
quantity Int @default(1)
stripeSubscriptionId String?
status SubscriptionStatus
currentPeriodEnd DateTime
currentPeriodStart DateTime
cancelAtPeriodEnd Boolean
refundedAt DateTime?
creationSource PurchaseCreationSource
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
SubscriptionInvoices SubscriptionInvoice[]
@@id([tenancyId, id])
@@unique([tenancyId, stripeSubscriptionId])
}
model ItemQuantityChange {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
customerId String
customerType CustomerType
itemId String
quantity Int
description String?
expiresAt DateTime?
createdAt DateTime @default(now())
@@id([tenancyId, id])
@@index([tenancyId, customerId, expiresAt])
}
model OneTimePurchase {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
customerId String
customerType CustomerType
productId String?
priceId String?
product Json
quantity Int
stripePaymentIntentId String?
createdAt DateTime @default(now())
refundedAt DateTime?
creationSource PurchaseCreationSource
@@id([tenancyId, id])
@@unique([tenancyId, stripePaymentIntentId])
}
model DataVaultEntry {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
storeId String
hashedKey String
encrypted Json // Contains { edkBase64, ciphertextBase64 } from encryptWithKms()
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@id([tenancyId, id])
@@unique([tenancyId, storeId, hashedKey])
@@index([tenancyId, storeId])
}
model CacheEntry {
id String @id @default(uuid()) @db.Uuid
namespace String
cacheKey String
payload Json
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([namespace, cacheKey])
}
model SubscriptionInvoice {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
stripeSubscriptionId String
stripeInvoiceId String
isSubscriptionCreationInvoice Boolean
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
subscription Subscription @relation(fields: [tenancyId, stripeSubscriptionId], references: [tenancyId, stripeSubscriptionId])
@@id([tenancyId, id])
@@unique([tenancyId, stripeInvoiceId])
}